> For the complete documentation index, see [llms.txt](https://qbits-organization.gitbook.io/buildwise-doc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://qbits-organization.gitbook.io/buildwise-doc/accounting/transaction.md).

# Transaction

The Transaction API provides endpoints for managing accounting transactions in the BuildWise system. It supports various transaction types including simple transactions, invoices, expenses, and direct

### Create Simple Transaction

Creates a simple transaction with a single debit and credit entry. This is the most common type of construction transaction.

#### Endpoint

```
POST /api/v1/accounting/transactions/simple
```

#### Request Body

```json
{
  "organisationId": "123e4567-e89b-12d3-a456-426614174000",
  "projectId": "456e7890-e89b-12d3-a456-426614174001",
  "debitAccountId": "789e0123-e89b-12d3-a456-426614174002",
  "creditAccountId": "012e3456-e89b-12d3-a456-426614174003",
  "amount": 1500.00,
  "description": "Payment for construction materials",
  "referenceNumber": "REF-2025-001"
}
```

#### Validation Rules

* **organisationId**: Required, must be a valid UUID
* **debitAccountId**: Required, must be a valid account ID
* **creditAccountId**: Required, must be a valid account ID
* **amount**: Required, must be greater than 0
* **description**: Required, cannot be blank
* **projectId**: Optional, must be a valid project ID if provided
* **referenceNumber**: Optional

#### Success Response

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Simple transaction created successfully",
  "action_time": "2025-06-14T10:30:15.123456",
  "data": {
    "journalEntryId": "345e6789-e89b-12d3-a456-426614174004",
    "description": "Payment for construction materials",
    "referenceNumber": "REF-2025-001",
    "transactionDateTime": "2025-06-14T10:30:15.123456",
    "organisationId": "123e4567-e89b-12d3-a456-426614174000",
    "projectId": "456e7890-e89b-12d3-a456-426614174001",
    "projectName": "Office Building Construction",
    "transactionLevel": "PROJECT",
    "lineCount": 2,
    "totalAmount": 1500.00
  }
}
```

#### Error Responses

* **400** - Missing required fields, invalid data, or account validation errors
* **401** - Unauthorized (invalid token)
* **404** - Organisation, project, or accounts not found
* **500** - An unexpected error occurred while processing the transaction

***

### Create Invoice Transaction

Creates an invoice transaction for customer billing with support for multiple line items and tax calculations.

#### Endpoint

```
POST /api/v1/accounting/transactions/invoice
```

#### Request Body

```json
{
  "organisationId": "123e4567-e89b-12d3-a456-426614174000",
  "projectId": "456e7890-e89b-12d3-a456-426614174001",
  "customerId": "678e9012-e89b-12d3-a456-426614174005",
  "totalAmount": 5000.00,
  "taxAmount": 500.00,
  "description": "Monthly construction progress billing",
  "referenceNumber": "INV-2025-001",
  "lineItems": [
    {
      "description": "Foundation work",
      "amount": 3000.00,
      "accountId": "789e0123-e89b-12d3-a456-426614174006"
    },
    {
      "description": "Materials",
      "amount": 2000.00,
      "accountId": "890e1234-e89b-12d3-a456-426614174007"
    }
  ]
}
```

#### Validation Rules

* **organisationId**: Required, must be a valid UUID
* **customerId**: Required, must be a valid customer ID
* **totalAmount**: Required, must be greater than 0
* **taxAmount**: Optional, must be non-negative if provided
* **description**: Required, cannot be blank
* **lineItems**: Optional, array of invoice line items
* **projectId**: Optional, must be a valid project ID if provided
* **referenceNumber**: Optional

#### Success Response

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Invoice transaction created successfully",
  "action_time": "2025-06-14T11:15:30.654321",
  "data": {
    "journalEntryId": "567e8901-e89b-12d3-a456-426614174008",
    "description": "Monthly construction progress billing",
    "referenceNumber": "INV-2025-001",
    "transactionDateTime": "2025-06-14T11:15:30.654321",
    "organisationId": "123e4567-e89b-12d3-a456-426614174000",
    "projectId": "456e7890-e89b-12d3-a456-426614174001",
    "projectName": "Office Building Construction",
    "transactionLevel": "PROJECT",
    "lineCount": 3,
    "totalAmount": 5000.00
  }
}
```

#### Error Responses

* **400** - Missing required fields, invalid data, or line item validation errors
* **401** - Unauthorized (invalid token)
* **404** - Organisation, project, customer, or accounts not found
* **500** - An unexpected error occurred while processing the invoice

