eProjektant Wastpol - Project Management System
A comprehensive project management system built with Next.js 15 for managing construction and design projects. Tailored for Polish construction/engineering companies with full Polish localization, GIS integration, and enterprise-grade features.
🌟 Overview
eProjektant Wastpol is a production-ready, full-stack web application designed to manage the complete lifecycle of design and construction projects. It features advanced task tracking, contact management, document generation, file attachments, and automated workflows with role-based access control.
✨ Key Features
📋 Project Management
- Full Project Lifecycle Tracking - From registration to fulfillment
- Project Types: Design, Construction, or Combined (Design+Construction)
- Project Statuses: Registered, In Progress (Design/Construction), Fulfilled, Cancelled
- Contract Integration - Link multiple projects to contracts
- GIS Coordinates - Map integration with Polish coordinate systems (EPSG:2180)
- Advanced Search & Filtering - Filter by status, type, customer, assigned user
- User Assignment - Track project ownership and assignments
- Budget Tracking - Monitor project values (wartość zlecenia)
- Completion Tracking - Track planned vs actual completion dates
- Field History - Audit trail for critical field changes (finish dates, etc.)
📄 Contract Management
- Complete Contract CRUD - Create, read, update, delete contracts
- Customer & Investor Tracking - Separate fields for both parties
- Contract Numbers - Both company and customer contract numbering
- Multi-Project Contracts - One contract can have many projects
- Date Tracking - Signing dates and finish dates
- File Attachments - Upload contract documents
✅ Advanced Task System
- Task Templates - Reusable task templates for both design and construction
- Task Sets - Pre-configured groups of tasks for quick project setup
- Task Categories - Separate design and construction task libraries
- Custom Tasks - Add one-off tasks specific to individual projects
- Task Statuses: Not Started, In Progress, Completed, Cancelled
- Priority Levels - Task prioritization
- Max Wait Days - Built-in deadline tracking for each task type
- Task Assignment - Assign tasks to team members
- Task Notes - Detailed notes and comments per task
- Date Tracking - Started, completed, and due dates
👥 Contact Management
- Comprehensive Contact Database - Phone, email, company, position
- Contact Types: Project, Contractor, Office, Supplier, Other
- Many-to-Many Relationships - Link multiple contacts to projects
- Primary Contact Designation - Mark primary contacts per project
- CardDAV/Radicale Sync - Bi-directional sync with CardDAV servers
- Contact Export - Export contacts to VCard format
- Contact Statistics - Usage tracking and analytics
📄 Document Generation
- DOCX Template System - Upload Word templates with placeholders
- Dynamic Document Generation - Generate documents from project/contract data
- Template Variables - Support for project fields, contract data, coordinates
- Template Management - Upload, edit, soft-delete templates
- Download Generated Docs - Instant document generation and download
📎 File Management
- Generic Attachment System - Files for contracts, projects, and tasks
- Multi-File Upload - Upload multiple files simultaneously
- File Metadata - Track uploader, date, description, file type
- File Size Limit - 10MB per file
- Supported Types: PDF, Word, Excel, Images, Text
- Inline Viewing - View PDFs and images in browser
- File Descriptions - Editable descriptions for organization
🔔 Notification System
- In-App Notifications - Real-time notification center
- Notification Types: Task Assigned, Status Changes, Due Date Reminders, System Announcements, Mentions
- Priority Levels: Low, Normal, High, Urgent
- Read/Unread Tracking - Mark notifications as read
- Auto-Expire - Optional expiration dates
- Action URLs - Click to navigate to related resources
- Unread Count Badge - Visual indicator in navigation
🗺️ Geographic Information System (GIS)
- Interactive Maps - Leaflet-based map interface
- Polish Coordinate Systems - EPSG:2180 (Polish 1992), EPSG:3857 (Web Mercator)
- 8 Base Layers:
- OpenStreetMap (default)
- Polish Orthophoto (Standard & High Resolution WMTS)
- Google Satellite, Hybrid, Roads
- Esri Satellite
- CartoDB Topographic
- 6 Overlay Layers (with transparency):
- Polish Cadastral Data (WMS)
- Polish Spatial Planning (WMS)
- LP-Portal Roads, Street Names, Parcels, Survey Markers (WMS)
- Project Location Markers - Plot projects on map
- Route Planning - Optimization for project visits
🔐 Security & Authentication
- NextAuth.js v5 - Modern authentication with credential provider
- 5 User Roles:
- Admin - Full system access, user management
- Project Manager - Full access except user management
- Team Lead - Specialized dashboard access
- User - Standard project/task access
- Read Only - View-only permissions
- Account Security:
- Password hashing with bcrypt
- Account lockout after 5 failed attempts (15-minute lock)
- Secure session management
- Failed login tracking
- Route Protection - Middleware-based authentication
- API Authorization - Per-route authorization middleware
- Audit Logging - Comprehensive security event tracking
📊 Audit & Compliance
- Comprehensive Audit Log - All user actions tracked
- Audit Event Types: Login, CRUD operations, file operations
- Field Change History - Track changes to critical fields
- System Notes - Auto-generated notes for status changes
- IP Address Tracking - Security monitoring
- User Agent Logging - Device/browser tracking
- Audit Statistics - Usage analytics and reporting
- Compliance Ready - Full audit trail for regulatory compliance
📈 Reporting & Export
- Excel Export - Export projects grouped by status
- PDF Generation - Generate PDF reports (jsPDF + AutoTable)
- Project Statistics - Dashboard with key metrics
- Audit Reports - Comprehensive activity reports
- Contact Statistics - Contact usage analytics
- Custom Reports - Extensible reporting framework
🌍 Internationalization
- Polish Primary - Full Polish translation (~1200+ keys)
- English Support - Complete English translation
- Client-Side i18n - Dynamic language switching
- Server-Side Translations - API response localization
- Date Formatting - Locale-aware date formatting
- Number Formatting - Currency and number localization
🔄 Automated Tasks
- Daily Database Backup - Automatic SQLite backups (keeps last 30)
- Due Date Reminders - Notifications 3 days and 1 day before deadline
- Cron Job Management - Admin interface for cron status/control
- Background Processing - Async task execution
- Notification System - Automated alerts to assigned users
🎨 Modern UI/UX
- Dark/Light Themes - User-selectable theme with system preference detection
- Responsive Design - Mobile-first, optimized for all screen sizes
- Component Library - Reusable UI components (40+ components)
- Loading States - Skeleton screens and spinners
- Error Handling - User-friendly error messages
- Toast Notifications - Non-intrusive feedback
- Modal Dialogs - Clean form interfaces
- Drag & Drop - File upload with drag-and-drop
- Search Autocomplete - Real-time search suggestions
- Badge System - Visual status indicators
- Tailwind CSS - Modern utility-first styling
🛠️ Tech Stack
Frontend
- Framework: Next.js 15.1.11 with App Router (React 19)
- Styling: Tailwind CSS 3.4 with custom theme
- UI Components: Custom component library (40+ components)
- State Management: React hooks + NextAuth session
- Forms: Native with Zod validation
- Maps: Leaflet 1.9.4 + React-Leaflet 5.0
- Charts: Recharts 2.15
- Date Handling: date-fns 4.1
- Projections: Proj4 + Proj4Leaflet for coordinate transformations
Backend
- Runtime: Node.js (v22.11.0)
- API: Next.js API Routes (Node.js runtime)
- Database: SQLite with better-sqlite3 11.10
- Authentication: NextAuth.js v5.0 (beta)
- Password Hashing: bcryptjs 3.0
- Validation: Zod 3.25
- Sessions: Custom SQLite session store
Document Processing
- DOCX: Docxtemplater 3.67 + PizZip 3.2
- Excel: ExcelJS 4.4 + XLSX 0.18
- PDF: jsPDF 3.0 + jsPDF-AutoTable 5.0
- Screenshots: html2canvas 1.4
Infrastructure
- Container: Docker with multi-stage builds
- Orchestration: Docker Compose
- Cron: Linux cron for scheduled tasks
- Timezone: Europe/Warsaw
- Proxy: Nginx (recommended for production)
Development Tools
- Testing:
- Playwright 1.40 (E2E tests)
- Jest 29.7 + Testing Library (unit/integration)
- Linting: ESLint 9 with Next.js config
- Type Safety: JSDoc annotations (future TypeScript migration ready)
- Version Control: Git
- CI/CD: Docker-based deployment pipeline
External Integrations
- Map Services:
- Polish Geoportal (WMTS/WMS)
- Google Maps
- OpenStreetMap
- Esri
- CartoDB
- LP-Portal (Polish cadastral data)
- CardDAV: Radicale server sync for contacts
- Email: SMTP support (configurable)
🚀 Getting Started
Prerequisites
- Node.js v16+ (v22.11.0 recommended for production)
- npm or yarn
- Docker & Docker Compose (optional, recommended for production)
- Git (for version control and git-based deployment)
Installation
Option 1: Local Development
- Clone the repository
git clone <repository-url>
cd panel
- Install dependencies
npm install
- Initialize the database
The database will auto-initialize on first run, or you can manually run:
node src/lib/init-db.js
- Create an admin user
npm run create-admin
Follow the prompts to create your first admin account.
- Start development server
npm run dev
- Open in browser
Navigate to http://localhost:3000
Option 2: Docker Development
- Clone the repository
git clone <repository-url>
cd panel
- Start with Docker Compose
docker-compose -f docker-compose.yml up --build
- Create admin user (in container)
docker-compose exec app npm run create-admin
- Open in browser
Navigate to http://localhost:3000
Option 3: Production Deployment with Docker
- Set environment variables
Create a .env file:
NEXTAUTH_SECRET=your-very-secure-random-string-at-least-32-characters
NEXTAUTH_URL=https://yourdomain.com
GIT_REPO_URL=https://github.com/yourusername/panel.git
GIT_BRANCH=main
- Deploy with Docker Compose
docker-compose -f docker-compose.prod.yml up -d
- Setup cron jobs (inside container)
docker-compose exec app bash setup-cron.sh
- Create admin user
docker-compose exec app npm run create-admin
The application will be available on port 3001 (mapped from internal 3000).
Configuration
Environment Variables
NODE_ENV- Environment mode (developmentorproduction)NEXTAUTH_SECRET- Secret key for NextAuth.js sessions (min 32 chars)NEXTAUTH_URL- Full URL of your applicationAUTH_TRUST_HOST- Set totruefor production behind reverse proxyTZ- Timezone (default:Europe/Warsaw)NODE_OPTIONS- Node.js options (default:--max-old-space-size=2048)
Docker Build Arguments
GIT_REPO_URL- Git repository URL for deploymentGIT_BRANCH- Branch to deploy (default:main)GIT_COMMIT- Specific commit to deploy (optional)
Database Setup
The application uses SQLite with automatic initialization. On first run:
- Database file created at
data/database.sqlite - All tables created automatically
- Indexes created for performance
- Default settings inserted
Database location: ./data/database.sqlite
Backup location: ./backups/
Migrations: Handled automatically via init-db.js with try-catch blocks
📁 Project Structure
panel/
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── api/ # API Routes (25+ endpoints)
│ │ │ ├── admin/ # Admin endpoints
│ │ │ │ ├── users/ # User management CRUD
│ │ │ │ ├── settings/ # System settings
│ │ │ │ └── cron/ # Cron job management
│ │ │ ├── audit-logs/ # Audit log endpoints
│ │ │ ├── auth/ # Authentication
│ │ │ │ ├── [...nextauth]/ # NextAuth handler
│ │ │ │ └── change-password/ # Password change
│ │ │ ├── contacts/ # Contact management
│ │ │ ├── contracts/ # Contract CRUD
│ │ │ ├── files/ # File upload/download
│ │ │ ├── field-history/ # Field change history
│ │ │ ├── notes/ # Notes CRUD
│ │ │ ├── notifications/ # Notification system
│ │ │ ├── projects/ # Project CRUD + export
│ │ │ ├── project-tasks/ # Project task instances
│ │ │ ├── reports/ # Reporting endpoints
│ │ │ ├── tasks/ # Task templates
│ │ │ ├── task-sets/ # Task set management
│ │ │ └── templates/ # DOCX templates + generation
│ │ ├── admin/ # Admin pages
│ │ │ ├── users/ # User management UI
│ │ │ └── settings/ # Settings UI
│ │ ├── auth/ # Auth pages
│ │ │ ├── signin/ # Login page
│ │ │ └── error/ # Auth error page
│ │ ├── calendar/ # Calendar view
│ │ ├── contacts/ # Contact pages
│ │ ├── contracts/ # Contract pages
│ │ ├── dashboard/ # Team lead dashboard
│ │ ├── projects/ # Project pages
│ │ │ ├── [id]/ # Single project view
│ │ │ └── page.js # Project list
│ │ ├── project-tasks/ # Project task pages
│ │ ├── settings/ # User settings
│ │ ├── tasks/ # Task template pages
│ │ ├── task-sets/ # Task set pages
│ │ ├── templates/ # Template management pages
│ │ ├── layout.js # Root layout with providers
│ │ ├── page.js # Home (redirects to projects)
│ │ └── globals.css # Global styles
│ ├── components/ # React Components (40+)
│ │ ├── ui/ # Reusable UI components
│ │ │ ├── Navigation.js # Main navigation
│ │ │ ├── Button.js # Button component
│ │ │ ├── Card.js # Card component
│ │ │ ├── Input.js # Form inputs
│ │ │ ├── Badge.js # Status badges
│ │ │ ├── SearchBar.js # Search component
│ │ │ ├── PageContainer.js # Page wrapper
│ │ │ └── States.js # Loading/error states
│ │ ├── auth/ # Auth components
│ │ │ └── AuthProvider.js # Session provider
│ │ ├── reports/ # Reporting components
│ │ ├── settings/ # Settings components
│ │ ├── project-view/ # Project detail components
│ │ ├── AuditLogViewer.js # Audit log viewer
│ │ ├── ContactForm.js # Contact form
│ │ ├── ContractForm.js # Contract form
│ │ ├── DocumentGenerator.js # DOCX generator
│ │ ├── FileUploadModal.js # File upload UI
│ │ ├── FileAttachmentsList.js # File list
│ │ ├── NoteForm.js # Note editor
│ │ ├── ProjectForm.js # Project form
│ │ ├── ProjectTaskForm.js # Task form
│ │ ├── TaskTemplateForm.js # Template form
│ │ ├── ThemeProvider.js # Theme context
│ ├── lib/ # Utilities & Backend Logic
│ │ ├── queries/ # Database queries
│ │ │ ├── projects.js # Project queries
│ │ │ ├── tasks.js # Task queries
│ │ │ ├── contacts.js # Contact queries
│ │ │ ├── contracts.js # Contract queries
│ │ │ ├── notes.js # Note queries
│ │ │ └── fieldHistory.js # History queries
│ │ ├── schemas/ # Zod validation schemas
│ │ ├── middleware/ # Auth middleware
│ │ │ ├── auth.js # Auth wrappers
│ │ │ └── auditLog.js # Audit middleware
│ │ ├── auth.js # NextAuth config
│ │ ├── db.js # Database connection
│ │ ├── init-db.js # Database initialization
│ │ ├── auditLog.js # Audit logging
│ │ ├── auditLogSafe.js # Edge-safe audit logging
│ │ ├── notifications.js # Notification system
│ │ ├── userManagement.js # User CRUD
│ │ ├── radicale-sync.js # CardDAV sync
│ │ ├── routeUtils.js # Route optimization
│ │ ├── i18n.js # Internationalization
│ │ ├── serverTranslations.js # Server-side i18n
│ │ └── utils.js # Utility functions
│ └── middleware.js # Next.js middleware (auth)
├── public/ # Static assets
│ ├── uploads/ # User uploads
│ │ ├── contracts/ # Contract files
│ │ ├── projects/ # Project files
│ │ └── tasks/ # Task files
│ ├── templates/ # DOCX template files
│ └── leaflet/ # Leaflet assets
├── data/ # SQLite database
│ └── database.sqlite # Main database file
├── backups/ # Database backups
├── templates/ # Server-side templates
├── scripts/ # Utility scripts
│ ├── create-admin.js # Create admin user
│ ├── create-test-data.js # Generate test data
│ └── create-sample-projects.js # Sample data
├── __tests__/ # Test files
│ ├── api/ # API tests
│ ├── components/ # Component tests
│ └── queries/ # Query tests
├── e2e/ # Playwright E2E tests
├── docs/ # Documentation
│ └── MAP_LAYERS.md # Map layer configuration
├── backup-db.mjs # Backup script
├── send-due-date-reminders.mjs # Reminder script
├── export-projects-to-excel.mjs # Export script
├── export-contacts-to-radicale.mjs # CardDAV export
├── setup-cron.sh # Cron setup script
├── docker-entrypoint.sh # Docker startup
├── Dockerfile # Production Docker image
├── Dockerfile.dev # Development Docker image
├── docker-compose.yml # Development compose
├── docker-compose.prod.yml # Production compose
├── next.config.mjs # Next.js config
├── tailwind.config.mjs # Tailwind config
├── package.json # Dependencies
└── README.md # This file
📜 Available Scripts
Development
npm run dev- Start development server on port 3000npm run build- Build for production (outputs to.next/)npm run start- Start production servernpm run lint- Run ESLint for code quality
Testing
npm test- Run Jest unit/integration testsnpm run test:watch- Run tests in watch modenpm run test:coverage- Generate test coverage reportnpm run test:e2e- Run Playwright E2E testsnpm run test:e2e:ui- Run Playwright tests with UI
Utilities
npm run create-admin- Interactive admin user creationnpm run export-projects- Export all projects to Excel filenpm run send-due-date-reminders- Manually trigger due date remindersnpm run test-due-date-reminders- Test reminder functionality
Production Scripts (run in container)
backup-db.mjs- Create database backup (scheduled via cron)send-due-date-reminders.mjs- Send due date notifications (scheduled via cron)export-contacts-to-radicale.mjs- One-time CardDAV exportsetup-cron.sh- Setup automated cron jobs
🐳 Docker Commands
Development
# Start development environment
docker-compose up
# Rebuild and start
docker-compose up --build
# Stop containers
docker-compose down
# View logs
docker-compose logs -f
# Execute commands in container
docker-compose exec app npm run create-admin
Production
# Deploy production
docker-compose -f docker-compose.prod.yml up -d
# View production logs
docker-compose -f docker-compose.prod.yml logs -f app
# Restart production
docker-compose -f docker-compose.prod.yml restart
# Stop production
docker-compose -f docker-compose.prod.yml down
# Backup database
docker-compose -f docker-compose.prod.yml exec app node backup-db.mjs
# Access container shell
docker-compose -f docker-compose.prod.yml exec app bash
Git-Based Deployment
# Deploy from Git repository
GIT_REPO_URL=https://github.com/user/repo.git \
GIT_BRANCH=main \
docker-compose -f docker-compose.prod.yml up -d --build
# Deploy specific commit
GIT_REPO_URL=https://github.com/user/repo.git \
GIT_COMMIT=abc123 \
docker-compose -f docker-compose.prod.yml up -d --build
🗄️ Database Schema
The application uses SQLite with the following comprehensive schema:
Core Business Entities
contracts
- Contract management with customer/investor tracking
- Fields: contract_id, contract_number, customer_contract_number, contract_name, customer, investor, date_signed, finish_date
projects
- Design and construction project tracking
- Fields: project_id, contract_id (FK), project_name, project_number, address, plot, district, unit, city, investment_number, finish_date, completion_date, wp, contact, notes, wartosc_zlecenia, project_type, project_status, coordinates, created_by, assigned_to, created_at, updated_at
- Types: design, construction, design+construction
- Statuses: registered, in_progress_design, in_progress_construction, fulfilled, cancelled
tasks
- Reusable task templates
- Fields: task_id, name, description, max_wait_days, is_standard, task_category
- Categories: design, construction
task_sets
- Pre-configured task groups
- Fields: set_id, name, description, task_category, created_at, updated_at
task_set_templates
- Junction table for tasks in sets
- Fields: set_id (FK), task_template_id (FK), sort_order
project_tasks
- Task instances assigned to projects
- Fields: id, project_id (FK), task_template_id (FK), custom_task_name, custom_description, custom_max_wait_days, status, date_added, date_started, date_completed, priority, created_by, assigned_to, created_at, updated_at
- Statuses: not_started, pending, in_progress, completed, cancelled
notes
- Project and task notes
- Fields: note_id, project_id (FK), task_id (FK), note, note_date, created_by, is_system
contacts
- Contact database
- Fields: contact_id, name, phone, email, company, position, contact_type, notes, is_active, created_at, updated_at
- Types: project, contractor, office, supplier, other
project_contacts
- Many-to-many project-contact relationships
- Fields: project_id (FK), contact_id (FK), relationship_type, is_primary, added_at, added_by
Authentication & Security
users
- User accounts with roles
- Fields: id, name, username, password_hash, role, created_at, updated_at, is_active, last_login, failed_login_attempts, locked_until
- Roles: admin, project_manager, team_lead, user, read_only
sessions
- NextAuth session management
- Fields: id, session_token, user_id (FK), expires, created_at
audit_logs
- Comprehensive audit trail
- Fields: id, user_id (FK), action, resource_type, resource_id, ip_address, user_agent, timestamp, details
password_reset_tokens
- Password reset functionality
- Fields: id, user_id (FK), token, expires_at, used, created_at
File Management
file_attachments
- Generic file storage for entities
- Fields: file_id, entity_type, entity_id, original_filename, stored_filename, file_path, file_size, mime_type, description, uploaded_by, upload_date
- Entity types: contract, project, task
docx_templates
- DOCX template management
- Fields: template_id, template_name, description, original_filename, stored_filename, file_path, file_size, mime_type, is_active, created_at, created_by, updated_at
Audit & History
field_change_history
- Track field-level changes
- Fields: id, table_name, record_id, field_name, old_value, new_value, changed_by, changed_at, change_reason
Notifications
notifications
- In-app notification system
- Fields: id, user_id (FK), type, title, message, resource_type, resource_id, is_read, priority, created_at, expires_at, action_url
- Types: task_assigned, task_status_changed, project_updated, due_date_reminder, system_announcement, mention
- Priorities: low, normal, high, urgent
Settings
settings
- Application configuration
- Fields: key, value, description, updated_at, updated_by
Indexes
Performance-optimized with indexes on:
- User lookups (username, id)
- Session tokens
- Audit log queries (user_id + timestamp)
- Project/task assignments
- File entity lookups
- Contact relationships
- Notification queries
🔌 API Endpoints
Projects
GET /api/projects- Get all projects with filters (status, type, customer, assigned user)POST /api/projects- Create new project (requires user auth)GET /api/projects/[id]- Get project by ID with contract detailsPUT /api/projects/[id]- Update project (requires user auth)DELETE /api/projects/[id]- Delete project (requires user auth)GET /api/projects/export- Export projects to Excel (read-only auth)
Contracts
GET /api/contracts- Get all contracts (read-only auth)POST /api/contracts- Create new contract (requires user auth)GET /api/contracts/[id]- Get contract by ID (read-only auth)DELETE /api/contracts/[id]- Delete contract (requires user auth)
Tasks (Templates)
GET /api/tasks- Get task templates with filters (category)POST /api/tasks- Create new task template (requires user auth)GET /api/tasks/[id]- Get task template by ID (read-only auth)PUT /api/tasks/[id]- Update task template (requires user auth)DELETE /api/tasks/[id]- Delete task template (requires user auth)
Task Sets
GET /api/task-sets- Get all task sets with filtersPOST /api/task-sets- Create new task set (requires user auth)GET /api/task-sets/[id]- Get task set with tasks (read-only auth)PUT /api/task-sets/[id]- Update task set (requires user auth)DELETE /api/task-sets/[id]- Delete task set (requires user auth)
Project Tasks (Instances)
GET /api/project-tasks- Get project tasks with filters (project_id, status)POST /api/project-tasks- Create new project task (requires user auth)GET /api/all-project-tasks- Get all project tasks across projects (read-only auth)PUT /api/project-tasks/[id]- Update project task (requires user auth)PATCH /api/project-tasks/[id]- Update task status (requires user auth)DELETE /api/project-tasks/[id]- Delete project task (requires user auth)
Contacts
GET /api/contacts- Get all contacts with filters and stats (requires auth)POST /api/contacts- Create new contact (requires auth)GET /api/contacts/[id]- Get contact by ID (requires auth)PUT /api/contacts/[id]- Update contact (requires auth)DELETE /api/contacts/[id]- Delete contact (requires auth)POST /api/contacts/[id]/sync- Sync contact to Radicale (requires auth)
Notes
GET /api/notes- Get notes with filters (project_id, task_id) (read-only auth)POST /api/notes- Create new note (requires user auth)PUT /api/notes/[id]- Update note (requires user auth)DELETE /api/notes- Delete note (requires user auth)
Files
POST /api/files- Upload file (entity_type, entity_id, file)GET /api/files- Get files with filters (entity_type, entity_id)GET /api/files/[fileId]- Download/view filePUT /api/files/[fileId]- Update file metadataDELETE /api/files/[fileId]- Delete file
Templates (DOCX)
GET /api/templates- Get all DOCX templatesPOST /api/templates- Upload new templatePUT /api/templates/[id]- Update template metadataDELETE /api/templates/[id]- Soft-delete templatePOST /api/templates/generate- Generate document from templateGET /api/templates/download/[filename]- Download template file
Notifications
GET /api/notifications- Get user notifications (paginated)PUT /api/notifications- Mark notifications as readGET /api/notifications/unread-count- Get unread notification count
Audit Logs
GET /api/audit-logs- Get audit logs with filters (requires auth)POST /api/audit-logs/log- Create audit log entry (internal use)GET /api/audit-logs/stats- Get audit statistics (requires auth)
Field History
GET /api/field-history- Get field change history (table, record_id, field)
Reports
GET /api/reports/project-stats- Get project statisticsGET /api/reports/task-stats- Get task statisticsGET /api/reports/user-activity- Get user activity stats
Admin (Admin Auth Required)
GET /api/admin/users- Get all usersPOST /api/admin/users- Create new userGET /api/admin/users/[id]- Get user by IDPUT /api/admin/users/[id]- Update userDELETE /api/admin/users/[id]- Delete userGET /api/admin/settings- Get all settingsPUT /api/admin/settings- Update settingGET /api/admin/cron- Get cron job statusPOST /api/admin/cron- Trigger cron action (backup, reminder)
Authentication
GET /api/auth/[...nextauth]- NextAuth handlersPOST /api/auth/[...nextauth]- NextAuth handlersPOST /api/auth/change-password- Change user password
Dashboard
GET /api/dashboard/stats- Get dashboard statisticsGET /api/dashboard/team-tasks- Get team tasks (team lead)
Auth Middleware Levels:
- Public - No authentication required
- Read Auth (
withReadAuth) - Any authenticated user - User Auth (
withUserAuth) - User role and above (excludes read-only) - Admin Auth (
withAdminAuth) - Admin and project_manager only
🗺️ Advanced Map Features
This project includes a comprehensive GIS system for visualizing project locations with support for Polish coordinate systems and multiple data layers.
Coordinate Systems
- EPSG:2180 - Polish 1992 coordinate system (native)
- EPSG:3857 - Web Mercator (Google Maps compatible)
- Dynamic Transformation - Proj4 handles conversions between systems
Base Layers (8 options)
- OpenStreetMap - Default open-source street map
- 🇵🇱 Polish Orthophoto (Standard) - WMTS aerial imagery (standard resolution)
- 🇵🇱 Polish Orthophoto (High-Res) - WMTS aerial imagery (high resolution)
- 🌍 Google Satellite - Global satellite imagery
- 🌍 Google Hybrid - Satellite imagery with road/label overlays
- 🌍 Google Roads - Google Maps road view
- Satellite (Esri) - Alternative satellite imagery provider
- Topographic - CartoDB topographic maps
Overlay Layers (6 transparent layers)
- 📋 Polish Cadastral Data (WMS) - Property boundaries, 80% opacity
- 🏗️ Polish Spatial Planning (WMS) - Zoning and planning data, 70% opacity
- 🛣️ LP-Portal Roads (WMS) - Polish road network, 90% opacity
- 🏷️ LP-Portal Street Names (WMS) - Street labels, 100% opacity
- 📐 LP-Portal Parcels (WMS) - Property parcels, 60% opacity
- 📍 LP-Portal Survey Markers (WMS) - Geodetic survey points, 80% opacity
Features
- Layer Switcher - Interactive control (📚 icon) to switch base layers and toggle overlays
- Project Markers - Plot all projects on map with clickable markers
- Popup Information - Click markers to see project details
- Dynamic Loading - WMTS/WMS layers configured via OGC GetCapabilities
- Route Planning - Optimize routes between project locations
- Search Integration - Find projects by location
- Responsive - Mobile-optimized map interface
Configuration
Map layers are easily configurable. See docs/MAP_LAYERS.md for:
- Adding new base layers
- Configuring WMS/WMTS sources
- Custom overlay creation
- Styling and opacity settings
Data Sources
- Geoportal.gov.pl - Official Polish government geospatial data
- LP-Portal - Polish cadastral and planning information
- Google Maps - Global satellite and road data
- OpenStreetMap - Community-driven open data
- Esri - Commercial satellite imagery
- CartoDB - Topographic map tiles
🔄 Automated Tasks & Cron Jobs
The system includes automated background tasks managed via Linux cron:
Daily Database Backup
Script: backup-db.mjs
Schedule: Daily (configurable via cron)
Features:
- Creates timestamped SQLite backup
- Stores in
backups/directory - Retains last 30 backups (auto-cleanup)
- Sends notification to configured admin user
- Logs backup completion
Due Date Reminders
Script: send-due-date-reminders.mjs
Schedule: Daily (typically runs at night)
Features:
- Checks projects finishing in 3 days
- Checks projects finishing in 1 day
- Creates notifications for assigned users
- Skips fulfilled/cancelled projects
- Logs reminder activity
Cron Management
Setup: Run setup-cron.sh in Docker container
Admin Interface: /admin/cron - View status, trigger manual runs
Cron Status API: /api/admin/cron - Get cron job status
Manual Triggers
# Manual backup
docker-compose exec app node backup-db.mjs
# Manual reminders
docker-compose exec app node send-due-date-reminders.mjs
# Test reminders (dry run)
docker-compose exec app npm run test-due-date-reminders
🌐 CardDAV Integration (Radicale)
Synchronize contacts with external CardDAV servers (e.g., Radicale):
Features
- Bi-directional Sync - Push contacts to CardDAV server
- VCard Format - Standard vCard 3.0 format
- Automatic Sync - Option to sync on contact create/update
- Manual Export - One-time export script available
- Conflict Resolution - Handles existing contacts gracefully
Configuration
Configure in src/lib/radicale-sync.js:
- Radicale server URL
- Authentication credentials
- Collection name
Usage
# One-time export all contacts
node export-contacts-to-radicale.mjs
# Automatic sync (via API)
POST /api/contacts/[id]/sync
🎨 UI/UX Features
Theme System
- Dark Mode - Full dark theme support
- Light Mode - Clean light theme
- System Preference - Automatic detection
- Persistent - Theme choice saved per user
- Smooth Transitions - Animated theme switching
Responsive Design
- Mobile-First - Optimized for mobile devices
- Tablet Support - Adaptive layouts for tablets
- Desktop Optimized - Full-featured desktop experience
- Touch-Friendly - Large touch targets on mobile
Component Library
40+ reusable React components:
- Forms - Inputs, selects, textareas with validation
- Cards - Content containers with headers
- Buttons - Multiple variants and sizes
- Badges - Status indicators with color coding
- Modals - Dialog boxes for forms and confirmations
- Tables - Sortable, filterable data tables
- Loading States - Skeletons and spinners
- Error States - User-friendly error messages
- Navigation - Responsive navbar with dropdowns
- Search - Real-time search with highlighting
User Experience
- Auto-Save Indicators - Visual feedback on saves
- Validation Feedback - Inline form validation
- Confirmation Dialogs - Prevent accidental deletions
- Keyboard Shortcuts - Power user features
- Breadcrumbs - Easy navigation
- Progress Indicators - Upload/processing progress
- Tooltips - Helpful hints and information
- Toast Notifications - Non-intrusive feedback
🧪 Testing
Unit & Integration Tests (Jest)
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
Test Suites:
- API endpoint tests (
__tests__/api/) - Component tests (
__tests__/components/) - Query function tests (
__tests__/queries/) - Utility function tests (
__tests__/utils/)
End-to-End Tests (Playwright)
npm run test:e2e # Run E2E tests
npm run test:e2e:ui # Interactive UI mode
Test Scenarios:
- User authentication flows
- Project creation workflow
- Task management
- File uploads
- Form validations
- Navigation
Test Coverage
- API Routes: Comprehensive endpoint testing
- Database Queries: All CRUD operations
- Authentication: Login, logout, session management
- Authorization: Role-based access control
- Components: Critical UI components
- Business Logic: Core functionality
🚀 Deployment
Production Checklist
-
Environment Variables
- Set strong
NEXTAUTH_SECRET(min 32 chars) - Configure
NEXTAUTH_URLto production domain - Set
NODE_ENV=production
- Set strong
-
Database
- Ensure
data/directory is persistent (volume mount) - Set up backup schedule (cron)
- Test database initialization
- Ensure
-
File Storage
- Mount persistent volumes for
uploads/,templates/,backups/ - Set appropriate permissions
- Configure backup strategy
- Mount persistent volumes for
-
Reverse Proxy (recommended: Nginx)
- SSL/TLS certificates (Let's Encrypt)
- Gzip compression
- Static file caching
- Rate limiting
- Request size limits
-
Security
- Change default admin password
- Enable firewall rules
- Configure CORS if needed
- Set up monitoring
-
Cron Jobs
- Run
setup-cron.shin container - Verify backup schedule
- Test reminder notifications
- Run
-
Monitoring
- Set up log aggregation
- Configure error tracking
- Monitor disk space (backups)
- Database performance monitoring
Nginx Example Configuration
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
client_max_body_size 10M;
location / {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}
Backup Strategy
- Database: Daily automated backups via cron (last 30 retained)
- Files: Regular volume backups of
uploads/andtemplates/ - Configuration: Version control for config files
- Off-site: Copy backups to external storage weekly
Scaling Considerations
- Vertical Scaling: Increase RAM/CPU for Docker container
- Database: SQLite suitable for 100s of concurrent users
- File Storage: Mount NFS/S3 for distributed storage
- Caching: Add Redis for session storage (future)
- CDN: Serve static assets via CDN (future)
📚 Documentation
Additional documentation available in the /docs directory:
docs/MAP_LAYERS.md- Map layer configuration guideDEPLOYMENT_GUIDE_TEMPLATE.md- Detailed deployment instructionsDOCKER_GIT_DEPLOYMENT.md- Git-based deployment guideCONTACTS_SYSTEM_README.md- Contact management detailsRADICALE_SYNC_README.md- CardDAV sync documentationDOCX_TEMPLATES_README.md- Document template systemroute_planning_readme.md- Route optimization featuresROADMAP.md- Future feature roadmap
🔧 Troubleshooting
Common Issues
Database locked error
- Ensure only one process accesses database
- Check for hung connections
- Restart application
File upload fails
- Verify
uploads/directory exists and is writable - Check disk space
- Confirm file size under 10MB
Map layers not loading
- Check network connectivity to external services
- Verify CORS configuration
- Check browser console for errors
Cron jobs not running
- Verify cron service is running in container
- Check
setup-cron.shwas executed - Review cron logs:
docker-compose exec app crontab -l
Authentication issues
- Clear browser cookies
- Verify
NEXTAUTH_SECRETis set - Check session expiration
- Review audit logs for failed attempts
Debug Mode
# View detailed logs
docker-compose logs -f app
# Access container shell
docker-compose exec app bash
# Check database
docker-compose exec app sqlite3 data/database.sqlite
# Test API endpoints
curl -X GET http://localhost:3001/api/projects
🤝 Contributing
Development Workflow
- Fork & Clone
git clone <your-fork-url>
cd panel
git remote add upstream <original-repo-url>
- Create Feature Branch
git checkout -b feature/amazing-feature
- Make Changes
- Write code following existing patterns
- Add tests for new features
- Update documentation
- Follow ESLint rules
- Test
npm run lint
npm test
npm run test:e2e
- Commit
git add .
git commit -m "feat: add amazing feature"
Use conventional commits:
feat:- New featurefix:- Bug fixdocs:- Documentationstyle:- Formattingrefactor:- Code restructuretest:- Testschore:- Maintenance
- Push & PR
git push origin feature/amazing-feature
Create Pull Request on GitHub
Code Standards
- ESLint: Follow Next.js recommended config
- Components: Functional components with hooks
- Naming: Descriptive names, camelCase for variables
- Files: PascalCase for components, kebab-case for utils
- Comments: JSDoc for functions, inline for complex logic
- Formatting: Consistent indentation (tabs)
Database Migrations
Add migrations in src/lib/init-db.js:
try {
db.exec(`ALTER TABLE table_name ADD COLUMN new_column TEXT;`);
} catch (e) {
// Column already exists
}
<EFBFBD> Documentation
Core Documentation
- Main README - This file - complete project overview
- Development Roadmap - Feature priorities, timelines, and future plans
- Documentation Index - Complete documentation directory
Feature Guides
- Contacts System - Contact management and CardDAV integration
- DOCX Templates - Document generation system with troubleshooting
- Radicale CardDAV Sync - Automatic contact synchronization
- Route Planning - Multi-point route optimization
- Map Layers Configuration - WMTS/WMS layer setup guide
Deployment Guides
- Advanced Deployment - Detailed deployment strategies
- Git-Based Deployment - CI/CD and repository deployment
<EFBFBD>📄 License
This project is private and proprietary. All rights reserved.
Unauthorized copying, modification, distribution, or use of this software is strictly prohibited.
📞 Support
For issues, questions, or feature requests, please contact the development team or create an issue in the repository.
Built with ❤️ for Wastpol | Version 0.1.1 | January 2026