# **Cobranza App – Data Model Brief**

## **1. General Information**

The system is a multi-tenant SaaS designed to help companies (Companies) manage debts, invoices, and payment reconciliation with their end clients (Clients).

The data model is built around **clear separation of concerns**:

- **Core business entities** (Debt, Client, Payment)
- **Process intermediaries** (PaymentAttempt, PaymentProof, PaymentMatch)
- **Configuration & Templates** (InvoiceTemplate, ReceiptTemplate, NotificationTemplate)
- **Automation & Reconciliation** (DebtSchedule, BankStatement, BankTransaction)

All main entities are scoped to a `company_id` (multi-tenancy). The model supports both manual and semi-automated payment reconciliation workflows.

## **2. Entity Definitions & Roles**

- **Company**: The main tenant / customer of the SaaS. Represents the business that uses the platform to manage its debtors.

- **CompanyPlan**: Defines the commercial agreement with the Company (commission rates, SaaS percentage, currency, validity period).

- **User**: Any person with an account in the system (Company staff or future authenticated end users).

- **CompanyUser**: Junction table that assigns Users to a Company with a specific Role (admin, operator, etc.).

- **Client**: End customer / debtor of a Company. The person or business that owes money.

- **Debt**: A concrete, individual debt assigned to a Client. It has an amount, due date, and status. This is the central business object.

- **DebtSchedule**: Recurring debt configuration. Allows automatic generation of Debts on a schedule (monthly, weekly, etc.).

- **Invoice**: Formal document (pagaré / bill) generated from a Debt. Visible to the Client.

- **InvoiceTemplate**: Configurable HTML template used to generate Invoices for a Company.

- **PaymentProof**: File (photo/PDF) uploaded by the Client as proof of payment.

- **PaymentAttempt**: Intermediate entity representing a payment upload that is being processed/validated. Bridges the gap between the uploaded proof and final confirmation.

- **Payment**: Confirmed and definitive payment record. Applied against a specific Debt. This is the single source of truth for accounting.

- **Receipt**: Official receipt generated by the system when a Payment is confirmed.

- **ReceiptTemplate**: Configurable template used to generate Receipts.

- **BankStatement**: Bank statement file uploaded by the Company for reconciliation.

- **BankTransaction**: Individual transaction parsed from a BankStatement.

- **PaymentMatch**: Record of a successful match between a PaymentAttempt and a BankTransaction.

- **Notification / NotificationTemplate**: System messages sent to Clients or Company Users.

- **ClientDebtSummary**: Summary table (can be a materialized view) with current balance per Client.

- **CompanyMonthlySummary**: Monthly aggregation used for billing the Company (commissions).
- **Optionality (Task 5):** `Company.contact`, `Client.fullName`, and
  `Debt.description` are optional fields (nullable where applicable).

## **2.x Standard Audit Fields (`BaseEntity`)**

Every entity in the model extends the `BaseEntity` interface defined in
`src/interfaces/base-entity.interface.ts`. The library inherits these fields on all
entities; they are not redeclared per entity:

| Field         | Type | Required | Purpose                                  |
|---------------|------|----------|------------------------------------------|
| `id`          | UUID | Yes      | Primary key (persistence-assigned)        |
| `createdAt`   | Date | Yes      | Creation timestamp                        |
| `createdBy`   | UUID | Yes      | UUID of the creating user                 |
| `updatedAt`   | Date | No       | Last update timestamp (null until updated) |
| `updatedBy`   | UUID | No       | UUID of the last modifying user            |
| `deletedAt`   | Date | No       | Soft-delete marker                         |
| `deletedBy`   | UUID | No       | UUID of the user who soft-deleted          |

> Some entities previously lacked `createdAt` / `createdBy` (e.g. `PaymentMatch`,
> `ClientDebtSummary`) — these are now required per `BaseEntity`. Consumers that
> generate these entities must supply `createdBy`; persistence layers supply `id`
> and `createdAt`.

## **3. Main System Flows**

### **Flow 1: Creating Recurring Debt → Invoice**

1. Company User creates a **DebtSchedule** for a Client (e.g., monthly fee of $15,000 ARS, every 5th of the month).
2. The system automatically generates a new **Debt** on the scheduled date.
3. When the Client accesses their portal, the system generates an **Invoice** on-the-fly using the assigned **InvoiceTemplate**.
4. The Client can view and download the Invoice with the Company’s branding and custom text.

**Example**:  
A accountant creates a DebtSchedule “Monthly Retainer” for Client “Juan Pérez”. On the 1st of each month, a Debt is generated → Client sees a professional Invoice.

### **Flow 2: Client Uploads Payment Proof → Confirmation**

1. Client uploads a payment proof (photo or PDF) → **PaymentProof** is created.
2. System creates a **PaymentAttempt** linked to the chosen Debt/Invoice.
3. System attempts to parse the file (OCR / text extraction).
   - If successful → populates amount & currency.
   - If fails → status = `PARSE_FAILED`.
4. The PaymentAttempt goes into `PENDING_VALIDATION`.
5. Company User can review manually and **APPROVE** or **REJECT**, or the system can auto-approve via bank matching.
6. On approval → **Payment** is created (definitive record).
7. System generates a **Receipt** using the **ReceiptTemplate** and sends it to the Client.

### **Flow 3: Bank Reconciliation Flow**

1. Company User uploads a bank statement → **BankStatement** is created (with selected `bank` and `format`).
2. System processes the file and creates multiple **BankTransaction** records.
3. The reconciliation engine tries to match **BankTransactions** with existing **PaymentAttempts** (by amount, reference, date, client detection, etc.).
4. Successful matches create a **PaymentMatch** record.
5. Matched PaymentAttempts are automatically moved to `APPROVED` and generate a **Payment**.

This enables semi-automatic reconciliation.

### **Flow 4: Receipt Generation**

When a **Payment** is confirmed (either manually or via matching):

- System creates a **Receipt** record.
- Uses the Company’s active **ReceiptTemplate** to generate a professional document (PDF).
- The receipt is made available for download by the Client and optionally sent via email/WhatsApp.