***

### Create Expense Transaction

Creates an expense transaction for business expenses with vendor tracking and support for both paid and unpaid expenses.

#### Endpoint

```
POST /api/v1/accounting/transactions/expense
```

#### Request Body

```json
{
  "organisationId": "123e4567-e89b-12d3-a456-426614174000",
  "projectId": "456e7890-e89b-12d3-a456-426614174001",
  "vendorId": "789e0123-e89b-12d3-a456-426614174009",
  "expenseAccountId": "890e1234-e89b-12d3-a456-426614174010",
  "amount": 750.00,
  "category": "MATERIALS",
  "paid": true,
  "description": "Steel reinforcement bars",
  "referenceNumber": "EXP-2025-001"
}
```

#### Validation Rules

* **organisationId**: Required, must be a valid UUID
* **amount**: Required, must be greater than 0
* **description**: Required, cannot be blank
* **paid**: Required, boolean indicating if expense is paid
* **vendorId**: Optional, must be a valid vendor ID if provided
* **expenseAccountId**: Optional, system will use default expense account if not provided
* **category**: Optional, expense category for reporting
* **projectId**: Optional, must be a valid project ID if provided
* **referenceNumber**: Optional

#### Success Response

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Expense transaction created successfully",
  "action_time": "2025-06-14T12:45:20.987654",
  "data": {
    "journalEntryId": "012e3456-e89b-12d3-a456-426614174011",
    "description": "Steel reinforcement bars",
    "referenceNumber": "EXP-2025-001",
    "transactionDateTime": "2025-06-14T12:45:20.987654",
    "organisationId": "123e4567-e89b-12d3-a456-426614174000",
    "projectId": "456e7890-e89b-12d3-a456-426614174001",
    "projectName": "Office Building Construction",
    "transactionLevel": "PROJECT",
    "lineCount": 2,
    "totalAmount": 750.00
  }
}
```

#### Error Responses

* **400** - Missing required fields, invalid data, or account validation errors
* **401** - Unauthorized (invalid token)
* **404** - Organisation, project, vendor, or accounts not found
* **500** - An unexpected error occurred while processing the expense

***

### Create Direct Journal Entry

Creates a direct journal entry for advanced users or system integrations. This bypasses business event processing and creates journal entries directly.

#### Endpoint

```
POST /api/v1/accounting/transactions/journal-entry
```

#### Request Body

```json
{
  "organisationId": "123e4567-e89b-12d3-a456-426614174000",
  "projectId": "456e7890-e89b-12d3-a456-426614174001",
  "description": "Manual adjustment for equipment depreciation",
  "referenceNumber": "JE-2025-001",
  "transactionDateTime": "2025-06-14T13:30:00.000000",
  "lineCount": 2,
  "journalEntryLines": [
    {
      "accountId": "234e5678-e89b-12d3-a456-426614174012",
      "debitAmount": 1000.00,
      "creditAmount": null,
      "description": "Depreciation expense"
    },
    {
      "accountId": "345e6789-e89b-12d3-a456-426614174013",
      "debitAmount": null,
      "creditAmount": 1000.00,
      "description": "Accumulated depreciation"
    }
  ]
}
```

#### Validation Rules

* **organisationId**: Required, must be a valid UUID
* **description**: Required, cannot be blank
* **journalEntryLines**: Required, must have at least 2 lines
* **lineCount**: Required, must match the number of journal entry lines
* **accountId**: Required for each line, must be valid account IDs
* **debitAmount/creditAmount**: One must be provided per line, both cannot be null or both cannot have values
* **Total debits must equal total credits**
* **projectId**: Optional, must be a valid project ID if provided
* **referenceNumber**: Optional
* **transactionDateTime**: Optional, defaults to current time

#### Success Response

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Journal entry created successfully",
  "action_time": "2025-06-14T13:30:15.456789",
  "data": {
    "journalEntryId": "456e7890-e89b-12d3-a456-426614174014",
    "description": "Manual adjustment for equipment depreciation",
    "referenceNumber": "JE-2025-001",
    "transactionDateTime": "2025-06-14T13:30:00.000000",
    "organisationId": "123e4567-e89b-12d3-a456-426614174000",
    "projectId": "456e7890-e89b-12d3-a456-426614174001",
    "projectName": "Office Building Construction",
    "transactionLevel": "PROJECT",
    "lineCount": 2,
    "totalAmount": 1000.00
  }
}
```

