PHP code example of azaharizaman / nexus-receivable

1. Go to this page and download the library: Download azaharizaman/nexus-receivable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azaharizaman / nexus-receivable example snippets


use Nexus\Receivable\Services\PaymentAllocation\FifoStrategy;

$strategy = new FifoStrategy();
$allocations = $strategy->allocate($paymentAmount, $openInvoices);

// Result: {'invoice-001' => 500.00, 'invoice-002' => 500.00}

use Nexus\Receivable\Services\PaymentAllocation\ProportionalStrategy;

$strategy = new ProportionalStrategy();
$allocations = $strategy->allocate(1000.00, $openInvoices);

// If invoices: $600, $300, $300
// Result: {'inv-1' => 500.00, 'inv-2' => 250.00, 'inv-3' => 250.00}

use Nexus\Receivable\Services\PaymentAllocation\ManualStrategy;

$strategy = new ManualStrategy([
    'invoice-001' => 750.00,
    'invoice-002' => 250.00,
]);

$customer->setPaymentAllocationPreference('fifo'); // or 'proportional', 'manual'

use Nexus\Receivable\Contracts\CreditLimitCheckerInterface;

$creditChecker = app(CreditLimitCheckerInterface::class);

try {
    $creditChecker->checkCreditLimit(
        tenantId: $tenantId,
        customerId: $customerId,
        orderTotal: 5000.00,
        currencyCode: 'MYR'
    );
    
    // ✅ Credit approved - proceed with order
    
} catch (CreditLimitExceededException $e) {
    // ❌ Credit limit exceeded
    // Message: "Credit limit exceeded for customer X. 
    //          Credit limit: 10000.00, Current balance: 8000.00, 
    //          Requested: 5000.00, Projected: 13000.00"
}

$creditChecker->checkGroupCreditLimit(
    tenantId: $tenantId,
    groupId: 'megacorp-group',
    orderTotal: 50000.00
);

// In Sales package
$this->creditLimitChecker->checkCreditLimit($tenantId, $customerId, $orderTotal, $currency);

use Nexus\Receivable\Contracts\DunningManagerInterface;

$dunningManager = app(DunningManagerInterface::class);

// Process all overdue invoices
$noticesSent = $dunningManager->processOverdueInvoices(
    tenantId: $tenantId,
    asOfDate: new \DateTimeImmutable('2025-11-21')
);

// Send specific notice
$dunningManager->sendDunningNotice(
    customerId: $customerId,
    escalationLevel: 'second_reminder'
);

// Trigger workflow for 30-day overdue
$workflowEngine->startProcess('dunning_escalation', [
    'customer_id' => $customerId,
    'escalation_level' => 'final_notice',
    'invoices' => $overdueInvoices,
]);

$paymentData = [
    'customer_id' => $customerId,
    'amount' => 4500.00,
    'currency' => 'MYR',
    'payment_method' => 'bank_transfer',
    'invoice_allocations' => [
        'invoice-usd-001' => 1000.00, // Invoice amount in USD
    ],
];

$receipt = $receivableManager->recordPayment($tenantId, $paymentData);

payment_receipts:
    amount: 4500.00                    // Original payment amount
    currency: 'MYR'                    // Payment currency
    amount_in_invoice_currency: 1000.00 // Converted amount
    exchange_rate: 4.50                // Rate used

$fxGainLoss = $paymentProcessor->calculateFxGainLoss(
    paymentAmount: 4500.00,
    paymentCurrency: 'MYR',
    invoiceAmount: 1000.00,
    invoiceCurrency: 'USD',
    exchangeRate: 4.50
);
// Result: 0.00 (no gain/loss if rate matches perfectly)

$exchangeRate = $currencyManager->getExchangeRate(
    fromCurrency: 'MYR',
    toCurrency: 'USD',
    asOfDate: $paymentDate
);

// Sales package publishes event
$this->auditLogger->log($orderId, 'order_fulfilled', '...');

// Receivable listens and creates invoice
$invoice = $receivableManager->createInvoiceFromOrder($tenantId, $salesOrderId);

// In SalesOrderManager::confirmOrder()
$this->creditLimitChecker->checkCreditLimit($tenantId, $customerId, $total, $currency);

$journalId = $financeManager->postJournal(
    tenantId: $tenantId,
    journalDate: $invoiceDate,
    description: "Customer invoice {$invoiceNumber}",
    lines: [
        ['account' => '1200', 'debit' => 1000.00, 'credit' => 0.00], // AR Control
        ['account' => '4100', 'debit' => 0.00, 'credit' => 1000.00], // Revenue
    ]
);

$journalId = $financeManager->postJournal(
    tenantId: $tenantId,
    journalDate: $paymentDate,
    description: "Payment receipt {$receiptNumber}",
    lines: [
        ['account' => '1000', 'debit' => 1000.00, 'credit' => 0.00], // Cash
        ['account' => '1200', 'debit' => 0.00, 'credit' => 1000.00], // AR Control
    ]
);

