Template
1
0

feat: update payment views

This commit is contained in:
2025-12-06 20:42:10 +01:00
parent ce4d5ba013
commit 37164b560f
49 changed files with 1826 additions and 624 deletions

View File

@@ -11,7 +11,7 @@ get {
}
params:path {
id: 2f6dfb20-7834-484c-8472-096f72fc5f08
id: 16f41847-4bc4-4898-92d1-75fd314d15a8
}
settings {

View File

@@ -18,5 +18,7 @@
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
"registries": {
"@wds": "https://wds-shadcn-registry.netlify.app/r/{name}.json"
}
}

View File

@@ -18,12 +18,14 @@
"@module/payment": "workspace:*",
"@radix-ui/react-avatar": "1.1.11",
"@radix-ui/react-checkbox": "1.3.3",
"@radix-ui/react-dialog": "1.1.15",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "2.1.16",
"@radix-ui/react-label": "2.1.8",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-select": "2.2.6",
"@radix-ui/react-separator": "1.1.8",
"@radix-ui/react-slot": "1.2.4",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "1.1.13",
"@radix-ui/react-toggle": "1.1.10",
"@radix-ui/react-toggle-group": "1.1.11",
@@ -32,9 +34,11 @@
"@tailwindcss/vite": "4.1.17",
"@tanstack/react-router": "1.139.9",
"@tanstack/react-table": "8.21.3",
"@valkyr/db": "npm:@jsr/valkyr__db@2.0.0",
"@zitadel/react": "1.1.0",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
"cmdk": "^1.1.1",
"lucide-react": "0.555.0",
"next-themes": "0.4.6",
"react": "19.2.0",

View File

@@ -1,20 +1,3 @@
import { Controller } from "@/lib/controller.tsx";
import { api } from "@/services/api.ts";
export class DashboardController extends Controller<{
beneficiaries: any[];
}> {
async onInit() {
return {
beneficiaries: await this.#getBenficiaries(),
};
}
async #getBenficiaries() {
const response = await api.ledger.benficiaries.list();
if ("error" in response) {
return [];
}
return response.data;
}
}
export class DashboardController extends Controller {}

View File

@@ -2,11 +2,6 @@ import { makeControllerComponent } from "@/lib/controller.tsx";
import { DashboardController } from "./dashboard.controller.ts";
export const DashboardView = makeControllerComponent(DashboardController, ({ beneficiaries }) => {
return (
<div>
Dashboard
<pre>{JSON.stringify(beneficiaries, null, 2)}</pre>
</div>
);
export const DashboardView = makeControllerComponent(DashboardController, () => {
return <div>Dashboard</div>;
});

View File

@@ -0,0 +1,36 @@
import type { Beneficiary } from "@module/payment/client";
import { loadBeneficiaries, payment } from "@/database/payment.ts";
import { Controller } from "@/lib/controller.tsx";
import { User } from "@/services/user.ts";
export class PaymentDashboardController extends Controller<{
beneficiaries: Beneficiary[];
}> {
#subscriptions: any[] = [];
async onInit() {
await this.#subscribe();
return {
isCreating: false,
beneficiaries: [],
};
}
async onDestroy(): Promise<void> {
for (const subscription of this.#subscriptions) {
subscription.unsubscribe();
}
}
async #subscribe() {
await loadBeneficiaries();
this.#subscriptions.push(
await payment
.collection("beneficiary")
.subscribe({ tenantId: await User.getTenantId() }, { sort: { label: 1 } }, (documents) => {
this.setState("beneficiaries", documents);
}),
);
}
}

View File

@@ -0,0 +1,22 @@
import { makeControllerComponent } from "@/lib/controller.tsx";
import { PaymentDashboardController } from "./dashboard.controller.ts";
export const PaymentDashboardView = makeControllerComponent(PaymentDashboardController, ({ beneficiaries }) => {
if (beneficiaries.length === 0) {
return (
<div className="w-full flex flex-col pt-20 items-center justify-center text-center">
<h1 className="text-2xl font-semibold tracking-tight">No Beneficiaries Found</h1>
<p className="text-muted-foreground mt-2 max-w-sm">
This tenant does not have a beneficiaries assigned. A beneficiary entity is required to continue.
</p>
</div>
);
}
return (
<div>
Payments
<pre>{JSON.stringify(beneficiaries, null, 2)}</pre>
</div>
);
});

View File

@@ -0,0 +1,34 @@
import { GalleryVerticalEnd } from "lucide-react";
import { Controller } from "@/lib/controller.tsx";
import { User } from "@/services/user.ts";
type Tenant = {
name: string;
logo: React.ElementType;
domain: string;
};
export class AppSiderbarController extends Controller<{
tenant: Tenant;
}> {
async onInit() {
const user = await User.resolve();
if (user === undefined) {
return {
tenant: {
name: "Zitadel",
logo: GalleryVerticalEnd,
domain: "iam.valkyrjs.com",
},
};
}
return {
tenant: {
name: user.tenant.name,
logo: GalleryVerticalEnd,
domain: user.tenant.domain,
},
};
}
}

View File

@@ -1,26 +1,7 @@
import * as React from "react"
import {
IconCamera,
IconChartBar,
IconDashboard,
IconDatabase,
IconFileAi,
IconFileDescription,
IconFileWord,
IconFolder,
IconHelp,
IconInnerShadowTop,
IconListDetails,
IconReport,
IconSearch,
IconSettings,
IconUsers,
} from "@tabler/icons-react"
import { Link } from "@tanstack/react-router";
import { GalleryVerticalEnd } from "lucide-react";
import { NavDocuments } from "@/components/nav-documents"
import { NavMain } from "@/components/nav-main"
import { NavSecondary } from "@/components/nav-secondary"
import { NavUser } from "@/components/nav-user"
import { NavUser } from "@/components/nav-user";
import {
Sidebar,
SidebarContent,
@@ -29,151 +10,38 @@ import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar"
} from "@/components/ui/sidebar";
const data = {
user: {
name: "shadcn",
email: "m@example.com",
avatar: "/avatars/shadcn.jpg",
},
navMain: [
{
title: "Dashboard",
url: "#",
icon: IconDashboard,
},
{
title: "Lifecycle",
url: "#",
icon: IconListDetails,
},
{
title: "Analytics",
url: "#",
icon: IconChartBar,
},
{
title: "Projects",
url: "#",
icon: IconFolder,
},
{
title: "Team",
url: "#",
icon: IconUsers,
},
],
navClouds: [
{
title: "Capture",
icon: IconCamera,
isActive: true,
url: "#",
items: [
{
title: "Active Proposals",
url: "#",
},
{
title: "Archived",
url: "#",
},
],
},
{
title: "Proposal",
icon: IconFileDescription,
url: "#",
items: [
{
title: "Active Proposals",
url: "#",
},
{
title: "Archived",
url: "#",
},
],
},
{
title: "Prompts",
icon: IconFileAi,
url: "#",
items: [
{
title: "Active Proposals",
url: "#",
},
{
title: "Archived",
url: "#",
},
],
},
],
navSecondary: [
{
title: "Settings",
url: "#",
icon: IconSettings,
},
{
title: "Get Help",
url: "#",
icon: IconHelp,
},
{
title: "Search",
url: "#",
icon: IconSearch,
},
],
documents: [
{
name: "Data Library",
url: "#",
icon: IconDatabase,
},
{
name: "Reports",
url: "#",
icon: IconReport,
},
{
name: "Word Assistant",
url: "#",
icon: IconFileWord,
},
],
}
import { makeControllerComponent } from "../lib/controller.tsx";
import { AppSiderbarController } from "./app-sidebar.controller.ts";
import { NavPayment } from "./nav-payment.tsx";
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
export const AppSidebar = makeControllerComponent(AppSiderbarController, ({ tenant }) => {
return (
<Sidebar collapsible="offcanvas" {...props}>
<Sidebar collapsible="offcanvas">
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
asChild
className="data-[slot=sidebar-menu-button]:!p-1.5"
>
<a href="#">
<IconInnerShadowTop className="!size-5" />
<span className="text-base font-semibold">Acme Inc.</span>
</a>
<SidebarMenuButton size="lg" asChild>
<Link to="/">
<div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
<GalleryVerticalEnd className="size-4" />
</div>
<div className="flex flex-col gap-0.5 leading-none">
<span className="font-medium">{tenant.name}</span>
<span className="">{tenant.domain}</span>
</div>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<NavMain items={data.navMain} />
<NavDocuments items={data.documents} />
<NavSecondary items={data.navSecondary} className="mt-auto" />
<NavPayment />
</SidebarContent>
<SidebarFooter>
<NavUser user={data.user} />
<NavUser />
</SidebarFooter>
</Sidebar>
)
}
);
});

