Skip to content

Latest commit

 

History

History
executable file
·
972 lines (784 loc) · 41 KB

File metadata and controls

executable file
·
972 lines (784 loc) · 41 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Canonical URI: chittycanon://core/services/chittyfinance | Tier 3 (Service Layer) | finance.chitty.cc

Project Overview

ChittyFinance is a full-stack financial management platform for the ChittyOS ecosystem. It provides intelligent financial tracking, AI-powered advice, recurring charge optimization, and integrations with Mercury Bank, Wave Accounting, and Stripe payments.

Architecture: Hono on Cloudflare Workers (production) + legacy Express (local dev). PostgreSQL (Neon) with Drizzle ORM. React frontend.

Essential Commands

Development

npm install              # Install dependencies
npm run dev              # Auto-detect mode and start dev server on port 5000
npm run dev:standalone   # Start in standalone mode (local development)
npm run dev:system       # Start in system mode (ChittyOS integration)
npm run check            # TypeScript type checking
npm run mode:detect      # Detect and display current mode
npm run mode:setup       # Setup mode configuration (script not yet implemented)

Build & Deployment

npm run build            # Build system mode (default for production)
npm run build:standalone # Build standalone mode (outputs to dist/standalone)
npm run build:system     # Build system mode (outputs to dist/system)
npm run build:both       # Build both modes
npm run start            # Run standalone production build locally
npm run deploy           # Deploy to Cloudflare Workers (system mode)
npm run deploy:staging   # Deploy to staging environment
npm run deploy:production # Deploy to production environment

Database Operations

npm run db:push              # Push schema changes (uses current drizzle.config.ts)
npm run db:push:system       # Push system schema to PostgreSQL
npm run db:push:standalone   # Push standalone schema to SQLite
npm run db:seed              # Seed IT CAN BE LLC entity structure

First-Time Setup (System Mode):

MODE=system npm run db:push:system   # Create tables
npm run db:seed                      # Create tenants and users

First-Time Setup (Standalone Mode):

npm run db:push:standalone   # Create SQLite tables
# No seeding needed - single user mode

Critical:

  • Port 5001 is used in server/index.ts for local Express development
  • Server uses reusePort: true for multiple process support on the same port

Architecture

Dual-Mode Operation

ChittyFinance supports two operational modes (controlled by MODE environment variable):

Standalone Mode (default for local development):

  • SQLite database for quick local development
  • Single-tenant (no multi-tenancy overhead)
  • Simplified schema in database/standalone.schema.ts
  • Build output: dist/standalone/
  • Database file: ./chittyfinance.db
  • Run: npm run dev or npm run dev:standalone

System Mode (production - multi-tenant):

  • PostgreSQL (Neon) with full multi-tenancy
  • Supports IT CAN BE LLC entity structure
  • Complete schema in database/system.schema.ts
  • Build output: dist/system/
  • Cloudflare Workers deployment
  • Run: npm run dev:system
  • Deploy: npm run deploy or npm run deploy:production

Mode Detection:

  • Default: npm run dev runs in standalone mode
  • Explicitly set: MODE=system npm run dev
  • Auto-detection script: npm run mode:detect

Multi-Tenant Architecture (System Mode)

IT CAN BE LLC Entity Structure:

IT CAN BE LLC (holding)
├── JEAN ARLENE VENTURING LLC (personal, 85% owner)
├── Nicholas Bianchi (personal — income/mgmt assigned to JAV LLC)
│   ├── Lakeside Loft — 541 W Addison St #3S, Chicago IL
│   └── Cozy Castle — 550 W Surf St #504, Chicago IL
├── ARIBIA LLC (series, 100% owned)
│   ├── ARIBIA LLC - MGMT (management)
│   │   ├── Chicago Furnished Condos (consumer brand)
│   │   └── Chitty Services (vendor/tech services)
│   ├── ARIBIA LLC - CITY STUDIO (property)
│   │   └── City Studio — 550 W Surf St C211, Chicago IL
│   ├── ARIBIA LLC - APT ARLENE (property)
│   │   └── Villa Vista — 4343 N Clarendon #1610, Chicago IL
│   └── Morada Mami — Carrera 76A #53-215, Medellin, Colombia
└── ChittyCorp LLC (holding, pending formation)

Tenant Types:

  • holding - Holding companies (IT CAN BE LLC, ChittyCorp LLC)
  • series - Series LLCs (ARIBIA LLC)
  • property - Property holding entities (City Studio, Apt Arlene)
  • management - Management companies (ARIBIA LLC - MGMT)
  • personal - Personal entities (JEAN ARLENE VENTURING LLC, Nicholas Bianchi)

Key Features:

  • Each tenant has isolated financial data
  • Inter-company transaction tracking
  • Property-specific rent roll and lease management
  • User access control per tenant (roles: owner, admin, manager, viewer)
  • Consolidated reporting across entities

