npm package: @nodee.co/insights
Description: Embed Nodee Merchant Intelligence insights into any web application. Works with React and vanilla JS.
Latest version: 1.0.1

# @nodee.co/insights

Embeddable **Merchant Intelligence** dashboard for nodee partners. Display rich analytics and insights — KPIs, trending products, customer segments, competitive pricing, revenue forecasts, and more — inside your own SaaS web application.

Works with **React** and **vanilla JavaScript** (or any framework).

For questions or support, access https://nodee.co

## Installation

```bash
npm install @nodee.co/insights
```

## Quick Start — Vanilla JS

```html
<div id="insights"></div>

<script type="module">
  import { NodeeInsights } from '@nodee.co/insights'

  const insights = new NodeeInsights({
    apiKey: 'your-partner-api-key',
    merchantId: 'merchant-123',
    primaryColor: '#7C3AED',             // optional – defaults to #3B82F6
    fontFamily: "'Poppins', sans-serif", // optional – defaults to Inter
    language: 'en',                      // 'en' | 'pt' | 'es' | 'ca'
  })

  insights.mount(document.getElementById('insights'))
</script>
```

## Quick Start — React

```tsx
import { NodeeInsightsDashboard } from '@nodee.co/insights/react'

function MerchantPage({ merchantId }: { merchantId: string }) {
  return (
    <NodeeInsightsDashboard
      apiKey="your-partner-api-key"
      merchantId={merchantId}
      primaryColor="#7C3AED"
      fontFamily="'Poppins', sans-serif"
      language="en"
    />
  )
}
```

## Authentication

The package authenticates using your **partner API key** sent via the `x-api-key` header. Each request targets a specific merchant through the endpoint pattern:

```
GET /:merchantId/insights/:insight-name
```

| Parameter     | Description                                  |
|---------------|----------------------------------------------|
| `apiKey`      | Your partner API key (required)               |
| `merchantId`  | The merchant whose insights to display (required) |

## Configuration

| Option          | Type                  | Default              | Description                          |
|-----------------|-----------------------|----------------------|--------------------------------------|
| `apiKey`        | `string`              | *required*           | Partner API key                      |
| `merchantId`    | `string`              | *required*           | Merchant ID                          |
| `primaryColor`  | `string`              | `#3B82F6`            | Brand accent color (hex)             |
| `fontFamily`    | `string`              | `Inter`              | Font family for all dashboard text   |
| `language`      | `'en'\|'pt'\|'es'\|'ca'` | `'en'`            | UI language                          |
| `sections`      | `InsightSection[]`    | all 13 sections      | Which sections to show               |
| `timeout`       | `number`              | `10000`              | API request timeout (ms)             |
| `onDataLoaded`  | `(data) => void`      | —                    | Callback after fetch                 |
| `onError`       | `(error) => void`     | —                    | Callback on error                    |

## Available Sections

Pass any subset of these to `sections` to customize which panels appear:

| Section ID                | Description                             |
|---------------------------|-----------------------------------------|
| `kpi`                     | KPI overview (transaction value, daily customers, market share, retention) |
| `topProducts`             | Top trending products with period filter |
| `weeklyPatterns`          | Weekly purchase patterns bar chart       |
| `customerSegments`        | Customer segments with spend and frequency |
| `productsBoughtTogether`  | Products bought together (basket affinity) |
| `competitivePricing`      | Competitive price comparison             |
| `competitorProducts`      | Products competitors offer (you don't)   |
| `uniqueProducts`          | Your unique products (market gaps)       |
| `customerOverlap`         | Customer base overlap with competitors   |
| `revenueForecast`         | Revenue forecast (week, month, quarter)  |
| `shoppingJourney`         | Customer shopping journey (before/after) |
| `loyaltyComparison`       | Customer loyalty vs. competitors         |
| `churnRiskSignals`        | Churn risk signals with recommended actions |

### Example — show only KPIs and forecasts

```tsx
<NodeeInsightsDashboard
  apiKey="key"
  merchantId="m-123"
  sections={['kpi', 'revenueForecast']}
/>
```

## React Hook

For custom rendering, use the data-fetching hook directly:

```tsx
import { useNodeeInsights } from '@nodee.co/insights/react'

function CustomDashboard({ merchantId }: { merchantId: string }) {
  const { data, loading, error, refresh } = useNodeeInsights({
    apiKey: 'your-partner-api-key',
    merchantId,
  })

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error: {error.message}</p>

  return (
    <div>
      {data?.kpi && <h2>Avg Transaction: €{data.kpi.averageTransactionValue.value}</h2>}
      <button onClick={refresh}>Refresh</button>
    </div>
  )
}
```

## Vanilla JS — Advanced

```js
import { NodeeInsights } from '@nodee.co/insights'

const insights = new NodeeInsights({
  apiKey: 'key',
  merchantId: 'm-123',
  sections: ['kpi', 'topProducts', 'churnRiskSignals'],
  onDataLoaded: (data) => console.log('Loaded', data),
  onError: (err) => console.error(err),
})

// Mount
insights.mount(document.getElementById('app'))

// Later: refresh
insights.refresh()

// Tear down
insights.destroy()
```

## Standalone data fetch

Use `fetchInsights` directly if you want full control:

```js
import { fetchInsights } from '@nodee.co/insights'

const data = await fetchInsights({
  apiKey: 'key',
  merchantId: 'm-123',
})

console.log(data.kpi)
console.log(data.revenueForecast?.salesForecast.nextWeek)
```

## Styling

The package injects its own scoped CSS (all classes prefixed with `ni-`). It does not require Tailwind or any other CSS framework. The styles are automatically injected into `<head>` on first use.

Two first-class style overrides are available via config:

- **`primaryColor`** — accent / brand color applied to buttons, icons, progress bars, and highlighted values.
- **`fontFamily`** — font stack applied to all dashboard text. Accepts any valid CSS `font-family` value (e.g. `"'Poppins', sans-serif"`). Defaults to `Inter`.

If you need further customization, you can override the `ni-*` CSS classes in your own stylesheet.

## Languages

Four languages are bundled: English (`en`), Portuguese (`pt`), Spanish (`es`), and Catalan (`ca`).

## TypeScript

Full TypeScript definitions are included. All data interfaces are exported:

```ts
import type { InsightsData, KPIData, TopProductsData, RevenueForecastData } from '@nodee.co/insights'
```

## License

MIT