create AI_template

This commit is contained in:
olekhondera
2025-11-18 03:15:04 +02:00
parent f8c854e3e1
commit 3f4a98d42d
17 changed files with 932 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
# Frontend Architecture Plan — Accounting AI Agent
> **Status:** Phase 0 (Planning) — recommendations to finalize in Phase 1
> **Scope:** Next.js (App Router, TS) + Tailwind + React Query/SWR for ingestion → categorization → approvals → reporting → billing
> **Sources:** Next.js App Router best practices (per latest docs), product/domain docs in `/docs`
## 0. Goals & Non-Goals
- Ship a clear, predictable frontend for finance users: fast tables, reliable status, explainability (rule hit, embedding score, LLM reasoning trace).
- Optimize for multi-tenant, webhook-driven states, and Stripe-hosted billing; no direct provider/LLM calls from the browser.
- Non-goal: custom card forms or direct provider SDKs in the browser.
## 1. Routing & Layout
- App Router with `app/`; root `layout.tsx` imports globals (per Next.js docs).
- Layout shells: public (marketing), app shell (auth/tenant-protected), auth screens.
- Minimal routes: `/`, `/transactions`, `/transactions/review`, `/rules`, `/reports`, `/settings/billing`, `/settings/accounts`, `/settings/team`.
- Navigation state from `next/navigation`; avoid dynamic `href` objects in `<Link>` (App Router requirement).
## 2. Feature/Folder Structure
```
src/
app/ # routes/layouts
features/ # onboarding, transactions, approvals, rules, reports, billing, settings
entities/ # tenant, user, transaction, rule, report, event, integration
shared/ # ui kit, hooks, api client, lib (formatting, currency), auth client
widgets/ # composed UI blocks (dashboards, charts, tables)
```
- Co-locate queries/mutations/types/tests per feature; keep shared minimal.
## 3. Data Layer & State
- HTTP client with typed fetchers; attach auth/tenant context; central 401/403 handling.
- React Query/SWR for cache + background refresh; server-side data where possible (RSC) with client wrappers for interactivity.
- Pagination/virtualization for large lists (`/transactions`, `/events`); filters persisted in URL search params.
- Optimistic updates only for low-risk actions (naming/rule toggles); approvals/overrides stay pessimistic with clear status.
## 4. Auth, Tenant, Roles
- Clerk/Auth.js client; protect routes via middleware and layout guards.
- Tenant selector (if multiple) with context propagated to fetchers.
- Role-based UI gating (owner/admin/viewer); hide/disable disallowed actions.
## 5. UX for Key Flows
- **Transactions:** table with status chips (ingested/categorized/needs_approval/approved/error), drawer: raw payload, rule hit, embedding score, `reasoning_trace`, receipts, history.
- **Approvals:** queue view, approve/override with confirmation; optional rule creation inline; show impact preview.
- **Rules:** list (priority, hit rate), editor with condition/action JSON preview, test on sample set.
- **Reports:** date range, currency/timezone indicators; async export with status chips and download links.
- **Billing:** Stripe-hosted Checkout/Portal; post-return state from backend; recovery CTAs.
- **Integrations:** QuickBooks/bank connection status, webhook health, rotate secrets; surface retry guidance.
- **Errors/Support:** human-readable errors with traceId; recovery steps for webhook/LLM failures.
## 6. Styling & UI Kit
- Tailwind for utilities; small UI kit in `shared/ui` (buttons, inputs, selects, tables, drawer, modal, badge, toast, skeleton).
- Use accessible patterns: focus states, keyboard nav, ARIA labels for tables/dialogs.
## 7. Forms & Validation
- React Hook Form + Zod (or similar).
- Common patterns: debounced search, controlled filters, guarded destructive actions.
- Show server errors inline; avoid duplicate submits; loading/disabled states on primary actions.
## 8. Data Fetching Patterns (per Next.js App Router)
- Server Components for initial data where possible; client components for interactive tables/forms.
- Route Handlers/Server Actions for simple backend-for-frontend glue (if used).
- Avoid dynamic Link objects; use string hrefs for dynamic routes.
## 9. Observability & Telemetry
- Log traceId from responses in UI for support; send non-PII analytics for funnel: onboarding, connection success/failure, categorize actions, approvals, billing, exports.
- Respect consent; no PII in client analytics events.
## 10. Performance
- Table virtualization for large datasets; incremental rendering with skeletons/placeholders.
- Code splitting by route/feature; lazy-load heavy widgets (charts, diff/trace viewers).
- Image optimization via Next.js `Image` if/when used; minimize client JS in shells.
## 11. Testing
- Unit: helpers/formatters.
- Component: transactions table/drawer, approvals flow, rule editor, billing/status banners.
- E2E: onboarding + source connect, transaction ingest display, categorize → approve, rule create/apply, billing flow, report export.
## 12. Open Questions / To Finalize
- Exact table virtualization lib (if any) and charting choice.
- How much data is loaded server-side vs client-side for `/transactions` (depends on API paging).
- Error surface for LLM fallback (what to show vs hide).
- i18n scope (English only vs multi-lingual).
- Whether to expose `rawSnippet` of LLM response in UI or keep to audit logs only.

