From 5369c799d0bf0f5b8e8d2738920a017cae90613e Mon Sep 17 00:00:00 2001 From: RKWojs Date: Fri, 16 Jan 2026 10:30:43 +0100 Subject: [PATCH] Update Readme --- README.md | 1320 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 1119 insertions(+), 201 deletions(-) diff --git a/README.md b/README.md index b77e172..b72d531 100644 --- a/README.md +++ b/README.md @@ -1,307 +1,1225 @@ -# Project Management Panel +# eProjektant Wastpol - Project Management System -A comprehensive project management system built with Next.js for managing construction/engineering projects, contracts, and tasks. +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. -## 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 -- Create and manage projects with detailed information -- Link projects to contracts -- Track project deadlines and progress -- Add custom notes and contact information +- **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 -- Create and manage contracts -- Track contract details including customer and investor information -- Link multiple projects to contracts -- Monitor contract deadlines +- **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 -### βœ… Task Management +### βœ… Advanced Task System -- Create task templates for reusable workflows -- Add tasks to projects (both template-based and custom) -- Track task status and priorities -- Monitor task deadlines and completion +- **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 -### πŸ“Š Dashboard +### πŸ‘₯ Contact Management -- Overview of project statistics -- Recent projects display -- Task completion tracking -- Quick access to pending items +- **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 -### πŸ” Authentication & Authorization +### πŸ“„ Document Generation -- Complete user authentication system with NextAuth.js -- Role-based access control (Admin, User, Guest roles) -- Secure session management -- Password-based authentication -- User registration and management +- **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 -### πŸ‘₯ User Management +### πŸ“Ž File Management -- Admin interface for user administration -- Create, edit, and delete user accounts -- Role assignment and permission management -- User activity monitoring +- **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 -### πŸ“‹ Audit Logging +### πŸ”” Notification System -- Comprehensive logging of all user actions -- Security event tracking -- System activity monitoring -- Audit trail for compliance and debugging +- **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 -### πŸ“Š Data Export +### πŸ—ΊοΈ Geographic Information System (GIS) -- Export projects to Excel format grouped by status -- Includes project name, address, plot, WP, and finish date -- Separate sheets for each project status (registered, in progress, fulfilled, etc.) +- **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 -## Tech Stack +### πŸ” Security & Authentication -- **Framework**: Next.js 15.1.8 -- **Database**: SQLite with better-sqlite3 -- **Authentication**: NextAuth.js -- **Styling**: Tailwind CSS -- **Date Handling**: date-fns -- **Frontend**: React 19 -- **Mapping**: Leaflet with React-Leaflet -- **Container**: Docker & Docker Compose +- **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 -## Getting Started +### πŸ“Š 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 (version 16 or higher) -- npm or yarn -- Docker (optional, for containerized development) +- **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 -1. Clone the repository - +1. **Clone the repository** ```bash git clone cd panel ``` -2. Install dependencies - +2. **Install dependencies** ```bash npm install ``` -3. Start the development server +3. **Initialize the database** +The database will auto-initialize on first run, or you can manually run: +```bash +node src/lib/init-db.js +``` + +4. **Create an admin user** +```bash +npm run create-admin +``` + +Follow the prompts to create your first admin account. + +5. **Start development server** ```bash npm run dev ``` -4. Open [http://localhost:3000](http://localhost:3000) in your browser +6. **Open in browser** + +Navigate to [http://localhost:3000](http://localhost:3000) #### Option 2: Docker Development -1. Clone the repository - +1. **Clone the repository** ```bash git clone cd panel ``` -2. Start with Docker Compose - +2. **Start with Docker Compose** ```bash -docker-compose up +docker-compose -f docker-compose.yml up --build ``` -3. Open [http://localhost:3000](http://localhost:3000) in your browser +3. **Create admin user** (in container) +```bash +docker-compose exec app npm run create-admin +``` + +4. **Open in browser** + +Navigate to [http://localhost:3000](http://localhost:3000) + +#### Option 3: Production Deployment with Docker + +1. **Set environment variables** + +Create a `.env` file: +```env +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 +``` + +2. **Deploy with Docker Compose** +```bash +docker-compose -f docker-compose.prod.yml up -d +``` + +3. **Setup cron jobs** (inside container) +```bash +docker-compose exec app bash setup-cron.sh +``` + +4. **Create admin user** +```bash +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 (`development` or `production`) +- `NEXTAUTH_SECRET` - Secret key for NextAuth.js sessions (min 32 chars) +- `NEXTAUTH_URL` - Full URL of your application +- `AUTH_TRUST_HOST` - Set to `true` for production behind reverse proxy +- `TZ` - 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 deployment +- `GIT_BRANCH` - Branch to deploy (default: `main`) +- `GIT_COMMIT` - Specific commit to deploy (optional) ### Database Setup -The application uses SQLite database which will be automatically initialized on first run. The database file is located at `data/database.sqlite`. +The application uses SQLite with automatic initialization. On first run: -### Admin Setup +1. Database file created at `data/database.sqlite` +2. All tables created automatically +3. Indexes created for performance +4. Default settings inserted -To create an initial admin user: +**Database location**: `./data/database.sqlite` -```bash -npm run create-admin -``` +**Backup location**: `./backups/` -This will create an admin user account. Access the admin panel at `/admin/users` to manage users and roles. +**Migrations**: Handled automatically via `init-db.js` with try-catch blocks -## Project Structure + + +## πŸ“ Project Structure ``` -src/ -β”œβ”€β”€ app/ # Next.js app router pages -β”‚ β”œβ”€β”€ admin/ # Admin dashboard and user management -β”‚ β”œβ”€β”€ api/ # API routes -β”‚ β”‚ β”œβ”€β”€ admin/ # Admin-related endpoints (e.g., user management) -β”‚ β”‚ β”œβ”€β”€ all-project-tasks/ # Get all project tasks endpoint -β”‚ β”‚ β”œβ”€β”€ audit-logs/ # Audit log endpoints -β”‚ β”‚ β”œβ”€β”€ auth/ # Authentication endpoints -β”‚ β”‚ β”œβ”€β”€ contracts/ # Contract management endpoints -β”‚ β”‚ β”œβ”€β”€ notes/ # Notes management endpoints -β”‚ β”‚ β”œβ”€β”€ projects/ # Project management endpoints -β”‚ β”‚ β”œβ”€β”€ project-tasks/ # Task management endpoints -β”‚ β”‚ β”œβ”€β”€ task-notes/ # Task-specific notes endpoints -β”‚ β”‚ └── tasks/ # Task template endpoints -β”‚ β”œβ”€β”€ auth/ # Authentication pages (login, etc.) -β”‚ β”œβ”€β”€ contracts/ # Contract pages -β”‚ β”œβ”€β”€ projects/ # Project pages -β”‚ β”œβ”€β”€ project-tasks/ # Project-specific task pages -β”‚ └── tasks/ # Task management pages -β”œβ”€β”€ components/ # Reusable React components -β”‚ β”œβ”€β”€ auth/ # Authentication-related components -β”‚ β”œβ”€β”€ ui/ # UI components (Button, Card, etc.) -β”‚ β”œβ”€β”€ AuditLogViewer.js # Component to view audit logs -β”‚ β”œβ”€β”€ ContractForm.js # Contract form component -β”‚ β”œβ”€β”€ NoteForm.js # Note form component -β”‚ β”œβ”€β”€ ProjectForm.js # Project form component -β”‚ β”œβ”€β”€ ProjectTaskForm.js # Project task form component -β”‚ β”œβ”€β”€ ProjectTasksSection.js # Project tasks section component -β”‚ β”œβ”€β”€ TaskForm.js # Task form component -β”‚ └── TaskTemplateForm.js # Task template form component -β”œβ”€β”€ lib/ # Utility functions -β”‚ β”œβ”€β”€ queries/ # Database query functions -β”‚ β”œβ”€β”€ auditLog.js # Audit logging utilities -β”‚ β”œβ”€β”€ auth.js # Authentication helpers -β”‚ β”œβ”€β”€ db.js # Database connection -β”‚ β”œβ”€β”€ init-db.js # Database initialization -β”‚ └── userManagement.js # User management functions -└── middleware.js # Next.js middleware for auth and routing +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 -- `npm run dev` - Start development server -- `npm run build` - Build for production + +## πŸ“œ Available Scripts + +### Development +- `npm run dev` - Start development server on port 3000 +- `npm run build` - Build for production (outputs to `.next/`) - `npm run start` - Start production server -- `npm run lint` - Run ESLint -- `npm run export-projects` - Export all projects to Excel file grouped by status +- `npm run lint` - Run ESLint for code quality -## Docker Commands +### Testing +- `npm test` - Run Jest unit/integration tests +- `npm run test:watch` - Run tests in watch mode +- `npm run test:coverage` - Generate test coverage report +- `npm run test:e2e` - Run Playwright E2E tests +- `npm run test:e2e:ui` - Run Playwright tests with UI -- `docker-compose up` - Start the application with Docker -- `docker-compose down` - Stop the Docker containers -- `docker-compose up --build` - Rebuild and start the application +### Utilities +- `npm run create-admin` - Interactive admin user creation +- `npm run export-projects` - Export all projects to Excel file +- `npm run send-due-date-reminders` - Manually trigger due date reminders +- `npm run test-due-date-reminders` - Test reminder functionality -## Database Schema +### 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 export +- `setup-cron.sh` - Setup automated cron jobs -The application uses the following main tables: +## 🐳 Docker Commands -- **contracts** - Contract information -- **projects** - Project details linked to contracts -- **tasks** - Task templates -- **project_tasks** - Tasks assigned to specific projects -- **notes** - Project notes and updates -- **users** - User accounts and roles for authentication -- **sessions** - User session management -- **audit_logs** - Detailed logs for security and tracking +### Development +```bash +# Start development environment +docker-compose up -## API Endpoints +# 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 +```bash +# 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 +```bash +# 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 -- `POST /api/projects` - Create new project -- `GET /api/projects/[id]` - Get project by ID -- `PUT /api/projects/[id]` - Update project -- `DELETE /api/projects/[id]` - Delete project +- `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 details +- `PUT /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) -- `GET /api/contracts` - Get all contracts -- `POST /api/contracts` - Create new contract -- `GET /api/contracts/[id]` - Get contract by ID -- `PUT /api/contracts/[id]` - Update contract -- `DELETE /api/contracts/[id]` - Delete contract +### 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) -### Tasks +### Task Sets +- `GET /api/task-sets` - Get all task sets with filters +- `POST /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) -- `GET /api/tasks` - Get task templates -- `POST /api/tasks` - Create new task template -- `GET /api/tasks/[id]` - Get task template by ID -- `PUT /api/tasks/[id]` - Update task template -- `DELETE /api/tasks/[id]` - Delete task template -- `GET /api/tasks/templates` - Get all task templates +### 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) -### Project Tasks - -- `GET /api/project-tasks` - Get project tasks or task templates -- `POST /api/project-tasks` - Create new project task -- `PATCH /api/project-tasks/[id]` - Update task status -- `DELETE /api/project-tasks/[id]` - Delete task -- `GET /api/all-project-tasks` - Get all project tasks across all projects +### 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) -- `POST /api/notes` - Create new note -- `DELETE /api/notes` - Delete note +### 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 file +- `PUT /api/files/[fileId]` - Update file metadata +- `DELETE /api/files/[fileId]` - Delete file + +### Templates (DOCX) +- `GET /api/templates` - Get all DOCX templates +- `POST /api/templates` - Upload new template +- `PUT /api/templates/[id]` - Update template metadata +- `DELETE /api/templates/[id]` - Soft-delete template +- `POST /api/templates/generate` - Generate document from template +- `GET /api/templates/download/[filename]` - Download template file + +### Notifications +- `GET /api/notifications` - Get user notifications (paginated) +- `PUT /api/notifications` - Mark notifications as read +- `GET /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) -- `GET /api/audit-logs` - Get all audit logs -- `POST /api/audit-logs/log` - Create a new audit log entry -- `GET /api/audit-logs/stats` - Get audit log statistics +### Field History +- `GET /api/field-history` - Get field change history (table, record_id, field) -### Admin +### Reports +- `GET /api/reports/project-stats` - Get project statistics +- `GET /api/reports/task-stats` - Get task statistics +- `GET /api/reports/user-activity` - Get user activity stats +### Admin (Admin Auth Required) - `GET /api/admin/users` - Get all users -- `POST /api/admin/users` - Create a new user -- `PUT /api/admin/users/[id]` - Update a user -- `DELETE /api/admin/users/[id]` - Delete a user +- `POST /api/admin/users` - Create new user +- `GET /api/admin/users/[id]` - Get user by ID +- `PUT /api/admin/users/[id]` - Update user +- `DELETE /api/admin/users/[id]` - Delete user +- `GET /api/admin/settings` - Get all settings +- `PUT /api/admin/settings` - Update setting +- `GET /api/admin/cron` - Get cron job status +- `POST /api/admin/cron` - Trigger cron action (backup, reminder) -## Advanced Map Features +### Authentication +- `GET /api/auth/[...nextauth]` - NextAuth handlers +- `POST /api/auth/[...nextauth]` - NextAuth handlers +- `POST /api/auth/change-password` - Change user password -This project includes a powerful map system for project locations, supporting multiple dynamic base layers and transparent overlays: +### Dashboard +- `GET /api/dashboard/stats` - Get dashboard statistics +- `GET /api/dashboard/team-tasks` - Get team tasks (team lead) -### Base Layers (8 total) -- **OpenStreetMap** (default street map) -- **πŸ‡΅πŸ‡± Polish Orthophoto (Standard Resolution)** - WMTS aerial imagery -- **πŸ‡΅πŸ‡± Polish Orthophoto (High Resolution)** - WMTS high-res aerial imagery -- **🌍 Google Satellite** - Global satellite imagery -- **🌍 Google Hybrid** - Satellite imagery with road overlays -- **🌍 Google Roads** - Google Maps road view -- **Satellite (Esri)** - Alternative satellite imagery -- **Topographic** - CartoDB topographic maps +**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 -### Overlay Layers (6 total with transparency) -- **πŸ“‹ Polish Cadastral Data** (WMS, property boundaries - 80% opacity) -- **πŸ—οΈ Polish Spatial Planning** (WMS, zoning data - 70% opacity) -- **πŸ›£οΈ LP-Portal Roads** (WMS, 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, survey points - 80% opacity) -Users can switch layers using the map control (πŸ“š icon). WMTS/WMS layers are configured dynamically using OGC GetCapabilities, making it easy to add new sources. See [`docs/MAP_LAYERS.md`](docs/MAP_LAYERS.md) for details on adding and configuring map layers. -## UI/UX +## πŸ—ΊοΈ Advanced Map Features -- Modern, responsive interface built with React 19 and Tailwind CSS -- Intuitive dashboards, search, and filter components -- Modular, reusable UI components for forms, lists, and maps +This project includes a comprehensive GIS system for visualizing project locations with support for Polish coordinate systems and multiple data layers. -## Extensibility & Testing +### Coordinate Systems +- **EPSG:2180** - Polish 1992 coordinate system (native) +- **EPSG:3857** - Web Mercator (Google Maps compatible) +- **Dynamic Transformation** - Proj4 handles conversions between systems -- Modular codebase: easily add new features, endpoints, or UI components -- Automated tests: Playwright for E2E, Jest and Testing Library for unit/integration -- Dockerized for consistent development and deployment +### Base Layers (8 options) +1. **OpenStreetMap** - Default open-source street map +2. **πŸ‡΅πŸ‡± Polish Orthophoto (Standard)** - WMTS aerial imagery (standard resolution) +3. **πŸ‡΅πŸ‡± Polish Orthophoto (High-Res)** - WMTS aerial imagery (high resolution) +4. **🌍 Google Satellite** - Global satellite imagery +5. **🌍 Google Hybrid** - Satellite imagery with road/label overlays +6. **🌍 Google Roads** - Google Maps road view +7. **Satellite (Esri)** - Alternative satellite imagery provider +8. **Topographic** - CartoDB topographic maps -## Contributing +### Overlay Layers (6 transparent layers) +1. **πŸ“‹ Polish Cadastral Data** (WMS) - Property boundaries, 80% opacity +2. **πŸ—οΈ Polish Spatial Planning** (WMS) - Zoning and planning data, 70% opacity +3. **πŸ›£οΈ LP-Portal Roads** (WMS) - Polish road network, 90% opacity +4. **🏷️ LP-Portal Street Names** (WMS) - Street labels, 100% opacity +5. **πŸ“ LP-Portal Parcels** (WMS) - Property parcels, 60% opacity +6. **πŸ“ LP-Portal Survey Markers** (WMS) - Geodetic survey points, 80% opacity -1. Fork the repository -2. Create a feature branch (`git checkout -b feature/amazing-feature`) -3. Commit your changes (`git commit -m 'Add some amazing feature'`) -4. Push to the branch (`git push origin feature/amazing-feature`) -5. Open a Pull Request +### 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 -## License +### Configuration +Map layers are easily configurable. See [`docs/MAP_LAYERS.md`](docs/MAP_LAYERS.md) for: +- Adding new base layers +- Configuring WMS/WMTS sources +- Custom overlay creation +- Styling and opacity settings -This project is private and proprietary. +### 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 +```bash +# 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 +```bash +# 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) +```bash +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) +```bash +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 + +1. **Environment Variables** + - Set strong `NEXTAUTH_SECRET` (min 32 chars) + - Configure `NEXTAUTH_URL` to production domain + - Set `NODE_ENV=production` + +2. **Database** + - Ensure `data/` directory is persistent (volume mount) + - Set up backup schedule (cron) + - Test database initialization + +3. **File Storage** + - Mount persistent volumes for `uploads/`, `templates/`, `backups/` + - Set appropriate permissions + - Configure backup strategy + +4. **Reverse Proxy** (recommended: Nginx) + - SSL/TLS certificates (Let's Encrypt) + - Gzip compression + - Static file caching + - Rate limiting + - Request size limits + +5. **Security** + - Change default admin password + - Enable firewall rules + - Configure CORS if needed + - Set up monitoring + +6. **Cron Jobs** + - Run `setup-cron.sh` in container + - Verify backup schedule + - Test reminder notifications + +7. **Monitoring** + - Set up log aggregation + - Configure error tracking + - Monitor disk space (backups) + - Database performance monitoring + +### Nginx Example Configuration +```nginx +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 +1. **Database**: Daily automated backups via cron (last 30 retained) +2. **Files**: Regular volume backups of `uploads/` and `templates/` +3. **Configuration**: Version control for config files +4. **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`](docs/MAP_LAYERS.md) - Map layer configuration guide +- `DEPLOYMENT_GUIDE_TEMPLATE.md` - Detailed deployment instructions +- `DOCKER_GIT_DEPLOYMENT.md` - Git-based deployment guide +- `CONTACTS_SYSTEM_README.md` - Contact management details +- `RADICALE_SYNC_README.md` - CardDAV sync documentation +- `DOCX_TEMPLATES_README.md` - Document template system +- `route_planning_readme.md` - Route optimization features +- `ROADMAP.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.sh` was executed +- Review cron logs: `docker-compose exec app crontab -l` + +**Authentication issues** +- Clear browser cookies +- Verify `NEXTAUTH_SECRET` is set +- Check session expiration +- Review audit logs for failed attempts + +### Debug Mode +```bash +# 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 + +1. **Fork & Clone** +```bash +git clone +cd panel +git remote add upstream +``` + +2. **Create Feature Branch** +```bash +git checkout -b feature/amazing-feature +``` + +3. **Make Changes** +- Write code following existing patterns +- Add tests for new features +- Update documentation +- Follow ESLint rules + +4. **Test** +```bash +npm run lint +npm test +npm run test:e2e +``` + +5. **Commit** +```bash +git add . +git commit -m "feat: add amazing feature" +``` + +Use conventional commits: +- `feat:` - New feature +- `fix:` - Bug fix +- `docs:` - Documentation +- `style:` - Formatting +- `refactor:` - Code restructure +- `test:` - Tests +- `chore:` - Maintenance + +6. **Push & PR** +```bash +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`: +```javascript +try { + db.exec(`ALTER TABLE table_name ADD COLUMN new_column TEXT;`); +} catch (e) { + // Column already exists +} +``` + +## πŸ“„ 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