#### Error Responses

* **400** - Missing required fields, invalid data, unbalanced entries, or account validation errors
* **401** - Unauthorized (invalid token)
* **404** - Organisation, project, or accounts not found
* **500** - An unexpected error occurred while creating the journal entry

***

### Approve Transaction

Approves a transaction that requires management approval. This updates the transaction status and records the approval details.

#### Endpoint

```
POST /api/v1/accounting/transactions/{journalEntryId}/approve
```

#### Path Parameters

* **journalEntryId** (UUID) - The journal entry identifier to approve

#### Request Body

```json
{
  "approverId": "567e8901-e89b-12d3-a456-426614174015",
  "comments": "Approved - all documentation verified"
}
```

#### Validation Rules

* **journalEntryId**: Required, must be a valid journal entry ID
* **approverId**: Required, must be a valid user ID with approval permissions
* **Comments**: Optional, approval comments
* **Transaction must be in pending approval status**
* **User** must have OWNER or ADMIN role

#### Success Response

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Transaction approved successfully",
  "action_time": "2025-06-14T14:20:45.321098",
  "data": {
    "journalEntryId": "456e7890-e89b-12d3-a456-426614174014",
    "description": "Manual adjustment for equipment depreciation",
    "referenceNumber": "JE-2025-001",
    "transactionDateTime": "2025-06-14T13:30:00.000000",
    "organisationId": "123e4567-e89b-12d3-a456-426614174000",
    "projectId": "456e7890-e89b-12d3-a456-426614174001",
    "projectName": "Office Building Construction",
    "transactionLevel": "APPROVED",
    "lineCount": 2,
    "totalAmount": 1000.00
  }
}
```

#### Error Responses

* **400** - Invalid approval request or transaction not eligible for approval
* **401** - Unauthorized (invalid token)
* **403** - Access denied (insufficient permissions)
* **404** - Transaction not found
* **500** - An unexpected error occurred while approving the transaction

***

### Authentication & Authorization

#### General Rules

* All endpoints require authentication via a JWT token
* Users must be active members of the relevant organisation
* Transaction creation requires appropriate permissions based on transaction type and amount
* Transaction approval requires OWNER or ADMIN role
* System automatically determines account assignments using intelligent lookup service

#### Account Lookup Service

The system includes an intelligent account lookup service that automatically assigns appropriate accounts based on:

* **Cash Account**: Looks for accounts with codes 1010, 1020 or names containing "cash", "operating", "project funds"
* **Accounts Receivable**: Looks for account code 1100 or names containing "receivable", "accounts receivable", "a/r"
* **Accounts Payable**: Looks for account code 2010 or names containing "payable", "accounts payable", "a/p"
* **Tax Payable**: Looks for names containing "tax", "vat", "sales tax", "tax payable"
* **Default Revenue**: Looks for account code 4000 or names containing "construction revenue", "revenue", "sales"
* **Default Expense**: Looks for account codes 5000, 5010 or names containing "materials", "direct costs", "expense"

#### Common Error Responses

All endpoints may return:

* **401 Unauthorized** - Invalid or missing authentication token
* **500 Internal Server Error** - Unexpected server error

***

### Response Format

All successful responses follow this structure:

```json
{
  "success": true,
  "httpStatus": "OK",
  "message": "Description of the operation",
  "action_time": "2025-06-14T15:45:30.123456",
  "data": { /* Response data or null */ }
}
```

***

### Additional Notes

#### Transaction Types

The system supports several transaction types:

* **Simple Transaction**: Basic debit/credit entries
* **Invoice Transaction**: Customer billing with line items and tax support
* **Expense Transaction**: Vendor expenses with payment tracking
* **Journal Entry**: Direct accounting entries for advanced users

#### Transaction Levels

Transactions can be processed at different levels:

* **ORGANISATION**: Organisation-wide transactions
* **PROJECT**: Project-specific transactions
* **PENDING\_APPROVAL**: Transactions requiring approval
* **APPROVED**: Approved transactions

#### Business Event Processing

Most transactions are processed through business events that:

* Validate transaction data
* Perform automatic account lookups
* Apply business rules
* Create journal entries
* Handle approval workflows
* Generate audit trails

#### Automatic Account Assignment

When account IDs are not explicitly provided, the system uses intelligent lookup to assign appropriate accounts based on:

* Account codes (following standard accounting conventions)
* Account names (keyword matching)
* Account types (Asset, Liability, Revenue, Expense)
* Fallback to the first available account of the correct type
