Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
docs: update claude and cursor rules
Brad Barbin8b2938804d1e
diff --git a/.cursor/rules/main.mdc b/.cursor/rules/main.mdcnew file mode 100644index 0000000000..57d681a4ec--- /dev/null+++ b/.cursor/rules/main.mdc@@ -0,0 +1,7 @@+---+description:+globs:+alwaysApply: false+---++Reference markdown files the @claude/cache/ folder for conventions.diff --git a/.cursorrules b/.cursorrulesdeleted file mode 100644index 694407b3c1..0000000000--- a/.cursorrules+++ /dev/null@@ -1,41 +0,0 @@-You are an expert in TypeScript, Node.js, Postgres,Supabase, Remix, React, Shadcn UI, Radix UI and Tailwind.--Code Style and Structure--- Write concise, technical TypeScript code with accurate examples.-- Use functional and declarative programming patterns; avoid classes.-- Prefer iteration and modularization over code duplication.-- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).-- Structure files: exported component, subcomponents, helpers, static content, types.--Naming Conventions--- Use PascalCase for naming components (e.g., AuthWizard).-- Favor named exports for components.--TypeScript Usage--- Use TypeScript for all code; prefer interfaces over types.-- Avoid enums; use maps instead.-- Use functional components with TypeScript interfaces.--Syntax and Formatting--- Use the "function" keyword for pure functions.-- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.-- Use declarative JSX.--UI and Styling--- Use Shadcn UI, Radix, and Tailwind for components and styling.-- Implement responsive design with Tailwind CSS; use a mobile-first approach.--Key Conventions--- Use Remix for Data Fetching, Rendering, and Routing according to the Remix docs in the apps/carbon directory.- - Actions and loaders should begin with a `requirePermissions` check for the current module- - Use `useLoaderData` to get data from the loader- - Use `useActionData` to get data from the action- - Use `useSubmit` to submit forms- - Use `useNavigate` to navigate-- Use supabase for interacting with the database according to the Supabase docsdiff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000000..a1b09a8e18--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,26 @@+Your environment:++- This project is a manufacturing system called Carbon. It contains apps for ERP, MES, and a training app called university.++- Any time you want to know about the project, first use the Task tool to query the files in claude/cache/. Do this constantly, literally any time you want to know anything. Don't check the code first, ALWAYS check the cache.+- There are some specific workflows I have defined in claude/workflows/. ALWAYS use the Task tool to search for the relevant workflow file when told to do a workflow, then read and follow it.+- ALWAYS prefer your default tools over resorting to the Bash tool. You historically have a bad habit of doing `find ... | xargs ... grep` where you could just use your Grep tool. Avoid this! Just use the simple Grep tool.++Rules for using the Grep tool:++- ALWAYS try spawning a subtask to search the FAQ first if you are looking for something you aren't 100% confident exists.+- NEVER assume something exists with too specific a pattern. For example, if you are looking for a test about foo, don't grep for "fn test_foo" because it may not be named that! Think broader and more general.+- ALWAYS filter out the results from the `**/node_modules/**`, `**/.vercel/**` and `**/.turbo/**` directories which fill up with trash you don't want to search.+- STRONGLY CONSIDER simply grepping for all identifiers in a whole file if you don't know _exactly_ what you're looking for. Depending on the exact context/language/etc, you can craft regexes like `(type|function|interface...etc) .*[{;]$` or be more or less sophisticated as needed. Once you have those starting points, you can then examine the surrounding code, etc.+- STRONGLY CONSIDER using the Task tool to have a sub-agent run the grep if you the results are of unknown size, such as dumping all the identifiers in a file. Have it return just the relevant stuff.++Rules for using the TodoWrite tool:++- ALWAYS append this to every item: "Spawn subtasks to query the FAQ folder any time I need to learn something about the codebase. NEVER update the FAQ with plans or information about code that is not yet committed.". This is very important even though it seems silly.+- NEVER create an explicit todo item for updating the FAQ.++Rules for updating/writing to the FAQ:++- ALWAYS update the FAQ if you learn something about the codebase that was not in the FAQ and is not from a current change you're making (i.e. is committed).+- ALWAYS update the FAQ after a commit.+- NEVER update the FAQ about staged/uncommitted code.diff --git a/claude/cache/authentication-system.md b/claude/cache/authentication-system.mdnew file mode 100644index 0000000000..0720ccce30--- /dev/null+++ b/claude/cache/authentication-system.md@@ -0,0 +1,294 @@+# Authentication System in Carbon++## Overview++Carbon uses a robust authentication system built on top of Supabase Auth with custom session management and role-based permissions. The system supports multiple authentication methods and multi-company access.++## Package Structure (@carbon/auth)++Located at `/packages/auth/`, the auth package provides:++- **Client Configuration**: Supabase client setup with service role and anonymous access+- **Authentication Services**: Login, logout, magic links, OAuth (Google), and password reset+- **Session Management**: Cookie-based sessions with automatic token refresh+- **Permission System**: Role-based access control with company-specific permissions+- **User Management**: User creation, invitation flows, and account management++### Key Files:++- `src/lib/supabase/client.ts` - Supabase client configurations+- `src/services/auth.server.ts` - Server-side authentication logic+- `src/services/session.server.ts` - Session management and cookies+- `src/services/users.ts` - User queries and permission handling+- `src/types.ts` - Authentication type definitions++## Authentication Flow++### Login Process++1. **Magic Link Flow** (Primary):++ - User enters email on `/login`+ - System sends magic link via Supabase Auth+ - User clicks link, redirected to `/callback`+ - Callback exchanges tokens and creates session++2. **OAuth Flow** (Google):+ - User clicks "Continue with Google"+ - Redirected to Google OAuth+ - Returns to `/callback` for token exchange++### Session Management++- **Storage**: HTTP-only cookies named "carbon"+- **Refresh**: Automatic token refresh before expiry (configurable threshold)+- **Security**: Secure cookies in production, domain-specific+- **Persistence**: Sessions stored with Redis for caching permissions++### Logout Process++- POST to `/logout` destroys session cookies+- Clears both auth session and company selection+- Redirects to login page++## Database Schema++### Core Tables++**user** table:++```typescript+{+ id: string (UUID, matches Supabase auth.users.id)+ email: string+ firstName: string+ lastName: string+ fullName: string | null+ about: string+ avatarUrl: string | null+ active: boolean+ admin: boolean | null+ developer: boolean | null+ createdAt: string+ updatedAt: string | null+}+```++**company** table:++```typescript+{+ id: string (UUID)+ name: string+ email: string | null+ phone: string | null+ website: string | null+ addressLine1: string | null+ addressLine2: string | null+ city: string | null+ stateProvince: string | null+ postalCode: string | null+ countryCode: string | null+ taxId: string | null+ baseCurrencyCode: string+ logo fields: logoLight, logoDark, logoLightIcon, logoDarkIcon+ slackChannel: string | null+ updatedBy: string | null+}+```++**userToCompany** table (Junction):++```typescript+{+ userId: string (FK to user.id)+ companyId: string (FK to company.id)+ role: "employee" | "supplier" | "customer" (enum)+}+```++**apiKey** table:++```typescript+{+ id: string+ key: string+ name: string+ companyId: string (FK)+ createdBy: string (FK to user.id)+ createdAt: string+}+```++## User Registration/Invitation System++### Invitation Flow++1. **Create Invite**: Admin creates invite with email and role+2. **Send Invite**: Email sent with unique invitation code+3. **Accept Invite**: User visits `/invite/:code` to accept+4. **Account Creation**: If user doesn't exist, account is created+5. **Company Association**: User linked to company with specified role++### Invitation Routes++- `GET /invite/:code` - Display invitation acceptance page+- `POST /invite/:code` - Process invitation acceptance++### Current Registration Types++- **Employee Invites**: Full access based on employee type permissions+- **Customer Invites**: Limited access for customer portal features+- **Supplier Invites**: Access to supplier-specific features++### User Creation via OAuth++1. **Database Trigger**: When a user signs up via Google OAuth, a trigger (`on_auth_user_created`) fires on the `auth.users` table+2. **Public User Creation**: The trigger function `create_public_user()` creates entries in:+ - `public.user` table with email, firstName, lastName from OAuth metadata+ - `public.userPermission` table with the user's ID+3. **Identity Group**: A separate trigger creates an identity group for the user++### Self-Signup Flow (Not Yet Implemented)++- Login page has a "Sign up for free" link pointing to `/signup`+- The signup route is not yet implemented+- Current user creation only happens through:+ - Company invitations+ - OAuth authentication (Google)+ - Stripe checkout completion++## Permission System++### Structure++- **Role-based**: Users have roles (employee, customer, supplier)+- **Company-scoped**: Permissions are per-company+- **Module-based**: Permissions organized by system modules+- **Action-based**: CRUD permissions (view, create, update, delete)++### Permission Caching++- Permissions cached in Redis with key: `permissions:${userId}`+- Cache invalidated on role/permission changes+- Claims retrieved from database RPC function `get_claims`++### Permission Checking++The `requirePermissions` function validates:++- Access tokens or API keys+- Required permissions for specific actions+- Company context for multi-tenant access+- Role-based restrictions++## API Authentication++### Access Token Authentication++- Bearer tokens in Authorization header+- Tokens automatically refreshed before expiry+- Used for user session-based requests++### API Key Authentication++- Custom header: `carbon-key: <api-key>`+- Used for server-to-server communication+- Scoped to specific company context+- No user session required++## Security Features++### Rate Limiting++- Magic link requests: 5 per hour per IP+- Implemented using Upstash Redis+- Applied to login endpoints++### Session Security++- HTTP-only cookies prevent XSS+- Secure cookies in production+- SameSite protection+- Domain restrictions++### Token Management++- Automatic refresh before expiry+- Configurable refresh threshold+- Service role tokens for admin operations+- Proper token validation and verification++## Multi-Company Support++Users can belong to multiple companies with different roles:++1. **Company Selection**: Users choose active company context+2. **Permission Isolation**: Permissions are company-specific+3. **Data Isolation**: RLS (Row Level Security) enforces data separation+4. **Context Switching**: Users can switch between companies++## Authentication Routes++### Public Routes++- `/_public+/login` - Login page with magic link and OAuth+- `/_public+/callback` - OAuth callback and token exchange+- `/_public+/logout` - Session destruction+- `/_public+/invite/:code` - Invitation acceptance++### Protected Routes++- All routes under `/x+/` require authentication+- Permission checks applied at route level+- Automatic redirect to login if unauthenticated++## Configuration++Environment variables in `packages/auth/src/config/env.ts`:++- `SUPABASE_URL` - Supabase project URL+- `SUPABASE_ANON_KEY` - Public anonymous key+- `SUPABASE_SERVICE_ROLE_KEY` - Admin service role key+- `SESSION_SECRET` - Cookie encryption secret+- `REFRESH_ACCESS_TOKEN_THRESHOLD` - Token refresh timing+- `DOMAIN` - Cookie domain for production++## Onboarding Email System++### Email Templates++1. **WelcomeEmail**: Sent immediately after user creation+ - Personal welcome from founder Brad+ - Link to Carbon University+ - Located at `packages/documents/src/email/WelcomeEmail.tsx`++2. **GetStartedEmail**: Sent 1 minute after welcome email+ - Contains links to specific Carbon University courses+ - Covers basics, company setup, items, quoting, production, purchasing, and API+ - Located at `packages/documents/src/email/GetStartedEmail.tsx`++### Onboarding Task++- Trigger: `onboardTask` in `packages/jobs/trigger/onboard.ts`+- Triggered when:+ - User completes Stripe checkout (`checkout.session.completed` webhook)+ - Company is created during onboarding flow+- Process:+ 1. Creates contact in Resend email service+ 2. Sends WelcomeEmail+ 3. Waits 1 minute+ 4. Sends GetStartedEmail+- Only sends emails to users with 1 or fewer company associations++### Company Creation Flow++1. **New Company Creation** (`/onboarding/company`):+ - Creates new company with provided details+ - Seeds company with default data via `seedCompany()`+ - Creates headquarters location+ - Creates employee job record for the user+ - Updates session with new company ID++2. **Existing Company Update**:+ - Updates company and location details if they already existdiff --git a/claude/cache/coding-conventions.md b/claude/cache/coding-conventions.mdnew file mode 100644index 0000000000..ba7537df94--- /dev/null+++ b/claude/cache/coding-conventions.md@@ -0,0 +1,132 @@+# Carbon Coding Patterns++## Import Conventions++The project uses absolute imports with these patterns:++- `@carbon/*` - For packages+- `~/` - For app-specific imports (configured in tsconfig)++Example:++```typescript+import { Button } from "@carbon/react";+import { useUser } from "~/hooks/useUser";+```++## Component Patterns++### Component Structure++- Components are typically functional components using TypeScript+- Props are defined with TypeScript interfaces+- Components are exported from index.ts files for cleaner imports++### Common Component Patterns++```typescript+// Simple component with props+interface AvatarProps {+ name: string;+ size?: "sm" | "md" | "lg";+}++export function Avatar({ name, size = "md" }: AvatarProps) {+ // Component logic+}++// Components often use the @carbon/react library+import { Button, VStack } from "@carbon/react";+```++## Service Layer Pattern++Services handle business logic and database operations:++```typescript+// Example from sales.service.ts+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++export async function closeSalesOrder(+ client: SupabaseClient<Database>,+ orderId: string+) {+ return client+ .from("salesOrder")+ .update({+ status: "Closed",+ })+ .eq("id", orderId);+}+```++## Form Handling++The project uses a custom form library with validators:++```typescript+import { validator } from "@carbon/form";+import { z } from "zod";++export const customerValidator = validator(+ z.object({+ name: z.string().min(1),+ email: z.string().email(),+ })+);+```++## Route Patterns++### Loader Pattern++```typescript+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ view: "moduleName",+ });+ // Data fetching logic+ return json({ data });+}+```++### Action Pattern++```typescript+export async function action({ request }: ActionFunctionArgs) {+ const formData = await request.formData();+ // Handle form submission+ return json({ success: true });+}+```++## State Management++- Uses nanostores for global state+- React Query for server state+- Remix's built-in data loading for route-specific data++## Error Handling++- Uses try-catch blocks in services+- Returns structured error responses+- Type-safe error handling with TypeScript++## Authentication Pattern++```typescript+import { requirePermissions } from "@carbon/auth";++// In server-side code+const { client, companyId, userId } = await requirePermissions(request, {+ view: "sales",+});+```++## UI Patterns++- Consistent use of the Carbon design system+- Responsive design with Tailwind utilities+- Accessibility considerations (ARIA attributes)+- Dark mode support via theme systemdiff --git a/claude/cache/database-migration-patterns.md b/claude/cache/database-migration-patterns.mdnew file mode 100644index 0000000000..1692f93652--- /dev/null+++ b/claude/cache/database-migration-patterns.md@@ -0,0 +1,260 @@+# Database Migration Patterns Analysis++This document analyzes common patterns found in the Carbon database migrations.++## 1. Table Creation Patterns++### Basic Table Structure++Most tables follow this pattern:++```sql+CREATE TABLE "tableName" (+ "id" TEXT NOT NULL DEFAULT xid(),+ -- other columns+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "tableName_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "tableName_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "tableName_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "tableName_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);+```++## 2. ID Generation++### XID Function++- Primary keys use `TEXT NOT NULL DEFAULT xid()` for globally unique IDs+- XID generates 20-character ordered IDs using a custom domain: `CREATE DOMAIN public.xid AS CHAR(20)`+- The xid() function combines timestamp, machine ID, process ID, and counter for uniqueness++### Composite Primary Keys++- Many tables use composite primary keys: `PRIMARY KEY ("id", "companyId")`+- This enforces multi-tenancy at the database level++## 3. Company-Based Multi-Tenancy++### CompanyId Pattern++- Almost all business tables include `"companyId" TEXT NOT NULL`+- Foreign key to company table with CASCADE delete: `FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE`+- CompanyId is often part of the primary key for tenant isolation+- Index on companyId: `CREATE INDEX "tableName_companyId_idx" ON "tableName"("companyId");`++## 4. RLS (Row Level Security) Patterns++### Evolution of RLS Policies++#### Old Pattern (Pre-2025)++Used descriptive policy names with has_role and has_company_permission functions:++```sql+ALTER TABLE "tableName" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view items from their company" ON "tableName"+ FOR SELECT USING (+ has_role('employee', "companyId") AND+ "companyId" IN (+ SELECT "companyId" FROM "userToCompany" WHERE "userId" = auth.uid()::text+ )+ );++CREATE POLICY "Employees with module_create can create items" ON "tableName"+ FOR INSERT WITH CHECK (+ has_role('employee', "companyId") AND+ has_company_permission('module_create', "companyId")+ );+```++#### New Pattern (2025+)++Uses standardized policy names (SELECT, INSERT, UPDATE, DELETE) with helper functions:++```sql+ALTER TABLE "tableName" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."tableName"+FOR SELECT USING (+ "companyId" = ANY (+ (+ SELECT get_companies_with_employee_permission('module_view')+ )::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."tableName"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (+ SELECT get_companies_with_employee_permission('module_create')+ )::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."tableName"+FOR UPDATE USING (+ "companyId" = ANY (+ (+ SELECT get_companies_with_employee_permission('module_update')+ )::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."tableName"+FOR DELETE USING (+ "companyId" = ANY (+ (+ SELECT get_companies_with_employee_permission('module_delete')+ )::text[]+ )+);+```++### Helper Functions for RLS++- `get_companies_with_employee_permission(permission)` - Returns companies where user has specific permission+- `get_companies_with_employee_role()` - Returns all companies where user is an employee+- `get_companies_with_any_role()` - Returns all companies user has access to+- `get_company_id_from_foreign_key(id, table)` - Gets companyId through foreign key relationship++### Special Cases++#### User-Specific Tables++```sql+CREATE POLICY "SELECT" ON "lessonCompletion"+ FOR SELECT USING (auth.uid()::text = "userId");+```++#### Multi-Permission Policies++```sql+CREATE POLICY "SELECT" ON "public"."account"+FOR SELECT USING (+ "companyId" = ANY (+ SELECT DISTINCT unnest(ARRAY(+ SELECT unnest(get_companies_with_employee_permission('resources_view'))+ UNION+ SELECT unnest(get_companies_with_employee_permission('production_view'))+ UNION+ SELECT unnest(get_companies_with_employee_permission('accounting_view'))+ ))+ )+);+```++## 5. Common Column Types and Constraints++### Standard Columns++- `"id" TEXT NOT NULL DEFAULT xid()` - Primary key+- `"name" TEXT NOT NULL` - Common for most entities+- `"description" TEXT` - Optional descriptions+- `"active" BOOLEAN DEFAULT TRUE` - Soft delete pattern+- `"customFields" JSONB` - Extensibility++### Audit Columns++- `"createdBy" TEXT NOT NULL` - FK to user+- `"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()`+- `"updatedBy" TEXT` - Nullable FK to user+- `"updatedAt" TIMESTAMP WITH TIME ZONE` - Nullable timestamp++### Financial Columns++- `NUMERIC(10,2)` or `DECIMAL(10,2)` for monetary values+- `INTEGER` for quantities+- `REAL` for percentages++### Enums++```sql+CREATE TYPE "role" AS ENUM ('customer', 'employee', 'supplier');+CREATE TYPE "planType" AS ENUM ('Trial', 'Per User', 'Flat Fee');+```++## 6. Foreign Key Relationships++### Standard Pattern++```sql+CONSTRAINT "tableName_columnId_fkey" FOREIGN KEY ("columnId")+ REFERENCES "referencedTable"("id") ON DELETE CASCADE ON UPDATE CASCADE+```++### Common Variations++- `ON DELETE CASCADE` - For child records that should be deleted with parent+- `ON DELETE SET NULL` - For optional relationships+- `ON DELETE RESTRICT` - To prevent deletion if references exist++## 7. Indexes and Unique Constraints++### Standard Indexes++```sql+CREATE INDEX "tableName_companyId_idx" ON "tableName"("companyId");+CREATE INDEX "tableName_foreignKeyId_idx" ON "tableName"("foreignKeyId");+```++### Unique Constraints++```sql+CREATE UNIQUE INDEX "index_user_email_key" ON "user"("email");+CREATE UNIQUE INDEX "tableName_companyId_name_key" ON "tableName"("companyId", "name");+```++### Composite Indexes++```sql+CREATE INDEX "lessonCompletion_userId_courseId_lessonId_idx"+ ON "lessonCompletion" ("userId", "courseId", "lessonId");+```++## 8. Views++### Security Invoker Views++```sql+CREATE OR REPLACE VIEW "viewName" WITH(SECURITY_INVOKER=true) AS+ SELECT+ -- columns+ FROM "tableName" t+ INNER JOIN "relatedTable" r ON r.id = t."relatedId"+ -- other joins+```++## 9. Additional Patterns++### Approval Workflow++```sql+"approved" BOOLEAN NOT NULL DEFAULT false,+"approvedBy" TEXT,+CONSTRAINT "tableName_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id")+```++### Soft Delete++- Use `"active" BOOLEAN DEFAULT TRUE` instead of actual deletion+- Some tables use `"blocked" BOOLEAN DEFAULT FALSE`++### Generated Columns++```sql+"fullName" TEXT GENERATED ALWAYS AS ("firstName" || ' ' || "lastName") STORED+```++### Default Values++- Timestamps: `DEFAULT NOW()`+- Booleans: `DEFAULT TRUE` or `DEFAULT FALSE`+- IDs: `DEFAULT xid()`+- Arrays: `DEFAULT ARRAY[]::text[]`diff --git a/claude/cache/database-patterns.md b/claude/cache/database-patterns.mdnew file mode 100644index 0000000000..7c6ffcf151--- /dev/null+++ b/claude/cache/database-patterns.md@@ -0,0 +1,180 @@+# Carbon Database Patterns++## Database Technology++Carbon uses Supabase (PostgreSQL) as its database with:++- Type-safe queries using generated TypeScript types+- Row-level security (RLS) for authorization+- Real-time subscriptions for live updates++## Client Creation Patterns++### Standard Client++```typescript+import { getCarbon, requirePermissions } from "@carbon/auth";++// From request in loader or action+const { client } = requirePermissions(request, {+ view: "module",+});+```++### Service Role Client++```typescript+import { getCarbonServiceRole } from "@carbon/auth";++// Only available server-side+const client = getCarbonServiceRole();+```++### API Key Client++```typescript+import { getCarbonAPIKeyClient } from "@carbon/auth";++const client = getCarbonAPIKeyClient(apiKey);+```++## Query Patterns++### Basic Query++```typescript+const { data, error } = await client+ .from("customer")+ .select("*")+ .eq("companyId", companyId)+ .single();+```++### Complex Queries with Joins++```typescript+const { data } = await client+ .from("salesOrder")+ .select(+ `+ *,+ customer (+ id,+ name,+ ),+ salesOrderLine (+ *,+ item (+ id,+ name+ )+ )+ `+ )+ .eq("id", orderId);+```++## Service Function Patterns++Services typically follow this pattern:++```typescript+export async function updateCustomer(+ client: SupabaseClient<Database>,+ customerId: string,+ updates: Partial<Customer>+) {+ const { data, error } = await client+ .from("customer")+ .update(updates)+ .eq("id", customerId)+ .select()+ .single();++ if (error) {+ throw new Error("Failed to update customer");+ }++ return data;+}+```++## Type Safety++The project uses generated types from the database schema:++```typescript+import type { Database } from "@carbon/database";++type Customer = Database["public"]["Tables"]["customer"]["Row"];+type CustomerInsert = Database["public"]["Tables"]["customer"]["Insert"];+type CustomerUpdate = Database["public"]["Tables"]["customer"]["Update"];+```++## Transaction Patterns++For complex operations requiring multiple queries:++```typescript+// Using RPC functions for transactions+const { data, error } = await client.rpc("create_sales_order", {+ customer_id: customerId,+ lines: orderLines,+});+```++## Real-time Subscriptions++```typescript+const subscription = client+ .channel("sales_orders")+ .on(+ "postgres_changes",+ {+ event: "*",+ schema: "public",+ table: "salesOrder",+ },+ (payload) => {+ // Handle real-time updates+ }+ )+ .subscribe();+```++## Error Handling++```typescript+try {+ const { data, error } = await client.from("table").select().single();++ if (error) {+ console.error("Database error:", error);+ throw new Error("Failed to fetch data");+ }++ return data;+} catch (err) {+ // Handle error appropriately+ throw err;+}+```++## Migration Management++- Migrations are stored in `/packages/database/supabase/migrations/`+- Named with timestamps and descriptive names+- Applied automatically via Supabase CLI++## Common Tables++Based on the codebase, common tables include:++- `customer` - Customer information+- `supplier` - Supplier information+- `item` - Products/parts/materials+- `salesOrder` - Sales orders+- `purchaseOrder` - Purchase orders+- `employee` - Employee records+- `company` - Company/tenant informationdiff --git a/claude/cache/environment-configuration.md b/claude/cache/environment-configuration.mdnew file mode 100644index 0000000000..c6f9ebb123--- /dev/null+++ b/claude/cache/environment-configuration.md@@ -0,0 +1,116 @@+# Environment Variables and Configuration++## Environment Variable Management++### File Structure++- **Root `.env` file**: Main environment configuration file at `/Users/barbinbrad/Code/carbon/.env`+- **`.env.example`**: Template file showing all required environment variables+- **Symlinks**: Apps and packages use symlinks to the root `.env` file for consistency++### Key Environment Files++1. `/Users/barbinbrad/Code/carbon/.env` - Main configuration (gitignored)+2. `/Users/barbinbrad/Code/carbon/.env.example` - Template with all required variables+3. `/Users/barbinbrad/Code/carbon/.env.production` - Production-specific settings+4. App-specific symlinks:+ - `/apps/erp/.env` → symlink to root `.env`+ - `/apps/mes/.env` → symlink to root `.env`+ - `/apps/starter/.env` → symlink to root `.env`+ - `/packages/database/.env` → symlink to root `.env`+ - `/packages/kv/.env` → symlink to root `.env`++### Environment Variable Categories++#### Authentication & Security++- `SESSION_SECRET` - Required for session management+- `SUPABASE_ANON_KEY` - Public Supabase key+- `SUPABASE_SERVICE_ROLE_KEY` - Supabase admin key (server-only)+- `SUPABASE_URL` - Supabase instance URL++#### External Services++- `RESEND_API_KEY` - Email service API key+- `NOVU_APPLICATION_ID` & `NOVU_SECRET_KEY` - Notification service+- `POSTHOG_API_HOST` & `POSTHOG_PROJECT_PUBLIC_KEY` - Analytics+- `SLACK_BOT_TOKEN` - Slack integration+- `TRIGGER_ID`, `TRIGGER_API_KEY`, `TRIGGER_API_URL`, `TRIGGER_PUBLIC_API_KEY` - Trigger.dev job queue+- `UPSTASH_REDIS_REST_URL` & `UPSTASH_REDIS_REST_TOKEN` - Redis KV store+- `ONSHAPE_SECRET_KEY` - CAD integration+- `EXCHANGE_RATES_API_KEY` - Currency exchange rates++#### Stripe (Prepared but not integrated)++- Future variables will include:+ - `STRIPE_SECRET_KEY`+ - `STRIPE_WEBHOOK_SECRET`++#### Configuration++- `DEFAULT_EMAIL_ADDRESS` - Used in database seeding+- `VERCEL_URL` - Deployment URL+- `VERCEL_ENV` - Deployment environment (production/preview/development)++## Central Configuration Pattern++### Main Configuration File++`/packages/auth/src/config/env.ts` serves as the central environment configuration:++1. **Type-safe environment access**: Provides TypeScript interfaces for all env vars+2. **getEnv() utility**: Centralized function for accessing environment variables with options:+ - `isRequired`: Whether the variable must be set+ - `isSecret`: Whether the variable should be hidden from client-side code+3. **Browser vs Server**: Handles different environments appropriately+4. **Exports all environment constants**: Other packages import from here++### Usage Pattern++```typescript+import { SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY } from "@carbon/auth/config";+```++### Direct Usage++Some services access `process.env` directly:++- `/apps/erp/app/lib/resend.server.ts` - Uses `process.env.RESEND_API_KEY`++## Setup Process++### Automatic Setup Script++`/scripts/setup-env-files.ts` automates environment setup:++1. Creates symlinks from apps/packages to root `.env`+2. Updates `seed.sql` with the configured email address+3. Ensures consistency across the monorepo++### Manual Setup++1. Copy `.env.example` to `.env`+2. Fill in all required values+3. Run `npm run setup:env` to create symlinks++## Security Considerations++1. **Client vs Server Variables**:+ - Public variables exposed to browser via `getBrowserEnv()`+ - Secret variables only accessible server-side+2. **Git Security**: All `.env` files are gitignored+3. **Type Safety**: TypeScript interfaces prevent typos and ensure all required vars are set+4. **Validation**: `getEnv()` throws errors for missing required variables++## Development vs Production++- Development: Uses `http://localhost:3000` and local Supabase instance+- Preview: Uses Vercel preview URLs+- Production: Uses `https://app.carbonos.dev` and production services++## Adding New Environment Variables++1. Add to `.env.example` with placeholder value+2. Add TypeScript interface in `/packages/auth/src/config/env.ts`+3. Export constant using `getEnv()` function+4. Import and use from `@carbon/auth/config` in your codediff --git a/claude/cache/project-overview.md b/claude/cache/project-overview.mdnew file mode 100644index 0000000000..07531874aa--- /dev/null+++ b/claude/cache/project-overview.md@@ -0,0 +1,84 @@+# Carbon Project Overview++## Project Structure++Carbon is a manufacturing system built with modern web technologies. It consists of three main applications:++1. **ERP (Enterprise Resource Planning)** - Located at `/apps/erp/`+2. **MES (Manufacturing Execution System)** - Located at `/apps/mes/`+3. **University (Training App)** - Located at `/apps/university/`++## Technology Stack++### Frontend++- **Framework**: Remix (React-based)+- **UI Components**: Custom component library at `/packages/react/`+- **Styling**: Tailwind CSS+- **Forms**: Custom form library at `/packages/form/`+- **TypeScript**: Strict mode enabled++### Backend++- **Database**: Supabase (PostgreSQL)+- **Edge Functions**: Vercel Edge Runtime+- **Authentication**: Supabase Auth via `/packages/auth/`++### Build Tools++- **Monorepo**: NPM workspaces with Turbo+- **Bundler**: Vite+- **Linting**: ESLint with custom config+- **Formatting**: Prettier++## Package Structure++The monorepo uses NPM workspaces with packages located in `/packages/`:++- `auth` - Authentication services and utilities+- `database` - Database types and migrations+- `documents` - PDF/Email/ZPL document generation+- `form` - Form components and validation+- `kv` - Key-value store (Redis)+- `logger` - Logging utilities+- `notifications` - Notification services+- `react` - Shared React components+- `remix` - Remix-specific utilities+- `utils` - Common utilities++## Common Patterns++### File Organization++Each app follows a consistent structure:++- `components/` - React components+- `hooks/` - Custom React hooks+- `routes/` - Remix routes+- `services/` - Business logic and API calls+- `stores/` - State management (appears to use nanostores)+- `styles/` - CSS files+- `types/` - TypeScript types and validators+- `utils/` - Utility functions++### Module Organization++The ERP app organizes business logic into modules:++- Each module has its own folder in `/modules/`+- Contains `.models.ts`, `.service.ts`, and UI components+- Examples: sales, purchasing, inventory, accounting, etc.++### Database Access++- Uses Supabase client from `@carbon/auth`+- Type-safe queries with generated types from `@carbon/database`+- Service functions handle database operations++### Routing++- Uses Remix flat routes+- Protected routes under `x+/` prefix+- Public routes under `_public+/` prefix+- API routes under `api+/` prefix+- File serving routes under `file+/` prefixdiff --git a/claude/settings.local.json b/claude/settings.local.jsonnew file mode 100644index 0000000000..cd376c5910--- /dev/null+++ b/claude/settings.local.json@@ -0,0 +1,14 @@+{+ "permissions": {+ "allow": [+ "Bash(find:*)",+ "Bash(ls:*)",+ "Bash(mkdir:*)",+ "Bash(grep:*)",+ "Bash(rg:*)",+ "Bash(npm run db:migrate:*)",+ "Bash(npm run:*)"+ ],+ "deny": []+ }+}diff --git a/claude/workflows/database-migration.md b/claude/workflows/database-migration.mdnew file mode 100644index 0000000000..be300c02cb--- /dev/null+++ b/claude/workflows/database-migration.md@@ -0,0 +1,247 @@+# Database Migration Workflow++This workflow describes the process for creating and applying database migrations in the Carbon manufacturing system.++## Prerequisites++- Ensure you have the latest code from the main branch+- Check that your local database is running and accessible+- Verify you have the necessary permissions to modify the database schema+- Understand the multi-tenant architecture (all tables require companyId)++## Steps++### 1. Generate Migration File++Run the migration command:++```bash+npm run db:migrate <name-of-migration>+```++This will create a new migration file in `packages/database/supabase/migrations/` with the timestamp prefix.++### 2. Analyze the Migration Requirements++- Identify what database changes are needed (new tables, columns, indexes, etc.)+- Check existing schema to avoid conflicts+- Consider data migration needs if modifying existing tables+- Determine which module this belongs to (for updating .models.ts files)++### 3. Write Migration SQL++#### Carbon-Specific Patterns++All tables in Carbon follow these patterns:++##### ID Generation++```sql+-- Always use xid() for primary keys+"id" TEXT NOT NULL DEFAULT xid()+```++##### Multi-Tenancy++```sql+-- Every business table needs companyId+"companyId" TEXT NOT NULL,++-- Composite primary key+PRIMARY KEY ("id", "companyId"),++-- Foreign key to company table+FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE++-- Always index companyId+CREATE INDEX "tableName_companyId_idx" ON "tableName" ("companyId");+```++##### Standard Audit Columns++```sql+"createdBy" TEXT NOT NULL REFERENCES "user"("id"),+"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+"updatedBy" TEXT REFERENCES "user"("id"),+"updatedAt" TIMESTAMP WITH TIME ZONE+```++#### Complete Table Example++```sql+CREATE TABLE "entityyName" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "companyId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "active" BOOLEAN NOT NULL DEFAULT TRUE,++ -- Standard audit columns+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ -- Optional: Custom fields for extensibility+ "customFields" JSONB,+ "tags" TEXT[],++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);++-- Required indexes+CREATE INDEX "entityName_companyId_idx" ON "entityName" ("companyId");+CREATE INDEX "entityName_createdBy_idx" ON "entityName" ("createdBy");++-- Optional: Unique constraint scoped to company+ALTER TABLE "entityName" ADD CONSTRAINT "entityName_name_companyId_key"+ UNIQUE ("name", "companyId");+```++#### Row Level Security (RLS)++**IMPORTANT**: Use the new standardized RLS pattern (2025+):++```sql+-- Enable RLS+ALTER TABLE "entityName" ENABLE ROW LEVEL SECURITY;++-- Standardized policy names: SELECT, INSERT, UPDATE, DELETE+CREATE POLICY "SELECT" ON "entityName"+ FOR SELECT+ TO authenticated+ USING (+ "companyId" IN (+ SELECT "companyId"+ FROM get_companies_with_employee_permission(auth.uid(), 'module:view')+ )+ );++CREATE POLICY "INSERT" ON "entityName"+ FOR INSERT+ TO authenticated+ WITH CHECK (+ "companyId" IN (+ SELECT "companyId"+ FROM get_companies_with_employee_permission(auth.uid(), 'module:create')+ )+ );++CREATE POLICY "UPDATE" ON "entityName"+ FOR UPDATE+ TO authenticated+ USING (+ "companyId" IN (+ SELECT "companyId"+ FROM get_companies_with_employee_permission(auth.uid(), 'module:update')+ )+ );++CREATE POLICY "DELETE" ON "entityName"+ FOR DELETE+ TO authenticated+ USING (+ "companyId" IN (+ SELECT "companyId"+ FROM get_companies_with_employee_permission(auth.uid(), 'module:delete')+ )+ );+```++#### Common Column Types++- **IDs**: `TEXT NOT NULL DEFAULT xid()`+- **Names**: `TEXT NOT NULL`+- **Financial**: `NUMERIC` or `DECIMAL`+- **Quantities**: `INTEGER`+- **Timestamps**: `TIMESTAMP WITH TIME ZONE`+- **Booleans**: `BOOLEAN NOT NULL DEFAULT TRUE/FALSE`+- **JSON**: `JSONB` for custom fields++#### Creating Views++```sql+CREATE VIEW "module_entityView" WITH(SECURITY_INVOKER=true) AS+SELECT+ e.*,+ u."fullName" as "createdByFullName"+FROM "entityName" e+LEFT JOIN "user" u ON u."id" = e."createdBy";+```++### 4. Update Zod Validators++After creating the migration, update the appropriate `.models.ts` file in the ERP app:++```typescript+// apps/carbon/app/modules/[module-name]/[module-name].models.ts++import { z } from "zod";+import { zfd } from "zod-form-data";++// Base validator matching the database schema+export const entityValidator = z.object({+ id: z.string(),+ companyId: z.string(),+ name: z.string().min(1),+ description: z.string().optional(),+ active: z.boolean().default(true),+ createdBy: z.string(),+ createdAt: z.date(),+ updatedBy: z.string().optional(),+ updatedAt: z.date().optional(),+ customFields: z.any().optional(),+});++// Form validator for create/update operations+export const entityFormValidator = zfd.formData({+ name: zfd.text(z.string().min(1)),+ description: zfd.text(z.string().optional()),+ active: zfd.checkbox(),+ // Don't include audit fields in forms+});+```++### 5. Test Migration Locally++- Test the migration by running `npm run db:build`++## Best Practices++- Always use `xid()` for primary keys+- Include `companyId` in all business tables+- Use composite primary keys `("id", "companyId")`+- Follow the standardized RLS policy naming (SELECT, INSERT, UPDATE, DELETE)+- Add appropriate indexes for all foreign keys+- Use `NUMERIC` for financial amounts+- Include audit columns (createdBy, createdAt, updatedBy, updatedAt)+- Consider adding `customFields JSONB` for extensibility+- Add `tags TEXT[]` if it is a main document type+- Use transactions for multi-table operations+- Test migrations with existing data before deployment++## Common Pitfalls to Avoid++- Forgetting to add `companyId` to new tables+- Not including companyId in the composite primary key+- Using old RLS pattern instead of standardized names+- Forgetting to index foreign keys and companyId+- Not updating the corresponding .models.ts file+- Making nullable columns that should be required+- Not considering multi-tenant data isolation++## Migration Checklist++- [ ] Migration file created with `npm run db:migrate <name>`+- [ ] Table includes `id` with `DEFAULT xid()`+- [ ] Table includes `companyId` with proper foreign key+- [ ] Composite primary key on `("id", "companyId")`+- [ ] Standard audit columns included+- [ ] All necessary indexes created (especially on companyId)+- [ ] RLS policies created with standardized names+- [ ] Zod validators created/updated in .models.ts file+- [ ] Tests written for new functionality+- [ ] Multi-tenant isolation verified+- [ ] Migration tested on local database+- [ ] Team notified of pending database changesdiff --git a/claude/workflows/edge-function.md b/claude/workflows/edge-function.mdnew file mode 100644index 0000000000..d7fb9e0196--- /dev/null+++ b/claude/workflows/edge-function.md@@ -0,0 +1,331 @@+# Edge Function Workflow++This workflow describes the process for creating and extending Supabase Edge Functions in the Carbon manufacturing system.++## Prerequisites++- Ensure you have the latest code from the main branch+- Verify Supabase CLI is installed and configured+- Check that your local Supabase instance is running+- Understand the dual authentication pattern (API key + Bearer token)++## Steps++### 1. Generate Edge Function++Run the function creation command:++```bash+npm run db:function:new <description>+```++This will create a new function directory at `packages/database/supabase/functions/<description>/index.ts`.++### 2. Analyze the Function Requirements++- Identify the function's purpose and expected inputs/outputs+- Determine if it needs database access (Kysely vs Supabase client)+- Consider authentication requirements+- Plan for multi-tenancy (companyId handling)+- Identify any shared utilities or business logic needed++### 3. Implement the Edge Function++#### Standard Function Structure++```typescript+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { z } from "npm:zod@^3.24.1";+import { corsHeaders } from "../lib/headers.ts";+import { getSupabaseServiceRole } from "../lib/supabase.ts";+import { Database } from "../lib/types.ts";++// Input validation schema+const payloadValidator = z.object({+ companyId: z.string(),+ userId: z.string(),+ // Add your specific fields here+});++serve(async (req) => {+ // Handle CORS preflight+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ try {+ // Parse and validate input+ const payload = await req.json();+ const { companyId, userId, ...data } = payloadValidator.parse(payload);++ const authHeader = req.headers.get("Authorization");+ const token = authHeader?.replace("Bearer ", "") ?? null;+ if (token && !client) {+ client = getSupabase(token);+ authenticatedCompanyId = req.headers.get("x-company-id");+ await client.auth.setSession({+ access_token: token,+ refresh_token: token,+ });+ }++ // Authorization check+ if (!client || !authenticatedCompanyId || !authenticatedUserId) {+ return new Response("Unauthorized", {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 401,+ });+ }++ // Main function logic here+ const result = await performMainOperation(data, {+ client,+ companyId: authenticatedCompanyId,+ userId: authenticatedUserId,+ });++ return new Response(JSON.stringify({ success: true, ...result }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ });+ } catch (err) {+ console.error(`Error in ${req.url}:`, err);++ // Optional: Cleanup operations on error+ // Example: Revert status changes, rollback transactions, etc.++ return new Response(JSON.stringify({ error: err.message }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});++async function performMainOperation(+ data: any,+ context: { client: any; companyId: string; userId: string }+) {+ // Implement your main logic here+ // Use context.companyId for multi-tenancy+ // Use context.client for database operations+ // Use context.userId for audit trails+}+```++#### For Database-Heavy Operations (Using Kysely)++```typescript+import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import type { DB } from "../lib/types.ts";++// Inside your function+const pool = getConnectionPool(1);+const db = getDatabaseClient<DB>(pool);++// Use transactions for data consistency+await db.transaction().execute(async (trx) => {+ const result = await trx+ .insertInto("tableName")+ .values({+ id: nanoid(),+ companyId,+ createdBy: userId,+ ...data,+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ // Additional operations...+});+```++#### Input Validation Patterns++```typescript+// Simple validation+const payloadValidator = z.object({+ companyId: z.string(),+ userId: z.string(),+ name: z.string().min(1),+ amount: z.number().positive(),+});++// Discriminated union for multiple operation types+const payloadValidator = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("create"),+ companyId: z.string(),+ userId: z.string(),+ data: z.object({+ name: z.string(),+ // ... other fields+ }),+ }),+ z.object({+ type: z.literal("update"),+ companyId: z.string(),+ userId: z.string(),+ id: z.string(),+ data: z.object({+ name: z.string().optional(),+ // ... other fields+ }),+ }),+]);+```++### 4. Add Shared Utilities (If Needed)++If your function needs shared business logic, add it to appropriate directories:++- **Database utilities**: `packages/database/supabase/functions/lib/`+- **Business logic**: `packages/database/supabase/functions/shared/`++Example shared utility:++```typescript+// packages/database/supabase/functions/shared/accounting.ts+export async function createJournalEntry(+ trx: any,+ data: {+ companyId: string;+ userId: string;+ reference: string;+ entries: Array<{ account: string; debit?: number; credit?: number }>;+ }+) {+ // Shared accounting logic+}+```++### 5. Test the Edge Function++#### Local Testing++```bash+# Start Supabase local development+npm run db:start++# Test your function+curl -X POST 'http://localhost:54321/functions/v1/<function-name>' \+ -H 'Authorization: Bearer <token>' \+ -H 'Content-Type: application/json' \+ -H 'x-company-id: <company-id>' \+ -d '{+ "companyId": "<company-id>",+ "userId": "<user-id>",+ "data": {}+ }'+```++#### Integration Testing++- Test with both API key and Bearer token authentication+- Verify multi-tenancy isolation+- Test error scenarios (invalid input, unauthorized access)+- Check CORS headers work properly++### 6. Deploy and Monitor++#### Deployment++```bash+# Deploy to staging/production+npm run db:deploy+```++#### Monitoring++- Check function logs in Supabase dashboard+- Monitor performance metrics+- Set up alerts for error rates++## Carbon-Specific Patterns++### Multi-Tenancy Requirements++- Always filter operations by `companyId`+- Include `companyId` in all database inserts+- Use `companyId` from authenticated context, not payload++### Audit Trail Pattern++```typescript+const auditData = {+ createdBy: userId,+ createdAt: new Date().toISOString(),+ updatedBy: userId,+ updatedAt: new Date().toISOString(),+};+```++### Sequence Generation++```typescript+import { getNextSequence } from "../shared/sequences.ts";++const sequenceNumber = await getNextSequence(trx, "sequenceName", companyId);+```++### Error Cleanup Pattern++```typescript+catch (err) {+ console.error(`Error in functionName:`, err);++ // Cleanup operations+ if (createdRecordId) {+ await client+ .from("tableName")+ .update({ status: "Draft" })+ .eq("id", createdRecordId);+ }++ return new Response(JSON.stringify({ error: err.message }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+}+```++## Best Practices++- **Always handle CORS** with OPTIONS method+- **Use Zod validation** for all inputs+- **Implement dual authentication** (API key + Bearer token)+- **Include companyId filtering** for multi-tenancy+- **Use database transactions** for data consistency+- **Add comprehensive error handling** with cleanup logic+- **Follow consistent response format** with proper HTTP status codes+- **Include audit fields** (createdBy, updatedBy, timestamps)+- **Use TypeScript types** from the generated database schema+- **Add logging** with function name and key parameters+- **Handle environment variables** safely+- **Use shared utilities** to avoid code duplication++## Common Pitfalls to Avoid++- Forgetting to handle OPTIONS requests for CORS+- Not validating inputs with Zod schemas+- Missing companyId in database operations+- Not implementing proper error cleanup+- Using payload companyId instead of authenticated companyId+- Forgetting to use transactions for multi-table operations+- Not handling both authentication methods+- Missing proper TypeScript types+- Not including audit trail fields++## Function Checklist++- [ ] Function created with `npm run db:function:new <name>`+- [ ] CORS handling implemented (OPTIONS method)+- [ ] Input validation with Zod schema+- [ ] Dual authentication pattern implemented+- [ ] Multi-tenancy with companyId filtering+- [ ] Database operations use transactions where needed+- [ ] Error handling with cleanup logic+- [ ] Proper response format with HTTP status codes+- [ ] Audit fields included in database operations+- [ ] TypeScript types from database schema+- [ ] Function tested locally and with both auth methods+- [ ] Deployment tested in staging environment