Tech Stack

  • Frontend: React 18 with TypeScript, Wouter (routing), shadcn/ui (Radix UI components)
  • Backend: Hono (Cloudflare Workers, production) / Express.js (legacy, local dev)
  • Database: Neon PostgreSQL with Drizzle ORM
  • Build: Vite (frontend), esbuild (backend)
  • Styling: Tailwind CSS with tailwindcss-animate
  • State: TanStack React Query for server state
  • Payments: Stripe integration
  • AI: OpenAI GPT-4o for financial advice

Project Structure

chittyfinance/
├── client/                 # React frontend (Vite root)
│   └── src/
│       ├── pages/         # Page components (Dashboard, Settings, Landing)
│       ├── components/    # Reusable UI components (shadcn/ui)
│       ├── hooks/         # Custom React hooks
│       └── lib/           # Client utilities
├── server/                # Hono backend (Cloudflare Workers)
│   ├── app.ts            # Hono app factory with middleware wiring
│   ├── env.ts            # HonoEnv type (Bindings + Variables)
│   ├── worker.ts         # Cloudflare Workers entry point
│   ├── index.ts          # Legacy Express entry (standalone dev)
│   ├── routes.ts         # Legacy Express routes (reference only)
│   ├── routes/            # Hono route modules (22 files)
│   │   ├── health.ts     # /health, /api/v1/status
│   │   ├── docs.ts       # /api/v1/documentation (OpenAPI spec)
│   │   ├── accounts.ts   # /api/accounts
│   │   ├── summary.ts    # /api/summary
│   │   ├── tenants.ts    # /api/tenants
│   │   ├── properties.ts # /api/properties (CRUD + financials + rent roll + P&L)
│   │   ├── transactions.ts # /api/transactions (+ CSV/OFX/QFX export)
│   │   ├── integrations.ts # /api/integrations
│   │   ├── allocations.ts # /api/allocations (inter-company rules + execution)
│   │   ├── tasks.ts      # /api/tasks
│   │   ├── ai.ts         # /api/ai-messages
│   │   ├── mercury.ts    # /api/mercury (via ChittyConnect)
│   │   ├── github.ts     # /api/github
│   │   ├── stripe.ts     # /api/integrations/stripe
│   │   ├── wave.ts       # /api/integrations/wave (OAuth)
│   │   ├── charges.ts    # /api/charges (recurring)
│   │   ├── forensics.ts  # /api/forensics (21 endpoints)
│   │   ├── valuation.ts  # /api/properties/:id/valuation (multi-source AVM)
│   │   ├── session.ts    # /api/session (KV-backed cookie auth)
│   │   ├── email.ts      # /api/email (Cloudflare Email Service)
│   │   ├── import.ts     # /api/import (TurboTenant, Mercury, HD Pro, Amazon CSV + Wave sync)
│   │   └── webhooks.ts   # Stripe/Mercury/Wave webhooks (per-tenant HMAC)
│   ├── middleware/        # auth, tenant, error middleware
│   ├── storage/           # SystemStorage (Drizzle queries)
│   ├── db/                # connection.ts (Neon HTTP), schema.ts
│   └── lib/               # Server utilities
│       ├── wave-api.ts           # Wave Accounting GraphQL client
│       ├── oauth-state-edge.ts   # Edge-compatible HMAC OAuth state
│       ├── chargeAutomation.ts   # Recurring charge analysis (stubs)
│       ├── forensicService.ts    # Forensic algorithms (legacy)
│       └── valuation/            # Property valuation providers
│           ├── types.ts          # ValuationProvider interface, AggregatedValuation
│           ├── zillow.ts         # Zillow via RapidAPI
│           ├── redfin.ts         # Redfin via RapidAPI
│           ├── housecanary.ts    # HouseCanary REST API
│           ├── attom.ts          # ATTOM Data Gateway
│           ├── county.ts         # Cook County Assessor (Socrata)
│           └── index.ts          # Provider registry + confidence-weighted aggregation
├── database/              # Schema definitions
│   ├── system.schema.ts   # Multi-tenant PostgreSQL (UUID-based)
│   └── standalone.schema.ts # Single-tenant SQLite
├── shared/                # Shared types and schemas
│   └── schema.ts         # Legacy schema with forensic tables (integer-ID)
└── deploy/
    └── system-wrangler.jsonc # Cloudflare Workers config (JSONC)

Database Architecture

System Mode Schema (Multi-Tenant PostgreSQL)

Location: database/system.schema.ts

Core Tables:

  • tenants - Legal entities (LLCs, properties, management companies)
  • users - User accounts with email/password + optional ChittyID
  • tenant_users - User access to tenants with role-based permissions
  • accounts - Bank accounts, credit cards (tenant-scoped)
  • transactions - Financial transactions with decimal precision
  • intercompany_transactions - Transfers between tenants

Property Management Tables:

  • properties - Real estate assets
  • units - Rental units (if property has multiple units)
  • leases - Tenant leases with rent and dates
  • property_valuations - Cached AVM estimates from external providers (Zillow, Redfin, HouseCanary, ATTOM, County)

Chart of Accounts & Classification Tables:

  • chart_of_accounts - Database-backed COA with tenant customization (NULL tenant_id = global defaults, 60 REI accounts seeded)
  • classification_audit - Audit trail for every COA code change on a transaction (trust level L0-L4, actor attribution)

