Files
tfm_ainventory/.planning/phases/5-core-v2-features/5-PLAN-03.md

8.5 KiB

plan, feature, status, estimated_tasks, total_lines
plan feature status estimated_tasks total_lines
5-PLAN-03 Export/Reports (Admin Dashboard) ready 7 ~600

Phase 5 Plan 03: Export/Reports (Admin Dashboard)

Overview

Implement inventory snapshot and audit trail exports in CSV and Excel (.xlsx) formats for admins. Manual trigger via button in Admin Dashboard. Filenames include timestamps. Support future field additions without code changes.

Tasks

Task 1: Backend Export Service (Core Logic)

  • File: backend/services/export_service.py
  • Classes: ExportService, InventorySnapshotExporter, AuditTrailExporter
  • Functions:
    • InventorySnapshotExporter.to_csv(items: List[Item], timestamp: str) → str
    • InventorySnapshotExporter.to_excel(items: List[Item], timestamp: str) → bytes
    • AuditTrailExporter.to_csv(logs: List[AuditLog], timestamp: str) → str
    • AuditTrailExporter.to_excel(logs: List[AuditLog], timestamp: str) → bytes
  • Lines: ~200
  • Description: Export service handling CSV/Excel generation. Uses Python csv and openpyxl libraries. Returns file content ready for download. Timestamps included in both filenames and file content.
  • Acceptance Criteria:
    • InventorySnapshotExporter: exports all item fields (ID, Name, PN, Barcode, Category, Qty, Description, Notes, Box Label, Created, Modified, etc.)
    • AuditTrailExporter: exports all audit fields (ID, Item ID, Item Name, Action, Old Value, New Value, User, Timestamp, etc.)
    • CSV format: proper quoting/escaping, UTF-8 encoding, comma-separated
    • Excel format: .xlsx with headers, proper column widths, data types preserved
    • Both formats include timestamp in header/metadata
    • Filename format: inventory_snapshot_2026-04-22.csv, audit_trail_2026-04-22.xlsx, etc.
    • Handles empty datasets (no items → empty file with headers)
    • Unit tests: CSV generation, Excel generation, timestamp formatting

Task 2: Backend Export Endpoints (API)

  • File: backend/routers/admin/exports.py (new router)
  • Endpoints:
    • POST /admin/exports/inventory-snapshot?format={csv|xlsx} → file download
    • POST /admin/exports/audit-trail?format={csv|xlsx} → file download
  • Functions:
    • export_inventory_snapshot(format: str, auth: AdminUser) → FileResponse
    • export_audit_trail(format: str, auth: AdminUser) → FileResponse
  • Lines: ~80
  • Description: REST endpoints for triggering exports. Return file as download response with proper MIME type and filename.
  • Acceptance Criteria:
    • Both endpoints require admin authorization (auth.get_current_admin)
    • Query param format accepts "csv" or "xlsx" (case-insensitive)
    • Returns file with correct MIME type (text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)
    • HTTP header sets filename with timestamp
    • Endpoint audits the export action (log who exported, when, format)
    • Error handling: invalid format → 400 Bad Request
    • Unit tests: both formats, authorization checks, error cases

Task 3: Frontend Admin Export UI Component

  • File: frontend/components/admin/ExportPanel.tsx
  • Component: ExportPanel() → JSX.Element
  • Lines: ~180
  • Description: Dedicated panel in Admin Dashboard with export buttons. Two sections: Inventory Snapshot and Audit Trail. Each has CSV/Excel buttons. Loading spinners, success/error toasts.
  • Acceptance Criteria:
    • Two main sections: "Inventory Snapshot" and "Audit Trail"
    • Each section has "Export as CSV" and "Export as Excel" buttons
    • Button labels clearly indicate format
    • Loading spinner during export (prevents double-click)
    • Success toast: "Snapshot exported as CSV" with filename
    • Error toast: "Export failed: {error message}"
    • Buttons disabled while export in progress
    • Mobile-responsive button layout
    • Accessibility: ARIA labels on buttons, proper semantic HTML

