# ARCHITECTURE_GUIDE.md

# Architecture Guide
This document defines the architectural rules, conventions, and development philosophy for all applications built on this platform.

---

# Core Philosophy

## Build a Platform, Not Just an Application

Every feature should be designed for reuse across future products.

Examples of future products:
- Document Management
- Inventory Management
- CRM
- POS
- HR
- School Management
- ERP

Code should be written as reusable modules rather than application-specific implementations.

---

# Architectural Principles

1. Server-rendered first
2. Progressive enhancement with HTMX
3. Thin controllers
4. Business logic in services/actions
5. Reusable components
6. Modular boundaries
7. Convention over configuration
8. Minimize dependencies
9. Shared hosting friendly
10. Optimize for maintainability

---

# High-Level Architecture

Request
→ Router
→ Middleware
→ Controller
→ Service / Action
→ Repository
→ Model
→ Database

Response
← Twig View
← HTMX Partial
← Redirect

---

# Project Structure

app/
├── Actions/
├── Controllers/
├── DTOs/
├── Middleware/
├── Models/
├── Repositories/
├── Services/
├── Components/
├── Helpers/
├── Policies/
└── ViewModels/

config/
public/
resources/
routes/
storage/
vendor/

resources/
├── views/
├── layouts/
├── components/
└── pdf/

---

# Folder Responsibilities

## Controllers
Responsibilities:
- Receive requests
- Validate input
- Call services/actions
- Return views or partials

Controllers should not:
- Contain business rules
- Write SQL
- Generate PDFs
- Perform calculations

---

## Services
Responsibilities:
- Business workflows
- Orchestration
- Cross-module operations

Examples:
CreateInvoiceService
ConvertQuotationService
GenerateReportService

---

## Actions
Responsibilities:
Single-purpose operations.

Examples:
CreateCustomerAction
CalculateTotalsAction
GenerateDocumentNumberAction
SendEmailAction

Actions should be small and easily testable.

---

## Repositories
Responsibilities:
Data access abstraction.

Examples:
InvoiceRepository
CustomerRepository
DocumentRepository

Repositories:
- Query data
- Persist data
- Hide SQL details

Business logic should not live here.

---

## Models
Responsibilities:
Represent database entities.

Examples:
User
Company
Customer
Document
DocumentItem

Models should remain lightweight.

---

## DTOs

Purpose:
Transport structured data between layers.

Examples:
DocumentData
InvoiceData
CustomerData

Avoid passing raw request arrays throughout the system.

---

## Middleware

Examples:
Authentication
Authorization
CSRF
Rate limiting
Company context

---

## Components

Reusable UI building blocks.

Examples:
Button
DataTable
Modal
FormField
Pagination
StatusBadge
Card
SearchSelect

Components should remain generic.

---

# BusinessCore Modules

BusinessCore/
├── Auth/
├── Permissions/
├── Users/
├── Companies/
├── Settings/
├── Notifications/
├── Documents/
├── Reports/
└── Shared/

Every future application should reuse these modules.

---

# Naming Conventions

Controllers:
CustomerController
InvoiceController

Services:
CreateInvoiceService
GenerateReportService

Actions:
CreateCustomerAction
CalculateTotalsAction

Repositories:
CustomerRepository
InvoiceRepository

DTOs:
CustomerData
InvoiceData

Models:
Customer
Invoice
Document

---

# Dependency Injection

Prefer constructor injection.

Good:

class InvoiceController
{
    public function __construct(
        private CreateInvoiceService $service
    ) {}
}

Avoid:
- Service locators
- Global state
- Static dependencies where possible

---

# HTMX Conventions

## Full Page Request
Return:
Twig layout + page

## HTMX Request
Return:
Partial HTML only

Example usage:
- Search
- Pagination
- Inline editing
- Modal forms
- Dynamic tables

Prefer HTML over JSON whenever possible.

---

# Twig Conventions

Use:
layouts/
components/
pages/
partials/

Prefer:
Base layout
Reusable partials
Small templates

Avoid:
Large templates with embedded business logic.

---

# Database Principles

Use MariaDB.

Design:
- Normalized tables
- Foreign keys
- Proper indexes
- Soft deletes when appropriate
- Audit columns

Common columns:
id
created_at
updated_at
deleted_at

---

# Multi-Company Strategy

Every business entity should be capable of supporting:

company_id

Examples:
customers
documents
products
users
settings

This allows future multi-company support without major redesign.

---

# Document Engine

Use generic tables.

documents
document_items
document_types

Document types:
Quotation
Invoice
Receipt
Voucher
Delivery Note
Purchase Order
Credit Note
Debit Note

Avoid creating separate tables for every document type.

---

# Permissions Strategy

Entities:
roles
permissions
role_permissions
user_roles

Prefer:
Policy-based authorization.

---

# Component Design Rules

Components should:
- Be generic
- Accept configuration
- Avoid module-specific assumptions

Examples:
DataTable
Modal
FormBuilder
DatePicker
SearchSelect
StatusBadge

---

# Error Handling

Use:
Exceptions
Domain exceptions
Validation exceptions
Centralized error pages

Avoid:
Silent failures
Suppressing exceptions

---

# Logging

Log:
Authentication events
Errors
Failed jobs
Critical business events

Do not log:
Passwords
Sensitive tokens
Private customer information

---

# PDF Strategy

PDF templates:
resources/pdf/

Generate PDFs from:
Twig HTML templates
CSS styles

Documents:
Quotation
Invoice
Receipt
Voucher
Delivery Note

Keep PDF templates reusable.

---

# Performance Guidelines

Prefer:
Server rendering
Partial updates
Simple SQL
Database indexes
Caching when necessary

Avoid:
Large JavaScript bundles
Deep dependency trees
Premature optimization

---

# Future Module Integration

New modules should integrate through BusinessCore.

Example:

crm/
inventory/
school/
erp/
hr/

Each module should:
Reuse authentication
Reuse permissions
Reuse settings
Reuse notifications
Reuse UI components

Never duplicate shared functionality.

---

# Development Rule

When implementing a feature, ask:

1. Can this become a reusable component?
2. Can this become a shared module?
3. Can this design support future applications?
4. Can another system use this code without modification?

If yes, place it inside BusinessCore.
If no, keep it inside the current module.

The codebase should evolve into a reusable business application platform rather than a collection of isolated applications.
