Commit Graph

64 Commits

Author SHA1 Message Date
Dries Peeters
0c28b80346 docs: Add comprehensive features documentation and update READMEs
Create complete features overview documenting all 120+ features across
12 major categories, and update main README and docs README with
enhanced feature descriptions and links.

Changes:
- Add docs/FEATURES_COMPLETE.md with comprehensive feature documentation
  covering all features organized by category (Time Tracking, Project
  Management, Task Management, Client Management, Invoicing, Financial
  Management, Reporting & Analytics, User Management & Security,
  Productivity Features, Administration, Integration & API, Technical)
- Update README.md:
  - Add reference to complete features documentation
  - Expand feature descriptions with additional features (Focus Sessions,
    Recurring Time Blocks, Budget Alerts, Weekly Goals, etc.)
  - Enhance feature descriptions with more detail
- Update docs/README.md:
  - Add "Complete Features Reference" section at top
  - Reorganize feature documentation into logical groups
  - Add links to additional feature docs (Payment Tracking, Budget
    Alerts, Weekly Goals, etc.)

This provides users with a single comprehensive reference for all
available features while maintaining the quick overview in the main
README. The documentation is now better organized and more discoverable.
2025-11-13 09:31:07 +01:00
Dries Peeters
890df2f4bc Fix: Preserve task selection when duplicating time entries
Fix: Preserve task selection when duplicating time entriesWhen duplicating a time entry with an assigned task, the task was notbeing pre-selected in the duplicate form. This was caused by thetemplate application code interfering with the duplication logic.The template code would run after duplication data was set, overwritingthe `data-selected-task-id` attribute and clearing the task selectioneven when no template was being applied.Changes:- Added isDuplicating flag check in manual_entry.html to prevent  template application code from running during duplication- Template functionality continues to work normally for non-duplicate  manual entries- Added comprehensive test to verify task pre-selection is preserved- Updated documentation with fix notes and changelog entryImpact:- Users can now duplicate time entries with tasks and the task will be  correctly pre-selected, saving time and improving UX- No breaking changes - all existing tests pass (54/54)- Clean separation between duplication and template featuresTests:- test_duplicate_with_task_not_overridden_by_template_code (new)- All 22 duplication tests passing- All 32 template tests passing
2025-10-31 13:22:24 +01:00
Dries Peeters
12d3b9fb1b feat: Add comprehensive Import/Export system and standardize UI headers
## New Features

### Import/Export System
- Add DataImport and DataExport models for tracking operations
- Implement CSV import for bulk time entry data
- Add support for importing from Toggl and Harvest (placeholder)
- Implement GDPR-compliant full data export (JSON format)
- Add filtered export functionality with date/project filters
- Create backup/restore functionality for database migrations
- Build migration wizard UI for seamless data transitions
- Add comprehensive test coverage (unit and integration tests)
- Create user documentation (IMPORT_EXPORT_GUIDE.md)

### Database Changes
- Add migration 040: Create data_imports and data_exports tables
- Track import/export operations with status, logs, and file paths
- Support automatic file expiration for temporary downloads

## UI/UX Improvements

### Navigation Menu Restructure
- Rename "Work" to "Time Tracking" for clarity
- Rename "Finance" to "Finance & Expenses"
- Add "Tools & Data" submenu with Import/Export and Saved Filters
- Reorganize Time Tracking submenu: prioritize Log Time, add icons to all items
- Expand Finance submenu: add Mileage, Per Diem, and Budget Alerts
- Add icons to all Admin submenu items for better visual scanning
- Fix Weekly Goals not keeping Time Tracking menu open

### Standardized Page Headers
Apply consistent page_header macro across 26+ pages:
- **Time Tracking**: Tasks, Projects, Clients, Kanban, Weekly Goals, Templates, Manual Entry
- **Finance**: Invoices, Payments, Expenses, Mileage, Per Diem, Budget Alerts, Reports
- **Admin**: Dashboard, Users, Roles, Permissions, Settings, API Tokens, Backups, System Info, OIDC
- **Tools**: Import/Export, Saved Filters, Calendar
- **Analytics**: Dashboard

Each page now includes:
- Descriptive icon (Font Awesome)
- Clear title and subtitle
- Breadcrumb navigation
- Consistent action button placement
- Responsive design with dark mode support

## Bug Fixes

### Routing Errors
- Fix endpoint name: `per_diem.list_per_diems` → `per_diem.list_per_diem`
- Fix endpoint name: `reports.index` → `reports.reports`
- Fix endpoint name: `timer.timer` → `timer.manual_entry`
- Add missing route registration for import_export blueprint

### User Experience
- Remove duplicate "Test Configuration" button from OIDC debug page
- Clean up user dropdown menu (remove redundant Import/Export link)
- Improve menu item naming ("Profile" → "My Profile", "Settings" → "My Settings")

## Technical Details

### New Files
- `app/models/import_export.py` - Import/Export models
- `app/utils/data_import.py` - Import business logic
- `app/utils/data_export.py` - Export business logic
- `app/routes/import_export.py` - API endpoints
- `app/templates/import_export/index.html` - User interface
- `tests/test_import_export.py` - Integration tests
- `tests/models/test_import_export_models.py` - Model tests
- `docs/IMPORT_EXPORT_GUIDE.md` - User documentation
- `docs/import_export/README.md` - Quick reference
- `migrations/versions/040_add_import_export_tables.py` - Database migration

### Modified Files
- `app/__init__.py` - Register import_export blueprint
- `app/models/__init__.py` - Export new models
- `app/templates/base.html` - Restructure navigation menu
- 26+ template files - Standardize headers with page_header macro

## Breaking Changes
None. All changes are backward compatible.

## Testing
- All existing tests pass
- New test coverage for import/export functionality
- Manual testing of navigation menu changes
- Verified consistent UI across all updated pages
2025-10-31 09:56:49 +01:00
Dries Peeters
755faa22c3 feat: Add Budget Alerts & Forecasting system with modern UI
Implement comprehensive budget monitoring and forecasting feature with:

Database & Models:
- Add BudgetAlert model for tracking project budget alerts
- Create migration 039_add_budget_alerts_table with proper indexes
- Support alert types: 80_percent, 100_percent, over_budget
- Add acknowledgment tracking with user and timestamp

Budget Forecasting Utilities:
- Implement burn rate calculation (daily/weekly/monthly)
- Add completion date estimation based on burn rate
- Create resource allocation analysis per team member
- Build cost trend analysis with configurable granularity
- Add automatic budget alert detection with deduplication

Routes & API:
- Create budget_alerts blueprint with dashboard and detail views
- Add API endpoints for burn rate, completion estimates, and trends
- Implement resource allocation and cost trend API endpoints
- Add alert acknowledgment and manual budget check endpoints
- Fix log_event() calls to use keyword arguments

UI Templates:
- Design modern budget dashboard with Tailwind CSS
- Create detailed project budget analysis page with charts
- Add gradient stat cards with color-coded status indicators
- Implement responsive layouts with full dark mode support
- Add smooth animations and toast notifications
- Integrate Chart.js for cost trend visualization

Project Integration:
- Add Budget Alerts link to Finance navigation menu
- Enhance project view page with budget overview card
- Show budget progress bars with status indicators
- Add Budget Analysis button to project header and dashboard
- Display real-time budget status with color-coded badges

Visual Enhancements:
- Use gradient backgrounds for stat cards (blue/green/yellow/red)
- Add status badges with icons (healthy/warning/critical/over)
- Implement smooth progress bars with embedded percentages
- Support responsive grid layouts for all screen sizes
- Ensure proper type conversion (Decimal to float) in templates

Scheduled Tasks:
- Register budget alert checking job (runs every 6 hours)
- Integrate with existing APScheduler tasks
- Add logging for alert creation and monitoring

This feature provides project managers with real-time budget insights,
predictive analytics, and proactive alerts to prevent budget overruns.
2025-10-31 08:52:12 +01:00
Dries Peeters
0da5ac0077 feat: Add comprehensive project dashboard with analytics and visualizations
Implement a feature-rich project dashboard that provides visual analytics
and key performance indicators for project tracking and management.

Features:
- Individual project dashboard route (/projects/<id>/dashboard)
- Key metrics cards: Total Hours, Budget Used, Tasks Complete, Team Size
- Budget vs. Actual bar chart with threshold warnings
- Task status distribution doughnut chart
- Team member contributions horizontal bar chart (top 10)
- Time tracking timeline line chart
- Team member details with progress bars
- Recent activity feed (last 10 activities)
- Period filtering (All Time, 7/30/90/365 Days)
- Responsive design with dark mode support
- Navigation button added to project view page

Technical Implementation:
- New route: project_dashboard() in app/routes/projects.py
- Template: app/templates/projects/dashboard.html with Chart.js 4.4.0
- Data aggregation for budget, tasks, team contributions, and timeline
- Optimized database queries with proper filtering
- JavaScript escaping handled with |tojson filters and autoescape control

Testing:
- 20 comprehensive unit tests (test_project_dashboard.py)
- 23 smoke tests (smoke_test_project_dashboard.py)
- Full test coverage for all dashboard functionality

Documentation:
- Complete feature guide (docs/features/PROJECT_DASHBOARD.md)
- Implementation summary (PROJECT_DASHBOARD_IMPLEMENTATION_SUMMARY.md)
- Usage examples and troubleshooting guide

