npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bluecircuit/offer-calculator

v2.0.0

Published

CMS-driven React component for device offer calculation with multiplicative cascading discounts

Readme

React Offer Calculator Component

A reusable, CMS-driven React component for calculating device offers with multiplicative cascading discounts.

Features

  • CMS-Driven: All configuration (prices, defects, conditions) loaded from CMS
  • Multiplicative Cascading: Order-independent discount calculation
  • Minimum Price Enforcement: Configurable floor price (default: $1.00)
  • TypeScript: Fully typed for type safety
  • Accessible: ARIA support, keyboard navigation, screen reader friendly
  • Server-Side Rendering: Next.js App Router compatible
  • Tested: 50+ unit tests covering all edge cases

Quick Start

Installation

# Install dependencies (if using standalone)
npm install react react-dom next

# Or copy the src/ directory into your Next.js project

Basic Usage

import { OfferCalculator } from '@/components/calculator/OfferCalculator';
import { fetchCalculatorConfig } from '@/lib/cms/fetchCalculatorConfig';

export default async function CalculatorPage() {
  // Fetch configuration from CMS
  const config = await fetchCalculatorConfig('7885');

  return <OfferCalculator config={config} />;
}

Project Structure

src/
├── lib/
│   ├── calculator/
│   │   ├── types.ts              # TypeScript interfaces
│   │   ├── pricing.ts            # Core calculation logic
│   │   ├── validation.ts         # Config validation
│   │   └── hooks.ts              # React hooks
│   └── cms/
│       └── fetchCalculatorConfig.ts  # CMS data fetcher
├── components/
│   └── calculator/
│       ├── OfferCalculator.tsx   # Main component
│       ├── ConditionTabs.tsx     # Condition selector
│       ├── DefectCheckbox.tsx    # Defect checkbox
│       ├── PriceDisplay.tsx      # Price display
│       └── calculator.module.css # Styles
└── app/
    └── calculator/
        ├── page.tsx              # Server component
        └── loading.tsx           # Loading state

CMS Data Contract

API Endpoint

GET /api/calculator/config?deviceId=7885

Response: CalculatorConfig

Data Structure

interface CalculatorConfig {
  basePrice: number;              // e.g., 230.00
  currency: string;               // e.g., "USD"
  defects: DefectAdjustment[];    // List of selectable defects
  conditions: ConditionTier[];    // Condition tiers
  device: DeviceInfo;             // Device metadata
  minimumOffer: number;           // Minimum floor (e.g., 1.00)
}

interface DefectAdjustment {
  id: string;                     // e.g., "check1"
  label: string;                  // e.g., "Motherboard issues"
  percent: number;                // 0-100 (e.g., 60 = 60% discount)
  description?: string;           // Tooltip text
  category?: string;              // Grouping (e.g., "hardware")
}

interface ConditionTier {
  id: string;                     // e.g., "flawless"
  label: string;                  // e.g., "Flawless"
  percent: number;                // e.g., 100 (CMS value)
  multiplier: number;             // Computed: percent / 100
  description: string;            // Condition description
  isDefault?: boolean;            // Mark default tier
}

Example CMS Response

{
  "basePrice": 230.00,
  "currency": "USD",
  "defects": [
    {
      "id": "check1",
      "label": "Motherboard issues",
      "percent": 60,
      "description": "Select if device has defective MB...",
      "category": "critical"
    }
  ],
  "conditions": [
    {
      "id": "flawless",
      "label": "Flawless",
      "percent": 100,
      "multiplier": 1.0,
      "description": "Like New, no visible signs of previous usage.",
      "isDefault": true
    }
  ],
  "device": {
    "id": "7885",
    "model": "Dell G15 5510",
    "type": "laptop"
  },
  "minimumOffer": 1.00
}

Calculation Algorithm

How It Works

  1. Apply Condition Multiplier

    price = basePrice * conditionMultiplier
  2. Sort Defects by Severity (DESC)

    sorted = [60%, 45%, 15%]
  3. Apply Each Defect Multiplicatively

    price = price * (1 - percent/100)
  4. Round to 2 Decimals

    price = Math.round(price * 100) / 100
  5. Enforce Minimum

    finalPrice = Math.max(minimumOffer, price)

Example Calculation

Base Price: $230.00
Condition: Flawless (1.0x)
Defects: Motherboard (60%), Screen (45%)

Step 1: Apply condition
  $230.00 * 1.0 = $230.00

Step 2: Sort defects
  [60%, 45%]

Step 3: Apply defects
  $230.00 * (1 - 0.60) = $230.00 * 0.40 = $92.00
  $92.00 * (1 - 0.45) = $92.00 * 0.55 = $50.60

Step 4: Round
  $50.60

Step 5: Check minimum
  max($1.00, $50.60) = $50.60

Final Price: $50.60

Component Props

<OfferCalculator>

interface OfferCalculatorProps {
  config: CalculatorConfig;       // Required: CMS configuration
  showBreakdown?: boolean;        // Show detailed breakdown
  className?: string;             // Additional CSS classes
  formFieldPrefix?: string;       // Prefix for hidden form inputs
}

Example Usage

<OfferCalculator
  config={config}
  showBreakdown={true}
  className="my-custom-class"
  formFieldPrefix="offer"
/>

Customization

Styling

Option 1: Override CSS Module Classes

import styles from './custom-calculator.module.css';

<OfferCalculator config={config} className={styles.customCalculator} />

