Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Put the companies list back on the standard resource table

Damian Legawiec4757e0d34f00
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index eb30ca1356..0b1e263d17 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -389,7 +389,6 @@
"companies": {
"add_cta": "إضافة شركة",
"add_sheet_title": "شركة جديدة",
- "collapse_node": "طي",
"create_description": "الشركة هي جذر شجرة المؤسسة. يمكنك إضافة الوحدات الفرعية والأعضاء والعناوين والتسجيلات الضريبية وشهادات الإعفاء بعد إنشائها.",
"create_label": "إنشاء شركة",
"delete_confirm": {
@@ -403,12 +402,11 @@
"profile": "الشركة"
},
"empty": "لا توجد شركات بعد",
- "expand_node": "توسيع",
"kind": {
"company": "شركة",
"division": "قسم"
},
- "load_more": "عرض المزيد…",
+ "members_column": "الأعضاء",
"members_count_few": "{{count}} أعضاء",
"members_count_many": "{{count}} عضوًا",
"members_count_one": "عضو واحد",
@@ -419,7 +417,6 @@
"deleted": "تم حذف الشركة",
"updated": "تم تحديث الشركة"
},
- "search_empty": "لا توجد شركات مطابقة لبحثك",
"search_placeholder": "البحث في الشركات",
"sub_units": {
"add_cta": "إضافة وحدة فرعية",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 6225fbe31b..2da4606a86 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -386,7 +386,6 @@
"companies": {
"add_cta": "Unternehmen hinzufügen",
"add_sheet_title": "Neues Unternehmen",
- "collapse_node": "Zuklappen",
"create_description": "Ein Unternehmen ist die Wurzel eines Organisationsbaums. Untereinheiten, Mitglieder, Adressen, Steuerregistrierung und Befreiungsnachweise fügen Sie danach hinzu.",
"create_label": "Unternehmen erstellen",
"delete_confirm": {
@@ -400,12 +399,11 @@
"profile": "Unternehmen"
},
"empty": "Noch keine Unternehmen",
- "expand_node": "Aufklappen",
"kind": {
"company": "Unternehmen",
"division": "Abteilung"
},
- "load_more": "Mehr anzeigen…",
+ "members_column": "Mitglieder",
"members_count_one": "{{count}} Mitglied",
"members_count_other": "{{count}} Mitglieder",
"messages": {
@@ -413,7 +411,6 @@
"deleted": "Unternehmen gelöscht",
"updated": "Unternehmen aktualisiert"
},
- "search_empty": "Keine Unternehmen entsprechen Ihrer Suche",
"search_placeholder": "Unternehmen suchen",
"sub_units": {
"add_cta": "Untereinheit hinzufügen",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 95039ee784..a867e0664e 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -386,7 +386,6 @@
"companies": {
"add_cta": "Add company",
"add_sheet_title": "New company",
- "collapse_node": "Collapse",
"create_description": "A company is the root of an organization tree. Add sub-units, members, addresses, tax registration and exemption certificates once it exists.",
"create_label": "Create company",
"delete_confirm": {
@@ -400,12 +399,11 @@
"profile": "Company"
},
"empty": "No companies yet",
- "expand_node": "Expand",
"kind": {
"company": "Company",
"division": "Division"
},
- "load_more": "Show more…",
+ "members_column": "Members",
"members_count_one": "{{count}} member",
"members_count_other": "{{count}} members",
"messages": {
@@ -413,7 +411,6 @@
"deleted": "Company deleted",
"updated": "Company updated"
},
- "search_empty": "No companies match your search",
"search_placeholder": "Search companies",
"sub_units": {
"add_cta": "Add sub-unit",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index fcd723c374..6ad3295501 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -386,7 +386,6 @@
"companies": {
"add_cta": "Ajouter une entreprise",
"add_sheet_title": "Nouvelle entreprise",
- "collapse_node": "Replier",
"create_description": "Une entreprise est la racine d’un arbre organisationnel. Ajoutez ensuite sous-unités, membres, adresses, immatriculation fiscale et certificats d’exonération.",
"create_label": "Créer l’entreprise",
"delete_confirm": {
@@ -400,12 +399,11 @@
"profile": "Entreprise"
},
"empty": "Aucune entreprise pour le moment",
- "expand_node": "Déplier",
"kind": {
"company": "Entreprise",
"division": "Division"
},
- "load_more": "Afficher plus…",
+ "members_column": "Membres",
"members_count_one": "{{count}} membre",
"members_count_other": "{{count}} membres",
"messages": {
@@ -413,7 +411,6 @@
"deleted": "Entreprise supprimée",
"updated": "Entreprise mise à jour"
},
- "search_empty": "Aucune entreprise ne correspond à votre recherche",
"search_placeholder": "Rechercher des entreprises",
"sub_units": {
"add_cta": "Ajouter une sous-unité",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index da355ff1ec..c117370000 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -394,7 +394,6 @@
"companies": {
"add_cta": "Dodaj firmę",
"add_sheet_title": "Nowa firma",
- "collapse_node": "Zwiń",
"create_description": "Firma jest korzeniem drzewa organizacji. Jednostki podrzędne, członków, adresy, rejestracje podatkowe i certyfikaty zwolnień dodasz później.",
"create_label": "Utwórz firmę",
"delete_confirm": {
@@ -408,12 +407,11 @@
"profile": "Firma"
},
"empty": "Brak firm",
- "expand_node": "Rozwiń",
"kind": {
"company": "Firma",
"division": "Oddział"
},
- "load_more": "Pokaż więcej…",
+ "members_column": "Członkowie",
"members_count_few": "{{count}} członków",
"members_count_many": "{{count}} członków",
"members_count_one": "{{count}} członek",
@@ -423,7 +421,6 @@
"deleted": "Firma usunięta",
"updated": "Firma zaktualizowana"
},
- "search_empty": "Żadna firma nie pasuje do wyszukiwania",
"search_placeholder": "Szukaj firm",
"sub_units": {
"add_cta": "Dodaj jednostkę",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index c3302033a7..1427cc5d54 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -385,7 +385,6 @@
"companies": {
"add_cta": "添加公司",
"add_sheet_title": "新建公司",
- "collapse_node": "折叠",
"create_description": "公司是组织树的根节点。创建后可以添加子单位、成员、地址、税务登记和免税证书。",
"create_label": "创建公司",
"delete_confirm": {
@@ -399,19 +398,17 @@
"profile": "公司"
},
"empty": "暂无公司",
- "expand_node": "展开",
"kind": {
"company": "公司",
"division": "部门"
},
- "load_more": "显示更多…",
+ "members_column": "成员",
"members_count_other": "{{count}} 名成员",
"messages": {
"created": "公司已创建",
"deleted": "公司已删除",
"updated": "公司已更新"
},
- "search_empty": "没有匹配的公司",
"search_placeholder": "搜索公司",
"sub_units": {
"add_cta": "添加子单位",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx
index 1b30caa558..ac5ab24ba9 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx
@@ -4,49 +4,44 @@ import {
adminClient,
Can,
mapSpreeErrorsToForm,
- PageHeader,
+ ResourceTable,
+ resourceSearchSchema,
Subject,
- useResourceKey,
+ usePermissions,
} from '@spree/dashboard-core'
import {
Button,
- Card,
- CardContent,
- cn,
Field,
FieldError,
FieldGroup,
FieldLabel,
Input,
- Pagination,
- SearchInput,
+ RowActions,
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
- Skeleton,
+ useConfirm,
+ useRowClickBridge,
} from '@spree/dashboard-ui'
-import { useQuery } from '@tanstack/react-query'
-import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
-import { Building2Icon, ChevronDownIcon, ChevronRightIcon, PlusIcon } from 'lucide-react'
-import { useState } from 'react'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
-import { CompanyKindBadge } from '../../../../components/spree/company-kind-badge'
-import { useCompanyChildren, useCreateCompany } from '../../../../hooks/use-companies'
+import { useCreateCompany, useDeleteCompany } from '../../../../hooks/use-companies'
import {
COMPANY_DEFAULTS,
type CompanyFormValues,
companyFormSchema,
companyValuesToParams,
} from '../../../../schemas/company'
+import '../../../../tables/companies'
-const companiesSearchSchema = z.object({
+const companiesSearchSchema = resourceSearchSchema.extend({
new: z.coerce.boolean().optional(),
- q: z.string().optional(),
})
export const Route = createFileRoute('/_authenticated/$storeId/companies/')({
@@ -56,11 +51,18 @@ export const Route = createFileRoute('/_authenticated/$storeId/companies/')({
function CompaniesPage() {
const { t } = useTranslation()
+ const { storeId } = Route.useParams()
const search = Route.useSearch() as z.infer<typeof companiesSearchSchema>
const navigate = useNavigate()
+ const confirm = useConfirm()
+ const deleteMutation = useDeleteCompany()
+ const { permissions } = usePermissions()
const isCreating = !!search.new
- const query = search.q ?? ''
+
+ function openDetail(id: string) {
+ navigate({ to: '/$storeId/companies/$companyId', params: { storeId, companyId: id } })
+ }
const closeSheet = () =>
navigate({
@@ -73,22 +75,43 @@ function CompaniesPage() {
const openCreate = () =>
navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })
- const setQuery = (value: string) =>
- navigate({
- search: (prev: Record<string, unknown>) => {
- const { q: _q, ...rest } = prev
- return (value ? { ...rest, q: value } : rest) as never
- },
- replace: true,
+ useRowClickBridge('data-company-id', openDetail)
+
+ async function handleDelete(company: Company) {
+ const ok = await confirm({
+ title: t('admin.companies.delete_confirm.title'),
+ message: t('admin.companies.delete_confirm.message', { name: company.name ?? '' }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
})
+ if (!ok) return
+ await deleteMutation.mutateAsync(company.id).catch(() => undefined)
+ }
return (
- <div className="flex flex-col gap-4">
- <PageHeader
- title={t('admin.nav.companies')}
+ <>
+ <ResourceTable<Company>
+ tableKey="companies"
+ queryKey="companies"
+ queryFn={(params) => adminClient.companies.list(params)}
+ searchParams={search}
+ rowActions={(company) => (
+ <RowActions
+ actions={[
+ { key: 'edit', onSelect: () => openDetail(company.id) },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: permissions.can('destroy', Subject.Company),
+ disabled: deleteMutation.isPending,
+ onSelect: () => handleDelete(company),
+ },
+ ]}
+ />
+ )}
actions={
<Can I="create" a={Subject.Company}>
- <Button size="sm" onClick={openCreate}>
+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
<PlusIcon className="size-4" />
{t('admin.companies.add_cta')}
</Button>
@@ -96,182 +119,11 @@ function CompaniesPage() {
}
/>
- <SearchInput
- value={query}
- onValueChange={setQuery}
- placeholder={t('admin.companies.search_placeholder')}
- />
-
- <Card>
- <CardContent className="p-0">
- {query ? <CompanySearchResults query={query} /> : <CompanyTreeLevel depth={0} />}
- </CardContent>
- </Card>
-
{isCreating && <CreateCompanySheet open onOpenChange={(o) => !o && closeSheet()} />}
- </div>
- )
-}
-
-/**
- * One level of the tree: the roots, or a node's children when `parentId` is
- * set. Children load lazily on expand (`?q[parent_id_eq]` drives it), so a
- * large directory never loads whole.
- */
-function CompanyTreeLevel({ parentId, depth }: { parentId?: string; depth: number }) {
- const { t } = useTranslation()
- const [page, setPage] = useState(1)
- const { data, isLoading } = useCompanyChildren(parentId, page)
-
- const companies = data?.data ?? []
- const meta = data?.meta
-
- if (isLoading && !data) {
- return (
- <div className="flex flex-col gap-2 p-4" style={{ paddingLeft: `${depth * 1.5 + 1}rem` }}>
- <Skeleton className="h-5 w-1/2" />
- <Skeleton className="h-5 w-1/3" />
- </div>
- )
- }
-
- if (companies.length === 0 && depth === 0) {
- return (
- <div className="flex flex-col items-center gap-2 p-10 text-center">
- <Building2Icon className="size-8 text-muted-foreground" />
- <p className="text-muted-foreground text-sm">{t('admin.companies.empty')}</p>
- </div>
- )
- }
-
- return (
- <div className="flex flex-col">
- {companies.map((company) => (
- <CompanyTreeRow key={company.id} company={company} depth={depth} />
- ))}
- {depth === 0 && meta && meta.pages > 1 && <Pagination meta={meta} onPageChange={setPage} />}
- {depth > 0 && meta && meta.pages > 1 && page < meta.pages && (
- <button
- type="button"
- className="px-6 py-2 text-left text-muted-foreground text-xs hover:text-foreground"
- style={{ paddingLeft: `${depth * 1.5 + 1.5}rem` }}
- onClick={() => setPage(page + 1)}
- >
- {t('admin.companies.load_more')}
- </button>
- )}
- </div>
- )
-}
-
-function CompanyTreeRow({ company, depth }: { company: Company; depth: number }) {
- const { t } = useTranslation()
- const { storeId } = Route.useParams()
- const [expanded, setExpanded] = useState(false)
- const hasChildren = company.children_count > 0
-
- return (
- <>
- <div
- className="flex items-center gap-2 border-b px-4 py-2.5 last:border-b-0 hover:bg-muted/50"
- style={{ paddingLeft: `${depth * 1.5 + 1}rem` }}
- >
- <button
- type="button"
- onClick={() => setExpanded((prev) => !prev)}
- disabled={!hasChildren}
- aria-label={
- expanded ? t('admin.companies.collapse_node') : t('admin.companies.expand_node')
- }
- aria-expanded={hasChildren ? expanded : undefined}
- className={cn(
- 'flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground',
- hasChildren ? 'hover:bg-muted hover:text-foreground' : 'opacity-0',
- )}
- >
- {expanded ? (
- <ChevronDownIcon className="size-4" />
- ) : (
- <ChevronRightIcon className="size-4" />
- )}
- </button>
-
- <Link
- to={'/$storeId/companies/$companyId' as string}
- params={{ storeId, companyId: company.id }}
- className="flex min-w-0 flex-1 items-center gap-2 no-underline"
- >
- <span className="truncate font-medium text-foreground text-sm">{company.name}</span>
- <CompanyKindBadge kind={company.kind} />
- </Link>
-
- <span className="shrink-0 text-muted-foreground text-xs">
- {t('admin.companies.members_count', { count: company.members_count })}
- </span>
- </div>
- {expanded && <CompanyTreeLevel parentId={company.id} depth={depth + 1} />}
</>
)
}
-/** Flat, path-annotated results — the tree does not compose with search. */
-function CompanySearchResults({ query }: { query: string }) {
- const { t } = useTranslation()
- const { storeId } = Route.useParams()
- const [page, setPage] = useState(1)
- const { data, isLoading } = useQuery({
- queryKey: useResourceKey('companies', 'search', `${query}:${page}`),
- queryFn: () => adminClient.companies.list({ page, limit: 25, name_cont: query, sort: 'name' }),
- placeholderData: (previous) => previous,
- })
-
- const companies = data?.data ?? []
- const meta = data?.meta
-
- if (isLoading && !data) {
- return (
- <div className="flex flex-col gap-2 p-4">
- <Skeleton className="h-5 w-1/2" />
- </div>
- )
- }
-
- if (companies.length === 0) {
- return (
- <div className="flex flex-col items-center gap-2 p-10 text-center">
- <Building2Icon className="size-8 text-muted-foreground" />
- <p className="text-muted-foreground text-sm">{t('admin.companies.search_empty')}</p>
- </div>
- )
- }
-
- return (
- <div className="flex flex-col">
- {companies.map((company) => (
- <Link
- key={company.id}
- to={'/$storeId/companies/$companyId' as string}
- params={{ storeId, companyId: company.id }}
- className="flex items-center gap-2 border-b px-6 py-2.5 no-underline last:border-b-0 hover:bg-muted/50"
- >
- <span className="min-w-0 flex-col">
- <span className="flex items-center gap-2">
- <span className="truncate font-medium text-foreground text-sm">{company.name}</span>
- <CompanyKindBadge kind={company.kind} />
- </span>
- {company.ancestors.length > 0 && (
- <span className="block truncate text-muted-foreground text-xs">
- {company.ancestors.map((ancestor) => ancestor.name).join(' / ')}
- </span>
- )}
- </span>
- </Link>
- ))}
- {meta && meta.pages > 1 && <Pagination meta={meta} onPageChange={setPage} />}
- </div>
- )
-}
-
function CreateCompanySheet({
open,
onOpenChange,
@@ -290,7 +142,8 @@ function CreateCompanySheet({
})
// A new root is always a legal entity; sub-units are added from the node
- // page, where the parent is unambiguous.
+ // page, where the parent is unambiguous. Members, addresses and tax
+ // registrations also live there — so that is where the merchant is headed.
async function onSubmit(values: CompanyFormValues) {
try {
const company = await createMutation.mutateAsync(companyValuesToParams(values))
diff --git a/packages/dashboard/src/tables/companies.tsx b/packages/dashboard/src/tables/companies.tsx
new file mode 100644
index 0000000000..d02da15c78
--- /dev/null
+++ b/packages/dashboard/src/tables/companies.tsx
@@ -0,0 +1,70 @@
+import type { Company } from '@spree/admin-sdk'
+import { defineTable } from '@spree/dashboard-core'
+import { RelativeTime, ResourceNameCell } from '@spree/dashboard-ui'
+import i18n from 'i18next'
+import { Building2Icon } from 'lucide-react'
+import { CompanyKindBadge } from '../components/spree/company-kind-badge'
+
+defineTable<Company>('companies', {
+ title: i18n.t('admin.nav.companies'),
+ searchParam: 'name_cont',
+ searchPlaceholder: i18n.t('admin.companies.search_placeholder'),
+ defaultSort: { field: 'name', direction: 'asc' },
+ emptyIcon: <Building2Icon className="size-8 text-muted-foreground" />,
+ emptyMessage: i18n.t('admin.companies.empty'),
+ columns: [
+ {
+ key: 'name',
+ label: i18n.t('admin.fields.name.label'),
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (company) => (
+ <ResourceNameCell
+ id={company.id}
+ dataAttr="data-company-id"
+ name={company.name}
+ // The node's place in the tree — "Acme / EMEA" — so a flat,
+ // paginated list still reads hierarchically.
+ secondary={
+ company.ancestors.length > 0
+ ? company.ancestors.map((ancestor) => ancestor.name).join(' / ')
+ : undefined
+ }
+ />
+ ),
+ },
+ {
+ key: 'kind',
+ label: i18n.t('admin.fields.company.kind.label'),
+ sortable: true,
+ filterable: true,
+ filterType: 'enum',
+ filterOptions: [
+ { value: 'company', label: i18n.t('admin.companies.kind.company') },
+ { value: 'division', label: i18n.t('admin.companies.kind.division') },
+ ],
+ default: true,
+ render: (company) => <CompanyKindBadge kind={company.kind} />,
+ },
+ {
+ key: 'members_count',
+ label: i18n.t('admin.companies.members_column'),
+ default: true,
+ render: (company) => company.members_count,
+ },
+ {
+ key: 'children_count',
+ label: i18n.t('admin.companies.sub_units.title'),
+ default: true,
+ render: (company) => company.children_count,
+ },
+ {
+ key: 'created_at',
+ label: i18n.t('admin.fields.created_at.label'),
+ sortable: true,
+ default: true,
+ render: (company) => <RelativeTime iso={company.created_at} />,
+ },
+ ],
+})