# Reserves Migration

## Overview

This script is meant to be used to migrate the reserves that were taken in legacy accounting and that are scheduled to be released after the Orchard migration to Abacus in order for those reserves to be properly released by Abacus.

The script is composed of the following steps:
1. Fetch the legacy reserves scheduled to be released after the cutover statement period from Snowflake.
2. Map those records by account and taken period in order to compute the `outstanding_amount_after_installment` value, for which no equivalent exist in legacy accounting.
3. For each record, build a `ledger_reserve_release_schedule` entry. We're rounding the amount to two digits and using the remainder to build a `ledger_deposit` entry.
4. Insert those entries into `royalty_accounting` in bulk by calling `ows-ledger`.

The script relies on some "placeholder records" existing in the `royalty_accounting` database in order to populate the foreign keys for the `ledger_reserve_release_schedule` and `ledger_deposit` records.

You should be able to retrieve the placeholder records with:
```
SELECT *
FROM ledger_reserve_taken lrt
JOIN abacus_event ae ON ae.abacus_event_id = lrt.abacus_event_id
WHERE ae.event_name = 'orchard_reserves_migration'
```

## Running the script

1. Copy the `.env.shadow` template to a `.env` file and fill in the values
2. Install the dependencies: `make env`
3. Run the script: `make run`

You can then check the results with:
```
SELECT lrrs.*
FROM ledger_reserve_release_schedule lrrs
JOIN abacus_event ae ON ae.abacus_event_id = lrrs.abacus_event_id
WHERE ae.event_name = 'orchard_reserves_migration';

SELECT ld.*
FROM ledger_deposit ld
JOIN abacus_event ae ON ae.abacus_event_id = ld.abacus_event_id
WHERE ae.event_name = 'orchard_reserves_migration';
```
