diff --git a/.continue-here.md b/.continue-here.md new file mode 100644 index 00000000..f2c5fdaa --- /dev/null +++ b/.continue-here.md @@ -0,0 +1,265 @@ +# Continue Here: Float Precision Fix + +**Paused:** 2026-02-17T23:30:00Z +**Session Duration:** ~2 hours +**Branch:** `feat/float-precision-fix` +**Last Commit:** `3b8a0567 docs(phase-3): complete planning for frontend display cleanup` + +## πŸ“ Current Position + +**Phase:** Transition between Phase 2 (complete) and Phase 3 (planned) +**Status:** Phase 2 executed successfully, Phase 3 fully planned and ready for execution +**Next Action:** Execute Phase 3 using `/gsd:execute-phase 3` + +``` +Progress: [####......] 40% overall +Phase 1: [##########] βœ… Complete - Precision Foundation +Phase 2: [##########] βœ… Complete - Business Logic Migration +Phase 3: [##########] ⏸️ Planned - Frontend Display Cleanup (READY TO EXECUTE) +``` + +## βœ… Work Completed This Session + +### Phase 2: Business Logic Migration (EXECUTED) + +**Executed 3 plans in 2 waves:** + +**Wave 1:** +- βœ… Plan 01: Added `float_gte()` and `float_lte()` convenience functions + - File: `backend/api/utils/float_precision.py` + - Commit: `b68d20be` + +**Wave 2 (parallel):** +- βœ… Plan 02: Migrated WIP event comparisons + - Files: `wip_booked.py`, `wip_unbooked.py`, `wip_removed.py` + - Commit: `6d6d02cb` + +- βœ… Plan 03: Migrated production & inventory comparisons + - Files: `production.py`, `movement_updated.py`, `movement_reversed.py`, `progress_override_requested.py` + - Commit: `f34ab542` + +**State update:** +- βœ… Updated ROADMAP.md and STATE.md to mark Phase 2 complete +- Commit: `7f165035` + +### Phase 3: Frontend Display Cleanup (PLANNED) + +**Research completed:** +- βœ… Analyzed 100+ Vue components for float display patterns +- βœ… Identified existing partial solution (`roundQuantity` in MovementsRoot.vue) +- βœ… Discovered no global float formatting utility exists +- βœ… Created comprehensive research document + +**Plans created (3 plans in 2 waves):** +- βœ… 03-01-PLAN.md - Create global `$formatFloat` utility +- βœ… 03-02-PLAN.md - Migrate production component displays (6 files) +- βœ… 03-03-PLAN.md - Migrate warehouse component displays +- βœ… 03-RESEARCH.md - Complete codebase analysis +- Commit: `3b8a0567` + +## 🎯 Next Steps (In Order) + +### Immediate Next Action +```bash +/gsd:execute-phase 3 +``` + +This will execute Phase 3 in 2 waves: +1. **Wave 1**: Create global `$formatFloat` utility in `boot/filters.js` +2. **Wave 2**: Parallel migration of production and warehouse components + +### Expected Outcomes +- Global float formatting utility available to all Vue components +- 6+ production components updated with clean float displays +- Warehouse movement/inventory displays cleaned up +- Local `roundQuantity` function removed +- All frontend requirements (UI-01 through UI-07) delivered + +### After Phase 3 Completion +1. Verify all requirements delivered (should be 20/20) +2. Test the complete system end-to-end +3. Create pull request for review +4. Consider `/gsd:verify-work` for comprehensive testing + +## πŸ“Š Project Metrics + +| Metric | Value | +|--------|-------| +| Phases completed | 2/3 (66%) | +| Plans executed | 5/8 | +| Requirements delivered | 18/20 (90%) | +| Commits this session | 4 | +| Files modified | 12 backend files | +| Files planned | ~10 frontend files | + +## πŸ”‘ Key Decisions Made + +### Phase 2 Decisions +1. **Convenience functions approach**: Added `float_gte` and `float_lte` to avoid verbose `or` chains +2. **Selective migration**: Only migrated comparisons between float quantities, left exact comparisons (== 0) unchanged +3. **Comment discipline**: Added inline comments explaining tolerance usage at each migration site + +### Phase 3 Decisions +1. **Global property over filter**: Chose `$formatFloat` global property pattern (consistent with existing `$numberFormat`, `$durationFromMillisec`) +2. **6-decimal standard**: Maintained backend precision standard (6 decimals) vs. existing local `roundQuantity` (4 decimals) +3. **Strip trailing zeros**: Default behavior to show "100" instead of "100.000000" for better UX +4. **2-decimal progress**: Progress percentages limited to 2 decimals (99.99%) for readability + +## 🧩 Context for Resuming + +### Architecture Summary +- **Backend**: FastAPI + ArangoDB + event-sourcing pattern +- **Frontend**: Vue 3 + Quasar + Pinia (Options API and Composition API) +- **Standard**: 6-decimal float precision, 1e-6 epsilon tolerance +- **Pattern**: Pydantic validators + serializer rounding + tolerance comparisons + UI formatting + +### Files Touched This Session + +**Backend (Phase 2):** +``` +backend/api/utils/float_precision.py # Added float_gte, float_lte +backend/api/events/wip/wip_booked.py # Tolerance comparison +backend/api/events/wip/wip_unbooked.py # Tolerance comparison +backend/api/events/wip/wip_removed.py # Tolerance comparison +backend/api/endpoints/production.py # Job completion checks +backend/api/events/inventory/movement_updated.py # Movement completion +backend/api/events/inventory/movement_reversed.py # Reversal validation +backend/api/events/admin/progress_override_requested.py # WIP validation +``` + +**Frontend (Phase 3 - Planned):** +``` +webapps/main/src/boot/filters.js # Will add $formatFloat +webapps/main/src/components/JobCard.vue # Will format quantities +webapps/main/src/components/JobCardSlim.vue # Will format quantities +webapps/main/src/components/MediaViewer.vue # Will format quantities +webapps/main/src/components/OperatorJobsReorderDialog.vue +webapps/main/src/components/ProductionAdminMenu.vue +webapps/main/src/components/ProgressBtn.vue +webapps/main/src/views/warehouse/movements/MovementsRoot.vue +``` + +### Important Patterns + +**Backend tolerance comparison:** +```python +from utils.float_precision import float_gte, float_lte + +# Instead of: if job.qt_completed >= job.qt_planned +if float_gte(job.qt_completed, job.qt_planned): + close_job_and_update_queues(tx, job) +``` + +**Frontend formatting (to be implemented):** +```vue + +{{ $formatFloat(job.qt_completed) }} + + +{{ $formatFloat(job.progress, 2) }}% +``` + +## 🚧 Known Blockers/Issues + +**None identified.** The path forward is clear: +- Phase 3 plans are complete and verified +- All dependencies satisfied (Phases 1-2 complete) +- No blocking issues discovered during planning + +## πŸ’‘ Notes for Next Session + +### Testing Recommendations +1. **Backend testing** (already done in Phase 2): + - Verified all imports work + - Tested tolerance functions with edge cases + - All files import successfully + +2. **Frontend testing** (needed for Phase 3): + - Verify `$formatFloat` works in browser console + - Test with job cards showing various quantities + - Check movement displays in warehouse + - Test edge cases: null, NaN, very small numbers + - Confirm no visual regressions + +### Quality Checks +- βœ… All commits have proper messages +- βœ… All code changes have inline comments +- βœ… State files kept in sync +- ⏳ Frontend changes need manual verification (Phase 3) + +### Documentation +- βœ… CLAUDE.md has float precision standards documented +- βœ… Each phase has detailed research +- βœ… Plans are executable and verified +- ⏳ Consider updating CLAUDE.md after Phase 3 with frontend patterns + +## πŸ”„ How to Resume + +### Quick Start +```bash +# Verify you're on the right branch +git branch +# Should show: * feat/float-precision-fix + +# Check current state +git log --oneline -5 + +# Continue with Phase 3 execution +/gsd:execute-phase 3 +``` + +### Alternative Commands +```bash +# Check overall progress +/gsd:progress + +# Review Phase 3 plans first +cat .planning/phases/03-frontend-display-cleanup/03-01-PLAN.md +cat .planning/phases/03-frontend-display-cleanup/03-02-PLAN.md +cat .planning/phases/03-frontend-display-cleanup/03-03-PLAN.md + +# Verify phase 3 after execution +/gsd:verify-work 3 +``` + +### Context Files to Review +- `.planning/ROADMAP.md` - Overall project structure +- `.planning/STATE.md` - Current state and metrics +- `.planning/phases/03-frontend-display-cleanup/03-RESEARCH.md` - Frontend analysis +- `CLAUDE.md` - Float precision coding standards + +## πŸ“ˆ Success Metrics to Track + +**After Phase 3 completion:** +- [ ] Requirements: 20/20 delivered (currently 18/20) +- [ ] Plans: 8/8 executed (currently 5/8) +- [ ] Phases: 3/3 complete (currently 2/3) +- [ ] Overall progress: 100% (currently 40%) + +**Quality gates:** +- [ ] No console errors in frontend +- [ ] No visual regressions in UI +- [ ] All quantity displays show clean numbers +- [ ] Progress percentages limited to 2 decimals +- [ ] Movement quantities formatted consistently +- [ ] Inventory displays clean + +## 🎯 End Goal Reminder + +**Core Value:** +Accurate, clean numeric data throughout the system β€” quantities, progress, and measurements display correctly to users without floating-point noise, and comparisons work reliably without epsilon drift errors. + +**User-facing impact:** +- Users see "100" instead of "100.000001" ✨ +- Jobs close correctly when complete (99.999999 β‰ˆ 100) βœ… +- Inventory operations handle precision correctly βœ… +- Clean, professional UI everywhere 🎨 + +--- + +**Resume command:** `/gsd:execute-phase 3` +**Estimated time to completion:** 30-45 minutes +**Branch:** `feat/float-precision-fix` (up to date) +**Ready to ship:** After Phase 3 + verification + PR + +*Session paused: 2026-02-17T23:30:00Z* diff --git a/.planning/PROJECT.md b/.planning/PROJECT.md new file mode 100644 index 00000000..6dbdd3bf --- /dev/null +++ b/.planning/PROJECT.md @@ -0,0 +1,92 @@ +# Progress Platform - Float Precision Fix + +## What This Is + +A Manufacturing Operations Management (MOM) system that manages work orders, production tracking, inventory, traceability, quality control, and collaboration across manufacturing operations. Built with FastAPI backend, Vue 3 frontend, event-driven architecture using ArangoDB and Kafka, serving production operators and warehouse staff. + +## Core Value + +**Accurate, clean numeric data throughout the system** β€” quantities, progress, and measurements display correctly to users without floating-point noise, and comparisons work reliably without epsilon drift errors. + +## Requirements + +### Validated + + + +- βœ“ **Event-driven architecture** β€” Immutable event log with CQRS pattern (`backend/api/events/`) β€” existing +- βœ“ **Production management** β€” Work orders, jobs, batches, phases, processes, WIP tracking β€” existing +- βœ“ **Inventory management** β€” Movements, counting, stock levels, warehouse operations β€” existing +- βœ“ **Traceability** β€” Serial number tracking, batch tracking, genealogy β€” existing +- βœ“ **Collaboration** β€” Tasks, issues, data collection forms β€” existing +- βœ“ **Real-time updates** β€” WebSocket + Kafka for live state changes β€” existing +- βœ“ **Multi-tenant architecture** β€” Organizations, departments, users, permissions β€” existing +- βœ“ **Database transactions** β€” ArangoDB multi-collection ACID transactions in events β€” existing +- βœ“ **Dual frontends** β€” Main Quasar app + mobile warehouse app with Capacitor β€” existing +- βœ“ **i18n support** β€” English and Italian translations β€” existing + +### Active + + + +- [ ] **FLOAT-01**: All float values round to 6 decimal places when written to ArangoDB via serializer +- [ ] **FLOAT-02**: All float comparisons in business logic use tolerance-based equality (epsilon 1e-6) +- [ ] **FLOAT-03**: Vue components display quantities with clean decimal formatting (no trailing noise) +- [ ] **FLOAT-04**: Movement and inventory quantity displays show round numbers (e.g., 100.0 not 100.000001) +- [ ] **FLOAT-05**: Progress percentages display cleanly without floating-point artifacts +- [ ] **FLOAT-06**: Duration/time calculations in work sessions round consistently +- [ ] **FLOAT-07**: Batch completion and consumption quantities display cleanly +- [ ] **FLOAT-08**: Helper utility functions for tolerance-based comparison available system-wide + +### Out of Scope + +- **Migrate to Decimal type** β€” Too complex across Pydantic models, DB, frontend; float + rounding sufficient for domain needs +- **Migrate existing database values** β€” Leave historical data as-is, fix going forward only +- **Change number precision standard** β€” 6 decimals is the fixed standard, not configurable +- **Currency/monetary fields** β€” Not currently in scope; may revisit Decimal for true financial reconciliation in future +- **Test suite creation** β€” No active test suite to update; focus on implementation only + +## Context + +**Trigger**: UI displays excessive decimal places in movement/inventory quantities (e.g., `100.000001` instead of `100.0`), causing user confusion and visual noise. Root cause is floating-point arithmetic in division operations (progress calculations, unit processing time, proportional distributions). + +**Analysis completed**: Reviewed warehouse movements, inventory events, and related calculations. Determined that: +- Most operations are additions/subtractions/multiplications (low drift risk) +- Critical divisions: progress %, unit processing time, quantity ratios, proportional splits +- Domain requires fixed precision (6 decimals), not algebraic exactness +- Float + disciplined rounding is superior to Decimal migration (complexity/performance trade-off) + +**Existing serializer**: `backend/api/utils/db.py` has `model_to_db_dict()` and custom `encoder()` β€” ideal place to inject rounding logic for all DB writes. + +**Tech stack**: +- Backend: FastAPI + Pydantic v2 + ArangoDB (python-arango 8.x) +- Frontend: Vue 3 + Quasar 2.16 + Pinia +- Event system: 82 event classes across 7 domains (production, inventory, collaboration, serial, work_session, wip, admin) + +**Affected areas**: +- Quantities: `quantity`, `consumed_quantity`, `available_quantity`, etc. +- Progress: `progress` percentages, completion ratios +- Durations: Work session durations, processing times +- Any float field system-wide + +## Constraints + +- **Tech stack**: Must work with existing FastAPI + Pydantic v2 + ArangoDB + Vue 3 stack +- **Backwards compatibility**: Existing data in ArangoDB untouched; new writes only +- **No test suite**: No automated tests to update or maintain +- **Performance**: Rounding overhead must be negligible (single rounding op per float per write) +- **Brownfield**: Cannot break existing event application logic or API contracts + +## Key Decisions + +| Decision | Rationale | Outcome | +|----------|-----------|---------| +| Round at boundaries (not just divisions) | Prevents drift accumulation, ensures consistency, solves UI problem comprehensively, future-proof | β€” Pending | +| Use float (not Decimal) | Domain needs fixed precision (6 decimals), not algebraic equality; Decimal adds complexity across layers + performance cost | β€” Pending | +| 6 decimal precision standard | Sufficient for manufacturing quantities, progress, durations; common industry standard | β€” Pending | +| Tolerance 1e-6 for comparisons | Matches 6 decimal precision; prevents off-by-epsilon bugs in business logic | β€” Pending | +| Leave existing DB data as-is | Historical data doesn't cause issues; fix going forward only; avoids risky migration | β€” Pending | +| Inject rounding in db.py serializer | Single chokepoint for all DB writes; ensures consistency without hunting for write sites | β€” Pending | + +--- +*Last updated: 2026-02-17 after initialization* diff --git a/.planning/REQUIREMENTS.md b/.planning/REQUIREMENTS.md new file mode 100644 index 00000000..d78b2fc9 --- /dev/null +++ b/.planning/REQUIREMENTS.md @@ -0,0 +1,95 @@ +# Requirements: Float Precision Fix + +**Defined:** 2026-02-17 +**Core Value:** Accurate, clean numeric data throughout the system β€” quantities, progress, and measurements display correctly to users without floating-point noise, and comparisons work reliably without epsilon drift errors. + +## v1 Requirements + +Requirements for fixing floating-point precision system-wide. + +### Database Layer + +- [ ] **DB-01**: Serializer in `backend/api/utils/db.py` rounds all float values to 6 decimal places before writing to ArangoDB +- [ ] **DB-02**: Rounding applies to all numeric fields system-wide (quantities, progress, durations, etc.) +- [ ] **DB-03**: Existing database records remain unchanged (new writes only) +- [ ] **DB-04**: Serializer handles nested floats in dictionaries and lists + +### Business Logic Layer + +- [ ] **LOGIC-01**: Utility function `float_equals(a, b, epsilon=1e-6)` created for tolerance-based equality checks +- [ ] **LOGIC-02**: Utility function `float_less_than(a, b, epsilon=1e-6)` created for tolerance-based less-than comparisons +- [ ] **LOGIC-03**: Utility function `float_greater_than(a, b, epsilon=1e-6)` created for tolerance-based greater-than comparisons +- [ ] **LOGIC-04**: Comparison utilities available as importable module in `backend/api/utils/float_precision.py` +- [ ] **LOGIC-05**: Event validation logic using float comparisons migrated to use tolerance utilities +- [ ] **LOGIC-06**: Inventory business logic (movements, counting) uses tolerance comparisons +- [ ] **LOGIC-07**: Production business logic (progress, consumption) uses tolerance comparisons + +### UI Layer + +- [ ] **UI-01**: Vue components displaying quantities format floats to max 6 decimals +- [ ] **UI-02**: Movement quantity displays show clean numbers (e.g., 100.0 not 100.000001) +- [ ] **UI-03**: Inventory available_quantity displays show clean numbers +- [ ] **UI-04**: Progress percentage displays show clean numbers +- [ ] **UI-05**: Work session duration displays show clean numbers +- [ ] **UI-06**: Batch completion quantity displays show clean numbers +- [ ] **UI-07**: Reusable Vue composable or filter created for float formatting (if not already exists) + +### Utilities & Documentation + +- [ ] **UTIL-01**: Helper function `round_float(value, decimals=6)` created for explicit rounding +- [ ] **UTIL-02**: Rounding strategy documented in code comments (db.py, float_precision.py) +- [ ] **UTIL-03**: Epsilon tolerance standard (1e-6) documented in float_precision.py module docstring + +## v2 Requirements + +Not currently planned, potential future enhancements. + +(None identified) + +## Out of Scope + +| Feature | Reason | +|---------|--------| +| Migrate to Decimal type | Too complex across Pydantic models, DB, frontend; float + rounding sufficient for manufacturing domain needs | +| Migrate existing database values | Leave historical data as-is; risk of breaking existing records outweighs benefit; fix going forward only | +| Change precision standard (6 decimals) | 6 decimals is industry standard for manufacturing quantities; not configurable to maintain consistency | +| Create automated test suite | No active test suite exists; focus on implementation only; manual verification sufficient | +| Monetary/currency fields with Decimal | Not in current scope; may revisit Decimal for true financial reconciliation in future if needed | +| Configurable epsilon per operation | Single tolerance (1e-6) matches 6 decimal precision; complexity not justified for current needs | + +## Traceability + +Which phases cover which requirements. Updated during roadmap creation. + +| Requirement | Phase | Status | +|-------------|-------|--------| +| DB-01 | Phase 1 | Pending | +| DB-02 | Phase 1 | Pending | +| DB-03 | Phase 1 | Pending | +| DB-04 | Phase 1 | Pending | +| LOGIC-01 | Phase 1 | Pending | +| LOGIC-02 | Phase 1 | Pending | +| LOGIC-03 | Phase 1 | Pending | +| LOGIC-04 | Phase 1 | Pending | +| LOGIC-05 | Phase 2 | Pending | +| LOGIC-06 | Phase 2 | Pending | +| LOGIC-07 | Phase 2 | Pending | +| UI-01 | Phase 3 | Pending | +| UI-02 | Phase 3 | Pending | +| UI-03 | Phase 3 | Pending | +| UI-04 | Phase 3 | Pending | +| UI-05 | Phase 3 | Pending | +| UI-06 | Phase 3 | Pending | +| UI-07 | Phase 3 | Pending | +| UTIL-01 | Phase 1 | Pending | +| UTIL-02 | Phase 1 | Pending | +| UTIL-03 | Phase 1 | Pending | + +**Coverage:** +- v1 requirements: 20 total +- Mapped to phases: 20 +- Unmapped: 0 + +--- +*Requirements defined: 2026-02-17* +*Last updated: 2026-02-17 after roadmap creation* diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md new file mode 100644 index 00000000..67382582 --- /dev/null +++ b/.planning/ROADMAP.md @@ -0,0 +1,76 @@ +# Roadmap: Float Precision Fix + +**Created:** 2026-02-17 +**Depth:** Quick +**Phases:** 3 +**Coverage:** 20/20 v1 requirements mapped + +## Phases + +- [x] **Phase 1: Precision Foundation** - Serializer rounding, comparison utilities, and helper functions +- [x] **Phase 2: Business Logic Migration** - Migrate float comparisons in events and domain logic to tolerance utilities +- [ ] **Phase 3: Frontend Display Cleanup** - Clean numeric formatting across all Vue components + +## Phase Details + +### Phase 1: Precision Foundation +**Goal**: System has the core tools to write clean floats and compare them reliably +**Depends on**: Nothing (first phase) +**Requirements**: DB-01, DB-02, DB-03, DB-04, LOGIC-01, LOGIC-02, LOGIC-03, LOGIC-04, UTIL-01, UTIL-02, UTIL-03 +**Success Criteria** (what must be TRUE): + 1. Any float written to ArangoDB via the serializer is rounded to 6 decimal places (e.g., writing 1/3 stores 0.333333, not 0.3333333333333333) + 2. Nested float values inside dicts and lists are also rounded when serialized + 3. Existing database records are not modified by any migration or batch process + 4. Developers can import `float_equals`, `float_less_than`, `float_greater_than`, and `round_float` from a single utility module + 5. Module docstrings and code comments document the 6-decimal / 1e-6 epsilon standard + +**Plans:** 2 plans in 1 wave + +Plans: +- [ ] 01-01-PLAN.md β€” Float precision utilities (config + comparison functions) +- [ ] 01-02-PLAN.md β€” Database serializer rounding (modify encoder with recursive rounding) + +### Phase 2: Business Logic Migration +**Goal**: Business logic comparisons use tolerance-based equality instead of raw float comparison +**Depends on**: Phase 1 +**Requirements**: LOGIC-05, LOGIC-06, LOGIC-07 +**Success Criteria** (what must be TRUE): + 1. Event validation logic that compares float values (progress thresholds, quantity checks) uses tolerance utilities instead of == or < operators on floats + 2. Inventory operations (movements, counting reconciliation) use tolerance comparisons so that quantities like 99.999999 and 100.0 are treated as equal + 3. Production logic (progress completion checks, consumption quantity validation) uses tolerance comparisons so off-by-epsilon values do not block operations + +**Plans:** 3 plans in 2 waves + +Plans: +- [x] 02-01-PLAN.md β€” Add convenience comparison functions (float_gte, float_lte) +- [x] 02-02-PLAN.md β€” Migrate WIP event comparisons (wip_booked, wip_unbooked, wip_removed) +- [x] 02-03-PLAN.md β€” Migrate production & inventory comparisons (endpoints, events) + +### Phase 3: Frontend Display Cleanup +**Goal**: Users see clean, readable numbers everywhere in the UI +**Depends on**: Phase 1 (serializer ensures new data is clean); Phase 2 (business logic handles edge cases) +**Requirements**: UI-01, UI-02, UI-03, UI-04, UI-05, UI-06, UI-07 +**Success Criteria** (what must be TRUE): + 1. Movement quantity displays show round numbers (e.g., "100" or "100.5", not "100.000001") + 2. Inventory available_quantity and progress percentages display without trailing noise digits + 3. Work session durations and batch completion quantities display cleanly + 4. A reusable Vue composable or filter is available for consistent float formatting across components + +**Plans:** 3 plans in 2 waves + +Plans: +- [ ] 03-01-PLAN.md β€” Create global float formatting utility ($formatFloat) +- [ ] 03-02-PLAN.md β€” Migrate production component displays (JobCard, ProgressBtn, etc.) +- [ ] 03-03-PLAN.md β€” Migrate warehouse component displays (movements, inventory) + +## Progress + +| Phase | Plans Complete | Status | Completed | +|-------|----------------|--------|-----------| +| 1. Precision Foundation | 2/2 | βœ… Complete | 2026-02-17 | +| 2. Business Logic Migration | 3/3 | βœ… Complete | 2026-02-17 | +| 3. Frontend Display Cleanup | 0/3 | Planning complete | - | + +--- +*Roadmap created: 2026-02-17* +*Last updated: 2026-02-17 (Phases 1-2 complete, Phase 3 planning complete)* diff --git a/.planning/STATE.md b/.planning/STATE.md new file mode 100644 index 00000000..2f235c03 --- /dev/null +++ b/.planning/STATE.md @@ -0,0 +1,69 @@ +# Project State: Float Precision Fix + +## Project Reference + +**Core Value:** Accurate, clean numeric data throughout the system -- quantities, progress, and measurements display correctly without floating-point noise, and comparisons work reliably without epsilon drift errors. + +**Current Focus:** Phase 2 -- Business Logic Migration (tolerance-based comparisons) + +## Current Position + +**Phase:** 2 of 3 -- Business Logic Migration +**Plan:** Complete (Plans 02-01, 02-02, and 02-03 finished) +**Status:** Phase 2 complete + +``` +Progress: [####......] 40% +Phase 1: [##########] 2 of 2 plans complete βœ“ +Phase 2: [##########] 3 of 3 plans complete βœ“ +Phase 3: [..........] Not started +``` + +## Performance Metrics + +| Metric | Value | +|--------|-------| +| Phases completed | 2/3 | +| Plans completed | 5/? | +| Requirements delivered | 18/20 | + +| Phase | Plan | Duration | Tasks | Files | Date | +|-------|------|----------|-------|-------|------| +| 01 | 01 | 75s | 2 | 2 | 2026-02-17 | +| 01 | 02 | 120s | 3 | 1 | 2026-02-17 | +| 02 | 01 | 45s | 1 | 1 | 2026-02-17 | +| 02 | 02 | 60s | 1 | 3 | 2026-02-17 | +| 02 | 03 | 90s | 1 | 4 | 2026-02-17 | + +## Accumulated Context + +### Key Decisions +- Float + disciplined rounding chosen over Decimal migration (complexity/performance trade-off) +- 6 decimal precision standard, 1e-6 epsilon tolerance +- Serializer in db.py is the single chokepoint for all DB writes +- Existing DB data left as-is (new writes only) +- [Phase 01, Plan 01] Use absolute epsilon (1e-6) not relative tolerance for comparisons +- [Phase 01, Plan 01] Config-driven rounding precision via float_precision_decimals setting +- [Phase 01, Plan 01] NaN handling follows IEEE 754 standard (NaN != NaN) +- [Phase 01, Plan 02] Recursive helper function for nested dicts/lists +- [Phase 01, Plan 02] Preserve infinity and NaN values (rounding mathematically undefined) +- [Phase 01, Plan 02] Serializer injection pattern - transparent to application code +- [Phase 02, Plan 01] Convenience functions float_gte/float_lte avoid verbose or-chains +- [Phase 02, Plan 02] WIP booking/unbooking logic uses tolerance comparison +- [Phase 02, Plan 03] Production completion and inventory validation use tolerance utilities + +### Known Issues / Blockers +- None + +### TODOs +- Plan Phase 3 (frontend display cleanup) + +## Session Continuity + +**Last session:** 2026-02-17T23:15:00Z +**Stopped at:** Completed Phase 02 (Business Logic Migration) +**Next action:** Plan and execute Phase 3 (frontend display cleanup) + +--- +*State initialized: 2026-02-17* +*Last updated: 2026-02-17T23:15:00Z* diff --git a/.planning/codebase/ARCHITECTURE.md b/.planning/codebase/ARCHITECTURE.md new file mode 100644 index 00000000..add915e6 --- /dev/null +++ b/.planning/codebase/ARCHITECTURE.md @@ -0,0 +1,226 @@ +# Architecture + +**Analysis Date:** 2026-02-13 + +## Pattern Overview + +**Overall:** Event-sourcing with CQRS-style separation, using immutable event-based state mutations across a microservices architecture. + +**Key Characteristics:** +- **Event-driven**: All state changes flow through a single event system that persists to an immutable event log +- **Multi-service**: Decoupled backend (FastAPI), frontend (Vue 3), and workflow (Prefect) services +- **Graph-database centric**: ArangoDB as the system of record with transactional consistency +- **Message-driven communication**: Kafka integration for asynchronous event broadcasting and real-time updates +- **Transaction-scoped**: Multi-collection ArangoDB transactions ensure consistency within event application + +## Layers + +**Presentation Layer (Frontend):** +- Purpose: User interface for production management, inventory, tasks, quality, and analytics +- Location: `webapps/main/src/`, `webapps/warehouse/src/` +- Contains: Vue 3 components, composables, pages, routes, stores (Pinia + Vuex) +- Depends on: Backend API (REST), WebSocket for real-time updates +- Used by: End users and operators + +**API Layer (Backend):** +- Purpose: REST API endpoints that validate requests, dispatch events, and return results +- Location: `backend/api/endpoints/` +- Contains: Route handlers for 20+ domain areas (production, inventory, collaboration, etc.) +- Depends on: Event system, database utilities, auth middleware +- Used by: Frontend, external integrations, CLI tools + +**Event System:** +- Purpose: Immutable event log and application of business logic +- Location: `backend/api/events/` +- Contains: 82 event classes organized by domain (production, collaboration, inventory, serial, work_session, admin, wip) +- Depends on: Database transactions, event models +- Used by: Endpoints (to trigger events), post-processing (persists to Kafka) + +**Domain Logic Layer:** +- Purpose: Reusable business logic utilities and helpers +- Location: `backend/api/utils/` (domain-specific: `production.py`, `inventory.py`, `collaboration.py`, `traceability.py`, `serial.py`) +- Contains: Query helpers, validation, state computation +- Depends on: Database connection, models +- Used by: Events, endpoints + +**Data Layer:** +- Purpose: Database abstraction and persistence +- Location: `backend/api/utils/db.py`, `backend/api/managers/` +- Contains: ArangoDB connection pooling, transaction management, WebSocket manager, Kafka producer/consumer +- Depends on: External services (ArangoDB, Kafka) +- Used by: All layers above + +**Workflow Orchestration:** +- Purpose: Schedule and execute batch processes +- Location: `backend/workflow/flows/` +- Contains: Prefect 2.x flow definitions +- Depends on: Backend API, database +- Used by: System for scheduled/periodic operations + +## Data Flow + +**User Action β†’ Event β†’ State Update β†’ Real-time Broadcast:** + +1. User action on frontend (e.g., complete task) +2. Frontend calls `sendEvent()` composable (`webapps/main/src/composables/event.js`) +3. Event data posted to `POST /event` endpoint (`backend/api/endpoints/*.py`) +4. Endpoint validates auth, creates event instance from event class in `backend/api/events/` +5. Event class in `__init__` validates event data via Pydantic model +6. Event `save()` method: + - Creates ArangoDB transaction with required collections + - Calls `pre_processing()` (override hook for subclasses) + - Calls `apply()` - executes business logic (inserts/updates records, validates state) + - Stores immutable event record in `Event` collection + - Calls `post_processing()` (override hook) + - Commits transaction +7. Kafka producer publishes event to topic (async) +8. Kafka consumer in `NotificationsKafkaConsumer` picks up event +9. WebSocket manager broadcasts to connected clients +10. Frontend stores receive updates via WebSocket listener + +**State Management (Frontend):** +- Vuex store for session/auth state (`webapps/main/src/boot/store.js`) +- Pinia stores for domain state (`webapps/main/src/stores/*.js`) +- Store persistence via composables (`reStore.js`, task store uses automatic save on unload) + +## Key Abstractions + +**BaseEvent:** +- Purpose: Base class for all business events, enforces interface contract +- File: `backend/api/events/base_event.py` +- Pattern: Abstract base class with required methods `get_event_type()`, `get_tx_collections()`, `apply()` +- Example implementations: `TaskCreatedEvent`, `BatchCompletedEvent`, `IssueCreatedEvent` + +**EventInfoModel (Pydantic):** +- Purpose: Validates event payload data before persistence +- File: `backend/api/models/event.py` +- Pattern: Extends `EventInfoModel` class-by-class to define event-specific fields +- Example: `TaskCreatedEvent.InfoModel` defines task_key, task_type_key, title, assigned_to, etc. + +**Endpoint Pattern (FastAPI):** +- Purpose: Accept requests, validate, create events, handle responses +- Files: `backend/api/endpoints/*.py` (admin.py, production.py, collaboration.py, etc.) +- Pattern: `@router.post()` decorator β†’ dependencies=[auth.verify_token] β†’ create event β†’ return response +- Example: `POST /work-order` in `endpoints/production.py` creates WorkOrder + +**Domain Utility Functions:** +- Purpose: Shared logic for queries and state transitions +- Files: `backend/api/utils/production.py`, `inventory.py`, etc. +- Pattern: Stateless functions that accept transaction `tx` parameter +- Example: `create_job_record()`, `update_target_queue()` in `utils/production.py` + +**ArangoDB Base Models:** +- Purpose: Pydantic models that map to ArangoDB document structure +- File: `backend/api/models/base_models.py` +- Pattern: `FlexModel` (base), `ArangoDocument` (with _id, _key, _rev), `ArangoEdge` (_from, _to) +- Used by: All domain models (WorkOrder, Task, Issue, etc.) + +## Entry Points + +**Backend API:** +- Location: `backend/api/main.py` +- Triggers: FastAPI app startup on docker-compose up +- Responsibilities: + - Middleware stack setup (CORS, GZip filtering, notification middleware) + - Router registration (20+ routers from endpoints/) + - Kafka producer/consumer initialization + - WebSocket manager startup + +**Frontend Main App:** +- Location: `webapps/main/src/App.vue` +- Triggers: Vue 3 mount +- Responsibilities: + - Route rendering via `` + - CSS variables setup + - Session persistence (saves state on beforeunload) + - Task store recovery + +**Frontend Router:** +- Location: `webapps/main/src/router/index.js` +- Triggers: Navigation to any route +- Responsibilities: + - Permission checking (scope-based via store) + - Locale detection and i18n setup + - Task context handling on route change + - Authentication enforcement (redirects to login if not auth) + +**Workflow Service:** +- Location: `backend/workflow/flows/` +- Triggers: Prefect schedule or manual execution +- Responsibilities: Batch processing, report generation, data cleanup + +## Error Handling + +**Strategy:** Transaction-scoped rollback with explicit exception raising and HTTP error response + +**Patterns:** + +1. **Validation-level errors** (Pydantic models): + - Event `__init__` validates via model instantiation + - Raises `ValueError` if InfoModel validation fails + - Propagates to endpoint, caught as 422 Unprocessable Entity + +2. **Transaction-scoped errors** (Event apply): + - Event `apply()` method may raise exceptions + - Transaction auto-aborts via try/finally in `save()` + - Exception re-raised to endpoint + - Endpoint catches and returns 500 or custom HTTPError + +3. **Business logic errors** (Domain utilities): + - Utilities raise custom exceptions (e.g., `HTTPError` in `utils/exceptions.py`) + - Caught by endpoint, converted to HTTP response + - Example: "Task with code X already exists" β†’ 409 Conflict + +4. **Database errors**: + - Transaction errors bubble up as ArangoDB exceptions + - Caught in finally block to abort transaction + - Example: Collection not found, duplicate key β†’ 500 Server Error + +**Example (from `backend/api/events/collaboration/task_created.py`):** +```python +def apply(self): + # Validation error example + if self.tx.collection('Task').find(dict(code=self.info.code)).count() > 0: + raise ValueError(f"Task with code {self.info.code} already exists") + + # Exception handling in counter generation + try: + task_data.code = _generate_counter(self.tx, counter_key) + except Exception as e: + raise Exception("Cannot generate task code...") from e +``` + +## Cross-Cutting Concerns + +**Logging:** +- No structured logging framework detected; uses Python `print()` for debug info +- Kafka consumer logs message topic/offset +- Frontend uses `console.error()` and `console.log()` + +**Validation:** +- Pydantic models for schema validation (API requests β†’ models) +- Event InfoModel validation before database write +- Permission validation in router guards (`router/index.js`) +- Domain-level validation in event `apply()` methods + +**Authentication:** +- JWT token verification via `auth.verify_token` dependency +- Token validation in `utils/auth.py` (decode and extract user info) +- Session stored in Vuex state (`store.state.session.user`, `store.state.session.session_key`) +- Router redirects unauthenticated requests to login +- Token refreshed on `recognizeMe` action (persisted session recovery) + +**Authorization:** +- Scope-based (role-like system) in route meta +- `hasRoutePermission()` in router checks `store.getters.hasPermission(route.meta.scope)` +- Endpoint-level checks possible but not consistently applied + +**Real-time Updates:** +- WebSocket connection via NotificationMiddleware +- Kafka events β†’ NotificationsKafkaConsumer β†’ WebSocketManager.enqueue() +- Frontend consumes via WebSocket listener (composable or store subscription) +- Task context automatically attached to events if active task selected + +--- + +*Architecture analysis: 2026-02-13* diff --git a/.planning/codebase/CONCERNS.md b/.planning/codebase/CONCERNS.md new file mode 100644 index 00000000..01da1be4 --- /dev/null +++ b/.planning/codebase/CONCERNS.md @@ -0,0 +1,230 @@ +# Codebase Concerns + +**Analysis Date:** 2026-02-13 + +## Tech Debt + +**Abundant Debug Print Statements:** +- Issue: Extensive debug printing with emoji prefixes throughout `dhr.py` and multiple endpoints. These are verbose, unstructured, and should be replaced with proper logging. +- Files: `backend/api/utils/dhr.py` (40+ print statements), `backend/api/endpoints/traceability.py`, `backend/api/managers/websocket_manager.py`, `backend/workflow/flows/` +- Impact: Production logs become noise; difficult to parse and monitor. No log levels or structured output. +- Fix approach: Replace all print() calls with Python logging module. Use appropriate log levels (DEBUG, INFO, ERROR). Configure logging handler per environment. + +**Bare Except Clauses:** +- Issue: Extensive use of `except:` and `except Exception as e:` that silently swallow errors with print statements instead of logging +- Files: `backend/api/events/serial/base_serial.py`, `backend/api/events/serial/serial_booked.py`, `backend/api/endpoints/production.py` (12+ instances), `backend/api/endpoints/inventory.py` (17+ instances), `backend/api/utils/production.py` (3+ instances) +- Impact: Errors are masked. No stack traces propagate. Silent failures make debugging difficult. +- Fix approach: Catch specific exception types. Use proper logging instead of print. Let exceptions propagate or handle them explicitly. + +**Traceback Exposure in API Responses:** +- Issue: Full Python tracebacks returned to clients in HTTP responses via `traceback.format_exc()`. Security and information disclosure risk. +- Files: `backend/api/endpoints/production.py:52`, `backend/api/endpoints/inventory.py:33,237,398`, `backend/api/endpoints/traceability.py:64,129,142` +- Impact: Exposes internal code structure and paths to clients. May reveal secrets or database queries. +- Fix approach: Log full traceback server-side only. Return generic error messages to clients. Use structured error responses with error codes. + +**Incomplete TODO Markers (65+ instances):** +- Issue: Scattered TODO, FIXME, and XXX markers indicating incomplete or deferred work +- Files: `backend/api/endpoints/` (production.py, process.py, config.py, product.py, admin.py, media.py), `backend/api/utils/` (inventory.py, dhr.py, traceability.py, file.py), `backend/api/events/` (production/, inventory/, work_session/, wip/), `backend/api/models/process.py`, `backend/api/models/inventory/movement.py` +- Impact: Accumulated technical debt. Features may be half-implemented. Refactoring patterns unclear. +- Fix approach: Create backlog items for each TODO. Assign priorities. Schedule resolution or mark as permanently deferred with rationale. + +**Large Monolithic Files:** +- Issue: Several files exceed 600+ lines, indicating complex logic that should be decomposed +- Files: `backend/api/utils/dhr.py` (1297 lines), `backend/api/endpoints/production.py` (862 lines), `backend/api/endpoints/process.py` (713 lines), `backend/api/events/admin/progress_override_requested.py` (681 lines), `backend/api/events/inventory/count_imported.py` (636 lines) +- Impact: Difficult to test individual functions. High cyclomatic complexity. Hard to understand business logic. +- Fix approach: Break into smaller modules. Extract helper functions. Create domain-specific service classes. + +## Security Considerations + +**CORS Configuration Too Permissive:** +- Risk: CORS allows all origins (`["*"]`), credentials enabled, all methods and headers allowed +- Files: `backend/api/main.py:31-36`, `backend/api/utils/config.py:14` +- Current mitigation: None. Dev environment note in CLAUDE.md but persists in code +- Recommendations: Restrict CORS to specific allowed origins per environment. Use environment variables. Disable credentials if not needed. Restrict methods to GET, POST, OPTIONS. + +**Default Database Credentials:** +- Risk: Hardcoded default username 'root', blank password for API database connection +- Files: `backend/api/utils/config.py:12-13`, `backend/api/utils/db.py:30` +- Current mitigation: Reliant on Docker secrets for production +- Recommendations: Ensure secrets are NEVER hardcoded. Add validation that password is set in production. Use connection pooling with credentials rotation. + +**No Input Validation in Some Endpoints:** +- Risk: Several endpoints accept dynamic query parameters without validation +- Files: `backend/api/endpoints/inventory.py:24-28` (PositionSearchParams binding), `backend/api/endpoints/production.py:36-40` (Transaction collections) +- Current mitigation: Pydantic models provide some validation but not all fields validated +- Recommendations: Validate all user inputs. Use strict Pydantic validation. Whitelist allowed values for critical operations. + +**Traceback Information Disclosure:** +- Risk: Exception tracebacks exposed in HTTP error responses reveal internal code paths +- Files: Multiple endpoints (see above) +- Current mitigation: None +- Recommendations: Log tracebacks server-side only. Return generic error messages with error codes to clients. + +## Known Issues + +**Bare Except with Print Traceback Pattern:** +- Symptoms: Errors are printed but not properly logged. Silent failures occur. Response data may be incomplete. +- Files: `backend/api/events/serial/serial_unlinked.py:57-58`, `backend/api/events/serial/serial_created.py:75-76`, `backend/api/events/serial/serial_linked.py:109-110`, `backend/api/events/serial/serial_deleted.py:50-51`, `backend/api/events/serial/serial_booked.py:41-42` +- Trigger: Any exception during event apply, serial linking, unlinking, deletion +- Workaround: Enable debug logging on app startup to capture printed tracebacks in stdout/stderr + +## Performance Bottlenecks + +**Inefficient List Comprehensions with Multiple Database Calls:** +- Problem: Query results mapped to Pydantic models via list comprehensions without batching +- Files: `backend/api/endpoints/inventory.py:28`, `backend/api/endpoints/inventory.py:75`, `backend/api/endpoints/process.py:79`, `backend/api/endpoints/org.py:37`, `backend/api/endpoints/serial.py:55`, `backend/api/endpoints/traceability.py:183` +- Cause: `for position in db.collection('Department').all()` and similar patterns may load all records into memory, then iterate +- Improvement path: Use AQL queries with proper filtering/pagination. Implement cursor-based pagination for large result sets. + +**Lack of Query Optimization TODOs:** +- Problem: TODO marker on line 25 of `backend/api/endpoints/process.py` indicates queries need optimization +- Files: `backend/api/endpoints/process.py:25` +- Cause: Unknown - likely N+1 queries or inefficient AQL +- Improvement path: Profile query performance. Add indexes to frequently-queried fields. Use AQL JOIN/FILTER for related data. + +**Complex Event Processing in Progress Override:** +- Problem: `ProgressOverrideRequestedEvent` involves complex WIP, Batch, and WorkSession state management with multiple collections +- Files: `backend/api/events/admin/progress_override_requested.py` (681 lines) +- Cause: Business logic complexity combined with transaction coordination +- Improvement path: Break into smaller event handlers. Cache intermediate results. Consider event sourcing replay optimization. + +**No Query Result Caching:** +- Problem: Repeated queries for same data (config, product definitions) may hit database multiple times per request +- Files: Backend generally lacks caching layer +- Cause: Stateless API design without Redis or similar +- Improvement path: Add caching for config, product definitions, and user permissions. Use cache invalidation on updates. + +## Fragile Areas + +**Event Transaction Handling:** +- Files: `backend/api/events/base_event.py`, all event subclasses (82 files total) +- Why fragile: Complex transaction ownership tracking (`_owns_transaction`). If transaction handling fails partway, state becomes inconsistent. Child events depend on parent transaction. +- Safe modification: Never modify transaction handling without adding integration tests. Test rollback scenarios. Ensure all collections are included in `get_tx_collections()`. +- Test coverage: Event tests exist but transaction failure scenarios may not be fully covered. + +**Database Query AQL Strings:** +- Files: Throughout `backend/api/utils/` in Queries classes (production.py, traceability.py, inventory.py, collaboration.py, serial.py) +- Why fragile: AQL queries are strings. Easy to make syntax errors. Schema changes break queries silently. No type checking. +- Safe modification: Test queries with sample data. Use AQL syntax validator. Update query comments when schema changes. Add unit tests for queries. +- Test coverage: Queries tested in integration but not validated for schema conformance. + +**Kafka Message Processing:** +- Files: `backend/api/managers/kafka_consumer_manager.py`, `backend/api/utils/notification_kafka_consumer.py`, `backend/api/managers/websocket_manager.py` +- Why fragile: No explicit error handling for malformed messages. WebSocket manager relies on print() statements. No message validation or schema enforcement. +- Safe modification: Add message validation before processing. Implement retry logic with exponential backoff. Add schema validation (e.g., Avro). +- Test coverage: Limited. No tests for malformed message handling. + +**Job Queue Reordering:** +- Files: `backend/api/endpoints/production.py`, `backend/api/events/admin/progress_override_requested.py` (lines 30-36) +- Why fragile: Site key hardcoded to '0'. Multi-site support mentioned but incomplete (see TODO on line 77 of config.py). +- Safe modification: Extract site key from context or request. Implement proper multi-site support. Test queue reordering with multiple sites. +- Test coverage: Specific queue reordering scenarios may lack coverage. + +## Scaling Limits + +**No Database Connection Pooling Configuration:** +- Current capacity: Single ArangoClient instance created per application startup +- Limit: Under high concurrent load, may exhaust available connections +- Files: `backend/api/utils/db.py:28-30` +- Scaling path: Implement connection pooling with configurable pool size. Monitor connection utilization. Add health checks. + +**In-Memory Event Spawning:** +- Current capacity: All events spawned in memory before transaction commit +- Limit: Large batch operations (100+ events) may cause memory spikes +- Files: `backend/api/events/base_event.py:68-120` +- Scaling path: Implement event streaming or chunking. Commit intermediate results in long-running operations. + +**No Query Result Pagination in Some Endpoints:** +- Current capacity: Endpoints like `get_positions` may load entire result sets +- Limit: Queries with large result sets (10k+ records) will cause memory and response time issues +- Files: `backend/api/endpoints/inventory.py`, `backend/api/endpoints/org.py` +- Scaling path: Implement cursor-based pagination. Add limit/offset to all list endpoints. Return result counts with paging info. + +**Kafka Consumer Group Management:** +- Current capacity: Single consumer group for all notifications +- Limit: High message volume may cause lag or rebalancing issues +- Files: `backend/api/managers/kafka_consumer_manager.py` +- Scaling path: Implement consumer scaling per topic. Add lag monitoring. Implement backpressure handling. + +## Test Coverage Gaps + +**Event Error Scenarios:** +- What's not tested: Exception handling within event `apply()` methods. Transaction rollback scenarios. Child event failure cascade. +- Files: `backend/api/events/` (all event classes) +- Risk: Silent failures in event processing. State inconsistency undetected until later operations fail. +- Priority: High + +**API Error Response Handling:** +- What's not tested: Full error scenarios for traceback exposure. Invalid input handling. Edge cases in error formatting. +- Files: `backend/api/endpoints/production.py`, `backend/api/endpoints/inventory.py`, `backend/api/endpoints/process.py` +- Risk: Unexpected error responses leak information. Clients may crash on malformed error details. +- Priority: High + +**Kafka Consumer Failure:** +- What's not tested: Message processing failure. Consumer lag. Malformed message handling. +- Files: `backend/api/managers/kafka_consumer_manager.py`, `backend/api/utils/notification_kafka_consumer.py` +- Risk: Messages lost or stuck in queue. No visibility into consumer health. +- Priority: Medium + +**Database Query Edge Cases:** +- What's not tested: Large result sets. Complex AQL query failures. Schema version mismatches. +- Files: `backend/api/utils/` (all query files) +- Risk: Unexpected behavior with edge case data. Silent query failures. +- Priority: Medium + +**Frontend TypeScript Type Safety:** +- What's not tested: TypeScript compilation strictness. Any-typed values cause runtime errors. +- Files: `webapps/main/src/types/form.d.ts:value?: any` +- Risk: Type errors only caught at runtime. Form data handling fragile. +- Priority: Medium + +## Dependencies at Risk + +**WeasyPrint Integration:** +- Risk: Complex PDF generation in `dhr.py` relies on external library. Heavy file I/O. Timeout potential on large documents. +- Files: `backend/api/utils/dhr.py` (imports WeasyPrint, reportlab) +- Impact: DHR generation can fail silently with print statements. No timeout configuration visible. +- Migration plan: Wrap WeasyPrint in try-catch with logging. Add timeout configuration. Consider async PDF generation via Celery/Prefect. + +**Arango Python Client Version 8.x:** +- Risk: python-arango 8.x API may differ from newer versions. Transaction API could change. +- Files: `backend/api/utils/db.py` +- Impact: Version upgrades may break transaction handling. +- Migration plan: Pin version explicitly. Add compatibility tests. Track upstream changes to transaction API. + +**Prefect 2.x Workflow Integration:** +- Risk: Prefect API may evolve. Event-triggered workflow submissions may fail if API changes. +- Files: `backend/api/events/inventory/count_session_confirmed.py:272-275` +- Impact: Inventory count workflows may not trigger. No retry mechanism visible. +- Migration plan: Add error handling with retries. Document Prefect API version dependency. Monitor workflow execution. + +## Missing Critical Features + +**Structured Logging:** +- Problem: No central logging configuration. Debug prints used throughout. No log aggregation. +- Blocks: Observability, debugging, compliance (audit trails). +- Priority: High - Impacts production support + +**API Error Schema Standardization:** +- Problem: Error responses vary between endpoints. Some include tracebacks, others don't. No standard error format. +- Blocks: Client error handling, proper error reporting, monitoring. +- Priority: High - Impacts API reliability + +**Database Migration Versioning:** +- Problem: Only 2 AQL migration files exist. No migration history visible. No rollback mechanism. +- Blocks: Database schema evolution tracking, safe deployments, schema documentation. +- Priority: Medium - Impacts deployment safety + +**Request/Response Validation Middleware:** +- Problem: No centralized validation. Each endpoint validates independently. No OpenAPI spec visible. +- Blocks: Type safety, API documentation, test coverage. +- Priority: Medium - Impacts API maintainability + +**Comprehensive Configuration Management:** +- Problem: Config relies on environment variables and secrets. No validation that required configs are present. +- Blocks: Deployment confidence, multi-environment support, config drift detection. +- Priority: Medium - Impacts production readiness + +--- + +*Concerns audit: 2026-02-13* diff --git a/.planning/codebase/CONVENTIONS.md b/.planning/codebase/CONVENTIONS.md new file mode 100644 index 00000000..142f0407 --- /dev/null +++ b/.planning/codebase/CONVENTIONS.md @@ -0,0 +1,241 @@ +# Coding Conventions + +**Analysis Date:** 2026-02-13 + +## Naming Patterns + +**Files (Python Backend):** +- Snake case with underscores: `api_auth_manager.py`, `base_event.py`, `kafka_consumer.py` +- Event classes: `{domain}_{event}.py` (e.g., `batch_created.py`, `issue_updated.py`, `serial_booked.py`) +- Exception classes follow pattern: `{Action}Error` suffix (e.g., `SerialNotUpdatedError`, `SerialCodeAlreadyPresent`, `SerialNotCreatedError`) + +**Files (JavaScript/Vue Frontend):** +- Composables use `use` prefix followed by camelCase: `useFormFields.js`, `usePrefectAPI.js`, `useCountRecordExport.js` +- Store files (Pinia): lowercase domain names: `task.js`, `product.js`, `job.js` +- Components: PascalCase: `JobCard.vue`, `TaskNew.vue`, `MessageThread.vue`, `BaseTooltipIcon.vue` +- Utility files: camelCase: `apiCall.js`, `dateUtils.js`, `xlsxDownload.js`, `loadScript.js` +- Routes: descriptive camelCase: `productionRoutes.js`, `adminRoutes.js`, `taskRoutes.js` + +**Functions (Python):** +- Snake case: `create_job_record()`, `_update_job_progress()`, `verify_password()`, `get_user()` +- Private functions prefixed with underscore: `_generate_counter()`, `_get_job_data()`, `_update_job_progress()` +- Async functions (FastAPI): regular snake case with `async def`: `async def create_work_order()`, `async def get_issue_type()` + +**Functions (JavaScript):** +- camelCase: `getFieldByType()`, `getTaskByKey()`, `getTasksByStatus()`, `fetchTasks()` +- Event handlers: `handle{Action}` or `on{Event}`: common Vue pattern +- Getters in Pinia: `get{Entity}` (e.g., `getTaskByKey`, `getActiveTask`, `getTasksByStatus`) + +**Variables:** +- snake_case in Python: `wo_code`, `product_key`, `qt_planned`, `serial_key`, `batch_qt` +- camelCase in JavaScript: `activeTaskKey`, `ignoredEntities`, `isEntityIgnored`, `taskData` +- Boolean prefixes: `is`, `has` in both languages: `is_active`, `has_items`, `isLoading`, `hasError` + +**Types & Classes (Python):** +- PascalCase: `WorkOrderNew`, `ProductDetails`, `Batch`, `FlexModel`, `ArangoDocument`, `ArangoEdge` +- Pydantic model suffix not required but pattern is domain-based: `IssueType`, `IssueTypeFull`, `IssueTypeUpdate` +- Event classes: PascalCase ending with `Event`: `BatchCreatedEvent`, `WIPBookedEvent`, `IssueUpdatedEvent` +- Base classes prefixed with `Base`: `BaseEvent`, `BaseProductionEvent`, `BaseSe-rial`, `BaseCollaboration` + +**Types & Classes (JavaScript):** +- Store name pattern: `use{Domain}Store`: `useTaskStore`, `useCountSessionStore` +- No explicit TypeScript in code (using JSDoc when needed) + +**Database/Constants:** +- Collection names: PascalCase for Document collections (`Event`, `Batch`, `WorkOrder`, `Job`, `Queue`, `Product`, `Phase`), snake_case for edge collections (`requires`, `is_in_position`, etc.) +- Field names in documents: snake_case: `wo_code`, `product_key`, `qt_planned`, `_key`, `_id`, `_rev` +- Enum values: UPPER_SNAKE_CASE: `EventType.BATCH_CREATED`, `WorkStatus.COMPLETED` +- API event types: UPPER_SNAKE_CASE: `TASK_CREATED`, `ISSUE_CREATED`, `BATCH_COMPLETED` + +## Code Style + +**Formatting:** +- ESLint: eslint-plugin-vue v9.19.2 with Vue 3 recommended rules +- Prettier: v3.1.1 configured with single quotes only (`.prettierrc.json`: `{"singleQuote": true}`) +- Python: No explicit formatter configuration found; follows PEP 8 conventions observed in code + +**Linting (Frontend - JavaScript/Vue):** +- Tool: ESLint v8.57.0 +- Config: `.eslintrc.js` at root of each webapp +- Extensions: eslint-plugin-vue, eslint-plugin-import +- Key Rules: + - `vue/eqeqeq`: enforced (error) - strict equality checking + - `curly`: enforced (error) - require curly braces for all control structures + - `no-unused-vars`: enforced (error) with pattern `^_` for intentional unused (e.g., `_unusedParam`) + - `no-debugger`: error in production, off in development + - `vue/no-empty-component-block`: warning + - `vue/padding-line-between-blocks`: warning + - `import/order`: warning with alphabetical alphabetization - groups: [builtin, external, internal, parent, sibling, index, object, type] + +**Linting (Backend - Python):** +- No explicit linter config file found +- Code follows PEP 8 style +- Uses type hints throughout (Python 3.11) +- Union types: `str | None` (PEP 604 style, not `Optional[str]` or `Union[str, None]`) + +## Import Organization + +**Order (Backend - Python):** +1. Standard library: `import os`, `import traceback`, `from datetime import`, `from typing import` +2. Third-party: `from fastapi import`, `from pydantic import`, `from arango import` +3. Relative application imports: `from utils import`, `from models import`, `from events import` + +**Example from `endpoints/product.py`:** +```python +import os +import traceback + +from fastapi import APIRouter, Form, File, HTTPException, UploadFile, Body, Query, Depends +from utils import auth +from fastapi.encoders import jsonable_encoder +from typing import Annotated + +from utils.kpi import Queries as ProductStatQueries +from models.product import * +from models.process import PhaseData +from utils.api import APIResponse +from utils.db import db +from utils.dt import timestamp +from utils.file import FileHandler +from utils.product import * +from utils.process import Queries as ProcessQueries +``` + +**Order (Frontend - JavaScript):** +1. Vue/Framework: `import { defineStore } from 'pinia'` +2. External libraries: `import { Notify, Dialog } from 'quasar'`, `import axios from 'axios'` +3. Internal composables/utils: `import { useI18n } from 'vue-i18n'`, `import { computed } from 'vue'` +4. Application modules: `import { api } from '@/boot/axios.js'`, `import { sendEvent } from '@/composables/event.js'` + +**Path Aliases:** +- Frontend: `@/` resolves to `src/` directory (Vue path alias configured in jsconfig.json) +- Backend: Relative imports without path prefixes; Python path includes backend root + +## Error Handling + +**Patterns (Python Backend):** +- HTTPException from FastAPI for API errors: + ```python + raise HTTPException( + status_code=409, + detail="An issue type with the same code already exists" + ) + ``` +- Custom exceptions defined in `utils/exceptions.py`: `HTTPError`, `SerialCodeAlreadyPresent`, `SerialNotUpdatedError` +- Try/except blocks wrap database operations and external service calls +- ValueError for validation failures within event logic: + ```python + raise ValueError("Quantity cannot be zero or negative") + raise ValueError("You must provide serials to be linked to this new batch") + ``` +- Transaction abort on error: + ```python + try: + # ... logic + except Exception: + tx.abort_transaction() + raise HTTPException(...) + ``` +- traceback.format_exc() captured in error responses for debugging + +**Patterns (JavaScript Frontend):** +- Try/catch blocks for async operations: + ```javascript + try { + const { data } = await api.get('/task', { params: searchParams }) + // success handling + } catch (error) { + console.error('Error fetching tasks:', error) + throw error + } finally { + this.loading = false + } + ``` +- console.error() for logging: `console.error('Error fetching tasks:', error)` +- console.warn() for non-critical issues: `console.warn('API_CONFIG not found, using default configuration')` +- Quasar Notify for user-facing errors (from `quasar` imports) +- Dialog for confirmations and alerts + +## Logging + +**Framework:** +- Python: Uses `traceback.format_exc()` for exception details; console output via standard print (no logger import) +- JavaScript: Uses native `console` object + +**Patterns:** +- Python: Errors logged with full traceback included in HTTPException detail +- JavaScript: `console.error('Context: ')` for exceptions in try/catch blocks +- No structured logging framework found; relies on console output and traceback strings + +## Comments + +**When to Comment:** +- Comments used selectively for complex business logic +- Section dividers using dashes: `# ----------` (seen in endpoints for grouping related routes) +- Commented-out code kept for reference in some cases (e.g., `# TODO:` comments) + +**JSDoc/TSDoc:** +- Minimal JSDoc usage observed +- Example: `@see` reference in `src/composables/form.js`: + ```javascript + /** + * @see {@link ../mixins/form.js} + */ + export function useFormFields() { + ``` +- No formal TypeScript (JavaScript with JSDoc for type hints where needed) + +**Python Docstrings:** +- Docstrings present in base classes (ABC classes describe abstract methods): + ```python + @classmethod + @abstractmethod + def get_event_type(cls) -> EventType: + """ + Returns the event type. Must be implemented by the subclass. + """ + pass + ``` +- Event classes document their purpose implicitly through naming and implementation + +## Function Design + +**Size:** +- Backend: Functions typically 10-50 lines; complex event handlers can be 80+ lines +- Frontend: Composable functions 30-70 lines; component methods variable length based on feature + +**Parameters:** +- Python: Type hints required (Pydantic models preferred for complex data) +- Python event handlers: Require InfoModel inner class for event data validation +- JavaScript: No type enforcement; documented through usage patterns + +**Return Values:** +- Python: Explicit returns; event `apply()` methods store responses in `self.response` +- JavaScript: Async functions return Promises; Pinia actions return data for composition +- Python: Functions that spawn events return list or single response from `self.response` + +**Async Handling:** +- Python: FastAPI async def for route handlers; no explicit async/await in library calls (ArangoDB client is blocking) +- JavaScript: Explicit async/await for API calls; computed() for reactive data + +## Module Design + +**Exports:** +- Python: Event classes exported via __init__ imports; utils functions exported directly +- JavaScript: + - Named exports preferred: `export function getFieldByType() {}` + - Store exports: `export const useTaskStore = defineStore(...)` + - No default exports in most modules + +**Barrel Files:** +- Python: Minimal use; imports done from specific modules +- JavaScript: Router files act as barrel exports (e.g., `router/index.js` imports all route files) +- Frontend: Stores imported individually from `src/stores/` or `src/store/` + +**Architecture Patterns:** +- Backend: Event-sourced domain events; each event class encapsulates business logic in `apply()` method +- Frontend: Pinia stores with actions for API calls; composables for reusable logic; Vue 3 Composition API patterns + +--- + +*Convention analysis: 2026-02-13* diff --git a/.planning/codebase/INTEGRATIONS.md b/.planning/codebase/INTEGRATIONS.md new file mode 100644 index 00000000..3afbcb55 --- /dev/null +++ b/.planning/codebase/INTEGRATIONS.md @@ -0,0 +1,221 @@ +# External Integrations + +**Analysis Date:** 2026-02-13 + +## APIs & External Services + +**Third-Party API Clients:** +- None detected - No Stripe, SendGrid, Twilio, Slack, or similar SaaS integrations in codebase +- HTTP requests use standard `httpx` and `requests` libraries for generic API calls + +**Internal Service Communication:** +- Custom implementations only (`/backend/api/utils/auth.py`, `/backend/api/managers/`) +- No external SaaS integrations for auth, payment, or messaging + +## Data Storage + +**Databases:** + +**Primary - ArangoDB (Graph Database):** +- Provider: Self-hosted ArangoDB 3.11 +- Connection: `PROGRESS_ARANGO_URL` env var (default: `http://localhost:8529`) +- Client: `python-arango==8.*` (Python driver) +- Dev mode: Runs without authentication (`ARANGO_NO_AUTH=1`) +- Volumes: `db_data` (persistent storage), `db_backup` (backup directory) +- Collections: WorkOrder, Job, Queue, Product, Phase, Process, Batch, WIP, Event, StepExecutionData, WorkSession, CustomField, Config, Inventory, Movement, Counting, and others (graph relationships maintained via edges) +- Transactional support: Multi-collection transactions via event `apply()` methods in `/backend/api/events/` + +**Workflow Database - PostgreSQL:** +- Provider: PostgreSQL 15.2-alpine +- Purpose: Prefect workflow orchestration database +- Connection: `PREFECT_API_DATABASE_CONNECTION_URL=postgresql+asyncpg://postgres:postgres@workflow-db:5432/prefect` +- Used only by Prefect server and workers +- Located at: `/deploy/compose/workflow.yaml` service `workflow-db` +- Credentials: Default postgres user (dev config only) + +**File Storage:** +- Local filesystem only +- Media volume: `/media` mounted in `/deploy/compose/base.yaml` +- Path configured via `PROGRESS_MEDIA_PATH` env var (default: `/media`) +- Endpoints: `/backend/api/endpoints/media.py`, `/backend/api/endpoints/file.py` +- Handlers: `utils/media.py` for media operations + +**Caching:** +- None detected - No Redis, Memcached, or caching layer implemented +- Database queries executed directly against ArangoDB + +## Authentication & Identity + +**Auth Provider:** +- Custom implementation (no OAuth2/SAML/third-party provider) +- Location: `/backend/api/utils/auth.py`, `/backend/api/endpoints/auth.py` + +**Implementation Details:** +- JWT tokens using HS256 algorithm +- Token secret from docker secret `progress_jwt_secret` (or hardcoded in dev) +- Bcrypt password hashing via `passlib` library +- OAuth2 Bearer token scheme via FastAPI `OAuth2PasswordBearer` +- JWT validation middleware intercepts requests +- Scopes defined for authorization: admin, library, production, operator +- Frontend stores JWT in store and sends via Authorization header in axios interceptors (`/webapps/main/src/boot/axios.js`) + +**Password Management:** +- Bcrypt hashing with `passlib==1.7.2` +- Password context configured in `/backend/api/utils/auth.py` + +## Monitoring & Observability + +**Error Tracking:** +- None detected - No Sentry, Rollbar, or similar error tracking service + +**Logs:** +- Console/stdout logging (default FastAPI behavior) +- Structured logging via `logging` module +- Development: JSON-file driver with rotation in `/deploy/compose/dev.yaml` + - `max-size: "1k"`, `max-file: "3"` for log rotation +- API logs available via docker logs: `docker logs progress_lab_dev-api-1` + +**Performance Monitoring:** +- Traefik provides HTTP request metrics on port 8080 (dashboard accessible in dev) +- Kafka JMX metrics exposed on port 9101 +- No application-level APM detected + +## CI/CD & Deployment + +**Hosting:** +- Docker Swarm (production mode via `/deploy/compose/stack.yaml`) +- Could be adapted to Kubernetes +- GitLab Container Registry (images stored in `registry.gitlab.com/progresslab/progress-platform/`) + +**CI Pipeline:** +- GitLab CI (`.gitlab-ci.yml`) +- Triggers on semantic version tags: `v[0-9]+.[0-9]+.(a|b|rc)?[0-9]+` +- Build stages: + - `version-info` - Parse version from git tag + - `build:webapp` - Build main web app + - `build:warehouse` - Build warehouse mobile app + - `build:api` - Build API service + - `build:workflow` - Build workflow worker service +- Images tagged with both branch version (`$BRANCH_VERSION-latest`) and full version (`$VERSION`) +- All images pushed to `registry.gitlab.com/progresslab/progress-platform/` + +**Deployment:** +- Docker Compose files for different environments: + - `/deploy/compose/base.yaml` - Core services (Traefik, API, DB, Kafka, media) + - `/deploy/compose/dev.yaml` - Development overrides (source mounts, hot-reload) + - `/deploy/compose/dev.debug.yaml` - Remote debugging + - `/deploy/compose/workflow.yaml` - Prefect server + PostgreSQL + - `/deploy/compose/stack.yaml` - Production swarm deployment + - `/deploy/compose/kafka.dev.yaml` - Standalone Kafka (KRaft mode) + - `/deploy/compose/integration.yaml`, `/deploy/compose/reporting.yaml`, `/deploy/compose/notebooks.yaml` - Optional services +- Traefik 2.11 as reverse proxy with Docker provider +- Health checks via docker inspect (not configured in compose) + +## Environment Configuration + +**Required Environment Variables:** +- `PROGRESS_ARANGO_URL` - ArangoDB connection +- `PROGRESS_DB_NAME` - Database name (PROGRESS_TEST, PROGRESS_PROD, etc.) +- `PROGRESS_MEDIA_PATH` - Media directory path +- `PROGRESS_API_ROOT_PATH` - API root path (default: `/api`) +- `PROGRESS_KAFKA_BOOTSTRAP_SERVER` - Kafka broker address +- `PROGRESS_WEBAPP_URL` - Frontend URL for CORS +- `PREFECT_API_URL` - Prefect workflow server API + +**Secrets Location:** +- Docker secrets (production): `/run/secrets/` mounted in containers + - `progress_api_db_pwd` - ArangoDB password (not used in dev, required in prod) + - `progress_jwt_secret` - JWT signing secret + - `progress_admin_pwd` - Admin user password +- .env file (development): `env.dev` provides local defaults +- See `/backend/api/utils/config.py` for Pydantic settings configuration + +**Env Var Prefix:** +- All Progress-specific env vars use `PROGRESS_` prefix +- Loaded by Pydantic with `env_prefix="progress_"` +- Can also load from docker secrets directory + +## Webhooks & Callbacks + +**Incoming:** +- Kafka message consumption via `KafkaConsumerManager` (`/backend/api/managers/kafka_consumer_manager.py`) +- Notification channel subscriptions via WebSocket +- No HTTP webhooks implemented + +**Outgoing:** +- Kafka message production via `KafkaProducer` (`/backend/api/utils/kafka/kafka_producer.py`) +- Events streamed to Kafka from all business logic operations +- WebSocket broadcasts to connected clients via `WebsocketManager` (`/backend/api/managers/websocket_manager.py`) + +**Kafka Topics:** +- `notifications` - Auto-created on startup via `KafkaAdmin.getInstance().create_topic("notifications")` +- Other topics created dynamically by event system +- Broker: `apache/kafka:latest` in KRaft mode (no ZooKeeper) +- Bootstrap servers: + - Dev: `broker:19092` (internal docker network) + - Production: Configured via `PROGRESS_KAFKA_BOOTSTRAP_SERVER` env var + +## Event-Driven Architecture + +**Event System:** +- Base classes: `/backend/api/events/base_event.py` +- All domain events inherit from base and implement: + - `get_event_type()` - Returns event type string + - `get_tx_collections()` - Collections involved in transaction + - `apply()` - Business logic executed in ArangoDB transaction +- Event types: production, collaboration, work_session, wip, inventory, serial, traceability +- Events persisted in immutable `Event` collection +- Events streamed to Kafka for external consumption/audit + +**Workflow Integration:** +- Prefect 3.x orchestration server (`prefecthq/prefect:3-latest`) +- Workflow system worker: `wf-sys-worker` (custom image from `/backend/workflow`) +- Prefect API: `PREFECT_API_URL` configured for workers to connect +- PostgreSQL 15.2 backing Prefect database +- Traefik routes `/workflow/*` to Prefect server on port 4200 +- Base path: `/workflow` for UI, `/workflow/api` for API + +## Real-Time Communication + +**WebSockets:** +- Native FastAPI WebSocket support (`fastapi.WebSocket`) +- Manager: `WebsocketManager` (`/backend/api/managers/websocket_manager.py`) +- Active connection pool maintained in memory +- Messages queued via `asyncio.Queue` with max 100 items +- Used for live notifications and server events +- Frontend receives updates via WebSocket connections (declared in package.json) + +**Server-Sent Events (SSE):** +- `sse_starlette` library for SSE endpoints +- Alternative to WebSocket for one-way server-to-client updates +- Endpoint: `/backend/api/endpoints/notification.py` + +## Cross-Service Communication + +**Internal Service Boundaries:** +- API (`/backend/api`) - REST endpoints, WebSocket, Kafka producer +- Workflow (`/backend/workflow`) - Prefect flows as standalone service +- Frontend (`/webapps/main`, `/webapps/warehouse`) - HTTP/WebSocket clients + +**Message Bus:** +- Apache Kafka - Event streaming and async communication +- All business events published to Kafka +- KafkaConsumerManager subscribes to relevant topics +- Enables eventual consistency and event sourcing patterns + +## Media & File Handling + +**Storage:** +- Local filesystem at `/media` volume (externally managed volume) +- Direct file access via endpoints in `/backend/api/endpoints/file.py`, `/backend/api/endpoints/media.py` +- No CDN or external file storage (S3, Azure Blob, GCS) + +**Formats Supported:** +- PDF: Generation via WeasyPrint, PyPDF, ReportLab; viewing via vue-pdf-embed +- Excel: openpyxl for read/write operations +- Images: Handled via file upload/download +- Video: video.js player for streaming + +--- + +*Integration audit: 2026-02-13* diff --git a/.planning/codebase/STACK.md b/.planning/codebase/STACK.md new file mode 100644 index 00000000..06cba281 --- /dev/null +++ b/.planning/codebase/STACK.md @@ -0,0 +1,163 @@ +# Technology Stack + +**Analysis Date:** 2026-02-13 + +## Languages + +**Primary:** +- Python 3.11 - Backend API and workflow services (`/backend/api`, `/backend/workflow`) +- JavaScript/ES6+ - Frontend webapps and testing (`/webapps/main`, `/webapps/warehouse`, `/testing`) +- Vue 3 - Frontend component framework with Composition API + +**Secondary:** +- AQL - ArangoDB query language (`/db/migrations`) +- Robot Framework - BDD testing framework (`/testing/robot-test`) + +## Runtime + +**Environment:** +- Node.js 20.19.0 (specified in `.nvmrc`) +- Python 3.11 (specified in `/backend/.python-version`) +- Docker containerization (all services run in Docker Compose) + +**Package Managers:** +- npm/yarn for Node.js projects (main app `engine: "node": "^20.19.0 || ^22"`, warehouse `engine: "node": "^20.19.0 || ^22"`) +- pip for Python projects +- Lockfiles: `yarn.lock` present at project root + +## Frameworks + +**Backend:** +- FastAPI 0.x - REST API framework (`/backend/api/main.py`) +- Uvicorn/Gunicorn - ASGI web server +- Prefect 3.x - Workflow orchestration (`/backend/workflow`, prefect image: `prefecthq/prefect:3-latest`) + +**Frontend:** +- Quasar 2.16+ - Vue 3 UI framework with integrated build tools + - Main app: v2.16.0 (`/webapps/main`) + - Warehouse: v2.16.0 (`/webapps/warehouse`) +- Pinia 2.x - State management (`pinia: ^2.1.7`, `pinia: ^2.0.11`) +- Vue Router 4.x - Client-side routing +- Vue I18n 9.0.0 - Internationalization (English, Italian) + +**Testing:** +- Mocha 10.2.0 - JavaScript test runner (`/testing/package.json`) +- Chai 4.3.7 - Assertion library +- Cypress 13.10.0 - E2E testing +- Robot Framework - BDD/keyword-driven testing (`/testing/robot-test`) + +**Build/Dev:** +- Vite 5.4.0 - Frontend bundler +- Quasar CLI/App Vite 2.x - Quasar build system +- ESLint 8.57.0 - JavaScript linting (`.eslintrc.js`) +- Prettier 3.1.1 (main), 2.5.1 (warehouse) - Code formatting +- PostCSS 8.4.14 - CSS processing +- Esbuild 0.21.0 - JavaScript bundler + +## Key Dependencies + +**Critical Backend:** +- `python-arango==8.*` - ArangoDB Python driver (`/backend/api/requirements.txt`) +- `pydantic==2.*` - Data validation using Python type annotations (`/backend/api/requirements.txt`) +- `pydantic-settings==2.*` - Configuration management from environment (`/backend/api/requirements.txt`) +- `confluent_kafka` - Kafka producer/consumer (`/backend/api/requirements.txt`) +- `PyJWT==2.0.*` - JWT token handling for authentication (`/backend/api/requirements.txt`) +- `passlib==1.7.2` - Password hashing with bcrypt (`/backend/api/requirements.txt`) +- `websockets` - WebSocket support for real-time updates +- `sse_starlette` - Server-sent events support +- `python-jose` - JOSE (JWT) implementation +- `httpx==0.*` - Async HTTP client (`/backend/api/requirements.txt`) + +**PDF & Document Generation:** +- `weasyprint==66.*` - HTML to PDF conversion +- `pypdf==4.*` - PDF manipulation +- `reportlab==4.*` - PDF generation +- `openpyxl==3.*` - Excel file handling + +**Frontend:** +- `axios: ^1.7.0` - HTTP client for API calls +- `socket.io-client: ^4.7.5` - WebSocket client (unused in current exploration but declared) +- `vue-sse: ^2.5.2` - Server-sent events client +- `@pdfme/common`, `@pdfme/generator`, `@pdfme/schemas`, `@pdfme/ui: ^5.5.0` - PDF template engine (recently upgraded to v5) +- `vue-pdf-embed: 1.1.6` - PDF viewing component +- `vue-router: ^4.0.0` - Routing +- `vue-i18n: ^9.0.0` - Translation framework +- `luxon: ^3.0.4` - Date/time manipulation +- `sortablejs: ^1.15.0` - Drag-and-drop list reordering +- `file-saver: ^2.0.5` - File download utilities +- `xlsx: ^0.18.5` - Excel file handling +- `jwt-decode: ^3.1.2` - JWT parsing (without verification) +- `video.js: ^8.17.4` - Video player +- `codemirror: ^6.0.1` - Code editor +- `@vueuse/core: ^11.1.0` - Vue composables utility library + +**Warehouse App Specific:** +- `@capacitor/core, @capacitor/app, @capacitor/cli, @capacitor/splash-screen: ^6.0.0` - Capacitor for mobile (Android) +- `@zxing/browser, @zxing/library: ^0.21.3` - Barcode/QR code scanning +- `browserprint-es: ^0.0.5` - Print functionality + +## Configuration + +**Environment:** +- Configuration loaded via Pydantic Settings with environment prefix `PROGRESS_` (see `/backend/api/utils/config.py`) +- Environment variables or `.env` file support +- Docker secrets support for sensitive values (jwt_secret, admin_pwd, api_db_pwd) +- .env file support documented in `env.dev` + +**Key Configuration Variables:** +- `PROGRESS_ARANGO_URL` - ArangoDB connection URL (default: `http://localhost:8529`) +- `PROGRESS_DB_NAME` - Database name selection (dev: `PROGRESS_TEST`, prod: `PROGRESS_PROD`) +- `PROGRESS_API_DB_PWD` - Database password (docker secret) +- `PROGRESS_MEDIA_PATH` - Media files directory (default: `/media`) +- `PROGRESS_KAFKA_BOOTSTRAP_SERVER` - Kafka broker (default: `broker:19092`) +- `PROGRESS_WEBAPP_URL` - Frontend URL for CORS and redirects + +**Build:** +- `Dockerfile` in `/backend/api` - Python 3.11-slim with system deps for WeasyPrint +- `webapp.prod.Dockerfile` in `/webapps/main` - Production build +- `Dockerfile` in `/webapps/warehouse` - Warehouse app build +- ESLint config: `.eslintrc.js` in webapps +- Prettier config: `.prettierrc.json` (single quotes enabled) + +## Platform Requirements + +**Development:** +- Docker & Docker Compose +- Node.js 20.19.0 (or 22+) +- Python 3.11 +- ArangoDB 3.11 (Intel/x86_64 or arm64v8 for M1-M3 Apple Silicon) +- Apache Kafka (latest, KRaft mode - no ZooKeeper) +- PostgreSQL 15.2 (for Prefect workflow database) +- Traefik 2.11 (reverse proxy/load balancer) + +**Production:** +- Docker Swarm or Kubernetes deployment +- GitLab Container Registry for image storage +- All services containerized and orchestrated +- Production compose files: `/deploy/compose/stack.yaml`, `/deploy/compose/stack-dev.yaml` +- TLS support available via `/deploy/compose/tls.yaml` + +## Key Service Versions + +- **ArangoDB:** 3.11 (Intel: `arangodb:3.11`, ARM: `arm64v8/arangodb:3.11`) +- **Apache Kafka:** latest (KRaft mode, no ZooKeeper required) +- **PostgreSQL:** 15.2-alpine (for Prefect) +- **Prefect:** 3.x (`prefecthq/prefect:3-latest`) +- **Traefik:** 2.11 +- **Docker:** 24.0.5 + +## Lockfiles & Dependency Management + +- `yarn.lock` present at project root (for Node.js monorepo) +- Python requirements split by service: + - `/backend/api/requirements.txt` - API dependencies + - `/backend/workflow/requirements.txt` - Workflow service dependencies + - `/testing/robot-test/requirements.txt` - Testing dependencies +- Node dependencies managed per webapp: + - `/webapps/main/package.json` + - `/webapps/warehouse/package.json` + - `/testing/package.json` + +--- + +*Stack analysis: 2026-02-13* diff --git a/.planning/codebase/STRUCTURE.md b/.planning/codebase/STRUCTURE.md new file mode 100644 index 00000000..8160383b --- /dev/null +++ b/.planning/codebase/STRUCTURE.md @@ -0,0 +1,348 @@ +# Codebase Structure + +**Analysis Date:** 2026-02-13 + +## Directory Layout + +``` +progress-platform/ +β”œβ”€β”€ backend/ # Backend services (Python) +β”‚ β”œβ”€β”€ api/ # FastAPI main application +β”‚ β”‚ β”œβ”€β”€ main.py # Entry point, middleware, router registration +β”‚ β”‚ β”œβ”€β”€ endpoints/ # 20+ domain-specific route handlers +β”‚ β”‚ β”œβ”€β”€ events/ # Event-sourcing system (82 event classes) +β”‚ β”‚ β”œβ”€β”€ models/ # Pydantic models (domain objects) +β”‚ β”‚ β”œβ”€β”€ utils/ # Domain logic, database, auth, helpers +β”‚ β”‚ β”œβ”€β”€ managers/ # WebSocket, Kafka, Executor managers +β”‚ β”‚ β”œβ”€β”€ middlewares/ # Notification, GZip filtering +β”‚ β”‚ └── media/ # File/media handling +β”‚ β”œβ”€β”€ workflow/ # Prefect 2.x orchestration flows +β”‚ β”œβ”€β”€ commons/ # Shared utilities +β”‚ β”œβ”€β”€ scripts/ # Dev/CLI scripts +β”‚ └── lte/, mock/, reports/ # Legacy/specialized modules +β”‚ +β”œβ”€β”€ webapps/ # Frontend applications +β”‚ β”œβ”€β”€ main/ # Main production webapp (Quasar + Vue 3) +β”‚ β”‚ β”œβ”€β”€ src/ +β”‚ β”‚ β”‚ β”œβ”€β”€ App.vue # Root component +β”‚ β”‚ β”‚ β”œβ”€β”€ components/ # 90+ Vue components by feature +β”‚ β”‚ β”‚ β”œβ”€β”€ composables/ # 18 reusable logic modules +β”‚ β”‚ β”‚ β”œβ”€β”€ pages/ # Page views +β”‚ β”‚ β”‚ β”œβ”€β”€ views/ # Feature views (57 directories) +β”‚ β”‚ β”‚ β”œβ”€β”€ router/ # Route definitions (feature-based splitting) +β”‚ β”‚ β”‚ β”œβ”€β”€ stores/ # Pinia stores (task, config, countSession, taskType) +β”‚ β”‚ β”‚ β”œβ”€β”€ store/ # Vuex store (session, auth) +β”‚ β”‚ β”‚ β”œβ”€β”€ boot/ # Plugin initialization +β”‚ β”‚ β”‚ β”œβ”€β”€ i18n/ # Translations (en.js, it.js) +β”‚ β”‚ β”‚ β”œβ”€β”€ layouts/ # Layout components +β”‚ β”‚ β”‚ β”œβ”€β”€ css/ # Global styles +β”‚ β”‚ β”‚ β”œβ”€β”€ assets/ # Static assets +β”‚ β”‚ β”‚ β”œβ”€β”€ lib/ # Utility libraries +β”‚ β”‚ β”‚ β”œβ”€β”€ plugins/ # Custom Vue plugins +β”‚ β”‚ β”‚ β”œβ”€β”€ types/ # TypeScript definitions +β”‚ β”‚ β”‚ └── utils/ # Utility functions +β”‚ β”‚ └── quasar.conf.js # Quasar config +β”‚ β”‚ +β”‚ └── warehouse/ # Mobile warehouse app (Quasar + Capacitor) +β”‚ └── src/ # Same structure as main +β”‚ +β”œβ”€β”€ db/ # Database artifacts +β”‚ β”œβ”€β”€ migrations/ # AQL migration scripts (numbered: 226-*.aql) +β”‚ β”œβ”€β”€ scripts/ # Database initialization scripts +β”‚ β”œβ”€β”€ backup/ # Database backup files +β”‚ β”œβ”€β”€ DB Queries/ # Reference queries +β”‚ └── Data Architecture/ # Schema documentation +β”‚ +β”œβ”€β”€ deploy/ # Deployment configuration +β”‚ β”œβ”€β”€ compose/ # Docker Compose files +β”‚ β”‚ β”œβ”€β”€ base.yaml # Core services (Traefik, API, DB, Kafka) +β”‚ β”‚ β”œβ”€β”€ dev.yaml # Dev overrides (hot-reload, mounts) +β”‚ β”‚ β”œβ”€β”€ dev.debug.yaml # Remote debugging config +β”‚ β”‚ β”œβ”€β”€ workflow.yaml # Prefect server + PostgreSQL +β”‚ β”‚ β”œβ”€β”€ stack.yaml # Production Swarm config +β”‚ β”‚ β”œβ”€β”€ tls.yaml # TLS configuration +β”‚ β”‚ └── [other].yaml # Integration, warehouse, reporting configs +β”‚ └── [dockerfile locations] +β”‚ +β”œβ”€β”€ testing/ # Testing artifacts and data +β”œβ”€β”€ files/, media/ # File/media storage +β”œβ”€β”€ plans/, cli/ # Planning tools, CLI scripts +β”œβ”€β”€ km/ # Knowledge management / documentation +└── .planning/ # GSD planning outputs + └── codebase/ # This directory (architecture docs) +``` + +## Directory Purposes + +**backend/api/:** +- Purpose: Core FastAPI REST API +- Contains: Request handlers, events, data models, domain logic +- Key files: `main.py` (app setup), `endpoints/*.py` (route groups), `events/base_event.py` (event base) + +**backend/api/endpoints/:** +- Purpose: REST route handlers organized by domain +- Contains: 20+ files mapping to features: + - `production.py` - Work orders, jobs, batches + - `inventory.py` - Warehouse stock movements + - `collaboration.py` - Tasks, issues, messages + - `traceability.py` - Serial tracking + - `process.py` - Process definitions + - `product.py` - Product master data + - `auth.py`, `admin.py`, `org.py`, `form.py`, `serial.py`, `counting.py`, etc. +- Files: Router object named after module, always imported in `main.py` via `app.include_router()` + +**backend/api/events/:** +- Purpose: Event-sourcing system with immutable event log +- Contains: 82 event classes in domain folders + - `base_event.py` - BaseEvent abstract class + - `production/` (11 events) - Job/batch lifecycle + - `collaboration/` (13 events) - Task/issue/message lifecycle + - `inventory/` (13 events) - Movement/counting/warehouse + - `serial/` (8 events) - Serial number tracking + - `work_session/`, `wip/`, `admin/` - Specialized events +- Pattern: Each event extends BaseEvent, implements InfoModel, apply() method, get_event_type(), get_tx_collections() + +**backend/api/models/:** +- Purpose: Pydantic schema definitions for API and database +- Contains: 24 files by domain + - `base_models.py` - FlexModel, ArangoDocument, ArangoEdge + - `production.py` - WorkOrder, Job, Batch models + - `collaboration.py` - Task, Issue, Message models + - `event.py` - EventInfoModel, EventType enum (116 event types) + - Domain folders: `inventory/`, etc. + +**backend/api/utils/:** +- Purpose: Domain logic, database utilities, helpers +- Contains: 34 files + - `db.py` - ArangoDB connection singleton + - `auth.py` - JWT validation and user extraction + - Domain helpers: + - `production.py` - Queries, job/WO creation + - `inventory.py` - Movement validation, counting helpers + - `collaboration.py` - Task/issue utilities + - `traceability.py` - Serial tracking logic + - `kafka/` (6 files) - Kafka producer, consumer, admin + - `delayedqueue/` - Queue management + - `dhr.py` - Large helper file (44KB) + +**backend/api/managers/:** +- Purpose: Singleton managers for system-wide resources +- Contains: 5 files + - `websocket_manager.py` - WebSocket connection pooling + - `kafka_consumer_manager.py` - Consumer lifecycle + - `executor_manager.py` - Async task execution + - `server_event_manager.py` - Server-sent events + - `notification_manager.py` - Notification dispatch + +**webapps/main/src/components/:** +- Purpose: Reusable Vue 3 components +- Contains: 90+ `.vue` files organized by feature: + - Production components (work orders, jobs, phases) + - Inventory components (movements, counting) + - Collaboration components (tasks, issues, chat) + - Form components (fields, layouts) + - UI components (modals, dialogs, tables) +- Naming: `[Feature][Component].vue` (e.g., `ProductionJobDialog.vue`) + +**webapps/main/src/composables/:** +- Purpose: Reusable Vue 3 composition API logic +- Contains: 18 files + - `event.js` - `sendEvent()`, `sendEventsBulk()` for triggering events + - `reStore.js` - Store persistence utilities + - `taskNavigation.js` - Task context handling on route changes + - `productionAdminActions.js` - Production admin operations (20KB) + - `useCountRecordAggregation.js`, `useCountRecordFilters.js`, `useCountRecordExport.js` - Counting features + - `useUncountedInventory.js`, `warehouse.js` - Inventory features + +**webapps/main/src/stores/:** +- Purpose: Pinia stores (modern state management) +- Contains: 4 files + - `task.js` - Task state (tasks array, activeTaskKey, loading) + - `config.js` - Configuration state + - `countSession.js` - Counting session state + - `taskType.js` - Task type definitions + +**webapps/main/src/store/:** +- Purpose: Vuex store (legacy state management, being phased out) +- Contains: Session, auth, user preferences +- Location: `store/` (separate from Pinia `stores/`) + +**webapps/main/src/router/:** +- Purpose: Vue Router definitions with role-based code splitting +- Contains: 11 files + - `index.js` - Main router setup, guards, permission checking + - `routes.js` - Route collection + - Feature-specific route files: + - `adminRoutes.js` - Admin features + - `productionRoutes.js` - Production features + - `warehouseRoutes.js` - Warehouse features + - `qualityRoutes.js`, `taskRoutes.js`, `traceabilityRoutes.js`, `operatorRoutes.js` + - `libraryRoutes.js` - Reference/library features + +**webapps/main/src/i18n/:** +- Purpose: Translation files for internationalization +- Contains: 5 files + - `en.js` - English translations (complete set) + - `it.js` - Italian translations (complete set) + - Used by router to detect locale and app to switch languages + +**webapps/main/src/boot/:** +- Purpose: Plugin initialization and boot modules +- Contains: 8 files + - `axios.js` - HTTP client setup with base URL, headers, interceptors + - `pinia.js` - Pinia store initialization + - `store.js` - Vuex store initialization + - `i18n.js` - i18n plugin setup + - `theme.js` - Theme initialization + - `filters.js` - Custom Vue filters + - `form.js` - Form plugin setup + +**db/migrations/:** +- Purpose: Database schema evolution +- Contains: Numbered AQL scripts (e.g., `226-process-steps-to-custom-fields.aql`) +- Pattern: Run sequentially during deployment; immutable once created +- Examples: Collection creation, edge definitions, data transformations + +**deploy/compose/:** +- Purpose: Docker Compose orchestration +- Contains: 12 files + - `base.yaml` - Core services (Traefik reverse proxy, API, ArangoDB, Kafka, media volumes) + - `dev.yaml` - Development overrides (source code mounts for hot-reload) + - `dev.debug.yaml` - Remote debugging setup (port mappings) + - `workflow.yaml` - Prefect server + PostgreSQL for orchestration + - `stack.yaml` - Production Swarm deployment config + - `tls.yaml` - HTTPS/TLS setup + - Domain-specific: `warehouse.yaml`, `integration.yaml`, `reporting.yaml` + +## Key File Locations + +**Entry Points:** +- `backend/api/main.py` - FastAPI app initialization, middleware, router registration +- `webapps/main/src/App.vue` - Vue 3 root component, router view +- `webapps/main/src/router/index.js` - Router initialization, auth guards +- `webapps/main/quasar.conf.js` - Quasar build configuration + +**Configuration:** +- `backend/api/utils/config.py` - Environment config loading +- `webapps/main/quasar.conf.js` - Build settings, dev server config +- `webapps/main/src/boot/*.js` - Plugin/library setup +- `deploy/compose/base.yaml` - Service definitions + +**Core Logic:** +- `backend/api/events/base_event.py` - Event-sourcing pattern +- `backend/api/utils/production.py` - Work order/job utilities (20KB) +- `backend/api/utils/dhr.py` - Large domain helper (44KB) +- `webapps/main/src/composables/event.js` - Event dispatching +- `webapps/main/src/composables/taskNavigation.js` - Task context handling + +**Testing:** +- `testing/` - Test files and fixtures +- Test location convention: Test files co-located with source (patterns suggest `.test.py` or `.spec.js` naming) + +## Naming Conventions + +**Files:** +- Python: snake_case (e.g., `production.py`, `base_event.py`, `kafka_producer.py`) +- Vue/JS: PascalCase for components (e.g., `TaskDialog.vue`, `ProductionJobTable.vue`), camelCase for JS modules (e.g., `eventbus.js`, `reStore.js`) +- Models: PascalCase class names, snake_case filenames (e.g., `models/production.py` contains `WorkOrder`, `Job` classes) +- Events: PascalCase with `Event` suffix (e.g., `TaskCreatedEvent`, `BatchCompletedEvent`) + +**Directories:** +- Feature-based (e.g., `production/`, `inventory/`, `collaboration/`) +- Utility grouping (e.g., `utils/`, `managers/`, `models/`) +- Layer-based (e.g., `endpoints/`, `events/`, `components/`, `views/`) + +**Classes:** +- Base classes: `Base` prefix or `Base` suffix (e.g., `BaseEvent`, `FlexModel`) +- Models: Domain name (e.g., `WorkOrder`, `Task`, `Issue`) +- Events: Domain action (e.g., `TaskCreatedEvent`, `JobStartedEvent`) +- Managers: Resource + `Manager` suffix (e.g., `WebsocketManager`, `KafkaConsumerManager`) + +**Functions:** +- camelCase in JavaScript (e.g., `sendEvent()`, `hasRoutePermission()`) +- snake_case in Python (e.g., `create_job_record()`, `_generate_counter()`) + +**Constants/Enums:** +- UPPER_SNAKE_CASE (e.g., `EventType.TASK_CREATED`, `BATCH_COMPLETED`) + +## Where to Add New Code + +**New Feature (Complete Feature):** +- **Primary code:** + - Backend event: `backend/api/events/[domain]/[action].py` + - Endpoint: `backend/api/endpoints/[domain].py` (add route to existing file) + - Model: `backend/api/models/[domain].py` (extend existing) +- **Tests:** + - `testing/[domain]_test.py` (or co-located with source) +- **Frontend:** + - Component: `webapps/main/src/components/[Feature][Component].vue` + - Composable: `webapps/main/src/composables/use[Feature].js` + - Store (Pinia): `webapps/main/src/stores/[feature].js` + - Route: `webapps/main/src/router/[featureArea]Routes.js` + - View: `webapps/main/src/views/[Feature]/` (folder with subcomponents) + +**New Component/Module:** +- **Implementation:** Create in appropriate `src/components/`, `src/composables/`, `src/utils/` +- **Usage:** Import in parent component or composable +- **Exporting:** Vue components exported implicitly via `