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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added company and seller rankings, and moved reporting onto the status tokens
Damian Legawieccc66e5612e06
diff --git a/packages/dashboard/src/components/spree/reporting/growth-badge.tsx b/packages/dashboard/src/components/spree/reporting/growth-badge.tsxindex 04ec7756cb..c4162a31f9 100644--- a/packages/dashboard/src/components/spree/reporting/growth-badge.tsx+++ b/packages/dashboard/src/components/spree/reporting/growth-badge.tsx@@ -36,7 +36,10 @@ export function GrowthBadge({ growth }: { growth: number | null | undefined }) {<spanclassName={cn('inline-flex items-center gap-0.5 text-xs font-medium',- growth > 0 ? 'text-green-700 dark:text-green-400' : 'text-destructive',+ // The status trio, not a raw Tailwind ramp: a hand-picked green needs+ // re-tinting for dark mode at every call site, which is what the+ // token family exists to stop.+ growth > 0 ? 'text-success' : 'text-danger',)}title={t('admin.pages.home.growth.vs_previous')}>diff --git a/packages/dashboard/src/components/spree/reporting/report-builder.tsx b/packages/dashboard/src/components/spree/reporting/report-builder.tsxindex cb6cec0933..9facb4110a 100644--- a/packages/dashboard/src/components/spree/reporting/report-builder.tsx+++ b/packages/dashboard/src/components/spree/reporting/report-builder.tsx@@ -63,6 +63,27 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {const update = (patch: Partial<ReportDraft>) => onChange({ ...draft, ...patch })+ // Metrics from different families cannot be combined in one query, so the+ // picker groups them and disables the families the current selection has+ // ruled out — the alternative is a flat run of 27 checkboxes where the+ // refusal only arrives after you have picked an impossible pair.+ const metricGroups =+ schema.families?.length > 0+ ? schema.families+ .map((family) => ({+ name: family.name,+ label: family.label,+ metrics: schema.metrics.filter((metric) => family.metrics.includes(metric.name)),+ }))+ .filter((group) => group.metrics.length > 0)+ : [{ name: 'all', label: '', metrics: schema.metrics }]++ // Whichever family the current selection belongs to; null while nothing is+ // picked, so every family stays open.+ const activeFamily =+ metricGroups.find((group) => group.metrics.some((m) => draft.metrics.includes(m.name)))?.name ??+ null+const groupableDimensions = schema.dimensions.filter((d) =>draft.metrics.every((metric) => d.compatible_metrics.includes(metric)),)@@ -161,33 +182,46 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {<CardTitle>{t('admin.reports.builder.title')}</CardTitle></CardHeader><CardContent className="flex flex-col gap-6">- <FieldSet className="flex flex-col gap-2">- <FieldLegend variant="label">{t('admin.reports.builder.metrics')}</FieldLegend>- {schema.metrics.map((metric) => {- const id = `metric-${metric.name}`- // Greyed out when the chosen breakdown or any active filter cannot- // be combined with this metric.- const incompatible = [- dimension,- ...draft.filters.map((f) => findDimension(schema, f.dimension)),- ].some((d) => d && !d.compatible_metrics.includes(metric.name))- return (- <Field key={metric.name} orientation="horizontal">- <Checkbox- id={id}- checked={draft.metrics.includes(metric.name)}- disabled={incompatible}- onCheckedChange={(checked) => toggleMetric(metric.name, checked)}- />- <FieldLabel- htmlFor={id}- className={cn('font-normal', incompatible && 'text-muted-foreground')}- >- {metric.label}- </FieldLabel>- </Field>- )- })}+ <FieldSet className="flex flex-col gap-4">+ <FieldLegend variant="label" className="mb-0">+ {t('admin.reports.builder.metrics')}+ </FieldLegend>+ {metricGroups.map((group) => (+ <div key={group.name} className="flex flex-col gap-2">+ {metricGroups.length > 1 && (+ <span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">+ {group.label}+ </span>+ )}+ {group.metrics.map((metric) => {+ const id = `metric-${metric.name}`+ // Greyed out when the chosen breakdown, an active filter, or a+ // metric from another family cannot be combined with this one.+ const incompatible =+ [dimension, ...draft.filters.map((f) => findDimension(schema, f.dimension))].some(+ (d) => d && !d.compatible_metrics.includes(metric.name),+ ) ||+ (activeFamily !== null && group.name !== activeFamily)+ return (+ <Field key={metric.name} orientation="horizontal">+ <Checkbox+ id={id}+ checked={draft.metrics.includes(metric.name)}+ disabled={incompatible}+ onCheckedChange={(checked) => toggleMetric(metric.name, checked)}+ />+ <FieldLabel+ htmlFor={id}+ title={metric.description ?? undefined}+ className={cn('font-normal', incompatible && 'text-muted-foreground')}+ >+ {metric.label}+ </FieldLabel>+ </Field>+ )+ })}+ </div>+ ))}{draft.metrics.length === 0 && (<p className="text-xs text-destructive">{t('admin.reports.builder.no_metrics')}</p>)}@@ -249,7 +283,11 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {{draft.filters.map((filter, index) => {const definition = findDimension(schema, filter.dimension)return (- <div key={filter.dimension} className="flex flex-col gap-1.5 rounded-md border p-3">+ <Card+ key={filter.dimension}+ variant="nested"+ className="flex flex-col gap-1.5 py-2.5"+ ><div className="flex items-center justify-between gap-2"><span className="text-sm font-medium">{definition?.label ?? filter.dimension}@@ -271,7 +309,7 @@ export function ReportBuilder({ draft, onChange, schema }: ReportBuilderProps) {values={filter.values}onChange={(values) => setFilter(index, { ...filter, values })}/>- </div>+ </Card>)})}{filterableDimensions.length > 0 && (diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 565564dd4a..82a4efdba5 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3212,7 +3212,9 @@"subtitle": "الأفضل أداءً في الفترة المحددة.","tabs": {"customers": "العملاء",- "categories": "الفئات"+ "categories": "الفئات",+ "companies": "الشركات",+ "sellers": "البائعون"},"orders_count_zero": "لا طلبات","orders_count_one": "طلب واحد",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 1f365bfd3f..8006480866 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3195,7 +3195,9 @@"subtitle": "Top-Performer im ausgewählten Zeitraum.","tabs": {"customers": "Kunden",- "categories": "Kategorien"+ "categories": "Kategorien",+ "companies": "Firmen",+ "sellers": "Verkäufer"},"orders_count_one": "{{count}} Bestellung","orders_count_other": "{{count}} Bestellungen",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex af9a54775a..e88e5165c2 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3195,7 +3195,9 @@"subtitle": "Top performers in the selected period.","tabs": {"customers": "Customers",- "categories": "Categories"+ "categories": "Categories",+ "companies": "Companies",+ "sellers": "Sellers"},"orders_count_one": "{{count}} order","orders_count_other": "{{count}} orders",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 4739a28e76..ccfa2d47dd 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3195,7 +3195,9 @@"subtitle": "Meilleures performances sur la période sélectionnée.","tabs": {"customers": "Clients",- "categories": "Catégories"+ "categories": "Catégories",+ "companies": "Entreprises",+ "sellers": "Vendeurs"},"orders_count_one": "{{count}} commande","orders_count_other": "{{count}} commandes",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 06bf060500..5662756013 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3227,7 +3227,9 @@"subtitle": "Najlepsze wyniki w wybranym okresie.","tabs": {"customers": "Klienci",- "categories": "Kategorie"+ "categories": "Kategorie",+ "companies": "Firmy",+ "sellers": "Sprzedawcy"},"orders_count_one": "{{count}} zamówienie","orders_count_few": "{{count}} zamówienia",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 4442b0c643..959d831332 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3187,7 +3187,9 @@"subtitle": "所选时间段内表现最佳。","tabs": {"customers": "客户",- "categories": "类目"+ "categories": "类目",+ "companies": "公司",+ "sellers": "卖家"},"orders_count_other": "{{count}} 笔订单","units_count_other": "{{count}} 件",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsxindex 47df2e1176..3c26e67a2d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/index.tsx@@ -92,6 +92,8 @@ function DashboardPage() {const rankingTabs: RankingTab[] = [...(permissions.can('read', Subject.Customer) ? (['customers'] as const) : []),...(permissions.can('read', Subject.Category) ? (['categories'] as const) : []),+ ...(permissions.can('read', Subject.Company) ? (['companies'] as const) : []),+ ...(permissions.can('read', Subject.Seller) ? (['sellers'] as const) : []),]const channelParam = channelId === ALL_CHANNELS ? undefined : channelId@@ -348,7 +350,7 @@ function OperationsCard({)}-type RankingTab = 'customers' | 'categories'+type RankingTab = 'customers' | 'categories' | 'companies' | 'sellers'// Each tab is one contract query; the revenue metric doubles as the share bar.const RANKING_QUERIES: Record<@@ -379,6 +381,27 @@ const RANKING_QUERIES: Record<revenueMetric: 'net_sales',countMetric: 'units_sold',},+ companies: {+ query: {+ metrics: ['total_sales', 'orders'],+ dimensions: ['company'],+ sort: '-total_sales',+ limit: 5,+ },+ revenueMetric: 'total_sales',+ countMetric: 'orders',+ },+ // What each seller sold, on the line items that were theirs.+ sellers: {+ query: {+ metrics: ['net_sales', 'units_sold'],+ dimensions: ['seller'],+ sort: '-net_sales',+ limit: 5,+ },+ revenueMetric: 'net_sales',+ countMetric: 'units_sold',+ },}function RankingsCard({@@ -499,6 +522,30 @@ function RankingName({)}+ if (tab === 'companies') {+ return (+ <Link+ to="/$storeId/companies/$companyId"+ params={{ storeId, companyId: dimension.id }}+ className="min-w-0 hover:underline"+ >+ {label}+ </Link>+ )+ }++ if (tab === 'sellers') {+ return (+ <Link+ to="/$storeId/sellers/$sellerId"+ params={{ storeId, sellerId: dimension.id }}+ className="min-w-0 hover:underline"+ >+ {label}+ </Link>+ )+ }+return (<Linkto="/$storeId/products/categories/$categoryId"diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 6e1f3a26c6..50061d3c69 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1692,6 +1692,9 @@ en:channel:description: The channel the order came through.label: Sales channel+ company:+ description: The organisation the purchase was made for.+ label: Companycompleted_at:description: When the order was placed, bucketed by day, week or month in the store timezone.label: Datediff --git a/spree/core/lib/spree/reporting/default_vocabulary.rb b/spree/core/lib/spree/reporting/default_vocabulary.rbindex 69e7e169d7..223a82f8b1 100644--- a/spree/core/lib/spree/reporting/default_vocabulary.rb+++ b/spree/core/lib/spree/reporting/default_vocabulary.rb@@ -274,6 +274,18 @@ module Spreeend}+ # The buying organisation. Keyed by whichever node the purchase named+ # — a division's spend stays that division's, rather than rolling+ # silently into its parent.+ dimension :company, base: :orders, column: :company_id, lookup: :company,+ subject: -> { Spree::Company }, key_scope: 'read_customers',+ resolve: ->(store, value) { store.companies.find_by_prefix_id!(value).id },+ hydrate: lambda { |store, ids, _params|+ store.companies.where(id: ids).to_h do |company|+ [company.id, { id: company.prefixed_id, label: company.name, meta: { kind: company.kind } }]+ end+ }+dimension :category, base: :line_items, column: '%{product_categories}.category_id',joins: [{ variant: { product: :product_categories } }], lookup: :category,subject: -> { Spree::Category }, key_scope: 'read_categories',diff --git a/spree/core/spec/lib/spree/reporting/query_spec.rb b/spree/core/spec/lib/spree/reporting/query_spec.rbindex 33a8b5631e..12233591b7 100644--- a/spree/core/spec/lib/spree/reporting/query_spec.rb+++ b/spree/core/spec/lib/spree/reporting/query_spec.rb@@ -218,6 +218,27 @@ RSpec.describe Spree::Reporting::Query doendend+ describe 'company breakdown' do+ let!(:company) { create(:company, store: store) }+ let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }++ before { order.update_columns(company_id: company.id) }++ it 'ranks the organisations that bought' do+ result = run(metrics: %w[total_sales orders], dimensions: %w[company])++ expect(result.rows.first[:dimensions][:company]).to eq(company.id)+ expect(result.rows.first[:metrics][:orders][:value]).to eq(1)+ end++ it 'requires permission to read the buying organisation' do+ query = described_class.new(store: store, params: { metrics: %w[orders], dimensions: %w[company] })++ expect(query.required_subjects).to include(Spree::Company)+ expect(query.required_key_scopes).to contain_exactly('read_customers')+ end+ end+describe 'seller payout' dolet!(:seller) { create(:seller, :approved, store: store) }let!(:order) { create(:completed_order_with_totals, store: store, completed_at: 3.days.ago) }