> ## Documentation Index
> Fetch the complete documentation index at: https://cona.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Dev accounting rules seeding

# Dev/E2E Accounting Rules Seeding

This system provides convenient ways to seed development and testing organizations with standard fallback rules for posting matrices, eliminating the need to manually configure accounting rules during testing.

## Overview

The seeding system configures fallback rules for posting matrices. Fallback rules are used when no specific posting rules match transaction criteria, ensuring transactions always have a default GL account to post to.

### Current Standard Dev Fallback Rules

| Matrix          | Trigger Event     | Dimension | Fallback Account | Account Nr | Description                                              |
| --------------- | ----------------- | --------- | ---------------- | ---------- | -------------------------------------------------------- |
| Revenue Account | sales-invoice     | Credit    | Revenue Germany  | 8000       | Default revenue account for Sales Invoice credit side    |
| Revenue Account | sales-credit-note | Debit     | Revenue Germany  | 8000       | Default revenue account for Sales Credit Note debit side |

*Add more rules by editing the `DEV_POSTING_RULES` array in the CLI script.*

## Usage Methods

### 1. UI Button (Recommended for Manual Testing)

Navigate to `/setup/accounting-logic` in your dev environment and click the **"⚙️ Seed Dev Accounting Rules"** button at the top of the page.

* **Only visible in development environment** (NODE\_ENV === "development")
* Uses the `warning` button variant for dev/testing purposes
* Shows loading state during seeding
* Displays success/error toasts with detailed information
* Creates or updates fallback rules as needed

### 2. CLI Script (Recommended for Automation)

Use the CLI script for automated testing or CI/CD pipelines:

```bash theme={null}
# Interactive mode (will prompt for required parameters)
pnpm seed:dev-rules

# Non-interactive mode with parameters
pnpm seed:dev-rules <organizationId> [actorId]

# Direct script usage
node scripts/seed-dev-accounting-rules.mjs [organizationId] [actorId]
```

**Examples:**

**Interactive Mode:**

```bash theme={null}
# Will prompt for organization ID and optionally actor ID
pnpm seed:dev-rules

# Example interactive session:
🛠️ Dev Accounting Rules Seeding Tool

📋 Enter Organization ID (required): cloze123abc456def789
👤 Enter Actor ID (optional): [press enter to auto-detect]

🏢 Organization ID: cloze123abc456def789
👤 Actor ID: Auto-detect
✅ Proceed with seeding accounting rules? This will create/update fallback rules (y/N): y
```

**Non-Interactive Mode:**

```bash theme={null}
# Seed organization with ID (auto-detects actor)
pnpm seed:dev-rules cloze123abc456def789

# Seed with specific actor for audit trail
pnpm seed:dev-rules cloze123abc456def789 actor456def789
```

**Environment Requirements:**

