Skip to content

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.

feat: record quantities with realtime sync

Brad Barbin5c61e777a066
diff --git a/apps/carbon/app/styles/tailwind.css b/apps/carbon/app/styles/tailwind.css
index 08ab4f7ba2..bdb2310b50 100644
--- a/apps/carbon/app/styles/tailwind.css
+++ b/apps/carbon/app/styles/tailwind.css
@@ -68,14 +68,14 @@
}
}
-.forgeViewer {
+.forge-viewer {
position: relative;
width: 100%;
height: 100%;
min-height: 400px;
}
-.forgeViewer > div {
+.forge-viewer > div {
border-radius: var(--radius);
}
diff --git a/apps/carbon/app/utils/supabase.ts b/apps/carbon/app/utils/supabase.ts
index 4631ac61cb..01f712c67a 100644
--- a/apps/carbon/app/utils/supabase.ts
+++ b/apps/carbon/app/utils/supabase.ts
@@ -1,7 +1,15 @@
-export const sanitize = (input: Record<string, any>) => {
- const output = { ...input };
+export function sanitize<T extends Record<string, any>>(
+ input: T
+): {
+ [K in keyof T]: T[K] extends undefined ? null : T[K];
+} {
+ const output = { ...input } as {
+ [K in keyof T]: T[K] extends undefined ? null : T[K];
+ };
Object.keys(output).forEach((key) => {
- if (output[key] === undefined && key !== "id") output[key] = null;
+ if (output[key as keyof T] === undefined && key !== "id") {
+ output[key as keyof T] = null as any;
+ }
});
return output;
-};
+}
diff --git a/apps/developers/app/styles/tailwind.css b/apps/developers/app/styles/tailwind.css
index 08ab4f7ba2..bdb2310b50 100644
--- a/apps/developers/app/styles/tailwind.css
+++ b/apps/developers/app/styles/tailwind.css
@@ -68,14 +68,14 @@
}
}
-.forgeViewer {
+.forge-viewer {
position: relative;
width: 100%;
height: 100%;
min-height: 400px;
}
-.forgeViewer > div {
+.forge-viewer > div {
border-radius: var(--radius);
}
diff --git a/apps/docs/.eslintrc.js b/apps/docs/.eslintrc.js
deleted file mode 100644
index 1308cba140..0000000000
--- a/apps/docs/.eslintrc.js
+++ /dev/null
@@ -1,4 +0,0 @@
-module.exports = {
- root: true,
- extends: ["carbon"],
-};
diff --git a/apps/docs/.gitkeep b/apps/docs/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/apps/docs/components.json b/apps/docs/components.json
deleted file mode 100644
index bcca5fe878..0000000000
--- a/apps/docs/components.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "$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.tsx
deleted file mode 100644
index bbdccf07b3..0000000000
--- a/apps/docs/components/Home/components/features.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import React from "react";
-import { BsLightningCharge } from "react-icons/bs";
-import { GiSpeedometer } from "react-icons/gi";
-import { GoSync } from "react-icons/go";
-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: "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.",
- },
-] 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.ts
deleted file mode 100644
index 3be876dbd1..0000000000
--- a/apps/docs/components/Home/components/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import Features from "./features";
-
-export { Features };
diff --git a/apps/docs/components/Learn/LoomDemo.tsx b/apps/docs/components/Learn/LoomDemo.tsx
deleted file mode 100644
index 020719a748..0000000000
--- a/apps/docs/components/Learn/LoomDemo.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import * as React from "react";
-
-const LoomDemo = () => {
- return (
- <div
- style={{
- position: "relative",
- paddingBottom: "65.36363636363637%",
- height: 0,
- }}
- >
- <iframe
- title="CarbonOS Walkthrough"
- src="https://www.loom.com/share/7eb03a5e4d4d4836b34f173805fb7403?sid=7ed308d0-8d59-4230-a3f1-137aae3c24da"
- 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.ts
deleted file mode 100644
index 5fdae08463..0000000000
--- a/apps/docs/components/Learn/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import LoomDemo from "./LoomDemo";
-
-export { LoomDemo };
diff --git a/apps/docs/components/ui/button.tsx b/apps/docs/components/ui/button.tsx
deleted file mode 100644
index b7b3dc1937..0000000000
--- a/apps/docs/components/ui/button.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-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.tsx
deleted file mode 100644
index 0867b9054a..0000000000
--- a/apps/docs/components/ui/form.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-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.tsx
deleted file mode 100644
index 1538e73f64..0000000000
--- a/apps/docs/components/ui/input.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-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.tsx
deleted file mode 100644
index 22dbcac41e..0000000000
--- a/apps/docs/components/ui/label.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-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.tsx
deleted file mode 100644
index 9eae516aa4..0000000000
--- a/apps/docs/hooks/useGlowPointer.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-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.tsx
deleted file mode 100644
index 105fb4967f..0000000000
--- a/apps/docs/hooks/useWindowSize.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-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/docs/next-env.d.ts b/apps/docs/next-env.d.ts
deleted file mode 100644
index 4f11a03dc6..0000000000
--- a/apps/docs/next-env.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/// <reference types="next" />
-/// <reference types="next/image-types/global" />
-
-// NOTE: This file should not be edited
-// see https://nextjs.org/docs/basic-features/typescript for more information.
diff --git a/apps/docs/next.config.js b/apps/docs/next.config.js
deleted file mode 100644
index 0918793996..0000000000
--- a/apps/docs/next.config.js
+++ /dev/null
@@ -1,10 +0,0 @@
-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.json
deleted file mode 100644
index 83a74b5530..0000000000
--- a/apps/docs/package.json
+++ /dev/null
@@ -1,48 +0,0 @@
-{
- "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": "^11.1.7",
- "geist": "^1.3.0",
- "next": "14.2.3",
- "nextra": "^2.5.2",
- "nextra-theme-docs": "^2.5.2",
- "react": "^18.3.1",
- "react-dom": "^18.3.1",
- "react-hook-form": "7.51.2",
- "react-icons": "^5.3.0",
- "tailwind-merge": "^2.2.1",
- "tailwindcss-animate": "^1.0.7",
- "zod": "^3.23.8"
- },
- "devDependencies": {
- "@carbon/tailwind": "*",
- "@carbon/tsconfig": "*",
- "@types/jest": "^26.0.22",
- "@types/node": "^20.12.5",
- "@types/react": "^18.2.74",
- "@types/react-dom": "^18.2.24",
- "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.tsx
deleted file mode 100644
index 081937c892..0000000000
--- a/apps/docs/pages/_app.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-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.json
deleted file mode 100644
index 4709cf658f..0000000000
--- a/apps/docs/pages/_meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "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.json
deleted file mode 100644
index 298123a445..0000000000
--- a/apps/docs/pages/core-concepts/_meta.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "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.mdx
deleted file mode 100644
index 8875c9e8f6..0000000000
--- a/apps/docs/pages/core-concepts/fetching.mdx
+++ /dev/null
@@ -1,171 +0,0 @@
----
-title: Data Fetching in CarbonOS
-description: Conventions for fetching data in CarbonOS
----
-
-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, companyId } = 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, companyId, {
- search,
- limit,
- offset,
- sorts,
- filters,
- });
-
- 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.mdx
deleted file mode 100644
index af1fcc5edb..0000000000
--- a/apps/docs/pages/core-concepts/permissions.mdx
+++ /dev/null
@@ -1,169 +0,0 @@
----
-title: Permissions in CarbonOS
-description: Conventions for permissions in CarbonOS
----
-
-# Permissions
-
-There are two types of permissions in the system:
-
-1. **Role permissions** - These are permissions that are specific to a role. These are in the `auth.users` and included in the JWT.
-2. **Module permissions** - These are permissions that are specific to a module. They are stored in the `public.userPermission` table.
-
-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.
-
-Each user has a **role**, which may be one of the following:
-
-- `owner`
-- `employee`
-- `customer`
-- `supplier`
-
-Additionally, each user has company-based permissions which are something like this:
-
-```json
-{
- "sales_view": [1],
- "sales_create": [1],
- "sales_update": [1],
- "sales_delete": [1],
- ...
- "purchasing_view": [1,2],
- "purchasing_create": [1],
- "purchasing_update": [1],
- "purchasing_delete": [1],
- ...
-}
-```
-
-This permissions roughly translates to: "The user has full permissions in purchasing and sales for company 1, but only the ability to view purchasing for company 2.
-
-Generally, the permission values are an array of company IDs (integers), and keys 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 (
- has_role('employee', "companyId") AND
- has_company_permission('sales_view', "companyId")
- );
-
-CREATE POLICY "Customers with sales_view can their own organization" ON "customer"
- FOR SELECT
- USING (
- has_role('customer', "companyId") AND
- has_company_permission('sales_view', "companyId")
- 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 (
- has_role('employee', "companyId") AND
- has_company_permission('sales_create', "companyId")
- );
-
-CREATE POLICY "Employees with sales_update can update customers" ON "customer"
- FOR UPDATE
- USING (
- has_role('employee', "companyId") AND
- has_company_permission('sales_update', "companyId")
- );
-
-CREATE POLICY "Customers with sales_update can their own organization" ON "customer"
- FOR UPDATE
- USING (
- has_role('customer', "companyId") AND
- has_company_permission('sales_update', "companyId")
- 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 (
- has_role('employee', "companyId") AND
- has_company_permission('sales_delete', "companyId")
- );
-
-```
-
-### 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.mdx
deleted file mode 100644
index 6c26d53062..0000000000
--- a/apps/docs/pages/core-concepts/realtime.mdx
+++ /dev/null
@@ -1,107 +0,0 @@
----
-title: Realtime in CarbonOS
-description: Conventions for using realtime data in CarbonOS
----
-
-# Realtime
-
-There are two basic use cases for realtime data in CarbonOS:
-
-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.mdx
deleted file mode 100644
index 729e833e86..0000000000
--- a/apps/docs/pages/core-concepts/serverless.mdx
+++ /dev/null
@@ -1,6 +0,0 @@
----
-title: Serverless Architecture in CarbonOS
-description: Overview of serverless infrastructure in CarbonOS
----
-
-# Serverless Architecture
diff --git a/apps/docs/pages/core-concepts/transactions.mdx b/apps/docs/pages/core-concepts/transactions.mdx
deleted file mode 100644
index 5e671a9867..0000000000
--- a/apps/docs/pages/core-concepts/transactions.mdx
+++ /dev/null
@@ -1,6 +0,0 @@
----
-title: Realtime in CarbonOS
-description: Conventions for database transactions in CarbonOS
----
-
-# Transactions
diff --git a/apps/docs/pages/core-concepts/writing.mdx b/apps/docs/pages/core-concepts/writing.mdx
deleted file mode 100644
index bd7634d926..0000000000
--- a/apps/docs/pages/core-concepts/writing.mdx
+++ /dev/null
@@ -1,210 +0,0 @@
----
-title: Data Writes in CarbonOS
-description: Conventions for mutating data in CarbonOS
----
-
-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/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/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/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"];
- itemLedger: Database["public"]["Tables"]["itemLedger"]["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("itemLedger")
- .set({
- expectedCost: 0,
- })
- .where("id", "=", itemLedgerId)
- .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.mdx
deleted file mode 100644
index 0443bf4288..0000000000
--- a/apps/docs/pages/getting-started.mdx
+++ /dev/null
@@ -1,75 +0,0 @@
----
-title: Getting started with CarbonOS
-description: Carbon is a high-performance operating system for manufacturing
----
-
-# 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 |
-| --------------- | ------------------------------------------------------------------------------------------------------------------ |
-| CarbonOS | [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.mdx
deleted file mode 100644
index 70e43a6025..0000000000
--- a/apps/docs/pages/index.mdx
+++ /dev/null
@@ -1,152 +0,0 @@
----
-title: CarbonOS 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.mdx
deleted file mode 100644
index 7f7c1abc87..0000000000
--- a/apps/docs/pages/principles.mdx
+++ /dev/null
@@ -1,40 +0,0 @@
----
-title: CarbonOS Principles
-description: Simplicity, extensibility, openness, and productivity are the four principles that guide the development of CarbonOS.
----
-
-# Principles
-
-Decision-making is guided by four principles:
-
-1. Simplicity
-2. Extensibility
-3. 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
-
-## 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.js
deleted file mode 100644
index cbfea5ea20..0000000000
--- a/apps/docs/postcss.config.js
+++ /dev/null
@@ -1,7 +0,0 @@
-module.exports = {
- plugins: {
- "tailwindcss/nesting": {},
- tailwindcss: {},
- autoprefixer: {},
- },
-};
diff --git a/apps/docs/public/carbon-dark-mode.jpg b/apps/docs/public/carbon-dark-mode.jpg
deleted file mode 100644
index dd67723bd8..0000000000
Binary files a/apps/docs/public/carbon-dark-mode.jpg and /dev/null differ
diff --git a/apps/docs/public/carbon-dark.jpg b/apps/docs/public/carbon-dark.jpg
deleted file mode 100644
index b4f30dd7fe..0000000000
Binary files a/apps/docs/public/carbon-dark.jpg and /dev/null differ
diff --git a/apps/docs/public/carbon-light-mode.jpg b/apps/docs/public/carbon-light-mode.jpg
deleted file mode 100644
index ec54a84ce0..0000000000
Binary files a/apps/docs/public/carbon-light-mode.jpg and /dev/null differ
diff --git a/apps/docs/public/carbon-light.jpg b/apps/docs/public/carbon-light.jpg
deleted file mode 100644
index 2966e2b5d6..0000000000
Binary files a/apps/docs/public/carbon-light.jpg and /dev/null differ
diff --git a/apps/docs/public/favicon.ico b/apps/docs/public/favicon.ico
deleted file mode 100644
index ce92de6710..0000000000
Binary files a/apps/docs/public/favicon.ico and /dev/null differ
diff --git a/apps/docs/public/grid.svg b/apps/docs/public/grid.svg
deleted file mode 100644
index d9dc0423ed..0000000000
--- a/apps/docs/public/grid.svg
+++ /dev/null
@@ -1,5 +0,0 @@
-
-<svg 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.png
deleted file mode 100644
index 75399c8d11..0000000000
Binary files a/apps/docs/public/logo-dark.png and /dev/null differ
diff --git a/apps/docs/public/logo-full.png b/apps/docs/public/logo-full.png
deleted file mode 100644
index d0f052c476..0000000000
Binary files a/apps/docs/public/logo-full.png and /dev/null differ
diff --git a/apps/docs/public/logo-light.png b/apps/docs/public/logo-light.png
deleted file mode 100644
index c0f93e6fe2..0000000000
Binary files a/apps/docs/public/logo-light.png and /dev/null differ
diff --git a/apps/docs/styles.css b/apps/docs/styles.css
deleted file mode 100644
index 0307e94332..0000000000
--- a/apps/docs/styles.css
+++ /dev/null
@@ -1,132 +0,0 @@
-@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.js
deleted file mode 100644
index 0ea1cf06ca..0000000000
--- a/apps/docs/tailwind.config.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require("@carbon/tailwind/tailwind.config");
diff --git a/apps/docs/theme.config.js b/apps/docs/theme.config.js
deleted file mode 100644
index d65ffa5d23..0000000000
--- a/apps/docs/theme.config.js
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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: `CarbonOS ${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 – CarbonOS",
- };
- },
-};
diff --git a/apps/docs/tsconfig.json b/apps/docs/tsconfig.json
deleted file mode 100644
index 9f8edd776f..0000000000
--- a/apps/docs/tsconfig.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "exclude": ["node_modules"],
- "extends": "@carbon/tsconfig/nextjs.json",
- "compilerOptions": {
- "outDir": "dist",
- "baseUrl": ".",
- "paths": {
- "~/*": ["./src/*"]
- },
- "strict": false
- },
- "include": ["next-env.d.ts", "pages"]
-}
diff --git a/apps/docs/utils/cn.tsx b/apps/docs/utils/cn.tsx
deleted file mode 100644
index 88283f0133..0000000000
--- a/apps/docs/utils/cn.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-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/apps/mes/app/components/DocumentPreview.tsx b/apps/mes/app/components/FilePreview.tsx
similarity index 85%
rename from apps/mes/app/components/DocumentPreview.tsx
rename to apps/mes/app/components/FilePreview.tsx
index ce2eec499a..824f1d17b5 100644
--- a/apps/mes/app/components/DocumentPreview.tsx
+++ b/apps/mes/app/components/FilePreview.tsx
@@ -8,17 +8,15 @@ import type { ComponentPropsWithoutRef, ElementRef } from "react";
import { forwardRef } from "react";
import { path } from "~/utils/path";
-type DocumentPreviewProps = ComponentPropsWithoutRef<
- typeof HoverCardContent
-> & {
+type FilePreviewProps = ComponentPropsWithoutRef<typeof HoverCardContent> & {
bucket: "public" | "private";
pathToFile: string;
type: "PDF" | "Image";
};
-const DocumentPreview = forwardRef<
+const FilePreview = forwardRef<
ElementRef<typeof HoverCardContent>,
- DocumentPreviewProps
+ FilePreviewProps
>(({ bucket, pathToFile, type, children, className, ...props }, ref) => {
return (
<HoverCard>
@@ -55,6 +53,6 @@ const DocumentPreview = forwardRef<
</HoverCard>
);
});
-DocumentPreview.displayName = "DocumentPreview";
+FilePreview.displayName = "FilePreview";
-export default DocumentPreview;
+export default FilePreview;
diff --git a/apps/mes/app/components/Icons.tsx b/apps/mes/app/components/Icons.tsx
index be45a368e9..0b3f0735f7 100644
--- a/apps/mes/app/components/Icons.tsx
+++ b/apps/mes/app/components/Icons.tsx
@@ -34,14 +34,14 @@ import { MediumPriorityIcon } from "~/assets/icons/MediumPriorityIcon";
import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
import type { documentTypes, Operation } from "~/services/jobs.service";
-type DocumentIconProps = {
+type FileIconProps = {
type: (typeof documentTypes)[number];
className?: string;
};
const documentIconBaseClase = "w-6 h-6 flex-shrink-0";
-export const DocumentIcon = ({ type, className }: DocumentIconProps) => {
+export const FileIcon = ({ type, className }: FileIconProps) => {
switch (type) {
case "Document":
return (
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index 7ebfec8a71..08ad4497d7 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -18,6 +18,7 @@ import {
ScrollArea,
Separator,
Skeleton,
+ Slider,
Table,
Tabs,
TabsContent,
@@ -42,11 +43,18 @@ import {
} from "@carbon/react";
import { Await, Link, useFetcher } from "@remix-run/react";
import type { ComponentProps, ReactNode } from "react";
-import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ Suspense,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import {
DeadlineIcon,
- DocumentIcon,
- DocumentPreview,
+ FileIcon,
+ FilePreview,
Hyperlink,
OptionallyFullscreen,
StatusIcon,
@@ -55,7 +63,6 @@ import { useUser } from "~/hooks";
import type {
Job,
JobMaterial,
- Operation,
OperationWithDetails,
ProductionEvent,
productionEventType,
@@ -63,14 +70,21 @@ import type {
StorageItem,
} from "~/services/jobs.service";
import {
- getDocumentType,
+ getFileType,
+ nonScrapQuantityValidator,
productionEventValidator,
scrapQuantityValidator,
} from "~/services/jobs.service";
import { path } from "~/utils/path";
+import { capitalize } from "~/utils/string";
import { useCarbon } from "@carbon/auth";
-import { Hidden, Number, TextArea, ValidatedForm } from "@carbon/form";
+import {
+ Hidden,
+ NumberControlled,
+ TextArea,
+ ValidatedForm,
+} from "@carbon/form";
import {
convertDateStringToIsoString,
convertKbToString,
@@ -83,7 +97,7 @@ import {
parseAbsolute,
toZoned,
} from "@internationalized/date";
-import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { PostgrestResponse, RealtimeChannel } from "@supabase/supabase-js";
import { FaRedoAlt, FaTasks } from "react-icons/fa";
import {
FaCheck,
@@ -117,19 +131,22 @@ export const JobOperation = ({
files,
job,
materials,
- operation,
+ operation: originalOperation,
}: JobOperationProps) => {
const {
activeTab,
eventType,
fullscreen,
isOverdue,
+ operation,
scrapModal,
- downloadDocument,
- getDocumentPath,
+ reworkModal,
+ completeModal,
setActiveTab,
setEventType,
- } = useOperation(operation, job);
+ } = useOperationState(originalOperation, job);
+
+ const { downloadFile, getFilePath } = useFiles(job);
const {
active,
@@ -137,7 +154,7 @@ export const JobOperation = ({
laborProductionEvent,
machineProductionEvent,
progress,
- } = useActiveEvents(operation, events);
+ } = useActiveEvents(originalOperation, events);
return (
<OptionallyFullscreen
@@ -428,7 +445,7 @@ export const JobOperation = ({
<Td>{material.quantity}</Td>
<Td>{material.estimatedQuantity}</Td>
- <Td className="lg:block hidden">
+ <Td className="lg:table-cell hidden">
<Badge variant="secondary">
<MethodIcon
type={material.methodType}
@@ -474,24 +491,24 @@ export const JobOperation = ({
</Tr>
) : (
resolvedFiles.map((file) => {
- const type = getDocumentType(file.name);
+ const type = getFileType(file.name);
return (
<Tr key={file.id}>
<Td>
<HStack>
- <DocumentIcon type={type} />
+ <FileIcon type={type} />
<Hyperlink
- onClick={() => downloadDocument(file)}
+ onClick={() => downloadFile(file)}
>
{["PDF", "Image"].includes(type) ? (
- <DocumentPreview
+ <FilePreview
bucket="private"
- pathToFile={getDocumentPath(file)}
+ pathToFile={getFilePath(file)}
// @ts-ignore
- type={getDocumentType(file.name)}
+ type={getFileType(file.name)}
>
{file.name}
- </DocumentPreview>
+ </FilePreview>
) : (
file.name
)}
@@ -549,6 +566,7 @@ export const JobOperation = ({
<FaRedoAlt className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
tooltip="Rework"
+ onClick={reworkModal.onOpen}
/>
<IconButtonWithTooltip
icon={
@@ -570,6 +588,7 @@ export const JobOperation = ({
<FaCheck className="text-accent-foreground group-hover:text-accent-foreground/80" />
}
tooltip="Complete"
+ onClick={completeModal.onOpen}
/>
<IconButtonWithTooltip
icon={
@@ -588,8 +607,19 @@ export const JobOperation = ({
</Controls>
)}
</Tabs>
+ {reworkModal.isOpen && (
+ <QuantityModal
+ type="rework"
+ operation={operation}
+ setupProductionEvent={setupProductionEvent}
+ laborProductionEvent={laborProductionEvent}
+ machineProductionEvent={machineProductionEvent}
+ onClose={reworkModal.onClose}
+ />
+ )}
{scrapModal.isOpen && (
- <ScrapModal
+ <QuantityModal
+ type="scrap"
operation={operation}
setupProductionEvent={setupProductionEvent}
laborProductionEvent={laborProductionEvent}
@@ -597,6 +627,16 @@ export const JobOperation = ({
onClose={scrapModal.onClose}
/>
)}
+ {completeModal.isOpen && (
+ <QuantityModal
+ type="complete"
+ operation={operation}
+ setupProductionEvent={setupProductionEvent}
+ laborProductionEvent={laborProductionEvent}
+ machineProductionEvent={machineProductionEvent}
+ onClose={completeModal.onClose}
+ />
+ )}
</OptionallyFullscreen>
);
};
@@ -613,6 +653,7 @@ function useActiveEvents(
} {
const { carbon, accessToken } = useCarbon();
const user = useUser();
+ const channelRef = useRef<RealtimeChannel | null>(null);
const [eventState, setEventState] = useState<ProductionEvent[]>(events);
@@ -623,50 +664,57 @@ function useActiveEvents(
useEffect(() => {
if (!carbon || !accessToken) return;
carbon.realtime.setAuth(accessToken);
- const channel = carbon
- .channel("realtime:core")
- .on(
- "postgres_changes",
- {
- event: "*",
- schema: "public",
- table: "productionEvent",
- filter: `jobOperationId=eq.${operation.id}`,
- },
- (payload) => {
- switch (payload.eventType) {
- case "INSERT":
- const { new: inserted } = payload;
- setEventState((prevEvents) => [
- ...prevEvents,
- inserted as ProductionEvent,
- ]);
- break;
- case "UPDATE":
- const { new: updated } = payload;
- setEventState((prevEvents) =>
- prevEvents.map((event) =>
- event.id === updated.id ? (updated as ProductionEvent) : event
- )
- );
- break;
- case "DELETE":
- const { old: deleted } = payload;
- setEventState((prevEvents) =>
- prevEvents.filter((event) => event.id !== deleted.id)
- );
- break;
- default:
- break;
+
+ if (!channelRef.current) {
+ channelRef.current = carbon
+ .channel("realtime:core")
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "productionEvent",
+ filter: `jobOperationId=eq.${operation.id}`,
+ },
+ (payload) => {
+ switch (payload.eventType) {
+ case "INSERT":
+ const { new: inserted } = payload;
+ setEventState((prevEvents) => [
+ ...prevEvents,
+ inserted as ProductionEvent,
+ ]);
+ break;
+ case "UPDATE":
+ const { new: updated } = payload;
+ setEventState((prevEvents) =>
+ prevEvents.map((event) =>
+ event.id === updated.id
+ ? (updated as ProductionEvent)
+ : event
+ )
+ );
+ break;
+ case "DELETE":
+ const { old: deleted } = payload;
+ setEventState((prevEvents) =>
+ prevEvents.filter((event) => event.id !== deleted.id)
+ );
+ break;
+ default:
+ break;
+ }
}
- }
- )
- .subscribe();
+ )
+ .subscribe();
+ }
return () => {
- if (channel) carbon?.removeChannel(channel);
+ if (channelRef.current) carbon?.removeChannel(channelRef.current);
};
- }, [accessToken, carbon, operation.id]);
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [accessToken, operation.id]);
const getProgress = useCallback(() => {
const timeNow = now(getLocalTimeZone());
@@ -737,23 +785,11 @@ function useActiveEvents(
};
}
-function useOperation(operation: OperationWithDetails, job: Job) {
+function useFiles(job: Job) {
const user = useUser();
const { carbon } = useCarbon();
- const fullscreen = useDisclosure();
- const scrapModal = useDisclosure();
- const [activeTab, setActiveTab] = useState("details");
- const [eventType, setEventType] = useState(() => {
- if (operation.laborDuration > 0) {
- return "Labor";
- }
- if (operation.machineDuration > 0) {
- return "Machine";
- }
- return "Setup";
- });
- const getDocumentPath = useCallback(
+ const getFilePath = useCallback(
(file: StorageItem) => {
const companyId = user.company.id;
const { bucket } = file;
@@ -765,18 +801,16 @@ function useOperation(operation: OperationWithDetails, job: Job) {
[job.id, job.quoteLineId, job.salesOrderLineId, user.company.id]
);
- const downloadDocument = useCallback(
+ const downloadFile = useCallback(
async (file: StorageItem) => {
- const type = getDocumentType(file.name);
+ const type = getFileType(file.name);
if (type === "PDF") {
- const url = path.to.file.previewFile(
- `private/${getDocumentPath(file)}`
- );
+ const url = path.to.file.previewFile(`private/${getFilePath(file)}`);
window.open(url, "_blank");
} else {
const result = await carbon?.storage
.from("private")
- .download(getDocumentPath(file));
+ .download(getFilePath(file));
if (!result || result.error) {
toast.error(result?.error?.message || "Error downloading file");
@@ -796,20 +830,102 @@ function useOperation(operation: OperationWithDetails, job: Job) {
}, 0);
}
},
- [carbon?.storage, getDocumentPath]
+ [carbon?.storage, getFilePath]
);
return {
+ downloadFile,
+ getFilePath,
+ };
+}
+
+function useOperationState(operation: OperationWithDetails, job: Job) {
+ const fullscreen = useDisclosure();
+
+ const scrapModal = useDisclosure();
+ const reworkModal = useDisclosure();
+ const completeModal = useDisclosure();
+ const finishModal = useDisclosure();
+
+ const [activeTab, setActiveTab] = useState("details");
+ const [eventType, setEventType] = useState(() => {
+ if (operation.laborDuration > 0) {
+ return "Labor";
+ }
+ if (operation.machineDuration > 0) {
+ return "Machine";
+ }
+ return "Setup";
+ });
+
+ const { carbon, accessToken } = useCarbon();
+ const [operationState, setOperationState] = useState(operation);
+ const channelRef = useRef<RealtimeChannel | null>(null);
+
+ useEffect(() => {
+ setOperationState(operation);
+ }, [operation]);
+
+ useEffect(() => {
+ if (!carbon || !accessToken) return;
+
+ carbon.realtime.setAuth(accessToken);
+
+ if (!channelRef.current) {
+ channelRef.current = carbon
+ .channel("realtime:core")
+ .on(
+ "postgres_changes",
+ {
+ event: "*",
+ schema: "public",
+ table: "jobOperation",
+ filter: `id=eq.${operation.id}`,
+ },
+ (payload) => {
+ if (payload.eventType === "UPDATE") {
+ const { new: updated } = payload;
+ if (updated.id === operation.id) {
+ setOperationState((prevState) => ({
+ ...prevState,
+ quantityComplete: updated.quantityComplete,
+ quantityScrapped: updated.quantityScrapped,
+ quantityReworked: updated.quantityReworked,
+ }));
+ }
+ } else if (payload.eventType === "DELETE") {
+ if (payload.old.id === operation.id) {
+ alert("This operation has been deleted.");
+ window.location.href = path.to.jobs;
+ }
+ }
+ }
+ )
+ .subscribe();
+ }
+
+ return () => {
+ if (channelRef.current) {
+ carbon?.removeChannel(channelRef.current);
+ channelRef.current = null;
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [accessToken, operation.id]);
+
+ return {
+ operation: operationState,
activeTab,
eventType,
fullscreen,
scrapModal,
+ reworkModal,
+ completeModal,
+ finishModal,
isOverdue: operation.jobDueDate
? new Date(operation.jobDueDate) < new Date()
: false,
- downloadDocument,
- getDocumentPath,
setActiveTab,
setEventType,
};
@@ -1083,32 +1199,66 @@ function PlayButton({ className, ...props }: ComponentProps<"button">) {
);
}
-function ScrapModal({
+function QuantityModal({
operation,
setupProductionEvent,
laborProductionEvent,
machineProductionEvent,
onClose,
+ type,
}: {
- operation: Operation;
+ operation: OperationWithDetails;
setupProductionEvent: ProductionEvent | undefined;
laborProductionEvent: ProductionEvent | undefined;
machineProductionEvent: ProductionEvent | undefined;
onClose: () => void;
+ type: "scrap" | "rework" | "complete";
}) {
const fetcher = useFetcher<ProductionQuantity>();
- const [scrapReason, setScrapReason] = useState("");
+ const [reason, setReason] = useState("");
+ const [quantity, setQuantity] = useState(1);
+
+ const titleMap = {
+ scrap: `Scrap ${operation.itemReadableId}`,
+ rework: `Rework ${operation.itemReadableId}`,
+ complete: `Complete ${operation.itemReadableId}`,
+ };
+
+ const descriptionMap = {
+ scrap: "Select a scrap quantity and reason",
+ rework: "Select a rework quantity",
+ complete: "Select a completion quantity",
+ };
+
+ const actionMap = {
+ scrap: path.to.scrap,
+ rework: path.to.rework,
+ complete: path.to.complete,
+ };
+
+ const validatorMap = {
+ scrap: scrapQuantityValidator,
+ rework: nonScrapQuantityValidator,
+ complete: nonScrapQuantityValidator,
+ };
+
return (
- <Modal open>
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
<ModalContent>
<ValidatedForm
- action={path.to.scrap}
+ action={actionMap[type]}
method="post"
- validator={scrapQuantityValidator}
+ validator={validatorMap[type]}
defaultValues={{
jobOperationId: operation.id,
quantity: 1,
- scrapReason: "",
setupProductionEventId: setupProductionEvent?.id,
laborProductionEventId: laborProductionEvent?.id,
machineProductionEventId: machineProductionEvent?.id,
@@ -1119,10 +1269,8 @@ function ScrapModal({
}}
>
<ModalHeader>
- <ModalTitle>{`Scrap ${operation.itemReadableId}`}</ModalTitle>
- <ModalDescription>
- Select a scrap quantity and reason
- </ModalDescription>
+ <ModalTitle>{titleMap[type]}</ModalTitle>
+ <ModalDescription>{descriptionMap[type]}</ModalDescription>
</ModalHeader>
<ModalBody>
<Hidden name="jobOperationId" />
@@ -1130,41 +1278,66 @@ function ScrapModal({
<Hidden name="laborProductionEventId" />
<Hidden name="machineProductionEventId" />
<VStack spacing={2}>
- <Number
+ <NumberControlled
name="quantity"
label="Quantity"
+ value={quantity}
+ onChange={setQuantity}
minValue={1}
- maxValue={operation.operationQuantity}
/>
- <TextArea
- label="Scrap Reason"
- name="scrapReason"
- value={scrapReason}
- onChange={(e) => setScrapReason(e.target.value)}
+ <Slider
+ className="py-3"
+ value={[quantity]}
+ onValueChange={(value) => setQuantity(value[0])}
+ step={1}
+ min={1}
+ max={operation.operationQuantity}
/>
- <div className="col-span-2 flex gap-2 mt-2">
- <Badge
- variant="secondary"
- className="cursor-pointer"
- onClick={() => setScrapReason("Defective")}
- >
- Defective
- </Badge>
- <Badge
- variant="secondary"
- className="cursor-pointer"
- onClick={() => setScrapReason("Damaged")}
- >
- Damaged
- </Badge>
- <Badge
- variant="secondary"
- className="cursor-pointer"
- onClick={() => setScrapReason("Quality Control")}
- >
- Quality Control
- </Badge>
- </div>
+ {type === "scrap" ? (
+ <>
+ <TextArea
+ label="Scrap Reason"
+ name="scrapReason"
+ value={reason}
+ onChange={(e) => setReason(e.target.value)}
+ />
+ <div className="col-span-2 flex gap-2 mt-2">
+ <Badge
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setReason("Defective")}
+ >
+ Defective
+ </Badge>
+ <Badge
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setReason("Damaged")}
+ >
+ Damaged
+ </Badge>
+ <Badge
+ variant="secondary"
+ className="cursor-pointer"
+ onClick={() => setReason("Quality Control")}
+ >
+ Quality Control
+ </Badge>
+ </div>
+ </>
+ ) : (
+ <NumberControlled
+ name="totalQuantity"
+ label="Total Quantity"
+ value={
+ quantity +
+ (type === "rework"
+ ? operation.quantityReworked
+ : operation.quantityComplete)
+ }
+ isReadOnly
+ />
+ )}
</VStack>
</ModalBody>
<ModalFooter>
@@ -1172,8 +1345,11 @@ function ScrapModal({
Cancel
</Button>
- <Button variant="destructive" type="submit">
- Scrap
+ <Button
+ variant={type === "scrap" ? "destructive" : "primary"}
+ type="submit"
+ >
+ {capitalize(type)}
</Button>
</ModalFooter>
</ValidatedForm>
diff --git a/apps/mes/app/components/index.ts b/apps/mes/app/components/index.ts
index 1ee8333a6b..753d015372 100644
--- a/apps/mes/app/components/index.ts
+++ b/apps/mes/app/components/index.ts
@@ -1,8 +1,8 @@
import Avatar from "./Avatar";
import AvatarMenu from "./AvatarMenu";
-import DocumentPreview from "./DocumentPreview";
+import FilePreview from "./FilePreview";
import Hyperlink from "./Hyperlink";
-import { DeadlineIcon, DocumentIcon, StatusIcon } from "./Icons";
+import { DeadlineIcon, FileIcon, StatusIcon } from "./Icons";
import { JobOperation } from "./JobOperation";
import { Nav } from "./Nav";
import { OperationsList } from "./OperationsList";
@@ -12,8 +12,8 @@ export {
Avatar,
AvatarMenu,
DeadlineIcon,
- DocumentIcon,
- DocumentPreview,
+ FileIcon,
+ FilePreview,
Hyperlink,
JobOperation,
Nav,
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index 82ef272660..5bb7fb59bb 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -109,6 +109,10 @@ function Document({
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<title>{title}</title>
+ <meta charSet="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <Meta />
+ <link rel="manifest" href="/assets/manifest.webmanifest" />
<Links />
<script
defer
diff --git a/apps/mes/app/routes/assets+/manifest[.]webmanifest.ts b/apps/mes/app/routes/assets+/manifest[.]webmanifest.ts
new file mode 100644
index 0000000000..bd82213a0b
--- /dev/null
+++ b/apps/mes/app/routes/assets+/manifest[.]webmanifest.ts
@@ -0,0 +1,152 @@
+import type { LoaderFunction } from "@remix-run/node";
+
+export const loader: LoaderFunction = () => {
+ const manifest = {
+ short_name: "CarbonOS",
+ name: "CarbonOS MES",
+ orientation: "landscape",
+ icons: [
+ {
+ src: "/icons/16.png",
+ sizes: "16x16",
+ type: "image/png",
+ },
+ {
+ src: "/icons/20.png",
+ sizes: "20x20",
+ type: "image/png",
+ },
+ {
+ src: "/icons/29.png",
+ sizes: "29x29",
+ type: "image/png",
+ },
+ {
+ src: "/icons/32.png",
+ sizes: "32x32",
+ type: "image/png",
+ },
+ {
+ src: "/icons/40.png",
+ sizes: "40x40",
+ type: "image/png",
+ },
+ {
+ src: "/icons/50.png",
+ sizes: "50x50",
+ type: "image/png",
+ },
+ {
+ src: "/icons/57.png",
+ sizes: "57x57",
+ type: "image/png",
+ },
+ {
+ src: "/icons/58.png",
+ sizes: "58x58",
+ type: "image/png",
+ },
+ {
+ src: "/icons/60.png",
+ sizes: "60x60",
+ type: "image/png",
+ },
+ {
+ src: "/icons/64.png",
+ sizes: "64x64",
+ type: "image/png",
+ },
+ {
+ src: "/icons/72.png",
+ sizes: "72x72",
+ type: "image/png",
+ },
+ {
+ src: "/icons/76.png",
+ sizes: "76x76",
+ type: "image/png",
+ },
+ {
+ src: "/icons/80.png",
+ sizes: "80x80",
+ type: "image/png",
+ },
+ {
+ src: "/icons/87.png",
+ sizes: "87x87",
+ type: "image/png",
+ },
+ {
+ src: "/icons/100.png",
+ sizes: "100x100",
+ type: "image/png",
+ },
+ {
+ src: "/icons/114.png",
+ sizes: "114x114",
+ type: "image/png",
+ },
+ {
+ src: "/icons/120.png",
+ sizes: "120x120",
+ type: "image/png",
+ },
+ {
+ src: "/icons/128.png",
+ sizes: "128x128",
+ type: "image/png",
+ },
+ {
+ src: "/icons/144.png",
+ sizes: "144x144",
+ type: "image/png",
+ },
+ {
+ src: "/icons/152.png",
+ sizes: "152x152",
+ type: "image/png",
+ },
+ {
+ src: "/icons/167.png",
+ sizes: "167x167",
+ type: "image/png",
+ },
+ {
+ src: "/icons/180.png",
+ sizes: "180x180",
+ type: "image/png",
+ },
+ {
+ src: "/icons/192.png",
+ sizes: "192x192",
+ type: "image/png",
+ },
+ {
+ src: "/icons/256.png",
+ sizes: "256x256",
+ type: "image/png",
+ },
+ {
+ src: "/icons/512.png",
+ sizes: "512x512",
+ type: "image/png",
+ },
+ {
+ src: "/icons/1024.png",
+ sizes: "1024x1024",
+ type: "image/png",
+ },
+ ],
+ start_url: "/",
+ display: "standalone",
+ theme_color: "#2d2d2d",
+ background_color: "#2d2d2d",
+ };
+
+ return new Response(JSON.stringify(manifest), {
+ headers: {
+ "Content-Type": "application/manifest+json",
+ "Cache-Control": "public, max-age=600",
+ },
+ });
+};
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index c82b3a4d08..4ecbed5362 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -132,86 +132,98 @@ export default function AuthenticatedRoute() {
}, [transition.state]);
return (
- <CarbonProvider session={session}>
- <AutodeskProvider tokenEndpoint={path.to.api.autodeskToken}>
- <TooltipProvider delayDuration={0}>
- <ClientOnly fallback={null}>
- {() => (
- <ResizablePanelGroup
- direction="horizontal"
- className="h-full items-stretch"
- >
- <ResizablePanel
- ref={panelRef}
- defaultSize={isMobile ? 4 : defaultLayout[0]}
- collapsedSize={4}
- collapsible={true}
- minSize={15}
- maxSize={25}
- onCollapse={() => {
- setIsCollapsed(true);
- }}
- onExpand={() => {
- setIsCollapsed(false);
- }}
- className={cn(
- isCollapsed &&
- "min-w-[50px] transition-all duration-300 ease-in-out"
- )}
+ <div className="h-full w-full">
+ <div className="ray" data-theme="dark" data-chat-started="true">
+ <div className="light-ray ray-one"></div>
+ <div className="light-ray ray-two"></div>
+ <div className="light-ray ray-three"></div>
+ <div className="light-ray ray-four"></div>
+ <div className="light-ray ray-five"></div>
+ </div>
+
+ <CarbonProvider session={session}>
+ <AutodeskProvider tokenEndpoint={path.to.api.autodeskToken}>
+ <TooltipProvider delayDuration={0}>
+ <ClientOnly fallback={null}>
+ {() => (
+ <ResizablePanelGroup
+ direction="horizontal"
+ className="h-full items-stretch"
>
- <div
+ <ResizablePanel
+ ref={panelRef}
+ defaultSize={isMobile ? 4 : defaultLayout[0]}
+ collapsedSize={4}
+ collapsible={true}
+ minSize={15}
+ maxSize={25}
+ onCollapse={() => {
+ setIsCollapsed(true);
+ }}
+ onExpand={() => {
+ setIsCollapsed(false);
+ }}
className={cn(
- "flex h-[52px] items-center justify-start bg-background",
- isCollapsed ? "h-[52px]" : "px-2"
+ isCollapsed &&
+ "min-w-[50px] transition-all duration-300 ease-in-out"
)}
>
<div
- className={cn("flex w-full items-center justify-center")}
+ className={cn(
+ "flex h-[52px] items-center justify-start bg-background",
+ isCollapsed ? "h-[52px]" : "px-2"
+ )}
>
- <AvatarMenu
- // company={company}
- // companies={companies}
- isCollapsed={isCollapsed}
- location={location}
- locations={locations}
- />
+ <div
+ className={cn(
+ "flex w-full items-center justify-center"
+ )}
+ >
+ <AvatarMenu
+ // company={company}
+ // companies={companies}
+ isCollapsed={isCollapsed}
+ location={location}
+ locations={locations}
+ />
+ </div>
</div>
- </div>
- <div className="flex flex-col h-[calc(100%-52px)] justify-between overflow-y-auto bg-background">
- <div className="flex flex-col">
- <Separator />
- <Nav
- isCollapsed={isCollapsed}
- links={[
- {
- title: "Jobs",
- icon: LuInbox,
- to: path.to.jobs,
- },
- {
- title: "Active",
- icon: LuActivity,
- label: (activeEvents ?? 0).toString(),
- to: path.to.active,
- },
- {
- title: "Recent",
- icon: LuClock,
- to: path.to.recent,
- },
- ]}
- />
+ <div className="flex flex-col h-[calc(100%-52px)] justify-between overflow-y-auto bg-background">
+ <div className="flex flex-col">
+ <Separator />
+ <Nav
+ isCollapsed={isCollapsed}
+ links={[
+ {
+ title: "Jobs",
+ icon: LuInbox,
+ to: path.to.jobs,
+ },
+ {
+ title: "Active",
+ icon: LuActivity,
+ label: (activeEvents ?? 0).toString(),
+ to: path.to.active,
+ },
+ {
+ title: "Recent",
+ icon: LuClock,
+ to: path.to.recent,
+ },
+ ]}
+ />
+ </div>
</div>
- </div>
- </ResizablePanel>
- <ResizableHandle withHandle />
- <Outlet />
- </ResizablePanelGroup>
- )}
- </ClientOnly>
- </TooltipProvider>
- <Toaster position="top-right" />
- </AutodeskProvider>
- </CarbonProvider>
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <Outlet />
+ </ResizablePanelGroup>
+ )}
+ </ClientOnly>
+ </TooltipProvider>
+ <Toaster position="top-right" />
+ </AutodeskProvider>
+ </CarbonProvider>
+ </div>
);
}
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
new file mode 100644
index 0000000000..3a5319d79a
--- /dev/null
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -0,0 +1,47 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import {
+ insertProductionQuantity,
+ nonScrapQuantityValidator,
+} from "~/services/jobs.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "accounting",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(nonScrapQuantityValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const insertProduction = await insertProductionQuantity(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (insertProduction.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertProduction.error, "Failed to record production quantity")
+ )
+ );
+ }
+
+ return json(
+ insertProduction.data,
+ await flash(request, success("Production quantity recorded successfully"))
+ );
+}
diff --git a/apps/mes/app/routes/x+/rework.tsx b/apps/mes/app/routes/x+/rework.tsx
new file mode 100644
index 0000000000..e8bad5c4eb
--- /dev/null
+++ b/apps/mes/app/routes/x+/rework.tsx
@@ -0,0 +1,47 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import {
+ insertReworkQuantity,
+ nonScrapQuantityValidator,
+} from "~/services/jobs.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "accounting",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(nonScrapQuantityValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const insertRework = await insertReworkQuantity(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (insertRework.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(insertRework.error, "Failed to record rework quantity")
+ )
+ );
+ }
+
+ return json(
+ insertRework.data,
+ await flash(request, success("Rework quantity recorded successfully"))
+ );
+}
diff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsx
index 05ebbb85be..f784cf0531 100644
--- a/apps/mes/app/routes/x+/scrap.tsx
+++ b/apps/mes/app/routes/x+/scrap.tsx
@@ -31,7 +31,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (insertScrap.error) {
return json(
{},
- await flash(request, error("Failed to record scrap quantity"))
+ await flash(
+ request,
+ error(insertScrap.error, "Failed to record scrap quantity")
+ )
);
}
diff --git a/apps/mes/app/services/jobs.service.ts b/apps/mes/app/services/jobs.service.ts
index 1fa5f3f4f3..8da38a6ffd 100644
--- a/apps/mes/app/services/jobs.service.ts
+++ b/apps/mes/app/services/jobs.service.ts
@@ -3,6 +3,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { PostgrestResponse, SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import { zfd } from "zod-form-data";
+import { sanitize } from "~/utils/supabase";
export type BaseOperation = NonNullable<
Awaited<ReturnType<typeof getJobOperationsByWorkCenter>>["data"]
@@ -49,7 +50,7 @@ export type ProductionEvent = NonNullable<
>[number];
export type ProductionQuantity = NonNullable<
- Awaited<ReturnType<typeof insertScrapQuantity>>["data"]
+ Awaited<ReturnType<typeof getProductionQuantitiesForJobOperation>>["data"]
>[number];
export type StorageItem = FileObject & {
@@ -96,14 +97,16 @@ export const productionEventValidator = z.object({
workCenterId: zfd.text(z.string().optional()),
});
-export const scrapQuantityValidator = z.object({
+export const nonScrapQuantityValidator = z.object({
jobOperationId: z.string(),
quantity: zfd.numeric(z.number().positive()),
- unitOfMeasureCode: z.string().min(1),
- setupProductionEventId: z.string().optional(),
- laborProductionEventId: z.string().optional(),
- machineProductionEventId: z.string().optional(),
- scrapReason: z.string().min(1),
+ setupProductionEventId: zfd.text(z.string().optional()),
+ laborProductionEventId: zfd.text(z.string().optional()),
+ machineProductionEventId: zfd.text(z.string().optional()),
+});
+
+export const scrapQuantityValidator = nonScrapQuantityValidator.extend({
+ scrapReason: z.string().min(1, { message: "Scrap reason is required" }),
});
export async function getActiveJobOperationsByEmployee(
@@ -132,9 +135,7 @@ export async function getActiveJobCount(
});
}
-export function getDocumentType(
- fileName: string
-): (typeof documentTypes)[number] {
+export function getFileType(fileName: string): (typeof documentTypes)[number] {
const extension = fileName.split(".").pop()?.toLowerCase() ?? "";
if (["zip", "rar", "7z", "tar", "gz"].includes(extension)) {
return "Archive";
@@ -175,7 +176,7 @@ export function getDocumentType(
return "Other";
}
-export async function getJobDocuments(
+export async function getJobFiles(
client: SupabaseClient<Database>,
companyId: string,
job: Job
@@ -278,6 +279,16 @@ export async function getProductionEventsForJobOperation(
.eq("jobOperationId", args.operationId);
}
+export async function getProductionQuantitiesForJobOperation(
+ client: SupabaseClient<Database>,
+ operationId: string
+) {
+ return client
+ .from("productionQuantity")
+ .select("*")
+ .eq("jobOperationId", operationId);
+}
+
export async function getRecentJobOperationsByEmployee(
client: SupabaseClient<Database>,
args: {
@@ -320,6 +331,42 @@ export async function getWorkCentersByCompany(
.order("name", { ascending: true });
}
+export async function insertReworkQuantity(
+ client: SupabaseClient<Database>,
+ data: z.infer<typeof nonScrapQuantityValidator> & {
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("productionQuantity")
+ .insert(
+ sanitize({
+ ...data,
+ type: "Rework",
+ })
+ )
+ .select("*");
+}
+
+export async function insertProductionQuantity(
+ client: SupabaseClient<Database>,
+ data: z.infer<typeof nonScrapQuantityValidator> & {
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("productionQuantity")
+ .insert(
+ sanitize({
+ ...data,
+ type: "Production",
+ })
+ )
+ .select("*");
+}
+
export async function insertScrapQuantity(
client: SupabaseClient<Database>,
data: z.infer<typeof scrapQuantityValidator> & {
@@ -329,10 +376,12 @@ export async function insertScrapQuantity(
) {
return client
.from("productionQuantity")
- .insert({
- ...data,
- type: "Scrap",
- })
+ .insert(
+ sanitize({
+ ...data,
+ type: "Scrap",
+ })
+ )
.select("*");
}
diff --git a/apps/mes/app/services/operation.server.ts b/apps/mes/app/services/operation.server.ts
index 1d92543b48..80e3f49654 100644
--- a/apps/mes/app/services/operation.server.ts
+++ b/apps/mes/app/services/operation.server.ts
@@ -8,10 +8,11 @@ import { path } from "~/utils/path";
import type { OperationWithDetails } from "./jobs.service";
import {
getJobByOperationId,
- getJobDocuments,
+ getJobFiles,
getJobMaterialsByOperationId,
getJobOperationById,
getProductionEventsForJobOperation,
+ getProductionQuantitiesForJobOperation,
} from "./jobs.service";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -20,11 +21,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { operationId } = params;
if (!operationId) throw new Error("Operation ID is required");
- const [events, job, operation] = await Promise.all([
+ const [events, quantities, job, operation] = await Promise.all([
getProductionEventsForJobOperation(client, {
operationId,
userId,
}),
+ getProductionQuantitiesForJobOperation(client, operationId),
getJobByOperationId(client, operationId),
getJobOperationById(client, operationId),
]);
@@ -45,8 +47,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
events: events.data ?? [],
+ quantities: (quantities.data ?? []).reduce(
+ (acc, curr) => {
+ if (curr.type === "Scrap") {
+ acc.scrap += curr.quantity;
+ } else if (curr.type === "Production") {
+ acc.production += curr.quantity;
+ } else if (curr.type === "Rework") {
+ acc.rework += curr.quantity;
+ }
+ return acc;
+ },
+ { scrap: 0, production: 0, rework: 0 }
+ ),
job: job.data,
- files: getJobDocuments(client, companyId, job.data),
+ files: getJobFiles(client, companyId, job.data),
materials: getJobMaterialsByOperationId(client, operation.data?.[0]),
operation: makeDurations(operation.data?.[0]) as OperationWithDetails,
});
diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.css
index fae3c558d0..11cb7b9827 100644
--- a/apps/mes/app/styles/tailwind.css
+++ b/apps/mes/app/styles/tailwind.css
@@ -29,6 +29,11 @@
--input: 240 5.9% 90%;
--ring: 240 5% 64.9%;
--radius: 0.5rem;
+ --gradient-opacity: 0.85;
+ --ray-gradient: radial-gradient(
+ hsl(var(--primary)) 0%,
+ hsl(var(--background)) 100%
+ );
}
.dark {
@@ -53,6 +58,10 @@
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 240 4.9% 83.9%;
+ --ray-gradient: radial-gradient(
+ hsl(var(--primary)) 0%,
+ hsl(var(--background)) 100%
+ );
}
}
@@ -68,14 +77,14 @@
}
}
-.forgeViewer {
+.forge-viewer {
position: relative;
width: 100%;
height: 100%;
min-height: 400px;
}
-.forgeViewer > div {
+.forge-viewer > div {
border-radius: var(--radius);
}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index b76c1d6692..d5aab9d209 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -24,6 +24,7 @@ export const path = {
active: `${x}/active`,
authenticatedRoot: x,
callback: "/callback",
+ complete: `${x}/complete`,
forgotPassword: "/forgot-password",
healthcheck: "/healthcheck",
jobs: `${x}/jobs`,
@@ -34,6 +35,7 @@ export const path = {
recent: `${x}/recent`,
refreshSession: "/refresh-session",
requestAccess: "/request-access",
+ rework: `${x}/rework`,
root: "/",
scrap: `${x}/scrap`,
workCenter: (workCenter: string) => generatePath(`${x}/jobs/${workCenter}`),
diff --git a/apps/mes/app/utils/string.ts b/apps/mes/app/utils/string.ts
new file mode 100644
index 0000000000..56c86577f9
--- /dev/null
+++ b/apps/mes/app/utils/string.ts
@@ -0,0 +1,4 @@
+export const capitalize = (words: string) => {
+ const [first, ...otherLetters] = words;
+ return [first.toLocaleUpperCase(), ...otherLetters].join("");
+};
diff --git a/apps/mes/app/utils/supabase.ts b/apps/mes/app/utils/supabase.ts
index 4631ac61cb..01f712c67a 100644
--- a/apps/mes/app/utils/supabase.ts
+++ b/apps/mes/app/utils/supabase.ts
@@ -1,7 +1,15 @@
-export const sanitize = (input: Record<string, any>) => {
- const output = { ...input };
+export function sanitize<T extends Record<string, any>>(
+ input: T
+): {
+ [K in keyof T]: T[K] extends undefined ? null : T[K];
+} {
+ const output = { ...input } as {
+ [K in keyof T]: T[K] extends undefined ? null : T[K];
+ };
Object.keys(output).forEach((key) => {
- if (output[key] === undefined && key !== "id") output[key] = null;
+ if (output[key as keyof T] === undefined && key !== "id") {
+ output[key as keyof T] = null as any;
+ }
});
return output;
-};
+}
diff --git a/apps/mes/public/icons/100.png b/apps/mes/public/icons/100.png
new file mode 100644
index 0000000000..ade7d30c3d
Binary files /dev/null and b/apps/mes/public/icons/100.png differ
diff --git a/apps/mes/public/icons/1024.png b/apps/mes/public/icons/1024.png
new file mode 100644
index 0000000000..8cfb758e35
Binary files /dev/null and b/apps/mes/public/icons/1024.png differ
diff --git a/apps/mes/public/icons/114.png b/apps/mes/public/icons/114.png
new file mode 100644
index 0000000000..01cf4cae47
Binary files /dev/null and b/apps/mes/public/icons/114.png differ
diff --git a/apps/mes/public/icons/120.png b/apps/mes/public/icons/120.png
new file mode 100644
index 0000000000..f06b660b55
Binary files /dev/null and b/apps/mes/public/icons/120.png differ
diff --git a/apps/mes/public/icons/128.png b/apps/mes/public/icons/128.png
new file mode 100644
index 0000000000..f44d0d1679
Binary files /dev/null and b/apps/mes/public/icons/128.png differ
diff --git a/apps/mes/public/icons/144.png b/apps/mes/public/icons/144.png
new file mode 100644
index 0000000000..f567943958
Binary files /dev/null and b/apps/mes/public/icons/144.png differ
diff --git a/apps/mes/public/icons/152.png b/apps/mes/public/icons/152.png
new file mode 100644
index 0000000000..a94fd463bf
Binary files /dev/null and b/apps/mes/public/icons/152.png differ
diff --git a/apps/mes/public/icons/16.png b/apps/mes/public/icons/16.png
new file mode 100644
index 0000000000..fb7536eb56
Binary files /dev/null and b/apps/mes/public/icons/16.png differ
diff --git a/apps/mes/public/icons/167.png b/apps/mes/public/icons/167.png
new file mode 100644
index 0000000000..0f2ef7e8fb
Binary files /dev/null and b/apps/mes/public/icons/167.png differ
diff --git a/apps/mes/public/icons/180.png b/apps/mes/public/icons/180.png
new file mode 100644
index 0000000000..e698431ede
Binary files /dev/null and b/apps/mes/public/icons/180.png differ
diff --git a/apps/mes/public/icons/192.png b/apps/mes/public/icons/192.png
new file mode 100644
index 0000000000..14280eb03f
Binary files /dev/null and b/apps/mes/public/icons/192.png differ
diff --git a/apps/mes/public/icons/20.png b/apps/mes/public/icons/20.png
new file mode 100644
index 0000000000..3cc7c56a54
Binary files /dev/null and b/apps/mes/public/icons/20.png differ
diff --git a/apps/mes/public/icons/256.png b/apps/mes/public/icons/256.png
new file mode 100644
index 0000000000..295aedad53
Binary files /dev/null and b/apps/mes/public/icons/256.png differ
diff --git a/apps/mes/public/icons/29.png b/apps/mes/public/icons/29.png
new file mode 100644
index 0000000000..801646cbcc
Binary files /dev/null and b/apps/mes/public/icons/29.png differ
diff --git a/apps/mes/public/icons/32.png b/apps/mes/public/icons/32.png
new file mode 100644
index 0000000000..100f038128
Binary files /dev/null and b/apps/mes/public/icons/32.png differ
diff --git a/apps/mes/public/icons/40.png b/apps/mes/public/icons/40.png
new file mode 100644
index 0000000000..6e80374e0d
Binary files /dev/null and b/apps/mes/public/icons/40.png differ
diff --git a/apps/mes/public/icons/50.png b/apps/mes/public/icons/50.png
new file mode 100644
index 0000000000..c5a2673b8a
Binary files /dev/null and b/apps/mes/public/icons/50.png differ
diff --git a/apps/mes/public/icons/512.png b/apps/mes/public/icons/512.png
new file mode 100644
index 0000000000..ac39c49047
Binary files /dev/null and b/apps/mes/public/icons/512.png differ
diff --git a/apps/mes/public/icons/57.png b/apps/mes/public/icons/57.png
new file mode 100644
index 0000000000..75baf4e299
Binary files /dev/null and b/apps/mes/public/icons/57.png differ
diff --git a/apps/mes/public/icons/58.png b/apps/mes/public/icons/58.png
new file mode 100644
index 0000000000..08cc20fb31
Binary files /dev/null and b/apps/mes/public/icons/58.png differ
diff --git a/apps/mes/public/icons/60.png b/apps/mes/public/icons/60.png
new file mode 100644
index 0000000000..7b9f2a805a
Binary files /dev/null and b/apps/mes/public/icons/60.png differ
diff --git a/apps/mes/public/icons/64.png b/apps/mes/public/icons/64.png
new file mode 100644
index 0000000000..810706fef3
Binary files /dev/null and b/apps/mes/public/icons/64.png differ
diff --git a/apps/mes/public/icons/72.png b/apps/mes/public/icons/72.png
new file mode 100644
index 0000000000..8a985d5b97
Binary files /dev/null and b/apps/mes/public/icons/72.png differ
diff --git a/apps/mes/public/icons/76.png b/apps/mes/public/icons/76.png
new file mode 100644
index 0000000000..9b4fbf9399
Binary files /dev/null and b/apps/mes/public/icons/76.png differ
diff --git a/apps/mes/public/icons/80.png b/apps/mes/public/icons/80.png
new file mode 100644
index 0000000000..8bd45e36fe
Binary files /dev/null and b/apps/mes/public/icons/80.png differ
diff --git a/apps/mes/public/icons/87.png b/apps/mes/public/icons/87.png
new file mode 100644
index 0000000000..3e41ec46fd
Binary files /dev/null and b/apps/mes/public/icons/87.png differ
diff --git a/packages/database/supabase/migrations/20241002012019_production-quantities.sql b/packages/database/supabase/migrations/20241002012019_production-quantities.sql
index bf635a1a09..ef53a0e0bd 100644
--- a/packages/database/supabase/migrations/20241002012019_production-quantities.sql
+++ b/packages/database/supabase/migrations/20241002012019_production-quantities.sql
@@ -76,3 +76,75 @@ ALTER PUBLICATION supabase_realtime ADD TABLE "productionQuantity";
ALTER TABLE "jobOperation" REPLICA IDENTITY FULL;
ALTER PUBLICATION supabase_realtime ADD TABLE "jobOperation";
+
+-- Function to update job operation quantities
+CREATE OR REPLACE FUNCTION update_job_operation_quantities()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF TG_OP = 'INSERT' THEN
+ -- Increment quantities on insert
+ UPDATE "jobOperation"
+ SET
+ "quantityComplete" = "quantityComplete" +
+ CASE WHEN NEW."type" = 'Production' THEN NEW.quantity ELSE 0 END,
+ "quantityReworked" = "quantityReworked" +
+ CASE WHEN NEW."type" = 'Rework' THEN NEW.quantity ELSE 0 END,
+ "quantityScrapped" = "quantityScrapped" +
+ CASE WHEN NEW."type" = 'Scrap' THEN NEW.quantity ELSE 0 END
+ WHERE id = NEW."jobOperationId";
+ ELSIF TG_OP = 'UPDATE' THEN
+ -- Adjust quantities on update
+ UPDATE "jobOperation"
+ SET
+ "quantityComplete" = "quantityComplete" +
+ CASE
+ WHEN NEW."type" = 'Production' THEN NEW.quantity
+ WHEN OLD."type" = 'Production' THEN -OLD.quantity
+ ELSE 0
+ END,
+ "quantityReworked" = "quantityReworked" +
+ CASE
+ WHEN NEW."type" = 'Rework' THEN NEW.quantity
+ WHEN OLD."type" = 'Rework' THEN -OLD.quantity
+ ELSE 0
+ END,
+ "quantityScrapped" = "quantityScrapped" +
+ CASE
+ WHEN NEW."type" = 'Scrap' THEN NEW.quantity
+ WHEN OLD."type" = 'Scrap' THEN -OLD.quantity
+ ELSE 0
+ END
+ WHERE id = NEW."jobOperationId";
+ ELSIF TG_OP = 'DELETE' THEN
+ -- Decrement quantities on delete
+ UPDATE "jobOperation"
+ SET
+ "quantityComplete" = "quantityComplete" -
+ CASE WHEN OLD."type" = 'Production' THEN OLD.quantity ELSE 0 END,
+ "quantityReworked" = "quantityReworked" -
+ CASE WHEN OLD."type" = 'Rework' THEN OLD.quantity ELSE 0 END,
+ "quantityScrapped" = "quantityScrapped" -
+ CASE WHEN OLD."type" = 'Scrap' THEN OLD.quantity ELSE 0 END
+ WHERE id = OLD."jobOperationId";
+ END IF;
+ RETURN NULL;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Create trigger for INSERT
+CREATE TRIGGER insert_production_quantity_trigger
+AFTER INSERT ON "productionQuantity"
+FOR EACH ROW
+EXECUTE FUNCTION update_job_operation_quantities();
+
+-- Create trigger for UPDATE
+CREATE TRIGGER update_production_quantity_trigger
+AFTER UPDATE ON "productionQuantity"
+FOR EACH ROW
+EXECUTE FUNCTION update_job_operation_quantities();
+
+-- Create trigger for DELETE
+CREATE TRIGGER delete_production_quantity_trigger
+AFTER DELETE ON "productionQuantity"
+FOR EACH ROW
+EXECUTE FUNCTION update_job_operation_quantities();
diff --git a/packages/react/src/AutodeskViewer.tsx b/packages/react/src/AutodeskViewer.tsx
index d271badaa3..812a91e371 100644
--- a/packages/react/src/AutodeskViewer.tsx
+++ b/packages/react/src/AutodeskViewer.tsx
@@ -182,7 +182,7 @@ const AutodeskViewer: React.FC<AutodeskViewerProps> = ({
return typeof Autodesk === "undefined" ? (
<div>Please include viewer3D.min.js to the index.html </div>
) : (
- <div ref={viewerRef} className={cn("forgeViewer", className)}></div>
+ <div ref={viewerRef} className={cn("forge-viewer", className)}></div>
);
};
diff --git a/packages/react/src/Slider.tsx b/packages/react/src/Slider.tsx
index 20b50cd2ba..38a7abf8c0 100644
--- a/packages/react/src/Slider.tsx
+++ b/packages/react/src/Slider.tsx
@@ -1,70 +1,27 @@
-import * as RadixSlider from "@radix-ui/react-slider";
-import { cloneElement, type ComponentProps, type ReactElement } from "react";
-import { cn } from "./utils/cn";
-
-const variants = {
- primary: {
- container: "h-6 gap-1 rounded-sm hover:bg-muted px-1",
- icons: "h-4 w-4 text-foreground",
- root: "h-4",
- track: "h-1 bg-accent group-hover:bg-secondary",
- range: "bg-transparent group-hover:bg-primary",
- thumb: "h-3 w-3 border-2 border-primary bg-background shadow-md",
- },
-};
+"use client";
+import * as SliderPrimitive from "@radix-ui/react-slider";
+import * as React from "react";
-type VariantName = keyof typeof variants;
+import { cn } from "./utils/cn";
-export type SliderProps = ComponentProps<typeof RadixSlider.Root> & {
- leftIcon?: ReactElement;
- rightIcon?: ReactElement;
- variant: VariantName;
-};
+const Slider = React.forwardRef<
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative flex w-full touch-none select-none items-center",
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
+ <SliderPrimitive.Range className="absolute h-full bg-primary" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+));
+Slider.displayName = SliderPrimitive.Root.displayName;
-export function Slider({
- variant,
- className,
- leftIcon,
- rightIcon,
- ...props
-}: SliderProps) {
- const variation = variants[variant];
- return (
- <div className={cn("group flex items-center", variation.container)}>
- {leftIcon &&
- cloneElement(leftIcon, {
- className: !leftIcon.props?.size
- ? cn("mr-2 h-4 w-4", leftIcon.props.className)
- : cn("mr-2", leftIcon.props.className),
- })}
- <RadixSlider.Root
- className={cn(
- "relative flex touch-none select-none items-center",
- variation.root,
- className
- )}
- {...props}
- >
- <RadixSlider.Track
- className={cn("relative grow rounded-full", variation.track)}
- >
- <RadixSlider.Range
- className={cn("absolute h-full rounded-full", variation.range)}
- />
- </RadixSlider.Track>
- <RadixSlider.Thumb
- className={cn(
- "block cursor-pointer rounded-full transition focus:outline-none",
- variation.thumb
- )}
- />
- </RadixSlider.Root>
- {rightIcon &&
- cloneElement(rightIcon, {
- className: !rightIcon.props?.size
- ? cn("ml-2 h-4 w-4", rightIcon.props.className)
- : cn("ml-2", rightIcon.props.className),
- })}
- </div>
- );
-}
+export { Slider };