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: move docs site to its own app
Brad Barbin00beff4658b3
diff --git a/apps/docs/.eslintrc.js b/apps/docs/.eslintrc.jsnew file mode 100644index 0000000000..1308cba140--- /dev/null+++ b/apps/docs/.eslintrc.js@@ -0,0 +1,4 @@+module.exports = {+ root: true,+ extends: ["carbon"],+};diff --git a/apps/docs/.gitkeep b/apps/docs/.gitkeepnew file mode 100644index 0000000000..e69de29bb2diff --git a/apps/docs/README.md b/apps/docs/README.mdnew file mode 100644index 0000000000..59092d7a3d--- /dev/null+++ b/apps/docs/README.md@@ -0,0 +1,13 @@+# Carbon Docs++There are a few different types of technical documentation. This is the kind that tries to explain why certain decisions were made and provide a framework against which improvements can be suggested.++After reading the documentation, you should have enough knowledge to modify a module or create a new module.++## Running Locally++From the root repo run:++```bash+$ npm run dev:www+```diff --git a/apps/docs/components.json b/apps/docs/components.jsonnew file mode 100644index 0000000000..bcca5fe878--- /dev/null+++ b/apps/docs/components.json@@ -0,0 +1,17 @@+{+ "$schema": "https://ui.shadcn.com/schema.json",+ "style": "default",+ "rsc": false,+ "tsx": true,+ "tailwind": {+ "config": "tailwind.config.js",+ "css": "styles.css",+ "baseColor": "zinc",+ "cssVariables": true,+ "prefix": ""+ },+ "aliases": {+ "components": "/components",+ "utils": "www/utils/cn.tsx"+ }+}diff --git a/apps/docs/components/Home/components/features.tsx b/apps/docs/components/Home/components/features.tsxnew file mode 100644index 0000000000..828129f449--- /dev/null+++ b/apps/docs/components/Home/components/features.tsx@@ -0,0 +1,86 @@+import React from "react";+import { BsLightningCharge } from "react-icons/bs";+import { GiSpeedometer } from "react-icons/gi";+import { GoSync } from "react-icons/go";+import { HiCode, HiFingerPrint } from "react-icons/hi";+import { TbBuildingFactory2 } from "react-icons/tb";+import { useGlowPointer } from "../../../hooks/useGlowPointer";++declare global {+ interface Window {+ usingGlowPointer: boolean;+ }+}++const features = [+ {+ name: "High-Performance",+ icon: GiSpeedometer,+ description:+ "Built on best open-source technologies for incredible performance and security.",+ },+ {+ name: "Open Source",+ icon: HiCode,+ description:+ "Unlike other open-source ERPs, you can use Carbon to build your own proprietary systems.",+ },+ {+ name: "Serverless Architecture",+ icon: GoSync,+ description:+ "So you can focus on your business systems, not your infrastructure.",+ },+ {+ name: "Realtime",+ icon: BsLightningCharge,+ description: "All data can be updated in realtime across applications.",+ },+ {+ name: "Manufacturing",+ icon: TbBuildingFactory2,+ description: "Carbon has first-class support for American manufacturing.",+ },+ {+ name: "Single Tenant",+ icon: HiFingerPrint,+ description:+ "You're not sharing databases with other companies. Your data is yours.",+ },+] as const;++function Features({ showIcons = false }) {+ useGlowPointer();++ return (+ <>+ <div className="grid grid-cols-1 gap-6 my-12 sm:grid-cols-2 md:grid-cols-3 ">+ {features.map(({ icon: Icon, ...feature }, i) => (+ <div+ data-glow+ className="flex items-start p-8 space-x-4 bg-black/[0.03] dark:bg-zinc-900 round shadow-sm transition-all duration-300 ease-in-out"+ key={feature.name.split(" ").join("-")}+ >+ <div data-glow />+ {showIcons && (+ <Icon+ className="mt-0.5 block w-8 h-8"+ style={{ height: 24, width: 24 }}+ aria-hidden="true"+ />+ )}++ <div className="flex flex-col space-y-2">+ <h2 className="font-semibold dark:text-white">{feature.name}</h2>+ <p className="font-medium dark:text-white text-sm">+ {feature.description}+ </p>+ </div>+ </div>+ ))}+ </div>+ </>+ );+}++export default Features;diff --git a/apps/docs/components/Home/components/index.ts b/apps/docs/components/Home/components/index.tsnew file mode 100644index 0000000000..3be876dbd1--- /dev/null+++ b/apps/docs/components/Home/components/index.ts@@ -0,0 +1,3 @@+import Features from "./features";++export { Features };diff --git a/apps/docs/components/Learn/LoomDemo.tsx b/apps/docs/components/Learn/LoomDemo.tsxnew file mode 100644index 0000000000..fcac0247df--- /dev/null+++ b/apps/docs/components/Learn/LoomDemo.tsx@@ -0,0 +1,29 @@+import * as React from "react";++const LoomDemo = () => {+ return (+ <div+ style={{+ position: "relative",+ paddingBottom: "65.36363636363637%",+ height: 0,+ }}+ >+ <iframe+ title="Carbon ERP Walkthrough"+ src="https://www.loom.com/embed/7b2dccab3d404b84aa8f08e5bfa21d16?sid=178453fa-df5d-46b7-9c72-68a9b9e5158e"+ frameBorder={0}+ allowFullScreen+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ height: "100%",+ }}+ />+ </div>+ );+};++export default LoomDemo;diff --git a/apps/docs/components/Learn/index.ts b/apps/docs/components/Learn/index.tsnew file mode 100644index 0000000000..5fdae08463--- /dev/null+++ b/apps/docs/components/Learn/index.ts@@ -0,0 +1,3 @@+import LoomDemo from "./LoomDemo";++export { LoomDemo };diff --git a/apps/docs/components/ui/button.tsx b/apps/docs/components/ui/button.tsxnew file mode 100644index 0000000000..b7b3dc1937--- /dev/null+++ b/apps/docs/components/ui/button.tsx@@ -0,0 +1,56 @@+import * as React from "react";+import { Slot } from "@radix-ui/react-slot";+import { cva, type VariantProps } from "class-variance-authority";++import { cn } from "www/utils/cn.tsx";++const buttonVariants = cva(+ "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",+ {+ variants: {+ variant: {+ default: "bg-primary text-primary-foreground hover:bg-primary/90",+ destructive:+ "bg-destructive text-destructive-foreground hover:bg-destructive/90",+ outline:+ "border border-input bg-background hover:bg-accent hover:text-accent-foreground",+ secondary:+ "bg-secondary text-secondary-foreground hover:bg-secondary/80",+ ghost: "hover:bg-accent hover:text-accent-foreground",+ link: "text-primary underline-offset-4 hover:underline",+ },+ size: {+ default: "h-10 px-4 py-2",+ sm: "h-9 rounded-md px-3",+ lg: "h-11 rounded-md px-8",+ icon: "h-10 w-10",+ },+ },+ defaultVariants: {+ variant: "default",+ size: "default",+ },+ }+);++export interface ButtonProps+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,+ VariantProps<typeof buttonVariants> {+ asChild?: boolean;+}++const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(+ ({ className, variant, size, asChild = false, ...props }, ref) => {+ const Comp = asChild ? Slot : "button";+ return (+ <Comp+ className={cn(buttonVariants({ variant, size, className }))}+ ref={ref}+ {...props}+ />+ );+ }+);+Button.displayName = "Button";++export { Button, buttonVariants };diff --git a/apps/docs/components/ui/form.tsx b/apps/docs/components/ui/form.tsxnew file mode 100644index 0000000000..0867b9054a--- /dev/null+++ b/apps/docs/components/ui/form.tsx@@ -0,0 +1,171 @@+import * as React from "react";+import type * as LabelPrimitive from "@radix-ui/react-label";+import { Slot } from "@radix-ui/react-slot";+import type { ControllerProps, FieldPath, FieldValues } from "react-hook-form";+import { Controller, FormProvider, useFormContext } from "react-hook-form";++import { cn } from "www/utils/cn.tsx";+import { Label } from "/components/ui/label";++const Form = FormProvider;++type FormFieldContextValue<+ TFieldValues extends FieldValues = FieldValues,+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>+> = {+ name: TName;+};++const FormFieldContext = React.createContext<FormFieldContextValue>(+ {} as FormFieldContextValue+);++const FormField = <+ TFieldValues extends FieldValues = FieldValues,+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>+>({+ ...props+}: ControllerProps<TFieldValues, TName>) => {+ return (+ <FormFieldContext.Provider value={{ name: props.name }}>+ <Controller {...props} />+ </FormFieldContext.Provider>+ );+};++const useFormField = () => {+ const fieldContext = React.useContext(FormFieldContext);+ const itemContext = React.useContext(FormItemContext);+ const { getFieldState, formState } = useFormContext();++ const fieldState = getFieldState(fieldContext.name, formState);++ if (!fieldContext) {+ throw new Error("useFormField should be used within <FormField>");+ }++ const { id } = itemContext;++ return {+ id,+ name: fieldContext.name,+ formItemId: `${id}-form-item`,+ formDescriptionId: `${id}-form-item-description`,+ formMessageId: `${id}-form-item-message`,+ ...fieldState,+ };+};++type FormItemContextValue = {+ id: string;+};++const FormItemContext = React.createContext<FormItemContextValue>(+ {} as FormItemContextValue+);++const FormItem = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement>+>(({ className, ...props }, ref) => {+ const id = React.useId();++ return (+ <FormItemContext.Provider value={{ id }}>+ <div ref={ref} className={cn("space-y-2", className)} {...props} />+ </FormItemContext.Provider>+ );+});+FormItem.displayName = "FormItem";++const FormLabel = React.forwardRef<+ React.ElementRef<typeof LabelPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>+>(({ className, ...props }, ref) => {+ const { error, formItemId } = useFormField();++ return (+ <Label+ ref={ref}+ className={cn(error && "text-destructive", className)}+ htmlFor={formItemId}+ {...props}+ />+ );+});+FormLabel.displayName = "FormLabel";++const FormControl = React.forwardRef<+ React.ElementRef<typeof Slot>,+ React.ComponentPropsWithoutRef<typeof Slot>+>(({ ...props }, ref) => {+ const { error, formItemId, formDescriptionId, formMessageId } =+ useFormField();++ return (+ <Slot+ ref={ref}+ id={formItemId}+ aria-describedby={+ !error+ ? `${formDescriptionId}`+ : `${formDescriptionId} ${formMessageId}`+ }+ aria-invalid={!!error}+ {...props}+ />+ );+});+FormControl.displayName = "FormControl";++const FormDescription = React.forwardRef<+ HTMLParagraphElement,+ React.HTMLAttributes<HTMLParagraphElement>+>(({ className, ...props }, ref) => {+ const { formDescriptionId } = useFormField();++ return (+ <p+ ref={ref}+ id={formDescriptionId}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+ );+});+FormDescription.displayName = "FormDescription";++const FormMessage = React.forwardRef<+ HTMLParagraphElement,+ React.HTMLAttributes<HTMLParagraphElement>+>(({ className, children, ...props }, ref) => {+ const { error, formMessageId } = useFormField();+ const body = error ? String(error?.message) : children;++ if (!body) {+ return null;+ }++ return (+ <p+ ref={ref}+ id={formMessageId}+ className={cn("text-sm font-medium text-destructive", className)}+ {...props}+ >+ {body}+ </p>+ );+});+FormMessage.displayName = "FormMessage";++export {+ useFormField,+ Form,+ FormItem,+ FormLabel,+ FormControl,+ FormDescription,+ FormMessage,+ FormField,+};diff --git a/apps/docs/components/ui/input.tsx b/apps/docs/components/ui/input.tsxnew file mode 100644index 0000000000..1538e73f64--- /dev/null+++ b/apps/docs/components/ui/input.tsx@@ -0,0 +1,25 @@+import * as React from "react";++import { cn } from "www/utils/cn.tsx";++export interface InputProps+ extends React.InputHTMLAttributes<HTMLInputElement> {}++const Input = React.forwardRef<HTMLInputElement, InputProps>(+ ({ className, type, ...props }, ref) => {+ return (+ <input+ type={type}+ className={cn(+ "flex h-10 w-full rounded-md border border-input px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",+ className+ )}+ ref={ref}+ {...props}+ />+ );+ }+);+Input.displayName = "Input";++export { Input };diff --git a/apps/docs/components/ui/label.tsx b/apps/docs/components/ui/label.tsxnew file mode 100644index 0000000000..22dbcac41e--- /dev/null+++ b/apps/docs/components/ui/label.tsx@@ -0,0 +1,24 @@+import * as React from "react";+import * as LabelPrimitive from "@radix-ui/react-label";+import { cva, type VariantProps } from "class-variance-authority";++import { cn } from "www/utils/cn.tsx";++const labelVariants = cva(+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+);++const Label = React.forwardRef<+ React.ElementRef<typeof LabelPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &+ VariantProps<typeof labelVariants>+>(({ className, ...props }, ref) => (+ <LabelPrimitive.Root+ ref={ref}+ className={cn(labelVariants(), className)}+ {...props}+ />+));+Label.displayName = LabelPrimitive.Root.displayName;++export { Label };diff --git a/apps/docs/hooks/useGlowPointer.tsx b/apps/docs/hooks/useGlowPointer.tsxnew file mode 100644index 0000000000..9eae516aa4--- /dev/null+++ b/apps/docs/hooks/useGlowPointer.tsx@@ -0,0 +1,26 @@+import { useCallback, useEffect } from "react";++export function useGlowPointer() {+ const update = useCallback(({ x, y }) => {+ document.body.style.setProperty("--x", x.toFixed(2));+ document.body.style.setProperty("--xp", (x / window.innerWidth).toFixed(2));+ document.body.style.setProperty("--y", y.toFixed(2));+ document.body.style.setProperty(+ "--yp",+ (y / window.innerHeight).toFixed(2)+ );+ }, []);++ useEffect(() => {+ if (window.usingGlowPointer) return;+ window.usingGlowPointer = true;+ document.body.addEventListener("pointermove", update);+ document.body.style.setProperty("--base", "0");+ document.body.style.setProperty("--spread", "360");+ return () => {+ window.usingGlowPointer = false;+ document.body.removeEventListener("pointermove", update);+ };+ }, [update]);+ return null;+}diff --git a/apps/docs/hooks/useWindowSize.tsx b/apps/docs/hooks/useWindowSize.tsxnew file mode 100644index 0000000000..105fb4967f--- /dev/null+++ b/apps/docs/hooks/useWindowSize.tsx@@ -0,0 +1,32 @@+import { useEffect, useLayoutEffect, useState } from "react";++export const useIsomorphicLayoutEffect =+ typeof window !== "undefined" ? useLayoutEffect : useEffect;++export function useWindowSize() {+ const [size, setSize] = useState<{+ height: number | null;+ width: number | null;+ }>({+ width: null,+ height: null,+ });++ useIsomorphicLayoutEffect(() => {+ const handleResize = () => {+ setSize({+ width: window.innerWidth,+ height: window.innerHeight,+ });+ };++ handleResize();+ window.addEventListener("resize", handleResize);++ return () => {+ window.removeEventListener("resize", handleResize);+ };+ }, []);++ return size;+}diff --git a/apps/website/next-env.d.ts b/apps/docs/next-env.d.tssimilarity index 100%rename from apps/website/next-env.d.tsrename to apps/docs/next-env.d.tsdiff --git a/apps/docs/next.config.js b/apps/docs/next.config.jsnew file mode 100644index 0000000000..0918793996--- /dev/null+++ b/apps/docs/next.config.js@@ -0,0 +1,10 @@+const withNextra = require("nextra")({+ theme: "nextra-theme-docs",+ themeConfig: "./theme.config.js",+ defaultShowCopyCode: true,+});++module.exports = withNextra({+ reactStrictMode: true,+ transpilePackages: ["geist"],+});diff --git a/apps/docs/package.json b/apps/docs/package.jsonnew file mode 100644index 0000000000..6ad537ab75--- /dev/null+++ b/apps/docs/package.json@@ -0,0 +1,48 @@+{+ "name": "docs",+ "version": "0.0.1",+ "dependencies": {+ "@carbon/react": "*",+ "@hookform/resolvers": "^3.3.4",+ "@radix-ui/react-label": "^2.0.2",+ "@radix-ui/react-slot": "^1.0.2",+ "@supabase/supabase-js": "^2.40.0",+ "@tabler/icons-react": "3.1.0",+ "class-variance-authority": "^0.7.0",+ "clsx": "^2.1.0",+ "framer-motion": "^10.13.1",+ "geist": "1.2.0",+ "next": "^13.4.16",+ "nextra": "^2.5.2",+ "nextra-theme-docs": "^2.5.2",+ "react": "^18.2.0",+ "react-dom": "^18.2.0",+ "react-hook-form": "^7.51.1",+ "react-icons": "^4.12.0",+ "tailwind-merge": "^2.2.1",+ "tailwindcss-animate": "^1.0.7",+ "zod": "^3.22.4"+ },+ "devDependencies": {+ "@carbon/tailwind": "*",+ "@carbon/tsconfig": "*",+ "@types/jest": "^26.0.22",+ "@types/node": "^18.15.1",+ "@types/react": "^18.2.33",+ "@types/react-dom": "^18.2.14",+ "autoprefixer": "10.4.14",+ "dotenv": "16.3.1",+ "eslint-config-carbon": "*",+ "postcss": "^8.4.33",+ "tailwindcss": "3.3.2",+ "typescript": "^5.2.2"+ },+ "private": true,+ "scripts": {+ "build": "next build",+ "clean": "rimraf .turbo node_modules .next",+ "dev": "next dev -p 4111",+ "lint": "TIMING=1 next lint",+ "start": "next start "+ }+}diff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsxnew file mode 100644index 0000000000..081937c892--- /dev/null+++ b/apps/docs/pages/_app.tsx@@ -0,0 +1,21 @@+import type { AppProps } from "next/app";+import "nextra-theme-docs/style.css";++import { GeistMono } from "geist/font/mono";+import { GeistSans } from "geist/font/sans";+import React from "react";+import "../styles.css";++export default function Docs({ Component, pageProps }: AppProps) {+ React.useEffect(() => {+ const footer = document.querySelector("footer");+ if (footer) footer.classList.add("relative");+ }, []);++ return (+ <Component+ {...pageProps}+ className={[GeistSans.className, GeistMono.className].join(" ")}+ />+ );+}diff --git a/apps/docs/pages/_meta.json b/apps/docs/pages/_meta.jsonnew file mode 100644index 0000000000..4709cf658f--- /dev/null+++ b/apps/docs/pages/_meta.json@@ -0,0 +1,6 @@+{+ "index": "Tech Stack",+ "getting-started": "Getting Started",+ "core-concepts": "Core Concepts",+ "principles": "Principles"+}diff --git a/apps/docs/pages/core-concepts/_meta.json b/apps/docs/pages/core-concepts/_meta.jsonnew file mode 100644index 0000000000..298123a445--- /dev/null+++ b/apps/docs/pages/core-concepts/_meta.json@@ -0,0 +1,8 @@+{+ "permissions": "Permissions",+ "fetching": "Data Fetching",+ "writing": "Data Writes",+ "realtime": "Realtime",+ "transactions": "Transactions",+ "serverless": "Serverless"+}diff --git a/apps/docs/pages/core-concepts/fetching.mdx b/apps/docs/pages/core-concepts/fetching.mdxnew file mode 100644index 0000000000..d04785ab0b--- /dev/null+++ b/apps/docs/pages/core-concepts/fetching.mdx@@ -0,0 +1,170 @@+---+title: Data Fetching in Carbon ERP+description: Conventions for fetching data in Carbon ERP+---++import { Callout, Tab, Tabs } from "nextra-theme-docs";++# 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) {+ throw redirect(+ "/x/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 w="full" h="full" 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, [+ { column: "supplier(name)", ascending: false },+ ]);+ }++ 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/apps/docs/pages/core-concepts/permissions.mdx b/apps/docs/pages/core-concepts/permissions.mdxnew file mode 100644index 0000000000..349247fad5--- /dev/null+++ b/apps/docs/pages/core-concepts/permissions.mdx@@ -0,0 +1,168 @@+---+title: Permissions in Carbon ERP+description: Conventions for permissions in Carbon ERP+---++# 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 `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++ALTER TABLE "customer" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with sales_view can view customer" ON "customer"+ FOR SELECT+ USING (+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Customers with sales_view can their own organization" ON "customer"+ FOR SELECT+ USING (+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND id IN (+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()+ )+ );++CREATE POLICY "Employees with sales_create can create customers" ON "customer"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('sales_create')::boolean, false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with sales_update can update customers" ON "customer"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('sales_update')::boolean, false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Customers with sales_update can their own organization" ON "customer"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('sales_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"customer"'::jsonb+ AND id IN (+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()+ )+ );++CREATE POLICY "Employees with sales_delete can delete customers" ON "customer"+ FOR DELETE+ USING (+ coalesce(get_my_claim('sales_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++```++### 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/apps/docs/pages/core-concepts/realtime.mdx b/apps/docs/pages/core-concepts/realtime.mdxnew file mode 100644index 0000000000..3ed5564cb4--- /dev/null+++ b/apps/docs/pages/core-concepts/realtime.mdx@@ -0,0 +1,107 @@+---+title: Realtime in Carbon ERP+description: Conventions for using realtime data in Carbon ERP+---++# 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");+```++In practice, however, this approach is too heavy-handed. A better idea is to listen to 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/apps/docs/pages/core-concepts/serverless.mdx b/apps/docs/pages/core-concepts/serverless.mdxnew file mode 100644index 0000000000..8dd639c709--- /dev/null+++ b/apps/docs/pages/core-concepts/serverless.mdx@@ -0,0 +1,6 @@+---+title: Serverless Architecture in Carbon ERP+description: Overview of serverless infrastructure in Carbon ERP+---++# Serverless Architecturediff --git a/apps/docs/pages/core-concepts/transactions.mdx b/apps/docs/pages/core-concepts/transactions.mdxnew file mode 100644index 0000000000..936f432a24--- /dev/null+++ b/apps/docs/pages/core-concepts/transactions.mdx@@ -0,0 +1,6 @@+---+title: Realtime in Carbon ERP+description: Conventions for database transactions in Carbon ERP+---++# Transactionsdiff --git a/apps/docs/pages/core-concepts/writing.mdx b/apps/docs/pages/core-concepts/writing.mdxnew file mode 100644index 0000000000..fbd00df4ff--- /dev/null+++ b/apps/docs/pages/core-concepts/writing.mdx@@ -0,0 +1,210 @@+---+title: Data Writes in Carbon ERP+description: Conventions for mutating data in Carbon ERP+---++import { Callout } from "nextra-theme-docs";++# 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 { withZod } from "@carbon/remix-validated-form";+import { z } from "zod";+import { zfd } from "zod-form-data";++export const personValidator = withZod(+ 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 "@carbon/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 { validationError, validator } from "@carbon/remix-validated-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+ });++ throw 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 "../lib/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"];+ costLedger: Database["public"]["Tables"]["costLedger"]["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 costLedgerIds = await trx+ .insertInto("costLedger")+ .values(costLedgerInserts)+ .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,+ });+ }+});+```diff --git a/apps/docs/pages/getting-started.mdx b/apps/docs/pages/getting-started.mdxnew file mode 100644index 0000000000..1d031a282c--- /dev/null+++ b/apps/docs/pages/getting-started.mdx@@ -0,0 +1,75 @@+---+title: Getting started with Carbon ERP+description: Carbon is a high-performance, open-source ERP+---++# Getting Started++Before getting started with development, it's good to have a basic understanding of our [tech stack](/docs/tech-stack).++You'll need to have [node >= 18](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) and [Docker](https://docs.docker.com/desktop/install/mac-install/) installed on your system since this monorepo uses the Docker for local development.++After running the steps below you should be able to access the following apps/containers locally:++| Application | URL |+| --------------- | ------------------------------------------------------------------------------------------------------------------ |+| Carbon ERP | [http://localhost:3000](http://localhost:3000) |+| Postgres | [postgresql://postgres:postgres@localhost:54322/postgres](postgresql://postgres:postgres@localhost:54322/postgres) |+| Supabase Studio | [http://localhost:54323/project/default](http://localhost:54323/project/default) |+| Inbucket | [http://localhost:54324/monitor](http://localhost:54324/monitor) |+| Redis | [redis://localhost:6379](redis://localhost:6379) |+| Edge Functions | [http://localhost:54321/functions/v1/function-name](http://localhost:54321/functions/v1/function-name) |++First download and initialize the repository dependencies.++```bash+git clone https://github.com/barbinbrad/carbon+cd carbon+npm install # install dependencies+npm run db:start # pull and run the containers+```++Copy the environment variables from the initialization script to an `.env` file:++```bash+cp ./.env.example ./.env+```++After you've set the environment variables to the output of `npm run db:start` you can run++```bash+npm run db:build # run db migrations and seed script+npm run build # build the packages+```++Finally, start the apps and packages:++```bash+npm run dev # npm run dev in all apps & packages+```++To stop the database containers in a recoverable way, you can run:++```bash+npm run db:stop # stop and delete all database containers+```++To restart the database containers, you can run:++```bash+npm run db:restart # restart all database containers+```++To rebuild and reseed the database, you can run:++```bash+npm run db:build # runs db:kill, db:start, and setup+```++To run a particular application, use the `-w workspace` flag.++For example, to run test command in the `@carbon/react` package you can run:++```bash+npm run test -w @carbon/react+```diff --git a/apps/docs/pages/index.mdx b/apps/docs/pages/index.mdxnew file mode 100644index 0000000000..fbcbded1c5--- /dev/null+++ b/apps/docs/pages/index.mdx@@ -0,0 +1,152 @@+---+title: Carbon ERP Tech Stack+description: TypeScript, React, shadcn, Remix, Supabase+---++# Tech Stack++Our tech stack aims to be as simple as possible, while still being powerful enough to build any web application. We use the following technologies:++- [TypeScript](https://www.typescriptlang.org) is the programming language+- [React](https://reactjs.org) for the frontend+- [Remix](https://remix.run) for the routing and compiling+- [Supabase](https://supabase.io) for the database and authentication+- [shadcn](https://ui.shadcn.com) (Tailwind, Radix, cva) for the UI components++We also use [Redis](https://redis.io) for caching and queues and [Vercel](https://vercel.com) for hosting, though in most cases you probably won't interact with those.++In this page, we'll give you a basic overview of how the tech stack works together. If you want to learn more about any of the technologies, we recommend checking out their documentation.++## TypeScript++[TypeScript](https://www.typescriptlang.org) is a programming language that builds on top of JavaScript. It adds a bunch of features that make it easier to write code, and it also makes it easier to catch bugs before you ship your code.++We chose TypeScript because it allows us to use a single, strongly-typed language across the entire application. Every time you run `npm run db:build`, we use Supabase to generate TypeScript types for your database schema.++## React++[React](https://reactjs.org) is a JavaScript library for building user interfaces. React in 2023 is like the Honda Accord of frontend frameworks:++- ✅ Proven+- ✅ Popular+- ✅ Flexible+- ✅ Reliable+- ✅ Well documented+- ✅ Easy to find related components+- ✅ Easy to find people to work on it++However:++- 🚫 It's not the simplest+- 🚫 It's not the most modern+- 🚫 It's not “cool”++We have a package called [@carbon/react](https://github.com/barbinbrad/carbon/tree/main/packages/react/src) that has a bunch of React pre-built components that you can use to build your UI. You can also draw from a rich ecosystem of existing React component libraries.++## Remix++[Remix](https://remix.run) is a framework for building full-stack web applications. It's built on top of React, it is extremely cool. It allows us to co-locate server-side code and client-side code in the same files (routes). When combined with TypeScript and Supabase, this gives us type-safety from the database to the UI.++Remix makes for a beautiful developer experience. It's use of nested routes, [loaders, actions and components](https://remix.run/blog/remix-data-flow) **minimizes the amount of code that needs written while maximzing performance**. To learn more about Remix, check out their documentation, and take a look at some files from our [routes](https://github.com/barbinbrad/carbon/tree/main/apps/carbon/app/routes) directory.++Here's a slightly-simplified example of how a Remix route works:++```tsx+// File (route): /products/$productId/edit.tsx++export async function loader({ params }) {+ const product = await database.getProduct(params.productId);+ return json(product);+}++export default function Route() {+ const product = useLoaderData();+ return (+ <h2>Edit Product {product.id}</h2>+ <Form method="post">+ <input name="name" defaultValue={product.name} />+ <input name="price" defaultValue={product.price} />+ <button type="submit">Save</button>+ </Form>+ )+}++export async function action({params, request}) {+ const form = await request.formData();+ const name = form.get("name");+ const price = form.get("price");+ const product = await database.updateProduct({ id: params.productId, name, price });+ throw redirect(`/products/${product.id}`);+}+```++## Supabase++[Supabase](https://supabase.io) is a database, authentication, and storage service that's built on top of Postgres. It allows us to provide a simple, unified authentication layer across many applications (even those that don't exist yet).++Supabase provides a TypeScript client called [Supabase JS](https://supabase.com/docs/reference/javascript/typescript-support) that makes it incredibly easy to query/modify the database. It also makes it easy to use row-level security to restrict access to certain parts of the database on a per-user basis.++Here's a look at how you can use Supabase JS to query the database from a Remix loader where `client` is the supabase client specific to the user making the request:++```tsx+export async function loader({request}) {+ const { client } = requirePermissions(request, view: 'purchasing');+ const { data, error } = await client+ .from('purchaseOrder')+ .select(`+ id, name,+ customer(id, name),+ purchaseOrderItems(id, name, quantity, unitPrice, total)+ `)+ .order('createdAt', { ascending: false })+ .limit(10);++ if (error) {+ throw redirect('/');+ }++ return json(data);+}+```++This is similar to the following SQL query.++```sql+SELECT+ id,+ name,+ customer.id,+ customer,name+ purchaseOrderItems.id,+ purchaseOrderItems.name,+ purchaseOrderItems.quantity,+ purchaseOrderItems.unitPrice,+ purchaseOrderItems.total+FROM "purchaseOrder"+INNER JOIN "customer" ON "customer"."id" = "purchaseOrder"."customerId"+LEFT JOIN "purchaseOrderItem" ON "purchaseOrderItem"."purchaseOrderId" = "purchaseOrder"."id"+ORDER BY "createdAt" DESC+LIMIT 10+```++But unlike a raw SQL query, the data that we get back is strongly-typed, neatly-nested, with error handling built-in.++{/* TODO: explain why this is actually a bad setup for joins -- recommend putting joins in SQL VIEWs and then using the supabase client to supabase.from("view").select("*") */}++## shadcn++[shadcn](https://ui.shadcn.com) is an open source starting point for a component library that combines [Radix UI](https://radix-ui.com) with [Tailwind](https://tailwindcss.com) to provide beautiful, accessibile primitives for our `@carbon/react` component package. While the underlying implementation details are [a little complex](https://cva.style/docs/getting-started/variants), the developer experience is extremely simple.++Here's an example of a button:++```jsx+import { Button } from "@carbon/react";++function App() {+ return (+ <Button size="lg" variant="secondary">+ Click me+ </Button>+ );+}+```diff --git a/apps/docs/pages/principles.mdx b/apps/docs/pages/principles.mdxnew file mode 100644index 0000000000..5d95fb225f--- /dev/null+++ b/apps/docs/pages/principles.mdx@@ -0,0 +1,52 @@+---+title: Carbon ERP Principles+description: Simplicity, extensibility, openness, and productivity are the four principles that guide the development of Carbon ERP.+---++# 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 and free to modify**.++An open source ERP system has a number of benefits, including:++- Greater long-term stability+- Greater flexibility+- Lower costs+- 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.diff --git a/apps/docs/postcss.config.js b/apps/docs/postcss.config.jsnew file mode 100644index 0000000000..cbfea5ea20--- /dev/null+++ b/apps/docs/postcss.config.js@@ -0,0 +1,7 @@+module.exports = {+ plugins: {+ "tailwindcss/nesting": {},+ tailwindcss: {},+ autoprefixer: {},+ },+};diff --git a/apps/docs/public/carbon-dark-mode.jpg b/apps/docs/public/carbon-dark-mode.jpgnew file mode 100644index 0000000000..dd67723bd8Binary files /dev/null and b/apps/docs/public/carbon-dark-mode.jpg differdiff --git a/apps/docs/public/carbon-dark.jpg b/apps/docs/public/carbon-dark.jpgnew file mode 100644index 0000000000..b4f30dd7feBinary files /dev/null and b/apps/docs/public/carbon-dark.jpg differdiff --git a/apps/docs/public/carbon-light-mode.jpg b/apps/docs/public/carbon-light-mode.jpgnew file mode 100644index 0000000000..ec54a84ce0Binary files /dev/null and b/apps/docs/public/carbon-light-mode.jpg differdiff --git a/apps/docs/public/carbon-light.jpg b/apps/docs/public/carbon-light.jpgnew file mode 100644index 0000000000..2966e2b5d6Binary files /dev/null and b/apps/docs/public/carbon-light.jpg differdiff --git a/apps/docs/public/favicon.ico b/apps/docs/public/favicon.iconew file mode 100644index 0000000000..ce92de6710Binary files /dev/null and b/apps/docs/public/favicon.ico differdiff --git a/apps/docs/public/grid.svg b/apps/docs/public/grid.svgnew file mode 100644index 0000000000..76e3b29f0d--- /dev/null+++ b/apps/docs/public/grid.svg@@ -0,0 +1,5 @@++<svg id="download" xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">+ <path id="Path_3" data-name="Path 3" d="M96,95h4v1H96v4H95V96H86v4H85V96H76v4H75V96H66v4H65V96H56v4H55V96H46v4H45V96H36v4H35V96H26v4H25V96H16v4H15V96H0V95H15V86H0V85H15V76H0V75H15V66H0V65H15V56H0V55H15V46H0V45H15V36H0V35H15V26H0V25H15V16H0V15H15V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96Zm-1,0V86H86v9ZM85,95V86H76v9ZM75,95V86H66v9ZM65,95V86H56v9ZM55,95V86H46v9ZM45,95V86H36v9ZM35,95V86H26v9ZM25,95V86H16v9ZM16,85h9V76H16Zm10,0h9V76H26Zm10,0h9V76H36Zm10,0h9V76H46Zm10,0h9V76H56Zm10,0h9V76H66Zm10,0h9V76H76Zm10,0h9V76H86Zm9-10V66H86v9ZM85,75V66H76v9ZM75,75V66H66v9ZM65,75V66H56v9ZM55,75V66H46v9ZM45,75V66H36v9ZM35,75V66H26v9ZM25,75V66H16v9ZM16,65h9V56H16Zm10,0h9V56H26Zm10,0h9V56H36Zm10,0h9V56H46Zm10,0h9V56H56Zm10,0h9V56H66Zm10,0h9V56H76Zm10,0h9V56H86Zm9-10V46H86v9ZM85,55V46H76v9ZM75,55V46H66v9ZM65,55V46H56v9ZM55,55V46H46v9ZM45,55V46H36v9ZM35,55V46H26v9ZM25,55V46H16v9ZM16,45h9V36H16Zm10,0h9V36H26Zm10,0h9V36H36Zm10,0h9V36H46Zm10,0h9V36H56Zm10,0h9V36H66Zm10,0h9V36H76Zm10,0h9V36H86Zm9-10V26H86v9ZM85,35V26H76v9ZM75,35V26H66v9ZM65,35V26H56v9ZM55,35V26H46v9ZM45,35V26H36v9ZM35,35V26H26v9ZM25,35V26H16v9ZM16,25h9V16H16Zm10,0h9V16H26Zm10,0h9V16H36Zm10,0h9V16H46Zm10,0h9V16H56Zm10,0h9V16H66Zm10,0h9V16H76Zm10,0h9V16H86Z" fill="rgba(255,255,255,0.1)" fill-rule="evenodd" opacity="0.5"/>+ <path id="Path_4" data-name="Path 4" d="M6,5V0H5V5H0V6H5v94H6V6h94V5Z" fill="rgba(255,255,255,0.1)" fill-rule="evenodd"/>+</svg>diff --git a/apps/docs/public/logo-dark.png b/apps/docs/public/logo-dark.pngnew file mode 100644index 0000000000..75399c8d11Binary files /dev/null and b/apps/docs/public/logo-dark.png differdiff --git a/apps/docs/public/logo-full.png b/apps/docs/public/logo-full.pngnew file mode 100644index 0000000000..d0f052c476Binary files /dev/null and b/apps/docs/public/logo-full.png differdiff --git a/apps/docs/public/logo-light.png b/apps/docs/public/logo-light.pngnew file mode 100644index 0000000000..c0f93e6fe2Binary files /dev/null and b/apps/docs/public/logo-light.png differdiff --git a/apps/docs/styles.css b/apps/docs/styles.cssnew file mode 100644index 0000000000..0307e94332--- /dev/null+++ b/apps/docs/styles.css@@ -0,0 +1,132 @@+@tailwind base;+@tailwind components;+@tailwind utilities;++:root {+ --radius: 12px;+}++code {+ @apply text-sm;+}++:root {+ --nextra-primary-hue: 230deg;+}++.dark {+ --nextra-primary-hue: 161deg;+}++body {+ background: linear-gradient(+ to bottom,+ rgba(255, 255, 255, 0) 0%,+ rgba(255, 255, 255, 1) 300px+ ),+ fixed 0 0 / 20px 20px radial-gradient(#d1d1d1 1px, transparent 0),+ fixed 10px 10px / 20px 20px radial-gradient(#d1d1d1 1px, transparent 0);+}++.dark .invert-on-dark {+ filter: invert(1) brightness(1.8);+}++#__next .nextra-body > main h1 {+ margin-top: 0;+}++.dark body article pre {+ background-color: transparent;+ border: 1px solid rgba(224, 243, 255, 0.1);+ border-radius: 5px;+}++.light body article pre {+ background-color: transparent;+ border: 1px solid #e5e7eb;+ border-radius: 5px;+}++.light body {+ --shiki-color-text: #111;+ --shiki-token-constant: var(--shiki-color-text);+ --shiki-token-comment: #999;+ --shiki-token-keyword: #ff0078;+ --shiki-token-function: #2a0093;+ --shiki-token-string-expression: #028265;+ --shiki-token-punctuation: var(--shiki-color-text);+ --shiki-token-string: #797afa;+}++.dark body {+ --shiki-color-text: #eaeaea;+ --shiki-token-constant: var(--shiki-color-text);+ --shiki-token-comment: #666;+ --shiki-token-keyword: #ff0078;+ --shiki-token-function: #12ff00;+ --shiki-token-string-expression: #50e3c2;+ --shiki-token-punctuation: var(--shiki-color-text);+ --shiki-token-string: #797afa;++ background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, #111 300px),+ fixed 0 0 / 20px 20px radial-gradient(#313131 1px, transparent 0),+ fixed 10px 10px / 20px 20px radial-gradient(#313131 1px, transparent 0);+}++code[data-language="sh"] {+ --shiki-token-string: var(--shiki-color-text);+}++#__next article.nextra-body h1 {+ font-size: 2em;+}++#__next article.nextra-body h2 {+ font-size: 1.5em;+}++#__next article.nextra-body h3 {+ font-size: 1.25em;+}++#__next article.nextra-body h4 {+ font-size: 1em;+}++#__next article.nextra-body h5 {+ font-size: 0.875em;+}++#__next article.nextra-body h5 {+ font-size: 0.85em;+}++.light .nx-text-primary-600 {+ --tw-text-opacity: 1;+ color: hsl(+ var(--nextra-primary-hue) var(--nextra-primary-saturation) 35% /+ var(--tw-text-opacity)+ );+}++.nextra-nav-container {+ position: fixed;+}++.nextra-nav-container + div {+ min-height: 100vh;+}++section > section {+ padding-left: 0.5rem;+ padding-right: 0.5rem;+}++article {+ padding-top: 70px;+}++aside {+ padding-top: 15px;+}diff --git a/apps/docs/tailwind.config.js b/apps/docs/tailwind.config.jsnew file mode 100644index 0000000000..0ea1cf06ca--- /dev/null+++ b/apps/docs/tailwind.config.js@@ -0,0 +1 @@+module.exports = require("@carbon/tailwind/tailwind.config");diff --git a/apps/docs/theme.config.js b/apps/docs/theme.config.jsnew file mode 100644index 0000000000..6425056867--- /dev/null+++ b/apps/docs/theme.config.js@@ -0,0 +1,58 @@+// theme.config.js+import { useTheme } from "next-themes";+import Image from "next/image";+import { useEffect, useState } from "react";++const useDark = () => {+ const { resolvedTheme } = useTheme();+ const [isDark, setIsDark] = useState(false);+ useEffect(() => {+ setIsDark(resolvedTheme === "dark");+ return () => false;+ }, [resolvedTheme]);+ return isDark;+};++export default {+ project: {+ link: "https://github.com/barbinbrad/carbon", // GitHub link in the navbar+ },+ docsRepositoryBase: "https://github.com/barbinbrad/carbon/blob/main/apps/www", // base URL for the docs repository+ navigation: {+ next: true,+ prev: true,+ },+ sidebar: {+ defaultMenuCollapseLevel: 1,+ },+ darkMode: true,+ footer: {+ text: `Carbon ERP ${new Date().getFullYear()}. All rights reserved.`,+ },+ editLink: {+ text: `View this page on GitHub`,+ },+ logo: function Logo() {+ const isDark = useDark();+ return (+ <>+ <Image+ width={30}+ height={30}+ src={`/logo${isDark ? "-light" : "-dark"}.png`}+ alt="Carbon Logo"+ />+ </>+ );+ },+ head: (+ <>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ </>+ ),+ useNextSeoProps() {+ return {+ titleTemplate: "%s – Carbon ERP",+ };+ },+};diff --git a/apps/docs/tsconfig.json b/apps/docs/tsconfig.jsonnew file mode 100644index 0000000000..e981962739--- /dev/null+++ b/apps/docs/tsconfig.json@@ -0,0 +1,12 @@+{+ "exclude": ["node_modules"],+ "extends": "@carbon/tsconfig/nextjs.json",+ "compilerOptions": {+ "outDir": "dist",+ "baseUrl": ".",+ "paths": {+ "~/*": ["./src/*"]+ }+ },+ "include": ["next-env.d.ts", "pages"]+}diff --git a/apps/docs/utils/cn.tsx b/apps/docs/utils/cn.tsxnew file mode 100644index 0000000000..88283f0133--- /dev/null+++ b/apps/docs/utils/cn.tsx@@ -0,0 +1,7 @@+import type { ClassValue } from "clsx";+import { clsx } from "clsx";+import { twMerge } from "tailwind-merge";++export function cn(...inputs: ClassValue[]) {+ return twMerge(clsx(inputs));+}diff --git a/package-lock.json b/package-lock.jsonindex 2bb6003773..8ca2e76697 100644--- a/package-lock.json+++ b/package-lock.json@@ -162,6 +162,69 @@"react-dom": "*"}},+ "apps/docs": {+ "version": "0.0.1",+ "dependencies": {+ "@carbon/react": "*",+ "@hookform/resolvers": "^3.3.4",+ "@radix-ui/react-label": "^2.0.2",+ "@radix-ui/react-slot": "^1.0.2",+ "@supabase/supabase-js": "^2.40.0",+ "@tabler/icons-react": "3.1.0",+ "class-variance-authority": "^0.7.0",+ "clsx": "^2.1.0",+ "framer-motion": "^10.13.1",+ "geist": "1.2.0",+ "next": "^13.4.16",+ "nextra": "^2.5.2",+ "nextra-theme-docs": "^2.5.2",+ "react": "^18.2.0",+ "react-dom": "^18.2.0",+ "react-hook-form": "^7.51.1",+ "react-icons": "^4.12.0",+ "tailwind-merge": "^2.2.1",+ "tailwindcss-animate": "^1.0.7",+ "zod": "^3.22.4"+ },+ "devDependencies": {+ "@carbon/tailwind": "*",+ "@carbon/tsconfig": "*",+ "@types/jest": "^26.0.22",+ "@types/node": "^18.15.1",+ "@types/react": "^18.2.33",+ "@types/react-dom": "^18.2.14",+ "autoprefixer": "10.4.14",+ "dotenv": "16.3.1",+ "eslint-config-carbon": "*",+ "postcss": "^8.4.33",+ "tailwindcss": "3.3.2",+ "typescript": "^5.2.2"+ }+ },+ "apps/docs/node_modules/@tabler/icons": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.1.0.tgz",+ "integrity": "sha512-CpZGyS1IVJKFcv88yZ2sYZIpWWhQ6oy76BQKQ5SF0fGgOqgyqKdBGG/YGyyMW632on37MX7VqQIMTzN/uQqmFg==",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/codecalm"+ }+ },+ "apps/docs/node_modules/@tabler/icons-react": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@tabler/icons-react/-/icons-react-3.1.0.tgz",+ "integrity": "sha512-k/WTlax2vbj/LpxvaJ+BmaLAAhVUgyLj4Ftgaczz66tUSNzqrAZXCFdOU7cRMYPNVBqyqE2IdQd2rzzhDEJvkw==",+ "dependencies": {+ "@tabler/icons": "3.1.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/codecalm"+ },+ "peerDependencies": {+ "react": ">= 16"+ }+ },"node_modules/@aashutoshrathi/word-wrap": {"version": "1.2.6","resolved": "https://registry.npmjs.org/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz",@@ -13230,6 +13293,10 @@"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz","integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA=="},+ "node_modules/docs": {+ "resolved": "apps/docs",+ "link": true+ },"node_modules/doctrine": {"version": "3.0.0","resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",diff --git a/package.json b/package.jsonindex 1cf1c11aed..d0417c607b 100755--- a/package.json+++ b/package.json@@ -45,7 +45,8 @@"db:types": "npm run db:types -w @carbon/database","deploy": "turbo run deploy","dev": "turbo run dev --filter=./apps/* --filter=./packages/*",- "dev:apps": "turbo run dev --filter=./apps/*",+ "dev:apps": "turbo run dev --filter=./apps/carbon",+ "dev:docs": "turbo run dev --filter=./apps/docs","dev:packages": "turbo run dev --filter=./packages/*","dev:www": "turbo run dev --filter=./www","format": "prettier --write \"**/*.{ts,tsx,md}\"",@@ -58,7 +59,6 @@"workspaces": ["apps/*","packages/*",- "shared","www"]-}\ No newline at end of file+}