@rebasepro/plugin-insights 0.17.3 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,95 +0,0 @@
1
- import type { DataRow, ScorecardConfig } from "./widgets";
2
-
3
- export interface InsightContext {
4
- /** The resolved path of the collection (e.g., "products/123/orders" or "orders") */
5
- path?: string;
6
- parentCollectionSlugs?: string[];
7
- /** The parent entity IDs if this is a subcollection (e.g., ["123"]) */
8
- parentEntityIds?: string[];
9
- /** The collection slug if this is an insight at the collection level */
10
- collectionSlug?: string;
11
- }
12
-
13
- /**
14
- * Result returned by an insight's data callback.
15
- */
16
- export interface InsightDataResult {
17
- rows: DataRow[];
18
- }
19
-
20
- /**
21
- * A single insight definition — the "dry" configuration that describes
22
- * what data to fetch and how to render it.
23
- *
24
- * Each insight owns its own `data()` callback, giving the developer
25
- * full flexibility: use the Rebase client SDK, call a custom function,
26
- * hit an external API — whatever makes sense for that widget.
27
- */
28
- export interface InsightDefinition {
29
- /** Unique identifier for this insight */
30
- id: string;
31
- /** Display title */
32
- title: string;
33
- /** Optional description */
34
- description?: string;
35
-
36
- /**
37
- * Async callback that fetches data for this insight.
38
- *
39
- * The developer has full control — they can use any data source:
40
- * - `rebaseClient.data.orders.find({ limit: 100 })`
41
- * - `rebaseClient.call("functions/my-analytics", { ... })`
42
- * - A plain `fetch()` to any external API
43
- * - Static data for prototyping
44
- *
45
- * @returns Tabular data as `{ rows: DataRow[] }`.
46
- *
47
- * @example
48
- * ```typescript
49
- * data: async () => {
50
- * const res = await rebaseClient.data.orders.find({
51
- * limit: 1000,
52
- * orderBy: "created_at",
53
- * });
54
- * return { rows: res.data };
55
- * }
56
- * ```
57
- */
58
- data: (context: InsightContext) => Promise<InsightDataResult>;
59
-
60
- /** Scorecard field mapping + formatting. */
61
- scorecard: ScorecardConfig;
62
- }
63
-
64
- /**
65
- * Full plugin configuration passed to `useInsightsPlugin`.
66
- *
67
- * The developer defines scorecard widgets by placement and provides
68
- * their own data callbacks. No global fetch function needed — each
69
- * widget is self-contained.
70
- *
71
- * Collection-level insights (`collections.<slug>`) are rendered in two places
72
- * automatically:
73
- * - **Collection list view**: Scorecards appear inline below the title and
74
- * above the data list.
75
- * - **Home page cards**: Scorecards are auto-extracted and rendered as compact
76
- * widgets inside each collection's card on the home page.
77
- *
78
- * This eliminates the need to duplicate definitions across different locations.
79
- */
80
- export interface InsightsPluginConfig {
81
- /**
82
- * Insight definitions keyed by placement.
83
- *
84
- * - `home`: Rendered at the top of the home page via `home.children.start`.
85
- * - `collections.<slug>`: Rendered inline in that collection's list view
86
- * and auto-extracted as compact scorecards on the home card.
87
- */
88
- insights: {
89
- home?: InsightDefinition[];
90
- collections?: Record<string, InsightDefinition[]>;
91
- };
92
-
93
- /** Optional cache TTL in milliseconds (default: 60_000) */
94
- cacheTTL?: number;
95
- }
@@ -1,5 +0,0 @@
1
- // ── Insights engine types ────────────────────────────────────────────
2
- export * from "./engine";
3
-
4
- // ── Widget data & scorecard types ────────────────────────────────────
5
- export * from "./widgets";
@@ -1,66 +0,0 @@
1
- /**
2
- * Tabular data types used by insight widgets.
3
- */
4
-
5
- /** A single row of data as key-value pairs. */
6
- export type DataRow = Record<string, string | number | boolean | null>;
7
-
8
- /**
9
- * Formatting options for scorecard numbers.
10
- * Uses Intl.NumberFormat standard.
11
- */
12
- export interface ScorecardFormat {
13
- /**
14
- * The style of formatting.
15
- * - `decimal`: 1,234.5
16
- * - `currency`: $1,234.50
17
- * - `percent`: 12.5%
18
- */
19
- style: "decimal" | "currency" | "percent";
20
-
21
- /**
22
- * How to display the number.
23
- * - `standard`: 1,234,567 (default)
24
- * - `compact`: 1.2M
25
- */
26
- notation?: "standard" | "compact";
27
-
28
- /** Required if style is 'currency' (e.g., "USD", "EUR") */
29
- currency?: string;
30
-
31
- /** Number of decimal places to show */
32
- decimals?: number;
33
-
34
- /** If true, adds a '+' sign for positive numbers (e.g., +12.5%) */
35
- showSign?: boolean;
36
- }
37
-
38
- /**
39
- * Scorecard widget configuration — field mapping + formatting.
40
- */
41
- export interface ScorecardConfig {
42
- /** Main value configuration */
43
- value: {
44
- /** The column name from the query result for the main value */
45
- field: string;
46
- /** How to format this number */
47
- format?: ScorecardFormat;
48
- };
49
- /** Comparison value configuration (optional) */
50
- comparison?: {
51
- /** The column name from the query result for the comparison value */
52
- field: string;
53
- /** How to format this number */
54
- format?: ScorecardFormat;
55
- /**
56
- * Determines the color (green/red) based on the value.
57
- * - `increase_is_good`: Positive = green, negative = red.
58
- * - `decrease_is_good`: Positive = red, negative = green.
59
- */
60
- intent: "increase_is_good" | "decrease_is_good";
61
- };
62
- /** Optional icon key (e.g., "shopping_cart", "users") — resolved via getIcon */
63
- icon?: string;
64
- /** Optional date range text (e.g., "Last 30 days") */
65
- dateRange?: string;
66
- }
@@ -1,129 +0,0 @@
1
- import React from "react";
2
- import type { RebasePlugin, SlotContribution } from "@rebasepro/cms-types";
3
- import type { InsightsPluginConfig } from "./types";
4
- import { InsightsProvider } from "./engine/InsightsProvider";
5
- import { HomeCardInsightSlot } from "./components/HomeCardInsightSlot";
6
- import { HomeInsightsSlot } from "./components/HomeInsightsSlot";
7
- import { CollectionInsightsInline } from "./components/CollectionInsightsInline";
8
-
9
- /**
10
- * Creates the Insights plugin for Rebase.
11
- *
12
- * This plugin injects scorecard widgets into key UI locations:
13
- * - **Home page header**: KPI overview via `home.children.start` slot
14
- * - **Collection list view**: Scorecards inline (below title, above list) via `collection.widgets` slot
15
- * - **Home page cards**: Compact scorecard metrics auto-extracted from collection insights via `home.card.widget` slot
16
- *
17
- * Collection-level insights (`collections.<slug>`) are the single source of truth:
18
- * scorecards render in the collection list view and are automatically extracted
19
- * to show as compact widgets on the corresponding home page card.
20
- *
21
- * Each insight owns its own `data()` callback — use the Rebase client SDK,
22
- * call a custom function, or hit any external API. Full flexibility, zero new endpoints.
23
- *
24
- * @example
25
- * ```typescript
26
- * import { useInsightsPlugin } from "@rebasepro/plugin-insights";
27
- *
28
- * const insightsPlugin = useInsightsPlugin({
29
- * cacheTTL: 120_000,
30
- * insights: {
31
- * home: [
32
- * { id: "revenue", title: "Revenue", data: async () => ..., scorecard: { ... } },
33
- * ],
34
- * collections: {
35
- * orders: [
36
- * { id: "total", title: "Total Orders", data: async () => ..., scorecard: { ... } },
37
- * ],
38
- * },
39
- * },
40
- * });
41
- * ```
42
- */
43
- export function useInsightsPlugin(config: InsightsPluginConfig): RebasePlugin {
44
- const { insights, cacheTTL } = config;
45
-
46
- return React.useMemo(() => {
47
- const slots: SlotContribution[] = [];
48
-
49
- // ── Home page insights ────────────────────────────────────────────
50
- if (insights.home && insights.home.length > 0) {
51
- const homeInsights = insights.home;
52
- slots.push({
53
- slot: "home.children.start" as const,
54
- Component: (props: Record<string, unknown>) => (
55
- <HomeInsightsSlot
56
- {...props}
57
- insights={homeInsights}
58
- />
59
- ),
60
- order: 10
61
- });
62
- }
63
-
64
- // ── Per-collection insights ───────────────────────────────────────
65
- // A single `collections.<slug>` definition serves two slots:
66
- // 1. collection.widgets → inline scorecards in the list view
67
- // 2. home.card.widget → compact scorecards on the home card
68
- if (insights.collections) {
69
- for (const [slug, defs] of Object.entries(insights.collections)) {
70
- if (defs.length === 0) continue;
71
- const collectionInsights = defs;
72
-
73
- // 1. Inline in collection list view
74
- slots.push({
75
- slot: "collection.widgets" as const,
76
- Component: (props: Record<string, unknown>) => {
77
- const path = props.path as string;
78
- const collectionSlug = path?.split("/").filter(Boolean).pop() ?? "";
79
- if (collectionSlug !== slug) return null;
80
-
81
- // Skip relation-scoped views (e.g. a single product's Orders
82
- // tab). These aggregations are collection-wide — `InsightContext`
83
- // carries no parent entity id, so a definition cannot narrow to
84
- // the parent — and rendering "Revenue $36.2K" above one product's
85
- // two orders reads as a figure for those orders.
86
- const parentEntityIds = props.parentEntityIds as string[] | undefined;
87
- if (parentEntityIds && parentEntityIds.length > 0) return null;
88
-
89
- return (
90
- <CollectionInsightsInline
91
- {...props as { path: string; collection: unknown; parentCollectionSlugs: string[], parentEntityIds: string[] }}
92
- insights={collectionInsights}
93
- />
94
- );
95
- },
96
- order: 10
97
- });
98
-
99
- // 2. Auto-extract scorecards for home page card
100
- slots.push({
101
- slot: "home.card.widget" as const,
102
- Component: (props: Record<string, unknown>) => {
103
- const cardSlug = props.slug as string;
104
- if (cardSlug !== slug) return null;
105
- return (
106
- <HomeCardInsightSlot
107
- {...props as { slug: string; collection: unknown; context: unknown }}
108
- insights={collectionInsights}
109
- />
110
- );
111
- },
112
- order: 10
113
- });
114
- }
115
- }
116
-
117
- return {
118
- key: "plugin-insights",
119
- slots,
120
- providers: [
121
- {
122
- scope: "root" as const,
123
- Component: InsightsProvider as React.ComponentType<React.PropsWithChildren<Record<string, unknown>>>,
124
- props: { cacheTTL }
125
- }
126
- ]
127
- };
128
- }, [insights, cacheTTL]);
129
- }