Classification columns on transactions:

  • coa_code - Authoritative COA classification (L2+ executor writes)
  • suggested_coa_code - AI/keyword proposal (L1 writes, L3 auditor reviews)
  • classification_confidence - 0.000-1.000 score
  • classified_by / classified_at - Who set coa_code and when
  • reconciled_by / reconciled_at - L3 auditor who locked the transaction

Trust Path for Classification (executor/auditor segregation):

Level Role COA Permissions
L0 Ingest Executor Write to 9010 (suspense) only
L1 Suggest Executor Write suggested_coa_code, not coa_code
L2 Classify Executor Set coa_code on unreconciled transactions
L3 Reconcile Auditor Lock transactions, review L2 classifications
L4 Govern Auditor Modify the COA itself (add/rename/retire accounts)

Supporting Tables:

  • integrations - Mercury/Wave/Stripe API connections
  • tasks - Financial tasks
  • ai_messages - AI conversation history

Key Characteristics:

  • UUIDs for primary keys (better for distributed systems)
  • Decimal precision for all monetary amounts (12,2)
  • Full multi-tenancy with tenant isolation
  • Hierarchical tenants (parent-child relationships)
  • Indexed for performance (tenant_id, date, etc.)

Standalone Mode Schema (Single-Tenant SQLite)

Location: database/standalone.schema.ts

Simplified Tables:

  • users, accounts, transactions, properties, tasks, integrations

Key Characteristics:

  • Text IDs (simpler for SQLite)
  • Real (float) for amounts (acceptable for dev)
  • No multi-tenancy (single user)
  • Faster for local development

Database Connection

Mode-Aware Connection (server/db.ts):

The database connection automatically switches based on MODE environment variable:

System Mode (MODE=system):

// PostgreSQL (Neon) with multi-tenant schema
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzleNeon({ client: pool, schema: systemSchema });

Standalone Mode (MODE=standalone):

// SQLite for local development
const sqlite = new Database('./chittyfinance.db');
const db = drizzleBetterSqlite(sqlite, { schema: standaloneSchema });

Environment Variables:

  • System mode: DATABASE_URL (Neon PostgreSQL connection string)
  • Standalone mode: SQLITE_FILE (optional, defaults to ./chittyfinance.db)

Database Seeding (System Mode)

Seed Script: database/seeds/it-can-be-llc.ts

Creates the complete IT CAN BE LLC entity structure:

  1. IT CAN BE LLC (parent holding company)
  2. JEAN ARLENE VENTURING LLC (85% owner, personal income funnel)
  3. Nicholas Bianchi (personal — properties held individually, income/mgmt via JAV LLC)
  4. ARIBIA LLC (series parent)
  5. ARIBIA LLC - MGMT (management company with two brands)
  6. ARIBIA LLC - CITY STUDIO (property entity)
  7. ARIBIA LLC - APT ARLENE (property entity)
  8. ChittyCorp LLC (pending formation)

Also creates:

  • 5 property records: Lakeside Loft, Cozy Castle, City Studio, Villa Vista, Morada Mami
  • User accounts for Nicholas Bianchi and Sharon E Jones
  • Access permissions for each user to appropriate tenants

Run seeding:

npm run db:seed

Note: Only run after pushing the system schema (npm run db:push:system)

Storage Abstraction Layer

Critical Pattern: All database access goes through server/storage.ts. Never write direct Drizzle queries in routes.

⚠️ Important: The current server/storage.ts uses the old shared/schema.ts and needs to be updated to use database/system.schema.ts with tenant-aware queries.

Interface (server/storage.ts:12-42):

export interface IStorage {
  // User operations
  getUser(id: number): Promise<User | undefined>;
  getUserByUsername(username: string): Promise<User | undefined>;
  createUser(user: InsertUser): Promise<User>;

  // Integration operations
  getIntegrations(userId: number): Promise<Integration[]>;
  createIntegration(integration: InsertIntegration): Promise<Integration>;
  updateIntegration(id: number, integration: Partial<Integration>): Promise<Integration | undefined>;

  // Financial summary operations
  getFinancialSummary(userId: number): Promise<FinancialSummary | undefined>;
  createFinancialSummary(summary: InsertFinancialSummary): Promise<FinancialSummary>;

  // Transaction, Task, and AI Message operations...
}

Usage in routes (server/routes.ts):

import { storage } from "./storage";

const user = await storage.getUserByUsername("demo");
const summary = await storage.getFinancialSummary(user.id);

Key Features

1. Hybrid Authentication

Current implementation: Dual-path auth via hybridAuth middleware (server/middleware/auth.ts).

Path 1 — Service token (service-to-service):

  • Authorization: Bearer <CHITTY_AUTH_SERVICE_TOKEN> header
  • Used by ChittyConnect, MCP, and other ChittyOS services

Path 2 — Session cookie (browser clients):

  • cf_session cookie set by POST /api/session (login)
  • KV-backed (FINANCE_KV) with 7-day TTL
  • Session stores { userId }, resolved to full user by callerContext middleware