* `DATABASE_URL` must be set (uses organization's database)

### 3. Server Action (Programmatic Use)

For programmatic usage in tests or other server-side code:

```typescript theme={null}
import { seedDevAccountingRules } from "@/app/lib/actions/posting_matrix/seed-dev-accounting-rules";

// Within an authenticated context (requires auth)
const result = await seedDevAccountingRules();
if (result.success) {
  console.log(`Seeded ${result.data.length} fallback rules`);
}
```

## How It Works

The seeding system:

1. **Finds Posting Matrices**: Locates the specified posting matrices by label and trigger event
2. **Validates GL Dimensions**: Ensures the matrix has the correct GL dimension type (Credit/Debit)
3. **Locates Chart Accounts**: Finds the target chart accounts by account number
4. **Creates/Updates Fallback Rules**:
   * Creates new fallback rules with `is_fallback: true` and high order numbers (9999)
   * Updates existing fallback rules to point to the correct chart account
   * Links the rule to the appropriate posting matrix and GL account

## Features

* **Upsert Logic**: Rules are created or updated, so running the seed multiple times is safe
* **Validation**: Validates that posting matrices and chart accounts exist before creating rules
* **Error Handling**: Continues processing even if individual rules fail
* **Comprehensive Logging**: Detailed logging for debugging and audit trails
* **Interactive CLI**: Prompts for required parameters with validation
* **Single Source of Truth**: Fallback rules defined once in CLI script, imported by UI

## Prerequisites

Before using the accounting rules seeding:

1. **Posting Matrices Must Exist**: Run the standard posting matrix seeding first:

   ```typescript theme={null}
   // This is typically done during organization setup
   import { seedPostingMatrix } from "@/app/lib/actions/posting_matrix/posting-matrix-seed";
   await seedPostingMatrix(organizationId, actorId);
   ```

2. **Chart of Accounts Must Exist**: Ensure the target chart accounts are seeded:
   ```bash theme={null}
   # Seed chart accounts first
   pnpm seed:dev-chart <organizationId>
   ```

## E2E Testing Integration

### Playwright/E2E Tests

Add this to your test setup:

```typescript theme={null}
// In your test setup or beforeEach
await page.goto("/setup/accounting-logic");
await page.click('button:has-text("⚙️ Seed Dev Accounting Rules")');
await page.waitForSelector('.sonner-toast:has-text("Successfully seeded")');
```

### CI/CD Integration

Add to your CI pipeline after creating test organization and seeding prerequisites:

```yaml theme={null}
- name: Seed dev accounting rules
  run: |
    export DATABASE_URL=${{ secrets.TEST_DATABASE_URL }}
    # Seed chart accounts first
    pnpm seed:dev-chart ${{ env.TEST_ORG_ID }}
    # Then seed accounting rules
    pnpm seed:dev-rules ${{ env.TEST_ORG_ID }}
```

## Important Notes

⚠️ **This is for development/testing only!**

* This seeding is **NOT** part of production organization setup
* It's separate from the standard posting matrix seeding
* The UI button **only appears in development environment**
* Rules are created for testing purposes, not production-ready configurations
* Requires prerequisite seeding (posting matrices and chart accounts)

## Modifying Fallback Rules

To add, remove, or modify the standard dev fallback rules:

1. **Edit only** `apps/webapp/scripts/seed-dev-accounting-rules.mjs`
2. Update the `DEV_FALLBACK_RULES` array
3. Both UI button and CLI will automatically use the updated data

The fallback rules data is defined once in the CLI script and imported by the UI seeding functions, ensuring consistency and eliminating duplication.

## Fallback Rule Configuration Format

```javascript theme={null}
{
  matrixLabel: "Revenue Account",              // Exact posting matrix label
  triggerEvent: "sales-invoice",               // Trigger event slug
  dimensionType: "Credit",                     // "Credit" or "Debit"
  fallbackAccountNr: "8000",                   // Chart account number
  description: "Fallback to Revenue Germany..." // Description for documentation
}
```

## File Structure

```
apps/webapp/
├── scripts/
│   └── seed-dev-accounting-rules.mjs         # 📋 CLI script + single source of truth for rules data
├── app/lib/actions/posting_matrix/
│   └── seed-dev-accounting-rules.ts          # Server action wrapper (imports from CLI script)
├── app/ui/elements/
│   └── dev-accounting-rules-button.tsx       # UI button component (dev-only)
├── app/(pages)/(settings)/setup/accounting-logic/
│   └── page.tsx                               # Main accounting logic page with dev button
└── ../../internal-docs/dev-accounting-rules-seeding.mdx # This documentation
```

## Troubleshooting

**"Posting matrix not found" warnings:**

* Ensure posting matrices have been seeded first using `seedPostingMatrix`
* Verify the matrix label and trigger event slug are correct
* Check that matrices are active (`is_active: true`)

**"Chart account not found" warnings:**

* Run chart of accounts seeding first: `pnpm seed:dev-chart <orgId>`
* Verify the account number exists in the dev chart seeding data
* Ensure accounts are current and not deleted

**"GL dimension type mismatch" warnings:**

* Verify the posting matrix has the correct GL dimension type (Credit/Debit)
* Check the posting matrix configuration in the database

**UI button not visible:**

* Ensure you're in a development environment (`NODE_ENV === "development"`)
* Check that you're authenticated and have access to the organization

**Database connection errors:**

* Verify `DATABASE_URL` environment variable is set
* Check database connectivity

## Related Systems

* **Chart of Accounts Seeding**: `apps/internal-docs/guides/dev-chart-seeding.mdx`
* **Posting Matrix System**: Core business logic for GL account determination
* **GL Dimensions**: Credit and Debit dimension configuration