View File

@@ -0,0 +1,58 @@
# Frontend: Architecture (Recommendations)
---
**Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning)
**Status:** Draft — finalize in Phase 1
**Owner:** Frontend Architect
**References:**
- `/docs/project-overview.md`
- `/docs/content-structure.md`
- `/docs/backend/api-design.md`
- `/docs/backend/payment-flow.md`
- `/docs/frontend/ui-ux-guidelines.md`
---
> Recommendations for Phase 0. Lock decisions in Phase 1.
## 1. Stack
- Framework: Next.js (App Router) + TypeScript.
- Styling: Tailwind CSS.
- Data: React Query or SWR; keep fetchers typed.
- Forms: React Hook Form (or similar) + Zod (or similar) for validation.
## 2. Structure (feature-first)
```
src/
app/ # routes/layouts
features/ # flows: onboarding, transactions, approvals, reports, billing
entities/ # domain: tenant, user, transaction, rule, report, event
shared/ # ui kit, hooks, api client, utils
widgets/ # composed UI blocks
i18n/ # translations (if added)
```
Principles: co-locate tests/types; avoid cross-feature coupling; keep shared minimal.
## 3. Data & API
- Single typed HTTP client; attach auth tokens; handle 401/403 centrally.
- Cache with React Query/SWR; use optimistic/paused states carefully for approvals and rule edits.
- Prefer RSC for data loading; mark interactive leaf nodes with `"use client"`.
- Pagination/filtering for transaction-heavy views; background refetch for webhook-driven updates.
## 4. Payments & Billing UI
- Backend initiates Stripe sessions/portal links; frontend renders statuses only.
- After return from Stripe, fetch status from backend (webhook-driven source of truth); show success/fail/pending and recovery options.
- Never collect raw card data; no custom card forms.
## 5. LLM & Explainability Surfacing
- Frontend never calls LLMs directly. Display `reasoning_trace`, matched rule, and embedding score from backend payloads.
- Provide expandable details, copyable traces, and clear labels for confidence/status.
## 6. Authentication & Access
- Use Clerk/Auth.js client libraries; guard routes per tenant/role; soft-redirect unauthenticated users.
- Support tenant context switching if user belongs to multiple tenants.
## 7. Testing
- Unit: utility/helpers.
- Component: critical UI (transactions list, approval drawer, rule editor, billing modal).
- E2E: onboarding, ingestion health check, categorize + approve, billing change, report export.

40
docs/frontend/overview.md Normal file
View File

@@ -0,0 +1,40 @@
# Frontend: Overview
---
**Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning)
**Status:** Approved
**Owner:** Frontend Architect
**References:**
- `/docs/project-overview.md` (product goals)
- `/docs/frontend/architecture.md` (technical approach)
- `/docs/content-structure.md` (screens and flows)
---
## 1. Role of Frontend
- Deliver onboarding, data connection, categorization review, approval, reporting, and billing experiences for SMB finance users.
- Keep flows fast, explainable (surface reasoning trace, rule hit), and safe (reflect webhook/provider states, avoid double actions).
## 2. Core Screens & Flows
- Marketing/landing with CTA to signup.
- Onboarding: signup/login, plan selection (Stripe Checkout/portal), source connection (QuickBooks OAuth2, bank webhooks health), team invites.
- Transactions: lists/filters, detail drawer (raw fields, rule hit, embedding score, LLM reasoning trace), bulk actions.
- Approvals & Rules: approval queue, override + optional rule creation, rule list/editor, history snippets.
- Reports: P&L/summary dashboards, exports with statuses.
- Billing & Settings: subscription status, payment method, tenant/team management, integrations health, audit/event log view.
- Routes (min set): `/`, `/transactions`, `/transactions/review`, `/rules`, `/reports`, `/settings/billing`, `/settings/accounts`.
## 3. Technical Principles
- Next.js (App Router) with TypeScript; Tailwind for styling; React Query/SWR for data fetching and cache orchestration.
- Feature-first structure; keep state local to features when possible.
- Prefer Server Components; mark client components explicitly; use route handlers/server actions where appropriate.
- Strong loading/error/empty states for data-heavy lists; avoid blocking UX during long jobs (categorization replays, exports).
## 4. Backend Interaction
- All data via backend APIs; frontend never calls providers (Stripe/QuickBooks/banks/LLM) directly.
- Payments: initiate via backend (Stripe session/portal) and show statuses driven by webhooks.
- LLM: never called from the browser; surfaced reasoning traces come from backend responses.
- Auth: Clerk/Auth.js; guard routes per tenant/role; handle token refresh gracefully.
## 5. I18n
- Primary UI in English; other locales optional. Keep copy concise and finance-friendly.

