# sap-sync

Syncs Abacus contracts to SAP by triggering `sap_sync_contract` events via the OWS REST APIs.

## How it works

For each contract ID in `input.json`:

1. Fetch the contract's states from `ows-abacus-state`
2. Find the `sap_sync` state — if missing, fetch the contract (for its `contract_type`) and create states
3. Skip if the state is already `complete` or freshly `init` (< 5 hours), unless `resync` is enabled
4. Create a `sap_sync_contract` event via `ows-abacus-event` to trigger the sync

Duplicates are filtered out. All API calls are rate-limited. Results are written to `output.json`.

## Setup

```sh
pnpm install
cp .env.shadow .env
# Fill in ORCHARD_IDENTITY_ID
```

## Usage

1. Edit `input.json`:

```json
{
  "job": "sap_sync_contracts",
  "config": {
    "resync": true
  },
  "data": {
    "contractIds": [556554, 556553, 556552]
  }
}
```

2. Run:

```sh
pnpm start
```

3. Results are written to `output.json`.

## Environment variables

| Variable | Default | Description |
|---|---|---|
| `ORCHARD_IDENTITY_ID` | *(required)* | Auth identity ID for API requests |
| `ENVIRONMENT` | `qa` | Target environment (`dev`, `qa`, `uat`, `prod`) |
| `INPUT_PATH` | `./input.json` | Path to input file |
| `OUTPUT_PATH` | `./output.json` | Path to output file |
| `THROTTLE_RPS` | `40` | Max API requests per second |

## Config options

| Option | Default | Description |
|---|---|---|
| `resync` | `false` | Re-trigger sync even if already synced or in progress |

## Project structure

```
src/
├── index.ts      # Entry point — reads input, runs sync, writes output
├── env.ts        # Environment config and API base URLs
├── api.ts        # REST API calls (contract, state, event) with rate limiting
├── sap-sync.ts   # Core sync logic with progress logging
└── types.ts      # Zod schemas and API response types
```
