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: remove docs folder
Brad Barbinfbb2e0230478
diff --git a/docs/README.md b/docs/README.mddeleted file mode 100644index ae9d403714..0000000000--- a/docs/README.md+++ /dev/null@@ -1,3 +0,0 @@-# Carbon Documentation--- We've got to convert this into a site still, but here's some a few documents to get you started. The `/llm/cache` also has great info.diff --git a/docs/fetching.mdx b/docs/fetching.mdxdeleted file mode 100644index 1d1b487553..0000000000--- a/docs/fetching.mdx+++ /dev/null@@ -1,161 +0,0 @@-# Fetching--The convention is to fetch data on the server and pass it to the UI with the `useLoaderData` hook. Here's how that works:--1. Data is fetched on the server in a `loader` function-2. The `loader` function gets a `client` by calling `requirePermissions`-3. The `client` is passed to the server-side service, and returns both `{ data, error }`-4. The `loader` function redirects in the case of an error and returns the data in the case of no error-5. The component uses the `useLoaderData` hook to expose the data to the UI--<Callout>- Fetching should not be done with a `useEffect` hook. This is because the- `useEffect` hook is not called on the server, so the data will not be- available on the first render. Instead, use the `useLoaderData` hook.-</Callout>--Here's an example of simple route that fetches data from a service and displays it in a table:--```tsx-// app/routes/x+/resources+/partners.tsx--// loader is run on the server-export async function loader({ request }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, {- view: "resources",- role: "employee",- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const name = searchParams.get("name");- const { limit, offset, sorts } = getGenericQueryFilters(searchParams);-- const partners = await getPartners(client, {- name,- limit,- offset,- sorts,- });-- if (partners.error) {- return redirect(- path.to.resources,- await flash(request, error(partners.error, "Failed to load partners"))- );- }-- return json({- partners: partners.data ?? [],- count: partners.count ?? 0,- });-}--// data is passed to the UI with the useLoaderData hook-export default function Route() {- const { partners, count } = useLoaderData<typeof loader>();-- return (- <VStack spacing={0}>- <PartnersTable data={partners} count={count} />- <Outlet />- </VStack>- );-}-```--Here's an example of two services that fetch data from the database. The `.server.ts` file extension ensures that the code is only executed on the server:--```tsx-// app/modules/resources/resources.server.ts--export async function getPartner(- client: SupabaseClient<Database>,- partnerId: string-) {- // select a single row from the partner table- return client- .from("partner")- .select(`id, hoursPerWeek, supplier(name)`)- .eq("id", partnerId)- .single();-}--export async function getPartners(- client: SupabaseClient<Database>,- args?: GenericQueryFilters & { name: string | null }-) {- // select the partner id, supplier name, and hours per week- let query = client- .from("partner")- .select(`id, supplier(name), hoursPerWeek`, { count: "exact" })- .eq("active", true);-- if (args?.name) {- // if a name argument is provided, filter by name- query = query.ilike("name", `%${args.name}%`);- }-- if (args) {- // sort by supplier name by default- query = setGenericQueryFilters(query, args, "supplier(name)");- }-- return query;-}-```--If a query becomes complex, the convention is to create a SQL view in the database and query that instead. Here's an example of a view that joins the `partner` and `supplier` tables:--<Tabs- items={[- "SQL",- "TypeScript",- ]}->- <Tab>-```sql-CREATE OR REPLACE VIEW "partners" WITH (security_invoker=on) AS- SELECT- p.id AS "supplierLocationId",- p."active",- p."hoursPerWeek",- s.id AS "supplierId",- s.name AS "supplierName",- a.city,- a.state,- array_agg(pa."abilityId") AS "abilityIds"- FROM "partner" p- INNER JOIN "supplierLocation" sl- ON sl.id = p.id- INNER JOIN "supplier" s- ON s.id = sl."supplierId"- INNER JOIN "address" a- ON a.id = sl."addressId"- INNER JOIN "partnerAbility" pa- ON pa."partnerId" = p.id- WHERE p."active" = true- GROUP BY p.id, p.active, p."hoursPerWeek", s.id, a.id, s.name, a.city, a.state-;-```- </Tab>- <Tab>-```ts-export async function getPartner(- client: SupabaseClient<Database>,- partnerId: string-) {- return client- .from("partners")- .select("*")- .eq("supplierLocationId", partnerId)- .single();-}-```- </Tab>-</Tabs>-<Callout>- For more information on query building, see the [Supabase- documentation](https://supabase.io/docs/reference/javascript/select)-</Callout>-```diff --git a/docs/integrations/radan.md b/docs/integrations/radan.mddeleted file mode 100644index 82c48f27cb..0000000000--- a/docs/integrations/radan.md+++ /dev/null@@ -1,121 +0,0 @@-# Radan Integration--> **⚠️ Work in Progress**->-> This integration is currently under development and may not be fully functional. Please check back later for updates.--## Setup--The integration requires two steps:--1. Enabling the integration in Carbon-2. Generating an API Key for the Radan client--### Enabling the integration in Carbon--1. In Carbon, navigate to Settings > Integrations-2. Install the Radan integration-3. Select the relevant processes (e.g. Laser, Plasma)--### Generating an API Key for the Radan client--1. In Carbon, navigate to Settings > API Key-2. Generate a new API Key and save it.--## Using the API--Now you can fetch data for the integration using your API key:--```bash-curl 'https://app.carbon.ms/api/integrations/radan/v1' \--H "carbon-key: <your-api-key>"-```--Here's what an error looks like:--```json-{- "success": false,- "error": "Integration not active"-}-```--And here's what a success looks like:--> **⚠️ Heads Up!**->-> There is no mechanism in Carbon to determine which file is relevant for nesting so we must send them all (in the documents array)--```json-{- "success": true,- "data": [- {- "id": "pjSnUdrsFZmWDbCN1hvi2",- "assignee": null,- "description": "Laser",- "documents": [- {- "name": "X32329302.dxf",- "id": "d44c320d-b792-49da-b0fc-954cd09ed044",- "updated_at": "2025-09-02T12:39:03.795Z",- "created_at": "2025-09-02T12:39:03.795Z",- "last_accessed_at": "2025-09-02T12:39:03.795Z",- "metadata": {- "eTag": "\"8cddafa69a599294d7edd2ab359bc4ec\"",- "size": 28450,- "mimetype": "application/dxf",- "cacheControl": "max-age=43200",- "lastModified": "2025-09-02T12:39:03.788Z",- "contentLength": 28450,- "httpStatusCode": 200- },- "bucket": "parts"- }- ],- "itemDescription": "X32329302",- "itemId": "item_L2Pou8zCzNtZRzb9uyNMSD",- "itemReadableId": "X32329302",- "jobCustomerId": "cust_YVLo9Pkj2M9nShpwu5Ezaq",- "jobDeadlineType": "Hard Deadline",- "jobDueDate": "2025-05-15",- "jobId": "job_PVuhmo2W16NBy2Zsn9Dpy5",- "jobLocationName": "Headquarters",- "jobMakeMethodId": "jmm_S6DhS6kyTqbEoLyAXBthHs",- "jobReadableId": "J000001",- "jobStatus": "Ready",- "laborTime": 0,- "laborUnit": "Minutes/Piece",- "machineTime": 2,- "machineUnit": "Minutes/Piece",- "materialDimension": "1/4\"",- "materialFinish": null,- "materialForm": "Plate",- "materialGrade": "A36",- "materialItemDescription": "A36 Steel Plate 1/4\"",- "materialItemReadableId": "A36-STEEL-PLT-1/4\"",- "materialSubstance": "Steel",- "operationOrder": 1,- "operationOrderType": "After Previous",- "operationQuantity": 20,- "operationStatus": "Ready",- "parentMaterialId": null,- "priority": 1,- "processId": "pr_D1sq4wcav2cixyzf7C9Xci",- "quantityComplete": 0,- "quantityScrapped": 0,- "salesOrderId": "so_EjraNLcHiMNM7NzR9enVSC",- "salesOrderLineId": "8U5bd4Hzzvxp59jkYjj64e",- "salesOrderReadableId": "SO000001",- "setupTime": 20,- "setupUnit": "Total Minutes",- "tags": [],- "workCenterId": null- }- ]-}-```--## Webhook--A webhook will be implemented for the data to be returned that uses the same auth mechanism, but this will be determined at a later date.diff --git a/docs/permissions.mdx b/docs/permissions.mdxdeleted file mode 100644index e7e77ac872..0000000000--- a/docs/permissions.mdx+++ /dev/null@@ -1,153 +0,0 @@-# Permissions--There are two types of permissions in the system:--1. **Module permissions** - These are permissions that are specific to a module. For example, a user may have permission to view the sales module, but not to create, update or delete sales.-2. **Role permissions** - These are permissions that are specific to a role. For example, customers may be able to view the sales module, but a customer role limits the data to only their own sales, where an employee with the same permission can view all sales.--A user's permissions are stored in the `userPermissions` table and the role is stored in the `auth.users` table in the `raw_app_meta_data` column.--The JSON permissions data in that column something like this:--```json-{- "role": "employee",- ...- "sales_view": true,- "sales_create": true,- "sales_update": true,- "sales_delete": false,- ...- "purchasing_view": false,- "purchasing_create": false,- "purchasing_update": false,- "purchasing_delete": false,- ...-}-```--Each user has a **role**, which may be one of the following:--- `employee`-- `customer`-- `supplier`--Additionally, each user has a set of permissions for each module. Generally, the permissions are:--- `<module>_view`-- `<module>_create`-- `<module>_update`-- `<module>_delete`--Permissions are managed within the user module. **An employees' permissions are set according to the default permissions for their employee type when the user is created**. Each employee may then be fined tuned for individual permissions in the users module. There is also an option to bulk update permissions for employees.--Currently, all customers and suppliers have hard-coded permissions, which are set when the customer account or supplier account is created.--## Permissions in the Code--There are three places where permissions can be used in the code. In order of precedence, they are:--1. **Database row-level security (RLS)** - an in-database policy, written in SQL, that limits the data that a user can see or modify.-2. **Server-side permission checks** - a helper function that checks the user's permissions before making a call to the database.-3. **Client-side permission checks** - a helper function that checks the user's permissions before making a call to the server.--It is most important to use RLS. But server-side and client-side mechanisms can be used as additional security measures. RLS is expensive, so we use server-side and client-side checks to avoid making unnecessary calls to the database.--### Database Row-Level Security--Here is an example of how to use RLS policies to limit a user's rights to modify a table using the `get_my_claim` function. This is SQL that's run against the database to create a security policy for the `customer` table. If you're not familiar with the `::bolean` and `::jsonb` syntax, that's just casting the value to a boolean or jsonb type. The `get_my_claim` function is a custom function that returns the value of a claim from the user's permissions record. The `auth.uid()` function returns the user's ID.--```sql--- SQL---- 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('module_view')- )- );--CREATE POLICY "INSERT" ON "entityName"- FOR INSERT- TO authenticated- WITH CHECK (- "companyId" IN (- SELECT "companyId"- FROM get_companies_with_employee_permission('module_create')- )- );--CREATE POLICY "UPDATE" ON "entityName"- FOR UPDATE- TO authenticated- USING (- "companyId" IN (- SELECT "companyId"- FROM get_companies_with_employee_permission('module_update')- )- );--CREATE POLICY "DELETE" ON "entityName"- FOR DELETE- TO authenticated- USING (- "companyId" IN (- SELECT "companyId"- FROM get_companies_with_employee_permission('module_delete')- )- );-```--### Server-Side Permission Checks--We provide a helper function called `requirePermissions` that can be used to check the user's permissions before making a call to the database. This method is almost always called in an action (data write) or a loader (data fetch).--Here is an example of how to use it in a loader:--```tsx-export async function loader({ request }: LoaderFunctionArgs) {- const { client } = requirePermissions(request, {- view: "sales",- role: "employee",- });-- // call to the database-}-```--In this example, the user must have the `sales_view` permission and the `employee` role in order to access the loader. If the user does not have the required permissions, an `Access denied` error will be thrown, and the user will be redirected to the root page.--We can also required multiple permissions. In the next example, the user must have the `sales_update` permission and the `users_update` permission in order to invoke the action:--```tsx-export async function action({ request }: ActionFunctionArgs) {- const { client } = requirePermissions(request, {- update: ["sales", "users"],- });-- // call to the database-}-```--### Client-Side Permission Checks--Finally, we can use client-side permission checks to limit what the user can do in the UI. This is done using the `usePermissions` hook. It provides two methods:--1. `can` - a function that takes a module (sales) and an action (view, create, update, delete) and returns a boolean indicating whether the user has the required permission.-2. `is` - a function that takes a role (employee, customer, supplier) and returns a boolean indicating whether the user has the required role.--Here's an example of how we might use client-side permission checks to hide the NewSalesForm component if the user does not have the `sales_create` permission:--```tsx-import { usePermissions } from "~/hooks";--export default function SalesList() {- const permissions = usePermissions();-- return <>{permissions.can("create", "sales") && <NewSalesForm />}</>;-}-```diff --git a/docs/principles.mdx b/docs/principles.mdxdeleted file mode 100644index f83bca125e..0000000000--- a/docs/principles.mdx+++ /dev/null@@ -1,46 +0,0 @@-# Principles--Decision-making is guided by four principles:--1. Simplicity-2. Extensibility-3. Openness-4. Productivity--## Simplicity--We understand that manufacturers don't often have the luxury of large teams of developers. Often a single software developer will be responsible for many custom applications. Our goal is to provide **a simple platform with a single database** that manufacturers can use as **the heart of their digital operations**.--To provide simplicity we use these approaches:--- Best open-source software-- Minimal languages and setup (npm, TypeScript and SQL)-- Minimal dependencies-- Single-purpose examples and templates-- Detailed documentation-- Total transparency--## Extensibility--**Every manufacturer has unique needs that are not covered by the standard platform**. We want to make it easy to extend the platform to meet their needs.--To provide extensibility we have the following goals:--- Easy to add custom applications-- Easy to add API endpoints-- Easy to add custom database tables-- Easy to add modules and interfaces to the primary application--## Openness--The ERP system is the heart of a business' digital operation. We want to make sure that they can easily integrate with other systems and customize it in any way that they need. **The only real way to do this that to make the source code available**.--An open source ERP system has a number of benefits, including:--- Lower costs-- Greater flexibility-- Better security--## Productivity--When making decisions, we aim to **optimize for long-term developer productivity**. We take it as a given that everyone wants more features. But in order to quickly provide new features over time, we need to make sure that the platform is easy to use and maintain. This may mean that we have a steeper learning curve in the short term, but it should pay off in the long term.diff --git a/docs/realtime.mdx b/docs/realtime.mdxdeleted file mode 100644index 5efe12e4de..0000000000--- a/docs/realtime.mdx+++ /dev/null@@ -1,102 +0,0 @@-# Realtime--There are two basic use cases for realtime data in Carbon ERP:--1. Listening for async events to complete-2. Minimizing the number of requests for popular data--## Listening for async events to complete--When a user performs an action that triggers an async event (a job is inserted into a queue), the UI should listen for updates to the table to be updated.--This can be done easily with the `useRealtime` hook:--```tsx-// listen for udpates to the receipt table-useRealtime("receipt");-```--A smaller subset of the table can be listened to by passing a second argument. Here we listen for the rows with an `id` of `1`, `2`, or `3`:--```tsx-useRealtime("receipt", "id=in.(1,2,3)");-```--Whenever a row is updated, the data for the page will be re-fetched.--## Minimizing the number of requests for popular data--Some data like the list of parts, customers, and suppliers are used on many pages. And regularly refetching thousands of rows is not ideal. To avoid making a request for this data on every page, we load it once in the `<RealtimeDataProvider>` on page load. We then put the data from each table into a nanostore hook that has a getter and setter that can be accessed from any page. For example:--```tsx-import { useParts } from "~/stores";--const [parts, setParts] = useParts();-```--Without realtime, this data would quickly become stale. To keep data fresh, the `<RealtimeDataProvider>` listens for updates to the table and update the nanostore hook accordingly. This means that the data will be updated on every page that uses the hook.--Here is the basic pattern for listening to updates to a table in the `<RealtimeDataProvider>` component and updating the store:--```tsx-const { supabase } = useSupabase();-const [, setParts] = useParts();--useEffect(() => {- // fetch the all parts from the database and setParts to it's initial value- fetchData();-- // listen for updates to the table and update the parts store- const channel = supabase- .channel("realtime:core")- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "part",- },- (payload) => {- switch (payload.eventType) {- case "INSERT":- const { new: inserted } = payload;- setParts((parts) => [- ...parts,- {- id: inserted.id,- name: inserted.name,- replenishmentSystem: inserted.replenishmentSystem,- },- ]);- break;- case "UPDATE":- const { new: updated } = payload;- setParts((parts) =>- parts.map((p) => {- if (p.id === updated.id) {- return {- ...p,- name: updated.name,- replenishmentSystem: updated.replenishmentSystem,- };- }- return p;- })- );- break;- case "DELETE":- const { old: deleted } = payload;- setParts((parts) => parts.filter((p) => p.id !== deleted.id));- break;- default:- break;- }- }- )- .subscribe();-- return () => {- if (channel) supabase?.removeChannel(channel);- };-}, []);-```diff --git a/docs/supabase-pagination.md b/docs/supabase-pagination.mddeleted file mode 100644index e3c7df3e5a..0000000000--- a/docs/supabase-pagination.md+++ /dev/null@@ -1,179 +0,0 @@-# Supabase Pagination Utilities--## Overview--Supabase has a default limit of 1000 rows per request. To handle queries that might return more than 1000 rows, we've implemented pagination utilities that automatically handle batching and fetching all records.--## Utilities--### `fetchAllRecords<T>(baseQuery)`--Fetches all records from a Supabase query by automatically handling pagination.--```typescript-import { fetchAllRecords } from "~/utils/supabase-pagination";--const query = client.from("items").select("*").eq("companyId", companyId);--const result = await fetchAllRecords(query);-// result.data contains ALL items, not just first 1000-```--### `fetchAllFromTable<T>(client, tableName, selectColumns, filterFn)`--Helper function for simple table queries that need all records.--```typescript-import { fetchAllFromTable } from "@carbon/database";--const result = await fetchAllFromTable(- client,- "items",- "id, name, type",- (query) => query.eq("companyId", companyId).eq("active", true).order("name")-);-```--### `fetchRecordsInBatches<T>(baseQuery, batchSize)`--Async generator for processing large datasets in batches.--```typescript-import { fetchRecordsInBatches } from "~/utils/supabase-pagination";--const query = client.from("items").select("*").eq("companyId", companyId);--for await (const { data, batch, hasMore } of fetchRecordsInBatches(- query,- 500-)) {- console.log(`Processing batch ${batch} with ${data.length} items`);- // Process each batch of 500 items- await processItems(data);-}-```--## When to Use--### ✅ Use pagination utilities for:--- **RealtimeDataProvider queries** - Fetching all items, customers, suppliers, etc. for local storage-- **List functions** - `getPartsList()`, `getMaterialsList()`, etc. used in dropdowns-- **Export functions** - When exporting all records to CSV/Excel-- **Bulk operations** - Processing all records of a certain type-- **Any query that could potentially return >1000 rows**--### ❌ Don't use for:--- **UI pagination** - Use existing `setGenericQueryFilters()` with limit/offset-- **Single record lookups** - `.single()` queries-- **Small datasets** - Tables that will never exceed 1000 rows-- **Performance critical paths** - When you specifically need only the first N records--## Migration Examples--### Before (❌ Could hit 1000 row limit)--```typescript-export async function getItemsList(- client: SupabaseClient<Database>,- companyId: string-) {- return client- .from("item")- .select("id, name, type")- .eq("companyId", companyId)- .eq("active", true)- .order("name");-}-```--### After (✅ Handles unlimited rows)--```typescript-import { fetchAllFromTable } from "@carbon/database";--export async function getItemsList(- client: SupabaseClient<Database>,- companyId: string-) {- return fetchAllFromTable(client, "item", "id, name, type", (query) =>- query.eq("companyId", companyId).eq("active", true).order("name")- );-}-```--## Return Type--All pagination utilities return a `PaginatedResult<T>`:--```typescript-interface PaginatedResult<T> {- data: T[]; // All fetched records- count: number | null; // Total count (from first request)- error: any; // Error if query failed-}-```--## Performance Considerations--- **Batch size**: Default is 1000 (Supabase's limit). Can be customized for memory optimization-- **Memory usage**: All records are loaded into memory. Use `fetchRecordsInBatches` for very large datasets-- **Network requests**: Makes multiple requests automatically. Progress can be tracked with the generator approach-- **Caching**: Results are not cached. Consider implementing caching at the application level for frequently accessed data--## Example: Complex Query with Pagination--```typescript-import { fetchAllRecords } from "~/utils/supabase-pagination";--export async function getAllActiveItemsWithSuppliers(- client: SupabaseClient<Database>,- companyId: string-) {- const query = client- .from("items")- .select(- `- id,- name,- type,- supplier:supplierId (- id,- name- )- `- )- .eq("companyId", companyId)- .eq("active", true)- .order("name");-- const result = await fetchAllRecords(query);-- if (result.error) {- throw new Error(`Failed to fetch items: ${result.error.message}`);- }-- return result.data;-}-```--## Testing--When testing functions that use pagination utilities, the utilities will work normally but you can mock them if needed:--```typescript-import { fetchAllFromTable } from "@carbon/database";--// Mock for testing-jest.mock("~/utils/supabase-pagination", () => ({- fetchAllFromTable: jest.fn(),-}));--// In test-(fetchAllFromTable as jest.Mock).mockResolvedValue({- data: mockItems,- count: mockItems.length,- error: null,-});-```diff --git a/docs/writing.mdx b/docs/writing.mdxdeleted file mode 100644index a557934d52..0000000000--- a/docs/writing.mdx+++ /dev/null@@ -1,200 +0,0 @@-# Data Writes--Data writes should include:--1. An HTML form-2. Client-side validation in the component-3. Server-side validation in an action-4. A call to the service layer to perform the write--## Validation--Client-side validation and server-side validation can be done with the same validator. The convention is to store all validators for a module in `app/<module>/services/<module>.form.ts`. We use `zod` and `zod-form-data` for form validation. Here's an example of a simple validator:--```ts-import { z } from "zod";-import { zfd } from "zod-form-data";--export const personValidator = z.object({- // optional, parsed as string or undefined- id: zfd.text(z.string().optional()),- // required, parsed as string- name: z.string().min(1, { message: "Name is required" }),- // optional, parsed as number or undefined- age: zfd.numeric(z.number().optional()),- // required, parsed as boolean- male: zfd.checkbox(),-});-```--In this example, we have a validator for a person form. For most fields, `z.string()` will suffice, but sometimes, we want to parse the validated form values as numbers or booleans. In those cases, we use `zfd.numeric()` and `zfd.checkbox()`. There are fancier things you can do, but this example should cover 90% of use cases.--<Callout>- For more information on the validators, see the [remix-validated-form- documentation](https://www.remix-validated-form.io/)-</Callout>--## Client-Side Validation--On the client-side, there are two major components to be aware of:--1. Our form validation component from the [remix-validated-form](https://www.remix-validated-form.io/) package called `ValidatedForm` which accepts a `validator` prop.-2. Our form input components from `~/components/Form` which are designed to be used inside of `ValidatedForm`--Here's an example of how they work together on the client-side:--```tsx-import { ValidatedForm } from "remix-validated-form";-import { Boolean, Hidden, Input, Numeric, Submit } from "~/components/Form";-import { personValidator } from "~/modules/people";---const Form = ({initialValues}: FormProps) => {- return (- <ValidatedForm- method="post"- action="/path/to/the/action/route"- validator={personValidator}- defaultValues={initialValues}- >- <Hidden name="id" />- <Input name="name" label="Name">- <Numeric name="age" min={0} />- <Boolean name="male" label="Male" />- <Submit>Save</Submit>- </ValidatedForm>- )-}-```--The form is validated on the client-side before the form is submitted. If the form is invalid, the user can't submit the form until they fix the errors. If the form is valid, the user can submit the form and the server-side validation will run with the same validator.--## Server-Side Validation--On the server-side, we use the same validator in the `action` function to validate the form data. If the form data is invalid, we return the form with the errors. If the form data is valid, we call the service layer to perform the write.--```tsx-import { validator, validationError } from "@carbon/form";-import { createPerson, personValidator } from "~/modules/people";--export async function action({ request }: ActionFunctionArgs) {- const { client } = await requirePermissions(request);-- const validation = await validator(personValidator).validate(await request.formData());-- if (validation.error) {- return validationError(validation.error);- }-- const { name, male, age } = validation.data;-- await createPerson(client, {- name,- male,- age- });-- return redirect(- "/path/to/the/next/page",- await flash(request, success("Person created."))- );-```--## Service Layer--Finally, let's have a look at our service layer. The service layer is where we perform the actual write to the database using the `client` returned from `requirePermissions`. The convention is to store all service layer functions in `app/<module>/services/<module>.server.ts`. Including `.server` in the filename is important because it tells Remix to only include the file in the server bundle.--Here's an example of a simple service layer function:--```ts-export async function createPerson(- client: SupabaseClient<Database>,- person: {- name: string;- male: boolean;- age?: number;- }-) {- return client.from("people").insert(person);-}-```--<Callout>- For more information on the service layer, see the [Supabase- documentation](https://supabase.io/docs/reference/javascript/insert)-</Callout>--## Transactions--When a database transaction is needed, use a deno-based edge function. The reason for this is that the supabase client currently does not support transactions.--To create a new edge function run `npm run db:function:new <name-of-function>`--This will create a new edge function in `packages/database/supabase/functions/<name-of-function>`.--The pattern for the transaction looks like this:--```ts-import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";-import type { SupabaseClient } from "https://esm.sh/@supabase/[email protected]";--import type { Database } from "../../../src/types.ts";-import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";-import { corsHeaders } from "../lib/headers.ts";-import { getSupabaseServiceRole } from "../lib/supabase.ts";--// Use the supabase types to define a subset of the database we'll transact with-interface DB {- generalLedger: Database["public"]["Tables"]["generalLedger"]["Update"];- partLedger: Database["public"]["Tables"]["partLedger"]["Insert"];- valueLedger: Database["public"]["Tables"]["valueLedger"]["Insert"];-}--const pool = getConnectionPool(1);-const db = getDatabaseClient<DB>(pool);--serve(async (req: Request) => {- try {- if (req.method === "OPTIONS") {- return new Response("ok", { headers: corsHeaders });- }-- await db.transaction().execute(async (trx) => {- await trx- .updateTable("partLedger")- .set({- expectedCost: 0,- })- .where("id", "=", partLedgerId)- .execute();-- const generalLedgerIds = await trx- .insertInto("generalLedger")- .values(generalLedgerInserts)- .execute();-- const valueLedgerIds = await trx- .insertInto("valueLedger")- .values(valueLedgerInserts)- .execute();- });-- return new Response(- JSON.stringify({- data: null,- error: null,- }),- {- headers: { ...corsHeaders, "Content-Type": "application/json" },- }- );- } catch (err) {- console.error(err);- return new Response(JSON.stringify(err), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500,- });- }-});-```