Session routes (server/routes/session.ts — public, no auth required):

  • GET /api/session — return current user from cookie
  • POST /api/session — login with { email, password }
  • DELETE /api/session — logout (clear cookie + KV)

Password hashing: SHA-256 (Web Crypto in Workers, Node crypto in seed script).

Frontend flow (client/src/App.tsx):

  1. On load, fetches GET /api/session with credentials: "include"
  2. If 401, redirects to /login
  3. Login form POSTs credentials, cookie is set, page reloads

Note: ChittyID integration is planned to replace email/password auth.

2. Financial Dashboard

  • Real-time financial summary: Cash on hand, revenue, expenses, outstanding invoices
  • Data source: Cached in financialSummaries table, fetched from integrations
  • Demo data: Hardcoded values if no summary exists (server/routes.ts:51-55)

3. AI Financial Advice

Location: server/lib/openai.ts

Model: GPT-4o (hardcoded, comment at line 3 warns against changing)

Functions:

  • getFinancialAdvice() - Conversational financial advice based on financial data
  • generateCostReductionPlan() - AI-generated cost reduction strategies

API endpoint: POST /api/ai/message sends user query to OpenAI with financial context

4. Recurring Charge Automation

Location: server/lib/chargeAutomation.ts

Capabilities:

  • Identify recurring charges from integrated services
  • Generate optimization recommendations (cancel, downgrade, consolidate, negotiate)
  • Calculate potential savings

API endpoints:

  • GET /api/recurring-charges - List all recurring charges
  • GET /api/recurring-charges/:id/optimizations - Get optimization suggestions
  • POST /api/recurring-charges/:id/manage - Execute management action

5. Third-Party Integrations (Phase 3 - COMPLETED)

Mercury Bank (server/lib/financialServices.ts:22-51, via ChittyConnect):

  • Real integration through ChittyConnect backend
  • Multi-account support with account selection
  • Static egress IP for bank compliance
  • Fetches balances and transactions
  • Falls back to minimal data in standalone mode
  • Routes: /api/mercury/accounts, /api/mercury/select-accounts
  • Configuration: Requires CHITTYCONNECT_API_BASE + CHITTYCONNECT_API_TOKEN

Wave Accounting (server/lib/wave-api.ts + server/lib/financialServices.ts:54-116):

  • Real integration via OAuth 2.0 + GraphQL API
  • Complete OAuth flow with CSRF protection (HMAC-signed state tokens)
  • Fetches invoices, expenses, and financial summaries
  • Automatic token refresh support
  • Routes: /api/integrations/wave/authorize, /callback, /refresh
  • Requirements: Wave Pro subscription, WAVE_CLIENT_ID, WAVE_CLIENT_SECRET
  • Security: Uses server/lib/oauth-state.ts for secure state token generation/validation

Stripe (server/lib/stripe.ts):

  • Real integration for payment processing
  • Customer management with tenant metadata
  • Checkout session creation (ad-hoc payments)
  • Webhook verification and idempotent event processing
  • Routes: /api/integrations/stripe/connect, /checkout, /webhook
  • Configuration: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET
  • Events stored in webhook_events table (see shared/finance.schema.ts)

DoorLoop (server/lib/financialServices.ts:119-147):

  • Mock data (property management)
  • Returns hardcoded rent roll and maintenance data
  • Real API integration pending

GitHub (server/lib/github.ts):

  • Real GitHub API integration (not mock)
  • Fetches repositories, commits, PRs, issues
  • Used for project cost attribution

Integration Status Monitoring:

  • New endpoint: GET /api/integrations/status (server/routes.ts:122-126)
  • Validates which integrations are properly configured
  • Uses server/lib/integration-validation.ts to check environment variables
  • Returns configuration status for wave, stripe, mercury, openai

Utilities

check_system_operations_duplicates.js

A utility script for analyzing and detecting duplicate operations in system mode. Located at the project root. This script helps maintain code quality when working with ChittyOS integration.

Development Workflows

Adding a New Feature

  1. Update database schema in shared/schema.ts:

    export const newTable = pgTable("new_table", {
      id: serial("id").primaryKey(),
      userId: integer("user_id").notNull().references(() => users.id),
      // ... fields
    });
  2. Run migration: npm run db:push

  3. Add storage methods in server/storage.ts:

    async getNewData(userId: number): Promise<NewData[]> {
      return await db.select().from(newTable).where(eq(newTable.userId, userId));
    }
  4. Create API routes in server/routes.ts:

    api.get("/new-data", async (req: Request, res: Response) => {
      const user = await storage.getUserByUsername("demo");
      const data = await storage.getNewData(user.id);
      res.json(data);
    });
  5. Build frontend in client/src/pages/:

    • Use TanStack Query for data fetching
    • Import shadcn/ui components from @/components/ui/

Working with AI Features

OpenAI Configuration (server/lib/openai.ts):

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const openai = OPENAI_API_KEY ? new OpenAI({ apiKey: OPENAI_API_KEY }) : null;

Best practices:

  • Model is GPT-4o (do not change without user request per comment)
  • Max tokens: 500 for financial advice
  • Include financial context in system prompt
  • Handle API errors gracefully (rate limits, invalid keys)
  • When OPENAI_API_KEY is not set, AI functions return rule-based fallback advice
  • OpenAI client is null when unconfigured — functions guard with if (!openai) early returns