Option 2: Global CSS

/* Override specific elements */
.condition-tabs__tab {
  background: #your-color;
  border-radius: 12px;
}

.price-display__main {
  background: linear-gradient(135deg, #your-gradient);
}

Option 3: Inline Styles

<div style={{ maxWidth: '600px', margin: '0 auto' }}>
  <OfferCalculator config={config} />
</div>

Using with Different CMS

Update src/lib/cms/fetchCalculatorConfig.ts:

export async function fetchCalculatorConfig(deviceId: string) {
  // Replace with your CMS API endpoint
  const response = await fetch(`https://your-cms.com/api/devices/${deviceId}`);
  const rawData = await response.json();

  // Map your CMS data to CalculatorConfig
  const config = normalizeConfig({
    basePrice: rawData.price,
    currency: rawData.currency || 'USD',
    defects: rawData.defects_list,
    conditions: rawData.condition_tiers,
    device: rawData.device_info,
    minimumOffer: rawData.min_offer || 1.0,
  });

  return config;
}

Environment Variables

# .env.local

# API endpoint for calculator configuration
CALCULATOR_API_URL=https://your-cms.com/api/calculator/config

# Use mock data (for development)
USE_MOCK_CALCULATOR_DATA=true

Testing

Run Unit Tests

# Using Vitest
npm test

# Watch mode
npm test -- --watch

# Coverage
npm test -- --coverage

Test Coverage

  • ✅ 36 pricing algorithm tests
  • ✅ Minimum price enforcement
  • ✅ Order independence
  • ✅ CMS validation
  • ✅ Decimal precision
  • ✅ Real-world scenarios
  • ✅ Condition multipliers

Accessibility

The calculator is built with accessibility in mind:

  • ARIA Roles: Proper tablist, tab, tabpanel roles
  • Keyboard Navigation: Arrow keys, Tab, Space, Enter
  • Screen Reader Support: Descriptive labels, live regions
  • Focus Management: Logical tab order
  • Color Contrast: WCAG AA compliant

Keyboard Shortcuts

| Key | Action | |-----|--------| | Tab | Navigate between elements | | Arrow Keys | Navigate condition tabs | | Space | Toggle checkbox/radio | | Enter | Activate button |

Hidden Form Inputs

The calculator automatically creates hidden inputs for form submission:

<input type="hidden" name="device_price" value="50.60" />
<input type="hidden" name="gadget_cosmetic_condition" value="flawless" />
<input type="hidden" name="selected_defects" value='["check1","check2"]' />
<input type="hidden" name="device_id" value="7885" />

Access these in your backend:

// Next.js API route
export async function POST(request: Request) {
  const formData = await request.formData();

  const price = formData.get('device_price');
  const condition = formData.get('gadget_cosmetic_condition');
  const defects = JSON.parse(formData.get('selected_defects'));
  const deviceId = formData.get('device_id');

  // Process offer...
}

Caching & Revalidation

Next.js ISR (Incremental Static Regeneration)

// Automatic caching (1 hour)
const config = await fetchCalculatorConfig(deviceId);

On-Demand Revalidation

import { revalidateCalculatorConfig } from '@/lib/cms/fetchCalculatorConfig';

// In webhook or API route
await revalidateCalculatorConfig('7885');

Manual Cache Control

const config = await fetch('/api/calculator/config?deviceId=7885', {
  next: {
    revalidate: 3600,  // Cache for 1 hour
    tags: ['calculator-config-7885'],
  },
});

Troubleshooting

Calculator shows $1.00 for everything

Issue: Base price is invalid or missing

Solution: Check CMS response contains valid basePrice number

console.log('Config:', config);
// Check: config.basePrice > 0

Defects not appearing

Issue: Defects array is empty or invalid

Solution: Validate config.defects has valid items

console.log('Defects:', config.defects);
// Check: Array with id, label, percent

Price doesn't update when selecting defects

Issue: React state not updating

Solution: Check browser console for errors, ensure useOfferCalculator hook is working

Styles not loading

Issue: CSS module not imported

Solution: Ensure calculator.module.css is imported in component

Performance

  • Initial Load: ~50kb gzipped (component + deps)
  • Calculation Time: <5ms for any number of defects
  • Re-renders: Optimized with useMemo and useCallback
  • Bundle Size: Tree-shakeable, no unnecessary dependencies

Browser Support

  • Chrome/Edge: ✅ Latest 2 versions
  • Firefox: ✅ Latest 2 versions
  • Safari: ✅ Latest 2 versions
  • Mobile Safari: ✅ iOS 14+
  • Chrome Mobile: ✅ Latest

License

MIT License - See existing calculator license.

Support

For issues or questions:

  1. Check this README
  2. Review test cases in tests/calculator/pricing.test.ts
  3. Inspect browser console for errors
  4. Check CMS response format

Migration from Vanilla JS

If migrating from the original vanilla JS calculator:

  1. All calculation logic is preserved (identical results)
  2. Same multiplicative cascading algorithm
  3. Same minimum price enforcement
  4. Same defect percentages
  5. Enhanced with TypeScript type safety
  6. React component architecture for reusability

Version History

  • v2.0.0: React component conversion

    • TypeScript rewrite
    • CMS integration
    • Server-side rendering support
    • Comprehensive test suite
  • v1.0.0: Original vanilla JS implementation

    • Multiplicative cascading
    • Minimum price enforcement
    • 36 unit tests