# EasyCash Backend - AI Development Guide

## Project Overview

EasyCash is a SaaS backend for projected and executed cash flow management.

The backend is built with PHP 8.x, Slim 4, MySQL/MariaDB, PDO, Phinx migrations, JWT authentication and OpenAPI documentation.

The system must always respect multi-tenant isolation by organization and financial unit.

## Current Stack

* PHP 8.x
* Slim 4
* MySQL / MariaDB
* PDO
* Phinx migrations
* JWT authentication
* Refresh token via secure cookie
* OpenAPI 3.1
* Swagger UI
* Apache / XAMPP local environment

## Local Project Path

```txt
D:\reactProjects\easycash\backend
```

## Architecture Rules

The project follows a layered architecture:

* Routes define HTTP endpoints.
* Actions handle HTTP request and response.
* Validators validate input and business rules.
* Services handle business logic.
* Repositories handle database access.
* Domain entities represent business data.
* Middleware handles authentication, authorization and request concerns.

Do not place SQL queries directly inside Actions.

Do not place complex business logic directly inside Routes.

Do not bypass Validators when creating or updating business entities.

## Important Folders

Common structure:

```txt
src/
  Application/
  Domain/
  Infrastructure/
config/
db/
  migrations/
public/
  openapi.yaml
```

## Global Business Rules

* Always enforce organization isolation.
* Always enforce financial unit isolation when applicable.
* Never expose data from another organization.
* Validate ownership of related entities before saving.
* Use soft delete where the module already uses soft delete.
* Use audit log for create, update, delete and status changes when applicable.
* Return consistent JSON error responses.
* Use 422 for validation errors.
* Use 404 for not found resources.
* Use 409 for conflict errors.
* Use 401 for authentication errors.
* Use 403 for permission errors.

## Authentication and Permissions

The project uses JWT authentication and permissions.

Before adding a new endpoint:

1. Define the required permission.
2. Register the route.
3. Validate authorization.
4. Test access with authorized and unauthorized users.

## Projected Movements Rules

Projected movements are generated from income contracts and expense obligations.

Important rules:

* Pending projected movements may be regenerated only when critical fields change.
* Non-critical updates must not regenerate projected movements.
* Cancelled or executed movements must not be incorrectly overwritten.
* Each generated movement must be linked to its source entity.
* Frequency calculations must be centralized.
* Date ranges must be validated before generation.

## Income Contracts Rules

Income contracts generate projected income movements.

Already completed in Phase 2.1.

Main concepts:

* amount_type: fixed or variable
* frequency
* start_date
* end_date
* customer
* category
* bank account
* responsible_user_id
* projected movements summary

## Expense Obligations Rules

Expense obligations generate projected expense movements.

Completed test suite: 24/24 tests passed.

Main concepts:

* obligation_name
* supplier_id
* category_id
* payment_bank_account_id
* amount_type
* base_amount
* frequency
* start_date
* end_date
* projected movements summary
* regeneration control when critical fields change

Expense category must be type expense.

Related entities must belong to the same organization and financial unit.

## Testing Rules

Before approving a phase:

1. Run all planned test cases.
2. Verify happy paths.
3. Verify validation errors.
4. Verify tenant isolation.
5. Verify permission handling.
6. Verify not found cases.
7. Verify soft delete behavior.
8. Verify audit log where applicable.
9. Verify OpenAPI documentation.
10. Verify no sensitive files are committed.

## OpenAPI Rules

Whenever an endpoint changes, update:

```txt
public/openapi.yaml
```

OpenAPI must reflect:

* Path
* Method
* Request body
* Query params
* Path params
* Response codes
* Validation errors
* Authentication requirements

## Database Rules

Use Phinx migrations.

Do not manually alter production database structure without a migration.

When adding fields:

1. Create migration.
2. Add indexes when useful.
3. Define foreign keys carefully.
4. Validate delete behavior.
5. Update repositories.
6. Update tests.

## Code Style Preferences

* Keep code explicit and readable.
* Prefer robust solutions over quick hacks.
* Keep validation messages clear.
* Avoid over-engineering when a simpler structure works.
* Follow existing project patterns before introducing new ones.
* Do not rename existing structures without strong reason.

## Current Approved Phases

* Phase 0: Base, Auth, Docs and Health - Complete
* Phase 1.1: Organizations, Roles and Permissions - Complete
* Phase 1.2: User Management - Complete
* Phase 1.3: Financial Units and Bank Accounts - Complete
* Phase 1.4: Categories, Customers and Suppliers - Complete
* Phase 2.1: Income Contracts - Complete
* Phase 2.2: Expense Obligations - Complete
* Phase 2.3–2.6: Frequency Engine and Movement Generation - Complete
* Phase 3.1–3.5: Projected Movements Engine - Complete
* Phase 4.1–4.6: Execution Engine - Complete
* Phase 5.1: Dashboard Financial API - Complete
* Phase 5.2: Frontend MVP (login + layout + dashboard) - Complete
* Phase 5.3: Frontend Movimientos Proyectados Visuales - Complete
* Phase 5.4: Frontend — acciones sobre movimientos (ejecutar, editar, cancelar) - Complete
* Phase 5.5: Frontend — contratos de ingreso - Complete
* Phase 5.6: Frontend — clientes y proveedores - Complete
* Phase 5.7: Frontend — proveedores y obligaciones de gasto - Complete
* Phase 5.8: Frontend — unidades financieras y cuentas bancarias - Complete
* Phase 5.9: Frontend — calendario de flujo de caja - Complete
* Phase 5.10: Frontend — dashboard ejecutivo (vista de liquidez) - Complete
* Fase 6.1: Frontend — cobranza y pagos (vista operativa) - Completa
* Fase 6.2: Frontend — cuentas por cobrar / cuentas por pagar (dashboard analítico con aging) - Completa
* Fase 6.3: Frontend — acciones rápidas de contacto (WhatsApp y llamar) - Completa
* Fase 6.4: Frontend — alertas en tiempo real (liquidez, vencidos, saldos, próximos vencimientos) - Completa
* Fase 7.1: Reprogramaciones — historial con tabla reschedules, endpoint dedicado y auditoría - Completa

## Próxima Fase Planificada

Fase 7.2: Sugerencia automática de nueva fecha de reprogramación.

## AI Instructions

When helping with this project:

* First inspect this file.
* Then inspect PROJECT_STATUS.md.
* Then inspect relevant code files only.
* Avoid reading the whole project unless necessary.
* Prefer targeted changes.
* Explain which files need to change before changing them.
* Keep changes consistent with previous phases.
* Do not invent new architecture if an existing pattern already exists.
* Do not approve a phase without tests and documentation review.

## graphify

This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.

Rules:
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
