feat: Migrate to ultrathin monolith architecture

Consolidate 3 separate applications (reports-app, data-entry-app, telegram-bot) into a unified
architecture with single backend and frontend:

Backend Changes:
- Unified FastAPI backend at backend/ with modular structure
- Modules: reports, data_entry, telegram in backend/modules/
- Centralized config.py and main.py with all routers registered
- Single worker mode (--workers 1) for Telegram bot compatibility
- Shared Oracle connection pool and JWT authentication
- Unified requirements.txt and environment configuration

Frontend Changes:
- Single Vue.js SPA with module-based routing
- Unified frontend at src/ with modules in src/modules/{reports,data-entry}/
- Shared components and stores in src/shared/
- Error boundaries for module isolation
- Dual API proxy in Vite for module communication

Infrastructure:
- New unified startup scripts: start-prod.sh, start-test.sh, start-backend.sh
- Environment templates: .env.dev.example, .env.test.example, .env.prod.example
- Updated deployment scripts for Windows IIS
- Simplified SSH tunnel management

Documentation:
- Comprehensive CLAUDE.md with architecture overview
- Module-specific docs in docs/{data-entry,telegram}/
- Architecture decision records in docs/ARCHITECTURE-DECISIONS.md
- Deployment guides consolidated in deployment/windows/docs/

This migration reduces complexity, improves maintainability, and enables easier
deployment while maintaining all existing functionality.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-29 23:48:14 +02:00
parent 2a101f1ef5
commit c5e051ad80
378 changed files with 7566 additions and 73730 deletions

View File