Path Aliases

Configured in tsconfig.json:18-21:

{
  "@/*": ["./client/src/*"],
  "@shared/*": ["./shared/*"]
}

Additional alias in vite.config.ts:25:

"@assets": path.resolve(import.meta.dirname, "attached_assets")

Usage:

import { Button } from "@/components/ui/button";
import { users } from "@shared/schema";
import logo from "@assets/logo.png";

API Endpoints

Authentication (public — no auth required)

  • GET /api/session - Get current user from session cookie
  • POST /api/session - Login with email + password (sets cf_session cookie)
  • DELETE /api/session - Logout (clears cookie + KV entry)

Financial Data

  • GET /api/financial-summary - Get cached financial summary
  • GET /api/transactions - List transactions with optional filters

Integrations

  • GET /api/integrations - List configured integrations
  • GET /api/integrations/status - Check which integrations are properly configured
  • POST /api/integrations - Add new integration
  • PATCH /api/integrations/:id - Update integration credentials
  • GET /api/integrations/events - List webhook events with optional source filter
  • POST /api/admin/events/replay - Replay webhook events to ChittyOS services

Wave Accounting

  • GET /api/integrations/wave/authorize - Start OAuth flow (returns authorization URL)
  • GET /api/integrations/wave/callback - OAuth callback handler (redirects to /connections)
  • POST /api/integrations/wave/refresh - Refresh expired access token

Stripe

  • POST /api/integrations/stripe/connect - Create/fetch Stripe customer
  • POST /api/integrations/stripe/checkout - Create ad-hoc payment session
  • POST /api/integrations/stripe/webhook - Stripe webhook endpoint (signature verified)

Mercury Bank

  • GET /api/mercury/accounts - List available Mercury accounts via ChittyConnect
  • POST /api/mercury/select-accounts - Select which accounts to sync
  • POST /api/integrations/mercury/webhook - Mercury webhook endpoint (authenticated)

Recurring Charges

  • GET /api/charges/recurring - List recurring charges from integrations
  • GET /api/charges/optimizations - Get optimization recommendations
  • POST /api/charges/manage - Cancel/modify a recurring charge

AI Services

  • POST /api/ai/advice - Get initial AI financial advice
  • POST /api/ai/cost-reduction - Generate cost reduction plan
  • POST /api/ai/message - Conversational AI advice (includes previous context)

GitHub Integration

  • GET /api/github/repositories - List user repositories
  • GET /api/github/repositories/:owner/:repo/commits - Get repository commits
  • GET /api/github/repositories/:owner/:repo/pulls - Get pull requests
  • GET /api/github/repositories/:owner/:repo/issues - Get issues

Forensic Accounting

  • GET /api/forensics/investigations - List investigations
  • GET /api/forensics/investigations/:id - Get investigation
  • POST /api/forensics/investigations - Create investigation
  • PATCH /api/forensics/investigations/:id/status - Update status
  • POST /api/forensics/investigations/:id/evidence - Add evidence
  • GET /api/forensics/investigations/:id/evidence - List evidence
  • POST /api/forensics/evidence/:id/custody - Update chain of custody
  • POST /api/forensics/investigations/:id/analyze - Comprehensive analysis
  • POST /api/forensics/investigations/:id/analyze/duplicates - Duplicate payment detection
  • POST /api/forensics/investigations/:id/analyze/timing - Unusual timing detection
  • POST /api/forensics/investigations/:id/analyze/round-dollars - Round dollar anomalies
  • POST /api/forensics/investigations/:id/analyze/benfords-law - Benford's Law analysis
  • POST /api/forensics/investigations/:id/trace-funds - Trace flow of funds
  • POST /api/forensics/investigations/:id/flow-of-funds - Create flow of funds record
  • GET /api/forensics/investigations/:id/flow-of-funds - Get flow of funds
  • POST /api/forensics/investigations/:id/calculate-damages/direct-loss - Direct loss calculation
  • POST /api/forensics/investigations/:id/calculate-damages/net-worth - Net worth method
  • POST /api/forensics/calculate-interest - Pre-judgment interest calculation
  • POST /api/forensics/investigations/:id/generate-summary - Executive summary
  • POST /api/forensics/investigations/:id/reports - Create forensic report
  • GET /api/forensics/investigations/:id/reports - Get forensic reports

Tasks

  • GET /api/tasks - List financial tasks
  • POST /api/tasks - Create task
  • PATCH /api/tasks/:id - Update task
  • DELETE /api/tasks/:id - Delete task

Lease Notifications (Phase 4)

  • GET /api/leases/expiring?days=N - List leases expiring within N days (default 90, tenant-scoped)

Property CRUD (Phase 4)

  • POST /api/properties - Create property
  • PATCH /api/properties/:id - Update property
  • POST /api/properties/:id/units - Create unit
  • PATCH /api/properties/:id/units/:unitId - Update unit
  • POST /api/properties/:id/leases - Create lease
  • PATCH /api/properties/:id/leases/:leaseId - Update lease

