Author SHA1 Message Date
rick 212f19ac19 Add v6-rewrite OpenSpec: proposal, design, specs, and tasks
Complete specification for rewriting Swarmops v5 as using.cash v6:
- Proposal: scope buckets (Working Rewrite / First Beyond Working / Maybe),
  non-goals (governance, geography, memberships permanently cut)
- Design: 18 architectural decisions including preserved patterns
  (Basic/Logic, stored procs, credential split), new patterns (repository
  classes, chain abstraction, rate providers), and operational concerns
  (Galera awareness, continuation transactions, VAT booking, OOD
  denormalization)
- Specs: 17 capability specifications with SHALL/MUST requirements and
  WHEN/THEN scenarios, covering accounting core, AP/AR, crypto treasury,
  exchange rates, organizations, users/auth, documents, comms, dashboard,
  end-of-month, backend worker, event bus, data migration, API layer,
  frontend app, and CI/packaging
- Tasks: 145 implementation tasks grouped by subsystem, ordered by
  dependency (migration gates API/frontend work)

Two rounds of adversarial review incorporated.

Made-with: Cursor
2026-04-08 16:02:58 +02:00
25 changed files with 1769 additions and 0 deletions
+3
View File
@@ -7,6 +7,9 @@
*.sln.docstates
.vs/*
# Credentials
.git/credentials
# Build results
[Dd]ebug/
[Dd]ebugPublic/
+28
View File
@@ -0,0 +1,28 @@
# Agent Isolation Workflow
This repository uses per-agent worktree isolation. Every agent task must run in its own branch and worktree.
## Rules
- Do not edit from the shared integration checkout.
- Do not `git checkout` branches in shared checkouts while other agents may be active.
- Use one worktree per task and one branch per worktree.
- Keep a `.agent-lock` file in each active worktree.
- Keep OpenSpec change artifacts in the main checkout under `openspec/changes/`, even when implementation work happens in an agent worktree.
## Standard Flow
1. Create isolated worktree and branch from integration base:
- `scripts/agent-worktree.sh create <topic> [base-branch]`
2. Work only in that worktree path:
- `.worktree/<topic>`
- Exception: create and edit OpenSpec documents in the main checkout at `openspec/changes/<topic>/`.
3. Commit and push branch:
- `agent/<topic>`
4. Open PR into integration branch.
5. After merge, remove worktree:
- `scripts/agent-worktree.sh remove <topic>`
## Lock File Contract
Each active worktree contains `.agent-lock` with owner/task/timestamp. If lock ownership is unclear, stop and ask before making edits.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-04-08
+307
View File
@@ -0,0 +1,307 @@
## Context
Swarmops v5 is a monolithic C# application targeting .NET Framework 4.5.2 on Mono. It comprises ~1,200 .cs files across 13 projects, connected by a hand-rolled ADO.NET data access layer (`SwarmDb` partial class) against MySQL with ~100 stored procedures. The frontend is ASP.NET WebForms (109 .aspx pages) with jQuery/EasyUI. The build pipeline (CruiseControl.NET, Debian packaging) has been broken for years.
The codebase carries twenty years of accumulated features from its origins as a political party membership register. Roughly half the domain surface (governance, geography, memberships, activists) is no longer relevant to its current purpose as a crypto-centric accounting system.
Stakeholders: the project owner (sole maintainer), existing organizations whose closed accounting ledgers must remain legally presentation-immutable, and tax authorities who may audit those ledgers.
## Goals / Non-Goals
**Goals:**
- Build and run on .NET 8+ without Mono
- Replace ASP.NET WebForms frontend with React + Material UI SPA
- Clean database schema via ETL migration (v5 DB untouched)
- Strip all non-accounting features (governance, geography, memberships)
- Rename all namespaces, assemblies, and branding from Swarmops to UsingCash
- Preserve the financial core with its proven patterns intact
- Dockerized deployment with Gitea Actions CI
- Closed-ledger rendering parity: v6 must present identical numbers to v5
**Non-Goals:**
- Changing the database engine (MySQL stays)
- Rewriting the stored procedure security model (read/write/admin split preserved)
- Multi-chain crypto support in Bucket 1 (BCH only, but abstracted)
- Cloud-native storage or K8s in Bucket 1 (deferred to Bucket 2)
- Payroll, bank integration, or VAT reporting UI in Bucket 1 (deferred; VAT booking mechanics ARE in Bucket 1)
- Using `decimal` for intermediate currency calculations (deliberate: `double` is preserved from v5 to avoid hard-to-debug precision issues; documented as intentional trade-off)
## Decisions
### D1: Preserve Basic/Logic two-tier inheritance
**Decision:** Keep the `BasicFoo` (DTO) / `Foo` (rich domain) inheritance pattern and the `PluralBase<TPlural, TSingular, TBasic>` collection infrastructure.
**Rationale:** This pattern exists for a structural reason — it keeps the Database layer independent of Logic, which was essential during the MSSQL→MySQL migration and remains a clean separation boundary. The `PluralBase` generic eliminates duplication of complex hydration logic across dozens of entity types. Rewriting to a different pattern (e.g., AutoMapper + repositories) would be a large effort with no functional gain.
**Alternatives considered:**
- EF Core with POCO entities: would require abandoning the stored procedure write model and the credential split — too much lost for Bucket 1.
- Dapper with manual mapping: similar to current approach but loses the Basic/Logic split. No clear win.
**Adaptation for v6:** The `SingularFactory` uses reflection to find Logic subclasses. This is acceptable but should be initialized at startup (warm cache) rather than lazily discovered per-request.
### D2: Break SwarmDb into per-domain repository classes
**Decision:** Replace the monolithic `SwarmDb` partial class with domain-scoped repository classes (e.g., `FinancialRepository`, `UserRepository`, `OrganizationRepository`) that share a common `DatabaseConnection` factory providing the read/write/admin credential split.
**Rationale:** The original author wanted one file per table with a shared `GetDatabaseFor*()` method. The partial class achieved this but made the class unboundedly large. Per-domain repositories achieve the same readability while being independently testable and navigable.
**Pattern:**
```
DatabaseConnection (shared factory)
├── GetForReading() → MySQL user with SELECT only
├── GetForWriting() → MySQL user with EXECUTE on write procedures
└── GetForAdmin() → MySQL user with DDL privileges
FinancialRepository : RepositoryBase
├── GetTransaction(id) — uses GetForReading()
├── CreateTransaction(...) — uses GetForWriting(), calls stored proc
└── GetAccountsForOrganization(orgId)
```
### D3: ASP.NET Core minimal API as the HTTP layer
**Decision:** Use ASP.NET Core minimal API endpoints (not controllers) to replace the WebForms page methods and Json-*.aspx endpoints. WebSocket support via ASP.NET Core's built-in middleware replaces websocket-sharp.
**Rationale:** Minimal APIs are lighter weight, map naturally to the current flat endpoint structure (each Json-*.aspx becomes an endpoint group), and avoid the ceremony of MVC controllers for what is essentially a JSON API serving a React SPA.
**Alternatives considered:**
- ASP.NET Core MVC controllers: more structure than needed; the API is a thin translation layer over the Logic layer.
- gRPC: overkill for a browser-facing SPA; would require grpc-web proxy.
### D4: React + Material UI + Vite frontend
**Decision:** Single-page application using React 18+, Material UI (MUI) component library, TypeScript, and Vite as the build tool.
**Rationale:** MUI provides a comprehensive component set (data grids, forms, dialogs, navigation) that maps well to the existing EasyUI-based UI. Vite provides fast builds and HMR. TypeScript catches errors that the current loosely-typed jQuery code misses.
The frontend communicates with the backend exclusively through the REST API and WebSocket — no server-side rendering, no ASPX page lifecycle.
### D5: Clean v6 schema via ETL migration
**Decision:** v6 creates its own MySQL database with a clean schema. A migration tool reads the v5 database and populates v6 tables. The v5 database is never modified.
**Rationale:** The v5 schema carries 76 incremental upgrades, unused columns from cut features (geography, governance, memberships), naming inconsistencies, and stored procedures for deleted functionality. A clean schema lets v6 start with only the tables and procedures it needs.
**Migration tool responsibilities:**
1. Read v5 `FinancialAccounts`, `FinancialTransactions`, `FinancialTransactionRows`, tags, budgets → write to v6 equivalents
2. Read v5 `People` (subset needed as Users) → write to v6 `Users`
3. Read v5 `Organizations` → write to v6 `Organizations`
4. Read v5 `Documents` metadata → write to v6 `Documents` (file storage paths preserved or remapped)
5. Read v5 `Currencies`, `CurrencyExchangeRates` → write to v6 equivalents
6. Read v5 crypto tables (`HotBitcoinAddresses`, `HotBitcoinAddressUnspents`) → write to v6 equivalents
7. Read v5 `ExpenseClaims`, `InboundInvoices`, `OutboundInvoices`, `Payouts`, `Payments` → write to v6 equivalents
8. Mark migrated transactions in closed fiscal years as immutable in v6 schema
9. **Verification pass:** render balance sheets and P&L for all closed periods from both v5 and v6, diff the output — must be identical
**What is NOT migrated:** governance tables, geography hierarchy, memberships, activists, volunteers, parleys, media, ballots, motions, polls, PirateWeb/Activizr-era data, unused optional data types.
### D6: Closed-period immutability in v6 schema
**Decision:** v6 schema includes a `ClosedThroughYear` column on `Organizations` (replacing the v5 `ObjectOptionalData` pattern for `OrgBooksClosedForYear`). Transactions, transaction rows, and account structures within closed periods are protected by application-level enforcement (same as v5) plus a SQL trigger as a safety net.
**Rationale:** v5 relies entirely on application-level enforcement with no database-level guard. This is fragile — a bug in any code path could corrupt legally frozen books. Adding a SQL trigger that rejects `INSERT`/`UPDATE`/`DELETE` on `FinancialTransactionRows` where the transaction date falls within a closed period provides defense-in-depth without changing the application model.
### D7: Instance-level RBAC
**Decision:** Implement role-based access control at the instance level for Bucket 1. Users are assigned roles; roles have permissions. The v5 `Permission` enum is preserved (trimmed of governance/geography permissions). Organization-level roles are deferred to Bucket 2.
**Rationale:** The v5 codebase has a fully commented-out `Authorization.cs` that implemented role×permission checks against the database, plus an active but coarse `Position.HasAccess` path. The commented code was complex because it interacted with organization and geography trees. With geography gone and organizations flat, a straightforward roles-and-permissions model at the instance level is sufficient and dramatically simpler.
**Pattern:**
```
User ──has-many──▶ UserRole (instance-scoped)
Role ──has-many──▶ RolePermission
Permission enum: CanViewLedgers, CanEditTransactions, CanAttestExpenses,
CanManagePayouts, CanManageCrypto, CanAdminOrg,
CanAdminSystem, ...
```
### D8: Crypto chain abstraction
**Decision:** Introduce an `IBlockchainProvider` interface abstracting chain-specific operations (address generation, UTXO queries, transaction building, balance checks). Bucket 1 ships with a single implementation for Bitcoin Cash. The `HotWallet` domain model references a `CryptoChain` identifier rather than hardcoding BCH.
**Rationale:** The v5 code has BCH logic woven directly into `BitcoinUtility` and `BackendLoop`. Extracting an interface now — while we're rewriting anyway — costs little and prevents a second rewrite when adding another chain.
**Alternatives considered:**
- Full multi-chain support in Bucket 1: too much scope; each chain has unique UTXO/account models.
- No abstraction: would repeat the current tight coupling.
### D9: Exchange rate architecture
**Decision:** Preserve the BTC-hub model (all rates expressed relative to BTC, fiat-to-fiat derived by division). Replace the current regex-based BitPay parsing with proper JSON deserialization. Add a provider interface to support fallback/alternate rate sources.
**Pattern:**
```
IRateProvider
├── BitPayRateProvider (primary — BTC-denominated rates)
├── FallbackRateProvider (secondary — TBD, e.g. CoinGecko)
└── CachedRateProvider (wraps any provider with TTL cache)
ExchangeRateService
├── TakeSnapshot() → tries primary, falls back to secondary
└── GetRate(from, to, date) → lookup from stored snapshots
```
### D10: Backend worker as .NET hosted service
**Decision:** Replace the v5 `BackendLoop` console application with an ASP.NET Core `IHostedService` (or `BackgroundService`) running in the same process as the API, or optionally as a separate container.
**Rationale:** .NET 8 hosted services integrate with the DI container, configuration, and health checks. The backend worker needs access to the same repositories and configuration as the API. Running in-process simplifies deployment for Bucket 1; splitting into a separate container is trivial later.
### D11: Gitea Actions CI + Docker
**Decision:** CI runs on Gitea Actions (git.falkvinge.net). Pipeline builds a Docker image containing the .NET backend + pre-built React frontend static assets. The image is the deployment artifact.
**Rationale:** No existing CI to preserve (CruiseControl.NET is dead). Gitea Actions is workflow-compatible with GitHub Actions. Docker provides reproducible builds and deployment.
**Pipeline stages:**
1. `dotnet restore` + `dotnet build` + `dotnet test`
2. `npm ci` + `npm run build` (frontend)
3. `docker build` (multi-stage: build + runtime)
4. Push image to registry
### D12: Continuation transactions for closed-period operations
**Decision:** Preserve the v5 continuation transaction pattern. When `AddRow` is called on a transaction whose date falls in a closed fiscal period, the system creates (or reuses) a continuation transaction dated "now" in the open period, posts the rows there, and links the continuation to the original via `FinancialTransactionDependencies`. This preserves the v5 principle that financial objects are the working objects and accounting happens transparently.
**Rationale:** This is not an edge case — it's the normal path for any operation touching a financial object whose original transaction predates the close. Expense claim edits, invoice re-attestation, payout processing against closed-year items all hit this path. Without it, routine operations on historical items would fail.
**Future improvement (Bucket 2):** The silent redirect is hard to reason about. A better UX pattern (explicit user-visible rebooking) should be explored after Bucket 1 is working.
**Storage:** Continuation links use `FinancialTransactionDependencies` with type `FinancialTransaction` and `ForeignId` = parent transaction ID. `RecalculateTransaction` aggregates balances across the chain before computing deltas.
### D13: VAT booking at transaction creation time
**Decision:** VAT booking splits are part of Bucket 1. When an expense claim, inbound invoice, or outbound invoice includes a VAT amount, the system creates separate transaction rows for the net amount (on the budget/income account) and the VAT amount (on `AssetsVatInboundUnreported` or `DebtsVatOutboundUnreported`). VAT amounts are entered manually (total + VAT portion in cents), not computed from rates.
**Rationale:** VAT splits affect the ledger structure from the moment transactions are created. Deferring this would produce ledger entries that differ structurally from v5, breaking migration verification and making future VAT reporting harder to retrofit. European tax reporting requires VAT to be separable from the moment of booking.
**VAT-related accounts in the chart:**
- `AssetsVatInboundUnreported` / `AssetsVatInboundReported`
- `DebtsVatOutboundUnreported` / `DebtsVatOutboundReported`
**Per-org configuration:** `VatEnabled` controls whether VAT fields appear in the UI and whether booking splits apply. `DefaultVatRatePercent` (integer, e.g., 25 for Sweden) is used to pre-fill outbound invoice VAT amounts; it has no effect on inbound documents where VAT is always manual entry. Future Bucket 2+ work can add country-specific rate tables, item/service class rates, and reverse charge automation.
### D14: Self-attestation allowed
**Decision:** v6 allows self-attestation by default. A user who submits an expense claim and is also the budget owner can attest their own claim. This preserves v5 behavior and is essential for sole-proprietor organizations.
**Rationale:** Strict separation of duties would make the software unusable for the primary use case (sole proprietor doing all accounting). A future per-org toggle for larger organizations can be added in Bucket 2 with organization-level RBAC.
### D15: MariaDB/Galera cluster awareness
**Decision:** The database layer must be compatible with MariaDB running Galera consensus replication. Specifically: `LAST_INSERT_ID()` MUST be read on the same write connection that performed the insert, never on a read replica. This is the fundamental reason the read/write credential split exists and why write stored procedures return the identity via `SELECT LAST_INSERT_ID()`.
**Rationale:** In a Galera cluster, a freshly inserted row may not have replicated to read-only nodes when the write returns. The v5 architecture already handles this correctly by design — v6 must preserve this property.
### D16: ObjectOptionalData denormalization strategy
**Decision:** v6 denormalizes the v5 `ObjectOptionalData` EAV table into first-class columns on the entities they belong to. The migration tool maps each kept EAV key to a concrete v6 column. EAV keys for cut features are not migrated.
**Rationale:** The EAV pattern was a pragmatic choice in v5 for evolving the schema without DDL migrations on every change. With a clean v6 schema, there's no reason to preserve the indirection — first-class columns are type-safe, indexable, and self-documenting.
**Key mappings (kept, denormalized to columns):**
- Org: `EconomyEnabled`, `BooksClosedForYear`, `Currency`, `FirstFiscalYear`, `VatEnabled`, `VatReportFrequencyMonths`, `TaxAccount`, `TaxOcr`, `GovtRegistrationId`, `TaxAuthority`, `FinancialMailName`, `FinancialMailAddress`, `LogoLandscape`, `LogoSquare`
- FinancialAccount: `NativeCurrency`, `BitcoinPublicAddress`, `BitcoinPrivateRoot`, `BitcoinPublicRoot`, `BankTransactionTag`, `EnabledForExpensing`, `EnabledForInvoicing`, `OwnerUserId`, `AutomationProfileId`
- InboundInvoice: `Description`, `ExactBitcoinAmountSatoshis`, `NativeCurrencyCode`, `NativeCurrencyAmountCents`
- OutboundInvoice: `CreditedWithInvoice`, `CreditsInvoice`, `ToUserId`
- FinancialTransaction: `BlockchainHash`
- FinancialTransactionRow: `BitcoinDerivationPath`
- User (from Person): `BankName`, `BankClearing`, `BankAccount`, `BitcoinPayoutAddress`, `PreferredCulture`, `NeverMail`, `ResetPasswordTicket`
**Dropped:** All governance, geography, membership, activism, forum, party-era, and PII keys.
### D17: Foreign currency amounts on transaction rows
**Decision:** v6 preserves the `NativeCurrencyAmountCents` / `NativeCurrencyCode` tracking on financial transaction rows. When a transaction row is in a currency different from the organization's presentation currency, both the presentation-currency amount (in the main row) and the foreign-currency amount are stored.
**Rationale:** This is essential for multi-currency accounting. An org booking in SEK that receives BCH deposits needs both the SEK ledger amount and the original BCH amount for audit trail and reconciliation.
### D18: Localization strategy
**Decision:** v6 Bucket 1 ships with English (primary), Swedish (secondary), and German (should-have). Translation packs use standard .NET resource files (.resx) for the backend and a JSON-based i18n system (e.g., react-i18next) for the frontend. AI-assisted translation generates initial packs; human review for Swedish.
## Risks / Trade-offs
**[Risk] Migration data fidelity** — ETL could introduce rounding errors or miss edge cases in financial data, leading to legally incorrect ledger presentation.
→ **Mitigation:** Verification pass compares rendered output (balance sheets, P&L, individual transaction details) between v5 and v6 for all closed periods. Migration tool includes checksums on financial totals per organization per year.
**[Risk] Stored procedure maintenance burden** — Handwritten stored procedures are tedious to maintain and lack tooling support compared to ORM-generated SQL.
→ **Mitigation:** This is an accepted trade-off. The security benefit (write credentials can only execute specific procedures) outweighs the maintenance cost. Procedures are version-controlled and tested.
**[Risk] SingularFactory reflection** — The reflection-based factory for hydrating Logic types from Basic types could be fragile during the rename and type reorganization.
→ **Mitigation:** Warm the factory cache at startup; fail fast with clear errors if a Basic type lacks a corresponding Logic type. Add integration tests that verify all Basic→Logic mappings.
**[Risk] BitPay API deprecation** — Current rate data comes from a single source. If BitPay changes or removes the endpoint, exchange rates stop updating.
→ **Mitigation:** The `IRateProvider` abstraction with fallback support (D9) means a secondary provider can be added without code changes to the rate consumption path.
**[Risk] Large rename scope** — 6,146 occurrences of "Swarmops" across 1,371 files. Mechanical rename could miss edge cases (config files, SQL strings, hardcoded paths).
→ **Mitigation:** The rename happens as part of the rewrite, not as a find-and-replace on v5 code. Each subsystem is rewritten under the new namespace, so stale references are caught at compile time. SQL stored procedures don't use the Swarmops name internally.
**[Risk] Frontend feature parity** — The v5 UI has accumulated subtle behaviors (EasyUI grid customizations, jQuery widget interactions) that may be lost in translation to React.
→ **Mitigation:** Spec each frontend page's functional requirements independently of implementation. Use the v5 UI as reference for behavior, not for code.
**[Risk] ObjectOptionalData migration surface** — v5 stores hundreds of entity metadata fields in a generic EAV table. Missing keys during migration means losing org settings, account metadata, or financial configuration that doesn't live in the main entity tables.
→ **Mitigation:** D16 provides an explicit mapping of every kept EAV key to a v6 column. Migration includes an audit step that reports any EAV keys found in v5 data that are not in the mapping (either migrated or explicitly listed as dropped).
**[Risk] Continuation transaction chain correctness** — The silent redirect of rows from closed-period transactions to continuations is subtle. Recalculation must aggregate across chains correctly, and migration must preserve existing chains.
→ **Mitigation:** Integration tests specifically for continuation chains: create chain, recalculate, verify balances. Migration preserves `FinancialTransactionDependencies` with type `FinancialTransaction`.
**[Risk] Galera replication lag** — Read-after-write on a different MySQL node can return stale data.
→ **Mitigation:** D15 ensures `LAST_INSERT_ID()` is always read on the write connection. All write-then-read patterns use the write credential connection.
## Migration Plan
### Phase 1: Foundation (no user-visible features)
1. Scaffold .NET 8 solution with new project structure (`UsingCash.Common`, `.Basic`, `.Database`, `.Logic`, `.Api`, `.Backend`, `.Migration`, `.Tests`)
2. Create v6 MySQL schema (DDL + stored procedures for financial core, AP/AR, VAT accounts, crypto, users/orgs)
3. Build `DatabaseConnection` factory with credential split (Galera-aware: LAST_INSERT_ID on write connection)
4. Port `Money`, `Currency`, `BasicFinancialAccount`, `BasicFinancialTransaction`, etc.
5. Wire up CI pipeline (Gitea Actions + Docker + lint)
### Phase 2: Financial core + Migration (gates all later phases)
6. Port accounting Logic layer (accounts, transactions, tags, budgets, period closing, continuation transactions, VAT booking splits, foreign currency row amounts, OrganizationSequenceId)
7. Build ETL migration tool with ObjectOptionalData denormalization mapping
8. Run multi-level verification pass: balance sheets, P&L, per-account-per-year checksums, transaction-level spot checks
9. Port exchange rate system with proper BitPay JSON parsing and micro-BTC scaling
### Phase 3: API + Frontend shell
10. Implement REST API endpoints for ledger data (read-only first)
11. Scaffold React app with MUI, routing, auth (session cookies), i18n (EN/SV/DE)
12. Build ledger viewing pages (chart of accounts, inspect ledgers, balance sheet, P&L)
### Phase 4: Write operations
13. API endpoints for expense claims, invoices (with VAT booking), payouts
14. Frontend pages for AP/AR workflows
15. Attestation (with self-attestation support) and receipt validation flows
### Phase 5: Remaining Bucket 1
16. Crypto treasury (BCH hot wallet, blockchain ingestion)
17. Dashboard and dashboard tasks
18. End-of-month workflow (upload + manual review; no reconciliation until Bucket 2)
19. Comms/mail, event bus, backend worker (exchange rates, forex P&L, automated payouts, heartbeat)
20. User management and RBAC
21. Dev impersonation
22. Database seeding / bootstrap (first admin user + org on fresh deployment)
### Rollback strategy
The v5 database is never modified. If v6 deployment fails, the v5 system (once buildable again, or from the last known working state) can be restored against the original database. The v6 database can be dropped and re-migrated.
## Open Questions
1. **MySQL/MariaDB version requirement for v6?** — The v5 schema uses features available in MySQL 5.7+ / MariaDB 10.3+. Should v6 target MySQL 8.0+ / MariaDB 10.6+ to leverage CTEs, window functions, and improved JSON support? (Must remain Galera-compatible.)
2. **Frontend state management** — React Query (TanStack Query) for server state, or a more traditional Redux/Zustand setup? Given the accounting domain's read-heavy nature, React Query's cache-first approach seems natural. (Resolve before frontend implementation begins.)
## Resolved Questions
- **Auth token mechanism** — Session cookies. Simpler for single-domain SPA, easy to revoke, works naturally with the WebSocket auth model (cookie sent on WS upgrade), and compatible with Galera (session store can use the write DB or be in-process for single-instance Bucket 1). JWT adds complexity with no benefit at this scale.
- **File storage path mapping** — Configure v6 to read from the existing `/var/lib/swarmops/upload/` path via a config setting pointing to the legacy storage root. No file copy during migration. Document metadata is migrated with paths preserved. When Bucket 2 adds S3/MinIO, the `IDocumentStorage` abstraction handles the transition.
- **Intermediate currency calculation precision** — Keep `double`, matching v5. `decimal` causes hard-to-debug issues in practice. Rates are inherently fluctuating snapshots; sub-cent precision on conversions is not meaningful. Documented as deliberate.
- **Fiscal year start month** — Removed from v6 Bucket 1. v5 assumes calendar-year fiscal years. Configurable fiscal year start is a Bucket 2+ concern at best.
+109
View File
@@ -0,0 +1,109 @@
## Why
Swarmops v5 is unbuildable. Its build pipeline (CruiseControl.NET, Debian packaging, Mono runtime) has been broken for years, it targets .NET Framework 4.5.2 on Mono, and the ASP.NET WebForms frontend is a dead technology. Meanwhile the software has pivoted from a Pirate Party membership register to a crypto-centric accounting system — but the codebase still carries twenty years of political-organization features (governance, geography hierarchies, membership management) that no longer serve the product's purpose.
The v6 rewrite modernizes the runtime, replaces the frontend, strips the dead weight, and renames the product from "Swarmops" to "using.cash" (namespace `UsingCash`). The financial core — double-entry ledger, AP/AR, crypto treasury — is preserved and cleaned up. The v5 database is left untouched; v6 gets a clean schema populated by a one-time ETL migration, with closed ledger periods guaranteed to render identically on-screen.
## What Changes
### Scope Bucket 1 — Working Rewrite
- **BREAKING**: Runtime moves from .NET Framework 4.5.2 / Mono to .NET 8+
- **BREAKING**: Frontend replaced — ASP.NET WebForms → React + Material UI + TypeScript + Vite
- **BREAKING**: Backend HTTP layer replaced — WebForms page methods and Json-*.aspx → ASP.NET Core minimal API + WebSocket
- **BREAKING**: Namespace and branding rename — `Swarmops.*` → `UsingCash.*`, all PirateWeb/Activizr/Falconwing references removed
- **BREAKING**: New database schema — v6 owns its own MySQL database, populated via ETL from v5
- Accounting core preserved: double-entry ledger, chart of accounts, balance sheet, P&L, budget tracking, continuation transactions for closed-period operations, foreign currency amounts on transaction rows
- AP/AR preserved: expense claims, inbound/outbound invoices, attestation workflow (self-attestation allowed for sole proprietors), payouts, refunds
- VAT booking at transaction creation time: inbound VAT on expenses and supplier invoices, outbound VAT on customer invoices — split into dedicated VAT accounts. VAT reporting UI deferred to Bucket 2 but data must be correct from the moment it enters the ledger
- Crypto treasury preserved: BCH hot wallet with UTXO tracking, abstracted for future chain support
- Exchange rate system cleaned up: proper JSON parsing of BitPay API, fallback rate sources, BTC-hub model preserved
- Organizations preserved as multi-tenant boundary (flat, no tree hierarchy)
- Users replace People/Members — simplified identity with instance-level RBAC
- Comms/mailing simplified to direct SMTP delivery
- Documents preserved with local filesystem storage
- Dashboard tasks preserved
- Backend worker preserved: exchange rate snapshots, mail processing, heartbeat
- Event bus preserved (low-priority DB queue, simplified)
- Dev-mode impersonation ("become admin") preserved
- Read/Write/Admin DB credential split and stored procedure write pattern preserved
- Money as Int64 smallest-units preserved; double for intermediate rate calculations (deliberate — decimal causes hard-to-debug issues)
- Localization: English primary, Swedish secondary, German should-have
- Sequential journal numbering (OrganizationSequenceId) preserved for legal compliance
- CI: Gitea Actions + Docker build
- Migration tool: ETL from v5 MySQL → v6 schema, with multi-level ledger verification (balance sheets, P&L, transaction-level checksums, per-account-per-year totals)
- ObjectOptionalData EAV migration: financial/org/crypto keys denormalized to first-class columns in v6 schema
### Scope Bucket 2 — First Beyond Working
- Abstract document storage (S3/MinIO)
- Kubernetes deployment manifests
- Bank file integration (import/reconciliation)
- VAT reporting UI and periodic report generation
- Organization-level RBAC (flat, not tree)
- Improved continuation transaction UX (future: find a better pattern than silent redirect)
### Scope Bucket 3 — Maybe / Later
- Payroll and salary management
- Sweden-specific tax tables
- Additional cryptocurrency chain support
- Additional localization packs beyond EN/SV/DE
## Non-goals
These features are permanently cut from v6:
- Governance (elections, ballots, motions, internal polls, meetings)
- Parleys (event attendance tracking)
- Media tracking (reporters, blog influence)
- Geography hierarchy (countries, cities, postal codes as organizational structure)
- Memberships and membership payments
- Activists and volunteer management
- PilotInstallationIds (hardcoded beta deployment UUIDs)
- BitID (dead 2FA technology)
- PGP key support
- User-impersonation for help-desk use (admin helping members fill forms)
- Blog/forum/press watchers and scrapers
- RSS writer
- Interface project (functionality absorbed or dropped)
- FrontSocket / Falconwing (replaced by ASP.NET Core WebSocket)
- CruiseControl.NET and Debian packaging build infrastructure
- Boneyard (all legacy site generations)
## Capabilities
### New Capabilities
- `accounting-core`: Double-entry ledger engine — accounts, transactions, transaction rows (including foreign currency amounts), tags, budgets, period closing, continuation transactions, sequential journal numbering, balance/P&L/budget reporting, VAT booking splits
- `accounts-payable-receivable`: Expense claims, inbound invoices (supplier), outbound invoices (customer), attestation workflow, receipt validation, payouts, refunds
- `crypto-treasury`: BCH hot wallet, UTXO tracking, blockchain transaction ingestion, chain-abstraction layer for future multi-chain support
- `exchange-rates`: Rate snapshot system via BitPay API (BTC hub model), proper JSON parsing, fallback sources, fiat-to-fiat derivation
- `organizations`: Multi-tenant organization boundaries, org settings, org-scoped data isolation
- `users-and-auth`: User identity (replacing People/Members), login, password reset, instance-level RBAC with role-based permissions, dev-mode impersonation
- `documents`: File storage and metadata for receipts, invoices, financial supporting docs — local filesystem with path abstraction
- `comms`: Simplified outbound email via direct SMTP, mail templates, mail queue processing
- `dashboard`: Landing page with task summaries, end-of-month workflow status, quick links
- `dashboard-tasks`: Actionable work items (attest expenses, validate receipts, approve invoices) surfaced per-user
- `end-of-month`: Monthly workflow — books balancing verification, bank statement upload, close-books checklist, year-end closing journal
- `backend-worker`: Background processing daemon — exchange rate snapshots, mail delivery, heartbeat, event bus consumption
- `event-bus`: Low-priority asynchronous messaging via database queue between frontend and backend worker
- `data-migration`: One-time ETL from v5 Swarmops MySQL to v6 UsingCash schema, with closed-ledger verification (rendered diff)
- `api-layer`: ASP.NET Core REST API + WebSocket replacing WebForms page methods and Json-*.aspx endpoints
- `frontend-app`: React + MUI + TypeScript SPA — all user-facing pages for Bucket 1 scope
- `ci-and-packaging`: Gitea Actions pipelines, Docker image builds, automated testing
### Modified Capabilities
_(No existing specs to modify — this is a greenfield spec-driven rewrite.)_
## Impact
- **All code**: Every assembly renamed from `Swarmops.*` to `UsingCash.*`; all .csproj files rewritten for .NET 8+ SDK-style format
- **Database**: New MySQL schema; ~100 stored procedures rewritten (governance/geography/membership procedures dropped); read/write/admin user grants recreated
- **Frontend**: Complete replacement — 109 .aspx pages and 27 .ascx controls replaced by React components; jQuery/EasyUI dependencies eliminated
- **Backend**: `BackendLoop` and socket services ported to .NET 8+ hosted services; WebForms-specific code removed
- **Dependencies**: Mono runtime dropped; NBitcoin updated; MySql.Data updated; websocket-sharp replaced by ASP.NET Core WebSocket; RestSharp evaluated for replacement; all checked-in DLLs in `External Libraries/` replaced by NuGet references
- **Build**: CruiseControl.NET config, Debian packaging templates, and all `BuildFiles/` infrastructure replaced by Gitea Actions + Docker
- **Configuration**: `/etc/swarmops/` → `/etc/usingcash/`; `database.config` XML format preserved; `web.config` replaced by `appsettings.json`
- **File storage**: Storage root is configurable; fresh installs default to `/var/lib/usingcash/upload/`, migrations can point at the legacy `/var/lib/swarmops/upload/` path (Bucket 2 adds S3/MinIO abstraction)
@@ -0,0 +1,189 @@
## ADDED Requirements
### Requirement: Double-entry ledger engine
The system SHALL maintain a double-entry bookkeeping ledger where every financial transaction consists of two or more rows that sum to zero (debits equal credits). Transaction rows reference financial accounts. A transaction with rows that do not sum to zero SHALL be flagged as unbalanced.
#### Scenario: Balanced transaction
- **WHEN** a transaction is created with rows summing to zero across all referenced accounts
- **THEN** the transaction is stored and reflected in account balances
#### Scenario: Unbalanced transaction detection
- **WHEN** a transaction exists whose rows do not sum to zero
- **THEN** the system SHALL flag it as unbalanced and surface it in the end-of-month workflow
### Requirement: Chart of accounts
The system SHALL maintain a chart of accounts per organization. Each account has a type (Asset, Debt, Income, Cost), a name, an optional parent account (for hierarchical display), and an open/closed status. Result accounts (Income, Cost) SHALL have their signs reversed for display (positive means credit).
#### Scenario: Create account
- **WHEN** an authorized user creates a new financial account with a name, type, and optional parent
- **THEN** the account appears in the chart of accounts for that organization
#### Scenario: Close account
- **WHEN** an authorized user closes a financial account
- **THEN** the account no longer accepts new transaction rows but remains visible in historical ledger views
#### Scenario: Rename account in open period
- **WHEN** an authorized user renames an account whose first activity year is in an open fiscal period
- **THEN** the account name is updated
#### Scenario: Reject rename in closed period
- **WHEN** an authorized user attempts to rename an account whose first activity year falls within a closed fiscal period
- **THEN** the system SHALL reject the rename
### Requirement: Financial transaction tags
The system SHALL support multi-dimensional tagging of financial transactions. Tag sets define categories (e.g., project, department). Each transaction can have one tag per tag set. Tag types within a set have open/closed years controlling their availability.
#### Scenario: Tag a transaction
- **WHEN** a user assigns a tag from an active tag type to a transaction
- **THEN** the tag is stored and the transaction appears in filtered views for that tag
#### Scenario: Closed tag type
- **WHEN** a tag type's closed year has passed
- **THEN** it SHALL NOT be available for new tagging but remains visible on historical transactions
### Requirement: Budget tracking
The system SHALL support annual and monthly budget amounts per financial account. Budget vs actual reporting compares budgeted amounts against actual transaction row totals for the same account and period.
#### Scenario: Set annual budget
- **WHEN** an authorized user sets a budget amount for an account for a given year
- **THEN** the budget appears in budget-vs-actual reports for that year
#### Scenario: Budget vs actual report
- **WHEN** a user views the budget-vs-actual report for a year
- **THEN** the system displays each budgeted account with its budget amount, actual total from transaction rows, and the variance
### Requirement: Balance sheet reporting
The system SHALL generate a balance sheet showing all Asset and Debt accounts with their cumulative balances as of a specified date. The balance sheet MUST balance (total assets equals total debts plus equity).
#### Scenario: View balance sheet
- **WHEN** a user requests a balance sheet for a given date
- **THEN** the system displays Asset accounts, Debt accounts, and equity with their cumulative balances from the dawn of the organization through the specified date
### Requirement: Profit and loss reporting
The system SHALL generate a profit and loss statement showing all Income and Cost accounts with their totals for a specified period (typically a fiscal year).
#### Scenario: View P&L for fiscal year
- **WHEN** a user requests a P&L report for a given year
- **THEN** the system displays all Income and Cost accounts with totals for transactions dated within that year
### Requirement: Ledger inspection
The system SHALL allow users to view all transaction rows for a given account within a date range, with links to the parent transactions.
#### Scenario: Inspect account ledger
- **WHEN** a user selects an account and date range
- **THEN** the system displays all transaction rows for that account within the range, showing date, description, amount, running balance, and a link to the full transaction
### Requirement: Period closing
The system SHALL support closing fiscal years per organization. Closing a year requires: (1) no unbalanced transactions in that year, (2) balance sheet identity holds (asset/debt deltas equal negative P&L totals), (3) a closing journal entry is created on Dec 31 transferring P&L results to equity. Once closed, the `ClosedThroughYear` for the organization advances.
#### Scenario: Close fiscal year
- **WHEN** an authorized user initiates year-end closing for a year where all preconditions are met
- **THEN** a closing journal is created, and the organization's closed-through-year advances
#### Scenario: Reject close with unbalanced transactions
- **WHEN** an authorized user attempts to close a year that contains unbalanced transactions
- **THEN** the system SHALL reject the close and list the unbalanced transactions
#### Scenario: Reject direct modification in closed period
- **WHEN** any operation attempts to directly insert, update, or delete a transaction row where the transaction date falls within a closed fiscal period without going through the continuation mechanism
- **THEN** the system SHALL reject the operation at both the application layer and the database layer (SQL trigger)
### Requirement: Continuation transactions
When `AddRow` is called on a transaction whose date year falls within a closed fiscal period, the system SHALL NOT reject the operation. Instead, it SHALL create (or reuse) a continuation transaction dated at the current time in the open period, post the rows there, and link the continuation to the original via a dependency record of type `FinancialTransaction`. `RecalculateTransaction` SHALL aggregate balances across the entire continuation chain before computing deltas.
#### Scenario: AddRow on closed-period transaction
- **WHEN** a row is added to a transaction whose date is in a closed fiscal year
- **THEN** a continuation transaction is created (or reused) in the current open period, the row is posted there, and the continuation is linked to the original via a dependency
#### Scenario: Recursive continuation chain
- **WHEN** a continuation transaction itself falls in a newly closed period (due to books being closed since it was created)
- **THEN** the system recurses and creates another continuation in the current open period
#### Scenario: Recalculation across chain
- **WHEN** `RecalculateTransaction` is called on a transaction that has continuations
- **THEN** it aggregates balances from the root transaction and all continuations before computing adjustment deltas
### Requirement: Sequential journal numbering
The system SHALL assign a per-organization sequential number (`OrganizationSequenceId`) to each financial transaction. These numbers MUST be gap-free within an organization for legal compliance. Migration MUST preserve existing sequence numbers.
#### Scenario: New transaction gets sequence number
- **WHEN** a financial transaction is created for an organization
- **THEN** it receives the next sequential OrganizationSequenceId for that organization
#### Scenario: Sequence preserved in migration
- **WHEN** v5 transactions are migrated to v6
- **THEN** their OrganizationSequenceId values are preserved exactly
### Requirement: Foreign currency amounts on transaction rows
When a transaction row records an amount in a currency different from the organization's presentation currency, the system SHALL store both the presentation-currency amount (in the main row) and the foreign-currency amount and code. This preserves the audit trail for multi-currency operations.
#### Scenario: BCH deposit in SEK-denominated org
- **WHEN** a BCH deposit is recorded in an organization that books in SEK
- **THEN** the transaction row stores the SEK equivalent as the primary amount and the original BCH satoshi amount as the foreign currency amount
#### Scenario: Foreign amount preserved in migration
- **WHEN** v5 transaction rows with native currency data are migrated
- **THEN** the foreign currency code and amount are preserved exactly in v6
### Requirement: VAT booking splits
When an expense claim, inbound invoice, or outbound invoice includes a VAT amount and the organization has VAT enabled, the system SHALL create separate transaction rows: the net amount on the budget/income account and the VAT amount on the appropriate VAT account (`AssetsVatInboundUnreported` for expenses/inbound invoices, `DebtsVatOutboundUnreported` for outbound invoices). VAT amounts always enter the ledger as absolute cents regardless of how they were determined at the UI layer.
#### Scenario: Expense claim with VAT
- **WHEN** a user submits an expense of €125 with €25 VAT in a VAT-enabled org
- **THEN** the ledger records: DebtsExpenseClaims −12500, Budget +10000, AssetsVatInboundUnreported +2500
#### Scenario: Outbound invoice with VAT
- **WHEN** a user creates an outbound invoice for €1200 with €200 VAT
- **THEN** the ledger records: AssetsOutboundInvoices +120000, Budget −100000, DebtsVatOutboundUnreported −20000
#### Scenario: VAT disabled org
- **WHEN** an expense is submitted in an org where VAT is not enabled
- **THEN** the full amount goes to the budget account with no VAT split
### Requirement: VAT amount determination
For inbound documents (expense claims and supplier invoices), the VAT amount SHALL be entered manually in whole currency units (e.g., "25.00" for twenty-five euros) matching the receipt or invoice exactly — even if the counterparty calculated it incorrectly. The system SHALL NOT validate or recompute inbound VAT amounts. The UI-entered amount is converted to the smallest currency unit (cents) at the API boundary for internal storage. For outbound invoices, the system SHALL pre-fill the VAT amount computed from the organization's default VAT rate applied to the net amount, but this pre-filled amount SHALL be editable so the user can adjust it (for cross-border sales, exempt items, different rate classes, or reverse charge).
#### Scenario: Manual VAT on expense claim
- **WHEN** a user submits an expense claim and enters "25.00" as the VAT amount
- **THEN** the system converts this to 2500 cents internally and uses it for the VAT booking split, with no validation against any rate
#### Scenario: Manual VAT on inbound invoice
- **WHEN** a user registers a supplier invoice and enters the VAT amount from the invoice
- **THEN** the entered amount is converted to cents and used exactly, even if it does not match any standard VAT rate applied to the net amount
#### Scenario: Default VAT on outbound invoice
- **WHEN** a user creates an outbound invoice in a VAT-enabled org with a default rate of 25%
- **THEN** the VAT field is pre-filled with 25% of the net amount (displayed in whole units), and the user can accept or override it
#### Scenario: Override VAT on outbound invoice
- **WHEN** a user creates an outbound invoice and changes the pre-filled VAT amount (e.g., to 0.00 for a cross-border B2B reverse charge)
- **THEN** the overridden amount is converted to cents and used for the VAT booking split
### Requirement: Organization default VAT rate
A VAT-enabled organization SHALL have a configurable default VAT rate (percentage) representing the standard rate of the organization's home country. This rate is used to pre-fill outbound invoice VAT amounts. It does not affect inbound document VAT entry (which is always manual).
#### Scenario: Set default VAT rate
- **WHEN** an administrator sets the organization's default VAT rate to 25%
- **THEN** new outbound invoices pre-fill VAT at 25% of the net amount
### Requirement: Budget owner tracking
Each financial account SHALL have an optional owner (user) who serves as the budget owner for attestation purposes. The owner is stored as a first-class column on the account.
#### Scenario: Set budget owner
- **WHEN** an administrator assigns a user as the budget owner of a financial account
- **THEN** that user receives attestation tasks for expenses and invoices charged to that account
### Requirement: Money representation
The system SHALL represent all monetary amounts as Int64 values in the smallest unit of the currency (cents for fiat, satoshis for BTC/BCH). Display formatting SHALL convert to the appropriate decimal representation based on the currency's unit scale (100 for most fiat, 1,000,000 for microbitcoin display).
#### Scenario: Fiat amount storage
- **WHEN** an amount of €42.50 is stored
- **THEN** the internal representation is 4250 (cents) with currency EUR
#### Scenario: Crypto amount storage
- **WHEN** an amount of 0.005 BCH is stored
- **THEN** the internal representation is 500000 (satoshis) with currency BCH
#### Scenario: Cross-currency display
- **WHEN** a report displays amounts in multiple currencies
- **THEN** each amount is formatted according to its currency's decimal convention
@@ -0,0 +1,71 @@
## ADDED Requirements
### Requirement: Expense claim lifecycle
The system SHALL support expense claims where a user submits an expense with amount, description, date, and attached receipt. Claims progress through states: Created → Attested → Validated → Approved for Payout → Paid Out. Each state transition requires authorization.
#### Scenario: Submit expense claim
- **WHEN** a user submits an expense claim with required fields and a receipt document
- **THEN** the claim is created in "Created" state and a ledger transaction is generated against the appropriate cost account
#### Scenario: Attest expense claim
- **WHEN** the budget owner for the expense's cost account attests the claim
- **THEN** the claim advances to "Attested" state
#### Scenario: Validate receipt
- **WHEN** an authorized user validates that the receipt matches the claimed amount and description
- **THEN** the claim advances to "Validated" state
#### Scenario: Expense in closed fiscal year
- **WHEN** a user submits an expense claim with a date falling in a closed fiscal year
- **THEN** the ledger transaction date SHALL be set to the current date (landing in an open period) while the expense date is preserved as metadata
### Requirement: Inbound invoices (supplier invoices)
The system SHALL track invoices received from suppliers. An inbound invoice has a supplier name, amount, currency, due date, account allocation, and attached document. Inbound invoices follow an attestation workflow before being approved for payment.
#### Scenario: Register inbound invoice
- **WHEN** an authorized user registers an inbound invoice with required fields
- **THEN** the invoice is created and a ledger transaction is generated (debit cost/asset account, credit accounts-payable)
#### Scenario: Attest inbound invoice
- **WHEN** the budget owner attests the invoice
- **THEN** the invoice is marked as attested and eligible for payout
### Requirement: Outbound invoices (customer invoices)
The system SHALL support creating invoices sent to customers. An outbound invoice has a customer reference, line items with amounts, a due date, and generates a ledger transaction (debit accounts-receivable, credit income account).
#### Scenario: Create outbound invoice
- **WHEN** an authorized user creates an outbound invoice with line items
- **THEN** the invoice is stored and a ledger transaction is generated
#### Scenario: Mark outbound invoice paid
- **WHEN** payment is received and an authorized user marks the invoice as paid
- **THEN** a payment transaction is recorded (debit cash/bank account, credit accounts-receivable)
### Requirement: Attestation workflow
The system SHALL enforce that expenses and inbound invoices are attested by the budget owner of the account they are charged to. Attestation is a prerequisite for payout. Self-attestation (where the submitter is also the budget owner) is allowed — this is required for sole-proprietor organizations.
#### Scenario: Budget owner attests
- **WHEN** the budget owner for an account reviews a pending expense or invoice charged to that account
- **THEN** they can approve (attest) or reject it
#### Scenario: Self-attestation for sole proprietor
- **WHEN** a user who submitted an expense claim is also the budget owner
- **THEN** the system SHALL allow them to attest their own claim
### Requirement: Payouts
The system SHALL group approved expenses, attested invoices, and other payment obligations into payouts. Each payout targets a payment method (bank transfer, crypto) and has a lifecycle: Created → Executed → Confirmed.
#### Scenario: Create payout
- **WHEN** an authorized user initiates a payout for approved items
- **THEN** a payout record is created grouping the items, with a total amount and payment target
#### Scenario: Execute payout
- **WHEN** the payout is executed (bank transfer sent or crypto transaction broadcast)
- **THEN** the payout is marked as executed and the corresponding ledger transactions are updated
### Requirement: Refunds
The system SHALL support refunding a previously paid expense or invoice. A refund creates a reversing ledger transaction.
#### Scenario: Issue refund
- **WHEN** an authorized user issues a refund against a paid item
- **THEN** a reversing transaction is created in the ledger and the original item is marked as refunded
@@ -0,0 +1,56 @@
## ADDED Requirements
### Requirement: REST API endpoints
The system SHALL expose REST API endpoints for all operations currently served by WebForms page methods and Json-*.aspx pages. Endpoints return JSON and follow consistent conventions: resource-oriented URLs, standard HTTP methods, and consistent error response format.
#### Scenario: List financial accounts
- **WHEN** an authenticated client sends `GET /api/organizations/{orgId}/accounts`
- **THEN** the API returns the chart of accounts for that organization as JSON
#### Scenario: Create expense claim
- **WHEN** an authenticated client sends `POST /api/organizations/{orgId}/expense-claims` with claim data
- **THEN** the API creates the claim and returns the new resource with its ID
#### Scenario: Unauthenticated request
- **WHEN** an unauthenticated client calls any API endpoint
- **THEN** the API returns 401 Unauthorized
### Requirement: WebSocket for real-time updates
The system SHALL provide a WebSocket endpoint for real-time notifications to connected clients. Authentication on WebSocket upgrade uses the same session cookie as REST API requests. Events include: new blockchain deposits detected, task list changes, backend worker status updates.
#### Scenario: WebSocket connection
- **WHEN** an authenticated client connects to the WebSocket endpoint (session cookie sent on upgrade)
- **THEN** the client receives real-time events scoped to their active organization
#### Scenario: Unauthenticated WebSocket rejected
- **WHEN** a client without a valid session cookie attempts a WebSocket upgrade
- **THEN** the server rejects the upgrade with 401
#### Scenario: Blockchain deposit notification
- **WHEN** the backend worker detects a new deposit to a hot wallet address
- **THEN** connected clients for that organization receive a notification via WebSocket
### Requirement: Consistent error responses
All API errors SHALL return a JSON body with `error` (machine-readable code), `message` (human-readable description), and optional `details` (field-level validation errors). HTTP status codes follow REST conventions (400 for validation, 401 for auth, 403 for permission, 404 for not found, 500 for server errors).
#### Scenario: Validation error
- **WHEN** a client submits an expense claim missing a required field
- **THEN** the API returns 400 with an error body listing the missing fields
#### Scenario: Permission denied
- **WHEN** a user without the `CanAttestExpenses` permission attempts to attest a claim
- **THEN** the API returns 403 with an error body indicating the missing permission
### Requirement: Organization-scoped routing
All resource endpoints SHALL be scoped under `/api/organizations/{orgId}/` to enforce multi-tenant data isolation at the routing level. The API layer verifies the authenticated user has access to the specified organization before processing.
#### Scenario: Cross-org access denied
- **WHEN** a user belonging only to Organization A requests data for Organization B
- **THEN** the API returns 403
### Requirement: Static file serving
The API server SHALL serve the React SPA's static assets (HTML, JS, CSS) from a configured directory. All non-API routes SHALL fall through to the SPA's `index.html` for client-side routing.
#### Scenario: SPA route fallthrough
- **WHEN** a browser navigates to `/ledgers/balance-sheet`
- **THEN** the server serves `index.html` and the React router handles the route
@@ -0,0 +1,69 @@
## ADDED Requirements
### Requirement: Background processing service
The system SHALL run a background worker as a .NET `IHostedService` that executes scheduled tasks on configurable intervals. The worker runs in the same process as the API (or optionally as a separate container).
#### Scenario: Worker starts with API
- **WHEN** the application starts
- **THEN** the background worker begins its processing loop
#### Scenario: Worker task execution
- **WHEN** a scheduled interval elapses for a given task type
- **THEN** the worker executes that task and logs the result
### Requirement: Exchange rate snapshot task
The worker SHALL periodically capture exchange rate snapshots using the configured rate provider chain (primary + fallback).
#### Scenario: Scheduled rate snapshot
- **WHEN** the rate snapshot interval elapses (configurable, default 15 minutes)
- **THEN** the worker calls the exchange rate service to take a snapshot
### Requirement: Mail queue processing task
The worker SHALL periodically process the outbound mail queue, delivering pending emails via SMTP and updating their status.
#### Scenario: Process mail queue
- **WHEN** the mail queue check interval elapses
- **THEN** the worker attempts delivery of all pending emails
### Requirement: Blockchain monitoring task
The worker SHALL periodically check for new transactions to hot wallet addresses using the blockchain provider.
#### Scenario: Check blockchain
- **WHEN** the blockchain monitoring interval elapses
- **THEN** the worker queries the chain provider for new transactions to tracked addresses and ingests any deposits found
### Requirement: Forex P&L recalculation task
The worker SHALL periodically (weekly) recalculate unrealized gains and losses on financial accounts denominated in a foreign currency relative to the organization's presentation currency.
#### Scenario: Weekly forex recalculation
- **WHEN** the weekly forex P&L interval elapses
- **THEN** the worker computes unrealized currency gains/losses for each foreign-currency-denominated account and records adjustment transactions
### Requirement: Automated payout cycle task
The worker SHALL periodically (every 5 minutes) check for approved payouts that are ready for execution and process them automatically.
#### Scenario: Automated payout processing
- **WHEN** the payout cycle interval elapses and there are approved payouts pending execution
- **THEN** the worker executes the payouts and updates their status
### Requirement: Schema version check on startup
The worker SHALL check the database schema version on startup using admin credentials. If the schema needs upgrading, it applies migrations before starting normal operations.
#### Scenario: Schema up to date
- **WHEN** the worker starts and the schema version matches the expected version
- **THEN** normal operations begin immediately
#### Scenario: Schema needs upgrade
- **WHEN** the worker starts and the schema version is behind the expected version
- **THEN** it applies pending migrations using admin credentials before starting operations
### Requirement: Heartbeat
The worker SHALL periodically update a heartbeat timestamp in the database to indicate it is alive and operational. The frontend can check this timestamp to warn if the backend worker has stopped.
#### Scenario: Heartbeat update
- **WHEN** the heartbeat interval elapses
- **THEN** the worker updates the heartbeat timestamp in system settings
#### Scenario: Stale heartbeat detection
- **WHEN** the frontend checks the heartbeat and finds it older than a threshold (e.g., 5 minutes)
- **THEN** a warning is displayed to administrators
@@ -0,0 +1,49 @@
## ADDED Requirements
### Requirement: Gitea Actions CI pipeline
The system SHALL have a CI pipeline running on Gitea Actions (git.falkvinge.net) that builds, tests, and packages the application on every push and pull request.
#### Scenario: Push triggers CI
- **WHEN** a developer pushes to any branch
- **THEN** the CI pipeline runs build, test, and lint stages
#### Scenario: Build failure blocks merge
- **WHEN** a CI build fails on a pull request
- **THEN** the PR is not mergeable until the build passes
### Requirement: Docker image build
The CI pipeline SHALL produce a Docker image as the deployment artifact. The image uses a multi-stage build: build stage compiles the .NET backend and builds the React frontend; runtime stage contains only the .NET runtime, compiled backend, and built frontend static assets.
#### Scenario: Multi-stage Docker build
- **WHEN** the CI pipeline reaches the packaging stage
- **THEN** a Docker image is built containing the backend runtime and frontend static assets
#### Scenario: Image pushed to registry
- **WHEN** the Docker build succeeds on the main branch
- **THEN** the image is tagged and pushed to the configured container registry
### Requirement: Automated testing and linting in CI
The CI pipeline SHALL run: .NET unit/integration tests (`dotnet test`), .NET analyzers/linting, frontend tests (`npm test`) if present, and frontend linting (`npm run lint`). Test or lint failures fail the pipeline.
#### Scenario: Backend tests run
- **WHEN** the CI test stage executes
- **THEN** all .NET test projects are discovered and run
#### Scenario: Test failure
- **WHEN** any test fails
- **THEN** the pipeline fails and reports which tests failed
#### Scenario: Lint failure
- **WHEN** .NET analyzers or frontend ESLint report errors
- **THEN** the pipeline fails and reports the violations
### Requirement: Solution structure
The .NET solution SHALL use SDK-style project files targeting .NET 8+. Project structure: `UsingCash.Common`, `UsingCash.Basic`, `UsingCash.Database`, `UsingCash.Logic`, `UsingCash.Api` (web host + API endpoints), `UsingCash.Backend` (hosted service, may be in-process with Api), `UsingCash.Migration` (ETL tool), `UsingCash.Tests` (references Common, Basic, Database, Logic, Api, Migration for integration tests).
#### Scenario: Solution builds
- **WHEN** a developer runs `dotnet build` on the solution
- **THEN** all projects compile without errors targeting .NET 8+
#### Scenario: NuGet dependencies
- **WHEN** the solution restores dependencies
- **THEN** all external libraries (MySqlConnector, NBitcoin, etc.) are resolved from NuGet — no checked-in DLLs
@@ -0,0 +1,30 @@
## ADDED Requirements
### Requirement: Outbound email delivery
The system SHALL send outbound emails via direct SMTP connection to a configured mail server. Configuration includes SMTP host, port, and optional credentials.
#### Scenario: Send email
- **WHEN** the system needs to send an email (password reset, notification, etc.)
- **THEN** it connects to the configured SMTP server and delivers the message
#### Scenario: SMTP failure
- **WHEN** the SMTP connection fails
- **THEN** the email is queued for retry and the failure is logged
### Requirement: Mail queue
The system SHALL maintain a persistent mail queue in the database. Emails are enqueued by application code and dequeued by the backend worker for delivery. Failed deliveries are retried with backoff.
#### Scenario: Enqueue email
- **WHEN** application code requests an email be sent
- **THEN** the email is stored in the mail queue with recipient, subject, body, and status "pending"
#### Scenario: Backend worker processes queue
- **WHEN** the backend worker checks the mail queue
- **THEN** it attempts delivery of all pending emails and updates their status (sent or failed with retry count)
### Requirement: Mail templates
The system SHALL support named mail templates with placeholder substitution. Templates are stored in the database per organization. Placeholders use a simple token syntax (e.g., `%UserName%`, `%OrganizationName%`).
#### Scenario: Render template
- **WHEN** an email is composed using a template name and substitution values
- **THEN** the template body is fetched, placeholders are replaced, and the result is enqueued
@@ -0,0 +1,53 @@
## ADDED Requirements
### Requirement: Chain abstraction layer
The system SHALL define an `IBlockchainProvider` interface abstracting chain-specific operations: address generation, UTXO/balance queries, transaction building, and transaction broadcast. Each supported cryptocurrency chain implements this interface. Bucket 1 ships with Bitcoin Cash (BCH) only.
#### Scenario: Generate deposit address
- **WHEN** the system needs a new deposit address for an organization
- **THEN** it calls the chain provider's address generation method and stores the address with its derivation metadata
#### Scenario: Query UTXOs
- **WHEN** the system checks the balance of a hot wallet address
- **THEN** it calls the chain provider's UTXO query method and receives a list of unspent outputs with amounts in satoshis
### Requirement: Hot wallet management
The system SHALL maintain hot wallet addresses per organization, tracking each address and its unspent transaction outputs (UTXOs). The hot wallet balance is the sum of all UTXOs across all addresses for an organization.
#### Scenario: Track new UTXO
- **WHEN** a blockchain transaction sends funds to a tracked hot wallet address
- **THEN** the UTXO is recorded with its transaction hash, output index, and amount in satoshis
#### Scenario: Spend UTXO
- **WHEN** a payout or transfer consumes a UTXO
- **THEN** the UTXO is marked as spent with the consuming transaction hash
#### Scenario: View hot wallet balance
- **WHEN** a user views the crypto treasury page
- **THEN** the system displays the total hot wallet balance in both native crypto units and the organization's fiat equivalent (via exchange rates)
### Requirement: Blockchain transaction ingestion
The system SHALL periodically query blockchain data sources to detect incoming transactions to hot wallet addresses. Detected deposits create financial transactions in the ledger (debit crypto asset account, credit income or receivable account as appropriate).
#### Scenario: Detect incoming deposit
- **WHEN** the backend worker detects a new confirmed transaction to a hot wallet address
- **THEN** a ledger transaction is created recording the deposit and the UTXO is tracked
#### Scenario: Skip closed-period transactions
- **WHEN** a blockchain transaction's timestamp falls within a closed fiscal period
- **THEN** the system SHALL skip ingestion for that transaction, on the assumption that it was already ingested and recorded before the period was closed
#### Scenario: Late-discovered historical deposit
- **WHEN** a deposit to a hot wallet address is discovered for the first time but its blockchain timestamp falls within a closed fiscal period
- **THEN** the system SHALL log a warning with the transaction details for manual review rather than silently skipping it; a manual recovery path (posting to the current open period with a reference to the original chain timestamp) is required
### Requirement: Crypto payouts
The system SHALL support paying out approved expenses and invoices in cryptocurrency. A crypto payout builds a transaction from available UTXOs, broadcasts it via the chain provider, and records the outbound transaction in the ledger.
#### Scenario: Execute crypto payout
- **WHEN** an authorized user initiates a crypto payout for approved items
- **THEN** the system selects UTXOs sufficient to cover the amount plus fees, builds and broadcasts a transaction, and records it in the ledger
#### Scenario: Insufficient funds
- **WHEN** the hot wallet does not have sufficient UTXOs to cover a payout
- **THEN** the system SHALL reject the payout with a clear error indicating the shortfall
@@ -0,0 +1,30 @@
## ADDED Requirements
### Requirement: Task generation
The system SHALL generate actionable tasks for users based on their roles and the current state of financial objects. Task types include: attest expense claims, attest inbound invoices, validate receipts, and approve payouts.
#### Scenario: Expense claim pending attestation
- **WHEN** an expense claim is submitted against an account whose budget owner is User A
- **THEN** a task "Attest expense claim #N" appears in User A's task list
#### Scenario: Inbound invoice pending attestation
- **WHEN** an inbound invoice is registered against a budgeted account
- **THEN** a task appears for the budget owner to attest it
### Requirement: Task lifecycle
Each task SHALL have a creation timestamp and an optional expiry. Tasks are automatically resolved when the underlying action is completed (e.g., claim attested). Tasks that expire without action SHALL be visually flagged.
#### Scenario: Task auto-resolves
- **WHEN** User A attests expense claim #N
- **THEN** the corresponding task is removed from User A's task list
#### Scenario: Expired task
- **WHEN** an attestation task exceeds its expiry period (14 days from claim creation)
- **THEN** the task is flagged as overdue in the dashboard
### Requirement: Task list API
The system SHALL expose a REST endpoint returning the current user's active tasks, grouped by type, with counts per group.
#### Scenario: Fetch task list
- **WHEN** the frontend requests the current user's tasks
- **THEN** the API returns tasks grouped by type (e.g., "Attest Expenses: 3", "Validate Receipts: 1") with individual task details
@@ -0,0 +1,19 @@
## ADDED Requirements
### Requirement: Dashboard overview
The system SHALL present a dashboard as the landing page after login. The dashboard displays: a summary of pending tasks for the current user, organization financial summary (P&L year-to-date), and end-of-month workflow status.
#### Scenario: View dashboard
- **WHEN** an authenticated user navigates to the dashboard
- **THEN** the system displays their pending task count, YTD P&L summary for the active organization, and end-of-month checklist status
#### Scenario: Dashboard with no pending tasks
- **WHEN** a user has no pending tasks
- **THEN** the dashboard task section shows an empty state with a confirmation message
### Requirement: Quick navigation
The dashboard SHALL provide quick links to frequently used pages: inspect ledgers, submit expense claim, view chart of accounts, and crypto treasury overview.
#### Scenario: Navigate from dashboard
- **WHEN** a user clicks a quick link on the dashboard
- **THEN** they are navigated to the corresponding page with the active organization context preserved
@@ -0,0 +1,105 @@
## ADDED Requirements
### Requirement: One-time ETL migration tool
The system SHALL include a migration tool that reads from a v5 Swarmops MySQL database and populates a v6 UsingCash MySQL database. The v5 database MUST NOT be modified by the migration. The tool runs as a standalone CLI application.
#### Scenario: Run migration
- **WHEN** an administrator runs the migration tool pointing to v5 and v6 database connection strings
- **THEN** the tool reads v5 data, transforms it to v6 schema, and writes to the v6 database
#### Scenario: v5 database untouched
- **WHEN** the migration completes
- **THEN** the v5 database has zero modifications (no rows inserted, updated, or deleted)
### Requirement: Financial data migration
The tool SHALL migrate: financial accounts (chart of accounts with OwnerUserId), financial transactions and transaction rows (including foreign currency amounts from `FinancialTransactionRowsNativeCurrency`), transaction tags and tag sets, budget allocations, expense claims, inbound invoices, outbound invoices (including credit-link optional data), payouts, payments, payment groups, refunds, and continuation transaction dependency chains. All monetary amounts SHALL be preserved exactly (Int64 cents/satoshis, no rounding). OrganizationSequenceId values SHALL be preserved exactly.
#### Scenario: Ledger data fidelity
- **WHEN** financial transactions are migrated
- **THEN** every transaction row's amount in v6 is identical to v5, and account balances computed from v6 data match v5 exactly
#### Scenario: Foreign currency amounts preserved
- **WHEN** v5 transaction rows have associated native currency data in `FinancialTransactionRowsNativeCurrency`
- **THEN** the foreign currency code and amount are migrated to the corresponding v6 columns
#### Scenario: Continuation chains preserved
- **WHEN** v5 has continuation transactions linked via `FinancialTransactionDependencies` with type `FinancialTransaction`
- **THEN** the dependency chain is preserved in v6
#### Scenario: Closed-period marking
- **WHEN** an organization's `FiscalBooksClosedUntilYear` (stored as `OrgBooksClosedForYear` in v5 ObjectOptionalData) is N
- **THEN** the v6 organization's `ClosedThroughYear` is set to N and all transactions in years <= N are marked as belonging to a closed period
### Requirement: ObjectOptionalData denormalization
The tool SHALL read the v5 `ObjectOptionalData` EAV table and denormalize kept keys into first-class v6 columns per the mapping in design decision D16. The tool SHALL report any EAV keys found in v5 data that are not in the explicit keep/drop mapping, so nothing is silently lost.
#### Scenario: Org settings denormalized
- **WHEN** v5 has `OrgEconomyEnabled`, `OrgCurrency`, `OrgFirstFiscalYear`, `OrgBooksClosedForYear`, `OrgValueAddedTaxEnabled`, `OrgGovtRegistrationId`, etc. in ObjectOptionalData
- **THEN** these become first-class columns on the v6 Organizations table
#### Scenario: Financial account metadata denormalized
- **WHEN** v5 has `FinancialAccountNativeCurrency`, `FinancialAccountBitcoinPublicAddress`, `BankTransactionTag`, etc.
- **THEN** these become first-class columns on the v6 FinancialAccounts table
#### Scenario: Unknown EAV key warning
- **WHEN** the migration encounters an ObjectOptionalData key not in the keep or drop list
- **THEN** it logs a warning with the key name, object type, and object ID
### Requirement: Entity migration
The tool SHALL migrate: organizations (flat, dropping tree hierarchy and ParentOrganizationId), people (as users, dropping membership/activist data but preserving bank details, bitcoin payout address, preferred culture, and other kept optional data), currencies and exchange rate history (with micro-BTC scaling preserved), crypto hot wallet addresses and UTXOs, documents metadata (storage paths preserved pointing to existing filesystem), and system settings.
#### Scenario: People to users
- **WHEN** v5 People records are migrated
- **THEN** they become v6 User records with name, email, a flag indicating password reset is required, and denormalized optional data (bank details, bitcoin payout address, preferred culture)
#### Scenario: Organization flattening
- **WHEN** v5 organizations with parent-child relationships are migrated
- **THEN** each becomes a flat v6 organization with no hierarchy reference; ParentOrganizationId is dropped
#### Scenario: Exchange rate history preserved
- **WHEN** v5 exchange rate snapshots and datapoints are migrated
- **THEN** the micro-BTC scaling convention and BCH exception are preserved exactly
### Requirement: Auth/access migration
The tool SHALL create v6 role assignments based on v5 position/access data. Users who held positions with system-level or org-level access in v5 SHALL be assigned corresponding v6 roles. The mapping from v5 position types to v6 roles SHALL be documented and auditable.
#### Scenario: Admin position migrated
- **WHEN** a v5 person held a system-admin-level position
- **THEN** they receive the system administrator role in v6
#### Scenario: Org-level access migrated
- **WHEN** a v5 person held an org-level financial position
- **THEN** they receive an appropriate financial role in v6
### Requirement: Selective migration
The tool SHALL NOT migrate: governance data (elections, ballots, motions, polls), geography hierarchies, membership records, activist/volunteer data, parleys, media entries, PirateWeb/Activizr-era event data, or ObjectOptionalData keys explicitly classified as "dropped" in design D16.
#### Scenario: Governance data skipped
- **WHEN** the migration tool encounters governance-related tables
- **THEN** it skips them entirely
### Requirement: Multi-level verification pass
The migration tool SHALL include a verification mode with multiple levels of checking:
1. **Aggregate level:** Balance sheets and P&L reports for all closed periods, compared between v5 and v6
2. **Account level:** Per-account-per-year transaction totals, compared between v5 and v6
3. **Transaction level:** Spot checks on individual transactions (row counts, amounts, foreign currency data)
4. **Checksum level:** Per-organization-per-year hash of all transaction row amounts, ensuring no drift
#### Scenario: Aggregate verification succeeds
- **WHEN** the verification pass compares all closed-period balance sheets and P&L
- **THEN** every figure matches exactly between v5 and v6
#### Scenario: Account-level verification succeeds
- **WHEN** the verification pass compares per-account annual totals
- **THEN** every account's annual total matches exactly
#### Scenario: Verification finds discrepancy
- **WHEN** any figure differs at any verification level
- **THEN** the tool reports the specific level, accounts, periods, and amounts that differ and exits with a failure code
### Requirement: Idempotent re-run
The migration tool SHALL support re-running against a v6 database. Re-running drops and recreates the v6 data (or uses an upsert strategy) so that the migration can be repeated during development and testing without manual cleanup.
#### Scenario: Re-run migration
- **WHEN** the migration tool is run against a v6 database that already contains migrated data
- **THEN** the existing data is replaced with a fresh migration from v5
@@ -0,0 +1,34 @@
## ADDED Requirements
### Requirement: Document storage and metadata
The system SHALL store uploaded documents (receipts, invoices, supporting files) on the filesystem with metadata in the database. Metadata includes: document type, foreign object reference (expense claim, invoice, transaction), original filename, server filename, file size, uploader, and upload timestamp.
#### Scenario: Upload document
- **WHEN** a user uploads a file attached to an expense claim
- **THEN** the file is stored under the configured storage root in a `yyyy/mm/dd` directory structure and metadata is recorded in the database
#### Scenario: Retrieve document
- **WHEN** a user requests a document by its ID
- **THEN** the system serves the file from the storage path recorded in metadata
### Requirement: Document type association
Each document SHALL be typed (expense receipt, inbound invoice, outbound invoice, financial transaction support, etc.) and linked to a foreign object by type and ID. A single foreign object can have multiple documents attached.
#### Scenario: List documents for expense claim
- **WHEN** a user views an expense claim
- **THEN** all documents of type "expense receipt" linked to that claim are listed
#### Scenario: Reassign document
- **WHEN** an authorized user reassigns a document from one foreign object to another
- **THEN** the document's foreign reference is updated
### Requirement: Storage path abstraction
The system SHALL access document storage through an `IDocumentStorage` interface with a default local filesystem implementation. The storage root path SHALL be configurable. This enables a future swap to S3/MinIO (Bucket 2) without changing the application layer.
#### Scenario: Configurable storage root
- **WHEN** the storage root is configured (defaulting to `/var/lib/usingcash/upload/` for fresh installs, or pointing at the legacy `/var/lib/swarmops/upload/` path for migrations)
- **THEN** all document writes and reads use the configured path as the base directory
#### Scenario: Storage interface isolation
- **WHEN** a document is stored or retrieved
- **THEN** the operation goes through `IDocumentStorage` and does not directly reference filesystem APIs in the business logic
@@ -0,0 +1,41 @@
## ADDED Requirements
### Requirement: End-of-month checklist
The system SHALL present a monthly workflow page with a checklist of items to review before considering the month closed. Checklist items include: unbalanced transactions resolved, bank statement uploaded (for manual review — automated reconciliation is Bucket 2), all expense claims attested, all inbound invoices attested.
#### Scenario: View end-of-month checklist
- **WHEN** a user navigates to the end-of-month page
- **THEN** the system displays the checklist for the current month with pass/fail status for each item
#### Scenario: All items passed
- **WHEN** all checklist items for a month are satisfied
- **THEN** the month is visually marked as ready (though no formal "close month" operation is required — only year-end close is a formal action)
### Requirement: Bank statement upload
The system SHALL allow authorized users to upload bank statement files as part of the end-of-month workflow. Uploaded statements are stored as financial account documents associated with the relevant bank account and period.
#### Scenario: Upload bank statement
- **WHEN** a user uploads a bank statement file for a specific account and month
- **THEN** the file is stored as a document linked to the financial account with the period recorded
### Requirement: Books balancing verification
The system SHALL verify that all transactions within the period balance (all transaction row sums equal zero). Unbalanced transactions are listed with links to inspect and correct them.
#### Scenario: All transactions balanced
- **WHEN** the system checks the current month's transactions
- **THEN** the books-balancing item on the checklist shows "passed"
#### Scenario: Unbalanced transactions found
- **WHEN** the system finds transactions with non-zero row sums in the current month
- **THEN** the checklist item shows "failed" with a list of unbalanced transactions linked to the ledger inspection page
### Requirement: Year-end close integration
The end-of-month page SHALL include a year-end section visible in December (or the final month of the fiscal year) that links to the close-ledgers workflow when the fiscal year is eligible for closing.
#### Scenario: Year eligible for closing
- **WHEN** the current period is the last month of the fiscal year and all months have been reviewed
- **THEN** a "Close Fiscal Year" action is presented linking to the period-closing workflow
#### Scenario: Year not yet eligible
- **WHEN** the current fiscal year is still in progress
- **THEN** the year-end section indicates the year cannot yet be closed
@@ -0,0 +1,26 @@
## ADDED Requirements
### Requirement: Database-backed event queue
The system SHALL provide an asynchronous event queue backed by a database table. Events are enqueued by frontend/API operations and dequeued by the backend worker. This is for low-priority, non-time-critical signaling between components.
#### Scenario: Enqueue event
- **WHEN** an API operation needs to signal the backend worker (e.g., "new expense claim needs processing")
- **THEN** an event is inserted into the queue table with a type, payload, and timestamp
#### Scenario: Dequeue and process event
- **WHEN** the backend worker polls the event queue
- **THEN** it retrieves pending events, processes them by type, and marks them as completed
### Requirement: Event types
The system SHALL support typed events with a string type identifier and a JSON payload. Event types in Bucket 1 include: `ExpenseClaimCreated`, `InvoiceRegistered`, `PayoutRequested`, `ExchangeRateStale`, `DocumentUploaded`.
#### Scenario: Typed event handling
- **WHEN** the backend worker dequeues an event of type `ExpenseClaimCreated`
- **THEN** it routes the event to the expense claim handler which may trigger notifications
### Requirement: Event retention
Processed events SHALL be retained for a configurable period (default 30 days) for debugging and audit purposes, then purged.
#### Scenario: Purge old events
- **WHEN** the backend worker runs its maintenance cycle
- **THEN** completed events older than the retention period are deleted
@@ -0,0 +1,67 @@
## ADDED Requirements
### Requirement: Rate provider abstraction
The system SHALL define an `IRateProvider` interface for fetching exchange rates. Providers return rates expressed as amounts per one BTC. The system ships with a BitPay provider as primary and supports fallback providers.
#### Scenario: Fetch rates from primary provider
- **WHEN** the exchange rate service takes a snapshot
- **THEN** it calls the primary provider (BitPay) to get all available currency rates denominated in BTC
#### Scenario: Primary provider failure with fallback
- **WHEN** the primary provider fails (network error, API change, invalid response)
- **THEN** the system falls back to the next configured provider and logs the failure
### Requirement: BTC hub conversion model
The system SHALL store all exchange rates relative to BTC. Fiat-to-fiat conversion is derived by dividing the two currencies' BTC rates. This avoids needing direct fiat-to-fiat rate pairs.
#### Scenario: Convert EUR to USD
- **WHEN** a conversion from EUR to USD is requested for a given date
- **THEN** the system looks up both EUR-per-BTC and USD-per-BTC for that date and computes the cross rate
#### Scenario: Convert BCH to fiat
- **WHEN** a conversion from BCH to a fiat currency is requested
- **THEN** the system uses the stored BCH-per-BTC and fiat-per-BTC rates to compute the conversion
### Requirement: Rate snapshots
The system SHALL periodically capture exchange rate snapshots and store them with timestamps. Rate lookups for a given date use the closest available snapshot.
#### Scenario: Periodic snapshot
- **WHEN** the backend worker's scheduled interval elapses
- **THEN** a new rate snapshot is captured and stored
#### Scenario: Historical rate lookup
- **WHEN** a conversion is requested for a past date
- **THEN** the system uses the rate snapshot closest to that date
### Requirement: Proper BitPay API parsing
The BitPay rate provider SHALL parse the API response as JSON using a proper JSON deserializer. The response SHALL be validated for expected structure before extracting rates. Malformed responses SHALL be rejected with a logged error rather than silently producing incorrect rates.
#### Scenario: Valid BitPay response
- **WHEN** the BitPay API returns a well-formed JSON response with rate data
- **THEN** rates are deserialized and stored for all recognized currencies
#### Scenario: Malformed BitPay response
- **WHEN** the BitPay API returns invalid or unexpected JSON
- **THEN** the snapshot attempt fails, the error is logged, and the fallback provider is tried
### Requirement: Micro-BTC storage scaling
The system SHALL store exchange rates divided by 1,000,000 (micro-BTC scaling) for all currencies EXCEPT BCH, which is stored at face value. This matches the v5 convention where amounts are expressed in the smallest unit (satoshis = 1/100,000,000 BTC, but displayed as microbitcoin = 1/1,000,000 BTC). `GetConversionRate` SHALL account for this scaling. Getting this wrong would silently produce rates off by 6 orders of magnitude.
#### Scenario: Fiat rate storage
- **WHEN** BitPay reports 1 BTC = 50,000 USD
- **THEN** the stored rate for USD is 0.05 (50,000 / 1,000,000)
#### Scenario: BCH rate storage exception
- **WHEN** BitPay reports 1 BTC = 200 BCH
- **THEN** the stored rate for BCH is 200 (face value, no micro-BTC division)
#### Scenario: Rate retrieval correctness
- **WHEN** a conversion from EUR to USD is computed using stored micro-BTC-scaled rates
- **THEN** the scaling cancels out in the division and the result is correct
### Requirement: Currency conversion uses double arithmetic
The system SHALL use `double` (not `decimal`) for intermediate exchange rate calculations, matching v5 behavior. This is a deliberate choice: `decimal` causes hard-to-debug precision issues in practice, and exchange rates are inherently fluctuating snapshots where sub-cent precision is not meaningful.
#### Scenario: Rate multiplication
- **WHEN** a Money amount is converted to another currency
- **THEN** the Int64 cents value is multiplied by the double exchange rate and cast back to Int64
@@ -0,0 +1,125 @@
## ADDED Requirements
### Requirement: React SPA with Material UI
The frontend SHALL be a single-page application built with React 18+, Material UI (MUI), and TypeScript. Vite SHALL be used as the build tool. The SPA communicates exclusively via the REST API and WebSocket — no server-side rendering.
#### Scenario: Application loads
- **WHEN** a user navigates to the application URL
- **THEN** the React SPA loads and presents the login page (if unauthenticated) or dashboard (if authenticated)
### Requirement: Login and session management
The frontend SHALL present a login form and manage the authenticated session via HTTP-only session cookies. On successful login, the server sets a session cookie that is automatically included in subsequent API requests and WebSocket upgrade requests. Session expiry redirects to login.
#### Scenario: Login flow
- **WHEN** a user enters valid credentials on the login page
- **THEN** the server sets a session cookie and the frontend navigates to the dashboard
#### Scenario: Session expiry
- **WHEN** an API call returns 401 during an active session (cookie expired or invalidated)
- **THEN** the frontend redirects to the login page
### Requirement: Navigation structure
The frontend SHALL provide a sidebar navigation matching the Bucket 1 functional areas: Dashboard, Ledgers (Chart of Accounts, Inspect Ledgers, Balance Sheet, P&L, Budget vs Actual), Financial (Expense Claims, Inbound Invoices, Outbound Invoices, Payouts), Crypto Treasury, End-of-Month, Administration (Organization Settings, Users).
#### Scenario: Navigate to ledger page
- **WHEN** a user clicks "Balance Sheet" in the navigation
- **THEN** the balance sheet page loads with data for the active organization
### Requirement: Ledger pages
The frontend SHALL implement pages for: chart of accounts (tree view, create/edit/close accounts), inspect ledgers (account + date range → transaction rows), balance sheet (as-of date), P&L (fiscal year), and budget vs actual (year view with variance).
#### Scenario: Inspect ledger with date range
- **WHEN** a user selects an account and date range on the inspect ledgers page
- **THEN** transaction rows for that account and period are displayed with running balance
#### Scenario: Chart of accounts tree
- **WHEN** a user views the chart of accounts
- **THEN** accounts are displayed in a hierarchical tree grouped by type (Asset, Debt, Income, Cost)
### Requirement: Financial workflow pages
The frontend SHALL implement pages for: expense claim submission (with document upload), inbound invoice registration, outbound invoice creation, attestation queue (list of items pending the user's attestation), receipt validation, and payout management.
#### Scenario: Submit expense claim with manual VAT
- **WHEN** a user fills out the expense claim form, enters the total and the VAT amount exactly as shown on the receipt, and uploads the receipt
- **THEN** the claim is submitted via the API with the manually entered VAT amount
#### Scenario: Inbound invoice with manual VAT
- **WHEN** a user registers a supplier invoice with a VAT amount
- **THEN** the VAT field accepts manual entry (no rate computation) matching the invoice exactly
#### Scenario: Outbound invoice with default VAT
- **WHEN** a user creates an outbound invoice in a VAT-enabled org
- **THEN** the VAT amount is pre-filled from the org's default rate applied to the net amount, and the user can override it
#### Scenario: Attestation queue
- **WHEN** a budget owner views the attestation page
- **THEN** they see all expenses and invoices pending their attestation with approve/reject actions
### Requirement: Crypto treasury page
The frontend SHALL display the hot wallet overview: total balance per chain (BCH in Bucket 1), list of wallet addresses with individual balances, recent deposits and payouts, and fiat equivalent using current exchange rates.
#### Scenario: View crypto treasury
- **WHEN** a user navigates to the crypto treasury page
- **THEN** they see the total BCH balance, address list, and fiat equivalent
### Requirement: End-of-month page
The frontend SHALL implement the end-of-month workflow page with the monthly checklist, bank statement upload, and year-end close link when applicable.
#### Scenario: View end-of-month
- **WHEN** a user navigates to the end-of-month page
- **THEN** they see the checklist for the current month with actionable items
### Requirement: Administration pages
The frontend SHALL implement pages for: organization settings (name, currency, logo), and user management (list users, create user, assign roles, deactivate user).
#### Scenario: Manage users
- **WHEN** an administrator navigates to user management
- **THEN** they see a list of users with their roles and can create, edit, or deactivate users
### Requirement: Localization
The frontend SHALL support multiple languages: English (primary), Swedish (secondary), and German (should-have). Translation uses a JSON-based i18n system (e.g., react-i18next). Language selection is per-user (stored in user preferences). AI-assisted translation generates initial packs; Swedish reviewed by human translator.
#### Scenario: Switch language
- **WHEN** a user selects Swedish as their preferred language
- **THEN** all UI labels, menu items, and system messages are displayed in Swedish
#### Scenario: Fallback to English
- **WHEN** a translation key is missing in the selected language
- **THEN** the system falls back to the English translation
### Requirement: Smart monetary input component
The frontend SHALL provide a reusable monetary input component that accepts flexible numeric input (handling both decimal commas and decimal points as decimal separators), interprets the value as a currency amount, and displays the formatted result so the user can confirm the interpretation was correct. The component SHALL display the formatted amount in the organization's currency format after the user finishes typing.
#### Scenario: Decimal point input
- **WHEN** a user types "1234.50" into a monetary input
- **THEN** the component interprets this as 1234 units and 50 cents and displays the formatted result (e.g., "1,234.50" or "1 234,50" depending on locale)
#### Scenario: Decimal comma input
- **WHEN** a user types "1234,50" into a monetary input
- **THEN** the component interprets this as 1234 units and 50 cents (not one million two hundred thirty-four thousand fifty)
#### Scenario: Ambiguous input resolved
- **WHEN** a user types "1.234" into a monetary input
- **THEN** the component makes a qualified guess based on locale conventions (likely 1234 in European locale, 1.23 in US locale) and displays the formatted result so the user can verify
#### Scenario: Confirmation feedback
- **WHEN** the component finishes interpreting the input
- **THEN** the formatted amount is displayed clearly so the user can see whether the system understood their input correctly before submitting
### Requirement: Smart date input component
The frontend SHALL provide a reusable date input component that accepts flexible date entry (various formats like YYYY-MM-DD, DD/MM/YYYY, MM/DD/YYYY) and displays the interpreted date in a consistent format so the user can confirm correctness.
#### Scenario: ISO date input
- **WHEN** a user types "2025-03-15"
- **THEN** the component interprets this as March 15, 2025 and displays it in the locale-appropriate format
#### Scenario: Ambiguous date resolved
- **WHEN** a user types "03/04/2025"
- **THEN** the component interprets it based on locale conventions and displays the full result (e.g., "April 3, 2025" or "March 4, 2025") so the user can verify
### Requirement: Organization switcher
The frontend SHALL provide an organization switcher (in the top bar or navigation) for users with access to multiple organizations. Switching reloads all data for the new organization context.
#### Scenario: Switch organization
- **WHEN** a user selects a different organization from the switcher
- **THEN** all page data reloads scoped to the newly selected organization
@@ -0,0 +1,30 @@
## ADDED Requirements
### Requirement: Multi-tenant organization model
The system SHALL support multiple organizations on a single instance. Each organization is a flat entity (no tree hierarchy) with its own financial accounts, transactions, users, and settings. All data queries are scoped to the active organization.
#### Scenario: Create organization
- **WHEN** a system administrator creates a new organization with a name and default currency
- **THEN** the organization is created with a standard chart of accounts and ready for use
#### Scenario: Data isolation
- **WHEN** a user queries financial data while working in Organization A
- **THEN** only Organization A's accounts, transactions, and documents are visible
### Requirement: Organization settings
Each organization SHALL have configurable settings including: name, default currency, closed-through year, organization logo, VAT enabled flag, default VAT rate (percentage for outbound invoice pre-fill), VAT report frequency, economy enabled flag, first fiscal year, government registration ID, tax authority, tax account, and financial mail name/address. These are denormalized from v5 ObjectOptionalData into first-class columns.
#### Scenario: Update organization name
- **WHEN** an authorized user changes the organization name
- **THEN** the new name is reflected across the UI
#### Scenario: View closed-through year
- **WHEN** a user views organization settings
- **THEN** the current closed-through fiscal year is displayed
### Requirement: Organization switching
A user with access to multiple organizations SHALL be able to switch between them. The active organization determines the scope of all subsequent operations.
#### Scenario: Switch organization
- **WHEN** a user with access to organizations A and B switches from A to B
- **THEN** all subsequent data views and operations are scoped to organization B
@@ -0,0 +1,53 @@
## ADDED Requirements
### Requirement: User identity
The system SHALL maintain user accounts with: name, email, password hash, and active/inactive status. Users replace the v5 "People" and "Members" concepts — there is no membership lifecycle, only user accounts with system access.
#### Scenario: Create user
- **WHEN** an administrator creates a new user with name, email, and initial password
- **THEN** the user account is created and can log in
#### Scenario: Deactivate user
- **WHEN** an administrator deactivates a user
- **THEN** the user can no longer log in but their historical data (transaction authorship, attestations) is preserved
### Requirement: Authentication
The system SHALL support password-based authentication. Login produces a session/token that authenticates subsequent API requests. Failed login attempts SHALL be rate-limited.
#### Scenario: Successful login
- **WHEN** a user submits valid credentials
- **THEN** an authenticated session is established and the user is directed to the dashboard
#### Scenario: Failed login
- **WHEN** a user submits invalid credentials
- **THEN** the system rejects the attempt with a generic error (not revealing whether the email or password was wrong)
#### Scenario: Password reset
- **WHEN** a user requests a password reset
- **THEN** a reset link is sent to their registered email
### Requirement: Instance-level RBAC
The system SHALL implement role-based access control at the instance level. Users are assigned one or more roles. Each role has a set of permissions from the permission enum. Permission checks are enforced on API endpoints.
#### Scenario: Assign role to user
- **WHEN** an administrator assigns a role to a user
- **THEN** the user gains all permissions associated with that role
#### Scenario: Permission check on API call
- **WHEN** a user calls an API endpoint requiring a specific permission
- **THEN** the system checks whether any of the user's roles include that permission and rejects the call if not
#### Scenario: Role with multiple permissions
- **WHEN** a role is configured with permissions CanViewLedgers and CanAttestExpenses
- **THEN** users with that role can both view ledgers and attest expense claims
### Requirement: Dev-mode impersonation
The system SHALL support a development-mode-only feature where a developer can bypass login and assume administrator access. This feature MUST be disabled in production builds via configuration.
#### Scenario: Dev impersonation active
- **WHEN** the system runs in development mode and a developer activates impersonation
- **THEN** the developer is authenticated as a system administrator without credentials
#### Scenario: Dev impersonation blocked in production
- **WHEN** the system runs in production mode
- **THEN** the impersonation endpoint is not registered and returns 404
+184
View File
@@ -0,0 +1,184 @@
## 1. Solution Scaffolding & CI
- [ ] 1.1 Create .NET 8 SDK-style solution with projects: UsingCash.Common, UsingCash.Basic, UsingCash.Database, UsingCash.Logic, UsingCash.Api, UsingCash.Backend, UsingCash.Migration, UsingCash.Tests
- [ ] 1.2 Set up project references: Common ← Basic ← Database ← Logic ← Api/Backend/Migration; Tests → Common, Basic, Database, Logic, Api, Migration
- [ ] 1.3 Add NuGet dependencies: MySqlConnector, NBitcoin, System.Text.Json; remove all checked-in DLLs from External Libraries
- [ ] 1.4 Scaffold React + TypeScript + Vite frontend project in `frontend/` with MUI, react-router, react-i18next dependencies
- [ ] 1.5 Create multi-stage Dockerfile (build .NET + build frontend → runtime image serving both)
- [ ] 1.6 Create Gitea Actions workflow: dotnet restore → build → analyze/lint → test → npm ci → npm run lint → npm run build → docker build → push image
- [ ] 1.7 Add `appsettings.json` / `appsettings.Development.json` with database config section preserving read/write/admin credential structure, SMTP config, storage root path, dev-mode flag
## 2. Database Schema — Core Tables
- [ ] 2.1 Design and write DDL for Organizations table (denormalized from ObjectOptionalData: Currency, FirstFiscalYear, ClosedThroughYear, VatEnabled, DefaultVatRatePercent, VatReportFrequencyMonths, EconomyEnabled, GovtRegistrationId, TaxAuthority, TaxAccount, TaxOcr, FinancialMailName, FinancialMailAddress, LogoLandscape, LogoSquare)
- [ ] 2.2 Design and write DDL for Users table (Name, Email, PasswordHash, Active, PreferredCulture, BankName, BankClearing, BankAccount, BitcoinPayoutAddress, NeverMail, ResetPasswordTicket)
- [ ] 2.3 Design and write DDL for Roles, UserRoles, RolePermissions tables
- [ ] 2.4 Design and write DDL for FinancialAccounts table (including OwnerUserId, NativeCurrencyId, BitcoinPublicAddress, BitcoinPrivateRoot, BitcoinPublicRoot, BankTransactionTag, EnabledForExpensing, EnabledForInvoicing, AutomationProfileId, OpenedYear, ClosedYear)
- [ ] 2.5 Design and write DDL for FinancialTransactions table (including OrganizationSequenceId, BlockchainHash, ImportSha256)
- [ ] 2.6 Design and write DDL for FinancialTransactionRows table (including ForeignCurrencyCode, ForeignCurrencyAmountCents, BitcoinDerivationPath)
- [ ] 2.7 Design and write DDL for FinancialTransactionDependencies table (for continuation chains and business object links)
- [ ] 2.8 Design and write DDL for FinancialTransactionTags, TagSets, TagTypes tables
- [ ] 2.9 Design and write DDL for FinancialAccountBudgets table (monthly/yearly)
## 3. Database Schema — AP/AR & Support Tables
- [ ] 3.1 Design and write DDL for ExpenseClaims table (including VatCents, status lifecycle columns)
- [ ] 3.2 Design and write DDL for InboundInvoices table (including Description, VatCents, ExactBitcoinAmountSatoshis, NativeCurrencyCode, NativeCurrencyAmountCents)
- [ ] 3.3 Design and write DDL for OutboundInvoices and OutboundInvoiceItems tables (including VatCents, CreditedWithInvoice, CreditsInvoice, ToUserId)
- [ ] 3.4 Design and write DDL for Payouts, PayoutItems, Payments, PaymentGroups, Refunds tables
- [ ] 3.5 Design and write DDL for Documents and FinancialAccountDocuments tables
- [ ] 3.6 Design and write DDL for Currencies, ExchangeRateSnapshots, ExchangeRateDatapoints tables
- [ ] 3.7 Design and write DDL for CryptoChains, HotWalletAddresses, HotWalletUtxos tables
- [ ] 3.8 Design and write DDL for MailQueue, MailTemplates, EventQueue, SystemSettings tables
## 4. Database Schema — Stored Procedures & Security
- [ ] 4.1 Write stored procedures for financial transaction writes: CreateFinancialTransaction (with OrganizationSequenceId generation), AddTransactionRow, SetTransactionTag, SetTransactionDependency
- [ ] 4.2 Write stored procedures for financial account writes: CreateFinancialAccount, SetAccountName, SetAccountClosed, SetAccountOwner, SetBudget
- [ ] 4.3 Write stored procedures for expense claim writes: CreateExpenseClaim, SetExpenseClaimStatus, SetExpenseClaimAttested, SetExpenseClaimValidated
- [ ] 4.4 Write stored procedures for invoice writes: CreateInboundInvoice, SetInboundInvoiceStatus, CreateOutboundInvoice, SetOutboundInvoicePaid
- [ ] 4.5 Write stored procedures for payout/payment writes: CreatePayout, SetPayoutExecuted, CreatePayment, CreatePaymentGroup
- [ ] 4.6 Write stored procedures for user/org/crypto/document/mail/event writes
- [ ] 4.7 Write SQL trigger on FinancialTransactionRows rejecting direct inserts/updates/deletes where the transaction date falls within a closed fiscal period
- [ ] 4.8 Create MySQL users for read (SELECT only), write (EXECUTE on write procedures), and admin (DDL) with appropriate GRANTs
- [ ] 4.9 Write combined schema initialization script (all tables, procedures, triggers, users)
## 5. Database Layer (UsingCash.Database)
- [ ] 5.1 Implement DatabaseConnection factory with GetForReading(), GetForWriting(), GetForAdmin() — Galera-aware: LAST_INSERT_ID always read on write connection
- [ ] 5.2 Implement RepositoryBase with shared helpers: GetCommand (stored proc), AddParameter, ExecuteScalar, ExecuteReader, ExecuteNonQuery
- [ ] 5.3 Implement FinancialRepository: read methods (GetAccount, GetTransaction, GetTransactionRows, GetRowForeignCurrency, GetAccountsForOrg, GetTransactionsForAccountInRange, GetUnbalancedTransactions, GetBudgets, GetTransactionDependency, GetTransactionFromDependency)
- [ ] 5.4 Implement FinancialRepository: write methods wrapping stored procedures (CreateTransaction, AddRow, SetTag, SetDependency, CreateAccount, SetAccountName, SetAccountClosed, SetBudget, AdvanceClosedThroughYear)
- [ ] 5.5 Implement ApArRepository: read/write for expense claims, inbound/outbound invoices, payouts, payments, refunds
- [ ] 5.6 Implement UserRepository: read/write for users, roles, role assignments, permission lookups, password hash/verify
- [ ] 5.7 Implement OrganizationRepository: read/write for organizations and all denormalized settings
- [ ] 5.8 Implement CryptoRepository: read/write for hot wallet addresses, UTXOs, blockchain transactions
- [ ] 5.9 Implement DocumentRepository: read/write for document metadata and financial account documents
- [ ] 5.10 Implement CurrencyRepository: read/write for currencies, exchange rate snapshots and datapoints (micro-BTC scaling aware)
- [ ] 5.11 Implement SupportRepository: mail queue, mail templates, event queue, system settings
## 6. Common & Basic Layers
- [ ] 6.1 Port enums to UsingCash.Common: FinancialAccountType, Permission, DocumentType, CryptoChain, ExpenseClaimStatus, InvoiceStatus, PayoutStatus, FinancialDependencyType — trimming governance/geography/membership enums
- [ ] 6.2 Port IHasIdentity interface and shared attributes/interfaces to UsingCash.Common
- [ ] 6.3 Port Basic types: BasicFinancialAccount (with OwnerUserId, NativeCurrencyId), BasicFinancialTransaction (with OrganizationSequenceId, BlockchainHash), BasicFinancialTransactionRow (with ForeignCurrencyCode, ForeignCurrencyAmountCents), BasicCurrency, BasicOrganization (with all denormalized settings), BasicUser, BasicDocument, BasicExpenseClaim, BasicInboundInvoice, BasicOutboundInvoice, BasicPayout, BasicHotWalletAddress, BasicHotWalletUtxo
- [ ] 6.4 Implement Money value type (Int64 Cents, Currency reference, display formatting per currency unit scale, ToCurrency using double intermediate arithmetic)
## 7. Logic Layer (UsingCash.Logic)
- [ ] 7.1 Implement SingularFactory and PluralBase<TPlural, TSingular, TBasic> with startup-time cache warming and fail-fast on missing mappings
- [ ] 7.2 Implement FinancialAccount (extends BasicFinancialAccount): balance computation, budget access, rename/close with closed-period enforcement, budget owner
- [ ] 7.3 Implement FinancialTransaction (extends BasicFinancialTransaction): AddRow with closed-period check AND continuation transaction creation/reuse, dependency tracking, ContinuedTransaction property, AddContinuedTransactionsToLookup, RecalculateTransaction across chain
- [ ] 7.4 Implement reporting logic: BalanceSheet, ProfitAndLoss, BudgetVsActual
- [ ] 7.5 Implement period closing logic: precondition checks, closing journal creation (Dec 31), advance ClosedThroughYear
- [ ] 7.6 Implement VAT booking in expense/invoice creation: split net amount to budget and VAT to VatInbound/VatOutbound accounts when VatEnabled and vatCents > 0
- [ ] 7.7 Implement ExpenseClaim lifecycle: create (with VAT split) → attest (self-attestation allowed) → validate → approve → payout, with closed-year date bumping
- [ ] 7.8 Implement InboundInvoice logic with VAT split, ledger transaction generation, attestation workflow
- [ ] 7.9 Implement OutboundInvoice logic with VAT split, ledger transaction generation, credit linking
- [ ] 7.10 Implement Payout logic: group approved items, execute (record ledger transactions), confirm
- [ ] 7.11 Implement Currency and ExchangeRateService: GetConversionRate via BTC hub with micro-BTC scaling and BCH exception, TakeSnapshot using IRateProvider chain
- [ ] 7.12 Implement BitPayRateProvider with proper JSON deserialization, micro-BTC scaling, BCH exception, response validation, and error handling
- [ ] 7.13 Implement IBlockchainProvider interface and BchBlockchainProvider (address generation, UTXO queries, tx building via NBitcoin)
- [ ] 7.14 Implement HotWallet logic: track addresses/UTXOs, detect deposits, build payout transactions, compute balances
- [ ] 7.15 Implement User and Authority: authentication (password hash/verify), role-based permission checks, session management (cookie-based)
- [ ] 7.16 Implement Organization logic: create, settings (all denormalized columns), switching, data scoping
- [ ] 7.17 Implement Document and IDocumentStorage with LocalFilesystemStorage (yyyy/mm/dd path structure, configurable root supporting legacy /var/lib/swarmops/upload/ path)
- [ ] 7.18 Implement DashboardTasks: generate tasks from pending attestations, unvalidated receipts, pending payouts
- [ ] 7.19 Implement MailService: enqueue with template rendering, placeholder substitution
- [ ] 7.20 Implement EventBus: enqueue typed events, dequeue and dispatch, retention/purge
## 8. Data Migration (UsingCash.Migration) — gates API/frontend work
- [ ] 8.1 Implement CLI tool structure: connection string args for v5 (read-only) and v6 (write), run/verify/audit modes
- [ ] 8.2 Implement ObjectOptionalData audit: read all v5 EAV rows, classify each key as keep/drop per D16 mapping, report any unmapped keys
- [ ] 8.3 Implement organization migration: read v5 Organizations + ObjectOptionalData → write v6 Organizations (flat, denormalized settings, drop ParentOrganizationId and geography)
- [ ] 8.4 Implement user migration: read v5 People + ObjectOptionalData → write v6 Users (name, email, bank details, bitcoin payout, preferred culture, require-password-reset flag)
- [ ] 8.5 Implement auth/role migration: map v5 position/access assignments to v6 role assignments; document the mapping
- [ ] 8.6 Implement financial account migration: read v5 FinancialAccounts + ObjectOptionalData → write v6 FinancialAccounts (denormalized, drop geography)
- [ ] 8.7 Implement financial transaction migration: read v5 FinancialTransactions → write v6 (preserve OrganizationSequenceId, BlockchainHash, ImportSha256)
- [ ] 8.8 Implement financial transaction row migration: read v5 FinancialTransactionRows + FinancialTransactionRowsNativeCurrency → write v6 rows with foreign currency columns
- [ ] 8.9 Implement continuation chain migration: read v5 FinancialTransactionDependencies → write v6 dependencies (preserve all types including FinancialTransaction chains)
- [ ] 8.10 Implement tag/budget migration: transaction tags, tag sets, tag types, budget allocations
- [ ] 8.11 Implement AP/AR migration: expense claims, inbound invoices (with Description, ExactBitcoinAmountSatoshis, native currency), outbound invoices (with credit links, ToUserId), payouts, payments, refunds
- [ ] 8.12 Implement currency and exchange rate migration: currencies, snapshots, datapoints (preserve micro-BTC scaling and BCH exception)
- [ ] 8.13 Implement crypto migration: hot wallet addresses, UTXOs
- [ ] 8.14 Implement document metadata migration: document records with storage paths pointing to existing filesystem
- [ ] 8.15 Implement aggregate verification: render balance sheets and P&L for all closed periods from both v5 and v6, diff output
- [ ] 8.16 Implement account-level verification: per-account-per-year transaction totals comparison
- [ ] 8.17 Implement transaction-level spot checks and per-org-per-year checksum validation
- [ ] 8.18 Implement idempotent re-run: truncate/replace v6 data on repeated migration runs
## 9. API Layer (UsingCash.Api)
- [ ] 9.1 Configure ASP.NET Core host: DI registration for repositories and logic services, session-cookie auth middleware, org-scoping middleware, error response middleware
- [ ] 9.2 Implement auth endpoints: POST /api/auth/login, POST /api/auth/logout, POST /api/auth/reset-password, GET /api/auth/me
- [ ] 9.3 Implement financial account endpoints: GET/POST /api/organizations/{orgId}/accounts, PUT /api/organizations/{orgId}/accounts/{id} (including budget owner assignment)
- [ ] 9.4 Implement ledger endpoints: GET /api/organizations/{orgId}/ledger, GET .../balance-sheet, GET .../profit-loss, GET .../budget-vs-actual
- [ ] 9.5 Implement transaction endpoints: GET/POST /api/organizations/{orgId}/transactions, GET .../transactions/{id} (showing continuation chains)
- [ ] 9.6 Implement expense claim endpoints: GET/POST /api/organizations/{orgId}/expense-claims (with VAT), POST .../attest, POST .../validate
- [ ] 9.7 Implement invoice endpoints: GET/POST for inbound-invoices (with VAT) and outbound-invoices (with VAT), attestation and payment actions
- [ ] 9.8 Implement payout endpoints: GET/POST /api/organizations/{orgId}/payouts, POST .../execute, POST .../confirm
- [ ] 9.9 Implement crypto endpoints: GET /api/organizations/{orgId}/crypto/treasury, GET .../addresses, POST .../payouts
- [ ] 9.10 Implement document endpoints: POST /api/organizations/{orgId}/documents (upload), GET .../documents/{id} (download)
- [ ] 9.11 Implement dashboard endpoints: GET /api/organizations/{orgId}/dashboard, GET .../tasks
- [ ] 9.12 Implement end-of-month endpoints: GET /api/organizations/{orgId}/end-of-month/checklist, POST .../upload-statement, POST .../close-year
- [ ] 9.13 Implement organization endpoints: GET/PUT /api/organizations/{orgId} (all denormalized settings), GET /api/organizations
- [ ] 9.14 Implement user management endpoints: GET/POST/PUT /api/users, POST /api/users/{id}/roles
- [ ] 9.15 Implement WebSocket endpoint for real-time notifications (deposit alerts, task changes, heartbeat status) with session-cookie auth on upgrade
- [ ] 9.16 Configure static file serving for React SPA with fallthrough to index.html
- [ ] 9.17 Implement dev-mode impersonation endpoint (disabled in production via configuration)
## 10. Frontend Application
- [ ] 10.1 Set up React project structure: routing, API client module, auth context (session cookies), org context, MUI theme, react-i18next with EN/SV/DE translation files
- [ ] 10.2 Implement reusable smart input components: monetary input (handles decimal commas/points, shows formatted confirmation) and date input (flexible format entry, shows interpreted date for verification)
- [ ] 10.3 Implement login page and auth flow (session cookie management, 401 redirect)
- [ ] 10.4 Implement app shell: sidebar navigation, top bar with org switcher and language selector, responsive layout
- [ ] 10.5 Implement dashboard page: task summary, YTD P&L, quick links, end-of-month status
- [ ] 10.6 Implement chart of accounts page: tree view with account types, create/edit/close/assign-owner actions
- [ ] 10.7 Implement inspect ledgers page: account selector, date range picker, transaction row table with running balance and continuation chain links
- [ ] 10.8 Implement balance sheet page: as-of date selector, asset/debt/equity breakdown
- [ ] 10.9 Implement profit & loss page: fiscal year selector, income/cost breakdown
- [ ] 10.10 Implement budget vs actual page: year selector, account-level budget/actual/variance table
- [ ] 10.11 Implement expense claim pages: submission form with smart monetary input for amount and VAT (when org VatEnabled), document upload, list view, attestation/validation actions
- [ ] 10.12 Implement inbound invoice pages: registration form with smart monetary input for amount and VAT, smart date input for issue/due dates, list view, attestation action
- [ ] 10.13 Implement outbound invoice pages: creation form with line items, VAT pre-filled from org default rate (editable for cross-border/exempt) using smart monetary input, list view, mark-paid action
- [ ] 10.14 Implement payout management page: group items, execute, confirm
- [ ] 10.15 Implement crypto treasury page: wallet balance, address list, UTXO details, fiat equivalent, deposit/payout history
- [ ] 10.16 Implement end-of-month page: monthly checklist, bank statement upload (manual review), year-end close link
- [ ] 10.17 Implement organization settings page: all denormalized settings (name, currency, default VAT rate, VAT config, tax IDs, logo)
- [ ] 10.18 Implement user management page: user list, create/edit/deactivate, role assignment
- [ ] 10.19 Implement WebSocket client for real-time notifications (deposit alerts, task updates)
- [ ] 10.20 Generate initial Swedish and German translation packs; human review for Swedish
## 11. Backend Worker (UsingCash.Backend)
- [ ] 11.1 Implement IHostedService-based worker with configurable task intervals and DI integration
- [ ] 11.2 Implement schema version check on startup with auto-migration using admin credentials
- [ ] 11.3 Implement exchange rate snapshot task (periodic, using IRateProvider chain with micro-BTC scaling)
- [ ] 11.4 Implement mail queue processing task (dequeue pending, deliver via SMTP, update status)
- [ ] 11.5 Implement blockchain monitoring task (query chain provider for new deposits, ingest to ledger, skip closed periods)
- [ ] 11.6 Implement heartbeat task (update timestamp in system settings)
- [ ] 11.7 Implement event bus consumption task (dequeue events, dispatch to handlers, purge old events)
- [ ] 11.8 Implement forex P&L recalculation task (weekly, per foreign-currency account)
- [ ] 11.9 Implement automated payout cycle task (every 5 minutes, process approved payouts)
## 12. Bootstrap & Deployment
- [ ] 12.1 Implement database seeding: first-run bootstrap that creates initial admin user, system administrator role, and first organization
- [ ] 12.2 Write deployment documentation: Docker run instructions, database setup, credential configuration, storage path setup
- [ ] 12.3 Verify end-to-end: fresh deployment → seed → migration from v5 → verify → serve production traffic
## 13. Testing
- [ ] 13.1 Write unit tests for Money type (storage, conversion with double arithmetic, display formatting across fiat and crypto)
- [ ] 13.2 Write unit tests for period closing logic (preconditions, closing journal, advancement, rejection cases)
- [ ] 13.3 Write unit tests for continuation transactions (create chain, recurse, recalculate across chain, edge cases)
- [ ] 13.4 Write unit tests for expense claim lifecycle (state transitions, self-attestation allowed, closed-year date bumping, VAT splits)
- [ ] 13.5 Write unit tests for exchange rate conversion (BTC hub model, micro-BTC scaling, BCH exception, cross-rate derivation, missing rate handling)
- [ ] 13.6 Write unit tests for RBAC (role assignment, permission check, missing permission rejection)
- [ ] 13.7 Write integration tests for FinancialRepository against a test MySQL database (including foreign currency rows and continuation dependencies)
- [ ] 13.8 Write integration tests for migration tool against v5 test fixtures (including ObjectOptionalData denormalization, continuation chains, foreign currency, VAT-split rows)
- [ ] 13.9 Write API integration tests for auth, ledger reads, expense claim workflow (with VAT), permission enforcement
- [ ] 13.10 Write SingularFactory tests verifying all Basic→Logic type mappings resolve at startup
- [ ] 13.11 Write migration verification tests: confirm aggregate, account-level, and transaction-level checks catch introduced discrepancies
+26
View File
@@ -0,0 +1,26 @@
schema: spec-driven
context: |
Legacy codebase "Swarmops" being modernized as "using.cash" (v6).
Originally a Pirate Party membership register (~20 years old), pivoted to crypto-centric accounting.
Current stack: C# on .NET Framework 4.5.2 / Mono, ASP.NET WebForms frontend, MySQL, hand-written ADO.NET (SwarmDb partial class), stored procedures for all writes, read/write/admin credential split.
Target stack: C# on .NET 8+ / ASP.NET Core (backend), React + Material UI + TypeScript + Vite (frontend), MySQL, Gitea Actions CI, Docker.
Namespace rename: Swarmops.* → UsingCash.*
Key preserved patterns: Basic/Logic two-tier inheritance, PluralBase<T> collections, stored procedure writes, read/write/admin DB credential split, Money as Int64 smallest-units, exchange rates via BTC hub.
Domain: double-entry accounting, AP/AR, crypto treasury (BCH-first, abstractable), multi-tenant organizations, RBAC.
v5 database preserved untouched; v6 gets a clean schema via one-time ETL migration. Closed ledger periods are legally presentation-immutable.
rules:
proposal:
- Reference the three scope buckets (Working Rewrite, First Beyond Working, Maybe/Later)
- Include a Non-goals section for permanently cut features
tasks:
- Group tasks by subsystem (database, backend, frontend, migration, CI)
- Each task should be independently implementable and testable
- Prefer smaller tasks that can be completed in a focused session
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage:"
echo " $0 create <topic> [base-branch]"
echo " $0 list"
echo " $0 remove <topic>"
exit 1
}
sanitize_topic() {
local topic="${1:-}"
if [[ -z "$topic" ]]; then
usage
fi
echo "$topic" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr -cd 'a-z0-9._-'
}
cmd="${1:-}"
case "$cmd" in
create)
topic="$(sanitize_topic "${2:-}")"
base="${3:-falken-qol}"
branch="agent/${topic}"
wt_root=".worktree"
wt_path="${wt_root}/${topic}"
mkdir -p "$wt_root"
if [[ -e "$wt_path" ]]; then
echo "Worktree path already exists: $wt_path"
exit 1
fi
git fetch --all --prune
git worktree add "$wt_path" -b "$branch" "$base"
{
echo "owner=${USER:-unknown}"
echo "task=${topic}"
echo "branch=${branch}"
date -u +"created_at=%Y-%m-%dT%H:%M:%SZ"
} > "${wt_path}/.agent-lock"
echo "Created worktree: $wt_path"
echo "Branch: $branch"
;;
list)
git worktree list
;;
remove)
topic="$(sanitize_topic "${2:-}")"
wt_path=".worktree/${topic}"
if [[ ! -d "$wt_path" ]]; then
echo "Worktree path not found: $wt_path"
exit 1
fi
git worktree remove "$wt_path"
echo "Removed worktree: $wt_path"
;;
*)
usage
;;
esac