# Batchtastic — Changelog

---

## v4.15.0 — May 6, 2026
**Invoice Import — AI powered, SKU matching, supplier scoping**

### Invoice Import — Entry Point
- `+ Add Order` now shows a choice modal: **Import Invoice / Photo** | **Add Manually**
- Add Manually fires the existing PO form unchanged
- Import Invoice opens the new three-state import modal

### Invoice Import — AI Extraction (Gemini)
- PDF.js extracts raw text client-side (free, no server)
- Firebase AI Logic (Gemini 2.5 Flash-Lite) reads the text and returns structured JSON
- Works on any supplier invoice format — Bambu Lab, Amazon, SUNLU, others
- Dynamic import of `firebase-ai.js` — if Gemini unavailable, falls back to regex parser silently
- Gemini prompt extracts: supplier, invoice number, date, shipping, tax, total, items with description/SKU/qty/unit/unitCost
- Regex parser retained as fallback for Bambu Lab structured PDFs

### Invoice Import — JSON Upload
- Accepts `.json` files directly — upload AI-generated JSON without Gemini
- `normaliseImportJson()` handles field name variations across different AI tools
- Template download link in dropzone — generates `batchtastic-invoice-template.json`
- Drag and drop supported on the dropzone

### Invoice Import — Review Screen
- Three-state modal: Upload → Processing → Review
- Meta strip: Supplier dropdown, Date, Invoice #, Total
- Six-column table: Invoice Description | Match to Material | Qty | Unit | Unit Cost | Status
- Supplier dropdown fuzzy-matched against known suppliers (substring both directions)
- Qty auto-converts when unit changes within same family (kg → g = ×1000)
- Exclude toggle (×) per row — strikes through row, shows ↩ to restore
- Summary subtitle updates live as items are excluded
- Start Over resets to upload state

### Invoice Import — Material Matching
- **SKU prefix match** (new, highest priority) — splits SKU on `-`, counts matching leading segments. Handles suffix variants (`-SPL` vs `-SPLFREE` vs `-US`) gracefully. 80%+ prefix match = ✅ Matched
- **Supplier-scoped fuzzy** — if SKU not found, searches only materials from that supplier first. Lower confidence threshold (0.35 vs 0.45) since supplier context reduces ambiguity
- **Full inventory fuzzy** — fallback if nothing found in supplier pool
- Variant segment extraction — matches on text after last `/` for cleaner color matching
- Confidence badges: ✅ Matched (green), ⚠ Review (amber), ➕ New (blue), Excluded (grey)

### Invoice Import — Apply to PO
- Closes import modal, opens standard PO form pre-filled
- Supplier chip populated via fuzzy match
- Date, invoice number, shipping pre-filled
- All non-excluded line items added as PO line items
- Existing materials linked by ID; unmatched items staged as `_pendingNew`
- Snapshot taken after pre-fill so dirty-check works correctly

### Firebase & Security
- Firebase SDK bumped from 11.6.1 → 11.8.0 (required for `firebase-ai.js`)
- Firebase App Check registered with reCAPTCHA v3
- reCAPTCHA script added to `index.html`
- Firebase AI Logic enabled with Gemini Developer API (free tier)

---

## v4.14.0 — May 4, 2026
**Contextual stat cards, sidebar sticky, product margin column, QOL improvements**

### Stat Cards — Context Awareness
- Materials stat cards update when a category filter is active:
  - Card 1: category name + filtered count / sub "In this category"
  - Card 2: Low Stock filtered to that category
  - Card 3: Inventory Value filtered / sub "[Category] stock value"
  - Card 4: switches from Categories → Suppliers (distinct suppliers in that category)
- Products stat cards update when a category filter is active:
  - Card 1: category name + filtered count
  - Card 2: Low Stock filtered to that category
  - Card 3: Catalog Value filtered to that category
  - Card 4: switches from Categories → Avg Sale Price (average MSRP, priced products only)

### Products — Retail Margin Column
- New `Retail Margin` column: shows `86% · $13.00` (margin % + profit per unit)
- Colour coded: green ≥40%, amber ≥20%, red below
- Omits dollar amount if unit cost is 0 to avoid misleading values
- Sortable, available in column customiser and CSV export
- Added to default visible columns between MSRP and SKU
- Product detail drawer margin lines updated to same format (retail + wholesale)
- Wholesale shows `—` when not set

### Layout — Sidebar Fixed
- Sidebar no longer scrolls with main content
- `app-shell` bounded to `height: 100vh; overflow: hidden`
- Only `.main-content` scrolls
- Mobile layout reset correctly to natural flow

### Products Table
- Primary column capped at `max-width: 280px; width: 25%` matching materials table
- Overflow ellipsis on long product names

### Date Format Fixes
- `lastOrdered` column now respects global date format setting (was showing raw ISO string)
- Production run due dates now use `formatDisplayDate()` — respects `appSettings.dateFormat`

### Sale Stock Management Fixes
- Edit sale path now handles all stock commitment transitions (was doing nothing on edit)
- Cancel dialog return-to-stock no longer silently skips products missing from local array
- `loadProductsData()` called after any sale save or cancel to keep local array fresh

---

## v4.13.0 — May 4, 2026
**Purchase Orders module, picker redesign, history integration**

### Purchase Orders — Picker Redesign
- Removed QTY and UNIT from picker — selection only, configuration on PO form
- Removed `+ New` toggle and quick-add row
- Added `+ New Material` green footer button with inline-editable staging rows
- Staging rows use same 3-column grid as list (Category | Item | ×)
- Category picker uses portal dropdown to avoid overflow clipping
- Circle `+` buttons, horizontal separator bars between all picker zones
- New materials get full master unit list on PO form line item