View File

@@ -1,56 +0,0 @@
import { IconCirclePlusFilled, IconMail, type Icon } from "@tabler/icons-react"
import { Button } from "@/components/ui/button"
import {
SidebarGroup,
SidebarGroupContent,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar"
export function NavMain({
items,
}: {
items: {
title: string
url: string
icon?: Icon
}[]
}) {
return (
<SidebarGroup>
<SidebarGroupContent className="flex flex-col gap-2">
<SidebarMenu>
<SidebarMenuItem className="flex items-center gap-2">
<SidebarMenuButton
tooltip="Quick Create"
className="bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground active:bg-primary/90 active:text-primary-foreground min-w-8 duration-200 ease-linear"
>
<IconCirclePlusFilled />
<span>Quick Create</span>
</SidebarMenuButton>
<Button
size="icon"
className="size-8 group-data-[collapsible=icon]:opacity-0"
variant="outline"
>
<IconMail />
<span className="sr-only">Inbox</span>
</Button>
</SidebarMenuItem>
</SidebarMenu>
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton tooltip={item.title}>
{item.icon && <item.icon />}
<span>{item.title}</span>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
)
}

View File

@@ -0,0 +1,85 @@
import type { Beneficiary } from "@module/payment/client";
import { Book, CirclePlusIcon, type LucideIcon, SquareTerminal } from "lucide-react";
import type { FunctionComponent } from "react";
import { loadBeneficiaries, payment } from "@/database/payment.ts";
import { Controller } from "@/lib/controller.tsx";
import { User } from "@/services/user.ts";
import { DialogCreateBeneficiary } from "./payment/create-beneficiary.tsx";
export class NavPaymentController extends Controller<{
items: MenuItem[];
}> {
#subscriptions: any[] = [];
async onInit() {
await this.#subscribe();
return {
items: [
{
title: "Dashboard",
url: "/payment",
icon: SquareTerminal,
},
],
};
}
async #subscribe() {
await loadBeneficiaries();
this.#subscriptions.push(
await payment
.collection("beneficiary")
.subscribe({ tenantId: await User.getTenantId() }, { sort: { label: 1 } }, (beneficiaries) => {
this.setState("items", this.#getMenuItems(beneficiaries));
}),
);
}
#getMenuItems(beneficiaries: Beneficiary[]): MenuItem[] {
return [
{
title: "Dashboard",
url: "/payment",
icon: SquareTerminal,
},
{
title: "Beneficiaries",
url: "#",
icon: Book,
isActive: true,
items: [
{
title: "Create Beneficiary",
icon: CirclePlusIcon,
component: DialogCreateBeneficiary,
},
...beneficiaries.map((beneficiary) => ({
title: beneficiary.label ?? "Unlabeled",
url: `/payment/${beneficiary._id}`,
})),
],
},
];
}
}
type MenuItem = {
title: string;
url: string;
icon?: LucideIcon;
isActive?: boolean;
items?: SubMenuItem[];
};
type SubMenuItem =
| {
title: string;
url: string;
}
| {
title: string;
icon: LucideIcon;
component: FunctionComponent<{ title: string; icon: LucideIcon }>;
};

View File

