# Parked Transactions & Auto-Allocation Engine The `co_lending_parked_cron.py` module (and its associated endpoint `/api/co_lending_parked_cron`) manages the concept of "Parked Funds" (overpayments) in the BlackSoil co-lending ecosystem. ## Business Logic ### The Concept of Parked Funds In traditional loan systems, if a customer owes ₹10,000 for their EMI but pays ₹15,000, the extra ₹5,000 is immediately used to reduce the principal outstanding (Pre-Part Payment). However, in the BlackSoil co-lending ecosystem, overpayments are often meant to cover **future EMIs** rather than reduce principal immediately. When an overpayment occurs, the Payment Allocation Engine clears all current dues (Interest, Principal, Penalties), and any remaining cash is pushed into a "Parked" state. ### Auto-Consumption Once funds are parked, they sit idle until the next EMI becomes due. Every night, the Parked Cron wakes up and checks all loans with an `available_amount > 0` in the parked transactions table. If a new EMI has become due (or if new delay penalties have accrued), the cron automatically withdraws funds from the parked balance and processes a new "virtual" payment to clear those dues. ## Technical Logic ### The Lifecycle of Parked Cash 1. **Creation:** - A customer pays ₹15,000. Dues are ₹10,000. - The regular allocation script inserts a row into `co_lending_payment_logs` for ₹15,000. - It clears the ₹10,000 dues. - It detects ₹5,000 leftover and inserts a row into `co_lending_parked_transactions` with `total_amount = 5000` and `available_amount = 5000`, linking it to the original `payment_log_id`. 2. **Nightly Cron Trigger:** - The `/api/co_lending_parked_cron` endpoint is called automatically at midnight. - It queries: `SELECT * FROM co_lending_parked_transactions WHERE available_amount > 0`. 3. **Virtual Payment Generation:** - For every parked transaction found, the script first invokes the **Bounce & Penal Engine** to ensure all penalties are up-to-date. - It then passes the `available_amount` into the core Payment Allocation Engine (`co_lending_regular_allocation.py`). - The Allocation Engine processes the cash exactly as if the customer just paid it today. - The script creates a *new* `payment_log` representing the consumption, linking it back to the parked source. 4. **Balance Reduction:** - If the new dues were ₹3,000, the allocation engine consumes ₹3,000. - The script updates the `available_amount` in `co_lending_parked_transactions` from ₹5,000 down to ₹2,000. - The remaining ₹2,000 sits idle until the *next* cron run finds more dues. ### Table References * **Reads from:** `co_lending_parked_transactions` * **Creates:** `co_lending_payment_logs`, `co_lending_payment_transactions` * **Updates:** `co_lending_parked_transactions` (reduces `available_amount`), `co_lending_emi_payments` (clears dues).