### Purchase Orders — Save & Validation
- Blocks save: QTY = 0 (red input highlight), missing unit on new materials
- New materials save with correct `materialSource: "sourced"` (was "Supplier")
- Category fields fully populated on PO-created materials — fixes edit errors
- Defensive strip of `_pendingNew` / `_pendingData` before Firestore write

### Purchase Orders — History & UX
- `PO_CREATED` / `PO_UPDATED` logged with PO number, supplier, item count, total
- `MATERIAL_CREATED` logged for each new material created via PO
- PO history entries are clickable links → navigates to PO detail drawer
- Snapshot-based dirty detection on cancel — no false "unsaved changes" warnings
- `formatUnit()` applied in detail drawer (was showing raw keys like `weight.grams`)
- Detail drawer redesigned: 2-column info grid, bold "Order Items" heading, IMD-inspired layout

### Materials
- Edit drawer normalises legacy `materialSource: "Supplier"` → `"sourced"`

---

## v4.12.0 — April 26, 2026
**Sales stat blocks, nav memory, bulk edit layout, user notes**

- Stat blocks on sales tables
- Nav memory — returns to last active sub-filter on re-visit
- Bulk edit layout improvements
- User notes on sale records

---

## v4.11.0 — April 28, 2026
**Firebase Storage, invoice system overhaul, sale drawer ⋯ menu redesign**

### Firebase Storage
- Upgraded to Blaze plan — Firebase Storage enabled
- PDFs stored at `users/{uid}/invoices/INV-XXXX.pdf`, auto-deleted on sale delete
- Security rules match Firestore `users/{uid}/...` pattern

### Invoice System Overhaul
- Invoices open in browser (new tab) instead of downloading
- `invoiceUrl`, `invoiceGeneratedAt`, `invoiceStale` fields on sale docs
- Sale modal footer contextual: Generate / View ↗ / ⚠ Regenerate
- Fallback to local download if Storage upload fails

### Sale Drawer ⋯ Menu Redesign
- Full contextual menu: Edit / Edit Channel / Create Invoice / View Invoice / Regenerate / Delete
- Edit Channel uses app-style modal replacing browser `prompt()`

### Invoice PDF Quality
- html2canvas scale 1.75, JPEG 0.95 — reduced from ~12MB to ~143KB

---

## v4.10.0 — April 28, 2026
**Invoice PDF — html2canvas renderer, logo, accent color, print-ready layout**

- Replaced jsPDF text-drawing with html2canvas template capture
- Letter size (8.5×11), pixel-accurate layout
- Logo (base64, Firestore), accent color, print-legible label text

---

## v4.9.0 — April 26, 2026
**Inventory system, committed products report, cancel order dialog**

- Product stock committed on Placed, deducted on Fulfilled, released on Cancelled
- Cancel Order dialog: per-item return qty, live preview, partial returns
- Sale delete blocked unless Cancelled; edit disabled on Cancelled orders
- Committed Products report under Tools → Reports with ↺ Recalculate
- Default tax rate in Settings

---

## v4.8.0 — April 25, 2026
**Sales module — orders, modal, drawer, shipping & tracking, customer quick-add**

- Sales navigation: All Sales / Retail / Wholesale / Customers
- Full Add Sale modal with product picker, shipping, channel, discount/tax/fees
- Sale detail drawer: Details / Profit / Shipping tabs
- Shipping tracking with clickable carrier links
- Customer quick-add inline form

---

## v4.7.1 — April 23, 2026
**Email/password auth, beta signup, Users page, support mode**

- Email + password auth alongside Google
- Beta access code validation, signup attempt logging
- Users page 3-tab redesign; Support Mode with amber banner

---

## v4.7.0 — April 21, 2026
**Customers module, committed stock, production tab, UI standards**

- Full customer management (CUS-001 numbering)
- Committed Materials complete with writeBatch
- Production tab in product drawer
- UI standards: back buttons, sortable headers, save loading states

---

## v4.6.0 — April 19, 2026
**Production archive, run lifecycle guards**

- Archive tab for completed/cancelled runs
- Cancel Run blocked if batches made

---

## v4.5.0 — April 18, 2026
**Production — run lifecycle, tab strip**

- Start / Complete / Cancel / Move Back actions
- Tab strip: All · Planned · In Progress · Completed · Cancelled

---

## v4.4.0 — April 18, 2026
**Production runs, history grouping, stock precision**

- Run detail modal with split-panel BOM view
- History grouped by batch number
- `roundQty()` + precision cleanup

---

## v4.3.0 — April 14, 2026
**Production runs foundation, product stock updates, UI standards**

---

## v4.2.0 — April 2026
**Product & material detail drawer redesign**

---

## v3.9.0 — April 2026
**Restock cost tracking, Tools section, Cost Calculator**

---

## v3.8.0 — April 2026
**User management, security**

---

## v3.7.0 — April 2026
**History undo, Manage page**

---

## v3.6.0 — April 2026
**Products module complete**

---

## v3.5.0 — April 2026
**Products table, archived view, alerts**

---

## v3.4.0 — April 2026
**Material source types, full unit system, EAN/UPC**

---

## v3.3.0 — April 2026
**History, single material delete, product categories**

---

## v3.2.0 — April 2026
**Authentication and deployment — batchtastic.com**

---

## v3.1.0 — March 2026
**Core Materials (Phase 1)**

- Add, edit, duplicate, archive materials
- Stock update with reason tracking
- CSV import/export, categories, suppliers, brands
- Customizable column layouts, full activity history