View File

@@ -0,0 +1,38 @@
# Frontend: SEO & Performance
---
**Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning)
**Status:** Draft
**Owner:** Frontend Architect, SEO
**References:**
- `/docs/content-structure.md`
- `/docs/frontend/architecture.md`
- `/docs/project-overview.md`
---
## 1. Goals
- Ensure good indexation for marketing/landing pages; keep the app fast for data-heavy views.
- Hit Core Web Vitals targets where applicable; design for fast perceived performance in app flows.
## 2. SEO (marketing pages)
- Use SSR/SSG for landing/pricing/FAQ pages.
- Semantic markup; clean URLs; Open Graph/Twitter cards.
- sitemap/robots via backend/infra; keep URL ownership on frontend.
## 3. Core Web Vitals (targets)
- LCP < 2.5 s, CLS < 0.1, INP < 200 ms on marketing pages.
## 4. Asset & JS Optimization
- Modern image formats (WebP/AVIF) with `srcset/picture`; lazy-load non-critical blocks.
- Code splitting by route/feature; dynamically load heavy components (tables with virtualization, charts, diff/trace viewers).
- Minimize global state; prefer streaming data in RSC where possible.
## 5. Data-Heavy Views
- Virtualize large tables (transactions, events); paginate server-side.
- Background refetch for webhook-driven updates; avoid full-page reloads.
- Show skeletons and incremental data rather than blank states.
## 6. Analytics & Events
- Track funnel: onboarding steps, connection success/failure, categorization actions, approvals, billing changes, report exports.
- Respect consent/privacy; avoid sending PII in analytics events; provide trace IDs for support paths.

View File

@@ -0,0 +1,49 @@
# Frontend: UX/UI Guidelines
---
**Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning)
**Status:** Draft
**Owner:** UX/UI Team
**References:**
- `/docs/content-structure.md`
- `/docs/frontend/architecture.md`
- `/docs/backend/payment-flow.md`
---
## 1. Tone & Clarity
- Professional, concise, finance-friendly. Emphasize trust (audit log, reasoning traces, secure billing and webhooks).
- Avoid jargon without tooltips; show why a decision was made (rule hit, similarity, LLM reasoning).
## 2. Responsiveness
- Mobile-friendly for quick approvals; ensure tables/lists are scrollable and readable on small screens.
- Keep primary actions within easy reach; preserve context when opening drawers/modals.
## 3. Accessibility
- WCAG 2.2 AA: contrasts, focus states, keyboard navigation.
- Semantic HTML and ARIA for complex components (tables with controls, dialogs, toasts, dropdowns).
## 4. Key UX Flows
### Categorization & Approvals
- Show status per row (ingested/categorized/needs approval/approved/error).
- Detail drawer: raw data, matched rule, scores, `reasoning_trace`, history; clear “Approve/Override” CTAs.
- Prevent double actions; show optimistic state carefully; always provide “undo” or clear revert guidance.
### Rules
- Rule creation/edit with preview/test on sample set; highlight impact and conflicts.
- Require confirmation when enabling a high-priority rule; surface last editor and timestamp.
### Onboarding & Integrations
- Display connection status/health for QuickBooks/bank webhooks; guide recovery/retry.
- Stripe plan selection and post-checkout status must be clear and recoverable.
### Reports & Exports
- Show date range, currency, timezone; indicate processing state and download links when ready.
## 5. Payments & Billing UX
- Use provider trust markers (Stripe) and keep users on provider-hosted flows.
- Post-return states: success, pending, failed; include retry/contact support options.
## 6. Support & Errors
- For webhook/ingestion errors, show actionable next steps (retry, rotate secret, re-connect).
- Keep errors human-readable; include trace IDs for support.