Commit Graph

48 Commits

Author SHA1 Message Date
Dries Peeters e34a668ddc feat(auth): add LDAP directory authentication
Introduce AUTH_METHOD values ldap and all, with LDAP_* environment settings, ldap3-based LDAPService (search, optional groupOfNames checks, user bind, DB sync), and users.auth_provider (local|oidc|ldap) via migration 153_add_user_auth_provider.

Login supports LDAP-only and combined all (local then LDAP where appropriate); OIDC callback sets auth_provider. Forgot/reset/change password flows skip LDAP-managed accounts. Admin System Settings gains a read-only LDAP summary and POST /admin/ldap/test. Production env validation requires core LDAP variables when LDAP is enabled; OIDC registration and docs recognize all.

Documentation: new docs/admin/configuration/LDAP_SETUP.md; updates to OIDC_SETUP, GETTING_STARTED, Docker guides, Render deploy notes, docs README, and CHANGELOG. Tests: tests/test_ldap_auth.py; test_oidc_logout allows auth_method all.
2026-04-27 19:08:08 +02:00
Dries Peeters ea913c6c4b feat(ai,security): add web AI helper, secret encryption, and 2FA
Introduce a web-first AI helper with admin-configurable providers (Ollama or hosted OpenAI-compatible), server-side context building, and confirmed write actions. Expose the feature via session /api/ai/* endpoints and scoped /api/v1/ai/* endpoints.

Harden security by requiring a strong SECRET_KEY for Docker Compose, adding optional settings encryption-at-rest (Fernet), and introducing TOTP-based 2FA plus password reset flows. Update admin UI, API docs, and install documentation.
2026-04-26 07:55:47 +02:00
Dries Peeters 568933c3b9 fix(auth): scope client portal users to their assigned client
Client-portal-enabled users (main app login, typically viewer) were not
included in get_allowed_client_ids(), so ProjectService and other callers
saw scope_client_ids=None and listed every project.

- Return [client_id] for is_client_portal_user in User.get_allowed_client_ids
- Derive get_allowed_project_ids from allowed client IDs for all non-admins
- Apply client/project scope and access checks from allowed IDs, not only
  subcontractor is_scope_restricted (fixes user_can_access_* for portal)

Fixes DRYTRIX/TimeTracker#592.

Tests: extend test_scope_filter with client_portal_scoped_user and API
isolation for GET /api/v1/projects.
2026-04-24 16:15:24 +02:00
Dries Peeters 91127bf188 feat: smart in-app notifications, value dashboard stats, and search scope helpers
Smart notifications (opt-in under user settings): NotificationService builds candidates from the user's local day and active timers; GET /api/notifications and POST /api/notifications/dismiss; migration 150 adds user columns and user_smart_notification_dismissals. /api/summary/today uses the same local-day totals. Client polls from smart-notifications.js; toastManager.show gains onDismiss for server dismiss sync. Config and env.example document SMART_NOTIFY_* variables.

Value dashboard: StatsService with Redis-backed caching, GET /api/stats/value-dashboard, dashboard template and dashboard-enhancements polling alongside existing widgets.

API v1 token search now uses apply_project_scope and apply_client_scope on queries; scope_filter adds apply_project_scope; tests extended for the new helper.
2026-04-15 12:15:23 +02:00
Dries Peeters b0dde80ba9 feat(web): high-visibility support modal, prompts, and supporter UX
Add a support modal with usage stats, tier and license links, share control, and offline-safe outbound CTAs. Surface support from the header, sidebar, user menu, dashboard card, and settings "Support & Community" section without hiding entry points when a supporter license is active.

Introduce UsageStatsService and a persisted users.support_stats_reports_generated counter incremented on key report exports and custom report views. Add SupportPromptService for session-scoped soft toasts (after export, dashboard milestones, long session via POST /donate/request-soft-prompt).

Wire consent-aware track_event names support.* and mirror funnel rows in DonationInteraction; fix has_recent_donation_click to treat link_clicked as a recent click. Document events and SUPPORT_* / migration notes in docs.

Tests: tests/test_support_services.py for prompt and usage stats behavior.
2026-04-15 10:55:37 +02:00
Dries Peeters 96955aee62 feat(admin): GitHub-based version update notification for admins
Add VersionService to fetch and cache the latest GitHub release, compare it to the installed semver (APP_VERSION when valid, else setup.py), and expose admin-only GET /api/version/check and POST /api/version/dismiss on the legacy /api blueprint (session or Bearer token).

Persist per-user dismissal in users.dismissed_release_version (Alembic 148) and show a non-blocking update card in base.html for administrators. Add packaging for semver parsing and tests for comparison, service, and routes.

Document configuration in docs/admin/deployment/VERSION_MANAGEMENT.md and endpoints in docs/api/REST_API.md and docs/API.md.
2026-04-15 09:39:32 +02:00
Dries Peeters 404647eea3 feat(models): add ClientPortalDashboardPreference and update user/audit/link models
- Add ClientPortalDashboardPreference for per-client/widget dashboard layout and order
- Export new model in models __init__; minor updates to audit_log, link_template, user as needed
2026-03-16 15:15:21 +01:00
Dries Peeters b4486a627f fix: CI tests, code quality, and duplicate DB indexes
- Webhook models: remove duplicate index definitions so db.create_all()
  no longer raises 'index already exists' (columns already have index=True)
- ImportService: fix circular import by late-importing ClientService,
  ProjectService, TimeTrackingService in __init__
- reports: fix F823 by renaming unpack variable _ to _entry_count to avoid
  shadowing gettext _ in export_task_excel()
- Code quality: add .flake8 with extend-ignore so flake8 CI passes;
  simplify pyproject.toml isort config (drop unsupported options)
- Format: run black and isort on app/
- tests: restore minimal app fixture in test_import_export_models
2026-03-15 10:51:52 +01:00
Dries Peeters f150b73b94 feat: product value improvements (dashboard, reports, timer, reminders)
Dashboard:
- Add time-by-project chart (last 7 days) with Chart.js horizontal bar; link to Summary report

Summary report:
- Add time-by-project (last 30d) bar chart and daily trend (14d) line chart
- Add one-page PDF export (today/week/month hours + top projects table)

Post-timer flow:
- After stop, show toast "Logged Xh on [Project]" with action link "View time entries"
- Toast manager: optional actionLink/actionLabel for action links in toasts
- Session carries timer_stopped_toast to dashboard; no duplicate flash

Remind to log:
- User setting "Remind me to log time at end of day" + time picker (Settings)
- Hourly job: send one email per day if user has <0.5h logged that day (user TZ)
- Migration 135: notification_remind_to_log, reminder_to_log_time on users
2026-03-11 08:59:13 +01:00
Dries Peeters 55f2ef29fd feat(overtime): allow overtime calculation by weekly hours (Issue #551) 2026-03-09 20:33:48 +01:00
Dries Peeters 531f16b597 feat(workforce): add timesheet governance, time-off, and workforce dashboard
- Add TimesheetPeriod, TimesheetPolicy, TimeOff models and migration 132
- Add workforce blueprint, routes, and workforce_governance_service
- Add workforce dashboard template; register blueprint via blueprint_registry
- Extend User model for time-off and policy associations
2026-03-06 15:44:35 +01:00
Dries Peeters ae9ee9dec1 feat: add subcontractor role with assigned clients (scope-restricted access)
- Add user_clients table and UserClient model for many-to-many user-client assignment
- Add 'subcontractor' system role; users with this role see only assigned clients and their projects
- User helpers: is_scope_restricted, get_allowed_client_ids(), get_allowed_project_ids()
- Admin user form: assign clients when role is Subcontractor (multi-select, JS toggle)
- Scope filtering: clients, projects, time entries, reports, invoices, timer, API v1
- Direct access to out-of-scope client/project returns 403 (web and API)
- Migration 127_add_user_clients_table; scope_filter utility and ProjectService scope_client_ids
- Docs: SUBCONTRACTOR_ROLE.md, ADVANCED_PERMISSIONS.md, RBAC, CLIENT_PORTAL, README, CHANGELOG

Addresses GitHub Discussion #476 (user with limited clients/projects).
2026-02-16 07:12:57 +01:00
Dries Peeters 54533ec95e feat(reports): add Time Entries report with Excel/CSV export (Discussion #463)
- Add /reports/time-entries page listing all time entries (billed and unbilled)
- Columns: Date, Start, Stop, Duration, Project, Task, Notes, Billed, Client
- Filters: date range, user, project, client, task, billed (all/yes/no)
- Export to Excel and CSV with same filters; add Billed column to excel export
- Resolve client from entry.client or project.client in export
- Add Time Entries Report card to Reports index
2026-02-13 20:56:07 +01:00
Dries Peeters 17b67cc578 feat(calendar): default view setting and remember last view
- Resolve calendar view from URL param, then user default, then session
- Add user preference calendar_default_view (day/week/month or unset)
- Persist last-used view in session when opening with ?view=
- Settings: Calendar default view dropdown (Remember last view / Day / Week / Month)
- PATCH /api/preferences supports calendar_default_view
- Migration 123: add calendar_default_view to users
- Tests for calendar view resolution and settings form/API

Ref #518

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-09 20:22:08 +01:00
Dries Peeters 91685bb9c6 feat: allow users to hide donate/support UI via verified code
- Add Support visibility in Settings: users see a stable System ID and can
  enter a code to permanently hide donate buttons, support banner, and
  donate widgets.
- Verification supports two modes:
  - Ed25519: server stores only public key; codes are signatures generated
    offline with the private key (no secret on server).
  - HMAC: server stores a secret; code = HMAC(secret, system_id).
- Add User.ui_show_donate and Settings.system_instance_id (migration 121).
- Add donate_hide_code utility (HMAC + Ed25519 verify) and config for
  DONATE_HIDE_PUBLIC_KEY(_FILE) and DONATE_HIDE_UNLOCK_SECRET(_FILE).
- Wrap all donate UI in base, dashboard, about, help with conditional.
- Add admin doc SUPPORT_VISIBILITY.md; ignore docs/internal/ and
  code-generation script in .gitignore.
- Add translations for new strings.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 11:11:03 +01:00
Dries Peeters 8b6e61873b Use system date/time format by default with optional user override
Display formats for dates and times now follow the system settings (Admin
settings) by default. Users can override in their profile (User settings) or
choose "Use system default" so their view matches the rest of the system.

Backend:
- User.date_format and User.time_format are nullable; null means use system.
- Migration 120 makes these columns nullable (existing rows unchanged).
- get_resolved_date_format_key() and get_resolved_time_format_key() in
  timezone utils return the effective key (user or system) for templates and API.
- Context processor injects resolved_date_format_key and resolved_time_format_key
  so base.html and JS (window.userPrefs) always see the resolved format.
- User settings form: "Use system default" option and save logic for null.
- User.to_dict() includes resolved date_format, time_format, and timezone for
  API clients (e.g. mobile).

Web:
- base.html uses resolved keys for window.userPrefs (no hardcoded fallback).
- Replaced display-only strftime() in templates with |user_date, |user_datetime,
  |user_time, and |format_date so all visible dates/times respect settings.
  Left <input type="date"> values and URL/API params as YYYY-MM-DD where required.

Mobile:
- ApiClient.getCurrentUser() and user prefs provider load resolved prefs from
  /api/v1/users/me.
- date_format_utils maps API keys to intl patterns; formatDate, formatTime,
  formatDateTime, formatDateRange used for display.
- Time entries screen (filter dialog), time entry form, time entry card, and
  home dashboard use user prefs for formatting; API requests still send ISO dates.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-07 08:20:08 +01:00
Dries Peeters fe53c926ed feat(calendar): user-configurable colors for calendar item types
- Add User preferences: calendar_color_events, calendar_color_tasks,
  calendar_color_time_entries (nullable hex)
- Calendar API: attach color to each event/task/time_entry and return
  typeColors; view_calendar passes type_colors to template
- PATCH /api/preferences: accept and validate calendar color fields
- Migration 117: add the three user columns

Events, tasks, and time entries can now be distinguished by user-chosen
colors (defaults: blue, amber, green). Frontend color pickers and
legend are on the calendar page (already in previous commit).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-01-31 07:48:09 +01:00
Dries Peeters 456d2074b7 feat: Add persistent chat widget with user selection and status indicators
- Add user status tracking (online/offline/away) based on last_login
  - Implement is_online() and get_status() methods in User model
  - Include status in user.to_dict() for API responses

- Create persistent chat widget that remains open across page navigation
  - Floating chat button in bottom-right corner (always visible)
  - Expandable chat panel with channels, direct messages, and message input
  - State persistence using localStorage (remembers open/closed and active channel)
  - Auto-refreshes channels and messages periodically
  - Integrates with user selector for starting new chats

- Add chat user selection popup component
  - Searchable user list with avatars and status indicators
  - Color-coded status badges (green=online, yellow=away, gray=offline)
  - Creates or finds existing direct message channels

- Add API endpoints for chat functionality
  - GET /api/chat/users: List all active users with status
  - POST /api/chat/direct-message/<user_id>: Create or find direct message channel

- Add chat button to header navigation
  - Opens persistent chat widget or user selector
  - Only visible when team_chat module is enabled

- Add status indicators throughout chat interface
  - Show user status in direct messages list
  - Display status badges in channel member lists
  - Status visible in user selection popup

- Fix z-index and positioning issues
  - Chat widget positioned above other floating elements (z-[60])
  - Adjusted position to avoid overlap with quick actions button

- Fix CSRF token handling
  - Use FormData for message submission to properly handle CSRF
  - Include CSRF token in user selector requests
  - Fix file_size variable in upload_attachment endpoint
2026-01-23 22:39:06 +01:00
Dries Peeters 83a03f9a99 feat: enhance application features and routes
- Improve expenses route with additional functionality
- Enhance admin route with new features
- Update auth route with improved authentication handling
- Extend user model with new capabilities
- Update expenses view template
- Improve config manager utility
2026-01-07 20:04:50 +01:00
Dries Peeters 083dd9f1f2 feat: Implement comprehensive module system with visibility controls
- Add centralized module registry system (ModuleRegistry) for managing
  module metadata, dependencies, and visibility across the application
- Create module helper utilities with decorators (@module_enabled) and
  helper functions for route protection and template access
- Add database migration (092) to add missing module visibility flags
  to settings and users tables for granular control
- Extend Settings and User models with additional module visibility
  flags for CRM, Finance, Tools, and Advanced features
- Implement admin module management UI for system-wide module
  enable/disable controls
- Add module checks to routes (calendar, contacts, deals, expenses,
  invoices, leads, custom_reports) to enforce visibility rules
- Update scheduled report service and report templates to respect
  module visibility settings
- Bump version to 4.8.0 in setup.py
- Add comprehensive documentation for module integration planning
  and implementation analysis
2025-12-29 14:13:32 +01:00
Dries Peeters 7791e6ada0 feat: Add comprehensive issue/bug tracking system
Implement a complete issue management system with client portal integration
and internal admin interface for tracking and resolving client-reported issues.

Features:
- New Issue model with full lifecycle management (open, in_progress, resolved, closed, cancelled)
- Priority levels (low, medium, high, urgent) with visual indicators
- Issue linking to projects and tasks
- Create tasks directly from issues
- Client portal integration for issue reporting and viewing
- Internal admin routes for issue management, filtering, and assignment
- Comprehensive templates for both client and admin views
- Status filtering and search functionality
- Issue assignment to internal users
- Automatic timestamp tracking (created, updated, resolved, closed)

Client Portal:
- Clients can report new issues with project association
- View all issues with status filtering
- View individual issue details
- Submit issues with optional submitter name/email

Admin Interface:
- List all issues with advanced filtering (status, priority, client, project, assignee, search)
- View, edit, and delete issues
- Link issues to existing tasks
- Create tasks from issues
- Update issue status, priority, and assignment
- Issue statistics dashboard

Technical:
- Added Issue model with relationships to Client, Project, Task, and User
- New issues blueprint for internal management
- Extended client_portal routes with issue endpoints
- Updated model imports and relationships
- Added navigation links in base templates
- Version bump to 4.6.0
- Code cleanup in docker scripts and schema verification
2025-12-14 07:25:42 +01:00
Dries Peeters bde61c7f5d Fix permission and role management bugs
Fix multiple permission and role-related issues:

1. Gantt chart access: Replace is_admin check with view_projects permission
   - Users with custom roles having view_projects permission can now access
     Gantt charts, not just admins
   - Updated app/routes/gantt.py to check permissions properly

2. Task view filtering: Replace is_admin check with view_all_tasks permission
   - Users with custom roles having view_all_tasks permission can now see
     all tasks in the Tasks view, not just admins
   - Updated app/services/task_service.py to accept has_view_all_tasks parameter
   - Updated app/routes/tasks.py list_tasks and export_tasks to use permission check

3. Role assignment security: Prevent privilege escalation
   - Added is_super_admin property to User model
   - Only super_admins can assign super_admin role to users
   - Only super_admins can remove admin role from themselves or others
   - Prevents admins from escalating privileges or removing admin access
   - Updated app/routes/permissions.py manage_user_roles with validation

4. Version display consistency: Ensure consistent version display
   - Added APP_VERSION environment variable to docker-compose.example.yml
   - Ensures version is displayed consistently when using pre-built images

All changes maintain backward compatibility and follow the existing
permission system architecture.
2025-12-12 22:18:30 +01:00
Dries Peeters 9112a696dd feat: Enhance audit logging with improved error handling and diagnostic tools
- Improve audit logging error messages to distinguish table missing errors from other failures

- Add warning-level logging for audit_logs table missing scenarios with migration guidance

- Update audit event listener with better error detection and logging

- Add comprehensive diagnostic script for checking audit logging setup

- Update UI templates (base.html, admin forms, user settings, profile pages)

- Extend audit logging support across routes (admin, api, permissions, reports, timer, user)

- Add extensive test coverage for admin user management functionality

- Update time tracking service and user model with audit logging integration
2025-12-01 13:30:18 +01:00
Dries Peeters 583f9b6755 Format code with Black to fix code quality test 2025-11-29 07:13:23 +01:00
Dries Peeters dcbdfcc288 feat: Add client custom fields, link templates, UI feature flags, and client billing support
Add client custom fields (JSON) for flexible data storage

Implement link templates system for dynamic URL generation from custom fields

Add client_id support to time entries for direct client billing (project_id now nullable)

Implement user-level UI feature flags for customizable navigation visibility

Add system-wide UI feature flags in settings for admin control

Fix metadata column naming (user_badges.achievement_metadata, leaderboard_entries.entry_metadata)

Update templates and routes to support new features

Add comprehensive UI feature flag management in admin and user settings

Enhance client views with custom fields and link template integration

Update time entry forms to support client billing

Add tests for system UI flags

Migrations: 075-080 for custom fields, link templates, UI flags, client billing, and metadata fixes
2025-11-29 06:17:07 +01:00
Dries Peeters 6ad96f114a Fix user creation to use new Role system and add default password with forced change
- Updated user creation to assign roles from Role system instead of legacy role field
- Added password_change_required field to User model with migration
- Added default password input and force password change option in user creation form
- Updated login route to check password_change_required and redirect to change password page
- Created change_password route and template for forced password changes
- Updated all user creation points (admin, self-registration, OIDC, default admin) to use new Role system
- Updated user form template to show roles from Role system instead of hardcoded options

Fixes issue where newly created users were still using legacy roles instead of the new role-based permission system.
2025-11-28 22:47:01 +01:00
Dries Peeters 90dde470da style: standardize code formatting and normalize line endings
- Normalize line endings from CRLF to LF across all files to match .editorconfig
- Standardize quote style from single quotes to double quotes
- Normalize whitespace and formatting throughout codebase
- Apply consistent code style across 372 files including:
  * Application code (models, routes, services, utils)
  * Test files
  * Configuration files
  * CI/CD workflows

This ensures consistency with the project's .editorconfig settings and
improves code maintainability.
2025-11-28 20:05:37 +01:00
Dries Peeters 4930f6a3e5 feat: add multiple authentication modes support
Add support for four authentication modes via AUTH_METHOD environment variable:
- none: Username-only authentication (no password)
- local: Password authentication required (default)
- oidc: OIDC/Single Sign-On only
- both: OIDC + local password authentication

Key changes:
- Add password_hash column to users table (migration 068)
- Implement password storage and verification in User model
- Update login routes to handle all authentication modes
- Add conditional password fields in login templates
- Support password authentication in kiosk mode
- Allow password changes in user profile when enabled

Password authentication is now enabled by default for better security,
while remaining backward compatible with existing installations.
Users will be prompted to set passwords when required.

Fixes authentication bypass issue where users could access accounts
without passwords even after setting them.
2025-11-28 15:56:01 +01:00
Dries Peeters 9f4ab335fe tests 2025-11-14 21:57:59 +01:00
Dries Peeters 39cf649f8e feat: Add client portal with password setup email functionality
Implement a complete client portal feature that allows clients to access
their projects, invoices, and time entries through a dedicated portal with
separate authentication. Includes password setup via email with secure
token-based authentication.

Client Portal Features:
- Client-based authentication (separate from user accounts)
- Portal access can be enabled/disabled per client
- Clients can view their projects, invoices, and time entries
- Clean, minimal UI without main app navigation elements
- Login page styled to match main app design

Password Setup Email:
- Admin can send password setup emails to clients
- Secure token-based password setup (24-hour expiration)
- Email template with professional styling
- Password setup page matching app login design
- Token validation and automatic cleanup after use

Email Configuration:
- Email settings from admin menu are now used for sending
- Database email settings persist between restarts and updates
- Automatic reload of email configuration when sending emails
- Database settings take precedence over environment variables
- Improved error messages for email configuration issues

Database Changes:
- Add portal_enabled, portal_username, portal_password_hash to clients
- Add password_setup_token and password_setup_token_expires to clients
- Migration 047: Add client portal fields to users (legacy)
- Migration 048: Add client portal credentials to clients
- Migration 049: Add password setup token fields

New Files:
- app/routes/client_portal.py - Client portal routes and authentication
- app/templates/client_portal/ - Portal templates (base, login, dashboard, etc.)
- app/templates/email/client_portal_password_setup.html - Email template
- migrations/versions/047-049 - Database migrations
- tests/test_client_portal.py - Portal tests
- docs/CLIENT_PORTAL.md - Portal documentation

Modified Files:
- app/models/client.py - Add portal fields and password token methods
- app/routes/clients.py - Add send password email route
- app/routes/client_portal.py - Portal routes with redirect handling
- app/utils/email.py - Use database settings, add password setup email
- app/templates/clients/edit.html - Add send email button
- app/templates/components/ui.html - Support client portal breadcrumbs

Security:
- Secure token generation using secrets.token_urlsafe()
- Password hashing with werkzeug.security
- Token expiration (24 hours default)
- Token cleared after successful password setup
- CSRF protection on all forms
2025-11-14 15:15:38 +01:00
Dries Peeters a3e03828f3 Updated tests 2025-10-27 15:31:05 +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 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 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 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 b1973ca49a feat: Add Quick Wins feature set - activity tracking, templates, and user preferences
This commit introduces several high-impact features to improve user experience
and productivity:

New Features:
- Activity Logging: Comprehensive audit trail tracking user actions across the
  system with Activity model, including IP address and user agent tracking
- Time Entry Templates: Reusable templates for frequently logged activities with
  usage tracking and quick-start functionality
- Saved Filters: Save and reuse common search/filter combinations across
  different views (projects, tasks, reports)
- User Preferences: Enhanced user settings including email notifications,
  timezone, date/time formats, week start day, and theme preferences
- Excel Export: Generate formatted Excel exports for time entries and reports
  with styling and proper formatting
- Email Notifications: Complete email system for task assignments, overdue
  invoices, comments, and weekly summaries with HTML templates
- Scheduled Tasks: Background task scheduler for periodic operations

Models Added:
- Activity: Tracks all user actions with detailed context and metadata
- TimeEntryTemplate: Stores reusable time entry configurations
- SavedFilter: Manages user-saved filter configurations

Routes Added:
- user.py: User profile and settings management
- saved_filters.py: CRUD operations for saved filters
- time_entry_templates.py: Template management endpoints

UI Enhancements:
- Bulk actions widget component
- Keyboard shortcuts help modal with advanced shortcuts
- Save filter widget component
- Email notification templates
- User profile and settings pages
- Saved filters management interface
- Time entry templates interface

Database Changes:
- Migration 022: Creates activities and time_entry_templates tables
- Adds user preference columns (notifications, timezone, date/time formats)
- Proper indexes for query optimization

Backend Updates:
- Enhanced keyboard shortcuts system (commands.js, keyboard-shortcuts-advanced.js)
- Updated projects, reports, and tasks routes with activity logging
- Safe database commit utilities integration
- Event tracking for analytics

Dependencies:
- Added openpyxl for Excel generation
- Added Flask-Mail dependencies
- Updated requirements.txt

All new features include proper error handling, activity logging integration,
and maintain existing functionality while adding new capabilities.
2025-10-23 09:05:07 +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 73c9316b77 feat(profile): allow users to upload profile pictures (avatars)
- Add avatar_filename to User model with URL/path/existence helpers
- Alembic migration 020: add users.avatar_filename (nullable)
- Implement avatar upload in /profile/edit with Pillow validation
- Add avatar removal endpoint: POST /profile/avatar/remove
- Public serving route: /uploads/avatars/<filename>
- Update templates:
  - Header shows user’s avatar if present
  - Profile page displays avatar
  - Edit Profile supports file upload and removal
- Update Docker permission scripts to include uploads/avatars
- Add tests for upload and removal (tests/test_profile_avatar.py)
- Update README to mention profile pictures

Security/UX:
- Restrict types to PNG/JPG/JPEG/GIF/WEBP, verify content with Pillow
- Unique filenames; old file removed on replacement
- Respects MAX_CONTENT_LENGTH from config

Migration:
- Run: flask db upgrade
- Ensure app/static/uploads/avatars is writable (use fix upload permission scripts if needed)

No breaking changes.
2025-10-22 06:27:53 +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
Dries Peeters 0749b0adf9 reset to previous commit. 2025-10-09 06:49:56 +02:00
Dries Peeters 3b564f83d7 feat: Remove license server and add multi-tenant SaaS infrastructure
BREAKING CHANGE: Removed legacy license server in favor of Stripe billing

Major changes:
- Remove license server system (563 lines removed from license_server.py)
- Add multi-tenant support with organizations and memberships
- Integrate Stripe billing and subscription management
- Enhance authentication with 2FA, password reset, and JWT tokens
- Add provisioning and onboarding flows for new customers
- Implement row-level security (RLS) for data isolation
- Add GDPR compliance features and data retention policies
- Enhance admin dashboard with billing reconciliation and customer management
- Add security scanning tools (Bandit, Gitleaks, GitHub Actions workflow)
- Implement rate limiting and enhanced password policies
- Update all routes to support organization context
- Enhance user model with billing and security fields
- Add promo code system for marketing campaigns
- Update Docker initialization for better database setup

Modified files:
- Core: app.py, app/__init__.py, app/config.py
- Models: Enhanced user model (+175 lines), updated all models for multi-tenancy
- Routes: Enhanced admin routes (+479 lines), updated all routes for org context
- Templates: Updated login, admin dashboard, and settings
- Docker: Enhanced database initialization scripts
- Dependencies: Added stripe, pyotp, pyjwt, and security packages

Deleted files:
- app/utils/license_server.py
- docs/LICENSE_SERVER_*.md (3 files)
- templates/admin/license_status.html
- test_license_server.py

New features:
- Organizations and membership management
- Stripe billing integration with webhook handling
- Enhanced authentication (2FA, password reset, refresh tokens)
- GDPR compliance and data export/deletion
- Onboarding checklist for new customers
- Promo code system
- Security enhancements (rate limiting, password policies)
- Admin tools for customer and billing management

Net change: 46 files changed, 1490 insertions(+), 1968 deletions(-)
2025-10-07 22:06:19 +02:00
Dries Peeters 5c11010095 feat(oidc): add optional OIDC login via Authlib; config, routes, docs
- Add AUTH_METHOD switch (local | oidc | both); default remains local
- Update login UI to conditionally show SSO button and/or local form
- Add Authlib and initialize OAuth client (discovery-based) in app factory
- Implement OIDC Authorization Code flow with PKCE:
  - GET /login/oidc → starts auth flow, preserves `next`
  - GET /auth/oidc/callback → exchanges code, parses ID token, fetches userinfo
  - Maps claims to username/full_name/email; admin mapping via group/email
  - Logs user in and redirects to intended page
- Add optional OIDC end-session on logout (falls back gracefully if unsupported)
- Extend User model with `email`, `oidc_issuer`, `oidc_sub` and unique constraint
- Add Alembic migration 015 (adds columns, index, unique constraint)
- Update env.example with OIDC variables and AUTH_METHOD
- Add docs/OIDC_SETUP.md with provider-agnostic setup guide and examples
- fix: remove invalid walrus usage in OIDC client registration

Migration:
- Run database migrations (e.g., `flask db upgrade`) to apply revision 015

Config:
- AUTH_METHOD=local|oidc|both
- OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_REDIRECT_URI
- OIDC_SCOPES (default: "openid profile email")
- OIDC_USERNAME_CLAIM, OIDC_FULL_NAME_CLAIM, OIDC_EMAIL_CLAIM, OIDC_GROUPS_CLAIM
- OIDC_ADMIN_GROUP (optional), OIDC_ADMIN_EMAILS (optional)
- OIDC_POST_LOGOUT_REDIRECT_URI (optional)

Routes:
- /login (respects AUTH_METHOD), /login/oidc, /auth/oidc/callback, /logout

Docs:
- See docs/OIDC_SETUP.md for full setup, provider notes, and troubleshooting
2025-10-05 11:46:20 +02:00
Dries Peeters 69f9f1140d feat(i18n): add translations, locale switcher, and user language preference
- Integrate Flask-Babel and i18n utilities; initialize in app factory
- Add `preferred_language` to `User` with Alembic migration (011_add_user_preferred_language)
- Add `babel.cfg` and `scripts/extract_translations.py`
- Add `translations/` for en, de, fr, it, nl, fi
- Update templates to use `_()` and add language picker in navbar/profile
- Respect locale in routes and context processors; persist user preference
- Update requirements and Docker/Docker entrypoint for Babel/gettext support
- Minor copy and style adjustments across pages

Migration: run `alembic upgrade head`
2025-09-11 23:08:41 +02:00
Dries Peeters 66919c96b2 feat(ui): dark mode fixes and Log Time UX aligned with invoices
Make user dropdown fully dark; fix hover/divider; remove white overlay
Mobile dropdown respects dark vars; improve navbar-collapse bg/z-index
Improve action button grouping/contrast across pages
Add dark-mode variants for badges, lists, pagination, utilities
Refresh Log Time page: card header, mini-cards for Start/End, unified labels
Group Save/Clear actions; Back remains secondary
Per-user theme preference: model column + migration (003) + POST /auth/profile/theme
Base loads user theme (fallback to local/system); remove admin theme selector
2025-09-05 10:04:49 +02:00
Dries Peeters 7f8fd43eb5 feat: add real name support and fix task detail error
models/user: add nullable full_name and display_name property (fallback to username)
migrations: add 002_add_user_full_name to introduce users.full_name
auth/profile: show and allow editing full_name; persist on POST
templates:
use display_name across navbar, dashboard greeting, tasks (list/view/edit/my/overdue), projects view, reports (user/project), invoices (creator and generate-from-time), and admin (dashboard/users)
keep username where appropriate (e.g., read-only admin form field)
reports:
aggregate/group by display_name in summaries
CSV export writes display_name instead of username
projects: get_user_totals returns display names when available
main/dashboard: replace inline Jinja in script with data attribute flag to satisfy linter
tasks/view: remove Jinja desc() usage; iterate over pre-ordered time_entries from route and slice to 5
fixes jinja2 UndefinedError: 'desc' is undefined
2025-09-03 20:43:51 +02:00
Dries Peeters 8a378b7078 feat(clients,license,db): add client management, enhanced DB init, and tests
- Clients: add model, routes, and templates
  - app/models/client.py
  - app/routes/clients.py
  - templates/clients/{create,edit,list,view}.html
  - docs/CLIENT_MANAGEMENT_README.md
- Database: add enhanced init/verify scripts, migrations, and docs
  - docker/{init-database-enhanced.py,start-enhanced.py,verify-database.py}
  - docs/ENHANCED_DATABASE_STARTUP.md
  - migrations/{add_analytics_column.sql,add_analytics_setting.py,migrate_to_client_model.py}
- Scripts: add version manager and docker network test helpers
  - scripts/version-manager.{bat,ps1,py,sh}
  - scripts/test-docker-network.{bat,sh}
  - docs/VERSION_MANAGEMENT.md
- UI: tweak base stylesheet
  - app/static/base.css
- Tests: add client system test
  - test_client_system.py
2025-09-01 11:34:45 +02:00
Dries Peeters 1b3a703c04 feat: comprehensive project cleanup and timezone enhancement
- Remove redundant documentation files (DATABASE_INIT_FIX_*.md, TIMEZONE_FIX_README.md)
- Delete unused Docker files (Dockerfile.test, Dockerfile.combined, docker-compose.yml)
- Remove obsolete deployment scripts (deploy.sh) and unused files (index.html, _config.yml)
- Clean up logs directory (remove 2MB timetracker.log, keep .gitkeep)
- Remove .pytest_cache directory

- Consolidate Docker setup to two main container types:
  * Simple container (recommended for production)
  * Public container (for development/testing)

- Enhance timezone support in admin settings:
  * Add 100+ timezone options organized by region
  * Implement real-time timezone preview with current time display
  * Add timezone offset calculation and display
  * Remove search functionality for cleaner interface
  * Update timezone utility functions for database-driven configuration

- Update documentation:
  * Revise README.md to reflect current project state
  * Add comprehensive timezone features documentation
  * Update Docker deployment instructions
  * Create PROJECT_STRUCTURE.md for project overview
  * Remove references to deleted files

- Improve project structure:
  * Streamlined file organization
  * Better maintainability and focus
  * Preserved all essential functionality
  * Cleaner deployment options
2025-08-28 14:52:09 +02:00
Dries Peeters c92f9e196b V1.0.0 version push 2025-08-16 21:49:43 +02:00