@@ -0,0 +1,78 @@
"use client";
import { Link } from "@tanstack/react-router";
import { ChevronRight } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
} from "@/components/ui/sidebar";
import { makeControllerComponent } from "../lib/controller.tsx";
import { NavPaymentController } from "./nav-payment.controller.ts";
export const NavPayment = makeControllerComponent(NavPaymentController, ({ items }) => {
return (
<SidebarGroup>
<SidebarGroupLabel>Payment</SidebarGroupLabel>
<SidebarMenu>
{items.map((item) => {
if (item.items !== undefined) {
return (
<Collapsible key={item.title} asChild defaultOpen={item.isActive} className="group/collapsible">
<SidebarMenuItem>
<CollapsibleTrigger asChild>
<SidebarMenuButton tooltip={item.title}>
{item.icon && <item.icon />}
<span>{item.title}</span>
<ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
</SidebarMenuButton>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub>
{item.items?.map((subItem) => {
if ("component" in subItem) {
return (
<SidebarMenuSubItem key={subItem.title}>
<subItem.component title={subItem.title} icon={subItem.icon} />
</SidebarMenuSubItem>
);
}
return (
<SidebarMenuSubItem key={subItem.title}>
<SidebarMenuSubButton asChild>
<Link to={subItem.url}>
<span>{subItem.title}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
</SidebarMenuSub>
</CollapsibleContent>
</SidebarMenuItem>
</Collapsible>
);
}
return (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton tooltip={item.title} asChild>
<Link to={item.url}>
{item.icon && <item.icon />}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroup>
);
});

View File

@@ -1,5 +1,6 @@
import { Controller } from "@/lib/controller.tsx";
import { type User as ZitadelUser, zitadel } from "@/services/zitadel.ts";
import { User } from "@/services/user.ts";
import { zitadel } from "@/services/zitadel.ts";
export class NavUserController extends Controller<{
user: User;
@@ -11,38 +12,14 @@ export class NavUserController extends Controller<{
}
async #getAuthenticatedUser(): Promise<User> {
const user = await zitadel.userManager.getUser();
if (user === null) {
const user = await User.resolve();
if (user === undefined) {
throw new Error("Failed to resolve user session");
}
return getUserProfile(user);
return user;
}
signout() {
zitadel.signout();
}
}
function getUserProfile({ profile }: ZitadelUser): User {
const user: User = { name: "Unknown", email: "unknown@acme.none", avatar: "" };
if (profile.name) {
user.name = profile.name;
} else if (profile.given_name && profile.family_name) {
user.name = `${profile.given_name} ${profile.family_name}`;
} else if (profile.given_name) {
user.name = profile.given_name;
}
if (profile.email) {
user.email = profile.email;
}
if (profile.picture !== undefined) {
user.avatar = profile.picture;
}
return user;
}
type User = {
name: string;
email: string;
avatar: string;
};

View File

@@ -0,0 +1,41 @@
import type { LucideIcon } from "lucide-react";
import { payment } from "@/database/payment.ts";
import { Controller } from "@/lib/controller.tsx";
import { api, getSuccessResponse } from "@/services/api.ts";
import { User } from "@/services/user.ts";
export class CreateBeneficiaryController extends Controller<
{
isSubmitting: boolean;
},
{ title: string; icon: LucideIcon }
> {
#label?: string;
async onInit() {
return {
isSubmitting: false,
};
}
setLabel(label: string) {
this.#label = label;
}
async submit() {
this.setState("isSubmitting", true);
const res = await api.payment.benficiaries.create({
body: {
tenantId: await User.getTenantId(),
label: this.#label,
},
});
if ("data" in res) {
await payment
.collection("beneficiary")
.insertOne(await getSuccessResponse(api.payment.benficiaries.id({ params: { id: res.data } })));
}
this.setState("isSubmitting", false);
}
}

View File

@@ -0,0 +1,58 @@
import { useId } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { LoadingSwap } from "@/components/ui/loading-swap";
import { SidebarMenuSubButton } from "@/components/ui/sidebar.tsx";
import { makeControllerComponent } from "../../lib/controller.tsx";
import { CreateBeneficiaryController } from "./create-beneficiary.controller.ts";
export const DialogCreateBeneficiary = makeControllerComponent(
CreateBeneficiaryController,
({ title, setLabel, submit, isSubmitting, ...props }) => {
const labelId = useId();
return (
<Dialog>
<form>
<DialogTrigger asChild>
<SidebarMenuSubButton className="cursor-pointer bg-secondary hover:bg-secondary/70">
<props.icon /> <span>{title}</span>
</SidebarMenuSubButton>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Create beneficiary</DialogTitle>
<DialogDescription>Create a payment ledger and its supported currencies</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-3">
<Label htmlFor={labelId}>Label</Label>
<Input id={labelId} name="label" onChange={({ target: { value } }) => setLabel(value)} />
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button type="submit" onClick={submit}>
<LoadingSwap isLoading={isSubmitting}>Create</LoadingSwap>
</Button>
</DialogFooter>
</DialogContent>
</form>
</Dialog>
);
},
);

View File

@@ -0,0 +1,43 @@
import { CurrencySchema } from "@module/payment/client";
import type { LucideIcon } from "lucide-react";
import { api } from "@/services/api.ts";
import { Controller } from "../../lib/controller.tsx";
export class CreateLedgerController extends Controller<
{
isSubmitting: boolean;
},
{ title: string; icon: LucideIcon }
> {
#label?: string;
#currencies: string[] = [];
async onInit() {
return {
isSubmitting: false,
};
}
setLabel(label: string) {
this.#label = label;
}
setCurrencies(currencies: string[]) {
this.#currencies = currencies;
}
async submit() {
this.setState("isSubmitting", true);
const result = await api.payment.ledger.create({
body: {
beneficiaryId: crypto.randomUUID(),
label: this.#label,
currencies: this.#currencies.map((currency) => CurrencySchema.parse(currency)),
},
});
console.log(result);
this.setState("isSubmitting", false);
}
}

View File

@@ -0,0 +1,84 @@
import { currencies } from "@module/payment/client";
import { useId } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { LoadingSwap } from "@/components/ui/loading-swap";
import {
MultiSelect,
MultiSelectContent,
MultiSelectGroup,
MultiSelectItem,
MultiSelectTrigger,
MultiSelectValue,
} from "@/components/ui/multi-select";
import { SidebarMenuSubButton } from "@/components/ui/sidebar.tsx";
import { makeControllerComponent } from "../../lib/controller.tsx";
import { CreateLedgerController } from "./create-ledger.controller.ts";
export const DialogCreateLedger = makeControllerComponent(
CreateLedgerController,
({ title, setLabel, setCurrencies, submit, isSubmitting, ...props }) => {
const labelId = useId();
return (
<Dialog>
<form>
<DialogTrigger asChild>
<SidebarMenuSubButton className="cursor-pointer bg-secondary hover:bg-secondary/70">
<props.icon /> <span>{title}</span>
</SidebarMenuSubButton>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Create ledger</DialogTitle>
<DialogDescription>Create a payment ledger and its supported currencies</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-3">
<Label htmlFor={labelId}>Label</Label>
<Input id={labelId} name="label" onChange={({ target: { value } }) => setLabel(value)} />
</div>
<div className="grid gap-3">
<Label>Currencies</Label>
<MultiSelect onValuesChange={setCurrencies}>
<MultiSelectTrigger className="w-full max-w-[400px]">
<MultiSelectValue placeholder="Select frameworks..." />
</MultiSelectTrigger>
<MultiSelectContent>
<MultiSelectGroup>
{currencies.map((currency) => (
<MultiSelectItem key={currency} value={currency}>
{currency}
</MultiSelectItem>
))}
</MultiSelectGroup>
</MultiSelectContent>
</MultiSelect>
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button type="submit" onClick={submit}>
<LoadingSwap isLoading={isSubmitting}>Create</LoadingSwap>
</Button>
</DialogFooter>
</DialogContent>
</form>
</Dialog>
);
},
);

View File

@@ -0,0 +1,45 @@
import { AudioWaveform, Command, GalleryVerticalEnd } from "lucide-react";
import { Controller } from "@/lib/controller.tsx";
type Tenant = {
name: string;
logo: React.ElementType;
plan: string;
};
export class TenantSwitcherController extends Controller<{
activeTenant?: Tenant;
tenants: Tenant[];
}> {
async onInit() {
return {
activeTenant: {
name: "Acme Inc",
logo: GalleryVerticalEnd,
plan: "Enterprise",
},
tenants: [
{
name: "Acme Inc",
logo: GalleryVerticalEnd,
plan: "Enterprise",
},
{
name: "Acme Corp.",
logo: AudioWaveform,
plan: "Startup",
},
{
name: "Evil Corp.",
logo: Command,
plan: "Free",
},
],
};
}
setActiveTenant(tenant: Tenant) {
this.setState("activeTenant", tenant);
}
}

View File

@@ -0,0 +1,74 @@
"use client";
import { ChevronsUpDown, Plus } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
import { makeControllerComponent } from "../lib/controller.tsx";
import { TenantSwitcherController } from "./tenant-switcher.controller.ts";
export const TenantSwitcher = makeControllerComponent(
TenantSwitcherController,
({ tenants, activeTenant, setActiveTenant }) => {
const { isMobile } = useSidebar();
if (activeTenant === undefined) {
return null;
}
return (
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton
size="lg"
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
<div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
<activeTenant.logo className="size-4" />
</div>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{activeTenant.name}</span>
<span className="truncate text-xs">{activeTenant.plan}</span>
</div>
<ChevronsUpDown className="ml-auto" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
align="start"
side={isMobile ? "bottom" : "right"}
sideOffset={4}
>
<DropdownMenuLabel className="text-muted-foreground text-xs">Teams</DropdownMenuLabel>
{tenants.map((tenant, index) => (
<DropdownMenuItem key={tenant.name} onClick={() => setActiveTenant(tenant)} className="gap-2 p-2">
<div className="flex size-6 items-center justify-center rounded-md border">
<tenant.logo className="size-3.5 shrink-0" />
</div>
{tenant.name}
<DropdownMenuShortcut>{index + 1}</DropdownMenuShortcut>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2 p-2">
<div className="flex size-6 items-center justify-center rounded-md border bg-transparent">
<Plus className="size-4" />
</div>
<div className="text-muted-foreground font-medium">Add team</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu>
);
},
);

View File

@@ -1,8 +1,8 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
@@ -14,10 +14,8 @@ const buttonVariants = cva(
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
@@ -33,8 +31,8 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
)
},
);
function Button({
className,
@@ -44,17 +42,11 @@ function Button({
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "button"
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />;
}
export { Button, buttonVariants }
export { Button, buttonVariants };

View File

@@ -0,0 +1,31 @@
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
)
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
)
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

View File

@@ -0,0 +1,182 @@
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@@ -0,0 +1,141 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,33 @@
import { Loader2Icon } from "lucide-react";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
export function LoadingSwap({
isLoading,
children,
className,
}: {
isLoading: boolean;
children: ReactNode;
className?: string;
}) {
return (
<div className="grid grid-cols-1 items-center justify-items-center">
<div
className={cn(
"col-start-1 col-end-2 row-start-1 row-end-2 w-full",
isLoading ? "invisible" : "visible",
className,
)}
>
{children}
</div>
<div
className={cn("col-start-1 col-end-2 row-start-1 row-end-2", isLoading ? "visible" : "invisible", className)}
>
<Loader2Icon className="animate-spin" />
</div>
</div>
);
}

View File

@@ -0,0 +1,325 @@
"use client";
import { CheckIcon, ChevronsUpDownIcon, XIcon } from "lucide-react";
import {
type ComponentPropsWithoutRef,
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
type MultiSelectContextType = {
open: boolean;
setOpen: (open: boolean) => void;
selectedValues: Set<string>;
toggleValue: (value: string) => void;
items: Map<string, ReactNode>;
onItemAdded: (value: string, label: ReactNode) => void;
};
const MultiSelectContext = createContext<MultiSelectContextType | null>(null);
export function MultiSelect({
children,
values,
defaultValues,
onValuesChange,
}: {
children: ReactNode;
values?: string[];
defaultValues?: string[];
onValuesChange?: (values: string[]) => void;
}) {
const [open, setOpen] = useState(false);
const [internalValues, setInternalValues] = useState(new Set<string>(values ?? defaultValues));
const selectedValues = values ? new Set(values) : internalValues;
const [items, setItems] = useState<Map<string, ReactNode>>(new Map());
function toggleValue(value: string) {
const getNewSet = (prev: Set<string>) => {
const newSet = new Set(prev);
if (newSet.has(value)) {
newSet.delete(value);
} else {
newSet.add(value);
}
return newSet;
};
setInternalValues(getNewSet);
onValuesChange?.([...getNewSet(selectedValues)]);
}
const onItemAdded = useCallback((value: string, label: ReactNode) => {
setItems((prev) => {
if (prev.get(value) === label) return prev;
return new Map(prev).set(value, label);
});
}, []);
return (
<MultiSelectContext
value={{
open,
setOpen,
selectedValues,
toggleValue,
items,
onItemAdded,
}}
>
<Popover open={open} onOpenChange={setOpen} modal={true}>
{children}
</Popover>
</MultiSelectContext>
);
}
export function MultiSelectTrigger({
className,
children,
...props
}: {
className?: string;
children?: ReactNode;
} & ComponentPropsWithoutRef<typeof Button>) {
const { open } = useMultiSelectContext();
return (
<PopoverTrigger asChild>
<Button
{...props}
variant={props.variant ?? "outline"}
role={props.role ?? "combobox"}
aria-expanded={props["aria-expanded"] ?? open}
className={cn(
"flex h-auto min-h-9 w-fit items-center justify-between gap-2 overflow-hidden rounded-md border border-input bg-transparent px-3 py-1.5 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
>
{children}
<ChevronsUpDownIcon className="size-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
);
}
export function MultiSelectValue({
placeholder,
clickToRemove = true,
className,
overflowBehavior = "wrap-when-open",
...props
}: {
placeholder?: string;
clickToRemove?: boolean;
overflowBehavior?: "wrap" | "wrap-when-open" | "cutoff";
} & Omit<ComponentPropsWithoutRef<"div">, "children">) {
const { selectedValues, toggleValue, items, open } = useMultiSelectContext();
const [overflowAmount, setOverflowAmount] = useState(0);
const valueRef = useRef<HTMLDivElement>(null);
const overflowRef = useRef<HTMLDivElement>(null);
const shouldWrap = overflowBehavior === "wrap" || (overflowBehavior === "wrap-when-open" && open);
const checkOverflow = useCallback(() => {
if (valueRef.current == null) {
return;
}
const containerElement = valueRef.current;
const overflowElement = overflowRef.current;
const items = containerElement.querySelectorAll<HTMLElement>("[data-selected-item]");
if (overflowElement != null) {
overflowElement.style.display = "none";
}
for (const child of items) {
child.style.removeProperty("display");
}
let amount = 0;
for (let i = items.length - 1; i >= 0; i--) {
const child = items[i];
if (containerElement.scrollWidth <= containerElement.clientWidth) {
break;
}
amount = items.length - i;
child.style.display = "none";
overflowElement?.style.removeProperty("display");
}
setOverflowAmount(amount);
}, []);
const handleResize = useCallback(
(node: HTMLDivElement) => {
valueRef.current = node;
const mutationObserver = new MutationObserver(checkOverflow);
const observer = new ResizeObserver(debounce(checkOverflow, 100));
mutationObserver.observe(node, {
childList: true,
attributes: true,
attributeFilter: ["class", "style"],
});
observer.observe(node);
return () => {
observer.disconnect();
mutationObserver.disconnect();
valueRef.current = null;
};
},
[checkOverflow],
);
if (selectedValues.size === 0 && placeholder) {
return <span className="min-w-0 overflow-hidden font-normal text-muted-foreground">{placeholder}</span>;
}
return (
<div
{...props}
ref={handleResize}
className={cn("flex w-full gap-1.5 overflow-hidden", shouldWrap && "h-full flex-wrap", className)}
>
{[...selectedValues]
.filter((value) => items.has(value))
.map((value) => (
<Badge
variant="outline"
data-selected-item
className="group flex items-center gap-1"
key={value}
onClick={
clickToRemove
? (e) => {
e.stopPropagation();
toggleValue(value);
}
: undefined
}
>
{items.get(value)}
{clickToRemove && <XIcon className="size-2 text-muted-foreground group-hover:text-destructive" />}
</Badge>
))}
<Badge
style={{
display: overflowAmount > 0 && !shouldWrap ? "block" : "none",
}}
variant="outline"
ref={overflowRef}
>
+{overflowAmount}
</Badge>
</div>
);
}
export function MultiSelectContent({
search = true,
children,
...props
}: {
search?: boolean | { placeholder?: string; emptyMessage?: string };
children: ReactNode;
} & Omit<ComponentPropsWithoutRef<typeof Command>, "children">) {
const canSearch = typeof search === "object" ? true : search;
return (
<>
<div style={{ display: "none" }}>
<Command>
<CommandList>{children}</CommandList>
</Command>
</div>
<PopoverContent className="min-w-[var(--radix-popover-trigger-width)] p-0">
<Command {...props}>
{canSearch ? (
<CommandInput placeholder={typeof search === "object" ? search.placeholder : undefined} />
) : (
<button type="button" className="sr-only" />
)}
<CommandList>
{canSearch && <CommandEmpty>{typeof search === "object" ? search.emptyMessage : undefined}</CommandEmpty>}
{children}
</CommandList>
</Command>
</PopoverContent>
</>
);
}
export function MultiSelectItem({
value,
children,
badgeLabel,
onSelect,
...props
}: {
badgeLabel?: ReactNode;
value: string;
} & Omit<ComponentPropsWithoutRef<typeof CommandItem>, "value">) {
const { toggleValue, selectedValues, onItemAdded } = useMultiSelectContext();
const isSelected = selectedValues.has(value);
useEffect(() => {
onItemAdded(value, badgeLabel ?? children);
}, [value, children, onItemAdded, badgeLabel]);
return (
<CommandItem
{...props}
onSelect={() => {
toggleValue(value);
onSelect?.(value);
}}
>
<CheckIcon className={cn("mr-2 size-4", isSelected ? "opacity-100" : "opacity-0")} />
{children}
</CommandItem>
);
}
export function MultiSelectGroup(props: ComponentPropsWithoutRef<typeof CommandGroup>) {
return <CommandGroup {...props} />;
}
export function MultiSelectSeparator(props: ComponentPropsWithoutRef<typeof CommandSeparator>) {
return <CommandSeparator {...props} />;
}
function useMultiSelectContext() {
const context = useContext(MultiSelectContext);
if (context == null) {
throw new Error("useMultiSelectContext must be used within a MultiSelectContext");
}
return context;
}
function debounce<T extends (...args: never[]) => void>(func: T, wait: number): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout> | null = null;
return function (this: unknown, ...args: Parameters<T>) {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}

View File

@@ -0,0 +1,46 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@@ -0,0 +1,43 @@
import type { Account, Beneficiary, Ledger, Transaction, Wallet } from "@module/payment/client";
import { IndexedDatabase } from "@valkyr/db";
import { api } from "@/services/api.ts";
export const payment = new IndexedDatabase<{
account: Account;
beneficiary: Beneficiary;
ledger: Ledger;
transaction: Transaction;
wallet: Wallet;
}>({
name: "valkyr-sandbox:payment",
registrars: [
{
name: "account",
indexes: [["_id", { unique: true }], ["walletId"]],
},
{
name: "beneficiary",
indexes: [["_id", { unique: true }], ["tenantId"]],
},
{
name: "ledger",
indexes: [["_id", { unique: true }], ["beneficiaryId"]],
},
{
name: "transaction",
indexes: [["_id", { unique: true }]],
},
{
name: "wallet",
indexes: [["_id", { unique: true }], ["ledgerId"]],
},
],
});
export async function loadBeneficiaries(): Promise<void> {
const result = await api.payment.benficiaries.list();
if ("data" in result) {
payment.collection("beneficiary").insertMany(result.data);
}
}

View File

@@ -174,7 +174,7 @@ export function makeControllerComponent<TController extends new (...args: any[])
>,
LoadingComponent?: FunctionComponent<PropsWithChildren>,
ErrorComponent?: FunctionComponent<PropsWithChildren<{ error: Error }>>,
) {
): FunctionComponent<PropsWithChildren<InstanceType<TController>["$props"]>> {
const container: FunctionComponent<PropsWithChildren> = (props: any) => {
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<any>();

View File

@@ -6,6 +6,8 @@ import { LoginView } from "@/app/auth/login.view.tsx";
import { DashboardView } from "@/app/dashboard/dashboard.view.tsx";
import { zitadel } from "@/services/zitadel.ts";
import { PaymentDashboardView } from "../app/payment/dashboard/dashboard.view.tsx";
const root = createRootRoute();
const callback = createRoute({
@@ -41,7 +43,15 @@ const dashboard = createRoute({
component: DashboardView,
});
const payment = [
createRoute({
getParentRoute: () => app,
path: "/payment",
component: PaymentDashboardView,
}),
];
root.addChildren([app, login, callback]);
app.addChildren([dashboard]);
app.addChildren([dashboard, ...payment]);
export const router = createRouter({ routeTree: root });

View File

@@ -1,273 +0,0 @@
import {
assertServerErrorResponse,
type RelayAdapter,
type RelayInput,
type RelayResponse,
ServerError,
type ServerErrorResponse,
type ServerErrorType,
} from "@platform/relay";
/**
* HttpAdapter provides a unified transport layer for Relay.
*
* It supports sending JSON objects, nested structures, arrays, and file uploads
* via FormData. The adapter automatically detects the payload type and formats
* the request accordingly. Responses are normalized into `RelayResponse`.
*
* @example
* ```ts
* const adapter = new HttpAdapter({ url: "https://api.example.com" });
*
* // Sending JSON data
* const jsonResponse = await adapter.send({
* method: "POST",
* endpoint: "/users",
* body: { name: "Alice", age: 30 },
* });
*
* // Sending files and nested objects
* const formResponse = await adapter.send({
* method: "POST",
* endpoint: "/upload",
* body: {
* user: { name: "Bob", avatar: fileInput.files[0] },
* documents: [fileInput.files[1], fileInput.files[2]],
* },
* });
* ```
*/
export class HttpAdapter implements RelayAdapter {
/**
* Instantiate a new HttpAdapter instance.
*
* @param options - Adapter options.
*/
constructor(readonly options: HttpAdapterOptions) {}
/**
* Override the initial url value set by instantiator.
*/
set url(value: string) {
this.options.url = value;
}
/**
* Retrieve the URL value from options object.
*/
get url() {
return this.options.url;
}
/**
* Return the full URL from given endpoint.
*
* @param endpoint - Endpoint to get url for.
*/
getUrl(endpoint: string): string {
return `${this.url}${endpoint}`;
}
async send({ method, endpoint, query, body, headers = new Headers() }: RelayInput): Promise<RelayResponse> {
const init: RequestInit = { method, headers };
// ### Before Request
// If any before request hooks has been defined, we run them here passing in the
// request headers for further modification.
await this.#beforeRequest(headers);
// ### Body
if (body !== undefined) {
const type = this.#getRequestFormat(body);
if (type === "form-data") {
headers.delete("content-type");
init.body = this.#getFormData(body);
}
if (type === "json") {
headers.set("content-type", "application/json");
init.body = JSON.stringify(body);
}
}
// ### Response
return this.request(`${endpoint}${query}`, init);
}
/**
* Send a fetch request using the given fetch options and returns
* a relay formatted response.
*
* @param endpoint - Which endpoint to submit request to.
* @param init - Request init details to submit with the request.
*/
async request(endpoint: string, init?: RequestInit): Promise<RelayResponse> {
return this.#toResponse(await fetch(this.getUrl(endpoint), init));
}
/**
* Run before request operations.
*
* @param headers - Headers to pass to hooks.
*/
async #beforeRequest(headers: Headers) {
if (this.options.hooks?.beforeRequest !== undefined) {
for (const hook of this.options.hooks.beforeRequest) {
await hook(headers);
}
}
}
/**
* Determine the parser method required for the request.
*
* @param body - Request body.
*/
#getRequestFormat(body: unknown): "form-data" | "json" {
if (containsFile(body) === true) {
return "form-data";
}
return "json";
}
/**
* Get FormData instance for the given body.
*
* @param body - Request body.
*/
#getFormData(data: Record<string, unknown>, formData = new FormData(), parentKey?: string): FormData {
for (const key in data) {
const value = data[key];
if (value === undefined || value === null) continue;
const formKey = parentKey ? `${parentKey}[${key}]` : key;
if (value instanceof File) {
formData.append(formKey, value, value.name);
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
if (item instanceof File) {
formData.append(`${formKey}[${index}]`, item, item.name);
} else if (typeof item === "object") {
this.#getFormData(item as Record<string, unknown>, formData, `${formKey}[${index}]`);
} else {
formData.append(`${formKey}[${index}]`, String(item));
}
});
} else if (typeof value === "object") {
this.#getFormData(value as Record<string, unknown>, formData, formKey);
} else {
formData.append(formKey, String(value));
}
}
return formData;
}
/**
* Convert a fetch response to a compliant relay response.
*
* @param response - Fetch response to convert.
*/
async #toResponse(response: Response): Promise<RelayResponse> {
const type = response.headers.get("content-type");
// ### Content Type
// Ensure that the server responds with a 'content-type' definition. We should
// always expect the server to respond with a type.
if (type === null) {
return {
result: "error",
error: {
status: response.status,
message: "Missing 'content-type' in header returned from server.",
},
};
}
// ### Empty Response
// If the response comes back with empty response status 204 we simply return a
// empty success.
if (response.status === 204) {
return {
result: "success",
data: null,
};
}
// ### JSON
// If the 'content-type' contains 'json' we treat it as a 'json' compliant response
// and attempt to resolve it as such.
if (type.includes("json") === true) {
const parsed = await response.json();
if ("data" in parsed) {
return {
result: "success",
data: parsed.data,
};
}
if ("error" in parsed) {
return {
result: "error",
error: this.#toError(parsed),
};
}
return {
result: "error",
error: {
status: response.status,
message: "Unsupported 'json' body returned from server, missing 'data' or 'error' key.",
},
};
}
return {
result: "error",
error: {
status: response.status,
message: "Unsupported 'content-type' in header returned from server.",
},
};
}
#toError(candidate: unknown, status: number = 500): ServerErrorType | ServerErrorResponse["error"] {
if (assertServerErrorResponse(candidate)) {
return ServerError.fromJSON({ type: "relay", ...candidate.error });
}
if (typeof candidate === "string") {
return {
status,
message: candidate,
};
}
return {
status,
message: "Unsupported 'error' returned from server.",
};
}
}
function containsFile(value: unknown): boolean {
if (value instanceof File) {
return true;
}
if (Array.isArray(value)) {
return value.some(containsFile);
}
if (typeof value === "object" && value !== null) {
return Object.values(value).some(containsFile);
}
return false;
}
export type HttpAdapterOptions = {
url: string;
hooks?: {
beforeRequest?: ((headers: Headers) => Promise<void>)[];
};
};

View File

@@ -1,8 +1,6 @@
import { account } from "@module/account/client";
import { ledger } from "@module/ledger/client";
import { makeClient } from "@platform/relay";
import { HttpAdapter } from "./adapters/http.ts";
import { payment } from "@module/payment/client";
import { HttpAdapter, makeClient, type RelayResponse } from "@platform/relay";
export const api = makeClient(
{
@@ -12,6 +10,16 @@ export const api = makeClient(
},
{
account,
ledger,
payment,
},
);
export async function getSuccessResponse<TResponse extends RelayResponse>(
promise: Promise<TResponse>,
): Promise<Awaited<TResponse> extends RelayResponse<infer TData> ? TData : never> {
const response = await promise;
if ("error" in response) {
throw response.error;
}
return response.data as any;
}

92
app/src/services/user.ts Normal file
View File

@@ -0,0 +1,92 @@
import { redirect } from "@tanstack/react-router";
import z from "zod";
import { type ZitadelUser, zitadel } from "./zitadel.ts";
let cached: User | undefined;
const TenantSchema = z.strictObject({
id: z.string(),
name: z.string(),
domain: z.string(),
});
const ProfileSchema = z.strictObject({
id: z.string(),
name: z.string(),
email: z.string(),
avatar: z.string(),
});
export class User {
readonly id: string;
readonly name: string;
readonly email: string;
readonly avatar: string;
readonly tenant: Tenant;
constructor({ id, name, email, avatar }: Profile, tenant: Tenant) {
this.id = id;
this.name = name;
this.email = email;
this.avatar = avatar;
this.tenant = tenant;
}
static async getTenantId() {
return User.get().then((user) => user.tenant.id);
}
static async getTenantName() {
return User.get().then((user) => user.tenant.name);
}
static async get() {
const user = await User.resolve();
if (user === undefined) {
throw redirect({ to: "/login" });
}
return user;
}
static async resolve() {
if (cached === undefined) {
const user = await zitadel.userManager.getUser();
if (user === null) {
return undefined;
}
cached = new User(
getUserProfile(user),
TenantSchema.parse({
id: user.profile["urn:zitadel:iam:org:id"],
name: user.profile["urn:zitadel:iam:user:resourceowner:name"],
domain: user.profile["urn:zitadel:iam:user:resourceowner:primary_domain"],
}),
);
}
return cached;
}
}
function getUserProfile({ profile }: ZitadelUser): Profile {
const user: Profile = { id: profile.client_id as string, name: "Unknown", email: "unknown@acme.none", avatar: "" };
if (profile.name) {
user.name = profile.name;
} else if (profile.given_name && profile.family_name) {
user.name = `${profile.given_name} ${profile.family_name}`;
} else if (profile.given_name) {
user.name = profile.given_name;
}
if (profile.email) {
user.email = profile.email;
}
if (profile.picture !== undefined) {
user.avatar = profile.picture;
}
return user;
}
type Tenant = z.output<typeof TenantSchema>;
type Profile = z.output<typeof ProfileSchema>;

View File

@@ -7,9 +7,9 @@ const config: ZitadelConfig = {
redirect_uri: "http://localhost:5173/auth/callback",
post_logout_redirect_uri: "http://localhost:5173",
response_type: "code",
scope: "openid profile email urn:zitadel:iam:org:id:348388915649970180",
scope: "openid profile email urn:zitadel:iam:user:metadata urn:zitadel:iam:org:id:348388915649970180",
};
export const zitadel = createZitadelAuth(config);
export type User = NonNullable<Awaited<ReturnType<typeof zitadel.userManager.getUser>>>;
export type ZitadelUser = NonNullable<Awaited<ReturnType<typeof zitadel.userManager.getUser>>>;

83
deno.lock generated
View File

@@ -12,16 +12,19 @@
"npm:@jsr/std__assert@1.0.14": "1.0.14",
"npm:@jsr/std__dotenv@0.225.5": "0.225.5",
"npm:@jsr/std__testing@1.0.15": "1.0.15",
"npm:@jsr/valkyr__db@2.0.0": "2.0.0",
"npm:@jsr/valkyr__event-store@2.0.1": "2.0.1",
"npm:@jsr/valkyr__json-rpc@1.1.0": "1.1.0",
"npm:@radix-ui/react-avatar@1.1.11": "1.1.11_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-checkbox@1.3.3": "1.3.3_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-dialog@1.1.15": "1.1.15_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-collapsible@^1.1.12": "1.1.12_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-dialog@^1.1.15": "1.1.15_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-dropdown-menu@2.1.16": "2.1.16_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-label@2.1.8": "2.1.8_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-popover@^1.1.15": "1.1.15_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-select@2.2.6": "2.2.6_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-separator@1.1.8": "1.1.8_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-slot@1.2.4": "1.2.4_@types+react@19.2.7_react@19.2.0",
"npm:@radix-ui/react-slot@^1.2.4": "1.2.4_@types+react@19.2.7_react@19.2.0",
"npm:@radix-ui/react-tabs@1.1.13": "1.1.13_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-toggle-group@1.1.11": "1.1.11_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"npm:@radix-ui/react-toggle@1.1.10": "1.1.10_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
@@ -39,6 +42,7 @@
"npm:babel-plugin-react-compiler@1.0.0": "1.0.0",
"npm:class-variance-authority@0.7.1": "0.7.1",
"npm:clsx@2.1.1": "2.1.1",
"npm:cmdk@^1.1.1": "1.1.1_react@19.2.0_react-dom@19.2.0__react@19.2.0_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7",
"npm:eslint-plugin-react-hooks@7.0.1": "7.0.1_eslint@9.39.1_zod@4.1.13",
"npm:eslint-plugin-react-refresh@0.4.24": "0.4.24_eslint@9.39.1",
"npm:eslint@9.39.1": "9.39.1",
@@ -765,6 +769,27 @@
"@types/react-dom"
]
},
"@radix-ui/react-collapsible@1.1.12_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0": {
"integrity": "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==",
"dependencies": [
"@radix-ui/primitive",
"@radix-ui/react-compose-refs",
"@radix-ui/react-context@1.1.2_@types+react@19.2.7_react@19.2.0",
"@radix-ui/react-id",
"@radix-ui/react-presence",
"@radix-ui/react-primitive@2.1.3_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"@radix-ui/react-use-controllable-state",
"@radix-ui/react-use-layout-effect",
"@types/react",
"@types/react-dom",
"react",
"react-dom"
],
"optionalPeers": [
"@types/react",
"@types/react-dom"
]
},
"@radix-ui/react-collection@1.1.7_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0": {
"integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",
"dependencies": [
@@ -969,6 +994,34 @@
"@types/react-dom"
]
},
"@radix-ui/react-popover@1.1.15_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0": {
"integrity": "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==",
"dependencies": [
"@radix-ui/primitive",
"@radix-ui/react-compose-refs",
"@radix-ui/react-context@1.1.2_@types+react@19.2.7_react@19.2.0",
"@radix-ui/react-dismissable-layer",
"@radix-ui/react-focus-guards",
"@radix-ui/react-focus-scope",
"@radix-ui/react-id",
"@radix-ui/react-popper",
"@radix-ui/react-portal",
"@radix-ui/react-presence",
"@radix-ui/react-primitive@2.1.3_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"@radix-ui/react-slot@1.2.3_@types+react@19.2.7_react@19.2.0",
"@radix-ui/react-use-controllable-state",
"@types/react",
"@types/react-dom",
"aria-hidden",
"react",
"react-dom",
"react-remove-scroll"
],
"optionalPeers": [
"@types/react",
"@types/react-dom"
]
},
"@radix-ui/react-popper@1.2.8_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0": {
"integrity": "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==",
"dependencies": [
@@ -1944,6 +1997,17 @@
"clsx@2.1.1": {
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="
},
"cmdk@1.1.1_react@19.2.0_react-dom@19.2.0__react@19.2.0_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7": {
"integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==",
"dependencies": [
"@radix-ui/react-compose-refs",
"@radix-ui/react-dialog",
"@radix-ui/react-id",
"@radix-ui/react-primitive@2.1.4_@types+react@19.2.7_@types+react-dom@19.2.3__@types+react@19.2.7_react@19.2.0_react-dom@19.2.0__react@19.2.0",
"react",
"react-dom"
]
},
"color-convert@2.0.1": {
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dependencies": [
@@ -3209,14 +3273,17 @@
"npm:@dnd-kit/sortable@10.0.0",
"npm:@dnd-kit/utilities@3.2.2",
"npm:@eslint/js@9.39.1",
"npm:@jsr/valkyr__db@2.0.0",
"npm:@radix-ui/react-avatar@1.1.11",
"npm:@radix-ui/react-checkbox@1.3.3",
"npm:@radix-ui/react-dialog@1.1.15",
"npm:@radix-ui/react-collapsible@^1.1.12",
"npm:@radix-ui/react-dialog@^1.1.15",
"npm:@radix-ui/react-dropdown-menu@2.1.16",
"npm:@radix-ui/react-label@2.1.8",
"npm:@radix-ui/react-popover@^1.1.15",
"npm:@radix-ui/react-select@2.2.6",
"npm:@radix-ui/react-separator@1.1.8",
"npm:@radix-ui/react-slot@1.2.4",
"npm:@radix-ui/react-slot@^1.2.4",
"npm:@radix-ui/react-tabs@1.1.13",
"npm:@radix-ui/react-toggle-group@1.1.11",
"npm:@radix-ui/react-toggle@1.1.10",
@@ -3233,6 +3300,7 @@
"npm:babel-plugin-react-compiler@1.0.0",
"npm:class-variance-authority@0.7.1",
"npm:clsx@2.1.1",
"npm:cmdk@^1.1.1",
"npm:eslint-plugin-react-hooks@7.0.1",
"npm:eslint-plugin-react-refresh@0.4.24",
"npm:eslint@9.39.1",
@@ -3268,6 +3336,13 @@
]
}
},
"modules/tenant": {
"packageJson": {
"dependencies": [
"npm:zod@4.1.13"
]
}
},
"platform/cerbos": {
"packageJson": {
"dependencies": [

View File

@@ -1,9 +1,20 @@
export const ledger = {
export * from "../schemas/account.ts";
export * from "../schemas/beneficiary.ts";
export * from "../schemas/currency.ts";
export * from "../schemas/ledger.ts";
export * from "../schemas/transaction.ts";
export * from "../schemas/transaction-participant.ts";
export * from "../schemas/wallet.ts";
export const payment = {
dashboard: (await import("../routes/dashboard/spec.ts")).default,
benficiaries: {
create: (await import("../routes/beneficiaries/create/spec.ts")).default,
list: (await import("../routes/beneficiaries/list/spec.ts")).default,
id: (await import("../routes/beneficiaries/:id/spec.ts")).default,
ledgers: (await import("../routes/beneficiaries/ledgers/spec.ts")).default,
},
ledger: {
create: (await import("../routes/ledgers/create/spec.ts")).default,
},
create: (await import("../routes/ledgers/create/spec.ts")).default,
};

View File

@@ -1,5 +1,4 @@
import { db } from "@platform/database";
import { ConflictError } from "@platform/relay";
import {
type Beneficiary,
@@ -16,19 +15,9 @@ import {
* @param values - Beneficiary values to insert.
*/
export async function createBeneficiary({ tenantId, label }: BeneficiaryInsert): Promise<string> {
return db
.begin(async () => {
const _id = crypto.randomUUID();
await db.sql`ASSERT NOT EXISTS (SELECT 1 FROM payment.beneficiary WHERE "tenantId" = ${db.text(tenantId)}), 'duplicate_tenant'`;
await db.sql`INSERT INTO payment.beneficiary RECORDS ${db.transit({ _id, ...BeneficiaryInsertSchema.parse({ tenantId, label }) })}`;
return _id;
})
.catch((error) => {
if (error instanceof Error && error.message === "duplicate_tenant") {
throw new ConflictError(`Tenant '${tenantId}' already has a beneficiary`);
}
throw error;
});
const _id = crypto.randomUUID();
await db.sql`INSERT INTO payment.beneficiary RECORDS ${db.transit({ _id, ...BeneficiaryInsertSchema.parse({ tenantId, label }) })}`;
return _id;
}
/**

View File

@@ -30,7 +30,9 @@ export async function createLedger(values: LedgerInsert): Promise<string> {
})
.catch((error) => {
if (error instanceof Error && error.message === "missing_beneficiary") {
throw new BadRequestError(`Benficiary '${values.beneficiaryId}' does not exist`);
throw new BadRequestError(`Benficiary '${values.beneficiaryId}' does not exist`, {
input: "beneficiary",
});
}
throw error;
});

View File

@@ -1,5 +1,6 @@
import { route } from "@platform/relay";
import z from "zod";
import { BeneficiaryInsertSchema, BeneficiarySchema } from "../../../schemas/beneficiary.ts";
import { BeneficiaryInsertSchema } from "../../../schemas/beneficiary.ts";
export default route.post("/api/v1/payment/beneficiaries").body(BeneficiaryInsertSchema).response(BeneficiarySchema);
export default route.post("/api/v1/payment/beneficiaries").body(BeneficiaryInsertSchema).response(z.uuid());

View File

@@ -1,31 +1,29 @@
import { db } from "@platform/database";
import { NotFoundError } from "@platform/relay";
import route, { DashboardSchema } from "./spec.ts";
export default route.access("public").handle(async ({ params: { id } }) => {
const dashboard = await db.schema(DashboardSchema).one`
export default route.access("public").handle(async ({ params: { id: tenantId } }) => {
return db.schema(DashboardSchema).many`
SELECT
pb.*,
pb._system_from AS "createdAt",
NEST_MANY(
SELECT
pl.*,
pl._system_from AS "createdAt",
FROM
payment.ledger pl
WHERE
pl."beneficiaryId" = pb._id
ORDER BY
pl._id
COALESCE(
NEST_MANY(
SELECT
pl.*,
pl._system_from AS "createdAt"
FROM
payment.ledger pl
WHERE
pl."beneficiaryId" = pb._id
ORDER BY
pl._id
),
[] -- default to empty array
) AS ledgers
FROM
payment.beneficiary pb
WHERE
pb._id = ${id}
pb."tenantId" = ${tenantId}
`;
if (dashboard === undefined) {
return new NotFoundError("Beneficiary not found");
}
return dashboard;
});

View File

@@ -12,5 +12,5 @@ export const DashboardSchema = z.strictObject({
export default route
.get("/api/v1/payment/dashboard/:id")
.params({ id: BeneficiarySchema.shape._id })
.response(DashboardSchema);
.params({ id: BeneficiarySchema.shape.tenantId })
.response(z.array(DashboardSchema));

View File

@@ -9,16 +9,18 @@ import z from "zod";
|
*/
export const currencies = ["USD", "EUR", "GBP", "CHF", "JPY", "CAD", "AUD", "NOK", "SEK"] as const;
export const CurrencySchema = z.union([
z.literal("USD").describe("United States Dollar"),
z.literal("EUR").describe("Euro"),
z.literal("GBP").describe("British Pound Sterling"),
z.literal("CHF").describe("Swiss Franc"),
z.literal("JPY").describe("Japanese Yen"),
z.literal("CAD").describe("Canadian Dollar"),
z.literal("AUD").describe("Australian Dollar"),
z.literal("NOK").describe("Norwegian Krone"),
z.literal("SEK").describe("Swedish Krona"),
z.literal(currencies[0]).describe("United States Dollar"),
z.literal(currencies[1]).describe("Euro"),
z.literal(currencies[2]).describe("British Pound Sterling"),
z.literal(currencies[3]).describe("Swiss Franc"),
z.literal(currencies[4]).describe("Japanese Yen"),
z.literal(currencies[5]).describe("Canadian Dollar"),
z.literal(currencies[6]).describe("Australian Dollar"),
z.literal(currencies[7]).describe("Norwegian Krone"),
z.literal(currencies[8]).describe("Swedish Krona"),
]);
export type Currency = z.output<typeof CurrencySchema>;

View File

@@ -0,0 +1,3 @@
export const tenant = {
create: (await import("../routes/create/spec.ts")).default,
};

View File

@@ -0,0 +1,3 @@
export default {
routes: [(await import("../routes/create/handle.ts")).default],
};

View File

@@ -2,5 +2,15 @@
"name": "@module/tenant",
"version": "0.0.0",
"private": true,
"type": "module"
"type": "module",
"exports": {
"./server": "./entrypoints/server.ts",
"./client": "./entrypoints/client.ts"
},
"dependencies": {
"@platform/database": "workspace:*",
"@platform/parse": "workspace:*",
"@platform/relay": "workspace:*",
"zod": "4.1.13"
}
}

View File

View File

View File

@@ -0,0 +1,26 @@
import z from "zod";
/*
|--------------------------------------------------------------------------------
| Tenant
|--------------------------------------------------------------------------------
*/
export const TenantSchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the account"),
name: z.string().describe("Human-readable name for the tenant"),
});
export type Tenant = z.output<typeof TenantSchema>;
/*
|--------------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------------
*/
export const TenantInsertSchema = z.strictObject({
name: TenantSchema.shape.name,
});
export type TenantInsert = z.input<typeof TenantInsertSchema>;

View File

@@ -7,6 +7,74 @@ import {
} from "../libraries/adapter.ts";
import { ServerError, type ServerErrorType } from "../libraries/errors.ts";
class HttpReadQueue {
#cache = new Map<string, any>();
#queue: {
[url: string]: {
cb: () => Promise<any>;
resolve: (value: any) => void;
}[];
} = {};
#processing = new Set<string>();
async push<TCallback extends () => Promise<any>>(url: string, cb: TCallback) {
return new Promise<any>((resolve) => {
if (this.#queue[url] === undefined) {
this.#queue[url] = [];
}
this.#queue[url].push({
cb,
resolve,
});
this.process(url);
});
}
async process(url: string) {
const cachedResponse = this.#cache.get(url);
if (cachedResponse !== undefined) {
return this.drain(url);
}
if (this.#processing.has(url) === true) {
return;
}
const job = this.#queue[url]?.shift();
if (job === undefined) {
return this.#processing.delete(url);
}
this.#processing.add(url);
const result = await job.cb();
this.#cache.set(url, result);
job.resolve(result);
this.drain(url);
setTimeout(() => {
this.#cache.delete(url);
}, 1000);
return this.#processing.delete(url);
}
drain(url: string) {
const cache = this.#cache.get(url);
if (cache === undefined) {
return;
}
const job = this.#queue[url]?.shift();
if (job !== undefined) {
job.resolve(cache);
this.drain(url);
}
}
}
/**
* HttpAdapter provides a unified transport layer for Relay.
*
@@ -37,6 +105,8 @@ import { ServerError, type ServerErrorType } from "../libraries/errors.ts";
* ```
*/
export class HttpAdapter implements RelayAdapter {
readonly #queue = new HttpReadQueue();
/**
* Instantiate a new HttpAdapter instance.
*
@@ -92,7 +162,15 @@ export class HttpAdapter implements RelayAdapter {
// ### Response
return this.request(`${endpoint}${query}`, init);
const url = `${endpoint}${query}`;
if (method === "GET") {
return this.#queue.push(url, () => {
return this.request(url, init);
});
}
return this.request(url, init);
}
/**

View File

@@ -131,6 +131,7 @@ async function toParsedArgs(
): Promise<Record<string, string | number | boolean>> {
const result = await zod.safeParseAsync(args);
if (result.success === false) {
console.error(msg, args, result.error);
throw new Error(msg);
}
return result.data as Record<string, string | number | boolean>;