Fixes:
- JavaScript syntax errors from HTML entity escaping
- Proper use of |tojson filter for dynamic values in JavaScript
- Autoescape disabled for script blocks to prevent operator mangling

This dashboard provides project managers and team members with valuable
insights into project health, progress, budget utilization, and resource
allocation at a glance.
2025-10-30 10:43:31 +01:00
Dries Peeters
54ec5fe4b2 feat: Add bulk task operations and CSV export across all entities
Implements comprehensive bulk operations and export functionality for tasks,
clients, and projects with consistent UI/UX across all three entities.

Features Added:
- Bulk task operations (delete, status change, assignment, move to project)
- Multi-select checkboxes with "select all" functionality
- CSV export for tasks, clients, and projects
- Export respects current filters and permissions
- Modal dialogs for bulk operation confirmation

Bug Fixes:
- Fixed bulk delete not working due to dialog submission issue
- Fixed dropdown menus being cut off in short tables (z-index and overflow)
- Fixed projects export attempting to access .name on string property

Technical Details:
- Backend: Added 5 new routes (tasks bulk ops, 3 export routes)
- Frontend: Updated task/client/project list templates with consistent UI
- Tests: Added 23 comprehensive tests for bulk operations
- Changed table overflow from overflow-x-auto to overflow-visible
- Added z-50 to all dropdown menus for proper layering

Routes Added:
- POST /tasks/bulk-delete
- POST /tasks/bulk-status
- POST /tasks/bulk-assign
- POST /tasks/bulk-move-project
- GET /tasks/export
- GET /clients/export
- GET /projects/export

Files Changed:
- app/routes/tasks.py (+103 lines)
- app/routes/clients.py (+73 lines)
- app/routes/projects.py (+95 lines)
- app/templates/tasks/list.html (major refactor)
- app/templates/clients/list.html (+export, overflow fix)
- app/templates/projects/list.html (+export fix, overflow fix)
- tests/test_bulk_task_operations.py (NEW, 23 tests)
- docs/BULK_TASK_OPERATIONS.md (NEW)
- BULK_TASK_OPERATIONS_IMPLEMENTATION.md (NEW)
- BUGFIXES_BULK_OPERATIONS.md (NEW)
- BUGFIXES_CONSISTENCY_AND_EXPORT.md (NEW)

Breaking Changes: None
Migration Required: None
2025-10-30 10:06:13 +01:00
Dries Peeters
6cad084c8c feat: implement Activity Feed Widget with real-time filtering and audit trail
Add comprehensive Activity Feed Widget to dashboard providing team visibility
and audit trail functionality. The widget displays recent user activities with
advanced filtering, pagination, and auto-refresh capabilities.

Features:
- Dashboard widget showing last 10 activities with infinite scroll
- Filter by entity type (projects, tasks, time entries, templates, users, etc.)
- Real-time auto-refresh every 30 seconds
- Visual indicators for active filters (checkmark + dot)
- Load more pagination with "has_next" detection
- Refresh button with spinning animation feedback

API Endpoints:
- GET /api/activities - Retrieve activities with filtering & pagination
- GET /api/activities/stats - Activity statistics and analytics
- Support for user_id, entity_type, action, and date range filters

Activity Logging Integration:
- Projects: create, update, delete, archive, unarchive
- Tasks: create, update, delete
- Time Entries: start timer, stop timer
- All operations log user, IP address, and user agent for security

UI/UX Improvements:
- Vanilla JS implementation (removed Alpine.js dependency)
- Dark mode support with proper color schemes
- Responsive dropdown with scrollable content
- Action-specific icons (Font Awesome)
- Relative timestamps with timeago filter
- Error handling with user-friendly messages

Testing & Documentation:
- Comprehensive test suite (model, API, integration, widget)
- Feature documentation in docs/features/activity_feed.md
- Implementation summary and integration guide
- Console logging for debugging

Bug Fixes:
- Fixed "Load More" button not appending results
- Fixed refresh clearing list without reloading
- Fixed filter dropdown using Alpine.js (now vanilla JS)
- Fixed entity_type filter sending 'all' to API
- Added missing entity types (time_entry_template, user)

Technical Details:
- Activity model with optimized indexes for performance
- Promise-based async loading with proper error handling
- Credentials included in fetch for authentication
- Filter state management with visual feedback
- Graceful degradation on API failures

Impact:
- Team visibility into real-time activities
- Comprehensive audit trail for compliance
- Better accountability and transparency
- Improved troubleshooting capabilities
2025-10-30 09:20:03 +01:00
Dries Peeters
32bc87db5e feat: Complete Time Entry Templates feature with dashboard integration
Complete the Time Entry Templates feature by adding timer integration
and dashboard UI (70% → 100% complete).

Features Added:
- One-click start timer from template via new route
- Template selector in dashboard "Start Timer" modal
- Template pre-fill for manual time entries
- Auto-populate timer forms with template data
- Usage tracking when templates are used

Backend Changes:
- Added template support to /timer/start route
- Added template pre-fill to /timer/manual route
- New route: /timer/start/from-template/<id> for direct timer start
- Load recent templates (top 5) on dashboard
- All changes include proper validation and error handling

Frontend Changes:
- Template list in dashboard start timer modal
- JavaScript function to apply template data to forms
- Template cards show project/task information
- Link to full template management page
- Responsive design for mobile

Testing:
- Added 6 new integration tests for timer features
- Test start timer from template (success and error cases)
- Test manual entry pre-fill from template
- Test active timer validation
- All 32 tests passing with no linting errors

Documentation:
- Complete user guide (docs/TIME_ENTRY_TEMPLATES.md)
- Technical documentation (docs/features/TIME_ENTRY_TEMPLATES.md)
- Implementation summary with usage examples

Use Case: Quickly start timers for recurring activities
- 80% faster timer start for recurring tasks
- Zero retyping of project, task, notes, tags
- Consistent data across similar time entries
2025-10-30 08:32:11 +01:00
Dries Peeters
20b7401891 feat: Add invoice expenses, enhanced PDF editor with Konva.js, and uploads persistence
Major Features:
- Invoice Expenses: Allow linking billable expenses to invoices with automatic total calculations
  - Add expenses to invoices via "Generate from Time/Costs" workflow
  - Display expenses in invoice view, edit forms, and PDF exports
  - Track expense states (approved, invoiced, reimbursed) with automatic unlinking on invoice deletion
  - Update PDF generator and CSV exports to include expense line items

- Enhanced PDF Invoice Editor: Complete redesign using Konva.js for visual drag-and-drop layout design
  - Add 40+ draggable elements (company info, invoice data, shapes, text, advanced elements)
  - Implement comprehensive properties panel for precise element customization (position, fonts, colors, opacity)
  - Add canvas toolbar with alignment tools, zoom controls, and layer management
  - Support keyboard shortcuts (copy/paste, duplicate, arrow key positioning)
  - Save designs as JSON for editing and generate clean HTML/CSS for rendering
  - Add real-time preview with live data

- Uploads Persistence: Implement Docker volume persistence for user-uploaded files
  - Add app_uploads volume to all Docker Compose configurations
  - Ensure company logos and avatars persist across container rebuilds and restarts
  - Create migration script for existing installations
  - Update directory structure with proper permissions (755 for dirs, 644 for files)

Database & Backend:
- Add invoice_pdf_design_json column to settings table via Alembic migration
- Extend Invoice model with expenses relationship
- Update admin routes for PDF layout designer endpoints
- Enhance invoice routes to handle expense linking/unlinking

Frontend & UI:
- Redesign PDF layout editor template with Konva.js canvas (2484 lines, major overhaul)
- Update invoice edit/view templates to display and manage expenses
- Add expense sections to invoice forms with unlink functionality
- Enhance UI components with keyboard shortcuts support
- Update multiple templates for consistency and accessibility

Testing & Documentation:
- Add comprehensive test suites for invoice expenses, PDF layouts, and uploads persistence
- Create detailed documentation for all new features (5 new docs)
- Include migration guides and troubleshooting sections

Infrastructure:
- Update docker-compose files (main, example, remote, remote-dev, local-test) with uploads volume
- Configure pytest for new test modules
- Add template filters for currency formatting and expense display

This update significantly enhances TimeTracker's invoice management capabilities,
improves the PDF customization experience, and ensures uploaded files persist
reliably across deployments.
2025-10-29 15:03:01 +01:00
Dries Peeters
faec3f4d4d feat: Add admin user deletion with safety checks
- Add delete button to user list with confirmation dialog
- Prevent deletion of last admin and users with time entries
- Include CSRF protection on delete forms
- Add 41 comprehensive tests (unit, model, smoke)
- Document feature with usage guide and best practices

All safety checks implemented and tested.
2025-10-29 07:15:51 +01:00
Dries Peeters
8d4ec0e25f feat(payments): add analytics integration and improve UI consistency
## Payment Analytics Integration
- Add 5 new API endpoints for payment metrics:
  - /api/analytics/payments-over-time - trend visualization
  - /api/analytics/payments-by-status - status distribution
  - /api/analytics/payments-by-method - method breakdown
  - /api/analytics/payment-summary - statistics with period comparison
  - /api/analytics/revenue-vs-payments - collection rate tracking
- Integrate payment data into analytics dashboard with 4 new charts
- Add payment metrics to reports page (total, count, fees, net received)
- Update summary endpoint to include payment statistics

