diff --git a/docs/cursor/repository-review-2026-04-01/00-index.md b/docs/cursor/repository-review-2026-04-01/00-index.md new file mode 100644 index 00000000..1a69da1e --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/00-index.md @@ -0,0 +1,108 @@ +# StormCom Repository Review Pack + +Date: 2026-04-01 +Repository: `stormcom` +Reviewer mode: static code audit + partial runtime validation + +## Scope covered + +- `src/**` repository review, with emphasis on: + - App Router pages, layouts, loading/error boundaries + - API route handlers in `src/app/api/**` + - shared libraries, auth, permissions, security, and navigation +- `prisma/**` schema and migration review +- `package.json` and dependency usage cross-check +- `next.config.ts`, `vercel.json`, auth, proxy, and environment setup review +- `docs/cursor/**` cross-validation against the live codebase +- targeted online research for: + - traceability matrix best practices + - CRUD matrix best practices + - architecture blueprint / interaction map best practices + - Next.js 16 + Prisma + PostgreSQL + Vercel best practices + +## Output files + +1. `01-environment-setup-and-validation.md` +2. `02-routes-and-doc-cross-validation.md` +3. `03-src-prisma-dependency-review.md` +4. `04-security-issues-and-architecture-findings.md` +5. `05-ui-walkthrough-findings-and-limitations.md` +6. `06-traceability-matrix.md` +7. `07-crud-matrix.md` +8. `08-architecture-blueprint-interaction-map.md` +9. `09-progress-blockers-and-next-steps.md` + +## Executive summary + +This repository is a large multi-tenant commerce SaaS built on Next.js App Router with: + +- 110 page routes under `src/app/**/page.tsx` +- 291 API route modules under `src/app/api/**/route.ts` +- 3 layouts, 7 loading boundaries, 7 error boundaries, and no explicit `not-found.tsx` +- Prisma/PostgreSQL schema covering auth, organizations, stores, catalog, orders, subscriptions, webhooks, integrations, AI/chat, analytics, and landing pages + +## Key verified findings + +- Existing route docs in `docs/cursor/api-routes.md` and `docs/cursor/general/all-routes.md` are directionally strong, but they are not fully aligned with the current repository. +- `npm run build` does **not** currently succeed end-to-end. It fails during prerendering of `/_not-found` after repeated React key warnings in the metadata/head rendering path. +- Clean environment reproducibility is weak: + - local Docker was unavailable on this machine, so PostgreSQL could not be started from the committed `docker-compose.yml` + - `package-lock.json` is out of sync with `package.json`, so `npm ci` fails on a clean machine +- The repo uses strong central patterns (`apiHandler`, Prisma singleton, NextAuth, proxy-based route protection), but also has important consistency gaps: + - stale Prisma helper selects + - duplicated subscription state in both `Store` and normalized subscription tables + - route naming overlap (`/api/store` vs `/api/stores`, `/api/subscription` vs `/api/subscriptions`, `/api/webhook` vs `/api/webhooks`) + - insecure/legacy security header defaults and CSP trade-offs + - TypeScript build errors are currently masked in production builds via `ignoreBuildErrors: true` + +## Important limitation + +The requested page-by-page live walkthrough as merchant/store owner could not be completed in this session because: + +1. the machine had no Docker binary available +2. there was no native PostgreSQL server installed +3. the app build currently fails before successful full route export + +Because of that, the walkthrough documentation records: + +- what was verified from code and test scaffolding +- the seeded merchant credentials and Playwright auth flow +- the exact blockers and the next commands to run on a machine with Postgres/Docker + +## Review methodology + +- Repository exploration across `src/**`, `prisma/**`, `docs/cursor/**`, root config, and tests +- Route inventory from filesystem plus build log validation attempt +- Prisma schema and migration review +- Dependency-to-usage cross-check from `package.json` against repo search signals +- Environment setup attempt on this machine +- Current online research for RTM / CRUD matrix / architecture documentation best practices + +## Machine facts used during validation + +- OS: Linux 6.12 +- Node: `v22.22.1` +- npm: `10.9.4` +- Docker: not installed on this machine +- Native PostgreSQL binaries (`psql`, `postgres`, `pg_ctl`, `initdb`): not installed on this machine + +## Primary evidence sources + +- `package.json` +- `next.config.ts` +- `vercel.json` +- `proxy.ts` +- `src/lib/auth.ts` +- `src/lib/prisma.ts` +- `src/lib/security.ts` +- `src/lib/prisma-selects.ts` +- `src/components/app-sidebar.tsx` +- `prisma/schema.prisma` +- `prisma/migrations/**` +- `prisma/seed.mjs` +- `playwright.config.ts` +- `e2e/auth.setup.ts` +- `docs/cursor/api-routes.md` +- `docs/cursor/general/all-routes.md` +- `docs/cursor/nav-permissions.md` + diff --git a/docs/cursor/repository-review-2026-04-01/01-environment-setup-and-validation.md b/docs/cursor/repository-review-2026-04-01/01-environment-setup-and-validation.md new file mode 100644 index 00000000..b691d916 --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/01-environment-setup-and-validation.md @@ -0,0 +1,227 @@ +# Environment Setup and Validation + +Date: 2026-04-01 + +## Objective + +Set up a reproducible local development environment, validate the build, and establish whether the requested merchant walkthrough could be executed on this machine. + +## Verified repository setup inputs + +### Runtime and package manager + +- Node: `v22.22.1` +- npm: `10.9.4` +- Package manager in repo: npm (`package-lock.json` present, no pnpm/yarn lockfile) + +### Relevant scripts from `package.json` + +- `npm run dev` -> `next dev` +- `npm run build` -> `node scripts/build.js` +- `npm run start` -> `next start` +- `npm run prisma:generate` +- `npm run prisma:migrate:dev` +- `npm run prisma:migrate:deploy` +- `npm run prisma:seed` +- `npm run test:e2e` + +### Local database path defined by repository + +The repo includes `docker-compose.yml` with: + +- service: `postgres` +- image: `postgres:16-alpine` +- database: `stormcom_dev` +- user: `stormcom_user` +- password: `stormcom_password_dev` +- port: `5432` + +This is the intended local PostgreSQL bootstrap path. + +## Environment file prepared for validation + +A temporary local `.env.local` was created for build validation with these values: + +- `DATABASE_URL=postgresql://stormcom_user:stormcom_password_dev@localhost:5432/stormcom_dev` +- `NEXTAUTH_URL=http://localhost:3000` +- `NEXTAUTH_SECRET=dev-nextauth-secret-for-local-review-only-32chars` +- `NEXT_PUBLIC_APP_URL=http://localhost:3000` +- `NEXT_PUBLIC_APP_DOMAIN=localhost:3000` +- `RESEND_API_KEY=re_dummy_key_for_local_review` +- `EMAIL_FROM=noreply@example.com` +- `SEARCH_ENGINE=postgres` + +This file was used only to probe environment behavior and should not be committed. + +## What succeeded + +### Dependency installation + +`npm install` succeeded. + +Observed notes: + +- deprecated stub: `@types/bcryptjs` +- `npm audit --omit=dev` reported 3 low vulnerabilities + +### Prisma client generation + +`npm run prisma:generate` succeeded. + +Observed output: + +- Prisma schema loaded from `prisma/schema.prisma` +- Prisma Client generated successfully + +## What failed or blocked execution + +### 1. Docker unavailable on machine + +The committed `docker-compose.yml` could not be used because the machine does not have a Docker binary installed. + +Observed result: + +- `docker compose up -d postgres` -> `docker: command not found` + +Impact: + +- local PostgreSQL could not be started from repo-provided infrastructure +- migrations and seed execution could not be completed locally +- authenticated merchant walkthrough could not be performed with real runtime data + +### 2. No native PostgreSQL server tools installed + +Checked binaries: + +- `psql` +- `postgres` +- `pg_ctl` +- `initdb` + +None were available. + +Impact: + +- there was no alternate local PostgreSQL startup path after Docker failed + +### 3. `package-lock.json` is out of sync with `package.json` + +`npm ci` failed on a clean install. + +Observed error: + +- missing from lock file: `nodemailer@7.0.13` +- missing from lock file: `magicast@0.3.5` + +Impact: + +- clean environment reproducibility is currently broken +- CI or new developers using `npm ci` will fail unless the lockfile is regenerated and committed + +Severity: + +- High for reproducibility and CI confidence + +### 4. `npm run build` does not currently complete + +The build advanced through compile and partial prerendering, then failed. + +Observed build path: + +- compiled successfully +- type validation skipped +- static generation started +- repeated React warnings about missing `key` props in top-level `meta`, `head`, `html`, and viewport-related render paths +- final failure while prerendering `/_not-found` + +Observed terminal failure: + +- `Error occurred prerendering page "/_not-found"` +- `TypeError: Cannot read properties of null (reading 'useState')` + +Impact: + +- route output from the final successful build table could not be captured from `npm run build` +- deployment confidence is reduced +- runtime walkthrough was blocked even before DB availability was solved + +## Additional validation notes + +### Build configuration observations + +From `next.config.ts`: + +- `reactCompiler: true` +- `typescript.ignoreBuildErrors: true` +- experimental `optimizePackageImports` + +Important implication: + +- production build is configured to skip TypeScript errors, so a green build would not guarantee type safety + +### Postinstall behavior mismatch + +`scripts/postinstall.js` reads `.env`, not `.env.local`. + +`scripts/build.js` reads `.env.local`. + +Impact: + +- local install and local build do not use the same environment file convention +- Prisma generation may be skipped during install even when the project is otherwise configured in `.env.local` + +## Requested merchant/store-owner walkthrough status + +### Seeded credentials found in repository + +Merchant owner credentials are documented in: + +- `prisma/seed.mjs` +- `README.md` +- `e2e/auth.setup.ts` + +Verified merchant owner account: + +- email: `rafiq@techbazar.io` +- password: `Owner@123456` + +### Playwright support exists + +The repo includes: + +- Playwright config +- auth setup script +- multiple merchant flow specs + +However, these could not be executed meaningfully here because: + +1. no Postgres runtime +2. no seeded database +3. build/runtime instability + +## Recommended environment fix order + +1. Install Docker or PostgreSQL locally +2. Start database: + - preferred: `docker compose up -d postgres` +3. Regenerate and commit `package-lock.json` +4. Run: + - `npm run prisma:generate` + - `npm run prisma:migrate:dev` + - `npm run prisma:seed` +5. Fix the `/_not-found` prerender failure +6. Re-run: + - `npm run build` + - `npm run dev` + - `npx playwright test e2e/auth.setup.ts` +7. Execute merchant walkthrough + +## Environment readiness verdict + +Current status: Partially prepared, not fully runnable. + +The repository can be statically audited and partially built, but full local execution is currently blocked by: + +- unavailable database runtime on this machine +- lockfile drift +- application build failure during prerender diff --git a/docs/cursor/repository-review-2026-04-01/02-routes-and-doc-cross-validation.md b/docs/cursor/repository-review-2026-04-01/02-routes-and-doc-cross-validation.md new file mode 100644 index 00000000..33a52d7e --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/02-routes-and-doc-cross-validation.md @@ -0,0 +1,190 @@ +# Routes and Documentation Cross-Validation + +Date: 2026-04-01 + +## Route inventory from code + +## App Router UI surface + +Verified from `src/app/**`: + +- Page routes: 110 +- Layouts: 3 +- Loading boundaries: 7 +- Error boundaries: 7 +- Explicit `not-found.tsx`: 0 +- Parallel routes (`@slot`) detected: 0 +- Intercepted routes (`(.)segment`) detected: 0 + +### High-level UI route groups + +| Area | Examples | Notes | +|---|---|---| +| Public/auth | `/`, `/login`, `/signup`, `/forgot-password`, `/verify-email`, `/pending-approval` | Auth pages live in route group `(auth)` | +| Merchant/dashboard | `/dashboard`, `/dashboard/products`, `/dashboard/orders/[id]`, `/dashboard/stores/[storeId]/settings` | Protected primarily by `proxy.ts` and API-level authorization | +| Admin | `/admin`, `/admin/users`, `/admin/stores/[id]`, `/admin/roles/requests/[id]` | Super-admin layout guard in `src/app/admin/layout.tsx` | +| Settings | `/settings`, `/settings/billing`, `/settings/api-tokens`, `/settings/ai`, `/settings/integrations/facebook` | Protected by `proxy.ts` | +| Storefront | `/store/[slug]`, `/store/[slug]/products`, `/store/[slug]/products/[productSlug]`, `/store/[slug]/checkout` | Dynamic store layout and metadata | +| Checkout/payment | `/checkout`, `/checkout/success`, `/payment/success`, `/payment/error` | Platform-level checkout surface also exists | +| Tracking | `/track`, `/track/[consignmentId]`, `/track/order/[orderId]` | Public tracking routes | +| Landing pages | `/lp/[storeSlug]/[pageSlug]`, `/lp/preview/[templateId]` | Separate campaign / LP surface | +| Other signed-in UI | `/chat`, `/stormpilot`, `/team`, `/projects`, `/onboarding` | Mixed maturity level | + +## API route surface + +Verified from `src/app/api/**/route.ts`: + +- API route modules: 291 + +### Dominant API families + +| Prefix | Approx. size | Purpose | +|---|---:|---| +| `/api/admin/*` | large | platform admin, users, store requests, plans, reports | +| `/api/analytics/*` | medium | dashboards, alerts, export, realtime | +| `/api/chat/*` | large | AI chat, sessions, model management, OpenAI-compatible endpoints | +| `/api/integrations/*` | large | Facebook, SSLCommerz, integration registry | +| `/api/shipping/pathao/*` | medium | shipping auth, pricing, tracking, shipment creation | +| `/api/stores/[id]/*` | medium | store settings, theme, domain, storefront, staff, roles | +| `/api/store/[slug]/*` | medium | public storefront cart/coupon/order/payment methods | +| `/api/subscriptions/*` | medium | current plan, subscribe, renew, cancel, webhooks | +| `/api/orders/*` | medium | merchant-side order operations | +| `/api/products/*` | medium | catalog CRUD, import/export/upload | + +## Route protection patterns + +### Proxy-level protection + +`proxy.ts` protects these path prefixes with session checks: + +- `/dashboard` +- `/settings` +- `/team` +- `/projects` +- `/products` +- `/chat` +- `/stormpilot` + +Observations: + +- `/products` is listed as protected in `proxy.ts`, but there is no top-level `src/app/products/page.tsx`. +- API routes are excluded from the proxy matcher and rely on `apiHandler` or custom checks. + +### Layout-level protection + +`src/app/admin/layout.tsx` performs: + +- `getServerSession(authOptions)` +- redirect to `/login` when unauthenticated +- Prisma-backed `isSuperAdmin` check +- redirect to `/dashboard` when not a super admin + +### API-level protection + +The main API enforcement pattern is `apiHandler(...)` from `src/lib/api-middleware.ts`. + +Observed variants include: + +- permission-gated handlers +- store-scoped handlers +- explicit `skipAuth: true` + +Known public `skipAuth` examples: + +- `src/app/api/auth/signup/route.ts` +- `src/app/api/stores/lookup/route.ts` + +`/api/stores/lookup` is intentionally public for subdomain/custom-domain resolution in `proxy.ts`. + +## Cross-validation against existing docs + +## `docs/cursor/api-routes.md` + +Status: mostly accurate, high value. + +Verified: + +- documented total route modules: 291 +- major top-level families align with code +- endpoint list is broadly accurate + +Gaps: + +- methods are not listed, only endpoints +- route maturity and auth/public/private status are not captured +- singular/plural overlaps are not highlighted strongly enough: + - `/api/store` vs `/api/stores` + - `/api/subscription` vs `/api/subscriptions` + - `/api/webhook` vs `/api/webhooks` + +Recommendation: + +- keep this file as the endpoint index +- add companion status columns: methods, auth model, tenant scope, public/private + +## `docs/cursor/general/all-routes.md` + +Status: useful, but partially drifted. + +Verified: + +- major route groups and most URL surfaces match the repository +- API and UI sections are directionally correct + +Drift found: + +- the file includes `/_not-found` as if it is a normal app route output +- the actual repository has no explicit `src/app/not-found.tsx` +- current build cannot successfully finish route export because prerendering `/_not-found` crashes + +Interpretation: + +- the document appears to have been generated from a previous build snapshot or a different app state +- it should not be treated as the sole source of truth until the build is fixed and the route list is regenerated + +## `docs/cursor/nav-permissions.md` + +Status: strong and mostly aligned. + +Verified against `src/components/app-sidebar.tsx`: + +- main and secondary navigation mapping is accurate +- parent-vs-child permission behavior is described correctly +- super-admin entries are labeled correctly +- it correctly notes that `navClouds` exists in config but is not rendered + +Small caveat: + +- sidebar visibility is not the same thing as route authorization; this file documents menu rendering, not full access control + +## Build output cross-validation + +The user requested route labels from `npm run build`. + +What was verified: + +- `npm run build` compiles and begins static generation +- it emits repeated React key warnings in metadata/head rendering +- it fails while prerendering `/_not-found` + +Because the build fails, the final route table from a successful build could not be recorded in this session. + +## Important route inconsistencies worth documenting + +1. `/_not-found` behavior is broken in build-time prerender flow. +2. No explicit `not-found.tsx` exists, yet build output references `/_not-found`. +3. `/dashboard/admin/*` is distinct from `/admin/*`; only `/admin/*` is guarded by `admin/layout.tsx`. +4. `/api/store/*` and `/api/orders/*` overlap conceptually but serve different audiences. +5. `/api/subscription/*`, `/api/subscription-plans`, and `/api/subscriptions/*` are fragmented surfaces for one billing domain. +6. `/api/webhook/payment` and `/api/webhooks/*` create naming inconsistency for webhook consumers. + +## Recommended documentation actions + +1. Regenerate `docs/cursor/general/all-routes.md` only after `npm run build` succeeds. +2. Extend `docs/cursor/api-routes.md` with: + - method list + - auth type + - tenant scope + - owning domain +3. Keep `docs/cursor/nav-permissions.md`, but explicitly label it as navigation visibility, not access control. +4. Create a route-governance convention for singular/plural endpoint naming before adding more endpoints. diff --git a/docs/cursor/repository-review-2026-04-01/03-src-prisma-dependency-review.md b/docs/cursor/repository-review-2026-04-01/03-src-prisma-dependency-review.md new file mode 100644 index 00000000..98ca9e8d --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/03-src-prisma-dependency-review.md @@ -0,0 +1,364 @@ +# `src`, Prisma, and Dependency Review + +Date: 2026-04-01 + +## 1. Repository shape + +This codebase is organized primarily around the Next.js App Router under `src/app`, with supporting libraries in `src/lib`, UI/components in `src/components`, and a single Prisma schema under `prisma/schema.prisma`. + +Primary domains found in the code and schema: + +- authentication and account approval +- organizations, memberships, and store staff +- multi-tenant store management +- catalog and inventory +- customers, carts, coupons, orders, fulfillments +- subscriptions and billing +- notifications, audit, platform activity +- webhooks and third-party integrations +- AI chat and search +- landing pages and storefront configuration + +## 2. Prisma schema review + +### 2.1 Major schema domains + +From `prisma/schema.prisma`, the main model groups are: + +#### Auth and user identity + +- `User` +- `Account` +- `Session` +- `VerificationToken` +- `PendingSignup` + +#### Organization and tenancy + +- `Organization` +- `Membership` +- `Store` +- `StoreStaff` +- `CustomRole` +- `CustomRoleRequest` +- `Project` +- `ProjectMember` + +#### Commerce + +- `Product` +- `ProductVariant` +- `Category` +- `Brand` +- `ProductAttribute` +- `ProductAttributeValue` +- `Customer` +- `Order` +- `OrderItem` +- `DiscountCode` +- `Review` +- `Fulfillment` +- `PaymentAttempt` +- `PaymentConfiguration` +- `InventoryLog` +- `InventoryReservation` +- `InventoryReservationItem` + +#### Subscription and billing + +- `SubscriptionPlanModel` +- `Subscription` +- `SubscriptionLog` +- `SubPayment` +- `Invoice` +- `InvoiceItem` + +#### Integrations and platform ops + +- `Webhook` +- `WebhookDelivery` +- `ApiToken` +- `AuditLog` +- `Notification` +- `PlatformActivity` +- Pathao-related store/order fields +- multiple Facebook integration models + +#### AI and analytics + +- `ChatSession` +- `ChatMessage` +- `ChatAttachment` +- `ChatUsageLog` +- `OllamaConfig` +- `PerformanceMetric` +- `SearchAnalytics` +- `ApiUsageLog` +- `CacheMetric` +- `AnalyticsAlert` + +#### Marketing / storefront + +- `LandingPage` +- `LandingPageVersion` + +### 2.2 Strong points + +- Broad business coverage is modeled explicitly rather than hidden in opaque JSON alone. +- Partial indexes are being used in Prisma preview features, which is reasonable for large, filtered Postgres access paths. +- Core multi-tenant ownership chains exist in the schema: user -> membership/storeStaff -> organization/store. +- Most entities important to auditability have timestamps. +- Money fields are largely modeled as integer minor units, which is a better operational choice than floats. + +### 2.3 Schema concerns + +#### A. Subscription state appears duplicated + +`Store` contains: + +- `subscriptionPlan: String` +- `subscriptionStatus: SubscriptionStatus` +- `trialEndsAt` +- `subscriptionEndsAt` +- `productLimit` +- `orderLimit` + +while normalized subscription state also exists in: + +- `Subscription` +- `SubscriptionPlanModel` +- `SubscriptionLog` + +Risk: + +- plan enforcement, UI display, billing, admin repair flows, and trial lifecycle can diverge +- this risk is reinforced by the existence of admin repair endpoints like `src/app/api/admin/fix-broken-trials/route.ts` + +Recommendation: + +- treat `Subscription` + `SubscriptionPlanModel` as authoritative +- progressively demote `Store.subscriptionPlan` and similar fields to cached/derived state only, or remove them once migration risk is addressed + +#### B. Stale Prisma helper selects + +`src/lib/prisma-selects.ts` contains field names that do not match the current schema, for example: + +- `logoUrl` instead of `logo` +- `domain` instead of `subdomain` / `customDomain` +- `isActive` on `Store` +- `isPublished` on `Product` +- `stock` instead of `inventoryQty` +- `dimensions` +- `tags` +- `total`, `tax`, `shipping`, `discount` instead of current order amount fields + +This is one of the clearest repository drift signals found in the review. + +Risk: + +- future developers may reuse these helpers and introduce runtime/type failures +- the file communicates a false schema contract + +Recommendation: + +- either delete the file if unused, or rewrite it to match the current schema and add focused tests + +#### C. `WebhookDelivery` relation drift + +The schema review suggests `WebhookDelivery` uses `webhookId` without a complete Prisma relation back to `Webhook`. + +Risk: + +- typed traversal and referential expectations are weaker than they should be +- cleanup/cascade logic becomes easier to get wrong + +#### D. Enum and naming drift history + +Migrations indicate repeated fixes around: + +- subscription plan enum handling +- trial days +- money conversions +- duplicated Pathao integration migrations + +This is not inherently wrong, but it indicates that: + +- billing and integration layers have already experienced schema churn +- code review around those areas should remain stricter than average + +## 3. Dependency review + +### 3.1 Tech stack actually in use + +Confirmed core stack from code and config: + +- Next.js 16 App Router +- React 19 +- TypeScript 5 +- Tailwind CSS 4 +- Prisma 7 client + PostgreSQL adapter +- NextAuth v4 +- Vercel Analytics / Speed Insights +- Playwright + Vitest + +### 3.2 Important dependency observations + +#### Clearly used + +Examples with strong usage evidence: + +- `next`, `react`, `react-dom` +- `next-auth`, `@auth/prisma-adapter` +- `@prisma/client`, `@prisma/adapter-pg`, `pg` +- `zod` +- `react-hook-form`, `@hookform/resolvers` +- `lucide-react`, `@tabler/icons-react` +- `@vercel/analytics`, `@vercel/speed-insights` +- `stripe`, `@stripe/react-stripe-js`, `@stripe/stripe-js` +- `ollama` +- `socket.io`, `@socket.io/redis-adapter` +- `resend` + +#### Likely unused or misclassified + +These packages had no direct source/config import usage during targeted checks: + +- `radix-ui` +- `react-is` +- `nodemailer` +- `tw-animate-css` +- `baseline-browser-mapping` + +Additional note: + +- `@types/bcryptjs` is a type package but is listed under `dependencies`, not `devDependencies` +- npm also warns it is deprecated because `bcryptjs` ships its own types + +Why this matters: + +- unnecessary runtime dependencies enlarge attack surface and install time +- type-only packages should not ship in production dependency sets + +#### Audit result + +`npm audit --omit=dev` reported: + +- 3 low vulnerabilities +- all tied to `nodemailer` through `@auth/prisma-adapter` / `@auth/core` +- advisory: SMTP command injection in older `nodemailer` + +This is currently low severity, but it confirms that dependency governance needs cleanup. + +### 3.3 Lockfile reproducibility issue + +`npm ci` failed because the checked-in `package-lock.json` does not match `package.json`. + +Observed missing entries from lockfile: + +- `nodemailer@7.0.13` +- `magicast@0.3.5` + +This is a high-confidence repository issue. + +## 4. `src` review: notable implementation patterns + +### 4.1 Positive patterns + +#### Centralized API wrapper + +`src/lib/api-middleware.ts` is used broadly through `apiHandler(...)`. + +Benefits: + +- encourages consistent auth and permission checks +- centralizes request handling behavior +- improves maintainability compared to hand-rolled route logic everywhere + +#### Prisma singleton + +`src/lib/prisma.ts` follows the standard global singleton approach to avoid client proliferation in development. + +#### JWT context enrichment + +`src/lib/auth.ts` enriches the session token with: + +- super-admin state +- organization/store role +- store id +- permissions + +This reduces repeated downstream lookups. + +### 4.2 Caution areas + +#### Auth is split across multiple layers + +Protection is enforced by a mixture of: + +- `proxy.ts` redirect rules +- `apiHandler(...)` +- page/layout guards +- session-derived permission hooks + +This is workable, but the burden is on the team to ensure no route assumes another layer has already handled authorization. + +#### Large surface area without a clearly unified service layer + +A lot of routes call Prisma directly in handlers or in near-handler service code. + +Risk: + +- consistency of tenant filtering and authorization becomes harder to prove +- business rules get repeated + +This does not mean a full repository pattern is required, but it does argue for stronger domain service boundaries in the highest-risk areas: + +- subscriptions +- orders/payments +- store access control +- external webhooks + +## 5. Existing docs cross-check + +### `docs/cursor/api-routes.md` + +Strengths: + +- route count of 291 matches the current filesystem +- endpoint inventory is useful and mostly accurate + +Limitations: + +- it does not include HTTP method detail +- it cannot substitute for runtime verification + +### `docs/cursor/general/all-routes.md` + +Strengths: + +- broad route map is helpful +- major route groups are represented + +Limitations: + +- it includes `/_not-found` style output that does not correspond to an actual `src/app/not-found.tsx` +- it should be treated as build-output-derived documentation, not pure source-of-truth route structure + +### `docs/cursor/nav-permissions.md` + +Strengths: + +- aligns well with `src/components/app-sidebar.tsx` +- correctly distinguishes permission-gated and placeholder routes + +## 6. Overall verdict + +The repository is functionally broad and architecturally ambitious. Its biggest quality risks are not lack of features; they are consistency and drift: + +- schema-to-code drift +- docs-to-code drift +- lockfile-to-package drift +- build configuration masking type issues +- duplicated subscription state + +Those issues are addressable, but they currently reduce confidence in build reproducibility and long-term maintainability. diff --git a/docs/cursor/repository-review-2026-04-01/04-security-issues-and-architecture-findings.md b/docs/cursor/repository-review-2026-04-01/04-security-issues-and-architecture-findings.md new file mode 100644 index 00000000..330183d5 --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/04-security-issues-and-architecture-findings.md @@ -0,0 +1,409 @@ +# Security, Quality, and Architecture Findings + +Date: 2026-04-01 + +This document captures the highest-value issues discovered during the repository review. + +## Severity legend + +- Critical: release-blocking or likely to cause major outage/data exposure +- High: serious correctness, security, or operability risk +- Medium: meaningful weakness that should be scheduled +- Low: cleanup, hardening, or modernization + +## Findings + +### 1. High - production build currently fails during prerender + +Evidence: + +- `npm run build` fails while prerendering `/_not-found` +- terminal output shows repeated React key warnings in metadata/head rendering before: + - `Error occurred prerendering page "/_not-found"` + - `TypeError: Cannot read properties of null (reading 'useState')` + +Impact: + +- production deployment confidence is low +- route export list cannot currently be trusted from build output +- runtime validation and page walkthrough are blocked + +Likely investigation area: + +- root layout/provider stack in `src/app/layout.tsx` +- metadata generation in root layout and dynamic layout files +- client provider usage during error/not-found render paths + +Relevant files: + +- `src/app/layout.tsx` +- `src/components/providers.tsx` +- `src/components/ui/sonner.tsx` +- `src/app/store/[slug]/layout.tsx` + +--- + +### 2. High - clean install reproducibility is broken + +Evidence: + +- `npm ci` fails because `package-lock.json` is not in sync with `package.json` +- missing lockfile entries observed for `nodemailer@7.0.13` and `magicast@0.3.5` + +Impact: + +- CI and new developers cannot rely on deterministic clean installs +- repo state is not faithfully reproducible from committed sources + +Recommended fix: + +- regenerate lockfile from current `package.json` +- validate with `npm ci` +- commit the updated lockfile + +Relevant files: + +- `package.json` +- `package-lock.json` + +--- + +### 3. High - TypeScript build errors are masked in production builds + +Evidence: + +- `next.config.ts` sets: + - `typescript.ignoreBuildErrors: true` + +Impact: + +- type regressions can ship to production unnoticed +- Prisma/schema drift can survive build and fail at runtime + +Why this matters especially here: + +- the codebase is Prisma-heavy +- there is already evidence of stale helper definitions +- route handlers and server components rely on schema correctness + +Recommended fix: + +- treat `npm run type-check` as required in CI +- remove `ignoreBuildErrors` once the repo is clean + +Relevant file: + +- `next.config.ts` + +--- + +### 4. High - duplicated subscription source of truth + +Evidence: + +- `Store` contains direct subscription state: + - `subscriptionPlan` + - `subscriptionStatus` + - `trialEndsAt` + - `subscriptionEndsAt` + - limit fields +- schema also has normalized billing tables: + - `Subscription` + - `SubscriptionPlanModel` + - `SubscriptionLog` + - invoices and payments +- route surface also reflects drift: + - `/api/subscription/*` + - `/api/subscriptions/*` + - `/api/subscription-plans` + +Impact: + +- risk of inconsistent billing UI and enforcement +- admin “fix” routes are already a smell that recovery scripts are needed +- trial/grace/renew/cancel logic can diverge across tables and APIs + +Recommended fix: + +- define one canonical subscription state model +- reduce `Store` fields to derived/cache fields only, or remove them +- publish a state transition map covering trial, active, grace, expired, canceled + +Relevant files: + +- `prisma/schema.prisma` +- `src/app/api/subscription/**` +- `src/app/api/subscriptions/**` +- `src/app/api/admin/fix-broken-trials/route.ts` + +--- + +### 5. High - stale Prisma helper selects are out of schema + +Evidence from `src/lib/prisma-selects.ts`: + +- store fields referenced that do not exist: + - `logoUrl` + - `domain` + - `isActive` +- product fields referenced that do not exist: + - `isPublished` + - `stock` + - `dimensions` + - `tags` +- brand/category/order fields also reference legacy names like: + - `logoUrl` + - `isPublished` + - `total` + - `subtotal` + - `tax` + - `shipping` + - `discount` + +Impact: + +- any future usage of these helpers will break queries +- they communicate the wrong schema to future maintainers +- they indicate repository drift after schema refactors + +Additional note: + +- current search found no active imports of `prisma-selects`, which reduces immediate runtime risk but increases dead-code drift risk + +Recommended fix: + +- either delete the file if unused +- or rewrite it against the current Prisma schema and add tests + +Relevant file: + +- `src/lib/prisma-selects.ts` + +--- + +### 6. Medium - CSP and legacy headers need review + +Evidence: + +- `src/lib/security.ts` still includes: + - `X-XSS-Protection` + - `script-src 'self' 'unsafe-inline' 'unsafe-eval'` +- `next.config.ts` also injects CSP headers with inline/eval allowances + +Impact: + +- `X-XSS-Protection` is legacy and not meaningful hardening in modern browsers +- broad inline/eval allowances weaken CSP value +- duplicate security header definitions increase policy drift risk + +Nuance: + +- some Next.js/dev tooling needs relaxed policies in development +- production policy should be stricter and environment-sensitive + +Recommended fix: + +- centralize CSP policy definition +- make dev and prod policies explicit and different +- remove deprecated `X-XSS-Protection` +- use nonces/hashes or `next/script` strategies where needed + +Relevant files: + +- `src/lib/security.ts` +- `next.config.ts` +- `vercel.json` + +--- + +### 7. Medium - auth protection model is split across proxy, layout, and handlers + +Evidence: + +- `proxy.ts` protects selected app paths +- `/admin` also has a server layout guard in `src/app/admin/layout.tsx` +- API routes rely on `apiHandler` +- `/dashboard/admin/*` is a distinct path family from `/admin/*` + +Impact: + +- path-level authorization is harder to reason about +- accidental new routes can be added without consistent protection +- risk of assuming proxy protection equals server authorization + +Positive note: + +- the repo does explicitly note that `skipAuth` is only used intentionally for specific public endpoints + +Recommended fix: + +- document a single security model: + - proxy for navigation + - layout/page guards for SSR UI + - handler/action authorization for all mutations and reads +- add a protected-route coverage checklist for new route families + +Relevant files: + +- `proxy.ts` +- `src/app/admin/layout.tsx` +- `src/lib/api-middleware.ts` + +--- + +### 8. Medium - route naming overlaps create maintainability and client-integration risk + +Examples: + +- `/api/store/[slug]` vs `/api/stores` and `/api/stores/[id]` +- `/api/subscription/*` vs `/api/subscriptions/*` +- `/api/webhook/payment` vs `/api/webhooks/*` +- unversioned APIs vs `/api/v1/*` + +Impact: + +- increases client misuse risk +- complicates docs and OpenAPI interpretation +- raises long-term maintenance cost + +Recommended fix: + +- adopt naming rules: + - singular only for a single canonical resource if truly necessary + - plural for collections and resource families + - explicit versioning strategy for public APIs +- document public vs internal endpoints + +Relevant files: + +- `src/app/api/**` +- `docs/cursor/api-routes.md` + +--- + +### 9. Medium - README and setup docs drift from current implementation + +Evidence: + +- README tech stack versions are stale relative to `package.json` +- Facebook webhook path in README does not match current route handlers +- README contains appended malformed JSON/config fragments near the bottom + +Impact: + +- onboarding friction +- wrong third-party integration setup +- lower trust in docs + +Recommended fix: + +- rewrite README from current repo state +- move credentials and local setup to dedicated dev docs +- remove accidental appended config fragments + +Relevant files: + +- `README.md` +- `src/app/api/webhooks/facebook/route.ts` + +--- + +### 10. Low - `postinstall` and build env loading conventions differ + +Evidence: + +- `scripts/postinstall.js` loads `.env` +- `scripts/build.js` loads `.env.local` + +Impact: + +- confusing local behavior +- install may skip Prisma generation even when build is configured + +Recommended fix: + +- standardize environment loading across scripts +- prefer one documented local source of truth + +Relevant files: + +- `scripts/postinstall.js` +- `scripts/build.js` + +--- + +### 11. Low - direct dependency hygiene issues + +Confirmed non-usage / questionable packages: + +- `radix-ui` - no direct source imports +- `react-is` - no direct source imports +- `nodemailer` - no direct source imports +- `tw-animate-css` - no direct source or CSS usage +- `baseline-browser-mapping` - no direct repo usage +- `@types/bcryptjs` - deprecated stub package and should not be runtime dependency + +Impact: + +- larger dependency surface +- unnecessary audit noise +- confusing maintenance + +Recommended fix: + +- remove unused direct dependencies where safe +- move type-only packages to `devDependencies` +- document packages intentionally retained only for peer/override reasons + +Relevant file: + +- `package.json` + +--- + +### 12. Low - public store lookup endpoint is correctly intentional, but should be rate-limited and documented as public infrastructure + +Evidence: + +- `src/app/api/stores/lookup/route.ts` uses `skipAuth: true` +- endpoint is used by `proxy.ts` for subdomain/custom-domain resolution + +Assessment: + +- this is a justified public endpoint +- it returns minimal data only + +Residual risk: + +- can still be probed at scale for tenant enumeration + +Recommended hardening: + +- rate limit aggressively +- add caching and abuse monitoring +- document allowed fields and access intent + +Relevant files: + +- `src/app/api/stores/lookup/route.ts` +- `proxy.ts` + +## Strengths worth preserving + +- strong central `apiHandler` abstraction +- Prisma singleton pattern in `src/lib/prisma.ts` +- explicit admin layout guard +- clear sidebar permission documentation and hook structure +- broad Playwright coverage scaffolding already present +- dedicated Vercel deployment config with cron and function duration tuning + +## Priority order for remediation + +1. Fix build failure on `/_not-found` +2. Repair lockfile and clean-install reproducibility +3. Stop masking TypeScript build errors +4. Resolve subscription source-of-truth duplication +5. Remove or repair stale Prisma helper code +6. Normalize route naming and API version strategy +7. Tighten CSP/security header policy +8. Refresh README and setup docs diff --git a/docs/cursor/repository-review-2026-04-01/05-ui-walkthrough-findings-and-limitations.md b/docs/cursor/repository-review-2026-04-01/05-ui-walkthrough-findings-and-limitations.md new file mode 100644 index 00000000..2bcb32b5 --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/05-ui-walkthrough-findings-and-limitations.md @@ -0,0 +1,172 @@ +# UI Walkthrough Findings and Limitations + +Date: 2026-04-01 + +## Requested objective + +The requested objective was to: + +- run the application +- log in as a merchant / store owner +- navigate pages one by one +- perform real UI actions using seeded data +- document findings + +## What was verified from repository evidence + +### Merchant credentials exist in repo-owned seed/test assets + +Verified merchant credentials: + +- store owner: `rafiq@techbazar.io` +- password: `Owner@123456` + +Sources: + +- `prisma/seed.mjs` +- `README.md` +- `e2e/auth.setup.ts` + +### Merchant login flow exists + +Verified from `src/app/(auth)/login/page.tsx`: + +- password sign-in path is implemented through `next-auth/react` +- successful credential login redirects to `/dashboard` +- magic-link login is also supported + +### Auth backend supports password login + +Verified from `src/lib/auth.ts`: + +- `CredentialsProvider` is enabled +- password hashes are checked with `bcryptjs` +- only approved accounts or super admins can log in +- non-approved statuses return explicit error messages + +### Merchant walkthrough automation scaffolding exists + +Verified Playwright support: + +- `playwright.config.ts` +- `e2e/auth.setup.ts` +- multiple E2E specs for dashboard, checkout, cart, analytics, products, routing, infrastructure, and invoices + +This indicates the repository is designed for route-by-route walkthrough and smoke testing once the runtime is available. + +## What could not be completed live in this session + +The live walkthrough could not be executed end-to-end because all of the following were true at once: + +1. Docker was unavailable on this machine +2. native PostgreSQL binaries were unavailable +3. Prisma migrations/seeding could not be run locally +4. `npm run build` currently fails during prerender + +Because of that, the following could not be truthfully claimed as executed: + +- successful local sign-in against seeded merchant data +- route-by-route page visitation in browser +- performing UI actions with real database-backed state +- verifying page forms, saves, edits, deletes, and downstream API effects + +## What can still be inferred safely from code and tests + +### Primary merchant route families + +Likely merchant-facing areas: + +- `/dashboard` +- `/dashboard/products` +- `/dashboard/categories` +- `/dashboard/brands` +- `/dashboard/attributes` +- `/dashboard/inventory` +- `/dashboard/orders` +- `/dashboard/customers` +- `/dashboard/analytics` +- `/dashboard/coupons` +- `/dashboard/emails` +- `/dashboard/landing-pages` +- `/dashboard/webhooks` +- `/dashboard/integrations` +- `/dashboard/stores` +- `/dashboard/subscriptions` +- `/settings` +- `/settings/api-tokens` +- `/settings/ai` +- `/settings/stormpilot` + +### Storefront routes likely exercised by merchant-created data + +- `/store/[slug]` +- `/store/[slug]/products` +- `/store/[slug]/products/[productSlug]` +- `/store/[slug]/categories` +- `/store/[slug]/cart` +- `/store/[slug]/checkout` +- `/store/[slug]/orders/track` +- `/store/[slug]/orders/view` + +### Test-driven hint of important user journeys + +The E2E suite names suggest these core flows already matter to the repo: + +- auth setup +- comprehensive dashboard +- comprehensive platform coverage +- cart and checkout +- invoice download and order invoice flow +- product flows +- analytics +- subscription renewal +- multi-tenant routing +- theme editor +- landing page renderer + +## Provisional walkthrough checklist for the next runnable session + +Once PostgreSQL is available and the build issue is fixed, run the following walkthrough in order: + +1. login as `rafiq@techbazar.io` +2. verify redirect to `/dashboard` +3. open dashboard summary cards and confirm seed data presence +4. visit products list, product create, product detail edit +5. visit categories, brands, attributes +6. visit inventory and low stock/history behaviors +7. visit orders, COD, order detail, fulfillment/refund/cancel states +8. visit customers, coupons, analytics +9. visit landing pages, webhooks, integrations, subscriptions +10. visit store settings, appearance/editor, staff, roles, shipping +11. visit `/settings`, API tokens, AI settings, billing, Facebook integration +12. open storefront routes for the seeded store +13. add to cart, checkout, track order, view invoice + +## Findings from the requested walkthrough task + +### Verified findings + +- The repository contains enough seed data, login support, and Playwright coverage to perform the requested walkthrough on a machine with PostgreSQL. +- The intended merchant owner account and redirect target are clearly defined. +- The app appears to support broad merchant workflows, not just authentication and listing pages. + +### Unverified due to runtime blockers + +- actual page load success for each merchant route +- form save success +- authorization behavior for each page +- API/UI consistency under real data +- visual regressions or broken components on specific pages +- data mutations and downstream side effects + +## Confidence statement + +This document is intentionally conservative. + +It records: + +- what the repository demonstrates structurally +- what credentials and test assets exist +- what runtime blockers prevented completion + +It does **not** claim that the requested live merchant walkthrough was completed on this machine. diff --git a/docs/cursor/repository-review-2026-04-01/06-traceability-matrix.md b/docs/cursor/repository-review-2026-04-01/06-traceability-matrix.md new file mode 100644 index 00000000..45d81070 --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/06-traceability-matrix.md @@ -0,0 +1,74 @@ +# Traceability Matrix + +Date: 2026-04-01 + +## Purpose + +This matrix links major business capabilities and technical concerns to: + +- relevant UI routes +- supporting API routes +- database models +- principal source files +- current validation status +- observed risks or gaps + +This follows current RTM best practices: + +- unique capability identifiers +- bidirectional traceability mindset +- mapping from requirement -> implementation -> test/validation evidence +- explicit status/risk column for change management + +## Matrix + +| ID | Capability / Requirement | UI routes | API routes | Data models | Key source files | Validation status | Noted gaps / risk | +|---|---|---|---|---|---|---|---| +| RTM-01 | User authentication with password + email link | `/login`, `/signup`, `/verify-email`, `/forgot-password` | `/api/auth/[...nextauth]`, `/api/auth/signup`, `/api/auth/verify-email` | `User`, `Account`, `Session`, `VerificationToken`, `PendingSignup` | `src/lib/auth.ts`, `src/app/(auth)/**` | Code verified; runtime login not executed here | Email flow depends on Resend/env; walkthrough blocked by DB/runtime | +| RTM-02 | Session-aware route protection | `/dashboard/**`, `/settings/**`, `/chat`, `/stormpilot`, `/team`, `/projects` | indirect via NextAuth/session APIs | `User`, `Membership`, `StoreStaff` | `proxy.ts`, `src/lib/auth.ts` | Code verified | Proxy excludes `/api`; every mutation must still self-authorize | +| RTM-03 | Super-admin platform control | `/admin/**` | `/api/admin/**` | `User`, `StoreRequest`, `Subscription`, `SubscriptionPlanModel`, `PlatformActivity` | `src/app/admin/layout.tsx`, `src/app/api/admin/**` | Code verified | Split admin surface with `/dashboard/admin/**` may confuse governance | +| RTM-04 | Store/tenant resolution by subdomain or custom domain | storefront routes via rewrite to `/store/[slug]/**` | `/api/stores/lookup` | `Store`, `Organization` | `proxy.ts`, `src/app/api/stores/lookup/route.ts`, `src/app/store/[slug]/layout.tsx` | Code verified | Public lookup intentionally unauthenticated; cache and hostname trust should be monitored | +| RTM-05 | Merchant dashboard navigation and RBAC | `/dashboard/**`, `/settings/**` | `/api/permissions`, many resource APIs | `Membership`, `StoreStaff`, `CustomRole`, `CustomRoleRequest` | `src/components/app-sidebar.tsx`, `src/hooks/use-permissions.ts`, `src/lib/permissions.ts` | Code and docs verified | Sidebar visibility is not equivalent to endpoint authorization | +| RTM-06 | Product management | `/dashboard/products/**`, `/dashboard/categories/**`, `/dashboard/brands/**`, `/dashboard/attributes/**` | `/api/products/**`, `/api/categories/**`, `/api/brands/**`, `/api/attributes/**`, `/api/product-attributes` | `Product`, `ProductVariant`, `Category`, `Brand`, `ProductAttribute`, `ProductAttributeValue` | `src/app/dashboard/products/**`, `src/app/api/products/**` | Code verified | Stale Prisma select helpers indicate schema drift risk | +| RTM-07 | Inventory management | `/dashboard/inventory` | `/api/inventory/**`, `/api/orders/**`, `/api/cron/release-reservations` | `InventoryLog`, `InventoryReservation`, `InventoryReservationItem`, `ProductVariant` | `src/app/api/inventory/**`, `src/lib/services/inventory.service.ts`, `src/lib/inventory/**` | Code verified | Depends on correct reservation consistency and cron behavior | +| RTM-08 | Cart and checkout | `/store/[slug]/cart`, `/store/[slug]/checkout/**`, `/checkout/**` | `/api/cart/**`, `/api/checkout/**`, `/api/store/[slug]/cart/validate`, `/api/store/[slug]/orders` | `Order`, `OrderItem`, `Customer`, `PaymentAttempt`, `DiscountCode` | storefront pages + checkout API routes | Code verified | Duplicate checkout surfaces increase drift risk | +| RTM-09 | Order lifecycle and tracking | `/dashboard/orders/**`, `/store/[slug]/orders/view`, `/store/[slug]/orders/track`, `/track/**` | `/api/orders/**`, `/api/store/[slug]/orders/**`, `/api/fulfillments/**`, `/api/shipping/**` | `Order`, `OrderItem`, `Fulfillment`, `PaymentAttempt` | `src/app/api/orders/**`, `src/app/track/**`, storefront order pages | Code verified | Public and merchant order trees overlap conceptually; careful client routing needed | +| RTM-10 | Payment gateway orchestration | checkout/payment pages | `/api/payments/**`, `/api/integrations/sslcommerz/**`, `/api/webhooks/stripe`, `/api/webhooks/sslcommerz/**`, `/api/webhook/payment` | `PaymentAttempt`, `PaymentConfiguration`, `SubPayment`, `Invoice` | payment routes and libs | Code verified | Naming overlap and callback fragmentation | +| RTM-11 | Subscription and plan management | `/dashboard/subscriptions/**`, `/dashboard/admin/subscriptions`, `/settings/billing` | `/api/subscriptions/**`, `/api/subscription/**`, `/api/subscription-plans`, `/api/admin/subscriptions/**` | `SubscriptionPlanModel`, `Subscription`, `SubscriptionLog`, `Invoice`, `Store` | `src/app/api/subscriptions/**`, `prisma/schema.prisma` | Code verified | Dual source of truth between `Store` plan fields and normalized subscription tables | +| RTM-12 | Staff and role request management | `/dashboard/stores/[storeId]/staff`, `/dashboard/stores/[storeId]/roles/**`, `/admin/roles/requests/**` | `/api/stores/[id]/staff/**`, `/api/store-staff/**`, `/api/stores/[id]/role-requests/**`, `/api/admin/role-requests/**` | `StoreStaff`, `CustomRole`, `CustomRoleRequest`, `Membership` | staff/role pages and APIs | Code verified | Permission complexity warrants stronger matrix-based tests | +| RTM-13 | Storefront rendering and theming | `/store/[slug]/**`, `/dashboard/stores/[storeId]/appearance/**`, `/dashboard/visual-editor` | `/api/stores/[id]/theme`, `/api/stores/[id]/storefront/**`, `/api/themes`, `/api/stores/[id]/manifest`, `/api/stores/[id]/sw` | `Store`, `LandingPage`, `LandingPageVersion` | `src/app/store/[slug]/**`, storefront editor components | Code verified; runtime preview not executed | Build instability may intersect layout/metadata rendering | +| RTM-14 | Landing pages and marketing | `/dashboard/landing-pages/**`, `/lp/[storeSlug]/[pageSlug]`, `/lp/preview/[templateId]` | `/api/landing-pages/**`, `/api/emails/**`, `/api/coupons/**` | `LandingPage`, `LandingPageVersion`, `DiscountCode` | landing page editor and route handlers | Code verified | Needs end-to-end rendering verification with seeded data | +| RTM-15 | Notifications and realtime updates | `/dashboard/notifications` | `/api/notifications/**`, `/api/sse/notifications`, `/api/ws` | `Notification`, `PlatformActivity` | notification components, SSE/WS routes | Code verified | Realtime route operational verification not completed | +| RTM-16 | AI chat / StormPilot | `/chat`, `/stormpilot`, `/settings/ai` | `/api/chat/**`, `/api/settings/ai/**`, `/api/ai/recommendations` | `ChatSession`, `ChatMessage`, `ChatAttachment`, `ChatUsageLog`, `OllamaConfig` | AI chat routes/components | Code verified | Depends on external AI service config; broad surface area | +| RTM-17 | Facebook integration | `/dashboard/integrations/facebook`, `/settings/integrations/facebook` | `/api/integrations/facebook/**`, `/api/webhooks/facebook` | Facebook integration models in Prisma | `src/app/api/integrations/facebook/**` | Code verified | README webhook docs are stale/wrong | +| RTM-18 | Webhooks and auditability | dashboard webhooks page | `/api/webhooks/**`, `/api/webhook/payment`, `/api/audit-logs` | `Webhook`, `WebhookDelivery`, `AuditLog` | webhook routes and audit log route | Code verified | `WebhookDelivery` relation modeling is weak in schema | +| RTM-19 | Analytics and metrics | `/dashboard/analytics`, `/admin/analytics`, `/admin/metrics` | `/api/analytics/**`, `/api/metrics`, `/api/cache/stats` | `PerformanceMetric`, `SearchAnalytics`, `ApiUsageLog`, `CacheMetric`, `AnalyticsAlert` | analytics routes and components | Code verified | Runtime data quality not validated without seeded DB | +| RTM-20 | Public API documentation and versioned APIs | `/api-docs` | `/api/openapi`, `/api/v1/**` | n/a | `src/app/api-docs/page.tsx`, OpenAPI generator scripts | Code verified | Need successful build/runtime to validate docs rendering | + +## Traceability coverage assessment + +### Strongly covered + +- auth +- RBAC/navigation +- product/order/store management +- subscriptions and admin operations +- integrations and webhooks + +### Partially covered + +- live walkthrough evidence +- end-to-end store owner actions with real DB data +- realtime and websocket behavior +- third-party payment and shipping callbacks + +### Recommended next improvements + +1. Add a generated machine-readable route inventory artifact in CI. +2. Add matrix-linked integration tests for: + - subscription state transitions + - role approval flows + - store lookup and subdomain routing + - order creation and payment verification +3. Maintain stable capability IDs in docs so future reviews can diff coverage over time. + diff --git a/docs/cursor/repository-review-2026-04-01/07-crud-matrix.md b/docs/cursor/repository-review-2026-04-01/07-crud-matrix.md new file mode 100644 index 00000000..4eb8067f --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/07-crud-matrix.md @@ -0,0 +1,130 @@ +# CRUD Matrix + +Date: 2026-04-01 + +## Purpose + +This CRUD matrix maps major application modules to the primary data entities they create, read, update, or delete. + +Best-practice basis used: + +- map modules to data entities, not just screens +- highlight workflow-critical updates and delete operations +- note where permissions/audit concerns matter more than raw CRUD +- call out duplicated ownership or inconsistent write surfaces + +## Legend + +- C = create +- R = read +- U = update +- D = delete +- `*` = high-control operation; should be audited/permission-gated + +## Core business modules vs entities + +| Module / area | User | Organization | Store | Membership / Staff | Product | Category / Brand / Attr | Customer | Cart | Order | PaymentAttempt / Transaction | Subscription / Plan | Webhook | LandingPage | Notification / Audit | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| Auth / signup / approval | C/R/U* | - | - | - | - | - | - | - | - | - | - | - | - | C | +| Admin users | R/U*/D* | - | - | - | - | - | - | - | - | - | - | - | - | C/R | +| Admin stores / requests | - | C/R/U* | C/R/U*/D* | U* | - | - | - | - | - | - | U* | - | - | C/R | +| Dashboard stores / settings | - | R | R/U* | R/U* | - | - | - | - | - | - | R | R | R/U | C/R | +| Dashboard products | - | - | R | - | C/R/U*/D* | C/R/U*/D* | - | - | - | - | - | - | - | C/R | +| Storefront catalog | - | - | R | - | R | R | - | - | - | - | - | - | - | - | +| Storefront cart / checkout | - | - | R | - | R | R | C/R | C/R/U/D | C | C | - | - | - | C | +| Merchant orders | - | - | R | - | R | - | R | R | R/U*/D? | R/U* | - | - | - | C/R | +| Inventory management | - | - | R | - | R/U* | - | - | - | R | - | - | - | - | C/R | +| Reviews | R | - | R | - | R | - | R | - | R | - | - | - | - | C/R | +| Coupons / marketing | - | - | R | - | R | - | R | R | R | - | - | - | R/U* | C/R | +| Subscriptions / billing | R | R | R/U* | - | - | - | - | - | - | C/R/U* | C/R/U* | - | - | C/R | +| Integrations / Facebook / Pathao | - | - | R/U* | - | R/U | - | R | - | R/U | R/U | - | C/R/U*/D* | - | C/R | +| Notifications | R | - | R | - | - | - | - | - | - | - | - | - | - | C/R/U/D | +| AI / chat | R | R | R | - | R | R | - | - | R | - | - | - | - | C/R | +| Landing pages | - | - | R | - | R | R | - | - | - | - | - | - | C/R/U*/D* | C/R | + +## Key entity observations + +### 1. Store and subscription ownership is duplicated + +`Store` contains subscription-related fields while normalized subscription tables also exist. + +CRUD implication: + +- multiple modules can read/write effective subscription state +- policy decisions can diverge unless one source is designated authoritative + +### 2. Public storefront and authenticated merchant order surfaces both touch order/payment entities + +This is normal, but it increases the need for: + +- strong store scoping +- idempotency +- payment callback validation +- audit logging on status transitions + +### 3. Webhooks and integration callbacks update high-value entities indirectly + +External systems can mutate: + +- orders +- payments +- delivery state +- notifications + +These should be treated as privileged update paths, not auxiliary endpoints. + +### 4. Notifications and audit entities are cross-cutting + +Most sensitive module writes should create corresponding audit/notification entries, especially: + +- account approval/rejection/suspension +- subscription changes +- store request approval +- refund/cancel/fulfillment operations +- credential and integration changes + +## CRUD anti-patterns / risks observed + +1. **Ambiguous route prefixes for same entity class** + - `/api/store/.../orders` and `/api/orders/...` + - `/api/subscription/...` and `/api/subscriptions/...` + - `/api/webhook/...` and `/api/webhooks/...` + +2. **Stale helper field shapes** + - helper selects in `src/lib/prisma-selects.ts` no longer reflect actual schema fields + - this creates false assumptions about available read models + +3. **Delete semantics inconsistent by domain** + - some modules use hard delete + - some entities use `deletedAt` + - some integration/event data appears append-only + +4. **Permission model is stronger in UI/API wrapper than in documented domain ownership** + - CRUD surfaces exist, but domain ownership boundaries are not explicitly documented in one place + +## Recommended matrix improvements + +1. Define one authoritative write owner per core entity family: + - Store lifecycle + - Subscription lifecycle + - Order status and fulfillment + - Inventory reservation and release + +2. Add a second governance layer beside CRUD: + - actor role + - scope + - approval requirement + - audit requirement + +3. Standardize delete semantics: + - soft delete for business records that require audit/history + - hard delete only for ephemeral or clearly non-business entities + +4. For external callback routes, document: + - which entities they mutate + - whether mutations are idempotent + - what signature/auth checks are required + +## Verdict + +The repository supports a broad commerce CRUD surface and already contains many of the necessary entities and route handlers. The main weakness is not missing CRUD capability but inconsistent ownership and naming across overlapping surfaces. diff --git a/docs/cursor/repository-review-2026-04-01/08-architecture-blueprint-interaction-map.md b/docs/cursor/repository-review-2026-04-01/08-architecture-blueprint-interaction-map.md new file mode 100644 index 00000000..bc55ed39 --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/08-architecture-blueprint-interaction-map.md @@ -0,0 +1,559 @@ +# Architecture Blueprint and Interaction Map + +Date: 2026-04-01 + +## Purpose + +This document provides a living architecture blueprint and interaction map for the current StormCom repository. + +It is based on: + +- actual repository structure +- App Router and API routing +- Prisma schema and migrations +- auth, proxy, and permission flows +- current documentation and configuration +- current best-practice research favoring layered C4-style documentation with explicit interaction labeling + +## Best-practice framing used + +Recent architecture documentation guidance consistently favors: + +- a system-context view +- a container-level view +- a component/domain interaction view +- explicit labels on interactions +- living documentation tied to real code, not aspirational diagrams + +That approach is followed below. + +--- + +## 1. System context + +### Primary actors + +- Platform super admin +- Store owner / merchant +- Store staff +- Storefront customer / guest buyer +- External integration providers: + - Stripe + - SSLCommerz + - bKash + - Nagad + - Facebook/Meta + - Pathao + - Resend + - Redis / Upstash + - Vercel platform services + - optional Ollama / AI web tools + +### Primary external systems + +- PostgreSQL database +- email provider +- payment gateways +- shipping gateway +- social commerce integrations +- analytics / blob / edge hosting platform +- optional search / AI services + +### System responsibilities + +The repository acts as a multi-tenant commerce SaaS platform responsible for: + +- user authentication and approval workflows +- organization and store management +- storefront rendering +- merchant dashboard and operations +- catalog and inventory management +- checkout and order lifecycle management +- subscriptions and billing +- integrations and webhook processing +- landing pages and marketing tooling +- AI/chat and analytics features + +--- + +## 2. Container-level architecture + +### Container A: Next.js App Router web application + +Code roots: + +- `src/app/**` +- `src/components/**` +- `src/hooks/**` + +Responsibilities: + +- page rendering for admin, dashboard, store, checkout, settings, chat, track, and landing pages +- layout composition and metadata +- client and server component boundaries +- interactive merchant and storefront UI + +Interfaces: + +- browser HTTP requests +- internal route handlers under `/api/**` + +### Container B: Route handler API surface + +Code roots: + +- `src/app/api/**` +- `src/lib/api-middleware.ts` + +Responsibilities: + +- internal and public JSON APIs +- RBAC and store-scope enforcement +- CRUD operations over domain models +- integrations, webhooks, billing flows, admin operations + +Interfaces: + +- browser / frontend callers +- edge proxy lookup +- external systems and webhooks + +### Container C: Auth and session subsystem + +Code roots: + +- `src/lib/auth.ts` +- `src/app/api/auth/**` +- `proxy.ts` + +Responsibilities: + +- NextAuth provider configuration +- password and magic-link sign-in +- JWT enrichment with org/store roles and permissions +- protected route redirect behavior + +Interfaces: + +- browser sign-in UI +- session cookies / JWT token resolution +- Prisma user/session/account tables + +### Container D: Domain and service layer + +Code roots: + +- `src/lib/**` +- selective server components and route handlers + +Responsibilities: + +- payment orchestration +- inventory logic +- permissions and tenant resolution +- search and analytics helpers +- integration services +- cache and runtime support + +Observation: + +This layer is partially centralized, but significant domain logic still lives directly in route handlers. The architecture is therefore hybrid, not cleanly service-oriented. + +### Container E: Persistence layer + +Code roots: + +- `prisma/schema.prisma` +- `prisma/migrations/**` +- `src/lib/prisma.ts` + +Responsibilities: + +- relational data model +- schema evolution +- Prisma client access + +### Container F: Deployment/runtime configuration + +Files: + +- `next.config.ts` +- `vercel.json` +- `.env.example` +- `docker-compose.yml` + +Responsibilities: + +- build settings +- security headers +- function timeouts +- cron execution +- local developer setup + +--- + +## 3. High-level interaction map + +### A. Merchant dashboard flow + +1. Merchant opens protected route like `/dashboard` +2. `proxy.ts` checks JWT presence for protected prefixes +3. Next.js renders dashboard pages/components +4. UI calls `/api/**` endpoints +5. `apiHandler` resolves auth, store context, and permissions +6. Prisma reads/writes PostgreSQL +7. UI re-renders using returned data + +### B. Storefront browsing flow + +1. User visits subdomain or `/store/[slug]` +2. `proxy.ts` rewrites custom domain / subdomain traffic to `/store/[slug]` +3. store layout resolves store and categories +4. storefront pages render product/category/order pages +5. public store APIs support cart validation, coupons, order creation, payment verification, and tracking + +### C. Checkout and order flow + +1. customer builds cart +2. checkout UI calls validation/shipping/payment APIs +3. order creation writes `Order`, `OrderItem`, and payment attempt records +4. payment callback/webhook routes update payment status +5. order tracking and invoice routes expose downstream order lifecycle state + +### D. Admin governance flow + +1. super admin visits `/admin` +2. admin layout performs explicit server-side super-admin check +3. admin UI calls `/api/admin/**` +4. admin APIs inspect users, stores, subscriptions, requests, activity, and reports + +### E. Integration/webhook flow + +1. external provider posts callback/webhook +2. route handler validates payload/signature +3. route updates orders, subscriptions, integration state, or logs +4. merchant/admin UI later reads results through API/UI routes + +### F. AI/chat flow + +1. authenticated user accesses `/chat` or related AI pages +2. chat APIs manage sessions, messages, tools, models, embeddings, or provider proxies +3. chat state persists to Prisma tables + +--- + +## 4. Domain interaction map + +### Identity and tenancy + +- `User` +- `Account` +- `Session` +- `VerificationToken` +- `PendingSignup` +- `Organization` +- `Membership` +- `Store` +- `StoreStaff` +- `CustomRole` +- `CustomRoleRequest` + +Interaction pattern: + +- user identity is global +- org/store membership provides tenant context +- JWT enrichment caches effective role and permissions +- store-specific authorization relies on consistent API discipline + +### Commerce + +- `Product` +- `ProductVariant` +- `Category` +- `Brand` +- `ProductAttribute` +- `Customer` +- `Order` +- `OrderItem` +- `DiscountCode` +- `Review` +- `InventoryLog` +- `InventoryReservation` + +Interaction pattern: + +- store-scoped catalog feeds storefront pages and merchant dashboard +- checkout/order APIs bridge storefront activity into internal order management +- inventory is tightly coupled to orders and reservation logic + +### Billing and subscriptions + +- `SubscriptionPlanModel` +- `Subscription` +- `SubscriptionLog` +- `SubPayment` +- `Invoice` +- `InvoiceItem` +- store-level subscription fields on `Store` + +Interaction pattern: + +- normalized billing tables coexist with duplicated plan/status fields on `Store` +- this increases architectural ambiguity and drift risk + +### Integrations and logistics + +- Facebook models +- Pathao fields and shipping APIs +- payment callbacks/webhooks +- `Webhook` +- `WebhookDelivery` + +Interaction pattern: + +- integration logic spans route handlers, services, and database tables +- webhook surfaces are broad and structurally important to order lifecycle correctness + +### Analytics, AI, and content + +- `LandingPage` +- `LandingPageVersion` +- `ChatSession` +- `ChatMessage` +- `ChatAttachment` +- analytics and performance metric tables + +Interaction pattern: + +- these are platform extensions layered on top of core commerce data +- architecture is functional but broad for a single repository + +--- + +## 5. Practical architecture strengths + +### Strong points + +1. **Single repository with coherent platform scope** + - the major business capabilities are in one place, which improves discoverability + +2. **Central auth middleware pattern for APIs** + - `apiHandler` appears to be the intended security and permission choke point + +3. **Prisma singleton pattern** + - consistent with modern Next.js + Prisma development practices + +4. **Proxy-based storefront routing** + - custom domain and subdomain support is a meaningful architectural capability + +5. **Reasonable separation between public store APIs and merchant APIs** + - even if naming is imperfect + +6. **Playwright presence** + - useful foundation for validating architecture through real flows + +--- + +## 6. Architecture weaknesses and friction points + +### 1. Repository breadth is very high for a single app boundary + +The repo combines: + +- platform admin +- merchant dashboard +- public storefront +- subscriptions/billing +- payments +- shipping +- integrations +- landing pages +- AI/chat +- analytics + +This is still manageable, but architectural complexity is now high enough that domain boundaries need to be documented and enforced more rigorously. + +### 2. Route taxonomy is semantically inconsistent + +Examples: + +- `/api/store` vs `/api/stores` +- `/api/subscription` vs `/api/subscriptions` +- `/api/webhook` vs `/api/webhooks` +- versioned `/api/v1/*` mixed with broad unversioned APIs + +This increases cognitive load and weakens discoverability. + +### 3. Too much business logic remains close to route handlers + +The route layer is not just orchestration; in many places it is also where domain decisions live. + +Risk: + +- duplicated logic +- permission drift +- harder testing +- lower reuse across UI/API entry points + +### 4. Subscription architecture has dual sources of truth + +Using both: + +- `Store.subscriptionPlan` / `subscriptionStatus` +- normalized `Subscription` and `SubscriptionPlanModel` + +creates ambiguity about which object is authoritative for: + +- entitlements +- billing status +- limits +- renewal/grace/trial state + +### 5. Build/runtime health is not currently an architectural invariant + +The current state allows: + +- TypeScript build errors to be ignored in Next build +- lockfile drift +- build failure at prerender + +That means the architecture cannot currently guarantee deployable integrity from the main repo state. + +### 6. Documentation is useful but not fully generated from source + +The existing docs are strong starting points, but route and environment docs have already drifted. + +Living documentation should ideally be generated or validated automatically. + +--- + +## 7. Suggested target-state blueprint + +### Recommended top-level architecture posture + +Keep the monorepo/repo as one deployed app, but make domain seams clearer: + +#### Presentation layer + +- `src/app/**` +- `src/components/**` + +#### Application/API orchestration layer + +- `src/app/api/**` +- lightweight request parsing, auth context resolution, response mapping + +#### Domain services layer + +- explicit per-domain service modules: + - auth + - stores + - catalog + - orders + - inventory + - subscriptions + - payments + - integrations + - analytics + - chat + +#### Persistence layer + +- Prisma access + query helpers +- remove stale query helper modules + +#### Integration adapters layer + +- Stripe +- SSLCommerz +- bKash +- Nagad +- Facebook +- Pathao +- Resend +- Redis + +This would preserve current deployment simplicity while making system interactions easier to reason about. + +--- + +## 8. Priority architecture improvements + +### High priority + +1. Fix build health: + - resolve `/_not-found` prerender crash + - fix metadata/key warnings + - stop relying on `ignoreBuildErrors: true` + +2. Restore reproducible installs: + - synchronize `package-lock.json` + +3. Choose one canonical subscription truth model + +4. Normalize API surface naming + +5. Convert stale helper modules into either: + - deleted dead code + - generated typed selects + - tested reusable query fragments + +### Medium priority + +6. Formalize domain service boundaries + +7. Add automated route/doc generation + +8. Add architecture decision records for: + - tenancy model + - billing truth model + - public API versioning strategy + - integration boundary strategy + +9. Add e2e smoke packs tied to seeded merchant flows + +--- + +## 9. Text interaction diagram + +```text +Browser / External System + | + +--> proxy.ts + | | + | +--> protected route redirect + | +--> subdomain/custom-domain rewrite to /store/[slug] + | + +--> Next.js pages/components (src/app, src/components) + | | + | +--> client/server UI composition + | +--> calls internal route handlers + | + +--> Route Handlers (/api/**) + | + +--> apiHandler / auth / permission checks + +--> domain services and helpers + +--> Prisma client + +--> PostgreSQL + | + +--> payment providers + +--> email provider + +--> Facebook / Pathao / webhook providers + +--> Redis / platform services +``` + +--- + +## 10. Architecture verdict + +Current architecture: capable, ambitious, and feature-rich, but carrying meaningful complexity debt. + +The platform is beyond "starter SaaS" scale and now needs stronger operational architecture discipline in: + +- build integrity +- route taxonomy +- canonical domain ownership +- documentation synchronization +- security and authorization consistency + +The system is viable, but the next quality jump should come from architectural consolidation rather than adding more top-level feature surfaces. diff --git a/docs/cursor/repository-review-2026-04-01/09-progress-blockers-and-next-steps.md b/docs/cursor/repository-review-2026-04-01/09-progress-blockers-and-next-steps.md new file mode 100644 index 00000000..50d3b748 --- /dev/null +++ b/docs/cursor/repository-review-2026-04-01/09-progress-blockers-and-next-steps.md @@ -0,0 +1,137 @@ +# Progress, Blockers, and Next Steps + +Date: 2026-04-01 + +## What was completed in this session + +- Reviewed repository structure, routes, docs, auth, proxy, Prisma schema, migrations, config, and dependency declarations +- Cross-validated current `docs/cursor` route docs against the codebase +- Attempted local environment setup +- Installed dependencies and generated Prisma client +- Ran `npm run build` and captured the failure mode +- Produced the review documentation pack in this folder + +## What could not be completed here + +### 1. Live merchant/store-owner walkthrough + +Not completed in this session because the machine did not have: + +- Docker +- native PostgreSQL +- a working seeded database + +and the app build currently fails before full successful export. + +### 2. End-to-end page-by-page action execution with real data + +Blocked by the same environment/runtime issues above. + +### 3. Final route list from a successful `npm run build` + +Attempted, but `npm run build` fails during prerendering of `/_not-found`. + +## Exact blockers + +### Blocker A: local database runtime unavailable + +- `docker compose up -d postgres` failed because Docker is not installed +- native Postgres tools (`psql`, `postgres`, `pg_ctl`, `initdb`) are absent + +### Blocker B: clean install reproducibility broken + +- `npm ci` fails because `package-lock.json` and `package.json` are out of sync + +### Blocker C: application build failure + +- build ends with: + - repeated React key warnings in head/metadata rendering + - `Error occurred prerendering page "/_not-found"` + - `TypeError: Cannot read properties of null (reading 'useState')` + +## Fastest path to finish the remaining requested work + +1. Fix lockfile drift: + - regenerate `package-lock.json` + - commit it +2. Run local PostgreSQL: + - preferred: `docker compose up -d postgres` +3. Run database setup: + - `npm run prisma:generate` + - `npm run prisma:migrate:dev` + - `npm run prisma:seed` +4. Fix build failure around `/_not-found` / metadata path +5. Re-run `npm run build` and capture authoritative route output +6. Start app: + - `npm run dev` +7. Log in with seeded merchant owner: + - `rafiq@techbazar.io` + - `Owner@123456` +8. Execute page-by-page walkthrough manually or with Playwright +9. Append runtime screenshots/findings to `05-ui-walkthrough-findings-and-limitations.md` + +## Suggested runtime validation checklist after blockers are removed + +### Authentication + +- Login with password tab +- Verify redirect to `/dashboard` +- Check pending/non-approved account behavior + +### Merchant dashboard + +- Dashboard widgets render +- Products list/new/edit +- Categories/brands/attributes +- Inventory +- Orders list/detail/COD screens +- Customers +- Coupons +- Emails +- Landing pages +- Integrations +- Webhooks +- Notifications +- Subscriptions +- Store settings / appearance / staff / roles / shipping + +### Public storefront + +- `/store/[slug]` +- product listing +- product detail +- cart +- checkout +- order tracking + +### Admin area + +- login as super admin +- `/admin/**` +- `/dashboard/admin/**` +- role requests +- store requests +- platform analytics + +## Confidence status by artifact + +| Artifact | Status | Confidence | +|---|---|---| +| Route inventory from filesystem | Completed | High | +| Existing docs cross-validation | Completed | High | +| Prisma schema review | Completed | High | +| Dependency usage review | Completed | Medium-High | +| Security/architecture findings | Completed | High | +| Environment reproducibility review | Completed | High | +| Merchant live walkthrough | Blocked | Low | +| Build-derived final route table | Blocked by build failure | Medium | + +## Best next action + +The single highest-value next step is to resolve: + +1. lockfile drift +2. local Postgres availability +3. the `/_not-found` prerender failure + +Once those three are fixed, the remaining requested runtime review work becomes straightforward and can be completed in a follow-up pass.