@@ -1,535 +0,0 @@
# Feature: Ultrathin Monolith Backend Architecture
## Overview
Transform ROA2WEB from 3 separate backend services (reports-app:8001, data-entry-app:8003, telegram-bot:8002) into a single unified backend process running on port 8000. This architectural transformation simplifies deployment, centralizes logs, and reduces operational complexity for solo developer workflow while maintaining clear module boundaries.
## Problem Statement
**Current Pain Points:**
- Running 3 separate backend processes is complex to manage (start/stop/monitor)
- Windows deployment requires 3 NSSM services, significantly increasing deployment time
- Debugging is difficult with fragmented logs across multiple processes
- Resource overhead of multiple Python processes and connection pools
- Frontend already unified into single SPA, but backend remains fragmented
**Who Benefits:**
- Solo developer: Easier development workflow, simplified debugging
- Windows deployment: Single service instead of 3 (faster deployment)
- System resources: Single Oracle pool, single process overhead
## User Stories
- As a developer, I want to start the entire backend with a single command (`python main.py`) so that I can begin working faster
- As a developer, I want centralized logs in a single stream so that I can debug issues across all modules more easily
- As a deployer, I want to install a single Windows service so that deployment takes less time
- As a system administrator, I want a single backend process so that resource usage is more efficient
- As a developer, I want to keep separate module directories (reports/, data-entry/, telegram-bot/) so that code organization remains clear
## Functional Requirements
### Core Requirements
1. **Single Entry Point**
- One `main.py` file at project root (`/backend/main.py`)
- Single FastAPI application instance
- Single uvicorn process running on port 8000
2. **Module Prefix Routing**
- Reports endpoints: `/api/reports/*` (e.g., `/api/reports/invoices`, `/api/reports/dashboard`)
- Data Entry endpoints: `/api/data-entry/*` (e.g., `/api/data-entry/receipts`, `/api/data-entry/ocr`)
- Telegram endpoints: `/api/telegram/*` (e.g., `/api/telegram/auth/verify-user`)
- Shared endpoints: `/api/auth/*`, `/api/companies`, `/api/calendar` (no prefix change)
3. **Integrated Telegram Bot**
- Telegram bot runs in same process (background thread/task)
- Internal API endpoints accessible via `/api/telegram/*`
- Shared database access (no separate SQLite for bot)
4. **Unified Startup/Shutdown**
- Single lifespan manager initializing all modules
- Parallel initialization where possible (Oracle pool + PaddleOCR)
- Graceful shutdown for all components
- Centralized logging configuration
5. **Module Directory Structure**
- Keep existing directories: `backend/modules/reports/`, `backend/modules/data-entry/`, `backend/modules/telegram/`
- Each module retains its own routers, services, models
- Shared code remains in `shared/` (auth, database, routes)
### Secondary Requirements
1. **Environment Variable Consolidation**
- Single `.env` file at `backend/.env`
- Merge variables from all 3 backends
- Namespace conflicts resolved (e.g., `REPORTS_*`, `DATA_ENTRY_*` prefixes)
2. **Single Virtual Environment**
- Merged `requirements.txt` with all dependencies
- De-duplicated dependencies (single version of FastAPI, etc.)
- Optional dependency groups for OCR/Telegram
3. **Health Check Aggregation**
- Single `/health` endpoint reporting status of all modules
- Check Oracle connection, SQLite database, Telegram bot status
- Return comprehensive health information
4. **Code Cleanup**
- Remove duplicate auth router implementations (use shared router factory)
- Remove duplicate company/calendar router implementations
- Consolidate logging configuration
- Remove unused imports and code
## Technical Requirements
### Files to Create
| File | Purpose |
|------|---------|
| `/backend/main.py` | Single unified entry point - creates FastAPI app, registers all module routers, manages lifecycle |
| `/backend/config.py` | Unified configuration management (merges settings from all apps) |
| `/backend/requirements.txt` | Consolidated dependencies from all 3 backends |
| `/backend/.env.example` | Merged environment variables template |
| `/backend/modules/__init__.py` | Module package marker |
| `/backend/modules/reports/__init__.py` | Reports module package |
| `/backend/modules/data-entry/__init__.py` | Data entry module package |
| `/backend/modules/telegram/__init__.py` | Telegram module package |
### Files to Modify
| File | Changes |
|------|---------|
| `reports-app/backend/app/routers/*.py` | Move to `backend/modules/reports/routers/` |
| `reports-app/backend/app/services/*.py` | Move to `backend/modules/reports/services/` |
| `reports-app/backend/app/models/*.py` | Move to `backend/modules/reports/models/` |
| `reports-app/backend/app/cache/**/*.py` | Move to `backend/modules/reports/cache/` (reports-specific caching) |
| `data-entry-app/backend/app/routers/*.py` | Move to `backend/modules/data-entry/routers/` |
| `data-entry-app/backend/app/services/*.py` | Move to `backend/modules/data-entry/services/` |
| `data-entry-app/backend/app/db/**/*.py` | Move to `backend/modules/data-entry/db/` |
| `data-entry-app/backend/migrations/` | Move to `backend/modules/data-entry/migrations/` |
| `reports-app/telegram-bot/app/bot/*.py` | Move to `backend/modules/telegram/bot/` |
| `reports-app/telegram-bot/app/db/*.py` | Move to `backend/modules/telegram/db/` |
| `reports-app/telegram-bot/app/internal_api.py` | Integrate into main FastAPI app as router |
| All router files | Update imports to reflect new paths |
| `vite.config.js` | Update proxy configuration to single backend (port 8000) |
| `public/web.config` (IIS) | Update proxy rules to single backend (port 8000) |
### New Directory Structure
```
roa2web/
├── backend/ # UNIFIED BACKEND
│ ├── main.py # Single entry point
│ ├── config.py # Unified configuration
│ ├── requirements.txt # Merged dependencies
│ ├── .env # Merged environment variables
│ ├── .env.example # Environment template
│ ├── venv/ # Single virtual environment
│ │
│ ├── modules/ # Module-specific code
│ │ ├── __init__.py
│ │ │
│ │ ├── reports/ # Reports module (from reports-app)
│ │ │ ├── __init__.py
│ │ │ ├── routers/ # API endpoints (invoices, dashboard, treasury, etc.)
│ │ │ ├── services/ # Business logic
│ │ │ ├── models/ # Pydantic models
│ │ │ ├── schemas/ # Response schemas
│ │ │ └── cache/ # Caching system (L1+L2)
│ │ │
│ │ ├── data-entry/ # Data entry module (from data-entry-app)
│ │ │ ├── __init__.py
│ │ │ ├── routers/ # Receipts, OCR, nomenclature routers
│ │ │ ├── services/ # Business logic + OCR service
│ │ │ ├── db/ # SQLModel models + CRUD
│ │ │ ├── schemas/ # Pydantic schemas
│ │ │ └── migrations/ # Alembic migrations
│ │ │
│ │ └── telegram/ # Telegram bot module (from telegram-bot)
│ │ ├── __init__.py
│ │ ├── bot/ # Command handlers, formatters
│ │ ├── db/ # Bot-specific database (auth codes, sessions)
│ │ └── routers/ # Internal API endpoints (auth code management)
│ │
│ └── data/ # Data files
│ ├── cache/ # SQLite cache files (reports module)
│ ├── receipts/ # SQLite DB + uploads (data-entry module)
│ └── telegram/ # SQLite DB for bot (telegram module)
├── shared/ # Shared components (unchanged)
│ ├── auth/ # JWT authentication
│ ├── database/ # Oracle pool
│ ├── routes/ # Shared router factories
│ └── frontend/ # Shared Vue components
├── frontend/ # Unified frontend (unchanged structure)
│ ├── src/
│ │ ├── modules/
│ │ │ ├── reports/
│ │ │ └── data-entry/
│ │ └── shared/
│ └── vite.config.js # UPDATE: Single proxy to localhost:8000
├── deployment/ # Deployment scripts
│ └── windows/ # Windows deployment
│ └── install-service.ps1 # UPDATE: Single NSSM service
└── docs/ # Documentation
```
### Dependencies Consolidation
**Common Dependencies** (deduplicated):
```
fastapi>=0.109.0
uvicorn[standard]>=0.27.0
pydantic>=2.5.3
python-dotenv>=1.0.0
PyJWT>=2.8.0
python-jose[cryptography]>=3.3.0
oracledb>=2.0.1
aiosqlite>=0.19.0
httpx>=0.27.0
python-multipart>=0.0.6
```
**Reports-Specific**:
```
openpyxl>=3.1.0 # Excel export
fpdf2>=2.7.0 # PDF generation
python-dateutil>=2.8.2 # Date utilities
```
**Data Entry-Specific**:
```
sqlmodel>=0.0.14 # ORM
alembic>=1.13.1 # Migrations
aiofiles>=23.2.1 # Async file handling
Pillow>=10.2.0 # Image processing
paddleocr>=2.7.0 # OCR engine
paddlepaddle>=2.5.0 # PaddleOCR backend
opencv-python>=4.8.0 # Image processing
pytesseract>=0.3.10 # Tesseract OCR
pdf2image>=1.16.0 # PDF to image conversion
numpy>=1.24.0 # Array operations
```
**Telegram-Specific**:
```
python-telegram-bot>=20.7 # Telegram bot SDK
aiosmtplib>=3.0.0 # Email (2FA)
sentry-sdk>=1.40.0 # Monitoring (optional)
```
### Database Changes
**No schema changes** - databases remain separate:
- Oracle: Shared via `oracle_pool` (reports + data-entry nomenclatures + auth)
- SQLite (`receipts.db`): Data entry module receipts data
- SQLite (`cache.db`): Reports module caching
- SQLite (`telegram.db`): Telegram bot auth codes and sessions
**Database Access Patterns**:
- Oracle Pool: Single shared instance initialized at startup, used by all modules
- SQLite databases: Separate per module, stored in `backend/data/`
### API Changes
**URL Migration** (frontend must update):
| Old URL | New URL | Module |
|---------|---------|--------|
| `http://localhost:8001/api/invoices` | `http://localhost:8000/api/reports/invoices` | Reports |
| `http://localhost:8001/api/dashboard` | `http://localhost:8000/api/reports/dashboard` | Reports |
| `http://localhost:8001/api/treasury` | `http://localhost:8000/api/reports/treasury` | Reports |
| `http://localhost:8001/api/trial-balance` | `http://localhost:8000/api/reports/trial-balance` | Reports |
| `http://localhost:8001/api/cache/*` | `http://localhost:8000/api/reports/cache/*` | Reports |
| `http://localhost:8003/api/receipts` | `http://localhost:8000/api/data-entry/receipts` | Data Entry |
| `http://localhost:8003/api/ocr` | `http://localhost:8000/api/data-entry/ocr` | Data Entry |
| `http://localhost:8003/api/nomenclature` | `http://localhost:8000/api/data-entry/nomenclature` | Data Entry |
| `http://localhost:8002/api/telegram/*` | `http://localhost:8000/api/telegram/*` | Telegram |
| `http://localhost:8001/api/auth/login` | `http://localhost:8000/api/auth/login` | Shared (no change) |
| `http://localhost:8001/api/companies` | `http://localhost:8000/api/companies` | Shared (no change) |
| `http://localhost:8001/api/calendar` | `http://localhost:8000/api/calendar` | Shared (no change) |
**Frontend Configuration Updates**:
```javascript
// vite.config.js - BEFORE (3 proxies)
proxy: {
'/api/reports': { target: 'http://localhost:8001', rewrite: (path) => path.replace(/^\/api\/reports/, '/api') },
'/api/data-entry': { target: 'http://localhost:8003', rewrite: (path) => path.replace(/^\/api\/data-entry/, '/api') },
'/api/telegram': { target: 'http://localhost:8002', rewrite: (path) => path.replace(/^\/api\/telegram/, '/api') }
}
// vite.config.js - AFTER (1 proxy)
proxy: {
'/api': { target: 'http://localhost:8000', changeOrigin: true }
}
```
```xml
<!-- public/web.config - BEFORE (3 rules) -->
<rule name="Proxy Reports API" stopProcessing="true">
<match url="^api/reports/(.*)" />
<action type="Rewrite" url="http://localhost:8001/api/{R:1}" />
</rule>
<rule name="Proxy Data Entry API" stopProcessing="true">
<match url="^api/data-entry/(.*)" />
<action type="Rewrite" url="http://localhost:8003/api/{R:1}" />
</rule>
<rule name="Proxy Telegram API" stopProcessing="true">
<match url="^api/telegram/(.*)" />
<action type="Rewrite" url="http://localhost:8002/api/{R:1}" />
</rule>
<!-- public/web.config - AFTER (1 rule) -->
<rule name="Proxy Backend API" stopProcessing="true">
<match url="^api/(.*)" />
<action type="Rewrite" url="http://localhost:8000/api/{R:1}" />
</rule>
```
## Design Decisions
### Approach: Module-Based Monolith with Clear Boundaries
**Why This Approach:**
1. **Maintains Module Isolation**: Each module (reports, data-entry, telegram) keeps its own directory structure
2. **Simplifies Deployment**: Single process, single service, single log stream
3. **Preserves Code Organization**: Module boundaries remain clear in file structure
4. **Enables Gradual Migration**: Can move one module at a time
5. **Reduces Complexity**: Solo developer doesn't need microservices orchestration
**Key Architectural Patterns:**
- **Single FastAPI App**: One application instance with multiple routers registered with prefixes
- **Module Routers**: Each module exports a function that returns its configured router
- **Parallel Initialization**: Oracle pool and PaddleOCR load concurrently at startup
- **Unified Logging**: Single logging configuration with module-specific loggers
- **Shared Singleton**: Oracle pool shared across all modules
### Alternatives Considered
**Alternative 1: Keep Microservices Architecture**
- **Rejected**: Adds complexity without benefits for solo developer
- **Rejected**: Windows deployment remains slow (3 services)
- **Rejected**: Debugging remains difficult (fragmented logs)
**Alternative 2: Merge Everything into Flat Structure**
- **Rejected**: Loses module boundaries, code becomes harder to navigate
- **Rejected**: Difficult to understand which code belongs to which feature
**Alternative 3: Use Docker Compose for Orchestration**
- **Rejected**: Adds Docker overhead without solving core issues
- **Rejected**: Windows deployment still needs Docker Desktop or manual setup
- **Rejected**: Doesn't simplify solo developer workflow
## Acceptance Criteria
- [ ] Single `python backend/main.py` command starts entire backend
- [ ] All endpoints accessible on port 8000 with module prefixes (`/api/reports/*`, `/api/data-entry/*`, `/api/telegram/*`)
- [ ] Telegram bot runs in same process (background task), receives/sends messages
- [ ] Oracle pool initialized once, shared across all modules
- [ ] PaddleOCR loads in parallel with Oracle pool at startup (non-blocking)
- [ ] All logs appear in single console stream with module prefixes
- [ ] `/health` endpoint returns comprehensive status (Oracle, SQLite, Telegram bot)
- [ ] Frontend can access all functionality through unified backend
- [ ] Windows deployment requires only 1 NSSM service (not 3)
- [ ] All existing tests pass after migration
- [ ] Startup script simplified to single command (no parallel process management)
- [ ] Development mode: `uvicorn backend.main:app --reload` auto-reloads on code changes
- [ ] Module directories clearly separated (`modules/reports/`, `modules/data-entry/`, `modules/telegram/`)
## Out of Scope
**Explicitly NOT Included in This Transformation:**
- ❌ Frontend code changes (only configuration updates: vite.config.js, web.config)
- ❌ Business logic modifications (pure architectural refactoring)
- ❌ Database schema changes (no migrations needed)
- ❌ Authentication system changes (JWT logic stays same)
- ❌ API contract changes (same endpoints, just different base URL)
- ❌ Oracle database migration (stays on Oracle)
- ❌ SQLite schema changes (data-entry and telegram databases unchanged)
- ❌ UI/UX modifications (frontend functionality stays identical)
- ❌ Performance optimizations (beyond parallel initialization)
- ❌ New features (pure consolidation work)
## Risks and Mitigations
| Risk | Likelihood | Impact | Mitigation |
|------|------------|--------|------------|
| Import path issues after moving files | High | Medium | Use absolute imports with module prefixes (`from backend.modules.reports.services import ...`), update all imports systematically |
| Oracle pool initialization delays startup | Medium | Low | Use parallel initialization (Oracle + PaddleOCR concurrently), add timeout handling |
| Telegram bot blocks main thread | Medium | High | Run bot in background thread with `asyncio.create_task()` or `threading.Thread(daemon=True)` |
| PaddleOCR memory usage in same process | Low | Medium | Keep background initialization, monitor memory usage, add configuration to disable OCR if needed |
| Port 8000 conflicts with existing service | Low | Low | Make port configurable via environment variable, document port change |
| Frontend cache issues with URL changes | Medium | Low | Clear browser cache, document URL changes, use cache-busting headers |
| Windows service migration breaks existing deployment | Medium | High | Create new service name (`ROA2WEB-Unified`), test thoroughly before removing old services, document rollback procedure |
| Circular imports between modules | Low | Medium | Keep module dependencies one-way (reports/data-entry/telegram should not import each other), use shared code for common functionality |
| Environment variable conflicts | Low | Medium | Use namespaced prefixes (`REPORTS_*`, `DATA_ENTRY_*`, `TELEGRAM_*`), document all variables in `.env.example` |
| Lost logs during migration | Low | High | Keep old logs in archive, test logging thoroughly in dev environment first |
## Open Questions
1. **Telegram Bot Threading**: Should we use `asyncio.create_task()` (async) or `threading.Thread()` (sync) for Telegram bot polling?
- **Recommendation**: Use `asyncio.create_task()` to stay in async context, avoid GIL issues
2. **Module Import Strategy**: Should modules import from each other, or only through shared code?
- **Recommendation**: NO cross-module imports (reports ↔ data-entry ↔ telegram), only via `shared/`
3. **Health Check Depth**: How detailed should `/health` endpoint be (simple up/down vs full diagnostics)?
- **Recommendation**: Return dict with per-module status, keep fast (<500ms)
4. **Backward Compatibility**: Should we support old URLs temporarily (redirect 80018000)?
- **Recommendation**: NO - clean break, update frontend configuration once
5. **Development vs Production Config**: Should we have separate startup modes?
- **Recommendation**: Use environment variables (`ENV=development|production`), single entry point
6. **Migration Strategy**: Big bang (all at once) or incremental (one module at a time)?
- **Recommendation**: Big bang - easier to test, cleaner migration, no production deployment yet
7. **Logging Format**: Should we prefix all log messages with module name `[REPORTS]`, `[DATA-ENTRY]`, `[TELEGRAM]`?
- **Recommendation**: YES - use Python logging with module-specific loggers
## Estimated Complexity
**HIGH** - Major architectural transformation requiring:
**Justification:**
- Moving and reorganizing ~50+ files across 3 backends
- Updating ~200+ import statements
- Merging 3 separate lifecycle managers into one
- Integrating Telegram bot from separate process into main app
- Testing all functionality after migration
- Updating deployment scripts and documentation
- Ensuring no regressions across all modules
**Estimated Effort:**
- File reorganization: 4-6 hours
- Import path updates: 3-4 hours
- Unified main.py + lifecycle: 3-4 hours
- Telegram bot integration: 2-3 hours
- Testing (manual + automated): 4-6 hours
- Frontend configuration updates: 1-2 hours
- Deployment script updates: 2-3 hours
- Documentation updates: 2-3 hours
- **Total: 21-31 hours (~3-4 working days)**
**Recommended Approach:**
1. Create new structure, copy files (don't delete old ones yet)
2. Update imports module by module
3. Test each module independently
4. Integrate Telegram bot last
5. Full integration testing
6. Update frontend configuration
7. Archive old backend directories after verification
## Implementation Notes
### Startup Sequence
```python
# backend/main.py - Startup lifespan
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Unified startup/shutdown for all modules"""
# 1. Initialize logging
setup_logging()
# 2. Parallel initialization (Oracle + PaddleOCR)
await asyncio.gather(
init_oracle_pool(),
init_paddle_ocr(), # Background initialization
init_data_entry_db(),
init_telegram_db()
)
# 3. Initialize module-specific components
await init_reports_cache()
# 4. Start Telegram bot (background task)
telegram_task = asyncio.create_task(run_telegram_bot())
logger.info("🚀 ROA2WEB Unified Backend started on port 8000")
yield
# Shutdown
telegram_task.cancel()
await close_all_resources()
```
### Router Registration Pattern
```python
# backend/main.py - Router registration
from modules.reports.routers import create_reports_router
from modules.data_entry.routers import create_data_entry_router
from modules.telegram.routers import create_telegram_router
# Register module routers with prefixes
app.include_router(create_reports_router(), prefix="/api/reports", tags=["reports"])
app.include_router(create_data_entry_router(), prefix="/api/data-entry", tags=["data-entry"])
app.include_router(create_telegram_router(), prefix="/api/telegram", tags=["telegram"])
# Register shared routers (no prefix)
app.include_router(auth_router, prefix="/api/auth", tags=["auth"])
app.include_router(companies_router, prefix="/api/companies", tags=["companies"])
app.include_router(calendar_router, prefix="/api/calendar", tags=["calendar"])
```
### Module Router Factory Pattern
```python
# backend/modules/reports/routers/__init__.py
from fastapi import APIRouter
from .invoices import router as invoices_router
from .dashboard import router as dashboard_router
from .treasury import router as treasury_router
# ... other routers
def create_reports_router() -> APIRouter:
"""Create and configure reports module router"""
router = APIRouter()
# Include all sub-routers (no prefix - already in main.py)
router.include_router(invoices_router, prefix="/invoices")
router.include_router(dashboard_router, prefix="/dashboard")
router.include_router(treasury_router, prefix="/treasury")
# ... other routers
return router
```
### Critical Files List
**Top 10 Files That Will Be Affected:**
1. `/backend/main.py` - **NEW** - Single entry point, replaces 3 main.py files
2. `/backend/config.py` - **NEW** - Unified configuration
3. `/frontend/vite.config.js` - Update proxy configuration
4. `/frontend/public/web.config` - Update IIS rewrite rules
5. `reports-app/backend/app/main.py` - Move logic to unified main.py
6. `data-entry-app/backend/app/main.py` - Move logic to unified main.py
7. `reports-app/telegram-bot/app/main.py` - Move logic to unified main.py
8. `shared/database/oracle_pool.py` - Ensure singleton pattern for shared pool
9. `/deployment/windows/install-service.ps1` - Update to install single service
10. `/start-dev.sh` - Simplify to start single backend process
**Additional Critical Files:**
- All router files in `reports-app/backend/app/routers/` (~10 files)
- All router files in `data-entry-app/backend/app/routers/` (~4 files)
- Telegram bot handlers in `reports-app/telegram-bot/app/bot/handlers.py`
- Cache system in `reports-app/backend/app/cache/` (~9 files)
- OCR service in `data-entry-app/backend/app/services/ocr_service.py`
- Database models in `data-entry-app/backend/app/db/`
---
**Document Version**: 1.0
**Created**: 2025-12-24
**Author**: Auto-Build System
**Status**: Draft - Ready for Review

View File

@@ -1,121 +0,0 @@
{
"feature": "ultrathin-monolith",
"status": "spec_created",
"created_at": "2025-12-24T00:00:00Z",
"updated_at": "2025-12-24T00:00:00Z",
"spec_version": "1.0",
"complexity": "high",
"estimated_hours": "21-31",
"estimated_days": "3-4",
"key_changes": [
"Single backend entry point (backend/main.py) replacing 3 separate main.py files",
"Module-based directory structure (backend/modules/reports, backend/modules/data-entry, backend/modules/telegram)",
"API URL changes with module prefixes (/api/reports/*, /api/data-entry/*, /api/telegram/*)",
"Telegram bot integrated into main process (background task)",
"Parallel initialization (Oracle pool + PaddleOCR)",
"Unified logging with module prefixes",
"Single virtual environment with merged dependencies",
"Single Windows service for deployment (instead of 3)"
],
"modules_affected": [
"reports-app/backend",
"data-entry-app/backend",
"reports-app/telegram-bot",
"frontend (vite.config.js, web.config)",
"shared/database",
"shared/auth",
"deployment/windows"
],
"files_to_create": [
"/backend/main.py",
"/backend/config.py",
"/backend/requirements.txt",
"/backend/.env.example",
"/backend/modules/__init__.py",
"/backend/modules/reports/__init__.py",
"/backend/modules/data-entry/__init__.py",
"/backend/modules/telegram/__init__.py"
],
"files_to_move": [
"reports-app/backend/app/routers/* -> backend/modules/reports/routers/",
"reports-app/backend/app/services/* -> backend/modules/reports/services/",
"reports-app/backend/app/models/* -> backend/modules/reports/models/",
"reports-app/backend/app/cache/* -> backend/modules/reports/cache/",
"data-entry-app/backend/app/routers/* -> backend/modules/data-entry/routers/",
"data-entry-app/backend/app/services/* -> backend/modules/data-entry/services/",
"data-entry-app/backend/app/db/* -> backend/modules/data-entry/db/",
"data-entry-app/backend/migrations/* -> backend/modules/data-entry/migrations/",
"reports-app/telegram-bot/app/bot/* -> backend/modules/telegram/bot/",
"reports-app/telegram-bot/app/db/* -> backend/modules/telegram/db/"
],
"critical_files": [
"/backend/main.py (NEW - single entry point)",
"/backend/config.py (NEW - unified configuration)",
"/frontend/vite.config.js (UPDATE - single proxy)",
"/frontend/public/web.config (UPDATE - single IIS rule)",
"reports-app/backend/app/main.py (MIGRATE to unified)",
"data-entry-app/backend/app/main.py (MIGRATE to unified)",
"reports-app/telegram-bot/app/main.py (MIGRATE to unified)",
"shared/database/oracle_pool.py (VERIFY singleton)",
"/deployment/windows/install-service.ps1 (UPDATE single service)",
"/start-dev.sh (SIMPLIFY single process)"
],
"risks": [
{
"risk": "Import path issues after moving files",
"likelihood": "high",
"impact": "medium",
"mitigation": "Use absolute imports, update systematically"
},
{
"risk": "Telegram bot blocks main thread",
"likelihood": "medium",
"impact": "high",
"mitigation": "Run in background task with asyncio.create_task()"
},
{
"risk": "Windows service migration breaks deployment",
"likelihood": "medium",
"impact": "high",
"mitigation": "Create new service, test thoroughly, document rollback"
},
{
"risk": "Frontend cache issues with URL changes",
"likelihood": "medium",
"impact": "low",
"mitigation": "Clear browser cache, cache-busting headers"
}
],
"acceptance_criteria_count": 14,
"out_of_scope_count": 10,
"dependencies": [
"Frontend unified app (already completed)",
"SSH tunnel (unchanged)",
"Oracle database (unchanged)",
"Shared modules (auth, database, routes) - unchanged"
],
"testing_strategy": [
"Module-by-module verification during migration",
"Integration testing after all modules migrated",
"Frontend connectivity testing",
"Telegram bot functionality testing",
"Performance testing (startup time, memory usage)",
"Windows deployment testing"
],
"migration_approach": "big_bang",
"migration_notes": "Create new structure alongside old, copy files, update imports, test thoroughly, then archive old directories after verification",
"next_steps": [
"Review and approve specification",
"Create backend/ directory structure",
"Copy files to new structure (keep old as backup)",
"Update imports module by module",
"Create unified main.py",
"Test module routers independently",
"Integrate Telegram bot",
"Update frontend configuration",
"Full integration testing",
"Update deployment scripts",
"Update documentation",
"Archive old backend directories"
]
}

View File

@@ -1,406 +0,0 @@
# Unified App Migration Checklist
**Track your progress** as you implement the unified app.
---
## Phase 1: Project Setup (0.5 days)
### Directory Structure
- [ ] Create directory structure in root (`/mnt/e/proiecte/roa2web/`)
- [ ] Create `src/` subdirectories:
- [ ] `src/modules/reports/views/`
- [ ] `src/modules/reports/stores/`
- [ ] `src/modules/reports/services/`
- [ ] `src/modules/data-entry/views/receipts/`
- [ ] `src/modules/data-entry/components/ocr/`
- [ ] `src/modules/data-entry/stores/`
- [ ] `src/modules/data-entry/services/`
- [ ] `src/shared/components/`
- [ ] `src/shared/stores/`
- [ ] `src/shared/styles/`
- [ ] `src/config/`
- [ ] `src/router/`
- [ ] `src/assets/css/`
### Core Configuration Files
- [ ] Create `package.json` (merge dependencies from both apps)
- [ ] Create `vite.config.js` (dual proxy + lazy loading)
- [ ] Create `src/main.js` (PrimeVue setup)
- [ ] Create `.env.example` (environment variables)
- [ ] Create `.gitignore`
- [ ] Create `README.md`
### Copy Shared Resources
- [ ] Copy `shared/frontend/components/``src/shared/components/`
- [ ] Copy `shared/frontend/stores/``src/shared/stores/`
- [ ] Copy `shared/frontend/styles/``src/shared/styles/`
- [ ] Copy `reports-app/frontend/src/assets/css/``src/assets/css/`
### Verification
- [ ] Run `npm install` - succeeds
- [ ] Run `npm run dev` - starts on port 3000
- [ ] No console errors
---
## Phase 2: Module Migration (1 day)
### Reports Module - Views
- [ ] Copy `DashboardView.vue``src/modules/reports/views/`
- [ ] Copy `InvoicesView.vue``src/modules/reports/views/`
- [ ] Copy `BankCashRegisterView.vue``src/modules/reports/views/`
- [ ] Copy `TrialBalanceView.vue``src/modules/reports/views/`
- [ ] Copy `TelegramView.vue``src/modules/reports/views/`
- [ ] Copy `CacheStatsView.vue``src/modules/reports/views/`
- [ ] Update imports in all views (if needed)
### Reports Module - Stores
- [ ] Copy `dashboard.js``src/modules/reports/stores/`
- [ ] Copy `invoices.js``src/modules/reports/stores/`
- [ ] Copy `treasury.js``src/modules/reports/stores/`
- [ ] Copy `trialBalance.js``src/modules/reports/stores/`
- [ ] Copy `cacheStore.js``src/modules/reports/stores/`
- [ ] Update imports in all stores (if needed)
### Reports Module - Services
- [ ] Copy `api.js``src/modules/reports/services/` (in root)
- [ ] Update base URL to `/api/reports/` in api.js
- [ ] Test API calls route to localhost:8001
### Data Entry Module - Views
- [ ] Copy `ReceiptsListView.vue``src/modules/data-entry/views/receipts/`
- [ ] Copy `ReceiptCreateView.vue``src/modules/data-entry/views/receipts/`
- [ ] Update imports in views (if needed)
### Data Entry Module - Components
- [ ] Copy `OCRUploadZone.vue``src/modules/data-entry/components/ocr/`
- [ ] Copy `OCRPreview.vue``src/modules/data-entry/components/ocr/`
- [ ] Copy `OCRConfidenceIndicator.vue``src/modules/data-entry/components/ocr/`
- [ ] Update imports in components (if needed)
### Data Entry Module - Stores
- [ ] Copy `receiptsStore.js``src/modules/data-entry/stores/`
- [ ] Update imports in store (if needed)
### Data Entry Module - Services
- [ ] Copy `api.js``src/modules/data-entry/services/` (in root)
- [ ] Update base URL to `/api/data-entry/` in api.js
- [ ] Test API calls route to localhost:8003
### CSS Merge
- [ ] Review `data-entry-app/frontend/src/assets/css/main.css`
- [ ] Merge unique styles into `src/assets/css/` (in root)
- [ ] Resolve any style conflicts
- [ ] Test responsive design
### Verification
- [ ] All Reports views render without errors
- [ ] All Data Entry views render without errors
- [ ] No import errors in console
- [ ] CSS loads correctly
- [ ] No style conflicts
---
## Phase 3: Routing & Navigation (0.5 days)
### Router Configuration
- [ ] Create `src/router/index.js` (in root)
- [ ] Add `/login` route (eager loaded)
- [ ] Add `/reports/*` routes (lazy loaded)
- [ ] Add `/data-entry/*` routes (lazy loaded)
- [ ] Add redirect `/``/reports/dashboard`
- [ ] Add authentication guard
- [ ] Add 404 handling
- [ ] Test all routes work
### Menu Configuration
- [ ] Create `src/config/menu.js` (in root)
- [ ] Define "Rapoarte" section
- [ ] Define "Introduceri Date" section
- [ ] Define "Sistem" section
- [ ] Export menu configuration
### Feature Flags
- [ ] Create `src/config/features.js` (in root)
- [ ] Add reports.enabled flag
- [ ] Add dataEntry.enabled flag
- [ ] Add module-level flags
- [ ] Export isFeatureEnabled function
### Root Component
- [ ] Create `src/App.vue` (in root)
- [ ] Integrate AppHeader with unified menu
- [ ] Integrate SlideMenu with menu sections
- [ ] Add router-view
- [ ] Add Toast and ConfirmDialog
- [ ] Test menu navigation
### Verification
- [ ] Can navigate to all routes
- [ ] Menu highlights active route
- [ ] Authentication guard works
- [ ] Login redirects to dashboard
- [ ] 404 redirects work
---
## Phase 4: Error Boundaries & Resilience (0.25 days)
### Error Boundary Component
- [ ] Create `src/shared/components/ErrorBoundary.vue` (in root)
- [ ] Implement onErrorCaptured hook
- [ ] Add user-friendly error display
- [ ] Add retry functionality
- [ ] Add navigate away option
- [ ] Test with intentional error
### Module Layouts
- [ ] Create `src/modules/reports/ReportsLayout.vue` (in root)
- [ ] Wrap with ErrorBoundary component
- [ ] Create `src/modules/data-entry/DataEntryLayout.vue` (in root)
- [ ] Wrap with ErrorBoundary component
### Error Isolation Testing
- [ ] Introduce error in Reports module
- [ ] Verify Data Entry still works
- [ ] Introduce error in Data Entry module
- [ ] Verify Reports still works
- [ ] Test retry functionality
- [ ] Test navigate away functionality
### Feature Flags Testing
- [ ] Disable Reports module
- [ ] Verify menu items hidden
- [ ] Disable Data Entry module
- [ ] Verify menu items hidden
- [ ] Re-enable all modules
### Loading States
- [ ] Add loading spinner for lazy routes
- [ ] Test module switching loading
- [ ] Add skeleton screens (optional)
### Verification
- [ ] Error boundary catches component errors
- [ ] User sees friendly error message
- [ ] Can retry or navigate away
- [ ] Module isolation works (error in one doesn't crash other)
- [ ] Feature flags work
---
## Phase 5: Build & Deploy (0.25 days)
### Production Build
- [ ] Run `npm run build`
- [ ] Build succeeds without errors
- [ ] Check `dist/` output
- [ ] Verify chunks created:
- [ ] vendor-core.[hash].js
- [ ] vendor-primevue.[hash].js
- [ ] vendor-utils.[hash].js
- [ ] reports.[hash].js (lazy)
- [ ] data-entry.[hash].js (lazy)
- [ ] main.[hash].js
- [ ] main.[hash].css
### Bundle Analysis
- [ ] Install `rollup-plugin-visualizer`
- [ ] Analyze bundle sizes
- [ ] Verify total size ≤ sum of current apps
- [ ] Check for duplicate dependencies
### Local Preview
- [ ] Run `npm run preview`
- [ ] Test all routes work
- [ ] Test API calls work
- [ ] Test error boundaries
- [ ] Test lazy loading
### IIS Configuration
- [ ] Create `web.config` (in root) with URL rewrite rules
- [ ] Add SPA routing rule (all → index.html)
- [ ] Add proxy rule: `/api/reports/*``http://localhost:8001/api/*`
- [ ] Add proxy rule: `/api/data-entry/*``http://localhost:8003/api/*`
- [ ] Add proxy rule: `/uploads/*``http://localhost:8003/uploads/*`
### Staging Deployment
- [ ] Deploy to staging IIS site
- [ ] Test all routes
- [ ] Test API calls
- [ ] Test error boundaries
- [ ] Test on different browsers
- [ ] Test on mobile devices
### Production Deployment
- [ ] Backup current IIS configuration
- [ ] Backup current builds
- [ ] Deploy unified app
- [ ] Test all routes
- [ ] Test API calls
- [ ] Monitor error logs
### Verification
- [ ] Build succeeds
- [ ] Chunks split correctly
- [ ] IIS deployment works
- [ ] API routing correct
- [ ] All features work in production
---
## Testing Checklist
### Manual Testing
- [ ] Login flow works
- [ ] Navigate to all Reports views
- [ ] Navigate to all Data Entry views
- [ ] Switch between modules
- [ ] Test company selector
- [ ] Test period selector
- [ ] Test logout
- [ ] Test on mobile (375px)
- [ ] Test on tablet (768px)
- [ ] Test on desktop (1920px)
### E2E Tests
- [ ] Create `tests/e2e/login.spec.js` (in root)
- [ ] Create `tests/e2e/reports-navigation.spec.js` (in root)
- [ ] Create `tests/e2e/data-entry-navigation.spec.js` (in root)
- [ ] Create `tests/e2e/module-switching.spec.js` (in root)
- [ ] Create `tests/e2e/error-isolation.spec.js` (in root)
- [ ] Run all E2E tests - pass
### Performance Testing
- [ ] Run Lighthouse audit
- [ ] Performance score ≥ 90
- [ ] Initial load < 2 seconds
- [ ] Module switching < 500ms (cached)
---
## Post-Implementation Checklist
### Documentation Updates
- [ ] Update `CLAUDE.md` - Architecture section
- [ ] Update `CLAUDE.md` - Deployment section
- [ ] Update `README.md` - Quick start
- [ ] Update `README.md` - URL structure
- [ ] Update `DEPLOYMENT_GUIDE.md` - IIS configuration
- [ ] Update `docs/ARCHITECTURE_SCHEMA.md` - Diagrams
- [ ] Update `deployment/windows/README.md` - Deployment steps
### Cleanup (After 1 Week)
- [ ] Archive `reports-app/frontend/` `reports-app/frontend-archived/`
- [ ] Archive `data-entry-app/frontend/` `data-entry-app/frontend-archived/`
- [ ] Update `start-test.sh` to use root directory
- [ ] Update `start-data-entry.sh` to use root directory
- [ ] Update CI/CD pipelines (if any)
- [ ] Document migration in CHANGELOG.md
### Monitoring (First Week)
- [ ] Day 1: Review error logs
- [ ] Day 2: Review error logs
- [ ] Day 3: Review error logs
- [ ] Day 4: Review error logs
- [ ] Day 5: Review error logs
- [ ] Day 6: Review error logs
- [ ] Day 7: Review error logs + user feedback
### Optimization (First Month)
- [ ] Week 2: Analyze bundle sizes
- [ ] Week 2: Optimize images/assets
- [ ] Week 3: Consider further code splitting
- [ ] Week 3: Add performance monitoring
- [ ] Week 4: Evaluate feature flag usage
- [ ] Week 4: Plan next improvements
---
## Common Issues & Solutions
### Issue: CSS Conflicts
**Solution**: Use CSS modules, check `docs/CSS_PATTERNS.md`
### Issue: Import Errors
**Solution**: Update import paths, check alias configuration in vite.config.js
### Issue: API Calls Failing
**Solution**: Verify proxy configuration, check backend is running
### Issue: Error Boundary Not Catching
**Solution**: Check onErrorCaptured implementation, add global error handler
### Issue: Large Bundle Size
**Solution**: Review manualChunks, enable tree shaking, lazy load more
### Issue: IIS Routing Not Working
**Solution**: Check web.config URL rewrite rules, verify IIS URL Rewrite module installed
### Issue: Store Contamination
**Solution**: Use module-scoped stores, check for global state
### Issue: PrimeVue Theme Conflicts
**Solution**: Use single theme (saga-blue), override in vendor CSS
---
## Progress Tracking
**Phase 1: Setup**
- Started: ___________
- Completed: ___________
- Time Spent: ___________ hours
**Phase 2: Migration**
- Started: ___________
- Completed: ___________
- Time Spent: ___________ hours
**Phase 3: Routing**
- Started: ___________
- Completed: ___________
- Time Spent: ___________ hours
**Phase 4: Error Boundaries**
- Started: ___________
- Completed: ___________
- Time Spent: ___________ hours
**Phase 5: Build & Deploy**
- Started: ___________
- Completed: ___________
- Time Spent: ___________ hours
**Total Time**: ___________ hours (Estimated: 20 hours)
---
## Success Metrics
### Deployment
- [ ] Single IIS site running (not 2)
- [ ] Single build process (not 2)
- [ ] Zero downtime during deployment
### Performance
- [ ] Initial load < 2 seconds
- [ ] Module switching < 500ms
- [ ] Lighthouse score 90
- [ ] Bundle size sum of old apps
### Quality
- [ ] 100% feature parity
- [ ] All E2E tests passing
- [ ] Zero user-reported bugs (first week)
- [ ] Error isolation verified
---
**Status**: Not Started | 🔵 In Progress | Complete
**Last Updated**: ___________
**Completed By**: ___________
**Production Deploy Date**: ___________

View File

@@ -1,346 +0,0 @@
# Unified App Specification - Executive Summary
**Created**: 2025-12-22
**Status**: Implementation-Ready
**Estimated Effort**: 2.5 days
---
## What We're Building
A single unified SPA that consolidates the Reports App and Data Entry App into one application with:
- Unified menu navigation between modules
- Module isolation via error boundaries
- Lazy loading for optimal performance
- Single build and deployment process
---
## Key Requirements (Top 5)
1. **Unified Navigation**: Single menu with Reports and Data Entry sections
2. **Module Isolation**: Error in one module doesn't crash the other
3. **Lazy Loading**: Modules loaded on-demand, not upfront
4. **Simplified Deployment**: Single IIS site instead of 2
5. **Zero Backend Changes**: Both backends (8001, 8003) remain unchanged
---
## Technical Approach
### Architecture: Pragmatic Monolith
**NOT using micro-frontends** because:
- Only 1 developer (not 20+ team)
- Weekly deploys (not multiple times per day)
- 1-5 concurrent users (not millions)
- Same tech stack (Vue 3 only)
**Using instead**:
- Error boundaries for isolation (50-70% blast radius reduction)
- Lazy loading for performance
- Feature flags for module control
- Shared dependencies for smaller bundles
### URL Structure
```
/login → Login
/ → Redirect to /reports/dashboard
/reports/dashboard → Dashboard
/reports/invoices → Invoices
/reports/bank-cash → Bank/Cash
/reports/trial-balance → Trial Balance
/reports/telegram → Telegram Bot
/reports/cache-stats → Cache Stats
/data-entry → Receipts List
/data-entry/create → New Receipt
/data-entry/:id → View Receipt
/data-entry/:id/edit → Edit Receipt
```
### API Routing
**Vite Dev Proxy**:
- `/api/reports/*``http://localhost:8001/api/*`
- `/api/data-entry/*``http://localhost:8003/api/*`
- `/uploads/*``http://localhost:8003/uploads/*`
**IIS Production Proxy**:
- Same routing via web.config URL rewrite rules
---
## Critical Files (Top 10)
### To Create (in root directory)
1. `package.json` - Merged dependencies
2. `vite.config.js` - Dual proxy + lazy loading
3. `src/main.js` - App initialization
4. `src/App.vue` - Root with unified menu
5. `src/router/index.js` - Unified router
6. `src/config/menu.js` - Menu configuration
7. `src/shared/components/ErrorBoundary.vue` - Error isolation
8. `src/modules/reports/ReportsLayout.vue` - Reports wrapper
9. `src/modules/data-entry/DataEntryLayout.vue` - Data Entry wrapper
10. `web.config` - IIS configuration
### To Migrate
**Reports Module** (7 views, 5 stores, 1 service):
- Views: Dashboard, Invoices, BankCash, TrialBalance, Telegram, CacheStats
- Stores: dashboard, invoices, treasury, trialBalance, cacheStore
- Service: api.js (change base URL to `/api/reports/`)
**Data Entry Module** (2 views, 3 components, 1 store, 1 service):
- Views: ReceiptsList, ReceiptCreate
- Components: OCRUploadZone, OCRPreview, OCRConfidenceIndicator
- Store: receiptsStore
- Service: api.js (change base URL to `/api/data-entry/`)
**Shared** (5 components, 3 stores):
- Components: LoginView, AppHeader, SlideMenu, CompanySelector, PeriodSelector
- Stores: auth, companies, accountingPeriod (factories)
**CSS**: Copy entire `reports-app/frontend/src/assets/css/` structure
---
## Implementation Phases
### Phase 1: Setup (0.5 days)
- Create directory structure
- Setup package.json, vite.config.js
- Copy shared components and CSS
**Verify**: `npm install` and `npm run dev` work
### Phase 2: Migration (1 day)
- Migrate all views, components, stores
- Update API service base URLs
- Merge CSS
**Verify**: All views render, no import errors
### Phase 3: Routing & Navigation (0.5 days)
- Create unified router with lazy loading
- Create menu configuration
- Create error boundaries
- Integrate AppHeader and SlideMenu
**Verify**: Navigation works, lazy loading works
### Phase 4: Error Boundaries & Resilience (0.25 days)
- Test error isolation
- Test feature flags
- Add loading states
**Verify**: Error in one module doesn't crash other
### Phase 5: Build & Deploy (0.25 days)
- Production build
- IIS configuration
- Deploy to staging
- Test all routes
**Verify**: Build succeeds, IIS works, APIs route correctly
---
## Expected Build Output
```
dist/
├── index.html
├── assets/
│ ├── vendor-core.[hash].js (~150KB) - Vue, Router, Pinia
│ ├── vendor-primevue.[hash].js (~200KB) - PrimeVue components
│ ├── vendor-utils.[hash].js (~80KB) - Axios, date-fns
│ ├── vendor-charts.[hash].js (~150KB) - Chart.js (lazy)
│ ├── vendor-export.[hash].js (~200KB) - XLSX, jsPDF (lazy)
│ ├── reports.[hash].js (~150KB) - Reports module (lazy)
│ ├── data-entry.[hash].js (~100KB) - Data Entry module (lazy)
│ ├── main.[hash].js (~50KB) - App shell
│ └── main.[hash].css (~80KB) - Global CSS
```
---
## Success Criteria
### Must Have (Before Production)
- [ ] All Reports views work correctly
- [ ] All Data Entry views work correctly
- [ ] Navigation preserves auth and company/period
- [ ] Error in one module doesn't crash other
- [ ] Single IIS site deployment works
- [ ] API routing to both backends works
### Performance Targets
- [ ] Initial load < 2 seconds
- [ ] Module switching < 500ms (cached)
- [ ] Bundle size sum of current apps
- [ ] Lighthouse score 90
### Testing
- [ ] E2E tests pass for login
- [ ] E2E tests pass for Reports navigation
- [ ] E2E tests pass for Data Entry navigation
- [ ] E2E tests pass for module switching
- [ ] E2E tests verify error isolation
---
## Risks & Mitigations
| Risk | Mitigation |
|------|------------|
| CSS conflicts | Use design tokens, test thoroughly |
| Large bundle size | Lazy loading, code splitting, tree shaking |
| Error boundary gaps | Test error scenarios, add global handler |
| IIS deployment complexity | Document config, test on staging first |
| Store contamination | Module-scoped stores, test isolation |
---
## Rollback Plan
**If deployment fails**:
1. **Keep both apps running** (zero downtime)
- Leave `/roa2web/` and `/data-entry/` running
- Add unified app at `/unified/` for testing
2. **Quick rollback** (15 minutes)
- Restore IIS config from backup
- Restore builds from `dist-backup/`
3. **Git rollback**
- Tag before merge: `v1.0-pre-unified`
- Revert if needed: `git reset --hard v1.0-pre-unified`
---
## Post-Implementation
### After 1 Week of Stability
**Archive old frontends**:
```bash
mv reports-app/frontend reports-app/frontend-archived
mv data-entry-app/frontend data-entry-app/frontend-archived
```
**Update documentation**:
- CLAUDE.md - Architecture and deployment
- DEPLOYMENT_GUIDE.md - IIS configuration
- README.md - Quick start and commands
**Update scripts**:
- `./start-test.sh` - Point to root directory
- `./start-data-entry.sh` - Point to root directory
### Monitoring (First Month)
**Week 1**: Daily error log review
**Week 2-4**: Performance optimization
- Bundle size optimization
- Further code splitting
- Cache optimization
---
## Open Questions & Recommendations
### 1. PrimeVue Theme
**Question**: Use `saga-blue` (reports-app) or `lara-light-blue` (data-entry-app)?
**Recommendation**: `saga-blue` (reports-app is primary)
### 2. Feature Flags
**Question**: Config file or environment variables?
**Recommendation**: Config file for simplicity, env vars for override
### 3. Module Activation
**Question**: All active by default or opt-in?
**Recommendation**: All active by default (disable via config if needed)
### 4. Monitoring
**Question**: Console logs only or add Sentry/similar?
**Recommendation**: Console logs for MVP, add monitoring later
---
## Key Decisions Made
1. **Architecture**: Pragmatic monolith (not micro-frontends)
2. **Error Isolation**: Error boundaries per module
3. **Code Splitting**: Lazy loading with manual chunks
4. **URL Structure**: `/reports/*` and `/data-entry/*`
5. **API Routing**: Proxy via Vite (dev) and IIS (prod)
6. **CSS System**: Use reports-app CSS structure
7. **PrimeVue Theme**: saga-blue (from reports-app)
8. **Shared Components**: Use existing from `shared/frontend/`
9. **Deployment**: Single IIS site at root `/`
10. **Backends**: No changes (remain at 8001, 8003)
---
## Documentation Locations
**Complete Spec**: `.auto-build-data/specs/unified-app/spec.md`
**Critical Files**: `.auto-build-data/specs/unified-app/critical-files.md`
**This Summary**: `.auto-build-data/specs/unified-app/SUMMARY.md`
**Note**: All implementation files will be created in the project root directory (`.` or `/mnt/e/proiecte/roa2web/`)
**Reference Docs**:
- `IMPLEMENTATION_PLAN_UNIFIED_APP.md` - Original plan
- `CLAUDE.md` - Project documentation (update after)
- `docs/ONBOARDING_CSS.md` - CSS system guide
- `docs/CSS_PATTERNS.md` - Available CSS patterns
---
## Next Steps
1. **Read the complete spec**: `spec.md` (detailed technical specification)
2. **Review critical files**: `critical-files.md` (files to migrate/create)
3. **Start Phase 1**: Project setup (0.5 days)
4. **Follow implementation plan**: 5 phases over 2.5 days
5. **Test thoroughly**: E2E tests before production
6. **Deploy to staging**: Test IIS configuration
7. **Deploy to production**: Single site deployment
8. **Monitor for 1 week**: Daily error log review
9. **Archive old apps**: After stability confirmed
10. **Update docs**: Complete documentation updates
---
## Quick Stats
- **Files to create**: ~15
- **Files to migrate**: ~20
- **CSS files to copy**: ~30
- **Total files affected**: ~65
- **Estimated time**: 2.5 days (20 hours)
- **Complexity**: Medium
- **Risk level**: Medium-Low (with mitigations)
---
**Specification Status**: Implementation-Ready
**All Technical Decisions**: Made
**Rollback Plan**: Defined
**Success Criteria**: Defined
**Ready to implement!** 🚀
---
**Version**: 1.0
**Created**: 2025-12-22
**Author**: Claude (Specification Agent)
**For**: ROA2WEB Unified App Feature

View File

@@ -1,477 +0,0 @@
# Unified App - Critical Files Reference
**Quick Reference**: Files that will be most affected during implementation
---
## Files to Analyze (Before Implementation)
### Configuration Files
**Reports App**:
- `/mnt/e/proiecte/roa2web/reports-app/frontend/package.json` - Dependencies to merge
- `/mnt/e/proiecte/roa2web/reports-app/frontend/vite.config.js` - Proxy config, build settings
- `/mnt/e/proiecte/roa2web/reports-app/frontend/src/main.js` - PrimeVue setup
**Data Entry App**:
- `/mnt/e/proiecte/roa2web/data-entry-app/frontend/package.json` - Dependencies to merge
- `/mnt/e/proiecte/roa2web/data-entry-app/frontend/vite.config.js` - Proxy config
- `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/main.js` - PrimeVue setup
### Application Entry Points
**Reports App**:
- `/mnt/e/proiecte/roa2web/reports-app/frontend/src/App.vue` - Root component, menu integration
- `/mnt/e/proiecte/roa2web/reports-app/frontend/src/router/index.js` - Router config
**Data Entry App**:
- `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/App.vue` - Root component, menu integration
- `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/router/index.js` - Router config
### Shared Components (Already Created)
- `/mnt/e/proiecte/roa2web/shared/frontend/components/LoginView.vue`
- `/mnt/e/proiecte/roa2web/shared/frontend/components/layout/AppHeader.vue`
- `/mnt/e/proiecte/roa2web/shared/frontend/components/layout/SlideMenu.vue`
- `/mnt/e/proiecte/roa2web/shared/frontend/components/CompanySelector.vue`
- `/mnt/e/proiecte/roa2web/shared/frontend/components/PeriodSelector.vue`
### Shared Stores (Factories)
- `/mnt/e/proiecte/roa2web/shared/frontend/stores/auth.js`
- `/mnt/e/proiecte/roa2web/shared/frontend/stores/companies.js`
- `/mnt/e/proiecte/roa2web/shared/frontend/stores/accountingPeriod.js`
---
## Views to Migrate
### Reports Module (7 views)
Source: `/mnt/e/proiecte/roa2web/reports-app/frontend/src/views/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/reports/views/`
1. `DashboardView.vue` - Main dashboard with metrics
2. `InvoicesView.vue` - Invoices table and filters
3. `BankCashRegisterView.vue` - Bank and cash register transactions
4. `TrialBalanceView.vue` - Trial balance report
5. `TelegramView.vue` - Telegram bot management
6. `CacheStatsView.vue` - Cache statistics
7. ~~`LoginView.vue`~~ - USE SHARED VERSION
### Data Entry Module (2 views + 3 components)
**Views**:
Source: `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/views/receipts/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/data-entry/views/receipts/`
1. `ReceiptsListView.vue` - List of receipts with filters
2. `ReceiptCreateView.vue` - Create/edit receipt form
**Components**:
Source: `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/components/ocr/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/data-entry/components/ocr/`
1. `OCRUploadZone.vue` - File upload zone for receipts
2. `OCRPreview.vue` - Preview uploaded receipt image
3. `OCRConfidenceIndicator.vue` - OCR confidence indicator
---
## Stores to Migrate
### Reports Module (5 stores)
Source: `/mnt/e/proiecte/roa2web/reports-app/frontend/src/stores/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/reports/stores/`
1. `dashboard.js` - Dashboard data and metrics
2. `invoices.js` - Invoices data and filters
3. `treasury.js` - Bank/cash register data
4. `trialBalance.js` - Trial balance data
5. `cacheStore.js` - Cache statistics
**SKIP** (use shared):
- ~~`auth.js`~~ - Use `/mnt/e/proiecte/roa2web/shared/frontend/stores/auth.js`
- ~~`companies.js`~~ - Use `/mnt/e/proiecte/roa2web/shared/frontend/stores/companies.js`
- ~~`accountingPeriod.js`~~ - Use `/mnt/e/proiecte/roa2web/shared/frontend/stores/accountingPeriod.js`
### Data Entry Module (1 store)
Source: `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/stores/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/data-entry/stores/`
1. `receiptsStore.js` - Receipts data and CRUD operations
**SKIP** (use shared):
- ~~`auth.js`~~ - Use shared
- ~~`companies.js`~~ - Use shared
- ~~`accountingPeriod.js`~~ - Use shared
---
## Services to Migrate
### Reports Module
Source: `/mnt/e/proiecte/roa2web/reports-app/frontend/src/services/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/reports/services/`
1. `api.js` - **MODIFY**: Change base URL to `/api/reports/`
**Current**:
```javascript
const api = axios.create({
baseURL: '/api'
})
```
**New**:
```javascript
const api = axios.create({
baseURL: '/api/reports'
})
```
### Data Entry Module
Source: `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/services/`
Destination: `/mnt/e/proiecte/roa2web/src/modules/data-entry/services/`
1. `api.js` - **MODIFY**: Change base URL to `/api/data-entry/`
**Current**:
```javascript
const api = axios.create({
baseURL: '/api'
})
```
**New**:
```javascript
const api = axios.create({
baseURL: '/api/data-entry'
})
```
---
## CSS to Migrate
### Reports Module CSS (COPY ENTIRE STRUCTURE)
Source: `/mnt/e/proiecte/roa2web/reports-app/frontend/src/assets/css/`
Destination: `/mnt/e/proiecte/roa2web/src/assets/css/`
**Copy ALL files** (this is the main CSS system):
- `core/` - Design tokens (colors, spacing, typography)
- `components/` - Reusable UI patterns (buttons, forms, cards, tables, stats)
- `patterns/` - Interactive patterns (animations, dashboard, interactive)
- `layout/` - Page structure (containers, grid, navigation)
- `utilities/` - Utility classes (colors, spacing, flex, text, display)
- `vendor/` - PrimeVue overrides
- `global.css` - Global styles
- `main.css` - Main entry point
- `mobile.css` - Mobile responsive styles
### Data Entry Module CSS (MERGE)
Source: `/mnt/e/proiecte/roa2web/data-entry-app/frontend/src/assets/css/`
**Analyze and merge unique styles**:
- `main.css` - Merge with reports-app main.css
- Any component-specific styles - Integrate into unified system
### Shared CSS
Source: `/mnt/e/proiecte/roa2web/shared/frontend/styles/`
Destination: `/mnt/e/proiecte/roa2web/src/shared/styles/`
1. `login.css` - Login page styles
2. `layout/header.css` - Header styles
3. `layout/navigation.css` - Navigation styles
---
## Critical Implementation Files
### 1. Package Configuration
**File**: `/mnt/e/proiecte/roa2web/package.json`
**Dependencies to merge**:
- From reports-app: axios, chart.js, date-fns, jspdf, jspdf-autotable, qrcode.vue, xlsx
- From data-entry-app: All covered by reports-app
- Shared: vue@^3.4.0, vue-router@^4.2.5, pinia@^2.1.7, primevue@^3.46.0
### 2. Vite Configuration
**File**: `/mnt/e/proiecte/roa2web/vite.config.js`
**Key sections**:
- Dual proxy for `/api/reports/``http://localhost:8001`
- Dual proxy for `/api/data-entry/``http://localhost:8003`
- Lazy loading configuration (manualChunks)
- Alias configuration (@, @shared, @reports, @data-entry)
### 3. Application Entry
**File**: `/mnt/e/proiecte/roa2web/src/main.js`
**Key setup**:
- PrimeVue configuration (theme: saga-blue)
- Global components registration
- Router, Pinia, ToastService, ConfirmationService
- CSS imports
### 4. Root Component
**File**: `/mnt/e/proiecte/roa2web/src/App.vue`
**Key elements**:
- AppHeader with unified menu
- SlideMenu with module sections
- router-view
- Toast, ConfirmDialog
### 5. Router Configuration
**File**: `/mnt/e/proiecte/roa2web/src/router/index.js`
**Key routes**:
- `/login` - LoginView (eager loaded)
- `/reports/*` - ReportsLayout (lazy loaded) with children
- `/data-entry/*` - DataEntryLayout (lazy loaded) with children
- Authentication guard
### 6. Menu Configuration
**File**: `/mnt/e/proiecte/roa2web/src/config/menu.js`
**Sections**:
- Rapoarte (Reports)
- Introduceri Date (Data Entry)
- Sistem (System)
### 7. Feature Flags
**File**: `/mnt/e/proiecte/roa2web/src/config/features.js`
**Flags**:
- reports.enabled
- dataEntry.enabled
- Module-level flags
### 8. Error Boundary Component
**File**: `/mnt/e/proiecte/roa2web/src/shared/components/ErrorBoundary.vue`
**Key features**:
- onErrorCaptured hook
- User-friendly error display
- Retry functionality
- Navigate away option
### 9. Module Layouts
**File**: `/mnt/e/proiecte/roa2web/src/modules/reports/ReportsLayout.vue`
**Wrapper**:
```vue
<ErrorBoundary module-name="Reports">
<router-view />
</ErrorBoundary>
```
**File**: `/mnt/e/proiecte/roa2web/src/modules/data-entry/DataEntryLayout.vue`
**Wrapper**:
```vue
<ErrorBoundary module-name="Data Entry">
<router-view />
</ErrorBoundary>
```
---
## Deployment Files
### IIS Configuration
**File**: `/mnt/e/proiecte/roa2web/web.config`
**Key rules**:
- SPA routing (all routes → index.html)
- API proxy: `/api/reports/*``http://localhost:8001/api/*`
- API proxy: `/api/data-entry/*``http://localhost:8003/api/*`
- Uploads proxy: `/uploads/*``http://localhost:8003/uploads/*`
### Environment Variables
**File**: `/mnt/e/proiecte/roa2web/.env.example`
**Variables**:
```bash
# API Endpoints (dev only, production uses IIS proxy)
VITE_REPORTS_API=http://localhost:8001
VITE_DATA_ENTRY_API=http://localhost:8003
# Feature Flags
VITE_ENABLE_REPORTS=true
VITE_ENABLE_DATA_ENTRY=true
```
---
## Testing Files
### E2E Tests
**New files to create**:
- `/mnt/e/proiecte/roa2web/tests/e2e/login.spec.js`
- `/mnt/e/proiecte/roa2web/tests/e2e/reports-navigation.spec.js`
- `/mnt/e/proiecte/roa2web/tests/e2e/data-entry-navigation.spec.js`
- `/mnt/e/proiecte/roa2web/tests/e2e/module-switching.spec.js`
- `/mnt/e/proiecte/roa2web/tests/e2e/error-isolation.spec.js`
**Existing tests to adapt**:
- `/mnt/e/proiecte/roa2web/reports-app/frontend/tests/` - Update routes
- `/mnt/e/proiecte/roa2web/data-entry-app/frontend/tests/` - Update routes
---
## Documentation Files to Update
### Primary Documentation
1. **CLAUDE.md** (root)
- Update architecture diagram
- Add unified-app section
- Mark old apps as archived
- Update deployment instructions
2. **README.md** (root)
- Update quick start
- Update deployment section
- Update URL structure
3. **DEPLOYMENT_GUIDE.md**
- Update IIS configuration
- Update build process
- Add rollback instructions
4. **docs/ARCHITECTURE_SCHEMA.md**
- Update architecture diagrams
- Document module structure
- Add error boundary architecture
### Deployment Documentation
5. **deployment/windows/README.md**
- Update deployment steps
- Update IIS configuration
- Update proxy rules
6. **deployment/windows/docs/WINDOWS_DEPLOYMENT.md**
- Complete Windows guide updates
---
## File Count Summary
**To Create**: ~15 new files
- 9 core files (package.json, vite.config.js, main.js, App.vue, router, menu, features, ErrorBoundary, 2 layouts)
- 3 configuration files (.env.example, web.config, README.md)
- 3 documentation updates
**To Migrate**: ~20 files
- 7 Reports views
- 2 Data Entry views
- 3 Data Entry components
- 5 Reports stores
- 1 Data Entry store
- 2 API services
**To Copy**: ~30 CSS files
- Entire reports-app CSS structure
**Total Files Affected**: ~65 files
---
## Time Estimates per File Type
| Task | Files | Avg Time | Total |
|------|-------|----------|-------|
| Create core files | 9 | 30 min | 4.5 hours |
| Migrate views | 9 | 20 min | 3 hours |
| Migrate components | 3 | 15 min | 45 min |
| Migrate stores | 6 | 20 min | 2 hours |
| Migrate services | 2 | 30 min | 1 hour |
| Copy CSS | 1 | 1 hour | 1 hour |
| Configuration | 3 | 30 min | 1.5 hours |
| Documentation | 6 | 30 min | 3 hours |
| Testing & fixes | - | - | 4 hours |
**Total**: ~20 hours (~2.5 days)
---
## Verification Checklist
After migrating each category:
### Configuration Files ✓
- [ ] package.json has all dependencies
- [ ] vite.config.js has dual proxy
- [ ] main.js initializes correctly
- [ ] npm install succeeds
- [ ] npm run dev starts
### Views ✓
- [ ] All Reports views render
- [ ] All Data Entry views render
- [ ] No import errors
- [ ] Routes work
### Stores ✓
- [ ] All stores import correctly
- [ ] No duplicate store instances
- [ ] Shared stores work
- [ ] Module stores isolated
### Services ✓
- [ ] API calls route to correct backend
- [ ] /api/reports/ → :8001
- [ ] /api/data-entry/ → :8003
- [ ] Auth headers preserved
### CSS ✓
- [ ] No style conflicts
- [ ] Design tokens work
- [ ] PrimeVue theme consistent
- [ ] Responsive works
### Router ✓
- [ ] All routes accessible
- [ ] Lazy loading works
- [ ] Auth guard works
- [ ] 404 redirects
### Error Boundaries ✓
- [ ] Catches component errors
- [ ] Displays user message
- [ ] Module isolation works
- [ ] Can retry/navigate
### Build ✓
- [ ] npm run build succeeds
- [ ] Chunks split correctly
- [ ] Bundle size acceptable
- [ ] Preview works
---
**Last Updated**: 2025-12-22
**For**: Unified App Implementation
**Reference**: See spec.md for complete specification

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,86 +0,0 @@
{
"feature": "unified-app",
"status": "IMPLEMENTATION_COMPLETE",
"created": "2025-12-22T01:09:00Z",
"updated": "2025-12-23T21:25:00Z",
"complexity": "medium",
"estimated_effort": "2.5 days",
"worktree": "/mnt/e/proiecte/ab-worktrees/roa2web-unified-app",
"branch": "feature/ab-unified-app",
"totalTasks": 28,
"currentTask": 28,
"completedTasks": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
"tasksCompleted": 28,
"testing": {
"playwrightTestsCreated": 6,
"testsExecuted": 40,
"testsPassed": 4,
"testsBlocked": 36,
"blockingReason": "Backend authentication error (Oracle DB/SSH tunnel configuration)",
"frontendQuality": "100/100 - EXCELLENT",
"visualRegressionIssues": 0,
"consoleErrors": 0,
"consoleWarnings": 0
},
"history": [
{
"status": "SPEC_DRAFT",
"at": "2025-12-22T01:09:00Z"
},
{
"status": "SPEC_COMPLETE",
"at": "2025-12-22T01:13:00Z"
},
{
"status": "PLANNING",
"at": "2025-12-22T09:30:00Z"
},
{
"status": "PLANNING_COMPLETE",
"at": "2025-12-22T09:35:00Z"
},
{
"status": "IMPLEMENTING",
"at": "2025-12-22T18:25:00Z",
"task": 1
},
{
"status": "IMPLEMENTING",
"at": "2025-12-22T20:45:00Z",
"task": 28,
"started": true
},
{
"status": "TESTING",
"at": "2025-12-23T21:00:00Z",
"description": "Comprehensive Playwright E2E testing"
},
{
"status": "IMPLEMENTATION_COMPLETE",
"at": "2025-12-23T21:25:00Z",
"task": 28,
"completed": true,
"note": "All 28 tasks completed. Frontend fully functional. Backend auth requires Oracle/SSH configuration."
}
],
"files": {
"spec": "spec.md",
"summary": "SUMMARY.md",
"critical_files": "critical-files.md",
"migration_checklist": "MIGRATION_CHECKLIST.md",
"plan": "plan.md",
"test_report": "../../UNIFIED_APP_TEST_REPORT.md"
},
"stats": {
"files_to_create": 15,
"files_to_migrate": 20,
"css_files_to_copy": 30,
"total_files_affected": 65
},
"deployment": {
"ready": true,
"frontendStatus": "PRODUCTION_READY",
"backendStatus": "NEEDS_CONFIGURATION",
"blockers": ["Oracle DB authentication", "SSH tunnel configuration"]
}
}