## UI/UX Improvements
- Standardize form styling across all payment templates
  - Replace inconsistent Tailwind classes with form-input utility
  - Update card backgrounds to use card-light/card-dark
  - Fix label spacing to match application patterns
  - Ensure consistent border colors and backgrounds
- Replace browser confirm() with system-wide modal for payment deletion
  - Consistent danger variant with warning icon
  - Keyboard support (Enter/Escape)
  - Dark mode compatible
  - Clear messaging about impact on invoice status

## Technical Changes
- Import Payment and Invoice models in analytics and reports routes
- Add proper admin/user scoping for payment queries
- Maintain responsive design across all new components

Closes payment tracking phase 2 (analytics & polish)
2025-10-27 13:38:07 +01:00
Dries Peeters
154f9b37a6 feat: integrate calendar feature with tasks and time entries display
Refactored the existing calendar API endpoint to properly display calendar
events, tasks, and time entries with distinct visual representations.

Changes:
- Updated /api/calendar/events endpoint in api.py to use new
  CalendarEvent.get_events_in_range() method that fetches all three item types
- Fixed user_id bug where it was defaulting to None instead of current_user.id
- Modified API response format to include all items in unified 'events' array
  with item_type field ('event', 'task', 'time_entry') for differentiation
- Updated calendar.js to parse unified response format and filter items by type
- Added visual distinctions:
  * Tasks: 📋 emoji, orange (#f59e0b) color, clickable
  * Time entries: ⏱ emoji, project-based colors, non-clickable
  * Calendar events: 📅 emoji, custom colors, clickable
- Fixed task detail route from /tasks/view/{id} to /tasks/{id}
- Updated all calendar view renderers (month, week, day) to use correct
  data structure with extendedProps
- Added cache-busting to calendar.js (v7) and calendar.css (v2)
- Preserved backward compatibility with existing calendar filtering
  (project_id, task_id, tags)

The calendar now correctly displays all time tracking data in a unified view
with proper visual hierarchy and interaction patterns.

Fixes: Calendar not showing tasks and time entries
Related: Calendar/Agenda Support feature implementation
2025-10-27 11:40:38 +01:00
Dries Peeters
543be51c15 feat(admin): improve email configuration UI and logging
Enhance the email support feature with better UX and debugging capabilities:

- **Fix input field styling**: Update all form inputs to use project-standard
  'form-input' class and consistent checkbox styling matching other admin
  pages for uniform appearance across the application

- **Add comprehensive logging**: Implement detailed logging throughout email
  operations with clear prefixes ([EMAIL TEST], [EMAIL CONFIG]) to track:
  - Email configuration changes and validation
  - Test email sending process step-by-step
  - SMTP connection details and status
  - Success/failure indicators (✓/✗) for quick troubleshooting

- **Auto-reload after save**: Page now automatically refreshes 1.5 seconds
  after successfully saving email configuration to ensure UI reflects the
  latest settings and eliminate stale data

These improvements provide better visual consistency, easier debugging of
email issues, and smoother user experience when configuring email settings.

Files modified:
- app/templates/admin/email_support.html
- app/utils/email.py
- app/routes/admin.py
2025-10-27 10:13:58 +01:00
Dries Peeters
a1aaee6afd feat: Redesign and enhance backup restore functionality with dual restore methods
Major improvements to the backup restore system with a complete UI overhaul
and enhanced functionality:

UI/UX Improvements:
- Complete redesign of restore page with modern Tailwind CSS
- Added prominent warning banners and danger badges to prevent accidental data loss
- Implemented drag-and-drop file upload with visual feedback
- Added real-time progress tracking with auto-refresh every 2 seconds
- Added comprehensive safety information sidebar with checklists
- Full dark mode support throughout restore interface
- Enhanced confirmation flows with checkbox and modal confirmations

Functionality Enhancements:
- Added dual restore methods: upload new backup or restore from existing server backups
- Enhanced restore route to accept optional filename parameter for existing backups
- Added "Restore" button to each backup in the backups management page
- Implemented restore confirmation modal with critical warnings
- Added loading states and button disabling during restore operations
- Improved error handling and user feedback

Backend Changes:
- Enhanced admin.restore() to support both file upload and existing backup restore
- Added dual route support: /admin/restore and /admin/restore/<filename>
- Added shutil import for file copy operations during restore
- Improved security with secure_filename validation and file type checking
- Maintained existing rate limiting (3 requests per minute)

Frontend Improvements:
- Added interactive JavaScript for file selection, drag-and-drop, and modal management
- Implemented auto-refresh during restore process to show live progress
- Added escape key support for closing modals
- Enhanced user feedback with file name display and button states

Safety Features:
- Pre-restore checklist with 5 verification steps
- Multiple warning levels throughout the flow
- Confirmation checkbox required before upload restore
- Modal confirmation required before existing backup restore
- Clear documentation of what gets restored and post-restore steps

Dependencies:
- Updated flask-swagger-ui from 4.11.1 to 5.21.0

Files modified:
- app/templates/admin/restore.html (complete rewrite)
- app/templates/admin/backups.html (added restore functionality)
- app/routes/admin.py (enhanced restore route)
- requirements.txt (updated flask-swagger-ui version)
- RESTORE_BACKUP_IMPROVEMENTS.md (documentation)

This provides a significantly improved user experience for the restore process
while maintaining security and adding powerful new restore capabilities.
2025-10-27 09:34:51 +01:00
Dries Peeters
c93a37f126 feat: add overtime tracking support with configurable working hours
Implement comprehensive overtime tracking feature that allows users to
set their standard working hours per day and automatically calculates
overtime for hours worked beyond that threshold.

Core Features:
- Add standard_hours_per_day field to User model (default: 8.0 hours)
- Create Alembic migration (031_add_standard_hours_per_day.py)
- Implement overtime calculation utilities (app/utils/overtime.py)
  * calculate_daily_overtime: per-day overtime calculation
  * calculate_period_overtime: multi-day overtime aggregation
  * get_daily_breakdown: detailed day-by-day analysis
  * get_weekly_overtime_summary: weekly overtime statistics
  * get_overtime_statistics: comprehensive overtime metrics

User Interface:
- Add "Overtime Settings" section to user settings page
- Display overtime data in user reports (regular vs overtime hours)
- Show "Days with Overtime" badge in reports
- Add overtime analytics API endpoint (/api/analytics/overtime)
- Improve input field styling with cleaner appearance (no spinners)

Reports Enhancement:
- Standardize form input styling across all report pages
- Replace inline Tailwind classes with consistent form-input class
- Add FontAwesome icons to form labels for better UX
- Improve button hover states and transitions

Testing:
- Add comprehensive unit tests (tests/test_overtime.py)
- Add smoke tests for quick validation (tests/test_overtime_smoke.py)
- Test coverage for models, utilities, and various overtime scenarios

Documentation:
- OVERTIME_FEATURE_DOCUMENTATION.md: complete feature guide
- OVERTIME_IMPLEMENTATION_SUMMARY.md: technical implementation details
- docs/features/OVERTIME_TRACKING.md: quick start guide

This change enables organizations to track employee overtime accurately
based on individual working hour configurations, providing better
insights into work patterns and resource allocation.
2025-10-27 08:44:04 +01:00
Dries Peeters
69f2c80308 feat: Complete Admin Settings UI and enhance PDF logo reliability
This commit addresses multiple issues with the Admin Settings page and
improves PDF invoice logo embedding for better cross-platform reliability.

## Admin Settings UI - Missing Fields Fixed

The Admin → Settings page was incomplete, showing only basic timer and
regional settings. Added all missing sections:

- User Management: Self-registration toggle with admin username note
- Company Branding: Full company info fields (name, email, phone, website,
  address, tax ID, bank info) plus logo upload with preview
- Invoice Defaults: Prefix, start number, payment terms, and notes
- Backup Settings: Retention days and backup time configuration
- Export Settings: CSV delimiter preference selector
- Privacy & Analytics: Telemetry opt-in with detailed privacy information

The backend was already handling these fields - this was purely a frontend
template issue where form fields were missing.

## Analytics/Telemetry Preference Synchronization

Fixed critical bug where analytics checkbox in Admin Settings only updated
the database but not the InstallationConfig file that the telemetry system
actually reads from. Changes now properly sync both systems:

- On page load: Auto-sync database from InstallationConfig (source of truth)
- On save: Update both database AND InstallationConfig simultaneously
- Added logging for analytics preference changes
- Updated UI references: Initial setup and Telemetry dashboard now point
  to Admin → Settings as the primary location
- Added clear privacy information explaining what data is collected

## PDF Logo Embedding Enhancement

Improved logo reliability in PDF invoices by switching from file:// URIs
to base64 data URIs:

- More reliable across platforms (Windows, Linux, macOS)
- Works consistently in Docker containers
- Self-contained (no filesystem path dependencies)
- Automatic MIME type detection for all formats (PNG, JPG, GIF, SVG, WEBP)
- Graceful fallback to file:// URI if base64 fails
- Added comprehensive debug logging for troubleshooting

## Diagnostic Tools & Documentation

- Created test_logo_pdf.py: Diagnostic script to identify logo issues
- Created LOGO_PDF_TROUBLESHOOTING.md: Comprehensive troubleshooting guide
- Enhanced error messages with debug output throughout logo processing
- Added context passing fixes for PDF template rendering

## Files Changed

### Core Fixes
- app/templates/admin/settings.html: Complete rewrite with all sections
- app/routes/admin.py: InstallationConfig sync for analytics preference
- app/static/uploads/logos/.gitkeep: Ensure logos directory tracked by git

### PDF Logo Enhancement
- app/utils/pdf_generator.py: Base64 encoding + explicit context passing
- app/utils/template_filters.py: get_logo_base64() helper with debug logging
- app/templates/invoices/pdf_default.html: Base64 logo embedding

### Analytics Synchronization
- app/templates/setup/initial_setup.html: Updated settings reference
- app/templates/admin/telemetry.html: Cross-reference to Admin → Settings

### Documentation
- docs/GETTING_STARTED.md: Updated to reflect actual UI behavior
- test_logo_pdf.py: New diagnostic script
- LOGO_PDF_TROUBLESHOOTING.md: New troubleshooting guide

## Testing

Run diagnostic script to verify logo configuration:
2025-10-25 07:23:43 +02:00
Dries Peeters
f9b9dbfddc feat: Add extra goods export support to invoice PDFs
Implement comprehensive support for exporting extra goods (products,
services, materials, licenses) in invoice PDF documents. Extra goods
now appear in the invoice items table alongside time-based billing
entries with rich formatting including name, description, SKU codes,
and category labels.

Changes:
- Enhanced InvoicePDFGenerator._generate_items_rows() to include extra
  goods with detailed formatting (name, description, SKU, category)
- Updated pdf_default.html template to render extra goods loop in the
  invoice items table with conditional display of optional fields
- Enhanced InvoicePDFGeneratorFallback._build_items_table() for
  ReportLab compatibility with multi-line descriptions
- Added 6 comprehensive tests covering both WeasyPrint and ReportLab
  generators (unit tests and smoke tests)
- Created complete feature documentation in
  docs/INVOICE_EXTRA_GOODS_PDF_EXPORT.md

Technical Details:
- Extra goods display quantity, unit price, and total amount
- Automatic inclusion in invoice totals via existing calculate_totals()
- No database migrations required (extra_goods table already exists)
- Backward compatible - invoices without goods unchanged
- Supports both primary (WeasyPrint) and fallback (ReportLab) generators

Testing:
- 6 new tests added to tests/test_invoices.py
- 3 tests pass on Windows (ReportLab fallback)
- 3 tests require WeasyPrint system dependencies (Linux/Docker)
- All code changes validated with no linter errors

Files Modified:
- app/utils/pdf_generator.py
- app/templates/invoices/pdf_default.html
- app/utils/pdf_generator_fallback.py
- tests/test_invoices.py

Files Created:
- docs/INVOICE_EXTRA_GOODS_PDF_EXPORT.md
- INVOICE_GOODS_EXPORT_IMPLEMENTATION_SUMMARY.md
2025-10-24 13:13:29 +02:00
Dries Peeters
944b69a7fc feat: implement full permission enforcement and enhanced UI visibility
BREAKING CHANGE: Permission system now actively enforced across all routes

## Summary
Complete implementation of advanced role-based access control (RBAC) system
with full route protection, UI conditionals, and enhanced management interface.

## Route Protection
- Updated all admin routes to use @admin_or_permission_required decorator
- Replaced inline admin checks with granular permission checks in:
  * Admin routes: user management, settings, backups, telemetry, OIDC
  * Project routes: create, edit, delete, archive, bulk operations
  * Client routes: create, edit, delete, archive, bulk operations
- Maintained backward compatibility with existing @admin_required decorator

## UI Permission Integration
- Added template helpers (has_permission, has_any_permission) to all templates
- Navigation conditionally shows admin/OIDC links based on permissions
- Action buttons (Edit, Delete, Archive) conditional on user permissions
- Project and client pages respect permission requirements
- Create buttons visible only with appropriate permissions

## Enhanced Roles & Permissions UI
- Added statistics dashboard showing:
  * Total roles, system roles, custom roles, assigned users
- Implemented expandable permission details in roles list
  * Click to view all permissions grouped by category
  * Visual checkmarks for assigned permissions
- Enhanced user list with role visibility:
  * Shows all assigned roles as color-coded badges
  * Blue badges for system roles, gray for custom roles
  * Yellow badges for legacy roles with migration prompt
  * Merged legacy role column into unified "Roles & Permissions"
- User count per role now clickable and accurate

## Security Improvements
- Added CSRF tokens to all new permission system forms:
  * Role creation/edit form
  * Role deletion form
  * User role assignment form
- All POST requests now protected against CSRF attacks

## Technical Details
- Fixed SQLAlchemy relationship query issues (AppenderQuery)
- Proper use of .count() for relationship aggregation
- Jinja2 namespace for accumulating counts in templates
- Responsive grid layouts for statistics and permission cards

## Documentation
- Created comprehensive implementation guides
- Added permission enforcement documentation
- Documented UI enhancements and features
- Included CSRF protection review

## Impact
- Permissions are now actively enforced, not just defined
- Admins can easily see who has what access
- Clear visual indicators of permission assignments
- Secure forms with CSRF protection
- Production-ready permission system
2025-10-24 12:49:54 +02:00
Dries Peeters
a02fec04c8 feat: Add comprehensive expense tracking system
Implement a complete expense tracking feature that allows users to record,
manage, approve, and track business expenses with full integration into
existing project management and invoicing systems.

Features:
- Create and manage expenses with detailed information (amount, category,
  vendor, receipts, tax tracking)
- Multi-currency support (EUR, USD, GBP, CHF)
- Approval workflow with admin oversight (pending → approved → rejected)
- Reimbursement tracking and status management
- Billable expense flagging for client invoicing
- Receipt file upload and attachment
- Project and client association with auto-client selection
- Tag-based organization and advanced filtering
- CSV export functionality
- Analytics dashboard with category breakdowns
- API endpoints for programmatic access

Database Changes:
- Add expenses table with comprehensive schema
- Create Alembic migration (029_add_expenses_table.py)
- Add composite indexes for query performance
- Implement proper foreign key constraints and cascading

Routes & Templates:
- Add expenses blueprint with 14 endpoints (CRUD, approval, export, API)
- Create 4 responsive templates (list, form, view, dashboard)
- Implement advanced filtering (status, category, project, client, date range)
- Add permission-based access control (user vs admin)
- Integrate receipt file upload handling

User Experience:
- Add "Expenses" to Insights navigation menu
- Auto-populate client when project is selected
- Provide visual feedback for auto-selections
- Display summary statistics and analytics
- Implement pagination and search functionality

Testing & Documentation:
- Add 40+ comprehensive tests covering models, methods, and workflows
- Create complete user documentation (docs/EXPENSE_TRACKING.md)
- Add API documentation and examples
- Include troubleshooting guide and best practices

Integration:
- Link expenses to projects for cost tracking
- Associate with clients for billing purposes
- Connect billable expenses to invoicing system
- Add PostHog event tracking for analytics
- Implement structured logging for audit trail

Security:
- Role-based access control (users see only their expenses)
- Admin-only approval and reimbursement actions
- CSRF protection and file upload validation
- Proper permission checks on all operations

This implementation follows existing codebase patterns and includes full
test coverage, documentation, and database migrations per project standards.
2025-10-24 10:42:51 +02:00
Dries Peeters
dffa101936 Merge pull request #143 from DRYTRIX/Feat-Weekly-Time-Goals
feat: Add Weekly Time Goals feature for tracking weekly hour targets
2025-10-24 10:20:13 +02:00
Dries Peeters
d530ce48b0 feat: Add Weekly Time Goals feature for tracking weekly hour targets
Implemented a comprehensive Weekly Time Goals system that allows users to set
and track weekly hour targets with real-time progress monitoring.

Features:
- WeeklyTimeGoal model with status tracking (active, completed, failed, cancelled)
- Full CRUD interface for managing weekly goals
- Real-time progress calculation based on logged time entries
- Dashboard widget showing current week's goal progress
- Daily breakdown view with detailed statistics
- Automatic status updates based on goal completion and week end
- API endpoints for goal data and progress tracking

Technical changes:
- Added app/models/weekly_time_goal.py with local timezone support
- Created migration 027_add_weekly_time_goals.py for database schema
- Added app/routes/weekly_goals.py blueprint with all CRUD routes
- Created templates: index.html, create.html, edit.html, view.html
- Integrated weekly goal widget into main dashboard
- Added "Weekly Goals" navigation item to sidebar
- Implemented comprehensive test suite in tests/test_weekly_goals.py
- Added feature documentation in docs/WEEKLY_TIME_GOALS.md

Bug fixes:
- Fixed timezone handling to use TZ environment variable instead of Config.TIMEZONE
- Corrected log_event() calls to use proper signature (event name as first positional argument)
- Manually created database table via SQL when Alembic migration didn't execute

Database schema:
- weekly_time_goals table with user_id, target_hours, week_start_date, week_end_date, status, notes
- Indexes on user_id, week_start_date, status, and composite (user_id, week_start_date)
- Foreign key constraint to users table with CASCADE delete

The feature supports flexible week start days per user, calculates remaining hours,
provides daily average targets, and automatically updates goal status based on progress.
2025-10-24 10:15:03 +02:00
Dries Peeters
48ec29e096 feat: Add per-user time rounding preferences
Implement comprehensive time rounding preferences that allow each user to
configure how their time entries are rounded when stopping timers.

Features:
- Per-user rounding settings (independent from global config)
- Multiple rounding intervals: 1, 5, 10, 15, 30, 60 minutes
- Three rounding methods: nearest, up (ceiling), down (floor)
- Enable/disable toggle for flexible time tracking
- Real-time preview showing rounding examples
- Backward compatible with existing global rounding settings

Database Changes:
- Add migration 027 with three new user columns:
  * time_rounding_enabled (Boolean, default: true)
  * time_rounding_minutes (Integer, default: 1)
  * time_rounding_method (String, default: 'nearest')

Implementation:
- Update User model with rounding preference fields
- Modify TimeEntry.calculate_duration() to use per-user rounding
- Create app/utils/time_rounding.py with core rounding logic
- Update user settings route and template with rounding UI
- Add comprehensive unit, model, and smoke tests (50+ test cases)

UI/UX:
- Add "Time Rounding Preferences" section to user settings page
- Interactive controls with live example visualization
- Descriptive help text and method explanations
- Fix navigation: Settings link now correctly points to user.settings
- Fix CSRF token in settings form

Documentation:
- Add comprehensive user guide (docs/TIME_ROUNDING_PREFERENCES.md)
- Include API documentation and usage examples
- Provide troubleshooting guide and best practices
- Add deployment instructions for migration

Testing:
- Unit tests for rounding logic (tests/test_time_rounding.py)
- Model integration tests (tests/test_time_rounding_models.py)
- End-to-end smoke tests (tests/test_time_rounding_smoke.py)

Fixes:
- Correct settings navigation link in user dropdown menu
- Fix CSRF token format in user settings template

This feature enables flexible billing practices, supports different client
requirements, and maintains exact time tracking when needed.
2025-10-24 09:36:03 +02:00
Dries Peeters
6de86fca2b feat: Implement comprehensive project archiving system
Add enhanced project archiving functionality for better organization of
completed projects with metadata tracking and validation.

Key Features:
- Archive metadata tracking (timestamp, user, reason)
- Archive form with quick-select reason templates
- Bulk archiving with optional shared reason
- Archive information display on project details
- Prevent time tracking on archived projects
- Activity logging for archive/unarchive actions

Database Changes:
- Add migration 026_add_project_archiving_metadata.py
- New fields: archived_at, archived_by (FK), archived_reason
- Index on archived_at for faster filtering
- Cascade on user deletion (SET NULL)

Model Enhancements (app/models/project.py):
- Enhanced archive() method with user_id and reason parameters
- Enhanced unarchive() method to clear all metadata
- New properties: is_archived, archived_by_user
- Updated to_dict() to include archive metadata

Route Updates (app/routes/projects.py):
- Convert archive route to GET/POST (form-based)
- Add archive reason handling
- Enhanced bulk operations with reason support
- Activity logging for all archive operations

UI Improvements:
- New archive form template (app/templates/projects/archive.html)
- Quick-select buttons for common archive reasons
- Archive metadata display on project view page
- Bulk archive modal with reason input
- Updated project list filtering

Validation (app/routes/timer.py):
- Prevent timer start on archived projects
- Block manual entry creation on archived projects
- Block bulk entry creation on archived projects
- Clear error messages for users

Testing:
- 90+ comprehensive test cases
- Unit tests (tests/test_project_archiving.py)
- Model tests (tests/test_project_archiving_models.py)
- Smoke tests for complete workflows
- Edge case coverage

Documentation:
- User guide (docs/PROJECT_ARCHIVING_GUIDE.md)
- Implementation summary (PROJECT_ARCHIVING_IMPLEMENTATION_SUMMARY.md)
- API reference and examples
- Best practices and troubleshooting

Migration Notes:
- Backward compatible with existing archived projects
- Existing archives will have NULL metadata (can be added later)
- No data migration required
- Run: migrations/manage_migrations.py upgrade head

Breaking Changes: None
- All changes are additive and backward compatible

Related: Feat-Project-Archiving branch
2025-10-24 09:06:51 +02:00
Dries Peeters
935f30e4d6 feat: Add Client Notes feature for internal client tracking
Implement comprehensive client notes system allowing users to add
internal notes about clients that are never visible to clients
themselves. Notes support importance flagging, full CRUD operations,
and proper access controls.

Key Changes:
- Add ClientNote model with user/client relationships
- Create Alembic migration (025) for client_notes table
- Implement full REST API with 9 endpoints
- Add client_notes blueprint with CRUD routes
- Create UI templates (edit page + notes section on client view)
- Add importance toggle with AJAX functionality
- Implement permission system (users edit own, admins edit all)

Features:
- Internal-only notes with rich text support
- Mark notes as important for quick identification
- Author tracking with timestamps
- Cascade delete when client is removed
- Mobile-responsive design
- i18n support for all user-facing text

Testing:
- 24 comprehensive model tests
- 23 route/integration tests
- Full coverage of CRUD operations and permissions

Documentation:
- Complete feature guide in docs/CLIENT_NOTES_FEATURE.md
- API documentation with examples
- Troubleshooting section
- Updated main docs index

Database:
- Migration revision 025 (depends on 024)
- Fixed PostgreSQL boolean default value issue
- 4 indexes for query performance
- CASCADE delete constraint on client_id

This feature addresses the need for teams to track important
information about clients internally without exposing sensitive
notes to client-facing interfaces or documents.
2025-10-24 08:37:51 +02:00
Dries Peeters
ef427ed3ed feat: Add comprehensive testing and documentation for Time Entry Templates
- Add 26 comprehensive tests (all passing) covering models, routes, API, and integration
- Add user documentation (docs/features/TIME_ENTRY_TEMPLATES.md)
- Add developer documentation (docs/TIMETRACKER_TEMPLATES_IMPLEMENTATION.md)
- Add implementation summaries and completion reports
- Verify feature integration with navigation menu
- All tests passing, feature production-ready

Related to Quick Wins implementation (migration revision 022)
2025-10-24 08:20:59 +02:00
Dries Peeters
e9a7817cc6 feat: implement enhanced keyboard shortcuts system with context-awareness
Implements a comprehensive keyboard shortcuts system that goes far beyond
a simple command palette, providing 50+ shortcuts, context-aware behavior,
visual cheat sheet, usage analytics, and full customization capabilities.

Features:
- 50+ keyboard shortcuts across 10 categories (Navigation, Creation, Timer,
  Table, Form, Modal, Global, Help, Accessibility)
- Context-aware shortcuts that adapt based on user activity:
  * Global context: available everywhere
  * Table context: j/k navigation, Ctrl+A select all, Delete for bulk delete
  * Form context: Ctrl+S to save, Ctrl+Enter to submit, Escape to cancel
  * Modal context: Escape to close, Enter to confirm
- Vim-style key sequences (g d for dashboard, c p for create project, etc.)
- Visual cheat sheet (Shift+?) with search, categories, and statistics
- Full settings page with configuration options and usage analytics
- Usage tracking and statistics (most-used shortcuts, recent usage, counts)
- Onboarding hints for first-time users
- WCAG 2.1 Level AA accessibility compliance

New Files:
- app/static/keyboard-shortcuts-enhanced.js (main shortcuts manager, 1200 lines)
- app/static/keyboard-shortcuts.css (styling for all UI components, 600 lines)
- app/templates/settings/keyboard_shortcuts.html (settings page, 350 lines)
- app/routes/settings.py (new settings blueprint with keyboard shortcuts route)
- docs/features/KEYBOARD_SHORTCUTS_ENHANCED.md (comprehensive user guide)
- docs/KEYBOARD_SHORTCUTS_IMPLEMENTATION.md (developer implementation guide)
- docs/features/KEYBOARD_SHORTCUTS_README.md (quick reference)
- tests/test_keyboard_shortcuts.py (40+ test cases covering routes, integration,
  accessibility, performance, security, and edge cases)
- KEYBOARD_SHORTCUTS_SUMMARY.md (implementation summary)

Modified Files:
- app/__init__.py: registered settings blueprint
- app/templates/base.html: added keyboard-shortcuts.css and
  keyboard-shortcuts-enhanced.js includes

Key Shortcuts:
Navigation: g+d (dashboard), g+p (projects), g+t (tasks), g+r (reports)
Creation: c+p (project), c+t (task), c+c (client), c+e (time entry)
Timer: t+s (start), t+p (pause), t+l (log time), t+b (bulk entry)
Global: Ctrl+K (palette), Ctrl+/ (search), Shift+? (help), Ctrl+B (sidebar)

Technical Details:
- Zero runtime dependencies (vanilla JavaScript)
- LocalStorage for persistence (stats, custom shortcuts, settings)
- Performance: <50ms load time impact, <1MB memory, 23KB total size
- Browser support: Chrome/Edge 90+, Firefox 88+, Safari 14+
- Responsive design with mobile support
- Dark mode compatible
- Print-friendly layouts

Accessibility:
- Full keyboard-only navigation
- Screen reader support with ARIA labels
- High contrast mode support
- Reduced motion support (prefers-reduced-motion)
- Skip to main content shortcut (Alt+1)
- Focus indicators for keyboard navigation

Testing:
- 40+ test cases (unit, integration, accessibility, performance, security)
- Route tests for settings pages
- Integration tests with base template
- Security tests (auth, XSS, CSRF)
- Performance tests (load time, file size)
- Edge case coverage

Documentation:
- 1500+ lines of comprehensive user and developer documentation
- Usage guide with examples
- Troubleshooting and FAQ sections
- Implementation guide for developers
- Quick reference card

This implementation significantly enhances user productivity and provides
a modern, accessible keyboard-driven interface for power users.
2025-10-23 21:31:39 +02:00
Dries Peeters
18d9808d5e feat: add user favorite projects functionality with CSV export enhancements
Features:
Add favorite projects feature allowing users to star/bookmark frequently used projects
New UserFavoriteProject association model with user-project relationships
Star icons in project list for one-click favorite toggling via AJAX
Filter to display only favorite projects
Per-user favorites with proper isolation and cascade delete behavior
Activity logging for favorite/unfavorite actions
Database:
Add user_favorite_projects table with migration (023_add_user_favorite_projects.py)
Foreign keys to users and projects with CASCADE delete
Unique constraint preventing duplicate favorites
Indexes on user_id and project_id for query optimization
Models:
User model: Add favorite_projects relationship with helper methods
add_favorite_project() - add project to favorites
remove_favorite_project() - remove from favorites
is_project_favorite() - check favorite status
get_favorite_projects() - retrieve favorites with status filter
Project model: Add is_favorited_by() method and include favorite status in to_dict()
Export UserFavoriteProject model in app/models/__init__.py
Routes:
Add /projects/<id>/favorite POST endpoint to favorite a project
Add /projects/<id>/unfavorite POST endpoint to unfavorite a project
Update /projects GET route to support favorites=true query parameter
Fix status filtering to work correctly with favorites JOIN query
Add /reports/export/form GET endpoint for enhanced CSV export form
Templates:
Update projects/list.html:
Add favorites filter dropdown to filter form (5-column grid)
Add star icon column with Font Awesome icons (filled/unfilled)
Add JavaScript toggleFavorite() function for AJAX favorite toggling
Improve hover states and transitions for better UX
Pass favorite_project_ids and favorites_only to template
Update reports/index.html:
Update CSV export link to point to new export form
Add icon and improve hover styling
Reports:
Enhance CSV export functionality with dedicated form page
Add filter options for users, projects, clients, and date ranges
Set default date range to last 30 days
Import Client model and or_ operator for advanced filtering
Testing:
Comprehensive test suite in tests/test_favorite_projects.py (550+ lines)
Model tests for UserFavoriteProject creation and validation
User/Project method tests for favorite operations
Route tests for favorite/unfavorite endpoints
Filtering tests for favorites-only view
Relationship tests for cascade delete behavior
Smoke tests for complete workflows
Coverage for edge cases and error handling
Documentation:
Add comprehensive feature documentation in docs/FAVORITE_PROJECTS_FEATURE.md
User guide with step-by-step instructions
Technical implementation details
API documentation for new endpoints
Migration guide and troubleshooting
Performance and security considerations
Template Cleanup:
Remove duplicate templates from root templates/ directory
Admin templates (dashboard, users, settings, OIDC debug, etc.)
Client CRUD templates
Error page templates
Invoice templates
Project templates
Report templates
Timer templates
All templates now properly located in app/templates/
Breaking Changes:
None - fully backward compatible
Migration Required:
Run alembic upgrade head to create user_favorite_projects table
2025-10-23 21:15:16 +02:00
Dries Peeters
763978a9d8 Merge pull request #135 from DRYTRIX/Feat-Time-Entry-Duplication
feat: Add Time Entry Duplication functionality
2025-10-23 20:32:33 +02:00
Dries Peeters
6df92646a1 feat: Add Time Entry Duplication functionality
Implement comprehensive time entry duplication feature that allows users
to quickly copy previous entries with pre-filled data, improving
productivity for repetitive time tracking tasks.

Features:
- Add duplicate route endpoint (/timer/duplicate/<id>)
- Add duplicate buttons to dashboard and edit entry pages
- Pre-fill project, task, notes, tags, and billable status
- Show information banner with original entry details
- Implement permission checks (users can duplicate own entries, admins can duplicate any)
- Track analytics events for duplication actions

Backend Changes:
- app/routes/timer.py: Add duplicate_timer() route with security checks
- Route handles pre-filling manual entry form with original entry data
- Analytics tracking for 'timer.duplicated' events

Frontend Changes:
- app/templates/main/dashboard.html: Add duplicate icon button to Recent Entries table
- templates/timer/edit_timer.html: Add duplicate button next to Back button
- app/templates/timer/manual_entry.html: Support pre-filled data and duplication context
- Add blue information banner showing original entry details when duplicating

Testing:
- Add comprehensive test suite with 21 tests (all passing)
- tests/test_time_entry_duplication.py: Unit, integration, security, smoke, and edge case tests
- Test coverage includes: route access, authentication, pre-fill functionality, permissions, UI visibility

Documentation:
- docs/features/TIME_ENTRY_DUPLICATION.md: Technical documentation
- docs/user-guides/DUPLICATING_TIME_ENTRIES.md: User guide with examples
- TIME_ENTRY_DUPLICATION_IMPLEMENTATION.md: Implementation details
- TIME_ENTRY_DUPLICATION_FEATURE_SUMMARY.md: Complete feature overview

Benefits:
- Saves ~60% time when logging similar work
- Reduces manual data entry for recurring tasks
- Maintains data consistency through field copying
- Intuitive workflow with clear visual feedback

Security:
- Users can only duplicate their own entries
- Admin users can duplicate any entry
- Proper authentication and permission checks

Breaking Changes: None
2025-10-23 20:31:51 +02:00
Dries Peeters
81a68bf046 feat: Add enhanced CSV export with comprehensive filtering options
Implement robust CSV export feature with 8 filter options:
- Date range, user (admin), client, project, task
- Billable status, entry source, tags search

Features:
- New /reports/export/form route with modern UI
- Enhanced CSV output with task and timestamp columns
- Dynamic task loading based on project selection
- Smart filename generation with filter indicators
- Permission enforcement and analytics tracking

Files modified:
- app/routes/reports.py (enhanced routes)
- app/templates/reports/index.html (updated link)
- tests/test_routes.py (added tests)

Files created:
- app/templates/reports/export_form.html
- docs/features/CSV_EXPORT_ENHANCED.md
2025-10-23 20:04:07 +02:00
Dries Peeters
7dd39ef55a feat(ci): enhance PostHog credential injection visibility in release builds
Improved the Release Build workflow to clearly show that PostHog and Sentry
credentials are being injected from the GitHub Secret Store, providing better
transparency and auditability.

Changes:
- Enhanced workflow step name to explicitly mention "GitHub Secrets"
- Added comprehensive logging with visual separators and clear sections
- Added before/after file content display showing placeholder replacement
- Added secret availability verification with format validation
- Added detailed error messages with step-by-step fix instructions
- Enhanced release summary to highlight successful credential injection
- Updated build configuration documentation with cross-references

Benefits:
- Developers can immediately see credentials come from GitHub Secret Store
- Security teams have clear audit trail of credential injection process
- Better troubleshooting with detailed error messages
- Secrets remain protected with proper redaction (first 8 + last 4 chars)
- Multiple validation steps ensure correct injection

The workflow now outputs 50+ lines of structured logging showing:
- Secret store location (Settings → Secrets and variables → Actions)
- Target file being modified (app/config/analytics_defaults.py)
- Verification that secrets are available
- Format validation (phc_* pattern for PostHog)
- Confirmation of successful placeholder replacement
- Summary with redacted credential previews

Workflow: .github/workflows/cd-release.yml
Documentation: docs/cicd/README_BUILD_CONFIGURATION.md

Fully backward compatible - no breaking changes.
2025-10-23 15:32:57 +02:00
Dries Peeters
0c316ac5e1 feat: Implement bulk operations and status management improvements
Major improvements:
- Add bulk operations functionality across clients, projects, and tasks
- Implement deletion and status management enhancements
- Add project code field with database migration (022)
- Improve inactive status handling for projects

Backend changes:
- Update project model with new code field and status logic
- Enhance routes for clients, projects, and tasks with bulk actions
- Add migration for project_code field (022_add_project_code_field.py)

Frontend updates:
- Refactor bulk actions widget component
- Update clients list and detail views with bulk operations
- Enhance project list, view, and kanban templates
- Improve task list, edit, view, and kanban displays
- Update base template with UI improvements
- Refine saved filters and time entry templates lists

Testing:
- Add test_project_inactive_status.py for status handling
- Update test_tasks_templates.py with new functionality

Documentation:
- Add BULK_OPERATIONS_IMPROVEMENTS.md
- Add DELETION_AND_STATUS_IMPROVEMENTS.md
- Add docs/QUICK_WINS_IMPLEMENTATION.md
- Update ALL_BUGFIXES_SUMMARY.md and IMPLEMENTATION_COMPLETE.md
2025-10-23 12:41:22 +02:00
Dries Peeters
5280cbad2c fix: prevent re-creation of deleted default client and project
Implements persistent flag tracking to ensure default client and project
are only created on fresh installations and never recreated after user
deletion during updates or restarts.

- Added initial_data_seeded flag to InstallationConfig
- Updated all 3 database initialization scripts to check flag
- Added 3 unit tests (all passing)
- Created comprehensive documentation

Fixes issue where defaults were recreated after deletion during updates.
2025-10-23 09:31:39 +02:00
Dries Peeters
34946e1b80 feat: Make user profile pictures persistent across Docker updates
Store user avatars in persistent /data volume instead of application
directory to ensure profile pictures survive container rebuilds and
version updates.

Changes:
- Update avatar upload folder from app/static/uploads/avatars to
  /data/uploads/avatars using existing app_data volume mount
- Modify get_avatar_upload_folder() in auth routes to use persistent
  location with UPLOAD_FOLDER config
- Update User.get_avatar_path() to reference new storage location
- Add migration script to safely move existing avatars to new location
- Preserve backward compatibility - no database changes required

Benefits:
- Profile pictures now persist between Docker image updates
- Consistent with company logo storage pattern (/data/uploads)
- Better user experience - avatars not lost during upgrades
- Production-ready data/code separation
- All persistent uploads consolidated in app_data volume

Migration:
For existing installations with user avatars, run:
  docker-compose run --rm app python /app/docker/migrate-avatar-storage.py

New installations work automatically with no action required.

Documentation:
- docs/AVATAR_STORAGE_MIGRATION.md - Full migration guide
- docs/AVATAR_PERSISTENCE_SUMMARY.md - Quick reference
- docs/TEST_AVATAR_PERSISTENCE.md - Testing guide
- AVATAR_PERSISTENCE_CHANGELOG.md - Detailed changelog

Files modified:
- app/routes/auth.py
- app/models/user.py

Files added:
- docker/migrate-avatar-storage.py
- docs/AVATAR_STORAGE_MIGRATION.md
- docs/AVATAR_PERSISTENCE_SUMMARY.md
- docs/TEST_AVATAR_PERSISTENCE.md
- AVATAR_PERSISTENCE_CHANGELOG.md

Tested: ✓ No linter errors, backward compatible, volume mount verified
2025-10-22 11:12:11 +02:00
Dries Peeters
6559dd948b fix: resolve profile picture upload issues
- Add client_max_body_size 10M to nginx config to fix 413 error
- Add JavaScript preview for profile picture selection
- Include client-side validation for file size and type
2025-10-22 10:10:14 +02:00
Dries Peeters
84e2096602 feat: enhance CI/CD workflows and improve UX features
This commit improves the testing workflow, CI/CD documentation, and user experience:

## CI/CD Improvements:
- Add comprehensive testing strategy documentation to CD release workflow
- Document workflow triggers and testing approach in ci-comprehensive.yml
- Update CI/CD documentation with testing workflow details

## UX Enhancements:
- Add localStorage persistence for PWA install prompt dismissal
- Prevent repeated PWA install prompts after user dismisses
- Add dismiss button (×) to PWA install toast notification

## Dashboard Features:
- Add edit and delete actions to recent time entries table
- Include delete confirmation dialogs for time entries
- Add notes field to "Start Timer" modal
- Improve table layout with actions column

## Documentation:
- Create TESTING_WORKFLOW_STRATEGY.md for comprehensive testing guidelines
- Add QUICK_REFERENCE_TESTING.md for quick testing reference
- Document changes in CHANGES_SUMMARY_TESTING_WORKFLOW.md
- Update README_CI_CD_SECTION.md with workflow details

## Other Changes:
- Update setup.py configuration
- Enhance task templates (create/edit/view) with improved UI

These changes improve developer experience with better testing documentation
and enhance user experience with smarter PWA prompts and dashboard functionality.
2025-10-22 07:28:39 +02:00
Dries Peeters
79e826ced2 feat(tasks,ui): enhance task management UI; update routes; add tests
Improve task workflows and overall UX, and align backend routes with the
new UI flows. Update docs and development setup accordingly.

- UI: refine task list/view/edit templates, project views, and Kanban
  partial (`_kanban_tailwind.html`)
- CSS: polish `app/static/enhanced-ui.css` for spacing, layout, and
  responsiveness
- Routes: update `app/routes/tasks.py` and `app/routes/clients.py` to
  support new edit/delete/filter behaviors and validations
- Templates: align clients/projects pages for consistency and navigation
- Docs: refresh `docs/GETTING_STARTED.md` and
  `docs/TASK_MANAGEMENT_README.md`
- Dev: adjust `docker-compose.yml` and `setup.py` to match the latest
  runtime/build expectations
- Tests: add coverage for delete actions, task project editing, and task
  filters UI (`tests/test_delete_actions.py`,
  `tests/test_task_edit_project.py`,
  `tests/test_tasks_filters_ui.py`); update existing tests

Why:
- Streamlines common task operations and improves discoverability
- Ensures backend and UI are consistent and well-tested
2025-10-21 17:05:00 +02:00
Dries Peeters
330c4f2b5b Update install instructions 2025-10-21 13:00:59 +02:00
Dries Peeters
f390a13474 chore(devops): streamline Docker Compose and refresh docs/config
- Simplify docker-compose setup and align environment defaults
- Update README and Quick Start to reflect the new compose flow
- Refine app initialization and configuration for clearer env handling
- Minor consistency and cleanup in config modules

No breaking changes expected.
2025-10-20 20:44:11 +02:00
Dries Peeters
e4789cc26e feat: Add telemetry and analytics infrastructure with observability stack
Implement comprehensive analytics and monitoring system with PostHog integration,
complete observability stack (Prometheus, Grafana, Loki, Promtail), and CI/CD
workflows for automated builds.

Features:
- Add PostHog telemetry integration with privacy-focused event tracking
- Implement installation flow for opt-in telemetry configuration
- Add telemetry management UI in admin panel with detailed transparency
- Track key user events across all major features (projects, tasks, timer, etc.)

Infrastructure:
- Set up Prometheus for metrics collection
- Configure Grafana for visualization dashboards
- Integrate Loki and Promtail for log aggregation
- Add separate analytics docker-compose configuration

CI/CD:
- Add GitHub Actions workflows for building and publishing Docker images
- Implement separate dev and production build pipelines
- Configure automated image publishing to registry

Documentation:
- Restructure documentation into organized docs/ directory
- Add comprehensive guides for telemetry, analytics, and local development
- Create transparency documentation for tracked events
- Add CI/CD and build configuration guides

Code improvements:
- Integrate telemetry hooks across all route handlers
- Add feature flags and configuration management
- Refactor test suite for analytics functionality
- Clean up root directory by moving docs and removing test artifacts

Breaking changes:
- Requires new environment variables for PostHog configuration
- Docker compose setup now supports analytics stack

Changes: 73 files changed, 955 insertions(+), 14126 deletions(-)
2025-10-20 14:38:57 +02:00
Dries Peeters
04ed5ef8ae fix(oidc): only perform RP-Initiated Logout when OIDC_POST_LOGOUT_REDIRECT_URI is set
ixes #88

When OIDC_POST_LOGOUT_REDIRECT_URI was unset, the application was still
attempting RP-Initiated Logout by falling back to a generated redirect URL.
This caused issues with OIDC providers like Authelia that don't support
RP-Initiated Logout, resulting in failed redirects to unsupported endpoints.

Changes:
- Modified logout logic in app/routes/auth.py to only attempt provider
  logout when OIDC_POST_LOGOUT_REDIRECT_URI is explicitly configured
- If unset, users are now logged out locally and redirected to the
  TimeTracker login page (expected behavior)
- If set, RP-Initiated Logout proceeds as before (backward compatible)

Documentation:
- Updated docs/OIDC_SETUP.md with guidance on when to set the config
- Added clear comments in env.example explaining optional behavior
- Documented troubleshooting steps for providers without RP-Initiated
  Logout support (e.g., Authelia)

Tests:
- Added comprehensive test suite (tests/test_oidc_logout.py) with 9 tests
  covering different logout scenarios and edge cases
- All existing tests continue to pass (no regressions)

This change is fully backward compatible. Users with providers supporting
RP-Initiated Logout can continue using OIDC_POST_LOGOUT_REDIRECT_URI as
before. Users with providers like Authelia should leave it unset for
local-only logout.
2025-10-17 12:51:43 +02:00
Dries Peeters
3c3faf13d4 feat: Implement Tailwind CSS UI redesign across application
Migrate frontend from custom CSS to Tailwind CSS framework with comprehensive
template updates and improved component structure.

Breaking Changes:
- Remove legacy CSS files (base.css, calendar.css, ui.css, etc.)
- Replace with Tailwind-based styling system

New Features:
- Add Tailwind CSS configuration with PostCSS pipeline
- Create new template components for admin, clients, invoices, projects, reports
- Add form-bridge.css for smooth transition between legacy and Tailwind styles
- Add default avatar SVG asset
- Implement Tailwind-based kanban board template
- Add comprehensive UI quick wins documentation

Infrastructure:
- Add package.json with Tailwind dependencies
- Configure PostCSS and Tailwind build pipeline
- Update .gitignore for Node modules and build artifacts

Testing:
- Add template rendering tests (test_tasks_templates.py)
- Add UI component tests (test_ui_quick_wins.py)

Templates Added:
- Admin: dashboard, settings, system info, user management
- Clients: list and detail views
- Invoices: full CRUD templates with payment recording
- Projects: list, detail, and Tailwind kanban views
- Reports: comprehensive reporting templates
- Timer: manual entry interface

This commit represents the first phase of the UI redesign initiative,
maintaining backward compatibility where needed while establishing the
foundation for modern, responsive interfaces.
2025-10-17 11:51:36 +02:00
Dries Peeters
94e8e49439 feat: Add HTTPS support with mkcert and automatic SSL configuration
Add comprehensive HTTPS support with two deployment options:
- mkcert for local development with trusted certificates
- Automatic SSL with Let's Encrypt for production

HTTPS Implementation:
- Add docker-compose.https-mkcert.yml for local HTTPS development
- Add docker-compose.https-auto.yml for automatic SSL certificates
- Create Dockerfile.mkcert for certificate generation
- Add setup scripts (setup-https-mkcert.sh/bat)
- Add startup scripts (start-https.sh/bat)
- Add certificate generation script (generate-mkcert-certs.sh)

CSRF and IP Access Fixes:
- Fix CSRF token validation for IP-based access
- Add CSRF troubleshooting documentation
- Update configuration to handle various access patterns

Documentation:
- Add HTTPS_MKCERT_GUIDE.md with setup instructions
- Add README_HTTPS.md with general HTTPS documentation
- Add README_HTTPS_AUTO.md for automatic SSL setup
- Add AUTOMATIC_HTTPS_SUMMARY.md
- Add CSRF_IP_ACCESS_FIX.md and CSRF_IP_FIX_SUMMARY.md
- Add docs/CSRF_IP_ACCESS_GUIDE.md
- Update main README.md with HTTPS information

Configuration:
- Update .gitignore for SSL certificates and nginx configs
- Update env.example with new HTTPS-related variables
- Update docker-compose.yml with SSL configuration options

This enables secure HTTPS access in both development and production
environments while maintaining compatibility with existing deployments.
2025-10-13 18:32:45 +02:00
Dries Peeters
20824dbcb1 feat: Add customizable Kanban board columns and enhance CSRF configuration
This commit introduces a comprehensive Kanban board customization system and
improves CSRF token configuration for Docker deployments.

## Major Features

### 1. Customizable Kanban Board Columns
Add complete kanban column customization system allowing users to define
custom workflow states beyond the default columns.

**New Components:**
- Add KanbanColumn model with full CRUD operations (app/models/kanban_column.py)
- Add kanban routes blueprint with admin endpoints (app/routes/kanban.py)
- Add kanban column management templates (app/templates/kanban/)
- Add migration 019 for kanban_columns table (migrations/)

**Features:**
- Create unlimited custom columns with unique keys, labels, icons, and colors
- Drag-and-drop column reordering with position persistence
- Toggle column visibility without deletion
- Protected system columns (todo, in_progress, done) prevent accidental deletion
- Complete state marking for columns that should mark tasks as done
- Real-time updates via SocketIO broadcasts when columns change
- Font Awesome icon support (5000+ icons)
- Bootstrap color scheme integration
- Comprehensive validation and error handling

**Integration:**
- Update Task model to work with dynamic column statuses (app/models/task.py)
- Update task routes to use kanban column API (app/routes/tasks.py)
- Update project routes to fetch active columns (app/routes/projects.py)
- Add kanban column management links to base template (app/templates/base.html)
- Update kanban board templates to render dynamic columns (app/templates/tasks/)
- Add cache prevention headers to force fresh column data

**API Endpoints:**
- GET /api/kanban/columns - Fetch all active columns
- POST /api/kanban/columns/reorder - Reorder columns
- GET /kanban/columns - Column management interface (admin only)
- POST /kanban/columns/create - Create new column (admin only)
- POST /kanban/columns/<id>/edit - Edit column (admin only)
- POST /kanban/columns/<id>/delete - Delete column (admin only)
- POST /kanban/columns/<id>/toggle - Toggle column visibility (admin only)

### 2. Enhanced CSRF Configuration
Improve CSRF token configuration and documentation for Docker deployments.

**Configuration Updates:**
- Add WTF_CSRF_ENABLED environment variable to all docker-compose files
- Add WTF_CSRF_TIME_LIMIT environment variable with 1-hour default
- Update app/config.py to read CSRF settings from environment
- Add SECRET_KEY validation in app/__init__.py to prevent production deployment
  with default keys

**Docker Compose Updates:**
- docker-compose.yml: CSRF enabled by default for security testing
- docker-compose.remote.yml: CSRF always enabled in production
- docker-compose.remote-dev.yml: CSRF enabled with production-like settings
- docker-compose.local-test.yml: CSRF can be disabled for local testing
- Add helpful comments explaining each CSRF-related environment variable
- Update env.example with CSRF configuration examples

**Verification Scripts:**
- Add scripts/verify_csrf_config.sh for Unix systems
- Add scripts/verify_csrf_config.bat for Windows systems
- Scripts check SECRET_KEY, CSRF_ENABLED, and CSRF_TIME_LIMIT settings

### 3. Database Initialization Improvements
- Update app/__init__.py to run pending migrations on startup
- Add automatic kanban column initialization after migrations
- Improve error handling and logging during database setup

### 4. Configuration Management
- Update app/config.py with new CSRF and kanban-related settings
- Add environment variable parsing with sensible defaults
- Improve configuration validation and error messages

## Documentation

### New Documentation Files
- CUSTOM_KANBAN_README.md: Quick start guide for kanban customization
- KANBAN_CUSTOMIZATION.md: Detailed technical documentation
- IMPLEMENTATION_SUMMARY.md: Implementation details and architecture
- KANBAN_AUTO_REFRESH_COMPLETE.md: Real-time update system documentation
- KANBAN_REFRESH_FINAL_FIX.md: Cache and refresh troubleshooting
- KANBAN_REFRESH_SOLUTION.md: Technical solution for data freshness
- docs/CSRF_CONFIGURATION.md: Comprehensive CSRF setup guide
- CSRF_DOCKER_CONFIGURATION_SUMMARY.md: Docker-specific CSRF setup
- CSRF_TROUBLESHOOTING.md: Common CSRF issues and solutions
- APPLY_KANBAN_MIGRATION.md: Migration application guide
- APPLY_FIXES_NOW.md: Quick fix reference
- DEBUG_KANBAN_COLUMNS.md: Debugging guide
- DIAGNOSIS_STEPS.md: System diagnosis procedures
- BROWSER_CACHE_FIX.md: Browser cache troubleshooting
- FORCE_NO_CACHE_FIX.md: Cache prevention solutions
- SESSION_CLOSE_ERROR_FIX.md: Session handling fixes
- QUICK_FIX.md: Quick reference for common fixes

### Updated Documentation
- README.md: Add kanban customization feature description
- Update project documentation with new features

## Testing

### New Test Files
- test_kanban_refresh.py: Test kanban column refresh functionality

## Technical Details

**Database Changes:**
- New table: kanban_columns with 11 columns
- Indexes on: key, position
- Default data: 4 system columns (todo, in_progress, review, done)
- Support for both SQLite (development) and PostgreSQL (production)

**Real-Time Updates:**
- SocketIO events: 'kanban_columns_updated' with action type
- Automatic page refresh when columns are created/updated/deleted/reordered
- Prevents stale data by expiring SQLAlchemy caches after changes

**Security:**
- Admin-only access to column management
- CSRF protection on all column mutation endpoints
- API endpoints exempt from CSRF (use JSON and other auth mechanisms)
- System column protection prevents data integrity issues
- Validation prevents deletion of columns with active tasks

**Performance:**
- Efficient querying with position-based ordering
- Cached column data with cache invalidation on changes
- No-cache headers on API responses to prevent stale data
- Optimized database indexes for fast lookups

## Breaking Changes

None. This is a fully backward-compatible addition.

Existing workflows continue to work with the default columns.
Custom columns are opt-in via the admin interface.

## Migration Notes

1. Run migration 019 to create kanban_columns table
2. Default columns are initialized automatically on first run
3. No data migration needed for existing tasks
4. Existing task statuses map to new column keys

## Environment Variables

New environment variables (all optional with defaults):
- WTF_CSRF_ENABLED: Enable/disable CSRF protection (default: true)
- WTF_CSRF_TIME_LIMIT: CSRF token expiration in seconds (default: 3600)
- SECRET_KEY: Required in production, must be cryptographically secure

See env.example for complete configuration reference.

## Deployment Notes
2025-10-11 19:56:45 +02:00
Dries Peeters
ede8baa1ee yet another testing update 2025-10-10 13:33:49 +02:00
Dries Peeters
113a57d2eb testing updates 2025-10-10 11:37:23 +02:00
Dries Peeters
be06957138 update readme 2025-10-09 14:04:36 +02:00
Dries Peeters
de81b91510 small update 2025-10-09 13:53:58 +02:00
Dries Peeters
9e6d4bc514 update and cleanup 2025-10-09 13:48:03 +02:00
Dries Peeters
77aec94b86 feat: Add project costs tracking and remove license server integration
Major Features:
- Add project costs feature with full CRUD operations
- Implement toast notification system for better user feedback
- Enhance analytics dashboard with improved visualizations
- Add OIDC authentication improvements and debug tools

Improvements:
- Enhance reports with new filtering and export capabilities
- Update command palette with additional shortcuts
- Improve mobile responsiveness across all pages
- Refactor UI components for consistency

Removals:
- Remove license server integration and related dependencies
- Clean up unused license-related templates and utilities

Technical Changes:
- Add new migration 018 for project_costs table
- Update models: Project, Settings, User with new relationships
- Refactor routes: admin, analytics, auth, invoices, projects, reports
- Update static assets: CSS improvements, new JS modules
- Enhance templates: analytics, admin, projects, reports

Documentation:
- Add comprehensive documentation for project costs feature
- Document toast notification system with visual guides
- Update README with new feature descriptions
- Add migration instructions and quick start guides
- Document OIDC improvements and Kanban enhancements

Files Changed:
- Modified: 56 files (core app, models, routes, templates, static assets)
- Deleted: 6 files (license server integration)
- Added: 28 files (new features, documentation, migrations)
2025-10-09 11:50:26 +02:00