Property Financial Data (Phase 4)

  • GET /api/properties/:id/financials - NOI, cap rate, cash-on-cash, occupancy
  • GET /api/properties/:id/rent-roll - Unit-level rent roll with payment status
  • GET /api/properties/:id/pnl?start=YYYY-MM-DD&end=YYYY-MM-DD - Property P&L by REI category

Property Valuation (Phase 4)

  • GET /api/properties/:id/valuation - Aggregated multi-source valuation estimates
  • POST /api/properties/:id/valuation/refresh - Fetch fresh estimates from all configured providers
  • GET /api/properties/:id/valuation/history - Historical valuation timeline

Data Import (Phase 4)

  • POST /api/import/turbotenant - Import TurboTenant CSV ledger (requires X-Account-ID header)
  • POST /api/import/wave-sync - Sync Wave transactions via OAuth

Environment Configuration

Required Variables

Database (required):

DATABASE_URL="postgresql://user:pass@host/dbname"

Application:

NODE_ENV="development"                              # or "production"
MODE="standalone"                                   # or "system" (multi-tenant)
PUBLIC_APP_BASE_URL="http://localhost:5000"        # Base URL for OAuth redirects

OAuth Security (required for production):

OAUTH_STATE_SECRET="random-secret-32chars"         # HMAC secret for OAuth state tokens

AI & OpenAI (optional for development, required for AI features):

OPENAI_API_KEY="sk-..."                            # Required for AI financial advice

Wave Accounting (Phase 3 - Real Integration):

WAVE_CLIENT_ID="..."                               # OAuth client ID from Wave Developer Portal
WAVE_CLIENT_SECRET="..."                           # OAuth client secret
WAVE_REDIRECT_URI="http://localhost:5000/api/integrations/wave/callback"  # Optional, defaults to PUBLIC_APP_BASE_URL/api/integrations/wave/callback

Stripe (Phase 3 - Real Integration):

STRIPE_SECRET_KEY="sk_test_..."                    # Stripe secret key (test or live)
STRIPE_PUBLISHABLE_KEY="pk_test_..."               # Stripe publishable key (optional, frontend)
STRIPE_WEBHOOK_SECRET="whsec_..."                  # Webhook signing secret for verification

Mercury Bank (Phase 3 - Real Integration via ChittyConnect):

CHITTYCONNECT_API_BASE="https://connect.chitty.cc"  # ChittyConnect backend URL
CHITTYCONNECT_API_TOKEN="..."                       # Service authentication token
CHITTY_CONNECT_URL="https://connect.chitty.cc"      # Frontend redirect URL (optional)

GitHub (optional):

GITHUB_TOKEN="ghp_..."                             # Required for GitHub integration

Property Valuation (Phase 4 - optional, each enables its provider):

ZILLOW_API_KEY="..."                               # RapidAPI key for Zillow estimates
REDFIN_API_KEY="..."                               # RapidAPI key for Redfin estimates
HOUSECANARY_API_KEY="..."                          # HouseCanary API key
ATTOM_API_KEY="..."                                # ATTOM Data Gateway key

Cook County Assessor (Socrata) is always available — no API key required.

Local Development Setup

  1. Provision Neon database:

  2. Initialize schema:

    npm run db:push
  3. Create demo user (manual step required):

    INSERT INTO users (username, password, display_name, email, role)
    VALUES ('demo', 'hashed_password', 'Demo User', 'demo@example.com', 'user');
  4. Start dev server:

    npm run dev
  5. Access application: http://localhost:5000

Testing

Manual Testing

  1. Start dev server: npm run dev
  2. Navigate to http://localhost:5000
  3. Application auto-logs in as "demo" user
  4. Test dashboard, integrations, AI chat
  5. Check browser console for errors
  6. Monitor server logs in terminal

Testing AI Features

Testing Integrations

  • Mercury Bank: Real integration via ChittyConnect (requires CHITTYCONNECT_API_BASE + token)
  • Wave Accounting: Real integration via OAuth 2.0 (requires WAVE_CLIENT_ID + WAVE_CLIENT_SECRET)
  • Stripe: Real integration (requires STRIPE_SECRET_KEY + STRIPE_WEBHOOK_SECRET)
  • DoorLoop, QuickBooks, Xero, Brex, Gusto: Not yet implemented — return empty data with console.warn
  • Unimplemented integration functions return {} or [], not fabricated data

Common Issues & Solutions

Database Connection Errors

Error: DATABASE_URL must be set

Solutions:

  1. Verify DATABASE_URL environment variable is set
  2. Test connection: psql $DATABASE_URL -c "SELECT 1"
  3. Check Neon dashboard for database status
  4. Ensure WebSocket support (ws package installed)

Port 5000 Already in Use

Error: EADDRINUSE: address already in use :::5000

Solution:

lsof -ti:5000 | xargs kill -9

Note: Port cannot be changed (hardcoded for Replit deployment).

OpenAI API Errors

Error: 401 Unauthorized or 429 Rate Limit

