# Specification: 006-backstock-bin-crud-actions

## Status

| Field | Value |
|-------|-------|
| **Created** | 2026-02-07 |
| **Current Phase** | ✅ Specification Complete → Ready for Implementation |
| **Last Updated** | 2026-02-07 |

## Documents

| Document | Status | Notes |
|----------|--------|-------|
| product-requirements.md | ✅ completed | Completed 2026-02-07 |
| solution-design.md | ✅ completed | Reviewed 2026-02-07, all issues resolved |
| implementation-plan.md | ✅ completed | 10 phases, 150+ tasks defined |

**Status values**: `pending` | `in_progress` | `completed` | `skipped`

## Decisions Log

| Date | Decision | Rationale |
|------|----------|-----------|
| 2026-02-07 | Start with PRD | User chose full specification flow despite API being ready |
| 2026-02-07 | ADR-1: mobile_scanner | Barcode scanning package - well-maintained, 1D/2D support |
| 2026-02-07 | ADR-2: Extend models | Add to existing backstock_models.dart rather than new file |
| 2026-02-07 | ADR-3: Bottom sheets | Use bottom sheets for pickers (consistent with app UX) |
| 2026-02-07 | ADR-4: Session cache | Cache categories/locations/action types per session |
| 2026-02-07 | ADR-5: Navigate to detail | Navigate to bin detail after successful create |

## SDD Review (Codex) - 2026-02-07

### Key Findings Addressed

| Finding | Severity | Resolution |
|---------|----------|------------|
| Notifier vs AsyncNotifier conflict | Blocker | Updated to use `AsyncNotifier` per project convention |
| Action types inconsistency (6 vs 5) | Blocker | Added canonical mapping table with IDs 0-5 (ID 4 auto-only) |
| Generate Name feature under-specified | Blocker | Added full UI flow, provider method, create/edit integration |
| Hidden bins UX incomplete | Important | Added toggle, visual indicators, reactivation flow |
| Barcode scanner UI incomplete | Important | Added flash toggle, permission prompts, fallback link |
| Edit form "Save disabled" not specified | Important | Added dirty checking logic with `_hasChanges` getter |
| Cache invalidation missing | Important | Added invalidation rules table per CRUD operation |
| Missing endpoint payload contracts | Important | Added field-level tables for all endpoints |
| Analytics tracking not addressed | Important | Added event tracking implementation with all PRD events |
| Missing test scenarios | Moderate | Added scenarios 7-11 covering hidden bins, generate name, flash toggle, etc. |

### Architectural Decisions Confirmed

1. **AsyncNotifier Pattern**: All providers use `AsyncNotifier` for consistency with CLAUDE.md conventions
2. **Action Type Filtering**: ID 4 ("Created Bin") auto-recorded only, filtered from user picker
3. **Category Sorting**: Use `binCount` field from categories API for most-used-first ordering
4. **Cache Strategy**: Invalidate related providers after CRUD operations (see rules table)

### Changes Made to SDD

1. Updated CON-2 constraint to `AsyncNotifier` pattern
2. Added canonical action types reference table with UI behaviors
3. Added endpoint payload contracts with required/optional fields
4. Added Generate Name feature flow with provider method
5. Added Hidden Bins feature flow with toggle, visual indicators, reactivation
6. Updated barcode scanner flow with flash toggle and fallback
7. Updated state management pattern to AsyncNotifier with cache invalidation
8. Added edit form dirty checking logic
9. Added analytics tracking implementation section
10. Added test scenarios 7-11

### Ready for Implementation Plan

- [x] All blockers resolved
- [x] Design covers all PRD requirements
- [x] Architecture is sound and justified (AsyncNotifier pattern)
- [x] Interfaces clearly defined with payload contracts
- [x] Security (permissions) and error handling addressed
- [x] README updated with review notes

**Decision**: ✅ Ready to proceed to Implementation Plan phase

## Implementation Plan Review (Codex) - 2026-02-07

### Key Findings Addressed

| Finding | Severity | Resolution |
|---------|----------|------------|
| Generate Name workstream incomplete | Blocker | Added repo/provider/test tasks in P1, P2, P5, P6 |
| Domain/mapper layer missing | Blocker | Added T1.5 (entities), T1.6 (mappers) to Phase 1 |
| Analytics tracking gaps | Important | Added bin_deleted (P7), bin_action_abandoned (P7), bin_create_abandoned (P5), bin_name_generated (P5/P6) |
| Phase 3 → Phase 5 sequencing | Important | Added dependency note in Phase 3 header |
| Category/location cache verification | Important | Added T2.2.6, T2.2.7, T2.4.4 cache tests |
| Error handling for Scenario 11 | Important | Added T4.3.6, T7.3.9 for 404 during action |
| Inconsistent Definition of Done | Moderate | Added DoD checklist to all phases |
| Missing Risks section | Moderate | Added Risks & Mitigations section with PRD risks |

### Changes Made to Implementation Plan

