# Backstock System

The backstock system manages inventory bins, storage locations, categories, events, and reporting for retail stores. Each store has its own isolated backstock database tables.

## Overview

Backstock is a comprehensive inventory management module that allows stores to:
- Track storage bins with categories and locations
- Monitor bin aging to identify stale inventory
- Schedule and manage inventory events (audits, rotations, sales)
- Generate reports and analytics
- Log all activity for accountability

## Navigation

The backstock module is accessible from the admin sidebar under "Backstock" with the following pages:

| Page | Route | Description |
|------|-------|-------------|
| Home | `/backstock` | Main bin management with DataTable |
| Events | `/backstock/events` | Event scheduling and management |
| Notes | `/backstock/notes` | Store-wide notes and reminders |
| Reports | `/backstock/reports` | Analytics dashboard |
| Aging Report | `/backstock/aging` | Visual aging by category |

## Core Concepts

### Bins

A bin is a physical storage container (box, tote, shelf section) that holds inventory items.

**Key Properties:**
- **UUID** - 8-character unique identifier for labeling
- **Name** - Human-readable name (e.g., "Bin #101")
- **Main Category** - Primary classification (e.g., "Women's Tops")
- **Sub-Categories** - Additional categories the bin contains
- **Location** - Where the bin is stored
- **Age Date** - Used to calculate how long inventory has been sitting

**Aging System:**
- Age is calculated from `ageDate` to today
- Color gradient: green (fresh) → yellow → red (stale)
- Age can be reset when inventory is rotated
- Default stale threshold: 90+ days

### Categories

Categories classify what type of merchandise is in a bin.

- Each category has a name and color code
- Colors display as visual indicators in the UI
- Categories cannot be deleted if assigned to bins
- One main category + multiple sub-categories per bin

### Locations

Locations represent where bins are physically stored.

- **On-Site** - In the store (sales floor, back room)
- **Off-Site** - External storage (warehouse, unit)
- Locations cannot be deleted if bins exist there
- Helps track space utilization

### Actions

Every bin change is logged as an action for accountability.

**Action Types:**
| Code | Action | Description |
|------|--------|-------------|
| 0 | Empty | Removed everything from bin |
| 1 | Add | Added items to bin |
| 2 | Remove Some | Partially removed items |
| 3 | Remove All | Removed all of a category |

Actions track: employee, timestamp, category affected, and generate readable descriptions.

### Events

Events are scheduled activities involving bins (audits, sales, rotations).

**Event Features:**
- Create from templates or custom
- Assign bins to events
- Track progress and completion
- Set alerts and reminders
- Add comments/notes

**Event Statuses:**
- Scheduled
- In Progress
- Completed
- Cancelled

### Notes

Store-wide notes for communication and reminders.

- Pinned notes stay at top
- Markdown support for formatting
- Author and timestamp tracking
- Edit history

## User Interface

### Home Page (Bin Management)

The main DataTable provides:
- **Search** - Filter by name, UUID, category, location
- **Quick Filters** - "onsite" / "offsite" keywords
- **Sorting** - Click column headers
- **Selection** - Shift+Click, Ctrl+Click for multi-select
- **Export** - Excel, PDF, Print options
- **Column Visibility** - Show/hide columns

**Row Actions:**
- Click row to open bin details
- Action buttons for edit, log action, reprint, delete

**Toolbar Actions:**
- Add Bin - Create single bin
- Bulk Create - Create multiple bins
- Manage Locations
- Manage Categories

### Bin Details Modal

Shows complete bin information:
- Properties (name, categories, location, age)
- Action history timeline
- Quick action buttons

### Reports Dashboard

Visual analytics including:
- **Summary Stats** - Total bins, on-site/off-site counts, average age
- **Age Distribution** - Horizontal bar chart by age range
- **Category Health** - Health scores based on aging
- **Location Utilization** - Bins per location with averages
- **Stale Inventory** - List of bins 90+ days old
- **Activity Summary** - Actions, top performers, hot categories

### Aging Report

Chart.js horizontal stacked bar chart showing:
- All categories on Y-axis
- Age ranges stacked horizontally
- Color coded by age severity
- Location filtering

## API Reference

Base URL: `/api/{typeNum}/backstock/`

### Bins
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/bins` | List all bins |
| GET | `/bin/:id` | Get single bin |
| POST | `/bin` | Create bin |
| POST | `/bin/:id` | Update bin |
| DELETE | `/bin/:id` | Delete bin |
| POST | `/bulkCreate` | Create multiple bins |

### Categories
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/categories` | List categories |
| POST | `/categories` | Create category |
| POST | `/categories/:id/edit` | Update category |
| POST | `/categories/:id/delete` | Delete category |