Solutions:

  1. Verify OPENAI_API_KEY is valid
  2. Check API key has credits at https://platform.openai.com/account/billing
  3. Implement rate limiting or caching for AI requests
  4. Handle errors gracefully (see server/lib/openai.ts:58-60)

Demo User Not Found

Error: Demo user not found from /api/session

Solution: Create demo user in database:

INSERT INTO users (username, password, display_name, email, role)
VALUES ('demo', 'any_value', 'Demo User', 'demo@example.com', 'user');

Type Checking Failures

Error: TypeScript errors from npm run check

Common causes:

  1. Schema changes not reflected in types (types are auto-generated from schema)
  2. Missing imports from @shared/schema
  3. Path alias not resolving (check tsconfig.json)

Solution: Verify schema exports match usage, run npm run check to see all errors.

ChittyOS Integration Points

ChittyID Integration (Planned)

  • Replace demo authentication with ChittyID
  • Link financial data to ChittyID for cross-platform identity
  • Each user should have associated ChittyID DID

ChittyConnect Integration (Planned)

  • Expose financial summary as MCP resource
  • Provide AI financial advice as MCP tool
  • Enable cross-service financial queries

ChittyChronicle Integration (Planned)

  • Log all financial transactions to audit trail
  • Track AI advice and outcomes
  • Compliance and forensic analysis

Development Best Practices

Database Changes

  1. Update shared/schema.ts (single source of truth)
  2. Run npm run db:push to apply changes
  3. Test with demo user in development
  4. Types are auto-generated from schema (no manual type updates needed)

API Design

  • Always use storage abstraction layer (never direct Drizzle queries in routes)
  • Validate inputs with Zod schemas from @shared/schema
  • Use consistent error handling pattern
  • Return JSON responses with appropriate status codes