$journalId = $receivableManager->writeOffInvoice($invoiceId, 'Customer bankruptcy');

// Creates:
// Debit:  Bad Debt Expense (6100)  1,000.00
// Credit: AR Control (1200)        1,000.00

$customer = $partyManager->getParty($customerId);
$creditLimit = $customer->getCreditLimit();
$groupId = $customer->getCustomerGroupId();

$notifier->send(
    channel: 'email',
    recipient: $customer->getEmail(),
    template: 'dunning.first_reminder',
    variables: [
        'customer_name' => $customer->getName(),
        'invoice_number' => $invoice->getInvoiceNumber(),
        'days_overdue' => $invoice->getDaysPastDue(new \DateTimeImmutable()),
        'amount_due' => $invoice->getOutstandingBalance(),
    ]
);

$workflowEngine->startProcess('dunning_cycle', [
    'customer_id' => $customerId,
    'escalation_level' => $dunningManager->getEscalationLevel($daysOverdue),
    'invoices' => $overdueInvoices,
]);

$auditLogger->log(
    entity: 'customer_invoice',
    entityId: $invoiceId,
    action: 'posted_to_gl',
    tenantId: $tenantId,
    metadata: ['gl_journal_id' => $journalId]
);

// config/eventstream.php
'critical_domains' => [
    'receivable' => env('EVENTSTREAM_RECEIVABLE_ENABLED', false),
],

// If enabled, publish events:
$eventStore->append($aggregateId, new InvoiceGeneratedFromOrderEvent(...));
$eventStore->append($aggregateId, new PaymentReceivedEvent(...));
$eventStore->append($aggregateId, new PaymentAppliedEvent(...));

use Nexus\Receivable\Contracts\ReceivableManagerInterface;

$receivableManager = app(ReceivableManagerInterface::class);

$invoice = $receivableManager->createInvoiceFromOrder(
    tenantId: $tenantId,
    salesOrderId: $salesOrderId,
    overrides: [
        'description' => 'Custom invoice description',
    ]
);

// Invoice status: DRAFT

// Approve
$invoice = $receivableManager->approveInvoice(
    invoiceId: $invoice->getId(),
    approvedBy: $userId
);

// Invoice status: APPROVED

// Post to GL (Revenue Recognition)
$glJournalId = $receivableManager->postInvoiceToGL($invoice->getId());

// Invoice status: POSTED
// GL Entry created: Debit AR / Credit Revenue

// Record payment
$payment = $receivableManager->recordPayment(
    tenantId: $tenantId,
    paymentData: [
        'customer_id' => $customerId,
        'amount' => 1000.00,
        'currency' => 'MYR',
        'payment_method' => 'bank_transfer',
        'receipt_date' => '2025-11-21',
        'reference' => 'TXN12345',
    ]
);

// Apply to invoices (FIFO automatic)
$payment = $receivableManager->applyPayment(
    receiptId: $payment->getId(),
    allocations: [] // Empty = auto-allocate using FIFO
);

// Or manual allocation
$payment = $receivableManager->applyPayment(
    receiptId: $payment->getId(),
    allocations: [
        'invoice-001' => 600.00,
        'invoice-002' => 400.00,
    ]
);

use Nexus\Receivable\Contracts\UnappliedCashManagerInterface;

$unappliedManager = app(UnappliedCashManagerInterface::class);

// Customer pays before invoice created
$unappliedCash = $unappliedManager->recordUnappliedCash(
    tenantId: $tenantId,
    customerId: $customerId,
    receiptId: $receiptId,
    amount: 5000.00,
    currency: 'MYR'
);

// GL Entry: Debit Cash / Credit Unapplied Revenue (Liability)

// Later, when invoice created
$unappliedManager->applyToInvoice(
    unappliedCashId: $unappliedCash->getId(),
    invoiceId: $newInvoice->getId()
);

// GL Entry reverses liability and applies to invoice

use Nexus\Receivable\Contracts\AgingCalculatorInterface;

$agingCalculator = app(AgingCalculatorInterface::class);

$agingReport = $agingCalculator->calculateAgingReport(
    tenantId: $tenantId,
    asOfDate: new \DateTimeImmutable('2025-11-21')
);

// Result:
[
    [
        'customer_id' => 'cust-001',
        'customer_name' => 'ABC Corp',
        'current' => 5000.00,
        '1_30' => 2000.00,
        '31_60' => 1000.00,
        '61_90' => 500.00,
        'over_90' => 300.00,
        'total' => 8800.00,
    ],
    // ... more customers
]

$glJournalId = $receivableManager->writeOffInvoice(
    invoiceId: $badInvoice->getId(),
    reason: 'Customer bankruptcy - uncollectible'
);

// Invoice status: WRITTEN_OFF
// GL Entry: Debit Bad Debt Expense / Credit AR Control