# Product Requirements Document

For technical details and step-by-step execution, see:
- `solution-design.md`
- `implementation-plan.md`

## Validation Checklist

- [x] All required sections are complete
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Problem statement is specific and measurable
- [x] Problem is validated by evidence (not assumptions)
- [x] Context → Problem → Solution flow makes sense
- [x] Every persona has at least one user journey
- [x] All MoSCoW categories addressed (Must/Should/Could/Won't)
- [x] Every feature has testable acceptance criteria
- [x] Every metric has corresponding tracking events
- [x] No feature redundancy (check for duplicates)
- [x] No contradictions between sections
- [x] No low-level implementation details included
- [x] A new team member could understand this PRD

---

## Product Overview

### Vision
Transform BuyerKiosk's JavaScript infrastructure from manually-loaded script files into a modern, bundled module system that enables rapid adoption of third-party libraries (like Syncfusion) and improves developer productivity while maintaining full backward compatibility with existing code.

### Problem Statement
The BuyerKiosk codebase currently has **no JavaScript build system**:

1. **No package management** - No `package.json` and no npm dependency workflow. Third-party libraries are manually downloaded and version-tracked only in comments or not at all. Updating a library requires manual download and file replacement.

2. **No bundling** - 1,025+ JavaScript files (32 MB total) served as individual requests. The workspace footer alone loads 57+ separate `<script>` tags sequentially, blocking page rendering.

3. **No module system** - JavaScript files attach to `window` object for cross-file communication. No `import`/`export` statements. Dependency order is managed by explicit script tag ordering in templates.

4. **No minification for JS** - All JavaScript served unminified. Only CSS is minified via the `conductor` CLI tool.

5. **Cannot adopt modern libraries** - Libraries like Syncfusion (required for Floor Plan Designer in spec 016) require npm installation and ES module imports. The current infrastructure cannot use them.

**Evidence:**
- Code audit: 66+ individual script tags in workspace templates
- Analysis document confirms no bundler and a manual script-tag workflow
- Spec 016 (Syncfusion Floor Plan Designer) blocked on infrastructure
- jQuery 1.11.2 still in use (2015 version) because upgrading is manual
- Multiple copies of same libraries (jQuery in `/js/` and `/view/common/js/`)

**Consequences of not solving:**
- Cannot implement Floor Plan Designer (spec 016) - critical roadmap feature
- Cannot adopt any npm packages (Syncfusion, modern date libraries, etc.)
- Slow page loads due to 57+ sequential HTTP requests for JS
- Security vulnerabilities in outdated manual library copies
- Developer productivity reduced by lack of modern tooling

### Value Proposition
A Vite-based build infrastructure provides:

1. **Library adoption enablement** - Install any npm package with `npm install` and import it immediately. Unblocks Syncfusion adoption for Floor Plan Designer and Scheduler migration.

2. **Hybrid compatibility** - Existing 1,025+ JS files continue working unchanged. New bundled modules coexist with legacy scripts. Zero forced migration.

3. **Future-proof foundation** - Modern ES modules, tree-shaking, code splitting available when needed. Gradual migration path for legacy code.

4. **Developer experience** - Hot module replacement during development. Automatic dependency resolution. No more manual script ordering.

5. **Performance potential** - When ready, bundle 57 workspace files into 1-2 optimized chunks. ~75% reduction in HTTP requests.

## User Personas

### Primary Persona: Developer (Claude/AI Assistant)
- **Demographics:** AI-assisted development using Claude Code, working on BuyerKiosk features daily, high technical proficiency, operates via CLI and code editors
- **Goals:**
  - Install and use npm packages without manual setup
  - Write modern ES module code with imports/exports
  - Have changes reflected immediately during development
  - Not break existing functionality while adding new features
- **Pain Points:**
  - Cannot use `npm install` for new libraries
  - Must manually manage script load order in templates
  - No way to import third-party ES modules
  - Testing library updates requires manual file replacement

### Secondary Persona: Human Developer (Occasional)
- **Demographics:** Business owner or contract developer, occasional code modifications, moderate technical proficiency
- **Goals:**
  - Understand how to add new JavaScript to the project
  - Deploy changes safely with confidence
  - Not need to learn complex build tooling
- **Pain Points:**
  - Unclear how to add new JS files
  - Deployment process unclear for JS changes
  - No documentation on JS architecture

## User Journey Maps

### Primary User Journey: Adding a New npm Package
1. **Awareness:** Developer needs functionality from a third-party library (e.g., Syncfusion diagram component, date formatting library)
2. **Consideration:** Developer checks if package is available on npm and compatible with ES modules
3. **Adoption:** Developer runs `npm install package-name` in project root
4. **Usage:**
   - Create new JS entry file in the module source directory
   - Write `import { Component } from 'package-name'` (ES module syntax)
   - Use imported functionality
   - Build system bundles and outputs production artifacts to the public dist directory
   - Add Twig helpers to template to load the entry and its CSS dependencies
5. **Retention:** Package.json tracks all dependencies, `npm install` restores them on any machine, updates handled via `npm update`

### Secondary User Journey: Migrating Legacy Code to Modules
1. **Trigger:** Developer identifies legacy JS file that should use modern imports
2. **Planning:** Developer reviews existing global variables and dependencies
3. **Migration:**
   - Create new file in `resources/js/` mirroring functionality
   - Convert `window.` attachments to `export` statements
   - Import dependencies using ES module syntax
   - Optionally expose to `window` for backward compatibility
4. **Testing:** Verify both old and new code paths work
5. **Cleanup:** Eventually remove legacy script tag when all consumers migrated

### Secondary User Journey: Development with Hot Reload
1. **Start:** Developer runs `npm run dev` to start Vite dev server
2. **Development:** Developer edits module source files
3. **Feedback:** Changes apply immediately in the browser via HMR (hot module replacement) without a full page reload
4. **Testing:** Developer verifies functionality
5. **Completion:** Developer runs `npm run build` for production bundle

## Feature Requirements

### Must Have Features

#### Feature 1: npm Package Management
- **User Story:** As a developer, I want to install npm packages so that I can use third-party libraries without manual file management
- **Acceptance Criteria:**
  - [ ] `package.json` exists at project root with project metadata
  - [ ] Running `npm install <package>` adds package to `node_modules/` and `package.json`
  - [ ] `package-lock.json` ensures consistent installs across environments
  - [ ] `node_modules/` is gitignored
  - [ ] Running `npm install` in fresh clone restores all dependencies

#### Feature 2: Vite Build System
- **User Story:** As a developer, I want JavaScript modules bundled automatically so that I can use ES import/export syntax
- **Acceptance Criteria:**
  - [ ] `vite.config.js` configures build process
  - [ ] Module source files are bundled to the public dist directory
  - [ ] Running `npm run build` produces production-ready bundles
  - [ ] Running `npm run dev` starts development server with hot reload
  - [ ] Build manifest (`manifest.json`) generated for PHP asset helper

#### Feature 3: PHP Asset Helper
- **User Story:** As a developer, I want Twig helpers to include bundled JavaScript so that templates can reference built assets correctly
- **Acceptance Criteria:**
  - [ ] `ViteAssets` PHP class reads manifest and generates correct script tags
  - [ ] Twig helpers exist for loading module JS and associated CSS
  - [ ] Development mode serves from Vite dev server (hot reload)
  - [ ] Production mode serves from `public_html/js/dist/` with hashed filenames
  - [ ] CSS imported by JS entries loads without FOUC (flash of unstyled content)

#### Feature 4: Hybrid Loading Compatibility
- **User Story:** As a developer, I want new bundled code to coexist with existing scripts so that I don't have to migrate everything at once
- **Acceptance Criteria:**
  - [ ] Existing script tags in templates continue working unchanged
  - [ ] Bundled modules can access `window` globals from legacy scripts
  - [ ] Legacy scripts can access exports exposed via `window` from bundled modules
  - [ ] No changes required to existing JS files

#### Feature 5: Deployment Integration
- **User Story:** As a developer, I want production deployments to include correct bundled assets without requiring Node.js on the production server
- **Acceptance Criteria:**
  - [ ] Build artifacts in `public_html/js/dist/` are committed to git
  - [ ] `manifest.json` is committed to git and references only existing dist files
  - [ ] Production server serves committed dist assets (no dev server required)
  - [ ] Deployment fails fast if expected dist artifacts are missing

### Should Have Features

#### Feature 6: Multi-Entry Point Support
- **User Story:** As a developer, I want separate bundles for different features so that pages only load the JavaScript they need
- **Acceptance Criteria:**
  - [ ] Multiple entry points can be defined in Vite config
  - [ ] Each entry point produces a separate bundle
  - [ ] Shared code is automatically extracted to common chunks
  - [ ] Twig helper accepts entry point name to load specific bundle

#### Feature 7: Source Maps
- **User Story:** As a developer, I want source maps in development so that I can debug original source code in browser devtools
- **Acceptance Criteria:**
  - [ ] Development builds include source maps
  - [ ] Browser devtools show original file names and line numbers
  - [ ] Production builds exclude source maps (or generate separately)

### Could Have Features

#### Feature 8: CSS Processing via Vite
- **User Story:** As a developer, I want to optionally process CSS through Vite so that I can use CSS imports in JavaScript modules
- **Acceptance Criteria:**
  - [ ] CSS imported in JS is extracted and bundled
  - [ ] Existing `conductor` CSS build continues working
  - [ ] Developer can choose which CSS system to use per feature

#### Feature 9: TypeScript Support
- **User Story:** As a developer, I want to optionally write TypeScript so that I get type checking during development
- **Acceptance Criteria:**
  - [ ] `.ts` files compile to JavaScript
  - [ ] Type errors reported during build
  - [ ] Existing `.js` files continue working

### Won't Have (This Phase)

- **Full legacy migration** - Not converting existing 1,025+ JS files to ES modules
- **Replacing conductor CSS** - Existing CSS build system remains unchanged
- **Server-side rendering** - This is a client-side bundling solution only
- **Webpack/Rollup alternatives** - Vite is the selected tool, not evaluating others
- **Bundle size optimization** - Focus is on enabling, not optimizing (premature optimization)
- **Testing framework integration** - JS testing infrastructure is separate concern

## Detailed Feature Specifications

### Feature: PHP Asset Helper (Most Complex)
**Description:** A PHP class and Twig extension that reads the Vite build manifest and generates appropriate HTML script/style tags for both development and production environments.

**User Flow:**
1. Developer adds Twig helpers for a module entry (JS + CSS) to a template using the documented conventions
2. System checks whether development mode is explicitly enabled (env flag) and dev server is reachable
3. If dev mode: Outputs module script tags pointing at the dev server (HMR enabled)
4. If production: Reads `manifest.json`, finds hashed filenames, outputs tags pointing at `/js/dist/...`
5. If entry has CSS imports: CSS loads early (in `<head>`) to avoid FOUC

**Business Rules:**
- Rule 1: Development mode must be explicitly enabled via environment configuration
- Rule 2: Development mode should be resilient (if dev server unavailable, fall back to production assets)
- Rule 3: Production mode always uses the manifest and never attempts to use the dev server
- Rule 4: When manifest entry not found, throw clear error with build instructions
- Rule 5: All script tags use `type="module"` for ES module support
- Rule 6: CSS dependencies of JS entry are automatically included

**Edge Cases:**
- Scenario 1: Manifest file doesn't exist → Error: "Run 'npm run build' first"
- Scenario 2: Entry point not in manifest → Error: "Entry 'X' not found in manifest"
- Scenario 3: Dev server not responding → Fallback to production mode
- Scenario 4: Multiple templates request same entry → Output once (deduplicate)

## Success Metrics

### Key Performance Indicators

- **Adoption:** 100% of new Syncfusion features use bundled modules (Floor Plan, future Scheduler)
- **Engagement:** Every deployment includes up-to-date committed dist artifacts that match the PHP/templates in that release
- **Quality:** Zero regressions in existing JavaScript functionality after implementation
- **Business Impact:** Unblocks spec 016 (Syncfusion Floor Plan Designer) implementation

### Tracking Requirements

| Event | Properties | Purpose |
|-------|------------|---------|
| Build Execution | Success/failure, duration, entry point count | Monitor build reliability |
| Dev Server Usage | Session duration, hot reload count | Measure developer adoption |
| Bundle Size | Total bytes, per-entry bytes | Track growth over time |
| Legacy Script Count | Number of non-bundled script tags | Track migration progress |

---

## Constraints and Assumptions

### Constraints
- **Zero breaking changes** - All existing JavaScript must continue working unchanged
- **PHP 8.x compatibility** - PHP helper must work with current PHP version
- **No framework plugins** - Cannot use Laravel Vite plugin or similar (Slim 2.6 project)
- **Deployment simplicity** - Production deployments should not require npm/Node.js on the server
- **No FOUC** - CSS for Vite entries must be loaded in a way that avoids flash of unstyled content

### Assumptions
- Node.js 18+ available on development environments (and any build environment)
- Developers can run npm commands locally
- Production deployments use committed build artifacts
- Vite 5.x is stable and suitable for production use
- ES modules are supported by target browsers (modern Chrome/Firefox; tablets kept up-to-date)
- Existing security headers/CSP do not block ES module scripts; development mode may require HTTPS dev-server URLs if pages enforce `upgrade-insecure-requests`

## Risks and Mitigations

| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Node.js not on production server | High | Low | Verify with hosting provider; build locally if needed |
| Legacy script breaks after implementation | High | Low | Extensive testing; hybrid loading prevents interference |
| Vite configuration complexity | Medium | Medium | Start minimal; add features incrementally |
| Developer learning curve | Low | Medium | Document usage patterns; provide examples |
| Build time slows deployment | Low | Low | Vite is fast (~1-2 sec builds); cache node_modules |

## Open Questions

- [x] Deployment model - Decided: Commit build artifacts to git (no Node.js required on production server)
- [x] TypeScript initially - Decided: No, defer to Could Have
- [x] Asset injection strategy - Decided: CSS in `<head>` to prevent FOUC; JS loaded per template conventions
- [x] Syncfusion licensing storage - Decided: Provide license via `.env` (acceptable for this model)

---

## Glossary

- **HMR (Hot Module Replacement):** Development feature where code changes apply in the browser without a full page reload.
- **FOUC (Flash of Unstyled Content):** A brief moment where the page renders unstyled before CSS loads; avoided by loading CSS in `<head>`.

---

## Supporting Research

### Competitive Analysis
Modern PHP projects universally use npm + bundlers:
- **Laravel**: Built-in Vite integration since Laravel 9
- **Symfony**: Webpack Encore or Vite through community packages
- **WordPress**: Block editor uses npm + webpack
- **Drupal**: Asset libraries support npm packages

BuyerKiosk is behind industry standard by not having any JS build system.

### User Research
Analysis document (`docs/analysis/syncfusion-integration-analysis.md`) identifies:
- Floor Plan Designer blocked on npm/Vite infrastructure
- 4 hours estimated for infrastructure setup
- Hybrid loading strategy recommended
- Vite selected over Webpack for simplicity

### Market Data
- Vite: 60k+ GitHub stars, used by Vue, Nuxt, SvelteKit
- npm: 2M+ packages, industry standard for JS dependencies
- ES Modules: 97% browser support (caniuse.com)
- Build tools: Essential for any modern web application