Task 4: Frontend Export Hook

  • File: frontend/hooks/useExport.ts
  • Hook: useExport() → { exportSnapshot: (format: 'csv' | 'xlsx') => Promise<void>; exportAuditTrail: (format: 'csv' | 'xlsx') => Promise<void>; isLoading: boolean; error: string | null }
  • Lines: ~120
  • Description: Custom hook managing export API calls, loading states, error handling, and file download triggering.
  • Acceptance Criteria:
    • Calls POST endpoints with correct format parameter
    • Handles blob response and triggers browser download
    • Filename extracted from HTTP response header (Content-Disposition)
    • Error states propagated to caller
    • Loading state managed properly (prevents concurrent calls)
    • Unit tests: successful export, error handling, filename extraction

Task 5: Integrate ExportPanel into Admin Dashboard

  • File: frontend/app/admin/page.tsx
  • Component: Update admin page layout
  • Lines: ~40
  • Description: Add ExportPanel to Admin Dashboard. Include it in the main layout alongside other admin sections (settings, user management, etc.).
  • Acceptance Criteria:
    • ExportPanel renders in Admin Dashboard
    • Visually separated from other admin sections (e.g., card/section styling)
    • No layout conflicts with existing admin UI
    • Responsive on mobile/desktop
    • Only visible to admins (via auth check in component or page)

Task 6: Dependency Management & Configuration

  • File: backend/requirements.txt
  • Update: Add openpyxl library
  • Lines: ~5
  • Description: Ensure openpyxl (for .xlsx generation) is in requirements.txt with version constraint.
  • Acceptance Criteria:
    • openpyxl>=3.10.0 added to requirements.txt
    • Python csv module (stdlib) is available (no extra install needed)
    • All tests can import and use both libraries

Task 7: Integration & E2E Tests

  • File: frontend/tests/admin/exports.test.ts + backend/tests/test_exports.py
  • Tests: Full export workflow for both formats and both report types
  • Lines: ~250
  • Description: End-to-end tests confirming exports work, files are generated correctly, and contain expected data.
  • Acceptance Criteria:
    • Test: export inventory snapshot as CSV, verify file content
    • Test: export inventory snapshot as Excel, verify file is valid .xlsx
    • Test: export audit trail as CSV, verify headers and data
    • Test: export audit trail as Excel, verify structure and data types
    • Test: exports include timestamp in filename
    • Test: unauthorized user cannot export (403 Forbidden)
    • Test: invalid format param returns 400 Bad Request
    • Backend test: CSV generation logic (proper escaping, encoding)
    • Backend test: Excel generation logic (valid .xlsx structure)
    • Frontend test: button click triggers download
    • Frontend test: loading spinner appears during export
    • Frontend test: success/error toasts appear
    • All assertions pass (Vitest + Pytest)

Dependencies

  • Task 1 (export service) must complete before Tasks 2-3
  • Task 2 (backend endpoints) depends on Task 1
  • Task 4 (hook) depends on Task 2 (endpoints exist)
  • Task 3 (UI component) and Task 4 (hook) can run in parallel
  • Task 5 (integration) depends on Tasks 3-4
  • Task 6 (dependencies) can run in parallel with all other tasks
  • Task 7 (tests) depends on Tasks 1-5

Testing Strategy

  • Unit tests: ExportService CSV/Excel generation (Pytest), useExport hook (Vitest)
  • Integration tests: Full export workflow from Admin Dashboard (Vitest + mocked API)
  • Backend integration tests: Endpoints with real database, authorization checks (Pytest)
  • File validation tests: Verify exported CSV is valid (can parse), Excel is valid .xlsx (can open)
  • E2E: Manual verification: click export button, file downloads, verify content

Blockers & Workarounds

  • File download handling: Browser file downloads work via blob response + <a href="blob:..."> trick. Ensure Content-Disposition header is set correctly.
  • Large datasets: If inventory grows to 10k+ items, export may be slow. Defer pagination/streaming to Phase 6+ (for now, accept latency).
  • Excel generation: openpyxl can be memory-intensive. For Phase 5, assume datasets < 50k rows. Monitor performance in production.
  • Timestamp format: Use consistent ISO 8601 format (YYYY-MM-DD) in filenames and file headers. Document in PROJECT_ARCHITECTURE.md.
  • Future fields: Design exporters to dynamically include all item/audit fields (use __dict__ or similar) so adding new fields doesn't require code changes.