Frontend Development

  • Use shadcn/ui components for consistency (@/components/ui/*)
  • Implement responsive design with Tailwind utilities
  • Use TanStack Query for all API calls (handles caching, loading, errors)
  • Optimize re-renders with proper React patterns (memo, useCallback)

Security Considerations

OAuth Security (Phase 3 implemented):

  • CSRF Protection: OAuth state tokens use HMAC-SHA256 signatures (server/lib/oauth-state-edge.ts)
  • Replay Prevention: State tokens expire after 10 minutes (timestamp validation)
  • Tampering Detection: State includes cryptographic signature verified server-side
  • Production Requirement: Set OAUTH_STATE_SECRET to random 32+ character string

Webhook Security:

  • Stripe: Webhook signatures verified using STRIPE_WEBHOOK_SECRET
  • Mercury: Service authentication via serviceAuth middleware
  • Idempotency: All webhook events deduplicated using KV with 7-day TTL

Integration Validation (server/lib/integration-validation.ts):

  • Validates required environment variables before allowing integration connections
  • Returns 503 Service Unavailable if integration not properly configured
  • Prevents cryptic errors from misconfigured services

General Security:

  • Critical: Replace demo authentication before production (ChittyID integration pending)
  • Never commit API keys (use environment variables)
  • Sanitize financial data in logs (mask account numbers)
  • Validate all user inputs on backend (Zod schemas)
  • Use HTTPS in production (HTTP allowed for local dev only)
  • Credential data stored as JSONB in database (encrypted at rest by Neon)

Known Limitations

  1. Session Auth (not ChittyID): Email/password with KV-backed cookies — ChittyID SSO integration pending
  2. DoorLoop Sunset: DoorLoop integration is mock-only — platform is sunset for us, mock code is cleanup candidate
  3. No Migrations: Uses drizzle-kit push (destructive) instead of proper migrations
  4. Forensic Tables Not in System Schema: Forensic tables use integer IDs from shared/schema.ts and may not exist in the production database yet
  5. Legacy Express Code: server/routes.ts, server/storage.ts, server/db.ts are legacy Express code kept for standalone dev reference

Future Enhancements

Phase 1: Complete Multi-Tenant Implementation (COMPLETED)

  • ✅ Database schemas created (system.schema.ts, standalone.schema.ts)
  • ✅ Seeding script for IT CAN BE LLC entities
  • ✅ Mode-aware database connection
  • ✅ Wrangler configuration template with KV/R2 provisioned
  • ✅ SystemStorage with tenant-aware Drizzle queries (server/storage/system.ts)
  • ✅ Service token auth middleware (server/middleware/auth.ts)
  • ✅ Tenant-scoped middleware (server/middleware/tenant.ts)
  • ✅ Hierarchy-aware tenant switcher with consolidated portfolio view (PR #52)

Phase 1.5: Hono Route Migration (COMPLETED)

  • ✅ All route modules migrated from Express to Hono (22 route files)
  • ✅ Edge-compatible: Web Crypto API, Neon HTTP driver, no Node.js dependencies
  • ✅ Per-prefix middleware registration (avoids blocking public routes)
  • ✅ Deployed to Cloudflare Workers at finance.chitty.cc
  • ✅ Dev server migrated to Hono (server/dev.ts), 15 legacy lib modules deleted (PR #81)

Phase 2: ChittyConnect Integration (Partially Completed)

  • ✅ Mercury Bank via ChittyConnect backend (multi-account support)
  • ✅ Registered with ChittyRegistry (did:chitty:REG-XE6835, PR #49)
  • ✅ Log to ChittyChronicle (audit trail for classification + COA mutations, PR #92)
  • ✅ JWT session auth behind ChittyAuth (PR #96)
  • ⏳ Integrate with ChittyConnect MCP
  • ⏳ Issue ChittyCert certificates for secure connections

Phase 3: Real Third-Party Integrations (COMPLETED ✅)

  • Wave Accounting - OAuth 2.0 flow + GraphQL API (server/lib/wave-api.ts)
  • Stripe - Payment processing, checkout, webhooks (server/lib/stripe.ts)
  • Mercury Bank - Multi-account via ChittyConnect (static egress IP)
  • Mercury Native Webhooks - Per-tenant HMAC-SHA256 verification, 7 registrations (PR #99)
  • OAuth Security - CSRF-protected state tokens (server/lib/oauth-state-edge.ts)
  • Integration Monitoring - Config validation endpoint (/api/integrations/status)
  • Webhook Infrastructure - Idempotent event processing (KV-based dedup, 7-day TTL)
  • DoorLoop - Sunset, all code removed (PR #78, -35K lines)

Phase 3.5: COA Trust-Path + Classification (COMPLETED ✅)

  • ✅ Database-backed Chart of Accounts with 80 REI accounts seeded (PR #86)
  • ✅ L0→L4 trust-path enforcement with concurrency-safe reconciled lock (PR #86)
  • ✅ AI-assisted classification via GPT-4o-mini with defense-in-depth fallbacks (PR #87)
  • ✅ Classification review UI with bulk-accept guardrails (PR #88)
  • ✅ Admin COA editor with code-range validation (PR #89)
  • ✅ Mercury webhook real-time classification at ingest (PR #90)
  • ✅ Classification enhancements — bulk-accept opt-out, L3 audit trail, tenant settings (PR #94)
  • ✅ Schedule E tax workspace + line summary (PRs #91, #96)
  • ✅ 246+ tests passing

Phase 4: Property Financial API + Data Import (COMPLETED ✅)

  • property_valuations table in system schema
  • ✅ Property/unit/lease CRUD in SystemStorage
  • ✅ Financial aggregation methods (NOI, cap rate, cash-on-cash, occupancy, rent roll, P&L)
  • ✅ Property mutation + financial endpoints (10 new routes in properties.ts)
  • ✅ Multi-source valuation providers (Zillow, Redfin, HouseCanary, ATTOM, County)
  • ✅ Confidence-weighted valuation aggregation + valuation routes
  • ✅ TurboTenant CSV import with deduplication
  • ✅ Mercury CSV import with account auto-resolution (PR #101)
  • ✅ HD Pro CSV import (3K items, 24 job name normalizations) (PR #93)
  • ✅ Amazon Business import (2K items, returns dedup, payment card tracking) (PR #93)
  • ✅ Wave sync import endpoint
  • ✅ Frontend property management UI (Add/Edit property, units, leases, 5-tab detail panel)
  • ✅ Lease expiration notifications (cron trigger + API + dashboard widget, PR #70)

Phase 5: ChittyOS Ecosystem Integration (Partially Completed)

  • ✅ Replace demo auth with ChittyID SSO via OAuth 2.0 PKCE (PR #72)
  • ✅ Expose financial data as MCP resources (PR #92)
  • ✅ Log to ChittyChronicle (PR #92)
  • ✅ ChittyDiscovery self-registration + heartbeat (PR #79)
  • ✅ Fractal scope projection via shared @chittyos/schema/scope-projector (PR #103)
  • ✅ Governance workflow gates (PR #95)
  • ⏳ Issue ChittyCert certificates for secure connections
  • ⏳ Integrate with ChittyConnect MCP

Phase 6: Advanced Features (COMPLETED ✅)

  • ✅ Consolidated reporting across all entities (server/lib/consolidated-reporting.ts)
  • ✅ Multi-currency schema support (ISO 4217, PR #53)
  • ✅ Inter-company allocation automation engine (PR #75) + management UI (PR #80)
  • ✅ Transaction export CSV/OFX/QFX (PR #76)
  • ✅ Complete ledger audit coverage across all financial mutations (PR #77)
  • ✅ Cloudflare Email Service integration (PR #102)
  • ✅ Wrangler config TOML → JSONC (PR #104)
  • ⏳ Tax optimization and reporting (Schedule E data classified, export page shipped)
  • ⏳ Advanced AI forecasting (beyond GPT-4o)
  • ⏳ Mobile app (React Native)

Phase 7: furnished-condos.com (Planned)

  • Cooperative marketplace for small furnished rental operators (under 10 units)
  • Own distribution (not dependent on Airbnb/VRBO APIs)
  • DRL (Distributed Reputation Ledger) for focal trust scoring
  • Channel manager integration via Hospitable or similar for optional cross-posting
  • Guest-facing search + booking frontend
  • Operator onboarding + SaaS billing
  • Local data partnerships with trust-scored vendors

Related Documentation