### Locations
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/locations` | List locations |
| POST | `/locations` | Create location |
| POST | `/locations/:id/edit` | Update location |
| POST | `/locations/:id/delete` | Delete location |

### Actions
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/actions` | List all actions |
| POST | `/actions` | Log actions to bin |

### Events
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/events` | List events |
| GET | `/events/:id` | Get event details |
| POST | `/events` | Create event |
| POST | `/events/:id` | Update event |
| DELETE | `/events/:id` | Delete event |
| POST | `/events/:id/bins` | Assign bins to event |
| POST | `/events/:id/progress` | Update event progress |

### Notes
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/notes` | List notes |
| POST | `/notes` | Create note |
| POST | `/notes/:id` | Update note |
| DELETE | `/notes/:id` | Delete note |
| POST | `/notes/:id/pin` | Toggle pin status |

### Reports
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/reports/summary` | Summary statistics |
| GET | `/reports/age-distribution` | Age breakdown |
| GET | `/reports/aging` | Aging by category |
| GET | `/reports/categories/health` | Category health scores |
| GET | `/reports/locations/utilization` | Location stats |
| GET | `/reports/stale` | Stale inventory list |
| GET | `/reports/activity/summary` | Activity metrics |
| GET | `/reports/export/:format` | Export data |

## File Structure

```
userfrosting/
├── controllers/Backstock/
│   ├── BackstockController.php    # Page rendering
│   ├── BinController.php          # Bin CRUD API
│   ├── CategoriesController.php   # Category CRUD API
│   ├── LocationsController.php    # Location CRUD API
│   ├── ActionsController.php      # Action logging API
│   ├── EventController.php        # Event management API
│   ├── NoteController.php         # Notes API
│   └── ReportController.php       # Reports API
│
├── models/Class/Backstock/
│   ├── Backstock.php              # Base class
│   ├── Bin.php                    # Bin model
│   ├── Category.php               # Category model
│   ├── Location.php               # Location model
│   ├── Action.php                 # Action model
│   ├── Event.php                  # Event model
│   ├── EventCategory.php          # Event category model
│   ├── EventProgress.php          # Progress tracking
│   ├── EventAlert.php             # Event alerts
│   ├── EventService.php           # Event business logic
│   ├── Note.php                   # Note model
│   ├── BackstockFactory.php       # Factory/service class
│   ├── BinNamingService.php       # Bin naming utilities
│   └── ReportService.php          # Report generation
│
├── routes/groups/
│   └── backstock.php              # API route definitions
│
└── templates/themes/default/backstock/
    ├── home.html                  # Main bin page
    ├── events.html                # Events page
    ├── notes.html                 # Notes page
    ├── reports.html               # Reports dashboard
    ├── aging.html                 # Aging chart page
    ├── modals/                    # Modal templates
    ├── templates/                 # Handlebars templates
    └── js/                        # Page-specific JavaScript

public_html/css/
└── backstock-reports.css          # Reports page styles
```

## Database Tables

All tables are per-store in the store's database.

| Table | Purpose |
|-------|---------|
| `bsBins` | Storage bins |
| `bsCategories` | Category definitions |
| `bsLocations` | Location definitions |
| `bsActions` | Activity log |
| `bsBin_Cat` | Bin-category junction |
| `bsEvents` | Scheduled events |
| `bsEventCategories` | Event type templates |
| `bsEventBins` | Event-bin assignments |
| `bsEventProgress` | Progress tracking |
| `bsEventAlerts` | Event alerts |
| `bsNotes` | Store notes |

## Permissions

- Requires `uri_backstock` permission
- Requires store group membership
- Store API key required for DELETE operations

## Integration Points

### Workbook Summary
The workbook displays a backstock activity summary showing today's stats.

### Print Service
Bin labels can be printed via the integrated print service using Redis job queues.

### Employee System
Actions are tied to employee IDs for accountability and performance tracking.

## Best Practices

1. **Naming Convention** - Use consistent bin naming (e.g., "Bin #001")
2. **Category Colors** - Choose distinct colors for visual identification
3. **Regular Audits** - Create events to periodically audit bins
4. **Age Management** - Rotate inventory before it becomes stale
5. **Location Organization** - Group related bins by location
6. **Action Logging** - Always log when adding/removing items