1. Added **Risks & Mitigations** section with PRD risks and task-specific mitigations
2. Added **Definition of Done** checklists to all 10 phases
3. Added **Generate Name workstream** across P1, P2, P5, P6:
   - T1.2.6, T1.2.12: Tests for generate name
   - T1.3.2, T1.4.6: API constant and model
   - T1.7.10, T1.8.10: Repository interface and impl
   - T2.2.8, T2.3.6: Provider tests and implementation
   - T5.3.7 (expanded), T5.3.13: Create screen integration
   - T6.3.8, T6.3.10: Edit screen integration
4. Added **Domain entities and mappers** (T1.5, T1.6) per SDD directory map
5. Added **Cache verification tasks** (T2.2.6, T2.2.7, T2.4.4) for ADR-4
6. Added **Error handling tasks** for Scenario 11 (T4.3.6, T7.3.9)
7. Added **Analytics tracking** for all PRD events:
   - T5.3.14: bin_create_abandoned
   - T7.2.10, T7.3.13: bin_action_abandoned
   - T7.3.12: bin_deleted
   - T5.3.13, T6.3.10: bin_name_generated
8. Added **dependency note** in Phase 3 for create route sequencing

## Implementation Plan Summary - 2026-02-07

### Phase Overview

| Phase | Description | Dependencies | Parallel? | Tasks |
|-------|-------------|--------------|-----------|-------|
| **P1** | Data Layer Foundation | None | No | 35+ |
| **P2** | State Management (Providers) | P1 | No | 20+ |
| **P3** | Barcode Scanner Widget | P2 | No | 18 |
| **P4** | Picker Widgets (3 components) | P2 | **Yes** | 22 |
| **P5** | Bin Create Screen | P3, P4 | No | 25+ |
| **P6** | Bin Edit Screen | P4, P5 | No | 18 |
| **P7** | Bin Detail Screen Updates | P4, P6 | No | 22 |
| **P8** | Bin Search Screen Updates | P3, P7 | No | 14 |
| **P9** | Hidden Bins Sheet | P8 | No | 12 |
| **P10** | Integration & E2E Validation | P1-P9 | No | 35+ |

### Key Implementation Notes

1. **Phase 4 is parallelizable**: Category Picker, Location Picker, and Action Picker can be developed concurrently
2. **All phases follow TDD**: Prime → Write Tests → Implement → Validate
3. **11 repository methods** to implement for CRUD operations (including generateBinName)
4. **11 test scenarios** from SDD to validate in Phase 10
5. **7 PRD features** with acceptance criteria to verify
6. **10 analytics events** tracked per PRD requirements
7. **Each phase has Definition of Done** checklist for clear completion criteria

### Commands for Implementation

```bash
# Before each phase
flutter analyze

# After modifying Freezed models
dart run build_runner build --delete-conflicting-outputs

# Run tests for specific layer
flutter test test/data/
flutter test test/presentation/providers/backstock/
flutter test test/presentation/screens/backstock/

# Final verification
flutter test
flutter build apk --debug
```

### Ready for `/start:implement 006`

## Context

### Backend API Ready
10 new endpoints added to MobileApiController.php for comprehensive backstock bin management:

**Bin CRUD Operations:**
1. `POST /backstock/:typeNum/bins/create` - Create new bin with categories, location, date
2. `POST /backstock/:typeNum/bins/:binId/update` - Comprehensive save (mirrors website's save-all)
3. `POST /backstock/:typeNum/bins/:binId/delete` - Soft delete
4. `POST /backstock/:typeNum/bins/:binId/hide` - Hide (make inactive)
5. `POST /backstock/:typeNum/bins/:binId/activate` - Reactivate hidden bin

**Bin Actions:**
6. `POST /backstock/:typeNum/bins/:binId/action` - Perform actions (remove, restock, move, etc.)
7. `POST /backstock/:typeNum/bins/:binId/generate-name` - Generate descriptive name

**Bin Discovery:**
8. `POST /backstock/:typeNum/bins/lookup` - Exact name lookup (barcode scanning)
9. `POST /backstock/:typeNum/bins/hidden` - List hidden bins
10. `POST /backstock/:typeNum/action-types` - Action types reference

### Action Types
| ID | Name | Description |
|----|------|-------------|
| 0 | Removed Everything | All items removed from bin (clears categories) |
| 1 | Removed Some Items | Some items removed (requires categoryId) |
| 2 | Restock from Floor | Items returned from sales floor |
| 3 | Moved Bin | Bin moved to different location (requires toLocationId) |
| 4 | Created Bin | New bin created (auto-recorded) |
| 5 | Pulled for Replenishment | Bin pulled for floor replenishment |

### Existing Infrastructure
Flutter app already has backstock foundation:
- `lib/data/models/backstock/backstock_models.dart` - Freezed models
- `lib/domain/entities/backstock/backstock_entities.dart` - Domain entities
- `lib/data/repositories/backstock_repository_impl.dart` - Repository implementation
- `lib/presentation/providers/backstock_provider.dart` - Riverpod providers
- `lib/presentation/screens/backstock/` - Dashboard, reports, notes screens
- `lib/data/models/mappers/backstock_mapper.dart` - Model to entity mapping

### Authentication
- Hybrid auth (JWT or API key) + store access
- All actions recorded with userId

### Documentation
- Full API docs in `docs/backend-api-updates.md`
- Request/response examples for all endpoints

---
*This file is managed by the specification-management skill.*
