Excluded: .git, node_modules, secrets/, compose.env, assemblyscript tgz Source: /opt/alga-psa on psa.joliet.tech
14 KiB
Credits and Credit Reconciliation System
Table of Contents
- Introduction
- Credit System Architecture
- Credit Reconciliation System
- Reconciliation Resolution Workflow
- User Interface Components
- Technical Implementation
Introduction
The credit system allows companies to maintain prepaid balances that can be applied to invoices. The credit reconciliation system ensures the integrity of these balances by detecting and reporting discrepancies between the expected and actual credit balances, as well as issues with credit tracking entries.
This document provides a comprehensive overview of how credits and credit reconciliation work in the system, including the underlying architecture, reconciliation process, and resolution workflow.
Credit System Architecture
Data Model
The credit system is built around several key data structures:
-
Company Credit Balance: Each company has a
credit_balancefield that stores the total available credit. -
Credit Tracking Entries: The
credit_trackingtable maintains detailed records of all credits, including:- Original amount
- Remaining amount
- Creation date
- Expiration date
- Link to the originating transaction
-
Transactions: The
transactionstable records all credit-related activities with types:credit_issuance: Initial credit creationcredit_issuance_from_negative_invoice: Credits created from negative invoicescredit_application: Credits applied to invoicescredit_adjustment: Adjustments to credit balancescredit_expiration: Credits that have expiredcredit_transfer: Credits transferred between companies
-
Credit Allocations: The
credit_allocationstable links credit applications to specific invoices. -
Credit Reconciliation Reports: The
credit_reconciliation_reportstable stores detected discrepancies.
Credit Creation
Credits can be created through several mechanisms:
-
Prepayment Invoices: The primary method for creating credits is through prepayment invoices. These are special invoices with no billing cycle that represent funds added to a company's account.
// Creating a prepayment invoice const prepaymentInvoice = await createPrepaymentInvoice( companyId, amount, expirationDate // Optional ); // Finalizing the invoice to create the credit await finalizeInvoice(prepaymentInvoice.invoice_id); -
Negative Invoices: When an invoice has a negative balance (e.g., due to refunds or adjustments), it can generate credits.
-
Manual Adjustments: Administrators can manually add credits through credit adjustment transactions.
When credits are created:
- A
credit_issuancetransaction is recorded - A credit tracking entry is created with the full amount as the remaining amount
- The company's credit balance is increased
Credit Application
Credits are applied to invoices during the finalization process:
-
Automatic Application: When an invoice is finalized, available credits are automatically applied up to the invoice total.
-
Manual Application: Credits can also be manually applied to specific invoices.
// Applying credit to an invoice await applyCreditToInvoice(companyId, invoiceId, amount);
The credit application process:
- Retrieves available (non-expired) credit tracking entries
- Prioritizes credits by expiration date (oldest first)
- Creates
credit_applicationandcredit_adjustmenttransactions - Updates the remaining amount in credit tracking entries
- Updates the company's credit balance
- Creates credit allocation records linking transactions to invoices
Credit Expiration
Credits can have expiration dates, after which they are no longer available for use:
-
Expiration Configuration: Companies can configure:
- Whether credits expire (
enable_credit_expiration) - How many days until expiration (
credit_expiration_days) - When to send notifications before expiration (
credit_expiration_notification_days)
- Whether credits expire (
-
Expiration Process:
- Expired credits have their remaining amount set to zero
- A
credit_expirationtransaction is created - The company's credit balance is reduced by the expired amount
-
Scheduled Job: A daily job runs to process expired credits automatically.
Credit Transfers
Credits can be transferred between companies:
- The source company's credit tracking entry is updated to reduce the remaining amount
- A
credit_transfertransaction is created for the source company (negative amount) - The source company's credit balance is reduced
- A new
credit_transfertransaction is created for the target company (positive amount) - The target company's credit balance is increased
- A new credit tracking entry is created for the target company
Credit Reconciliation System
Reconciliation Philosophy
The credit reconciliation system is designed around these key principles:
-
Separation of Detection and Correction: The system detects discrepancies without automatically correcting them, ensuring all financial corrections are explicitly reviewed and approved.
-
Transparency: All discrepancies are reported with detailed information about the expected and actual values.
-
Manual Resolution: Authorized users must manually review and resolve discrepancies, maintaining financial integrity.
-
Comprehensive Audit Trail: All detections and resolutions are logged for accountability.
Types of Discrepancies
The system detects three main types of discrepancies:
-
Credit Balance Discrepancies: Differences between the expected credit balance (calculated from transactions) and the actual credit balance stored in the company record.
-
Missing Credit Tracking Entries: Transactions that should have corresponding credit tracking entries but don't.
-
Inconsistent Remaining Amounts: Credit tracking entries where the remaining amount doesn't match the expected value based on transaction history.
Reconciliation Process
The credit reconciliation process involves these steps:
-
Balance Validation:
- Calculate the expected credit balance by summing all credit-related transactions
- Compare with the actual credit balance in the company record
- Create a reconciliation report if there's a discrepancy
-
Credit Tracking Validation:
- Identify transactions that should have credit tracking entries but don't
- Calculate the expected remaining amount for each credit tracking entry
- Compare with the actual remaining amount
- Create reconciliation reports for any discrepancies
-
Report Creation:
- Store detailed information about each discrepancy
- Include metadata specific to the discrepancy type
- Set the status to 'open'
Scheduled Validation
Credit reconciliation runs automatically through scheduled jobs:
-
Daily Validation: A scheduled job runs daily at 2:00 AM to validate all companies.
-
Company-Specific Validation: Administrators can also trigger validation for specific companies through the UI.
-
Tenant-Aware: The validation process respects tenant boundaries, ensuring data isolation.
Reconciliation Resolution Workflow
Resolution Options
Discrepancies can be resolved through several methods, depending on the type:
-
For Credit Balance Discrepancies:
- Apply the recommended adjustment to match the expected balance
- Apply a custom adjustment amount
- Mark as resolved without action (if determined to be a false positive)
-
For Missing Credit Tracking Entries:
- Create the missing credit tracking entry
- Apply a custom credit adjustment
- Mark as resolved without action
-
For Inconsistent Remaining Amounts:
- Update the remaining amount to match the expected value
- Apply a custom credit adjustment
- Mark as resolved without action
Audit Trail
All reconciliation activities are logged for accountability:
-
Detection Logging: When discrepancies are detected, detailed information is logged.
-
Resolution Logging: When discrepancies are resolved, the resolution method, user, and notes are logged.
-
Transaction Records: All corrections create transaction records for financial traceability.
User Interface Components
Reconciliation Dashboard
The reconciliation dashboard provides an overview of all credit discrepancies:
-
Summary Statistics:
- Total discrepancies
- Total discrepancy amount
- Open issues count
-
Filtering Options:
- By company
- By status (open, in review, resolved)
- By date range
-
Tabular View:
- Company name
- Discrepancy amount
- Detection date
- Status
- Expected and actual balances
- Action buttons
-
Company-Specific Reconciliation:
- Dropdown to select a company
- Button to run reconciliation for the selected company
Discrepancy Detail View
The discrepancy detail view provides comprehensive information about a specific discrepancy:
-
Basic Information:
- Company details
- Discrepancy amount
- Detection date
- Status
-
Balance Comparison:
- Expected balance
- Actual balance
- Difference
-
Related Data:
- Transaction history
- Credit tracking entries
- Issue-specific details
-
Recommended Fix Panel:
- Suggested resolution options
- Impact summary
- Resolution form
Resolution Workflow
The resolution workflow guides users through the process of resolving discrepancies:
-
Fix Selection:
- Recommended fix based on discrepancy type
- Alternative fix options
- Option to mark as resolved without action
-
Resolution Form:
- Notes field for explaining the resolution
- Custom amount field for custom adjustments
- Impact summary showing the effect of the resolution
-
Confirmation:
- Review of the resolution details
- Final confirmation before applying the fix
Technical Implementation
Server Actions
The credit reconciliation system is implemented through several server actions:
-
Validation Actions:
validateCreditBalanceWithoutCorrection(): Validates credit balance without making correctionsvalidateCreditTrackingEntries(): Validates credit tracking entriesvalidateCreditTrackingRemainingAmounts(): Validates remaining amountsvalidateAllCreditTracking(): Runs both tracking validationsrunScheduledCreditBalanceValidation(): Runs validation for all companies or a specific company
-
Resolution Actions:
resolveReconciliationReport(): Resolves a reconciliation reportcreateMissingCreditTrackingEntry(): Creates a missing credit tracking entryupdateCreditTrackingRemainingAmount(): Updates a credit tracking entry's remaining amountapplyCustomCreditAdjustment(): Applies a custom credit adjustmentmarkReportAsResolvedNoAction(): Marks a report as resolved without action
-
Reporting Actions:
fetchReconciliationReports(): Retrieves reconciliation reports with filteringfetchReconciliationStats(): Retrieves summary statistics
Scheduled Jobs
The credit reconciliation system uses scheduled jobs for automation:
-
Credit Reconciliation Job:
- Runs daily at 2:00 AM
- Validates all companies in a tenant
- Creates reconciliation reports for any discrepancies
-
Expired Credits Job:
- Runs daily at 1:00 AM
- Processes expired credits
- Updates credit tracking entries and company balances
-
Expiring Credits Notification Job:
- Runs daily at 9:00 AM
- Sends notifications about credits that will expire soon
Database Schema
The credit reconciliation system uses these key database tables:
-
credit_reconciliation_reports:
report_id: Unique identifiercompany_id: The company with the discrepancyexpected_balance: The calculated correct balanceactual_balance: The stored balancedifference: The discrepancy amountdetection_date: When the discrepancy was detectedstatus: open, in_review, or resolvedresolution_date: When the discrepancy was resolvedresolution_user: Who resolved the discrepancyresolution_notes: Notes explaining the resolutionresolution_transaction_id: The transaction that resolved the discrepancymetadata: Additional information specific to the discrepancy type
-
transactions:
- Records all credit-related activities
- Includes credit adjustments from reconciliation resolutions
-
credit_tracking:
- Stores detailed information about each credit
- Updated during reconciliation resolution