# Coco Dreams Lanka - HR & Repair Management System
## Architecture, Database Design & Implementation Plan

---

### 1. Executive Summary & Client Brand Alignment
**Client**: Coco Dreams Lanka ([www.cocodreamslanka.com](http://www.cocodreamslanka.com))  
**Objective**: Build a bespoke, enterprise-grade HR Management System with a POS-style rapid-entry interface, full payroll support (monthly salary + contract/piece-rate), attendance with Excel import, leave management, service letter generation, repair/service tracking, and dual-database integration with their existing POS database.

To ensure the client recognizes this as an **expert, handcrafted human-grade enterprise system** (and never generic AI boilerplate):
- **Bespoke Theme & Design System**: Custom tailored palette reflecting Coco Dreams Lanka's premium natural brand (Deep Emerald `#0F392B`, Palm Gold `#C59B27`, Slate Dark `#1E293B`, and Clean Crisp White/Zinc surfaces).
- **POS-Style Ergonomics**: Real-time calculated line items, keyboard-accessible quick entry grids, barcode/serial search, modal drawers, and quick-filter data tables.
- **Enterprise Architecture**: Dual database connection support (`mysql` for HR & `mysql_pos` for POS database), repository/service pattern, role-based permission matrix, and automated PDF export views.

---

### 2. Dual Database Architecture

```mermaid
graph TD
    subgraph Coco Dreams Lanka HR System
        App[Laravel Application Backend]
        UI[POS-Style Modern Dashboard & Blades]
        HR_DB[(Primary HR Database: cocodreams_hr)]
    end

    subgraph Existing Client POS
        POS_DB[(External POS Database: cocodreams_pos)]
    end

    UI --> App
    App -->|Read / Write| HR_DB
    App -->|Read Customers, Invoices, Sync Employees| POS_DB
    App -->|Link POS Customer & Invoice to Repair Job| HR_DB
```

- **Connection 1 (`mysql`)**: Core HR & Operations Database (Employees, Departments, Piece Rates, Payroll, Attendance, Leaves, Service Jobs, User Roles).
- **Connection 2 (`mysql_pos`)**: Configurable secondary read-only / sync connection to the client's running POS database (Customer records, sales orders/invoices, item master).

---

### 3. Detailed Database Schema Design (Primary HR Database)

```mermaid
erDiagram
    DEPARTMENTS ||--o{ EMPLOYEES : employs
    DESIGNATIONS ||--o{ EMPLOYEES : assigns
    EMPLOYEES ||--o{ ATTENDANCES : logs
    EMPLOYEES ||--o{ LEAVE_REQUESTS : requests
    EMPLOYEES ||--o{ PIECE_RATE_ENTRIES : produces
    EMPLOYEES ||--o{ PAYROLL_RECORDS : receives
    EMPLOYEES ||--o{ REPAIR_JOBS : assigned_technician
    PIECE_RATE_ITEMS ||--o{ PIECE_RATE_ENTRIES : defines_rate
    PAYROLL_RECORDS ||--o{ PAYROLL_ITEMS : contains
    REPAIR_JOBS ||--o{ REPAIR_PARTS_USED : uses
    REPAIR_JOBS ||--o{ REPAIR_LOGS : logs_status
    ROLES ||--o{ ROLE_PERMISSIONS : defines
    USERS ||--o{ ROLES : belongs_to
```

#### 3.1 Core Authentication & Roles
- **`users`**: `id`, `name`, `email`, `password`, `employee_id` (nullable fk), `role_id`, `status` (`active`/`inactive`), `remember_token`, timestamps.
- **`roles`**: `id`, `name` (`Super Admin`, `HR Admin`, `Manager`, `Employee`, `Technician`), `slug`, `description`, timestamps.
- **`permissions`**: `id`, `name`, `slug`, `module` (`employees`, `payroll`, `attendance`, `leaves`, `repairs`, `pos_data`, `settings`), timestamps.
- **`role_permissions`**: `id`, `role_id`, `permission_id`.

#### 3.2 Employee Management
- **`departments`**: `id`, `name`, `code`, `is_active`, timestamps.
- **`designations`**: `id`, `name`, `department_id`, timestamps.
- **`employees`**:
  - `id`, `employee_number` (e.g. `CDL-1001`, unique)
  - `pos_employee_id` (external ID from POS system for automatic sync)
  - `first_name`, `last_name`, `email`, `phone`, `nic_passport`
  - `address`, `emergency_contact`, `date_of_birth`, `gender`
  - `department_id`, `designation_id`, `joining_date`, `exit_date`
  - `employment_type`: `enum('monthly', 'contract_piece_rate', 'probation', 'part_time')`
  - `salary_type`: `enum('monthly_fixed', 'piece_rate_only', 'hybrid')`
  - `basic_salary`: `decimal(12,2)` default 0.00
  - `bank_name`, `bank_account_no`, `bank_branch`
  - `status`: `enum('active', 'inactive', 'terminated', 'resigned')`
  - `profile_photo_path`, timestamps.

#### 3.3 Piece-Rate & Production (POS-Style Entry)
- **`piece_rate_items`**:
  - `id`, `item_code`, `name` (e.g., *Shoes ABC*, *Coir Fiber Roll 50m*, *Coco Peat Block 5kg*)
  - `default_rate`: `decimal(10,2)` (e.g. Rs. 150.00)
  - `unit`: `varchar(30)` (pieces, pairs, bundles, blocks)
  - `is_active`: `boolean`, timestamps.
- **`piece_rate_entries`**:
  - `id`, `entry_date`, `employee_id`, `piece_rate_item_id`
  - `quantity`: `decimal(10,2)`
  - `rate_applied`: `decimal(10,2)`
  - `total_amount`: `decimal(12,2)` (generated / auto-computed)
  - `batch_reference`: `varchar(50)` (optional shift / production batch)
  - `notes`: `text`, `recorded_by_user_id`, `payroll_record_id` (nullable when included in payroll), timestamps.

#### 3.4 Attendance & Leaves
- **`attendances`**:
  - `id`, `employee_id`, `date` (unique with employee_id)
  - `check_in`: `time`, `check_out`: `time`
  - `status`: `enum('present', 'absent', 'leave', 'half_day', 'holiday')`
  - `working_hours`: `decimal(5,2)`
  - `overtime_hours`: `decimal(5,2)`
  - `source`: `enum('manual', 'excel_import', 'biometric')`
  - `notes`: `varchar(255)`, timestamps.
- **`leave_types`**:
  - `id`, `name` (Annual, Casual, Medical, Unpaid), `annual_quota` (e.g. 14 days), `is_paid`: `boolean`.
- **`leave_requests`**:
  - `id`, `employee_id`, `leave_type_id`, `start_date`, `end_date`, `days_count`
  - `reason`: `text`, `status`: `enum('pending', 'approved', 'rejected')`
  - `approved_by_user_id`, `rejection_reason`: `text`, `created_at`, timestamps.

#### 3.5 Payroll Engine
- **`payroll_records`**:
  - `id`, `payroll_month` (e.g. `2026-09`), `employee_id`
  - `employment_type_at_run`: `varchar(50)`
  - `basic_salary`: `decimal(12,2)`
  - `total_piece_rate_pay`: `decimal(12,2)` (calculated from all piece entries)
  - `overtime_amount`: `decimal(12,2)`
  - `total_allowances`: `decimal(12,2)`
  - `gross_salary`: `decimal(12,2)`
  - `total_deductions`: `decimal(12,2)`
  - `net_salary`: `decimal(12,2)`
  - `payment_status`: `enum('draft', 'approved', 'paid')`
  - `payment_method`: `enum('bank_transfer', 'cash', 'cheque')`
  - `payment_date`: `date`, `processed_by_user_id`, timestamps.
- **`payroll_items`**:
  - `id`, `payroll_record_id`, `type`: `enum('allowance', 'deduction', 'piece_rate', 'overtime', 'bonus')`
  - `title`: `varchar(100)` (e.g., Transport Allowance, EPF Employee 8%, EPF Employer 12%, Advance)
  - `amount`: `decimal(12,2)`, timestamps.

#### 3.6 Repair & Service Job Tracking
- **`repair_jobs`**:
  - `id`, `job_number` (e.g. `SRV-2026-001`, unique)
  - `pos_customer_id`: `varchar(100)` (foreign key/ID from POS customer table)
  - `customer_name`: `varchar(150)` (cached for fast indexing)
  - `customer_phone`: `varchar(50)`
  - `pos_invoice_number`: `varchar(100)` (linked invoice from POS sales)
  - `product_name`: `varchar(200)`
  - `serial_number`: `varchar(150)`
  - `problem_complaint`: `text`
  - `assigned_technician_id`: `unsignedBigInteger` (fk to `employees`)
  - `received_date`: `date`
  - `estimated_completion_date`: `date`
  - `completed_date`: `date`
  - `delivered_date`: `date`
  - `warranty_type`: `enum('warranty', 'non_warranty')`
  - `status`: `enum('received', 'inspection', 'repairing', 'waiting_parts', 'completed', 'delivered')`
  - `technician_notes`: `text`
  - `labor_charges`: `decimal(10,2)` default 0.00
  - `parts_charges`: `decimal(10,2)` default 0.00
  - `total_charges`: `decimal(10,2)` default 0.00
  - `created_by_user_id`, timestamps.
- **`repair_parts_used`**:
  - `id`, `repair_job_id`, `part_name`, `part_code`, `quantity`: `int`, `unit_cost`: `decimal(10,2)`, `total_cost`: `decimal(10,2)`.
- **`repair_status_logs`**:
  - `id`, `repair_job_id`, `old_status`, `new_status`, `changed_by_user_id`, `comments`, `created_at`.

#### 3.7 Experience & Service Letter Templates
- **`experience_letters`**:
  - `id`, `employee_id`, `reference_number`, `issue_date`, `designation_title`, `joining_date`, `leaving_date`
  - `conduct_remarks`: `text`, `authorized_signatory_name`: `varchar(100)`, `authorized_signatory_title`: `varchar(100)`, timestamps.

---

### 4. POS Database Virtual Schema & Sync Integration

To fulfill:
> *"We have a running POS system, you have to connect its database with this system website. So, we need to see in another TAB customer's datails available in POS database. And, Sales details of it. Whenever add new employee in the POS, this HR system also should be updated according to those updates. In the HR system's REPAIR/SERVICE module, we need to search and select customer and invoice from POS database."*

We provide:
1. **Secondary Connection Config in `config/database.php`**:
   - `'pos' => ['driver' => 'mysql', 'host' => env('POS_DB_HOST'), ...]`
2. **Dedicated POS Tab Modules**:
   - **POS Customers**: Live search, full customer history, contact details, balance.
   - **POS Sales / Invoices**: Invoice view, purchased item line-details, date, totals.
3. **Repair Module Live Bridge**:
   - AJAX Typeahead autocomplete searching the `customers` and `invoices` table directly from the POS DB to instantly fill customer & purchase data.
4. **Employee Auto-Sync Engine**:
   - Artisan command & UI button: `php artisan pos:sync-employees` that automatically checks new employees in the POS DB and inserts/updates them into the HR employee roster.

---

### 5. Professional UI/UX Architecture (Anti-AI Aesthetic)

- **Header / Navigation**:
  - Top bar with Coco Dreams Lanka branding, date/shift indicator, quick actions dock (`+ Piece Entry`, `+ Punch Attendance`, `+ New Repair Job`).
  - Dark Slate / Emerald sidebar with clean icons (Lucide icons), categorizing:
    1. **Overview**: Executive Dashboard & Quick Stats
    2. **HR & Roster**: Employees, Departments, Experience Letters
    3. **Attendance & Leave**: Daily Attendance, Monthly Sheet, Excel Import, Leave Requests
    4. **Payroll & POS Calculator**: POS-Style Piece Rate Calculator, Monthly Run, Payslip Generator, Payroll Reports
    5. **Repair & Service**: Active Jobs, Pipeline Board (Kanban), Job Sheets, Spare Parts
    6. **POS Integration**: POS Customers, POS Sales & Invoices, Sync Manager
    7. **Administration**: Role & Permissions Matrix, System Settings
- **POS-Style Rapid Input Grids**:
  - High speed, responsive numeric inputs with instant calculation.
  - Printable Receipts, Service Job Cards, Payslips formatted with printable CSS `@media print`.

---

### 6. Step-by-Step Implementation Roadmap

1. **Phase 1**: Initialize clean Laravel project structure in `d:\Client_Projects\cocodreamslanka`.
2. **Phase 2**: Configure Database connections (`mysql` for HR + `mysql_pos` demo/production connection).
3. **Phase 3**: Create Eloquent Migrations for all HR, Payroll, Piece-Rate, Repair, and Role-Permission tables.
4. **Phase 4**: Create Seeders with realistic Coco Dreams Lanka data (Employees, Piece Rate items, Sample POS Customers & Invoices, Repair Jobs, User Roles).
5. **Phase 5**: Build the bespoke Coco Dreams Lanka POS-style Admin UI (Blade views, responsive CSS, interactive calculator).
6. **Phase 6**: Implement POS Integration controller & AJAX endpoints for Customer search, Invoice lookup, and Employee Sync.
7. **Phase 7**: Implement Experience Letter generation & Payroll Printable Payslips / Excel Export format.
8. **Phase 8**: Verification & Documentation walkthrough for deployment on the client's server.
