AgentSkillsCN

open-accounting-development

在开发或调试开放会计系统时使用:涵盖多租户架构、测试策略(尤其是面向演示界面的端到端测试),以及各层职责划分。适用于功能开发、缺陷修复、测试用例编写,或演示模式下的问题排查。

SKILL.md
--- frontmatter
name: open-accounting-development
description: Use when developing or debugging open-accounting - covers multi-tenant architecture, testing strategy (especially E2E for demo interface), and layer responsibilities. Activate for feature work, bug fixes, test writing, or demo mode issues.

Open Accounting Development Guide

Architecture Context

Multi-Tenant Data Flow

code
Request → Auth Middleware (JWT → user_id, tenant_id, role)
        → Tenant Middleware (sets schema name: "tenant_{uuid}")
        → Handler (validates input, extracts tenant context)
        → Service (business logic, orchestrates repositories)
        → Repository (schema-qualified queries: SELECT FROM {schema}.table)

Layer Responsibilities

LayerOwnsDoes NOT Own
HandlerHTTP concerns, input validation, response formattingBusiness logic, DB transactions
ServiceBusiness rules, orchestration, cross-entity logicHTTP details, direct SQL
RepositoryData access, schema qualification, query buildingBusiness validation, HTTP context

Key Files for Debugging

  • Tenant context: internal/auth/middleware.go (JWT extraction)
  • Schema routing: internal/tenant/service.go (schema name generation)
  • Demo detection: Check for demo@example.com user or demo tenant ID
  • Multi-tenant queries: All repositories use schemaName parameter for table qualification

Testing Strategy

Decision Tree - Which Test Type?

code
Is the change in...
├── Repository layer? → Integration test (needs real DB)
│   └── File: internal/{domain}/*_test.go with //go:build integration
│
├── Service layer? → Unit test with mocked repository
│   └── File: internal/{domain}/*_test.go
│
├── Handler layer? → Unit test with mocked service
│   └── File: internal/{domain}/handlers_test.go
│
├── Frontend component? → Vitest component test
│   └── File: frontend/src/tests/components/*.test.ts
│
├── User-facing workflow? → E2E test
│   └── Demo flow? → frontend/e2e/demo-*.spec.ts
│   └── Regular flow? → frontend/e2e/*.spec.ts

Coverage Targets

LayerTarget
Backend (unit + integration)90%+
Frontend95%+
Critical paths (auth, payments)95%+
Demo interface100% E2E

Demo E2E Priority

The demo at open-accounting.up.railway.app is the first impression for users. All demo functionality must have E2E coverage:

  • Login/logout flow
  • Dashboard widgets and navigation
  • CRUD operations (invoices, contacts, payments)
  • Report generation and exports
  • Error states and edge cases

Demo Mode Reference

Credentials

  • Email: demo@example.com
  • Password: demo123
  • Live demo: open-accounting.up.railway.app

Demo Data Seeding Flow

code
Login as demo@example.com
  → Backend checks if demo tenant exists
  → If not: creates tenant + schema + seeds demo data
  → If exists: optionally resets to fresh state (hourly on Railway)

Key Demo Files

PurposeLocation
Seed logicinternal/tenant/demo_seed.go
Demo handlersinternal/tenant/handlers.go (demo reset endpoint)
E2E testsfrontend/e2e/demo-*.spec.ts
Test configfrontend/playwright.config.ts
Test reportsfrontend/playwright-report-demo/

Multi-User Parallel Testing

E2E tests support parallel execution with isolated demo data:

  • Each test worker gets unique demo seed
  • Tenant IDs passed via URL parameters for data isolation
  • Prevents test interference when running in CI

Debugging Demo Issues

  1. Check tenant schema exists:

    sql
    SELECT schema_name FROM information_schema.schemata
    WHERE schema_name LIKE 'tenant_%';
    
  2. Verify seed data: Check internal/tenant/demo_seed.go for expected accounts/contacts/invoices

  3. Check E2E logs: Review frontend/playwright-report-demo/ for failure screenshots and traces

  4. Test locally: cd frontend && bun run test:e2e:demo

Documentation Checklist

After implementing a feature or fix, update relevant docs:

Change TypeUpdate
API changedocs/API.md
Architecture changedocs/ARCHITECTURE.md
Demo behavior changeREADME.md demo section
New E2E test patternsdocs/plans/ design doc
Translation keys addedBoth messages/en.json and messages/et.json

Plan Documents

For non-trivial work, create a design doc before implementation:

  • Location: docs/plans/YYYY-MM-DD-{topic}-design.md
  • Purpose: Capture decisions, trade-offs, implementation approach
  • Example: docs/plans/2026-01-04-demo-data-reset-testing-design.md

Commit Message Format

code
feat: add new capability
fix: resolve bug
docs: documentation only
test: add or update tests
refactor: restructure without behavior change
chore: maintenance tasks

Error Handling Patterns

Tenant Validation (Frontend)

All action handlers must validate tenant context and show errors to users:

typescript
import { requireTenantId, parseApiError } from '$lib/utils/tenant';
import ErrorAlert from '$lib/components/ErrorAlert.svelte';

// In action handler:
async function doAction() {
    const tenantId = requireTenantId($page, (err) => (error = err));
    if (!tenantId) return;  // Shows error to user automatically

    actionLoading = true;
    error = '';
    try {
        await api.someAction(tenantId, ...);
        success = 'Action completed';
    } catch (err) {
        error = parseApiError(err);  // Handles 403, 401, network errors
    } finally {
        actionLoading = false;
    }
}

Common Error Types

ErrorCauseUser Message
No tenantURL missing ?tenant= param"Please select an organization first"
Access deniedUser not member of tenant"Access denied to this organization"
Session expiredJWT expired"Your session has expired. Please log in again."
Network errorAPI unreachable"Network error. Please try again."

Key Files

PurposeLocation
Tenant validationfrontend/src/lib/utils/tenant.ts
Error alertsfrontend/src/lib/components/ErrorAlert.svelte
Global error pagefrontend/src/routes/+error.svelte
API error parsingfrontend/src/lib/utils/tenant.ts (parseApiError)

MCP Server

The project includes an MCP server for AI assistant integration.

Setup

bash
cd mcp-server
bun install
bun run dev  # Development

Add to Claude Code

bash
claude mcp add open-accounting -- npx tsx /path/to/mcp-server/src/index.ts

Environment Variables

bash
OPEN_ACCOUNTING_API_URL=http://localhost:8080
OPEN_ACCOUNTING_API_TOKEN=your-jwt-token

Available Tools

  • list_invoices - List invoices with filters
  • create_invoice - Create new invoice
  • get_account_balance - Get account balance
  • generate_report - Generate financial reports
  • list_contacts - List customers/vendors
  • record_payment - Record a payment
  • get_chart_of_accounts - Get chart of accounts

Quick Reference

Common Commands

bash
# Backend
go test -race -cover ./...                    # Unit tests
go test -tags=integration -race ./...         # Integration tests
go run ./cmd/api                              # Start API server

# Frontend
cd frontend
bun run dev                                   # Dev server
bun test                                      # Vitest unit tests
bun run test:e2e                              # Playwright E2E
bun run test:e2e:demo                         # Demo-specific E2E
bun run check                                 # TypeScript check
bun run paraglide                             # Compile translations

Project URLs (Local)

  • API: http://localhost:8080
  • Frontend: http://localhost:5173
  • Swagger: http://localhost:8080/swagger/