# Quick Start Guide - Ledger Correctness Boundaries

## 🚀 Quick Deployment

### 1. Verify Database Column Names (5 seconds)

```bash
npm run db:verify-columns
# or
psql $DATABASE_URL -f scripts/verify-column-names.sql
```

**Expected**: Database uses `snake_case` (e.g., `ledger_id`, `debit_account_id`)

### 2. Audit Existing Data (10 seconds)

```bash
npm run db:audit-balances
# or
psql $DATABASE_URL -f scripts/audit-balances.sql
```

**Action**: Fix any inconsistencies found before applying balance constraints.

### 3. Run Migrations (30 seconds)

```bash
npm run db:run-migrations
# or
./scripts/run-migrations.sh $DATABASE_URL
```

**Expected**: All migrations complete successfully.

### 4. Generate Prisma Client (5 seconds)

```bash
npm run prisma:generate
```

### 5. Configure SCB API Credentials

Set environment variables for each SCB:

```bash
export SCB_SCB-1_API_URL="https://scb1-api.example.com"
export SCB_SCB-1_API_KEY="your-api-key"
export SCB_SCB-2_API_URL="https://scb2-api.example.com"
export SCB_SCB-2_API_KEY="your-api-key"
# ... repeat for each SCB
```

### 6. Start Worker

```bash
npm run worker:dual-ledger-outbox
```

Or use PM2:
```bash
pm2 start npm --name dual-ledger-outbox -- run worker:dual-ledger-outbox
```

### 7. Monitor Outbox Queue

```bash
npm run db:monitor-outbox
# or
./scripts/monitor-outbox.sh $DATABASE_URL
```

---

## ✅ Verification (1 minute)

### Test Atomic Posting

```typescript
import { ledgerPostingModule } from '@/core/ledger/ledger-posting.module';

const result = await ledgerPostingModule.postEntry({
  ledgerId: 'Test',
  debitAccountId: 'account1',
  creditAccountId: 'account2',
  amount: '100.00',
  currencyCode: 'USD',
  assetType: 'fiat',
  transactionType: 'Type_A',
  referenceId: 'test-ref-123',
});
```

### Test Outbox Pattern

```typescript
import { gssMasterLedgerService } from '@/core/settlement/gss/gss-master-ledger.service';

const result = await gssMasterLedgerService.postToMasterLedger({
  nodeId: 'SSN-1',
  sourceBankId: 'SCB-1',
  destinationBankId: 'SCB-2',
  amount: '1000.00',
  currencyCode: 'USD',
  assetType: 'fiat',
}, 'my-reference-id');

// Check outbox
const outbox = await prisma.dual_ledger_outbox.findFirst({
  where: { referenceId: 'my-reference-id' },
});
console.log(outbox?.status); // Should be 'QUEUED'
```

---

## 📊 Key Metrics

### Monitor Queue Depth

```sql
SELECT status, COUNT(*) FROM dual_ledger_outbox GROUP BY status;
```

**Expected**:
- QUEUED: < 100
- FAILED: < 10
- FINALIZED: Most jobs

### Monitor Failed Jobs

```sql
SELECT * FROM dual_ledger_outbox 
WHERE status = 'FAILED' 
ORDER BY last_attempt_at DESC 
LIMIT 10;
```

---

## 🔧 Troubleshooting

### Issue: Migration fails "column does not exist"

**Fix**: Verify column names match your database schema.

### Issue: Balance constraints fail

**Fix**: Run `scripts/audit-balances.sql`, fix inconsistencies, then retry.

### Issue: Worker not processing jobs

**Check**:
1. Worker process is running: `ps aux | grep dual-ledger-outbox`
2. Outbox has QUEUED jobs: `SELECT COUNT(*) FROM dual_ledger_outbox WHERE status = 'QUEUED';`
3. Database connection is working

### Issue: SCB API calls failing

**Check**:
1. SCB API credentials configured: `echo $SCB_SCB-1_API_URL`
2. Network connectivity: `curl $SCB_SCB-1_API_URL/health`
3. Idempotency-Key header is being sent (check worker logs)

---

## 📚 Full Documentation

- **Architecture**: `LEDGER_CORRECTNESS_BOUNDARIES.md`
- **Deployment**: `IMPLEMENTATION_CHECKLIST.md`
- **Complete Summary**: `DEPLOYMENT_COMPLETE_SUMMARY.md`
- **Migrations**: `db/migrations/README.md`

---

## ✨ Status

✅ **All implementation steps complete**

**Ready for production deployment!**
