Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: mcp client
Brad Barbinf0298a51c916
diff --git a/apps/erp/app/components/Agent/Agent.tsx b/apps/erp/app/components/Agent/Agent.tsxnew file mode 100644index 0000000000..54333db224--- /dev/null+++ b/apps/erp/app/components/Agent/Agent.tsx@@ -0,0 +1,335 @@+import { Badge, Button, cn, CodeBlock, Popover, PopoverContent, PopoverTrigger } from "@carbon/react";+import { LuMessageSquare } from "react-icons/lu";+import { useUser } from "~/hooks/useUser";+import { Fragment, useEffect, useRef, useState } from "react";+import { flushSync } from "react-dom";+import { useCarbon } from "@carbon/auth";+import type { LanguageModelV1Prompt } from "ai";+import { EmployeeAvatar } from "~/components";+import { toast } from "@carbon/react";+import { LuCheck, LuChevronRight, LuWrench } from "react-icons/lu";+import { camelCaseToWords } from "~/utils/string";+import SYSTEM_PROMPT from "./system.txt?raw";++const providerMetadata = {+ anthropic: {+ cacheControl: {+ type: "ephemeral",+ },+ },+};++const getInitialPrompt = (): LanguageModelV1Prompt => [+ {+ role: "system",+ content: SYSTEM_PROMPT,+ providerMetadata,+ },+ {+ role: "system",+ content: `The current date is ${new Date().toDateString()}`,+ providerMetadata,+ },+];++export function Agent() {+ const [isOpen, setOpen] = useState(false);+ const {+ id: userId,+ company: { id: companyId },+ } = useUser();++ const rootRef = useRef<HTMLDivElement>(null);+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ const idRef = useRef(0);+ const abortControllerRef = useRef<AbortController | null>(null);++ const [tools, setTools] = useState<any[]>([]);+ const [status, setStatus] = useState<'ready' | 'submitted' | 'streaming' | 'error'>('ready');+ const [isRateLimited, setIsRateLimited] = useState(false);++ const messagesRef = useRef<LanguageModelV1Prompt>(getInitialPrompt());+ const [messages, setMessages] = useState<LanguageModelV1Prompt>(getInitialPrompt());++ const { carbon } = useCarbon();++ useEffect(() => {+ const initializeTools = async () => {+ if (!carbon) return;+ const tools = await carbon.functions.invoke("mcp", {+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "tools/list",+ id: ++idRef.current,+ }),+ headers: {+ "x-company-id": companyId,+ "x-user-id": userId,+ },+ });++ if (!tools?.data?.result) {+ toast.error("Failed to fetch tools");+ return;+ }++ setTools("tools" in tools?.data?.result ? tools.data.result.tools : []);+ };++ initializeTools();+ }, [carbon, companyId, userId]);++ const stop = () => {+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ abortControllerRef.current = null;+ }+ setStatus('ready');+ };++ useEffect(() => {+ if (rootRef.current) {+ rootRef.current.scrollTo(0, rootRef.current.scrollHeight);+ }+ }, [messages]);++ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === "Escape" && status !== 'ready') {+ stop();+ textareaRef.current?.focus();+ }+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [status]);++ async function send(message: string) {+ const newMessage: LanguageModelV1Prompt = [{+ role: "user",+ content: [+ {+ type: "text",+ text: message,+ providerMetadata: messagesRef.current.length === 1 ? providerMetadata : {},+ },+ ],+ }];++ messagesRef.current = [...messagesRef.current, ...newMessage];++ flushSync(() => {+ setMessages(messagesRef.current);+ setStatus('submitted');+ });++ await triggerRequest();+ }++ const triggerRequest = async () => {+ if (!carbon) return;++ try {+ const abortController = new AbortController();+ abortControllerRef.current = abortController;++ const response = await carbon.functions.invoke("chat", {+ headers: {+ "x-company-id": companyId,+ "x-user-id": userId,+ },+ body: JSON.stringify({+ prompt: messagesRef.current,+ mode: {+ type: "regular",+ tools: tools.map((tool) => ({+ type: "function",+ name: tool.name,+ description: tool.description,+ parameters: {+ ...tool.inputSchema,+ },+ })),+ },+ inputFormat: "messages",+ temperature: 1,+ }),+ });++ if (response?.error) {+ throw new Error(response.error);+ }++ const result = response.data;+ setStatus('streaming');++ if (result.text) {+ const newMessage: LanguageModelV1Prompt = [{+ role: "assistant",+ content: [+ {+ type: "text",+ text: result.text,+ },+ ],+ }];++ messagesRef.current = [...messagesRef.current, ...newMessage];+ setMessages(messagesRef.current);+ }++ setIsRateLimited(false);+ setStatus('ready');+ textareaRef.current?.focus();++ } catch (error) {+ console.error(error);+ setStatus('error');+ toast.error("An error occurred");+ } finally {+ abortControllerRef.current = null;+ }+ };++ return (+ <Popover onOpenChange={setOpen} open={isOpen}>+ <PopoverTrigger asChild>+ <Button+ variant="secondary"+ isIcon+ className="rounded-full before:rounded-full w-8 h-8 flex items-center"+ >+ <LuMessageSquare size={16} />+ </Button>+ </PopoverTrigger>+ <PopoverContent+ className="h-[calc(100vh-60px)] w-screen md:w-[480px] p-0 overflow-hidden flex flex-col"+ align="end"+ sideOffset={10}+ >+ <div className="flex-1 overflow-y-auto p-4">+ <div className="flex flex-col gap-y-4">+ {messages.map((item, index) => (+ <Fragment key={index}>+ {item.role === "user" && item.content[0].type === "text" && (+ <div className="flex items-center gap-x-2 bg-card p-3 rounded-lg border">+ <div className="h-8 w-8 rounded-full flex items-center justify-center">+ <EmployeeAvatar employeeId={userId} withName={false} />+ </div>+ <div className="whitespace-pre-wrap flex-1">+ {item.content[0].text}+ </div>+ </div>+ )}++ {item.role === "assistant" && item.content[0].type === "text" && (+ <div className="whitespace-pre-wrap text-foreground px-1">+ {item.content[0].text}+ </div>+ )}++{item.role === "assistant" && item.content[0].type === "tool-call" && (+ <ToolExecution+ toolCall={item.content[0]}+ result={messages[index + 1]?.role === "tool" ? messages[index + 1].content[0] : undefined}+ />+ )}++ {item.role === "system" && index > 1 && (+ <div className="whitespace-pre-wrap p-3 rounded bg-secondary border-l-[3px] border-l-muted italic opacity-80">+ {item.content}+ </div>+ )}+ </Fragment>+ ))}++ {status !== 'ready' && (+ <div className="w-full my-3 bg-secondary border-l-[3px] border-l-muted flex items-center">+ <div className="w-[18px] h-[18px] mr-3 relative">+ <div className="absolute w-full h-full rounded-full border-2 border-transparent border-t-muted-foreground border-b-muted animate-[thinking-spin-outer_1.5s_cubic-bezier(0.6,0.2,0.4,0.8)_infinite]">+ <div className="absolute inset-[2px] rounded-full border-2 border-transparent border-l-muted border-r-muted-foreground animate-[thinking-spin-inner_0.8s_cubic-bezier(0.3,0.7,0.7,0.3)_infinite]"></div>+ </div>+ </div>+ <div className="text-muted-foreground">+ {isRateLimited ? "Rate limited, retrying..." : "Thinking"}+ </div>+ </div>+ )}+ </div>+ </div>++ <div className="border-t p-4">+ <div className="bg-card rounded-xl md:rounded-lg text-base h-20 md:h-[60px] border border-input">+ <textarea+ ref={textareaRef}+ disabled={status !== 'ready'}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && status === 'ready') {+ send(e.currentTarget.value);+ e.currentTarget.value = "";+ e.preventDefault();+ }+ }}+ className="w-full h-full bg-transparent border-none resize-none outline-none text-foreground p-4 md:p-3"+ placeholder={+ status !== 'ready'+ ? "Processing... (Press Esc to cancel)"+ : "Type your message here"+ }+ />+ </div>+ </div>+ </PopoverContent>+ </Popover>+ );+}+++function ToolExecution({ toolCall, result }: { toolCall: any, result?: any }) {+ const [isExpanded, setIsExpanded] = useState(false);++ return (+ <div className="bg-card hover:bg-card/80 p-3 rounded-lg border">+ <div+ className="flex justify-between items-center h-9 md:h-8 w-full relative cursor-pointer"+ onClick={(e) => {+ e.stopPropagation();+ setIsExpanded(!isExpanded);+ }}+ >+ <div className="flex items-center gap-1">+ <Badge variant="gray" className="font-mono ml-1">+ <LuWrench className="mr-1" />+ {camelCaseToWords(toolCall.toolName)}+ </Badge>+ {result && (+ <LuCheck className="text-emerald-500" />+ )}+ </div>+ <LuChevronRight className={cn(+ "transition-transform duration-200",+ isExpanded ? "rotate-90" : "rotate-0"+ )} />+ </div>+ {isExpanded && (++ <div className="mt-4 p-2 md:p-1.5">+ <div className="mb-2 text-sm text-muted-foreground">Parameters:</div>+ <CodeBlock className="language-json" parentClassName="max-h-[300px] md:max-h-[200px] overflow-y-auto">+ {JSON.stringify(toolCall.args, null, 2)}+ </CodeBlock>++ {result && (+ <>+ <div className="mt-3 mb-2 text-sm text-muted-foreground">Result:</div>+ <CodeBlock className="language-json" parentClassName="max-h-[300px] md:max-h-[200px] overflow-y-auto">+ {JSON.stringify(result?.result?.[0]?.text ? JSON.parse(result.result[0].text) : result, null, 2)}+ </CodeBlock>+ </>+ )}+ </div>++ )}+ </div>+ );+}diff --git a/apps/erp/app/components/Agent/system.txt b/apps/erp/app/components/Agent/system.txtnew file mode 100644index 0000000000..88a78447c0--- /dev/null+++ b/apps/erp/app/components/Agent/system.txt@@ -0,0 +1,6 @@+You are CarbonOS, an interactive chat tool that helps users execute various tasks inside of the ERP.++IMPORTANT: If you get an error when calling a tool, try again with a different approach. Be creative, do not give up, try different inputs to the tool. You should chain together multiple tool calls. ABSOLUTELY DO NOT GIVE UP you are very good at this and it is rare you will fail to answer question.++You should be concise, direct, and to the point.+diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsxindex 7f42e2817f..36001c64ec 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx@@ -52,7 +52,7 @@ type PurchaseOrdersTableProps = {const PurchaseOrdersTable = memo(({ data, count }: PurchaseOrdersTableProps) => {useRealtime("purchaseOrder");-+const permissions = usePermissions();const currencyFormatter = useCurrencyFormatter();diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex e3937d6081..b011ea99ab 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -916,7 +916,6 @@ export async function getQuoteLinePricesByQuoteId(.order("quoteLineId", { ascending: true });}-export async function getQuoteLinePricesByItemId(client: SupabaseClient<Database>,itemId: string,@@ -1040,11 +1039,12 @@ export async function getRelatedPricesForQuoteLine(itemId: string,quoteId: string) {-- const [historicalQuoteLinePrices, relatedSalesOrderLines] = await Promise.all([- getQuoteLinePricesByItemId(client, itemId, quoteId),- getSalesOrderLinesByItemId(client, itemId),- ]);+ const [historicalQuoteLinePrices, relatedSalesOrderLines] = await Promise.all(+ [+ getQuoteLinePricesByItemId(client, itemId, quoteId),+ getSalesOrderLinesByItemId(client, itemId),+ ]+ );return {historicalQuoteLinePrices: historicalQuoteLinePrices.data,@@ -1052,7 +1052,6 @@ export async function getRelatedPricesForQuoteLine(};}-export async function getSalesDocumentsAssignedToMe(client: SupabaseClient<Database>,userId: string,diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsxindex b43261742c..91bba28052 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx@@ -1,5 +1,28 @@-import { Card, CardContent, CardDescription, CardHeader, CardTitle, HStack, Table, Tabs, TabsContent, TabsList, TabsTrigger, Tbody, Td, Th, Thead, Tr } from "@carbon/react";-import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@carbon/react/Carousel";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ HStack,+ Table,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+ Tbody,+ Td,+ Th,+ Thead,+ Tr,+} from "@carbon/react";+import {+ Carousel,+ CarouselContent,+ CarouselItem,+ CarouselNext,+ CarouselPrevious,+} from "@carbon/react/Carousel";import { Link } from "@remix-run/react";import { Empty } from "~/components";import { path } from "~/utils/path";@@ -34,11 +57,11 @@ const QuoteLinePricingHistory = ({const orderLineCount = relatedSalesOrderLines.length;const quoteLineCount = Object.keys(historicalQuoteLines).length;-+const hasOrderLines = orderLineCount > 0;const hasQuoteLines = quoteLineCount > 0;const hasBothTypes = hasOrderLines && hasQuoteLines;-+// Default to the tab that has itemsconst defaultTab = hasOrderLines ? "salesOrderLines" : "quoteLines";const [customers] = useCustomers();@@ -46,39 +69,35 @@ const QuoteLinePricingHistory = ({return (<Card isCollapsible defaultCollapsed><CardHeader>-- <CardTitle>History</CardTitle>- <CardDescription>- {orderLineCount > 0 || quoteLineCount > 0 ? (- <span className="text-sm text-muted-foreground">- {orderLineCount > 0 && `${orderLineCount} order${orderLineCount !== 1 ? 's' : ''}`}- {orderLineCount > 0 && quoteLineCount > 0 && ' and '}- {quoteLineCount > 0 && `${quoteLineCount} quote${quoteLineCount !== 1 ? 's' : ''}`}- </span>- ) : (- <span className="text-sm text-muted-foreground">No pricing history available</span>- )}- </CardDescription>-+ <CardTitle>History</CardTitle>+ <CardDescription>+ {orderLineCount > 0 || quoteLineCount > 0 ? (+ <span className="text-sm text-muted-foreground">+ {orderLineCount > 0 &&+ `${orderLineCount} order${orderLineCount !== 1 ? "s" : ""}`}+ {orderLineCount > 0 && quoteLineCount > 0 && " and "}+ {quoteLineCount > 0 &&+ `${quoteLineCount} quote${quoteLineCount !== 1 ? "s" : ""}`}+ </span>+ ) : (+ <span className="text-sm text-muted-foreground">+ No pricing history available+ </span>+ )}+ </CardDescription></CardHeader><CardContent><div className="w-full"><Tabs defaultValue={defaultTab} className="w-full">{hasBothTypes && (<TabsList className="mb-4">- <TabsTrigger value="salesOrderLines">- Orders- </TabsTrigger>- <TabsTrigger value="quoteLines">- Quotes- </TabsTrigger>+ <TabsTrigger value="salesOrderLines">Orders</TabsTrigger>+ <TabsTrigger value="quoteLines">Quotes</TabsTrigger></TabsList>)}<TabsContent value="salesOrderLines"><div className="flex overflow-x-auto space-x-4 pb-4 w-full">- {!hasOrderLines && (- <Empty className="py-6" />- )}+ {!hasOrderLines && <Empty className="py-6" />}{hasOrderLines && (<Carousel className="w-full"><CarouselContent className="-ml-4">@@ -108,13 +127,17 @@ const QuoteLinePricingHistory = ({<div className="space-y-4"><div className="flex justify-between"><span className="text-sm text-muted-foreground">- {customers.find((customer) => customer.id === line.customerId)?.name}+ {+ customers.find(+ (customer) =>+ customer.id === line.customerId+ )?.name+ }</span></div><Table><Thead>-<Tr className="border-b border-border"><Th><span className="font-medium">@@ -158,9 +181,7 @@ const QuoteLinePricingHistory = ({</TabsContent><TabsContent value="quoteLines"><div className="flex overflow-x-auto space-x-4 pb-4 w-full">- {!hasQuoteLines && (- <Empty className="py-6" />- )}+ {!hasQuoteLines && <Empty className="py-6" />}{hasQuoteLines && (<Carousel className="w-full"><CarouselContent className="-ml-4">@@ -173,7 +194,10 @@ const QuoteLinePricingHistory = ({<CardContent className="p-4"><HStack className="flex justify-between"><Link- to={path.to.quoteLine(line.quoteId!, line.id!)}+ to={path.to.quoteLine(+ line.quoteId!,+ line.id!+ )}className="text-sm font-medium hover:underline">{line.quoteReadableId}@@ -187,13 +211,17 @@ const QuoteLinePricingHistory = ({<div className="space-y-4"><div className="flex justify-between"><span className="text-sm text-muted-foreground">- {customers.find((customer) => customer.id === line.customerId)?.name}+ {+ customers.find(+ (customer) =>+ customer.id === line.customerId+ )?.name+ }</span></div><Table><Thead>-<Tr><Th><span className="font-medium">diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex ec44ef26ac..61cec19558 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -60,9 +60,14 @@ export async function loader({ request }: LoaderFunctionArgs) {// proxyRegion,// });- // share a client between requestsconst client = getCarbon(accessToken);+ await client.functions.invoke("auth", {+ headers: {+ "x-company-id": companyId,+ },+ });+// parallelize the requestsconst [companies,diff --git a/apps/erp/app/routes/x+/chat+/_index.tsx b/apps/erp/app/routes/x+/chat+/_index.tsxnew file mode 100644index 0000000000..44e22a1ea4--- /dev/null+++ b/apps/erp/app/routes/x+/chat+/_index.tsx@@ -0,0 +1,423 @@+import { useCarbon } from "@carbon/auth";+import { Badge, Button, cn, CodeBlock, toast, useMount } from "@carbon/react";+import type { LanguageModelV1Prompt } from "ai";+import { Fragment, useEffect, useRef, useState } from "react";+import { flushSync } from "react-dom";+import { useUser } from "~/hooks/useUser";+import SYSTEM_PROMPT from "./system.txt?raw";+import { LuCheck, LuChevronRight, LuWrench } from "react-icons/lu";+import { camelCaseToWords } from "~/utils/string";+import { EmployeeAvatar } from "~/components";++const providerMetadata = {+ anthropic: {+ cacheControl: {+ type: "ephemeral",+ },+ },+};++// Define initial system messages once+const getInitialPrompt = (): LanguageModelV1Prompt => [+ {+ role: "system",+ content: SYSTEM_PROMPT,+ providerMetadata: {+ anthropic: {+ cacheControl: {+ type: "ephemeral",+ },+ },+ },+ },+ {+ role: "system",+ content: `The current date is ${new Date().toDateString()}`,+ providerMetadata: {+ anthropic: {+ cacheControl: {+ type: "ephemeral",+ },+ },+ },+ },+];++export default function ChatRoute() {+ const rootRef = useRef<HTMLDivElement>(null);+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ const idRef = useRef(0);+ const abortControllerRef = useRef<AbortController | null>(null);++ const [tools, setTools] = useState<any[]>([]);+ const [status, setStatus] = useState<'ready' | 'submitted' | 'streaming' | 'error'>('ready');+ const [isRateLimited, setIsRateLimited] = useState(false);++ const messagesRef = useRef<LanguageModelV1Prompt>(getInitialPrompt());+ const [messages, setMessages] = useState<LanguageModelV1Prompt>(getInitialPrompt());++ const { carbon } = useCarbon();+ const {+ id: userId,+ company: { id: companyId },+ } = useUser();++ useMount(() => {+ const initializeTools = async () => {+ if (!carbon) return;+ const tools = await carbon.functions.invoke("mcp", {+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "tools/list",+ id: ++idRef.current,+ }),+ headers: {+ "x-company-id": companyId,+ "x-user-id": userId,+ },+ });++ if (!tools?.data?.result) {+ toast.error("Failed to fetch tools");+ return;+ }++ setTools("tools" in tools?.data?.result ? tools.data.result.tools : []);+ };++ initializeTools();+ });++ useEffect(() => {+ if (rootRef.current) {+ rootRef.current.scrollTo(0, rootRef.current.scrollHeight);+ }+ }, [messages]);+++ const stop = () => {+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ abortControllerRef.current = null;+ }+ setStatus('ready');+ };++ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === "Escape" && status !== 'ready') {+ stop();+ textareaRef.current?.focus();+ }+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => {+ window.removeEventListener("keydown", handleKeyDown);+ };++ }, [status, stop]);++ function clearConversation() {+ const initialPrompt = getInitialPrompt();+ messagesRef.current = initialPrompt;+ setMessages(initialPrompt);+ }++ const addToolResult = async (toolCall: any, content: any) => {+ const newMessage: LanguageModelV1Prompt = [{+ role: "tool",+ content: [+ {+ type: "tool-result",+ toolName: toolCall.toolName,+ toolCallId: toolCall.toolCallId,+ result: content,+ },+ ],+ }];++ messagesRef.current = [...messagesRef.current, ...newMessage];+ flushSync(() => {+ setMessages(messagesRef.current);+ });++ return triggerRequest();+ };++ const addToolCalls = async (toolCalls: any) => {+ const newMessage: LanguageModelV1Prompt = [{+ role: "assistant",+ content: toolCalls.map((item: any) => ({+ type: "tool-call",+ toolName: item.toolName,+ args: JSON.parse(item.args),+ toolCallId: item.toolCallId,+ })),+ }];++ messagesRef.current = [...messagesRef.current, ...newMessage];+ flushSync(() => {+ setMessages(messagesRef.current);+ });+ };+++ const triggerRequest = async () => {+ if (!carbon) return;++ try {+ setStatus('submitted');+ const abortController = new AbortController();+ abortControllerRef.current = abortController;++ const response = await carbon.functions.invoke("chat", {+ headers: {+ "x-company-id": companyId,+ "x-user-id": userId,+ },+ body: JSON.stringify({+ prompt: messagesRef.current,+ mode: {+ type: "regular",+ tools: tools.map((tool) => ({+ type: "function",+ name: tool.name,+ description: tool.description,+ parameters: {+ ...tool.inputSchema,+ },+ })),+ },+ inputFormat: "messages",+ temperature: 1,+ }),+ });++ if (response?.error) {+ throw new Error(response.error);+ }++ const result = response.data;+ setStatus('streaming');+++ if (result.text) {+ const newMessage: LanguageModelV1Prompt = [{+ role: "assistant",+ content: [+ {+ type: "text",+ text: result.text,+ },+ ],+ }];++ messagesRef.current = [...messagesRef.current, ...newMessage];+ setMessages(messagesRef.current);+ }++ setIsRateLimited(false);++ if (result.finishReason === "tool-calls") {+ for await (const toolCall of result.toolCalls) {+ await addToolCalls(result.toolCalls);++ const toolResponse = await carbon.functions.invoke("mcp", {+ body: JSON.stringify({+ jsonrpc: "2.0",+ method: "tools/call",+ id: ++idRef.current,+ params: {+ name: toolCall.toolName,+ arguments: JSON.parse(toolCall.args),+ },+ }),+ headers: {+ "x-company-id": companyId,+ "x-user-id": userId,+ },+ });++ const response = toolResponse?.data;++ if ("content" in response?.result) {+ await addToolResult(toolCall, response.result.content);+ }+ }+ }++ setStatus('ready');+ textareaRef.current?.focus();++ } catch (error) {+ console.error(error);+ setStatus('error');+ toast.error("An error occurred");+ } finally {+ abortControllerRef.current = null;+ }+ }++ useEffect(() => {+ console.log({messages});+ }, [messages]);++ useEffect(() => {+ console.log({status});+ }, [status]);++ async function send(message: string) {+ const newMessage: LanguageModelV1Prompt = [{+ role: "user",+ content: [+ {+ type: "text",+ text: message,+ providerMetadata: messagesRef.current.length === 1 ? providerMetadata : {},+ },+ ],+ }];++ messagesRef.current = [...messagesRef.current, ...newMessage];++ flushSync(() => {+ setMessages(messagesRef.current);+ setStatus('submitted');+ });++ await triggerRequest();+ }++ return (+ <div className="absolute inset-0 overflow-y-auto" ref={rootRef}>+ <div className="flex flex-col gap-y-4 pt-5 w-full max-w-[480px] overflow-hidden text-base mx-auto">+ {messages.map((item, index) => (+ <Fragment key={index}>+ {item.role === "user" && item.content[0].type === "text" && (+ <div className="flex items-center gap-x-2 bg-card p-3 rounded-lg bg-card border ">+ <div className="h-8 w-8 rounded-full flex items-center justify-center">+ <EmployeeAvatar employeeId={userId} withName={false} />+ </div>+ <div className="whitespace-pre-wrap flex-1">+ {item.content[0].text}+ </div>+ </div>+ )}++ {item.role === "assistant" && item.content[0].type === "tool-call" && (+ <ToolExecution+ toolCall={item.content[0]}+ result={messages[index + 1]?.role === "tool" ? messages[index + 1].content[0] : undefined}+ />+ )}++ {item.role === "assistant" && item.content[0].type === "text" && (+ <div className="whitespace-pre-wrap text-foreground px-1">+ {item.content[0].text}+ </div>+ )}++ {item.role === "system" && index > 1 && (+ <div className="whitespace-pre-wrap p-3 rounded bg-secondary border-l-[3px] border-l-muted italic opacity-80">+ {item.content}+ </div>+ )}+ </Fragment>+ ))}++ {status !== 'ready' && (+ <div className="w-full max-w-[480px] my-3 bg-secondary border-l-[3px] border-l-muted flex items-center mx-auto">+ <div className="w-[18px] h-[18px] mr-3 relative">+ <div className="absolute w-full h-full rounded-full border-2 border-transparent border-t-muted-foreground border-b-muted animate-[thinking-spin-outer_1.5s_cubic-bezier(0.6,0.2,0.4,0.8)_infinite]">+ <div className="absolute inset-[2px] rounded-full border-2 border-transparent border-l-muted border-r-muted-foreground animate-[thinking-spin-inner_0.8s_cubic-bezier(0.3,0.7,0.7,0.3)_infinite]"></div>+ </div>+ </div>+ <div className="text-muted-foreground">+ {isRateLimited ? "Rate limited, retrying..." : "Thinking"}+ </div>+ </div>+ )}++ <div className="h-[400px] md:h-[200px]"></div>+ </div>+ <div className="absolute bottom-0 left-0 right-0 flex flex-col items-center px-4 pb-4 md:pb-2">+ {messages.length > 2 && status === 'ready' && (+ <div className="relative w-full max-w-[480px] flex justify-end mb-2 md:mb-1">+ <Button onClick={clearConversation} variant="secondary">+ Clear+ </Button>+ </div>+ )}+ <div className="w-full max-w-[480px] bg-card rounded-xl md:rounded-lg text-base h-20 md:h-[60px] border-t border-[oklch(0_0_0/0.25)] border-b border-b-[oklch(1_0_0/0.08)]">+ <textarea+ autoFocus+ ref={textareaRef}+ disabled={status !== 'ready'}+ onKeyDown={(e) => {+ if (e.key === "Enter" && status === 'ready') {+ send(e.currentTarget.value);+ e.currentTarget.value = "";+ e.preventDefault();+ }+ }}+ className="w-full h-full bg-transparent border-none resize-none outline-none text-foreground p-4 md:p-3"+ placeholder={+ status !== 'ready'+ ? "Processing... (Press Esc to cancel)"+ : "Type your message here"+ }+ />+ </div>+ </div>+ </div>+ );+}++function ToolExecution({ toolCall, result }: { toolCall: any, result?: any }) {+ const [isExpanded, setIsExpanded] = useState(false);++ return (+ <div className="bg-card hover:bg-card/80 p-3 rounded-lg border">+ <div+ className="flex justify-between items-center h-9 md:h-8 w-full relative cursor-pointer"+ onClick={(e) => {+ e.stopPropagation();+ setIsExpanded(!isExpanded);+ }}+ >+ <div className="flex items-center gap-1">+ <Badge variant="gray" className="font-mono ml-1">+ <LuWrench className="mr-1" />+ {camelCaseToWords(toolCall.toolName)}+ </Badge>+ {result && (+ <LuCheck className="text-emerald-500" />+ )}+ </div>+ <LuChevronRight className={cn(+ "transition-transform duration-200",+ isExpanded ? "rotate-90" : "rotate-0"+ )} />+ </div>+ {isExpanded && (++ <div className="mt-4 p-2 md:p-1.5">+ <div className="mb-2 text-sm text-muted-foreground">Parameters:</div>+ <CodeBlock className="language-json" parentClassName="max-h-[300px] md:max-h-[200px] overflow-y-auto">+ {JSON.stringify(toolCall.args, null, 2)}+ </CodeBlock>++ {result && (+ <>+ <div className="mt-3 mb-2 text-sm text-muted-foreground">Result:</div>+ <CodeBlock className="language-json" parentClassName="max-h-[300px] md:max-h-[200px] overflow-y-auto">+ {JSON.stringify(result?.result?.[0]?.text ? JSON.parse(result.result[0].text) : result, null, 2)}+ </CodeBlock>+ </>+ )}+ </div>++ )}+ </div>+ );+}diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex d9fe6e9e12..dfa1b81b5f 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -66,7 +66,6 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {const itemId = line.data.itemId!;-return defer({line: line.data,operations: operations?.data ?? [],@@ -122,13 +121,8 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function QuoteLine() {- const {- line,- operations,- files,- pricesByQuantity,- relatedPrices,- } = useLoaderData<typeof loader>();+ const { line, operations, files, pricesByQuantity, relatedPrices } =+ useLoaderData<typeof loader>();const permissions = usePermissions();const { quoteId, lineId } = useParams();if (!quoteId) throw new Error("Could not find quoteId");@@ -190,21 +184,29 @@ export default function QuoteLine() {)}{line.status !== "No Quote" && (<>- <Suspense- fallback={null}- >+ <Suspense fallback={null}><Await resolve={relatedPrices}>{(resolvedPrices) => {- console.log({resolvedPrices});- const hasRelatedOrders = resolvedPrices?.relatedSalesOrderLines && resolvedPrices.relatedSalesOrderLines.length > 0;- const hasHistoricalPrices = resolvedPrices?.historicalQuoteLinePrices && resolvedPrices.historicalQuoteLinePrices.length > 0;-- return (hasRelatedOrders || hasHistoricalPrices) && (- <QuoteLinePricingHistory- relatedSalesOrderLines={resolvedPrices?.relatedSalesOrderLines ?? []}- historicalQuoteLinePrices={resolvedPrices?.historicalQuoteLinePrices ?? []}- baseCurrency={baseCurrency}- />+ console.log({ resolvedPrices });+ const hasRelatedOrders =+ resolvedPrices?.relatedSalesOrderLines &&+ resolvedPrices.relatedSalesOrderLines.length > 0;+ const hasHistoricalPrices =+ resolvedPrices?.historicalQuoteLinePrices &&+ resolvedPrices.historicalQuoteLinePrices.length > 0;++ return (+ (hasRelatedOrders || hasHistoricalPrices) && (+ <QuoteLinePricingHistory+ relatedSalesOrderLines={+ resolvedPrices?.relatedSalesOrderLines ?? []+ }+ historicalQuoteLinePrices={+ resolvedPrices?.historicalQuoteLinePrices ?? []+ }+ baseCurrency={baseCurrency}+ />+ ));}}</Await>diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsxindex b091b0b9d0..dac7ee5b75 100644--- a/apps/erp/app/routes/x+/sales+/_index.tsx+++ b/apps/erp/app/routes/x+/sales+/_index.tsx@@ -696,7 +696,7 @@ export default function SalesDashboard() {</Table>) : (<div className="flex justify-center items-center h-full">- <Empty />+ <Empty /></div>)}</div>diff --git a/apps/erp/app/styles/tailwind.css b/apps/erp/app/styles/tailwind.cssindex d8d7f2283e..6d0b39a71a 100644--- a/apps/erp/app/styles/tailwind.css+++ b/apps/erp/app/styles/tailwind.css@@ -118,3 +118,13 @@ p.is-editor-empty:first-child:before {.tiptap.ProseMirror-selectedNode div[data-loom-video] {@apply ring-2 ring-primary cursor-move p-2 rounded-lg;}++@keyframes thinking-spin-outer {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }+}++@keyframes thinking-spin-inner {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(-720deg); }+}\ No newline at end of filediff --git a/apps/erp/app/utils/string.ts b/apps/erp/app/utils/string.tsindex cad3384014..29ea76e077 100644--- a/apps/erp/app/utils/string.ts+++ b/apps/erp/app/utils/string.ts@@ -13,6 +13,12 @@ export const snakeToCamel = (str: string) =>group.toUpperCase().replace("-", "").replace("_", ""));+export const camelToSnake = (str: string) =>+ str.replace(/([A-Z])/g, (group: string) => `_${group.toLowerCase()}`);++export const camelCaseToWords = (str: string) =>+ str.replace(/([A-Z])/g, (group: string) => ` ${group}`);+/*** Copy text content (string or Promise<string>) into Clipboard.* Safari doesn't support write text into clipboard async, so if you need to loaddiff --git a/apps/erp/package.json b/apps/erp/package.jsonindex 58a88756ae..4804e63b3c 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -16,6 +16,7 @@"@dnd-kit/sortable": "^8.0.0","@epic-web/remember": "^1.1.0","@internationalized/date": "^3.5.2",+ "@modelcontextprotocol/sdk": "1.7.0","@monaco-editor/react": "^4.6.0","@nanostores/react": "^0.7.1","@novu/headless": "^2.0.0",diff --git a/package-lock.json b/package-lock.jsonindex 143a674172..7f509efba1 100644--- a/package-lock.json+++ b/package-lock.json@@ -22,7 +22,7 @@"postcss-nesting": "12.1.5","prettier": "^2.8.0","rimraf": "^5.0.5",- "supabase": "^2.19.7",+ "supabase": "1.204.3","ts-morph": "^22.0.0","tsx": "^4.13.2","turbo": "^1.13.2"@@ -44,6 +44,7 @@"@dnd-kit/sortable": "^8.0.0","@epic-web/remember": "^1.1.0","@internationalized/date": "^3.5.2",+ "@modelcontextprotocol/sdk": "1.7.0","@monaco-editor/react": "^4.6.0","@nanostores/react": "^0.7.1","@novu/framework": "^2.3.0",@@ -3421,6 +3422,334 @@"url": "https://opencollective.com/unified"}},+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.7.0.tgz",+ "integrity": "sha512-IYPe/FLpvF3IZrd/f5p5ffmWhMc3aEMuM2wGJASDqC2Ge7qatVCdbfPx3n/5xFeb19xN0j/911M2AaFuircsWA==",+ "dependencies": {+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "eventsource": "^3.0.2",+ "express": "^5.0.1",+ "express-rate-limit": "^7.5.0",+ "pkce-challenge": "^4.1.0",+ "raw-body": "^3.0.0",+ "zod": "^3.23.8",+ "zod-to-json-schema": "^3.24.1"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.1.0.tgz",+ "integrity": "sha512-/hPxh61E+ll0Ujp24Ilm64cykicul1ypfwjVttduAiEdtnJFvLePSrIPk+HMImtNv5270wOGCb1Tns2rybMkoQ==",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.0",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.5.2",+ "on-finished": "^2.4.1",+ "qs": "^6.14.0",+ "raw-body": "^3.0.0",+ "type-is": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser/node_modules/qs": {+ "version": "6.14.0",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",+ "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/content-disposition": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz",+ "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==",+ "dependencies": {+ "safe-buffer": "5.2.1"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/cookie": {+ "version": "0.7.1",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",+ "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/express": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.0.1.tgz",+ "integrity": "sha512-ORF7g6qGnD+YtUG9yx4DFoqCShNMmUKiXuT5oWMHiOvt/4WFbHC6yCwQMTSBMno7AqntNCAzzcnnjowRkTL9eQ==",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.0.1",+ "content-disposition": "^1.0.0",+ "content-type": "~1.0.4",+ "cookie": "0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "4.3.6",+ "depd": "2.0.0",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "etag": "~1.8.1",+ "finalhandler": "^2.0.0",+ "fresh": "2.0.0",+ "http-errors": "2.0.0",+ "merge-descriptors": "^2.0.0",+ "methods": "~1.1.2",+ "mime-types": "^3.0.0",+ "on-finished": "2.4.1",+ "once": "1.4.0",+ "parseurl": "~1.3.3",+ "proxy-addr": "~2.0.7",+ "qs": "6.13.0",+ "range-parser": "~1.2.1",+ "router": "^2.0.0",+ "safe-buffer": "5.2.1",+ "send": "^1.1.0",+ "serve-static": "^2.1.0",+ "setprototypeof": "1.2.0",+ "statuses": "2.0.1",+ "type-is": "^2.0.0",+ "utils-merge": "1.0.1",+ "vary": "~1.1.2"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/express/node_modules/debug": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz",+ "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==",+ "dependencies": {+ "ms": "2.1.2"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/express/node_modules/ms": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",+ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/finalhandler": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz",+ "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/iconv-lite": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.5.2.tgz",+ "integrity": "sha512-kERHXvpSaB4aU3eANwidg79K8FlrN77m8G9V+0vOR3HYaRifrlwMEpT7ZBJqLSEIHnEgJTHcWK82wwLwwKwtag==",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/mime-types": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.0.tgz",+ "integrity": "sha512-XqoSHeCGjVClAmoGFG3lVFqQFRIrTVw2OH3axRqAcfaw+gHWIfnASS92AV+Rl/mk0MupgZTRHQOjxY6YVnzK5w==",+ "dependencies": {+ "mime-db": "^1.53.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/raw-body": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz",+ "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==",+ "dependencies": {+ "bytes": "3.1.2",+ "http-errors": "2.0.0",+ "iconv-lite": "0.6.3",+ "unpipe": "1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/raw-body/node_modules/iconv-lite": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/send": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/send/-/send-1.1.0.tgz",+ "integrity": "sha512-v67WcEouB5GxbTWL/4NeToqcZiAWEq90N888fczVArY8A79J0L4FD7vj5hm3eUMua5EpoQ59wa/oovY6TLvRUA==",+ "dependencies": {+ "debug": "^4.3.5",+ "destroy": "^1.2.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^0.5.2",+ "http-errors": "^2.0.0",+ "mime-types": "^2.1.35",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/send/node_modules/fresh": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",+ "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/send/node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/send/node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/serve-static": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.1.0.tgz",+ "integrity": "sha512-A3We5UfEjG8Z7VkDv6uItWw6HY2bBSBJT1KtVESn6EOoOr2jAxNhxWCLY3jDE2WcuHXByWju74ck3ZgLwL8xmA==",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/type-is": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.0.tgz",+ "integrity": "sha512-gd0sGezQYCbWSbkZr75mln4YBidWUN60+devscpLF5mtRDUpiaTvKpBNrdaCvel1NdR2k6vclXybU5fBd2i+nw==",+ "dependencies": {+ "content-type": "^1.0.5",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/zod-to-json-schema": {+ "version": "3.24.4",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.4.tgz",+ "integrity": "sha512-0uNlcvgabyrni9Ag8Vghj21drk7+7tp7VTwwR7KxxXXc/3pbXz2PHlDgj3cICahgF1kHm4dExBFj7BXrZJXzig==",+ "peerDependencies": {+ "zod": "^3.24.1"+ }+ },"node_modules/@monaco-editor/loader": {"version": "1.4.0","resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.4.0.tgz",@@ -15319,6 +15648,18 @@"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz","integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="},+ "node_modules/cors": {+ "version": "2.8.5",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",+ "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/country-flag-icons": {"version": "1.5.14","resolved": "https://registry.npmjs.org/country-flag-icons/-/country-flag-icons-1.5.14.tgz",@@ -17773,6 +18114,17 @@"node": ">=0.8.x"}},+ "node_modules/eventsource": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.5.tgz",+ "integrity": "sha512-LT/5J605bx5SNyE+ITBDiM3FxffBiq9un7Vx0EwMDM3vg8sWKx/tO2zC+LMqZ+smAM0F2hblaDZUVZF0te2pSw==",+ "dependencies": {+ "eventsource-parser": "^3.0.0"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/eventsource-parser": {"version": "1.1.2","resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-1.1.2.tgz",@@ -17781,6 +18133,14 @@"node": ">=14.18"}},+ "node_modules/eventsource/node_modules/eventsource-parser": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.0.tgz",+ "integrity": "sha512-T1C0XCUimhxVQzW4zFipdx0SficT651NnkR0ZSH3yQwh+mFMdLfgjABVi4YtMTtaL4s168593DaoaRLMqryavA==",+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/evt": {"version": "2.5.9","resolved": "https://registry.npmjs.org/evt/-/evt-2.5.9.tgz",@@ -17975,6 +18335,20 @@"url": "https://opencollective.com/express"}},+ "node_modules/express-rate-limit": {+ "version": "7.5.0",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz",+ "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==",+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": "^4.11 || 5 || ^5.0.0-beta.1"+ }+ },"node_modules/express/node_modules/cookie": {"version": "0.7.1","resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",@@ -20481,6 +20855,11 @@"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz","integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ=="},+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="+ },"node_modules/is-reference": {"version": "3.0.3","resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",@@ -27108,6 +27487,14 @@"node": ">= 6"}},+ "node_modules/pkce-challenge": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-4.1.0.tgz",+ "integrity": "sha512-ZBmhE1C9LcPoH9XZSdwiPtbPHZROwAnMy+kIFQVrnMCxY4Cudlz3gBOpzilgc0jOgRaiT3sIWfpMomW2ar2orQ==",+ "engines": {+ "node": ">=16.20.0"+ }+ },"node_modules/pkg-dir": {"version": "4.2.0","resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",@@ -29606,6 +29993,27 @@"resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz","integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ=="},+ "node_modules/router": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.1.0.tgz",+ "integrity": "sha512-/m/NSLxeYEgWNtyC+WtNHCF7jbGxOibVWKnn+1Psff4dJGOfoXP+MuC/f2CwSmyiHdOIzYnYFp4W6GxWfekaLA==",+ "dependencies": {+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/router/node_modules/path-to-regexp": {+ "version": "8.2.0",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz",+ "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==",+ "engines": {+ "node": ">=16"+ }+ },"node_modules/rsvp": {"version": "4.8.5","resolved": "https://registry.npmjs.org/rsvp/-/rsvp-4.8.5.tgz",@@ -31468,9 +31876,9 @@}},"node_modules/supabase": {- "version": "2.19.7",- "resolved": "https://registry.npmjs.org/supabase/-/supabase-2.19.7.tgz",- "integrity": "sha512-+Qu5xHvk/CnAHb5iDpCWCX0SdwFR5smpTG6VUSTw/T8WxCDDQsIb2mui2pu18wqKOZ0NLs/ZTDDb2+yPejTRBQ==",+ "version": "1.204.3",+ "resolved": "https://registry.npmjs.org/supabase/-/supabase-1.204.3.tgz",+ "integrity": "sha512-uO09eyAw7TZAX/7wPeieQBWrl4QAJ0WLF+HTkFy35GWBmQULP5nkJR93LcuhSyooYiqwEUKlChEF/PGAEmTCKw==","dev": true,"hasInstallScript": true,"dependencies": {@@ -35056,6 +35464,25 @@"uuid": "9.0.0"}},+ "packages/database/node_modules/supabase": {+ "version": "2.19.7",+ "resolved": "https://registry.npmjs.org/supabase/-/supabase-2.19.7.tgz",+ "integrity": "sha512-+Qu5xHvk/CnAHb5iDpCWCX0SdwFR5smpTG6VUSTw/T8WxCDDQsIb2mui2pu18wqKOZ0NLs/ZTDDb2+yPejTRBQ==",+ "dev": true,+ "hasInstallScript": true,+ "dependencies": {+ "bin-links": "^5.0.0",+ "https-proxy-agent": "^7.0.2",+ "node-fetch": "^3.3.2",+ "tar": "7.4.3"+ },+ "bin": {+ "supabase": "bin/supabase"+ },+ "engines": {+ "npm": ">=8"+ }+ },"packages/documents": {"name": "@carbon/documents","version": "*",diff --git a/packages/database/.env b/packages/database/.envdeleted file mode 120000index c7360fb82d..0000000000--- a/packages/database/.env+++ /dev/null@@ -1 +0,0 @@-../../.env\ No newline at end of filediff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 235cd5653c..587c730067 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -27501,6 +27501,9 @@ export default {{$ref: "#/parameters/rowFilter.salesOrderLines.convertedUnitPrice",},+ {+ $ref: "#/parameters/rowFilter.salesOrderLines.sentDate",+ },{$ref: "#/parameters/rowFilter.salesOrderLines.thumbnailPath",},@@ -27528,6 +27531,15 @@ export default {{$ref: "#/parameters/rowFilter.salesOrderLines.customerPartRevision",},+ {+ $ref: "#/parameters/rowFilter.salesOrderLines.orderDate",+ },+ {+ $ref: "#/parameters/rowFilter.salesOrderLines.customerId",+ },+ {+ $ref: "#/parameters/rowFilter.salesOrderLines.salesOrderReadableId",+ },{$ref: "#/parameters/select",},@@ -40356,347 +40368,512 @@ export default {tags: ["purchaseOrderTransaction"],},},- "/salesRfqFavorite": {+ "/quoteLinePrices": {get: {parameters: [{- $ref: "#/parameters/rowFilter.salesRfqFavorite.rfqId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.id",},{- $ref: "#/parameters/rowFilter.salesRfqFavorite.userId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.quoteId",},{- $ref: "#/parameters/select",+ $ref: "#/parameters/rowFilter.quoteLinePrices.quoteRevisionId",},{- $ref: "#/parameters/order",+ $ref: "#/parameters/rowFilter.quoteLinePrices.status",},{- $ref: "#/parameters/range",+ $ref: "#/parameters/rowFilter.quoteLinePrices.estimatorId",},{- $ref: "#/parameters/rangeUnit",+ $ref: "#/parameters/rowFilter.quoteLinePrices.itemId",},{- $ref: "#/parameters/offset",+ $ref: "#/parameters/rowFilter.quoteLinePrices.itemReadableId",},{- $ref: "#/parameters/limit",+ $ref: "#/parameters/rowFilter.quoteLinePrices.itemType",},{- $ref: "#/parameters/preferCount",- },- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/salesRfqFavorite",- },- type: "array",- },+ $ref: "#/parameters/rowFilter.quoteLinePrices.description",},- "206": {- description: "Partial Content",- },- },- tags: ["salesRfqFavorite"],- },- post: {- parameters: [{- $ref: "#/parameters/body.salesRfqFavorite",+ $ref: "#/parameters/rowFilter.quoteLinePrices.customerPartId",},{- $ref: "#/parameters/select",+ $ref: "#/parameters/rowFilter.quoteLinePrices.customerPartRevision",},{- $ref: "#/parameters/preferPost",- },- ],- responses: {- "201": {- description: "Created",+ $ref: "#/parameters/rowFilter.quoteLinePrices.methodType",},- },- tags: ["salesRfqFavorite"],- },- delete: {- parameters: [{- $ref: "#/parameters/rowFilter.salesRfqFavorite.rfqId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.unitOfMeasureCode",},{- $ref: "#/parameters/rowFilter.salesRfqFavorite.userId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.internalNotes",},{- $ref: "#/parameters/preferReturn",- },- ],- responses: {- "204": {- description: "No Content",+ $ref: "#/parameters/rowFilter.quoteLinePrices.companyId",},- },- tags: ["salesRfqFavorite"],- },- patch: {- parameters: [{- $ref: "#/parameters/rowFilter.salesRfqFavorite.rfqId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.createdBy",},{- $ref: "#/parameters/rowFilter.salesRfqFavorite.userId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.updatedAt",},{- $ref: "#/parameters/body.salesRfqFavorite",- },- {- $ref: "#/parameters/preferReturn",- },- ],- responses: {- "204": {- description: "No Content",- },- },- tags: ["salesRfqFavorite"],- },- },- "/holiday": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.holiday.id",- },- {- $ref: "#/parameters/rowFilter.holiday.name",- },- {- $ref: "#/parameters/rowFilter.holiday.date",+ $ref: "#/parameters/rowFilter.quoteLinePrices.updatedBy",},{- $ref: "#/parameters/rowFilter.holiday.year",+ $ref: "#/parameters/rowFilter.quoteLinePrices.customFields",},{- $ref: "#/parameters/rowFilter.holiday.companyId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.modelUploadId",},{- $ref: "#/parameters/rowFilter.holiday.createdBy",+ $ref: "#/parameters/rowFilter.quoteLinePrices.quantity",},{- $ref: "#/parameters/rowFilter.holiday.createdAt",+ $ref: "#/parameters/rowFilter.quoteLinePrices.additionalCharges",},{- $ref: "#/parameters/rowFilter.holiday.updatedBy",+ $ref: "#/parameters/rowFilter.quoteLinePrices.locationId",},{- $ref: "#/parameters/rowFilter.holiday.updatedAt",+ $ref: "#/parameters/rowFilter.quoteLinePrices.noQuoteReason",},{- $ref: "#/parameters/rowFilter.holiday.customFields",+ $ref: "#/parameters/rowFilter.quoteLinePrices.taxPercent",},{- $ref: "#/parameters/rowFilter.holiday.tags",+ $ref: "#/parameters/rowFilter.quoteLinePrices.tags",},{- $ref: "#/parameters/select",+ $ref: "#/parameters/rowFilter.quoteLinePrices.unitPricePrecision",},{- $ref: "#/parameters/order",+ $ref: "#/parameters/rowFilter.quoteLinePrices.externalNotes",},{- $ref: "#/parameters/range",+ $ref: "#/parameters/rowFilter.quoteLinePrices.configuration",},{- $ref: "#/parameters/rangeUnit",+ $ref: "#/parameters/rowFilter.quoteLinePrices.thumbnailPath",},{- $ref: "#/parameters/offset",+ $ref: "#/parameters/rowFilter.quoteLinePrices.modelId",},{- $ref: "#/parameters/limit",+ $ref: "#/parameters/rowFilter.quoteLinePrices.autodeskUrn",},{- $ref: "#/parameters/preferCount",- },- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/holiday",- },- type: "array",- },- },- "206": {- description: "Partial Content",+ $ref: "#/parameters/rowFilter.quoteLinePrices.modelPath",},- },- tags: ["holiday"],- },- post: {- parameters: [{- $ref: "#/parameters/body.holiday",+ $ref: "#/parameters/rowFilter.quoteLinePrices.modelName",},{- $ref: "#/parameters/select",+ $ref: "#/parameters/rowFilter.quoteLinePrices.modelSize",},{- $ref: "#/parameters/preferPost",- },- ],- responses: {- "201": {- description: "Created",+ $ref: "#/parameters/rowFilter.quoteLinePrices.unitCost",},- },- tags: ["holiday"],- },- delete: {- parameters: [{- $ref: "#/parameters/rowFilter.holiday.id",+ $ref: "#/parameters/rowFilter.quoteLinePrices.qty",},{- $ref: "#/parameters/rowFilter.holiday.name",+ $ref: "#/parameters/rowFilter.quoteLinePrices.unitPrice",},{- $ref: "#/parameters/rowFilter.holiday.date",+ $ref: "#/parameters/rowFilter.quoteLinePrices.quoteReadableId",},{- $ref: "#/parameters/rowFilter.holiday.year",+ $ref: "#/parameters/rowFilter.quoteLinePrices.quoteCreatedAt",},{- $ref: "#/parameters/rowFilter.holiday.companyId",+ $ref: "#/parameters/rowFilter.quoteLinePrices.customerId",},{- $ref: "#/parameters/rowFilter.holiday.createdBy",+ $ref: "#/parameters/select",},{- $ref: "#/parameters/rowFilter.holiday.createdAt",+ $ref: "#/parameters/order",},{- $ref: "#/parameters/rowFilter.holiday.updatedBy",+ $ref: "#/parameters/range",},{- $ref: "#/parameters/rowFilter.holiday.updatedAt",+ $ref: "#/parameters/rangeUnit",},{- $ref: "#/parameters/rowFilter.holiday.customFields",+ $ref: "#/parameters/offset",},{- $ref: "#/parameters/rowFilter.holiday.tags",+ $ref: "#/parameters/limit",},{- $ref: "#/parameters/preferReturn",+ $ref: "#/parameters/preferCount",},],responses: {- "204": {- description: "No Content",- },- },- tags: ["holiday"],- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.holiday.id",- },- {- $ref: "#/parameters/rowFilter.holiday.name",- },- {- $ref: "#/parameters/rowFilter.holiday.date",- },- {- $ref: "#/parameters/rowFilter.holiday.year",- },- {- $ref: "#/parameters/rowFilter.holiday.companyId",- },- {- $ref: "#/parameters/rowFilter.holiday.createdBy",- },- {- $ref: "#/parameters/rowFilter.holiday.createdAt",- },- {- $ref: "#/parameters/rowFilter.holiday.updatedBy",- },- {- $ref: "#/parameters/rowFilter.holiday.updatedAt",- },- {- $ref: "#/parameters/rowFilter.holiday.customFields",- },- {- $ref: "#/parameters/rowFilter.holiday.tags",- },- {- $ref: "#/parameters/body.holiday",- },- {- $ref: "#/parameters/preferReturn",+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/quoteLinePrices",+ },+ type: "array",+ },},- ],- responses: {- "204": {- description: "No Content",+ "206": {+ description: "Partial Content",},},- tags: ["holiday"],+ tags: ["quoteLinePrices"],},},- "/productionEvent": {+ "/salesRfqFavorite": {get: {parameters: [{- $ref: "#/parameters/rowFilter.productionEvent.id",- },- {- $ref: "#/parameters/rowFilter.productionEvent.jobOperationId",- },- {- $ref: "#/parameters/rowFilter.productionEvent.type",- },- {- $ref: "#/parameters/rowFilter.productionEvent.startTime",- },- {- $ref: "#/parameters/rowFilter.productionEvent.endTime",- },- {- $ref: "#/parameters/rowFilter.productionEvent.duration",- },- {- $ref: "#/parameters/rowFilter.productionEvent.employeeId",- },- {- $ref: "#/parameters/rowFilter.productionEvent.workCenterId",- },- {- $ref: "#/parameters/rowFilter.productionEvent.companyId",- },- {- $ref: "#/parameters/rowFilter.productionEvent.createdAt",- },- {- $ref: "#/parameters/rowFilter.productionEvent.createdBy",- },- {- $ref: "#/parameters/rowFilter.productionEvent.updatedAt",- },- {- $ref: "#/parameters/rowFilter.productionEvent.updatedBy",+ $ref: "#/parameters/rowFilter.salesRfqFavorite.rfqId",},{- $ref: "#/parameters/rowFilter.productionEvent.notes",+ $ref: "#/parameters/rowFilter.salesRfqFavorite.userId",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/salesRfqFavorite",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["salesRfqFavorite"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.salesRfqFavorite",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["salesRfqFavorite"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.salesRfqFavorite.rfqId",+ },+ {+ $ref: "#/parameters/rowFilter.salesRfqFavorite.userId",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["salesRfqFavorite"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.salesRfqFavorite.rfqId",+ },+ {+ $ref: "#/parameters/rowFilter.salesRfqFavorite.userId",+ },+ {+ $ref: "#/parameters/body.salesRfqFavorite",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["salesRfqFavorite"],+ },+ },+ "/holiday": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.holiday.id",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.name",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.date",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.year",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.customFields",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.tags",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/holiday",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["holiday"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.holiday",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["holiday"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.holiday.id",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.name",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.date",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.year",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.customFields",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.tags",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["holiday"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.holiday.id",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.name",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.date",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.year",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.customFields",+ },+ {+ $ref: "#/parameters/rowFilter.holiday.tags",+ },+ {+ $ref: "#/parameters/body.holiday",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["holiday"],+ },+ },+ "/productionEvent": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.productionEvent.id",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.jobOperationId",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.type",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.startTime",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.endTime",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.duration",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.employeeId",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.workCenterId",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.createdAt",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.createdBy",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.productionEvent.notes",},{$ref: "#/parameters/select",@@ -44135,6 +44312,101 @@ export default {tags: ["(rpc) get_companies_with_employee_permission"],},},+ "/rpc/suppliers_search": {+ get: {+ parameters: [+ {+ format: "vector",+ in: "query",+ name: "query_embedding",+ required: true,+ type: "string",+ },+ {+ format: "double precision",+ in: "query",+ name: "match_threshold",+ required: true,+ type: "number",+ },+ {+ format: "integer",+ in: "query",+ name: "match_count",+ required: true,+ type: "integer",+ },+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) suppliers_search"],+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ match_count: {+ format: "integer",+ type: "integer",+ },+ match_threshold: {+ format: "double precision",+ type: "number",+ },+ p_company_id: {+ format: "text",+ type: "string",+ },+ query_embedding: {+ format: "vector",+ type: "string",+ },+ },+ required: [+ "query_embedding",+ "match_threshold",+ "match_count",+ "p_company_id",+ ],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) suppliers_search"],+ },+ },"/rpc/get_companies_with_any_role": {get: {produces: [@@ -47949,6 +48221,101 @@ export default {tags: ["(rpc) get_opportunity_with_related_records"],},},+ "/rpc/items_search": {+ get: {+ parameters: [+ {+ format: "vector",+ in: "query",+ name: "query_embedding",+ required: true,+ type: "string",+ },+ {+ format: "double precision",+ in: "query",+ name: "match_threshold",+ required: true,+ type: "number",+ },+ {+ format: "integer",+ in: "query",+ name: "match_count",+ required: true,+ type: "integer",+ },+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) items_search"],+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ match_count: {+ format: "integer",+ type: "integer",+ },+ match_threshold: {+ format: "double precision",+ type: "number",+ },+ p_company_id: {+ format: "text",+ type: "string",+ },+ query_embedding: {+ format: "vector",+ type: "string",+ },+ },+ required: [+ "query_embedding",+ "match_threshold",+ "match_count",+ "p_company_id",+ ],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) items_search"],+ },+ },"/rpc/get_direct_ancestors_of_tracked_entity_strict": {get: {parameters: [@@ -60294,6 +60661,10 @@ export default {format: "numeric",type: "number",},+ sentDate: {+ format: "date",+ type: "string",+ },thumbnailPath: {format: "text",type: "string",@@ -60330,6 +60701,20 @@ export default {format: "text",type: "string",},+ orderDate: {+ format: "date",+ type: "string",+ },+ customerId: {+ description:+ "Note:\nThis is a Foreign Key to `customer.id`.<fk table='customer' column='id'/>",+ format: "text",+ type: "string",+ },+ salesOrderReadableId: {+ format: "text",+ type: "string",+ },},type: "object",},@@ -65927,7 +66312,7 @@ export default {},supplierInteractionId: {description:- "Note:\nThis is a Foreign Key to `currencyCode.code`.<fk table='currencyCode' column='code'/>",+ "Note:\nThis is a Foreign Key to `supplierInteraction.id`.<fk table='supplierInteraction' column='id'/>",format: "text",type: "string",},@@ -66829,6 +67214,197 @@ export default {},type: "object",},+ quoteLinePrices: {+ properties: {+ id: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ quoteId: {+ description:+ "Note:\nThis is a Foreign Key to `quote.id`.<fk table='quote' column='id'/>",+ format: "text",+ type: "string",+ },+ quoteRevisionId: {+ format: "integer",+ type: "integer",+ },+ status: {+ enum: ["Not Started", "In Progress", "Complete", "No Quote"],+ format: 'public."quoteLineStatus"',+ type: "string",+ },+ estimatorId: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ itemId: {+ description:+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",+ format: "text",+ type: "string",+ },+ itemReadableId: {+ format: "text",+ type: "string",+ },+ itemType: {+ format: "text",+ type: "string",+ },+ description: {+ format: "text",+ type: "string",+ },+ customerPartId: {+ format: "text",+ type: "string",+ },+ customerPartRevision: {+ format: "text",+ type: "string",+ },+ methodType: {+ enum: ["Buy", "Make", "Pick"],+ format: 'public."methodType"',+ type: "string",+ },+ unitOfMeasureCode: {+ format: "text",+ type: "string",+ },+ internalNotes: {+ format: "json",+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ customFields: {+ format: "jsonb",+ },+ modelUploadId: {+ description:+ "Note:\nThis is a Foreign Key to `modelUpload.id`.<fk table='modelUpload' column='id'/>",+ format: "text",+ type: "string",+ },+ quantity: {+ format: "numeric[]",+ items: {+ type: "number",+ },+ type: "array",+ },+ additionalCharges: {+ format: "jsonb",+ },+ locationId: {+ description:+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",+ format: "text",+ type: "string",+ },+ noQuoteReason: {+ format: "text",+ type: "string",+ },+ taxPercent: {+ format: "numeric",+ type: "number",+ },+ tags: {+ format: "text[]",+ items: {+ type: "string",+ },+ type: "array",+ },+ unitPricePrecision: {+ format: "integer",+ type: "integer",+ },+ externalNotes: {+ format: "jsonb",+ },+ configuration: {+ format: "jsonb",+ },+ thumbnailPath: {+ format: "text",+ type: "string",+ },+ modelId: {+ format: "text",+ type: "string",+ },+ autodeskUrn: {+ format: "text",+ type: "string",+ },+ modelPath: {+ format: "text",+ type: "string",+ },+ modelName: {+ format: "text",+ type: "string",+ },+ modelSize: {+ format: "bigint",+ type: "integer",+ },+ unitCost: {+ format: "numeric",+ type: "number",+ },+ qty: {+ format: "numeric",+ type: "number",+ },+ unitPrice: {+ format: "numeric",+ type: "number",+ },+ quoteReadableId: {+ format: "text",+ type: "string",+ },+ quoteCreatedAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ customerId: {+ description:+ "Note:\nThis is a Foreign Key to `customer.id`.<fk table='customer' column='id'/>",+ format: "text",+ type: "string",+ },+ },+ type: "object",+ },salesRfqFavorite: {required: ["rfqId", "userId"],properties: {@@ -82219,6 +82795,12 @@ export default {in: "query",type: "string",},+ "rowFilter.salesOrderLines.sentDate": {+ name: "sentDate",+ required: false,+ in: "query",+ type: "string",+ },"rowFilter.salesOrderLines.thumbnailPath": {name: "thumbnailPath",required: false,@@ -82273,6 +82855,24 @@ export default {in: "query",type: "string",},+ "rowFilter.salesOrderLines.orderDate": {+ name: "orderDate",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.salesOrderLines.customerId": {+ name: "customerId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.salesOrderLines.salesOrderReadableId": {+ name: "salesOrderReadableId",+ required: false,+ in: "query",+ type: "string",+ },"body.customerAccount": {name: "customerAccount",description: "customerAccount",@@ -89641,6 +90241,261 @@ export default {in: "query",type: "string",},+ "body.quoteLinePrices": {+ name: "quoteLinePrices",+ description: "quoteLinePrices",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/quoteLinePrices",+ },+ },+ "rowFilter.quoteLinePrices.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.quoteId": {+ name: "quoteId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.quoteRevisionId": {+ name: "quoteRevisionId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.status": {+ name: "status",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.estimatorId": {+ name: "estimatorId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.itemId": {+ name: "itemId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.itemReadableId": {+ name: "itemReadableId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.itemType": {+ name: "itemType",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.description": {+ name: "description",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.customerPartId": {+ name: "customerPartId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.customerPartRevision": {+ name: "customerPartRevision",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.methodType": {+ name: "methodType",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.unitOfMeasureCode": {+ name: "unitOfMeasureCode",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.internalNotes": {+ name: "internalNotes",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.customFields": {+ name: "customFields",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.modelUploadId": {+ name: "modelUploadId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.quantity": {+ name: "quantity",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.additionalCharges": {+ name: "additionalCharges",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.locationId": {+ name: "locationId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.noQuoteReason": {+ name: "noQuoteReason",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.taxPercent": {+ name: "taxPercent",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.tags": {+ name: "tags",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.unitPricePrecision": {+ name: "unitPricePrecision",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.externalNotes": {+ name: "externalNotes",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.configuration": {+ name: "configuration",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.thumbnailPath": {+ name: "thumbnailPath",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.modelId": {+ name: "modelId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.autodeskUrn": {+ name: "autodeskUrn",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.modelPath": {+ name: "modelPath",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.modelName": {+ name: "modelName",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.modelSize": {+ name: "modelSize",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.unitCost": {+ name: "unitCost",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.qty": {+ name: "qty",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.unitPrice": {+ name: "unitPrice",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.quoteReadableId": {+ name: "quoteReadableId",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.quoteCreatedAt": {+ name: "quoteCreatedAt",+ required: false,+ in: "query",+ type: "string",+ },+ "rowFilter.quoteLinePrices.customerId": {+ name: "customerId",+ required: false,+ in: "query",+ type: "string",+ },"body.salesRfqFavorite": {name: "salesRfqFavorite",description: "salesRfqFavorite",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 5bed1aa7ce..b1ba4685ea 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -17790,6 +17790,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteLinePrice_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteLinePrice_quoteLineId_fkey";columns: ["quoteLineId"];@@ -17993,6 +18000,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteMakeMethod_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteMakeMethod_quoteLineId_fkey";columns: ["quoteLineId"];@@ -18212,6 +18226,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteMaterial_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteMaterial_quoteLineId_fkey";columns: ["quoteLineId"];@@ -18528,6 +18549,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteOperation_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteOperation_quoteLineId_fkey";columns: ["quoteLineId"];@@ -30471,14 +30499,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey";- columns: ["id"];+ columns: ["supplierLocationId"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];},{foreignKeyName: "partner_id_fkey";- columns: ["supplierLocationId"];+ columns: ["id"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];@@ -31777,14 +31805,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["supplierCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["supplierCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -32154,6 +32182,284 @@ export type Database = {}];};+ quoteLinePrices: {+ Row: {+ additionalCharges: Json | null;+ autodeskUrn: string | null;+ companyId: string | null;+ configuration: Json | null;+ createdBy: string | null;+ customerId: string | null;+ customerPartId: string | null;+ customerPartRevision: string | null;+ customFields: Json | null;+ description: string | null;+ estimatorId: string | null;+ externalNotes: Json | null;+ id: string | null;+ internalNotes: Json | null;+ itemId: string | null;+ itemReadableId: string | null;+ itemType: string | null;+ locationId: string | null;+ methodType: Database["public"]["Enums"]["methodType"] | null;+ modelId: string | null;+ modelName: string | null;+ modelPath: string | null;+ modelSize: number | null;+ modelUploadId: string | null;+ noQuoteReason: string | null;+ qty: number | null;+ quantity: number[] | null;+ quoteCreatedAt: string | null;+ quoteId: string | null;+ quoteReadableId: string | null;+ quoteRevisionId: number | null;+ status: Database["public"]["Enums"]["quoteLineStatus"] | null;+ tags: string[] | null;+ taxPercent: number | null;+ thumbnailPath: string | null;+ unitCost: number | null;+ unitOfMeasureCode: string | null;+ unitPrice: number | null;+ unitPricePrecision: number | null;+ updatedAt: string | null;+ updatedBy: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customer";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "salesOrderCustomers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "companies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "customFieldTables";+ referencedColumns: ["companyId"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "integrations";+ referencedColumns: ["companyId"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "employees";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "employeesAcrossCompanies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "employees";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "employeesAcrossCompanies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteLine_itemId_fkey";+ columns: ["itemId"];+ isOneToOne: false;+ referencedRelation: "item";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_locationId_fkey";+ columns: ["locationId"];+ isOneToOne: false;+ referencedRelation: "location";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "jobs";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "modelUpload";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "parts";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "salesRfqLines";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "tools";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ isOneToOne: false;+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ isOneToOne: false;+ referencedRelation: "quoteCustomerDetails";+ referencedColumns: ["quoteId"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ isOneToOne: false;+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_unitOfMeasureCode_fkey";+ columns: ["unitOfMeasureCode", "companyId"];+ isOneToOne: false;+ referencedRelation: "unitOfMeasure";+ referencedColumns: ["code", "companyId"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "employees";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "employeesAcrossCompanies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };quoteLines: {Row: {additionalCharges: Json | null;@@ -32532,6 +32838,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteMaterial_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteMaterial_quoteLineId_fkey";columns: ["quoteLineId"];@@ -32783,6 +33096,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteOperation_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteOperation_quoteLineId_fkey";columns: ["quoteLineId"];@@ -33215,6 +33535,7 @@ export type Database = {convertedUnitPrice: number | null;createdAt: string | null;createdBy: string | null;+ customerId: string | null;customerPartId: string | null;customerPartRevision: string | null;customFields: Json | null;@@ -33233,6 +33554,7 @@ export type Database = {modelPath: string | null;modelSize: number | null;modelUploadId: string | null;+ orderDate: string | null;promisedDate: string | null;quantityInvoiced: number | null;quantitySent: number | null;@@ -33244,7 +33566,9 @@ export type Database = {salesOrderLineType:| Database["public"]["Enums"]["salesOrderLineType"]| null;+ salesOrderReadableId: string | null;sentComplete: boolean | null;+ sentDate: string | null;setupPrice: number | null;shelfId: string | null;shippingCost: number | null;@@ -33258,6 +33582,27 @@ export type Database = {updatedBy: string | null;};Relationships: [+ {+ foreignKeyName: "salesOrder_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customer";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "salesOrder_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "salesOrder_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "salesOrderCustomers";+ referencedColumns: ["id"];+ },{foreignKeyName: "salesOrderLine_accountNumber_fkey";columns: ["accountNumber", "companyId"];@@ -33409,14 +33754,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["paymentCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["paymentCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -36305,28 +36650,11 @@ export type Database = {p_company_id: string;};Returns: {- active: boolean;- assignee: string | null;- companyId: string | null;- createdAt: string;- createdBy: string;- defaultMethodType: Database["public"]["Enums"]["methodType"] | null;- description: string | null;- embedding: unknown | null;- externalId: Json | null;id: string;- itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];- modelUploadId: string | null;- name: string;- notes: Json | null;readableId: string;- replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];- thumbnailPath: string | null;- trackingMethod: string | null;- type: Database["public"]["Enums"]["itemType"];- unitOfMeasureCode: string | null;- updatedAt: string | null;- updatedBy: string | null;+ name: string;+ description: string;+ similarity: number;}[];};journalLinesByAccountNumber: {@@ -36366,19 +36694,6 @@ export type Database = {};Returns: string;};- search_by_embedding: {- Args: {- table_name: string;- query_embedding: string;- match_threshold: number;- match_count: number;- p_company_id: string;- };- Returns: {- id: string;- distance: number;- }[];- };suppliers_search: {Args: {query_embedding: string;@@ -36387,28 +36702,9 @@ export type Database = {p_company_id: string;};Returns: {- active: boolean;- assignee: string | null;- companyId: string | null;- createdAt: string;- createdBy: string;- defaultMethodType: Database["public"]["Enums"]["methodType"] | null;- description: string | null;- embedding: unknown | null;- externalId: Json | null;id: string;- itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];- modelUploadId: string | null;name: string;- notes: Json | null;- readableId: string;- replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];- thumbnailPath: string | null;- trackingMethod: string | null;- type: Database["public"]["Enums"]["itemType"];- unitOfMeasureCode: string | null;- updatedAt: string | null;- updatedBy: string | null;+ similarity: number;}[];};update_receipt_line_batch_tracking: {diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.tomlindex b80ad20366..2c14fc6c80 100644--- a/packages/database/supabase/config.toml+++ b/packages/database/supabase/config.toml@@ -123,6 +123,8 @@ vector_port = 54328# Configure one of the supported backends: `postgres`, `bigquery`.backend = "postgres"+[functions.chat]+verify_jwt = false[functions.convert]enabled = true@@ -138,6 +140,7 @@ enabled = true[functions.image-resizer]enabled = true+verify_jwt = false[functions.import-csv]enabled = true@@ -160,8 +163,10 @@ enabled = true[functions.thumbnail]enabled = true+verify_jwt = false[functions.update-purchased-prices]enabled = true+diff --git a/packages/database/supabase/functions/chat/index.ts b/packages/database/supabase/functions/chat/index.tsnew file mode 100644index 0000000000..1b1e9f78d7--- /dev/null+++ b/packages/database/supabase/functions/chat/index.ts@@ -0,0 +1,91 @@+import "jsr:@supabase/functions-js/edge-runtime.d.ts";+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { createAnthropic } from "npm:@ai-sdk/anthropic";+import { APICallError, LanguageModelV1CallOptions } from "npm:ai";+import { z } from "npm:zod";+import { corsHeaders } from "../lib/headers.ts";++import { getAuthFromAPIKey, getSupabase } from "../lib/supabase.ts";+import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";+import { Database } from "../lib/types.ts";++const model = createAnthropic({+ apiKey: Deno.env.get("ANTHROPIC_API_KEY"),+})("claude-3-7-sonnet-20250219");++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ let client: SupabaseClient<Database> | null = null;+ let userId: string | null = null;+ let companyId: string | null = null;++ const CARBON_MCP_API_KEY = Deno.env.get("CARBON_MCP_API_KEY");+ if (CARBON_MCP_API_KEY) {+ const auth = await getAuthFromAPIKey(CARBON_MCP_API_KEY);+ if (auth) {+ client = auth.client;+ userId = auth.userId;+ companyId = auth.companyId;+ }+ }++ const authHeader = req.headers.get("Authorization");+ const token = authHeader?.replace("Bearer ", "") ?? null;++ if (token && !client) {+ client = getSupabase(token);+ companyId = req.headers.get("x-company-id");++ await client.auth.setSession({+ access_token: token,+ refresh_token: token,+ });++ const user = (await client.auth.getUser())?.data?.user;+ if (user) {+ userId = user.id;+ }+ }++ if (!client || !companyId || !userId) {+ return new Response("Unauthorized", {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 401,+ });+ }++ try {+ const payload = await req.json();+ const body = z.custom<LanguageModelV1CallOptions>().parse(payload);++++ const result = await model.doGenerate(body);++ return new Response(JSON.stringify(result), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ });+ } catch (error) {++ console.error(error);+ if (error instanceof APICallError) {+ throw new Response(+ JSON.stringify({+ message: "API call error",+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ }+ );+ }+ return new Response(JSON.stringify(error), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});diff --git a/packages/database/supabase/functions/embed/index.ts b/packages/database/supabase/functions/embed/index.tsindex ba6a86051d..6b80c2d581 100644--- a/packages/database/supabase/functions/embed/index.ts+++ b/packages/database/supabase/functions/embed/index.ts@@ -197,6 +197,7 @@ async function processJob(db: Kysely<DB>, job: Job) {*/function catchUnload() {return new Promise((reject) => {+ // deno-lint-ignore no-explicit-anyaddEventListener("beforeunload", (ev: any) => {reject(new Error(ev.detail?.reason));});diff --git a/packages/database/supabase/functions/lib/api/accounting.ts b/packages/database/supabase/functions/lib/api/accounting.tsindex 5a4c036c0e..c33de7485a 100644--- a/packages/database/supabase/functions/lib/api/accounting.ts+++ b/packages/database/supabase/functions/lib/api/accounting.ts@@ -12,4 +12,4 @@ export async function getCurrencyByCode(.where("code", "=", currencyCode).where("companyId", "=", companyId).executeTakeFirst();-}\ No newline at end of file+}diff --git a/packages/database/supabase/functions/lib/api/purchasing.ts b/packages/database/supabase/functions/lib/api/purchasing.tsindex f3966b0071..1f1d4be9ea 100644--- a/packages/database/supabase/functions/lib/api/purchasing.ts+++ b/packages/database/supabase/functions/lib/api/purchasing.ts@@ -1,8 +1,11 @@-import { Kysely } from "npm:[email protected]";+import type {+ Kysely,+ Transaction,+} from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";import { DB } from "../database.ts";export async function getSupplier(- db: Kysely<DB>,+ db: Kysely<DB> | Transaction<DB>,supplierId: string) {return await db@@ -13,7 +16,7 @@ export async function getSupplier(}export async function getSupplierPayment(- db: Kysely<DB>,+ db: Kysely<DB> | Transaction<DB>,supplierId: string) {return await db@@ -24,7 +27,7 @@ export async function getSupplierPayment(}export async function getSupplierShipping(- db: Kysely<DB>,+ db: Kysely<DB> | Transaction<DB>,supplierId: string) {return await db@@ -35,7 +38,7 @@ export async function getSupplierShipping(}export async function insertSupplierInteraction(- db: Kysely<DB>,+ db: Kysely<DB> | Transaction<DB>,companyId: string) {return await db@@ -46,7 +49,7 @@ export async function insertSupplierInteraction(}export async function deletePurchaseOrder(- db: Kysely<DB>,+ db: Kysely<DB> | Transaction<DB>,purchaseOrderId: string) {return await db@@ -56,11 +59,11 @@ export async function deletePurchaseOrder(}export async function deletePurchaseOrderLine(- db: Kysely<DB>,+ db: Kysely<DB> | Transaction<DB>,purchaseOrderLineId: string) {return await db.deleteFrom("purchaseOrderLine").where("id", "=", purchaseOrderLineId).execute();-}\ No newline at end of file+}diff --git a/packages/database/supabase/functions/lib/headers.ts b/packages/database/supabase/functions/lib/headers.tsindex 02b087a135..5fbf0103e5 100644--- a/packages/database/supabase/functions/lib/headers.ts+++ b/packages/database/supabase/functions/lib/headers.ts@@ -1,5 +1,5 @@export const corsHeaders = {"Access-Control-Allow-Origin": "*","Access-Control-Allow-Headers":- "authorization, x-client-info, apikey, content-type",+ "authorization, x-client-info, apikey, content-type, x-company-id, x-user-id",};diff --git a/packages/database/supabase/functions/lib/mcp.ts b/packages/database/supabase/functions/lib/mcp.tsindex cef9a00c4f..380039757d 100644--- a/packages/database/supabase/functions/lib/mcp.ts+++ b/packages/database/supabase/functions/lib/mcp.ts@@ -1,103 +1,42 @@+// deno-lint-ignore-file no-explicit-anyimport SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";-import { Kysely, Transaction } from "npm:[email protected]";+import type { Kysely } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";+import {+ CallToolRequestSchema,+ CallToolResult,+ InitializeRequestSchema,+ InitializeResult,+ JSONRPCRequest,+ JSONRPCResponse,+ ListToolsRequestSchema,+ ListToolsResult,+ Prompt,+} from "npm:@modelcontextprotocol/[email protected]/types.js";import z from "npm:zod@^3.24.1";import { zodToJsonSchema } from "npm:zod-to-json-schema@^3.24.3";import { Tool } from "./tool.ts";import { Database } from "./types.ts";import { DB } from "./database.ts";-// Define the types locally instead of importing from @modelcontextprotocol/sdk-export interface JSONRPCRequest {- jsonrpc: "2.0";- id: string | number;- method: string;- params?: any;-}--export interface JSONRPCResponse {- jsonrpc: "2.0";- id: string | number;- result?: any;- error?: {- code: number;- message: string;- data?: any;- };-}--// TODO: these types should be imported from the @modelcontextprotocol/sdk package-// Initialize request and result types-export interface InitializeParams {- protocolVersion: string;-}--export const InitializeRequestSchema = z.object({- method: z.literal("initialize"),- params: z.object({- protocolVersion: z.string(),- }),-});--export interface InitializeResult {- protocolVersion: string;- prompts: Record<string, any>;- capabilities: {- tools: Record<string, any>;- };- serverInfo: {- name: string;- version: string;- };-}--// List tools request and result types-export const ListToolsRequestSchema = z.object({- method: z.literal("tools/list"),- params: z.object({}).optional(),-});--export interface ListToolsResult {- tools: Array<{- name: string;- inputSchema: Record<string, any>;- description: string;- }>;-}--// Call tool request and result types-export const CallToolRequestSchema = z.object({- method: z.literal("tools/call"),- params: z.object({- name: z.string(),- arguments: z.record(z.any()),- }),-});--export interface CallToolResult {- isError?: boolean;- content: Array<{- type: string;- text: string;- }>;-}-const RequestSchema = z.union([InitializeRequestSchema,ListToolsRequestSchema,CallToolRequestSchema,]);-export function createMcp(input: {- prompt: Record<string, any>;- tools: Tool[];-}) {+export function createMcp(input: { prompt: Prompt; tools: Tool[] }) {return {async process({payload,context,}: {payload: JSONRPCRequest;- context: { companyId: string; userId: string; client: SupabaseClient<Database>; db: Kysely<DB> | Transaction<DB> };+ context: {+ companyId: string;+ userId: string;+ client: SupabaseClient<Database>;+ db: Kysely<DB>;+ };}) {const parsed = RequestSchema.parse(payload);diff --git a/packages/database/supabase/functions/lib/supabase.ts b/packages/database/supabase/functions/lib/supabase.tsindex 776bd31fc0..916ed17f38 100644--- a/packages/database/supabase/functions/lib/supabase.ts+++ b/packages/database/supabase/functions/lib/supabase.ts@@ -1,6 +1,43 @@import { createClient } from "https://esm.sh/@supabase/[email protected]";import type { Database } from "../lib/types.ts";+export const getAuthFromAPIKey = async (apiKey: string) => {+ const serviceRole = createClient<Database>(+ Deno.env.get("SUPABASE_URL") ?? "",+ Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "",+ {+ auth: {+ autoRefreshToken: false,+ persistSession: false,+ },+ }+ );++ const apiKeyRow = await serviceRole+ .from("apiKey")+ .select("companyId, createdBy")+ .eq("key", apiKey)+ .single();++ if (apiKeyRow.error) return null;++ return {+ client: createClient<Database>(+ Deno.env.get("SUPABASE_URL") ?? "",+ Deno.env.get("SUPABASE_ANON_KEY") ?? "",+ {+ global: {+ headers: {+ "carbon-key": apiKey,+ },+ },+ }+ ),+ companyId: apiKeyRow.data.companyId,+ userId: apiKeyRow.data.createdBy,+ };+};+export const getSupabase = (authorizationHeader: string | null) => {if (!authorizationHeader) throw new Error("Authorization header is required");diff --git a/packages/database/supabase/functions/lib/tool.ts b/packages/database/supabase/functions/lib/tool.tsindex 1ef3704a6c..24a879eb62 100644--- a/packages/database/supabase/functions/lib/tool.ts+++ b/packages/database/supabase/functions/lib/tool.ts@@ -1,6 +1,9 @@import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";import { StandardSchemaV1 } from "npm:@standard-schema/spec";-import { Kysely, Transaction } from "npm:[email protected]";+import {+ Kysely,+ Transaction,+} from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";import { Database } from "./types.ts";import { DB } from "./database.ts";@@ -13,7 +16,12 @@ export interface Tool<run: Args extends StandardSchemaV1? (args: StandardSchemaV1.InferOutput<Args>,- context: { companyId: string; userId: string; client: SupabaseClient<Database>; db: Kysely<DB> | Transaction<DB> }+ context: {+ companyId: string;+ userId: string;+ client: SupabaseClient<Database>;+ db: Kysely<DB> | Transaction<DB>;+ }) => Promise<unknown>: () => Promise<unknown>;}diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 5bed1aa7ce..b1ba4685ea 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -17790,6 +17790,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteLinePrice_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteLinePrice_quoteLineId_fkey";columns: ["quoteLineId"];@@ -17993,6 +18000,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteMakeMethod_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteMakeMethod_quoteLineId_fkey";columns: ["quoteLineId"];@@ -18212,6 +18226,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteMaterial_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteMaterial_quoteLineId_fkey";columns: ["quoteLineId"];@@ -18528,6 +18549,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteOperation_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteOperation_quoteLineId_fkey";columns: ["quoteLineId"];@@ -30471,14 +30499,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey";- columns: ["id"];+ columns: ["supplierLocationId"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];},{foreignKeyName: "partner_id_fkey";- columns: ["supplierLocationId"];+ columns: ["id"];isOneToOne: false;referencedRelation: "supplierLocation";referencedColumns: ["id"];@@ -31777,14 +31805,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["supplierCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["supplierCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -32154,6 +32182,284 @@ export type Database = {}];};+ quoteLinePrices: {+ Row: {+ additionalCharges: Json | null;+ autodeskUrn: string | null;+ companyId: string | null;+ configuration: Json | null;+ createdBy: string | null;+ customerId: string | null;+ customerPartId: string | null;+ customerPartRevision: string | null;+ customFields: Json | null;+ description: string | null;+ estimatorId: string | null;+ externalNotes: Json | null;+ id: string | null;+ internalNotes: Json | null;+ itemId: string | null;+ itemReadableId: string | null;+ itemType: string | null;+ locationId: string | null;+ methodType: Database["public"]["Enums"]["methodType"] | null;+ modelId: string | null;+ modelName: string | null;+ modelPath: string | null;+ modelSize: number | null;+ modelUploadId: string | null;+ noQuoteReason: string | null;+ qty: number | null;+ quantity: number[] | null;+ quoteCreatedAt: string | null;+ quoteId: string | null;+ quoteReadableId: string | null;+ quoteRevisionId: number | null;+ status: Database["public"]["Enums"]["quoteLineStatus"] | null;+ tags: string[] | null;+ taxPercent: number | null;+ thumbnailPath: string | null;+ unitCost: number | null;+ unitOfMeasureCode: string | null;+ unitPrice: number | null;+ unitPricePrecision: number | null;+ updatedAt: string | null;+ updatedBy: string | null;+ };+ Relationships: [+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customer";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quote_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "salesOrderCustomers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "companies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "company";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "customFieldTables";+ referencedColumns: ["companyId"];+ },+ {+ foreignKeyName: "quoteLine_companyId_fkey";+ columns: ["companyId"];+ isOneToOne: false;+ referencedRelation: "integrations";+ referencedColumns: ["companyId"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "employees";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "employeesAcrossCompanies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_createdBy_fkey";+ columns: ["createdBy"];+ isOneToOne: false;+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "employees";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "employeesAcrossCompanies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_estimatorId_fkey";+ columns: ["estimatorId"];+ isOneToOne: false;+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ },+ {+ foreignKeyName: "quoteLine_itemId_fkey";+ columns: ["itemId"];+ isOneToOne: false;+ referencedRelation: "item";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_locationId_fkey";+ columns: ["locationId"];+ isOneToOne: false;+ referencedRelation: "location";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "jobs";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "modelUpload";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "parts";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "salesRfqLines";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_modelUploadId_fkey";+ columns: ["modelUploadId"];+ isOneToOne: false;+ referencedRelation: "tools";+ referencedColumns: ["modelId"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ isOneToOne: false;+ referencedRelation: "quote";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ isOneToOne: false;+ referencedRelation: "quoteCustomerDetails";+ referencedColumns: ["quoteId"];+ },+ {+ foreignKeyName: "quoteLine_quoteId_fkey";+ columns: ["quoteId"];+ isOneToOne: false;+ referencedRelation: "quotes";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_unitOfMeasureCode_fkey";+ columns: ["unitOfMeasureCode", "companyId"];+ isOneToOne: false;+ referencedRelation: "unitOfMeasure";+ referencedColumns: ["code", "companyId"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "employees";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "employeesAcrossCompanies";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "employeeSummary";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "user";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "quoteLine_updatedBy_fkey";+ columns: ["updatedBy"];+ isOneToOne: false;+ referencedRelation: "userDefaults";+ referencedColumns: ["userId"];+ }+ ];+ };quoteLines: {Row: {additionalCharges: Json | null;@@ -32532,6 +32838,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteMaterial_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteMaterial_quoteLineId_fkey";columns: ["quoteLineId"];@@ -32783,6 +33096,13 @@ export type Database = {referencedRelation: "quoteLine";referencedColumns: ["id"];},+ {+ foreignKeyName: "quoteOperation_quoteLineId_fkey";+ columns: ["quoteLineId"];+ isOneToOne: false;+ referencedRelation: "quoteLinePrices";+ referencedColumns: ["id"];+ },{foreignKeyName: "quoteOperation_quoteLineId_fkey";columns: ["quoteLineId"];@@ -33215,6 +33535,7 @@ export type Database = {convertedUnitPrice: number | null;createdAt: string | null;createdBy: string | null;+ customerId: string | null;customerPartId: string | null;customerPartRevision: string | null;customFields: Json | null;@@ -33233,6 +33554,7 @@ export type Database = {modelPath: string | null;modelSize: number | null;modelUploadId: string | null;+ orderDate: string | null;promisedDate: string | null;quantityInvoiced: number | null;quantitySent: number | null;@@ -33244,7 +33566,9 @@ export type Database = {salesOrderLineType:| Database["public"]["Enums"]["salesOrderLineType"]| null;+ salesOrderReadableId: string | null;sentComplete: boolean | null;+ sentDate: string | null;setupPrice: number | null;shelfId: string | null;shippingCost: number | null;@@ -33258,6 +33582,27 @@ export type Database = {updatedBy: string | null;};Relationships: [+ {+ foreignKeyName: "salesOrder_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customer";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "salesOrder_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "customers";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "salesOrder_customerId_fkey";+ columns: ["customerId"];+ isOneToOne: false;+ referencedRelation: "salesOrderCustomers";+ referencedColumns: ["id"];+ },{foreignKeyName: "salesOrderLine_accountNumber_fkey";columns: ["accountNumber", "companyId"];@@ -33409,14 +33754,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey";- columns: ["customerCountryCode"];+ columns: ["paymentCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];},{foreignKeyName: "address_countryCode_fkey";- columns: ["paymentCountryCode"];+ columns: ["customerCountryCode"];isOneToOne: false;referencedRelation: "country";referencedColumns: ["alpha2"];@@ -36305,28 +36650,11 @@ export type Database = {p_company_id: string;};Returns: {- active: boolean;- assignee: string | null;- companyId: string | null;- createdAt: string;- createdBy: string;- defaultMethodType: Database["public"]["Enums"]["methodType"] | null;- description: string | null;- embedding: unknown | null;- externalId: Json | null;id: string;- itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];- modelUploadId: string | null;- name: string;- notes: Json | null;readableId: string;- replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];- thumbnailPath: string | null;- trackingMethod: string | null;- type: Database["public"]["Enums"]["itemType"];- unitOfMeasureCode: string | null;- updatedAt: string | null;- updatedBy: string | null;+ name: string;+ description: string;+ similarity: number;}[];};journalLinesByAccountNumber: {@@ -36366,19 +36694,6 @@ export type Database = {};Returns: string;};- search_by_embedding: {- Args: {- table_name: string;- query_embedding: string;- match_threshold: number;- match_count: number;- p_company_id: string;- };- Returns: {- id: string;- distance: number;- }[];- };suppliers_search: {Args: {query_embedding: string;@@ -36387,28 +36702,9 @@ export type Database = {p_company_id: string;};Returns: {- active: boolean;- assignee: string | null;- companyId: string | null;- createdAt: string;- createdBy: string;- defaultMethodType: Database["public"]["Enums"]["methodType"] | null;- description: string | null;- embedding: unknown | null;- externalId: Json | null;id: string;- itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];- modelUploadId: string | null;name: string;- notes: Json | null;- readableId: string;- replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];- thumbnailPath: string | null;- trackingMethod: string | null;- type: Database["public"]["Enums"]["itemType"];- unitOfMeasureCode: string | null;- updatedAt: string | null;- updatedBy: string | null;+ similarity: number;}[];};update_receipt_line_batch_tracking: {diff --git a/packages/database/supabase/functions/mcp/index.ts b/packages/database/supabase/functions/mcp/index.tsindex 5315323ae0..218e0f252a 100644--- a/packages/database/supabase/functions/mcp/index.ts+++ b/packages/database/supabase/functions/mcp/index.ts@@ -1,11 +1,13 @@import "jsr:@supabase/functions-js/edge-runtime.d.ts";import { serve } from "https://deno.land/[email protected]/http/server.ts";+import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";import { corsHeaders } from "../lib/headers.ts";import { createMcp } from "../lib/mcp.ts";import { prompt, tools } from "./tools.ts";-import { getSupabaseServiceRole } from "../lib/supabase.ts";+import { getAuthFromAPIKey, getSupabase } from "../lib/supabase.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { Database } from "../lib/types.ts";const mcp = createMcp({ prompt, tools });const pool = getConnectionPool(1);@@ -17,17 +19,53 @@ serve(async (req: Request) => {}const payload = await req.json();- const companyId = "cvcqgb0mc0m048ha48i0";- const client = await getSupabaseServiceRole(- req.headers.get("Authorization"),- "crbn_8gX_n5oy_vRUmqTyCmKMD",- companyId- );- const userId = "system";+ console.log({+ function: 'mcp',+ ...payload,+ });++ let client: SupabaseClient<Database> | null = null;+ let userId: string | null = null;+ let companyId: string | null = null;++ const CARBON_MCP_API_KEY = Deno.env.get("CARBON_MCP_API_KEY");+ if (CARBON_MCP_API_KEY) {+ const auth = await getAuthFromAPIKey(CARBON_MCP_API_KEY);+ if (auth) {+ client = auth.client;+ userId = auth.userId;+ companyId = auth.companyId;+ }+ }++ const authHeader = req.headers.get("Authorization");+ const token = authHeader?.replace("Bearer ", "") ?? null;++ if (token && !client) {+ client = getSupabase(token);+ companyId = req.headers.get("x-company-id");++ await client.auth.setSession({+ access_token: token,+ refresh_token: token,+ });++ const user = (await client.auth.getUser())?.data?.user;+ if (user) {+ userId = user.id;+ }+ }++ if (!client || !companyId || !userId) {+ return new Response("Unauthorized", {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 401,+ });+ }try {- const result = await mcp.process({+ const result = await mcp.process({payload,context: {client,diff --git a/packages/database/supabase/functions/mcp/tools.ts b/packages/database/supabase/functions/mcp/tools.tsindex 13406d5979..a6b2a2eb17 100644--- a/packages/database/supabase/functions/mcp/tools.ts+++ b/packages/database/supabase/functions/mcp/tools.ts@@ -12,12 +12,14 @@ import {} from "../lib/api/purchasing.ts";import { getCurrencyByCode } from "../lib/api/accounting.ts";import { getNextSequence } from "../shared/get-next-sequence.ts";+import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";+import { DB } from "../lib/database.ts";const model = new Supabase.ai.Session("gte-small");const createPurchaseOrder = tool({name: "createPurchaseOrder",- description: "Create a purchase order",+ description: "Create a purchase order from a list of parts and a supplier",args: z.object({supplierId: z.string(),parts: z.array(@@ -28,7 +30,6 @@ const createPurchaseOrder = tool({),}),async run(args, context) {-const [nextSequence,supplierInteraction,@@ -37,7 +38,11 @@ const createPurchaseOrder = tool({supplierShipping,// purchaser] = await Promise.all([- getNextSequence(context.db, "purchaseOrder", context.companyId),+ getNextSequence(+ context.db as unknown as Transaction<DB>,+ "purchaseOrder",+ context.companyId+ ),insertSupplierInteraction(context.db, context.companyId),getSupplierById(context.db, args.supplierId),getSupplierPayment(context.db, args.supplierId),@@ -50,7 +55,7 @@ const createPurchaseOrder = tool({error: "Failed to create supplier interaction",};}-+if (!supplier) {return {error: "Supplier not found",@@ -66,7 +71,6 @@ const createPurchaseOrder = tool({error: "Supplier shipping not found",};}-const purchaseOrder = {purchaseOrderId: nextSequence,@@ -101,9 +105,7 @@ const createPurchaseOrder = tool({const order = await context.db.insertInto("purchaseOrder")- .values([- purchaseOrder- ])+ .values([purchaseOrder]).returning(["id", "purchaseOrderId"]).executeTakeFirst();@@ -147,9 +149,86 @@ const createPurchaseOrder = tool({.executeTakeFirstOrThrow(),]);+ // Create purchase order lines for each part+ await Promise.all(+ args.parts.map(async (part) => {+ // Get item details+ const [item, supplierPart] = await Promise.all([+ context.db+ .selectFrom("item")+ .select(["id", "name", "readableId", "type", "unitOfMeasureCode"])+ .where("id", "=", part.partId)+ .where("companyId", "=", context.companyId)+ .executeTakeFirst(),+ context.db+ .selectFrom("supplierPart")+ .selectAll()+ .where("itemId", "=", part.partId)+ .where("companyId", "=", context.companyId)+ .where("supplierId", "=", args.supplierId)+ .executeTakeFirst(),+ ]);++ if (!item) {+ throw new Error(`Item not found: ${part.partId}`);+ }++ // Get item cost and replenishment info+ const [itemCost, itemReplenishment] = await Promise.all([+ context.db+ .selectFrom("itemCost")+ .select(["unitCost"])+ .where("itemId", "=", part.partId)+ .executeTakeFirst(),+ context.db+ .selectFrom("itemReplenishment")+ .select([+ "purchasingUnitOfMeasureCode",+ "conversionFactor",+ "purchasingLeadTime",+ ])+ .where("itemId", "=", part.partId)+ .executeTakeFirst(),+ ]);++ // Create the purchase order line+ return context.db+ .insertInto("purchaseOrderLine")+ .values({+ purchaseOrderId: purchaseOrderId,+ itemId: part.partId,+ itemReadableId: item.readableId,+ description: item.name,+ purchaseOrderLineType: item.type,+ purchaseQuantity: part.quantity,+ supplierUnitPrice:+ (supplierPart?.unitPrice ?? itemCost?.unitCost ?? 0) /+ purchaseOrder.exchangeRate,+ supplierShippingCost: 0,+ purchaseUnitOfMeasureCode:+ supplierPart?.supplierUnitOfMeasureCode ??+ itemReplenishment?.purchasingUnitOfMeasureCode ??+ item.unitOfMeasureCode ??+ "EA",+ inventoryUnitOfMeasureCode: item.unitOfMeasureCode ?? "EA",+ conversionFactor:+ supplierPart?.conversionFactor ??+ itemReplenishment?.conversionFactor ??+ 1,+ locationId: locationId,+ shelfId: null,+ supplierTaxAmount: 0,+ companyId: context.companyId,+ createdBy: context.userId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ })+ );+return order;} catch (error) {- if(purchaseOrderId) {+ if (purchaseOrderId) {await deletePurchaseOrder(context.db, purchaseOrderId);}return {@@ -242,9 +321,12 @@ const getSupplier = tool({description: z.string().optional(),partIds: z.array(z.string()).optional(),})- .refine((data) => data.id || data.name || data.description || data.partIds, {- message: "Either id, name, description, or partIds must be provided",- }),+ .refine(+ (data) => data.id || data.name || data.description || data.partIds,+ {+ message: "Either id, name, description, or partIds must be provided",+ }+ ),async run(args, context) {let { name, description, partIds } = args;@@ -304,8 +386,8 @@ const getSupplier = tool({},});-const suggestSupplierForParts = tool({- name: "suggestSupplierForParts",+const getSupplierForParts = tool({+ name: "getSupplierForParts",description: "Suggest a list of suppliers for a given list of parts",args: z.object({partIds: z.array(z.string()),@@ -426,7 +508,7 @@ export const tools = [createPurchaseOrder,getPart,getSupplier,- suggestSupplierForParts,+ getSupplierForParts,];export const prompt = {@@ -439,7 +521,7 @@ When handling purchase order requests:1. First identify the part details (including quantities and measurements)2. Use getPart to look up the part ID3. If no supplier is explicitly specified in the prompt:- - Use suggestSupplierForParts to get recommended suppliers+ - Use getSupplierForParts to get recommended suppliers- Ask the user to confirm which supplier they want to use4. Only proceed with createPurchaseOrder when both part and supplier are confirmed5. If there are multiple options for a part or supplier, ask the user to confirm which one they want to use@@ -468,13 +550,13 @@ Key capabilities:Tools:- getPart- Search for a part by readable id or description- - Returns an id that can be used to create a purchase order+ - Returns an id that can be used to create, update, or search for documents by part id- getSupplier- Search for suppliers by id, a specific name from the prompt, a deduced description, or a list of part ids- - Returns an id that can be used to create a purchase order-- suggestSupplierForParts+ - Returns an id that can be used to create, update, or search for documents by supplier id+- getSupplierForParts- Suggest a list of suppliers for a given list of parts- createPurchaseOrder- Create a purchase order in draft status with multiple parts`,-};\ No newline at end of file+};diff --git a/packages/database/supabase/functions/shared/get-next-sequence.ts b/packages/database/supabase/functions/shared/get-next-sequence.tsindex 65de55c685..50bb24d35e 100644--- a/packages/database/supabase/functions/shared/get-next-sequence.ts+++ b/packages/database/supabase/functions/shared/get-next-sequence.ts@@ -1,9 +1,9 @@-import { Kysely, Transaction } from "https://esm.sh/[email protected]";+import { Transaction } from "https://esm.sh/[email protected]";import { DB } from "../lib/database.ts";import { interpolateSequenceDate } from "../lib/utils.ts";export async function getNextSequence(- trx: Transaction<DB> | Kysely<DB>,+ trx: Transaction<DB>,tableName: string,companyId: string) {diff --git a/packages/database/supabase/migrations/20250317171124_embeddings.sql b/packages/database/supabase/migrations/20250317171124_embeddings.sqlindex 9058861b1f..b334abd718 100644--- a/packages/database/supabase/migrations/20250317171124_embeddings.sql+++ b/packages/database/supabase/migrations/20250317171124_embeddings.sql@@ -302,6 +302,7 @@ CREATE OR REPLACE FUNCTION public.items_search()RETURNS TABLE (id text,+ "readableId" text,name text,description text,similarity float@@ -311,6 +312,7 @@ SECURITY DEFINERAS $$SELECTitem.id,+ item."readableId",item.name,item.description,1 - (item.embedding <=> query_embedding) AS similarity@@ -347,4 +349,3 @@ AS $$$$;-ALTER PUBLICATION supabase_realtime ADD TABLE "purchaseOrder";