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(custom-fields): show Link fields as safe links
Raul9ad9f48a5c9e
diff --git a/apps/erp/app/components/Form/CustomFormFields.tsx b/apps/erp/app/components/Form/CustomFormFields.tsxindex 8f08517680..344a0cef0f 100644--- a/apps/erp/app/components/Form/CustomFormFields.tsx+++ b/apps/erp/app/components/Form/CustomFormFields.tsx@@ -10,6 +10,8 @@ import {Select,useAdditionalValidatorsContext} from "@carbon/form";+import { toSafeHref } from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";import { useEffect, useMemo } from "react";import { useCustomFieldsSchema } from "~/hooks/useCustomFieldsSchema";import { DataType } from "~/modules/shared";@@ -23,26 +25,44 @@ type CustomFormFieldsProps = {};const CustomFormFields = ({ table, tags = [] }: CustomFormFieldsProps) => {+ const { t } = useLingui();const customFormSchema = useCustomFieldsSchema();const tableFields = customFormSchema?.[table];const additionalValidatorCtx = useAdditionalValidatorsContext();const tagsKey = tags.join(",");- const requiredFieldNames = useMemo(() => {+ const visibleFields = useMemo(() => {if (!tableFields) return [];- return tableFields- .filter((field) => {- if (!field.required || field.dataTypeId === DataType.Boolean)- return false;- if (!field.tags || field.tags.length === 0) return true;- return field.tags.some((tag) => tagsKey.split(",").includes(tag));- })- .map((field) => getCustomFieldName(field.id));- // eslint-disable-next-line react-hooks/exhaustive-deps+ return tableFields.filter((field) => {+ if (!field.tags || field.tags.length === 0) return true;+ return field.tags.some((tag) => tagsKey.split(",").includes(tag));+ });}, [tableFields, tagsKey]);+ const requiredFieldNames = useMemo(+ () =>+ visibleFields+ .filter(+ (field) => field.required && field.dataTypeId !== DataType.Boolean+ )+ .map((field) => getCustomFieldName(field.id)),+ [visibleFields]+ );++ const linkFieldNames = useMemo(+ () =>+ visibleFields+ .filter((field) => field.dataTypeId === DataType.Link)+ .map((field) => getCustomFieldName(field.id)),+ [visibleFields]+ );+useEffect(() => {- if (!additionalValidatorCtx || requiredFieldNames.length === 0) return;+ if (+ !additionalValidatorCtx ||+ (requiredFieldNames.length === 0 && linkFieldNames.length === 0)+ )+ return;const id = `custom-${table}`;additionalValidatorCtx.register(id, (formData) => {@@ -53,11 +73,21 @@ const CustomFormFields = ({ table, tags = [] }: CustomFormFieldsProps) => {errors[name] = "Required";}}+ for (const name of linkFieldNames) {+ const value = formData.get(name);+ if (+ typeof value === "string" &&+ value.trim() !== "" &&+ toSafeHref(value) === null+ ) {+ errors[name] = t`Enter a web address, such as https://example.com`;+ }+ }return errors;});return () => additionalValidatorCtx.unregister(id);- }, [requiredFieldNames, table, additionalValidatorCtx]);+ }, [requiredFieldNames, linkFieldNames, table, additionalValidatorCtx, t]);if (!tableFields) return null;@@ -128,6 +158,17 @@ const CustomFormFields = ({ table, tags = [] }: CustomFormFieldsProps) => {isRequired={isRequired}/>);+ case DataType.Link:+ return (+ <Input+ key={field.id}+ name={getCustomFieldName(field.id)}+ label={field.name}+ isRequired={isRequired}+ inputMode="url"+ placeholder="https://"+ />+ );case DataType.User:return (<Employeediff --git a/apps/erp/app/components/Form/CustomFormInlineFields.tsx b/apps/erp/app/components/Form/CustomFormInlineFields.tsxindex cf9caf77d1..8624881028 100644--- a/apps/erp/app/components/Form/CustomFormInlineFields.tsx+++ b/apps/erp/app/components/Form/CustomFormInlineFields.tsx@@ -16,6 +16,7 @@ import { zfd } from "zod-form-data";import { useCustomFieldsSchema } from "~/hooks/useCustomFieldsSchema";import { DataType } from "~/modules/shared";import { Enumerable } from "../Enumerable";+import LinkValue from "../LinkValue";import Customer from "./Customer";import Employee from "./Employee";import Supplier from "./Supplier";@@ -214,6 +215,39 @@ const CustomFormInlineFields = ({/></ValidatedForm>);+ case DataType.Link:+ return (+ // biome-ignore lint/correctness/useJsxKeyInIterable: suppressed due to migration+ <ValidatedForm+ defaultValues={{+ [field.id]: fields[field.id] as string+ }}+ validator={z.object({+ [field.id]: zfd.text(z.string().optional())+ })}+ className="w-full"+ >+ <InputControlled+ name={field.id}+ label={field.name}+ value={fields[field.id] as string}+ size="sm"+ inline+ inputMode="url"+ placeholder="https://"+ renderInlineValue={(value) => <LinkValue value={value} />}+ isReadOnly={isDisabled}+ onBlur={(e) => {+ onUpdate(+ JSON.stringify({+ ...fields,+ [field.id]: e.target.value+ })+ );+ }}+ />+ </ValidatedForm>+ );case DataType.User:return (// biome-ignore lint/correctness/useJsxKeyInIterable: suppressed due to migrationdiff --git a/apps/erp/app/components/LinkValue.tsx b/apps/erp/app/components/LinkValue.tsxnew file mode 100644index 0000000000..a23c1eb403--- /dev/null+++ b/apps/erp/app/components/LinkValue.tsx@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { cn } from "@carbon/react";+import { toLinkLabel, toSafeHref } from "@carbon/utils";+import { LuExternalLink } from "react-icons/lu";++type LinkValueProps = {+ value: string;+ className?: string;+};++/**+ * A stored web address. It opens in a new tab when `toSafeHref` accepts it, and+ * shows as plain text when it does not (another scheme, or not an address).+ * The link text is the short form from `toLinkLabel`; the tooltip has it in full.+ */+const LinkValue = ({ value, className }: LinkValueProps) => {+ const href = toSafeHref(value);+ if (!href) return <span className={className}>{value}</span>;++ return (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ title={href}+ // A link inside a clickable row or panel opens the address, not the row.+ onClick={(e) => e.stopPropagation()}+ className={cn(+ "inline-flex max-w-full items-center gap-1 text-foreground hover:underline",+ className+ )}+ >+ <span className="truncate">{toLinkLabel(value)}</span>+ <LuExternalLink className="size-3 flex-shrink-0 text-muted-foreground" />+ </a>+ );+};++export default LinkValue;diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.tsindex 78212df93a..1659d2e8cc 100644--- a/apps/erp/app/components/index.ts+++ b/apps/erp/app/components/index.ts@@ -36,6 +36,7 @@ import {} from "./Icons";import { ItemLifecycleBadge } from "./ItemLifecycleBadge";import ItemThumbnail from "./ItemThumbnail";+import LinkValue from "./LinkValue";import Location from "./Location";import MetricCard from "./MetricCard";import { ModelOptimizedIndicator } from "./ModelOptimizedIndicator";@@ -82,6 +83,7 @@ export {Hyperlink,ItemLifecycleBadge,ItemThumbnail,+ LinkValue,Location,MethodBadge,MethodIcon,diff --git a/apps/erp/app/hooks/useCustomColumns.tsx b/apps/erp/app/hooks/useCustomColumns.tsxindex d7e493cde2..60c3c335ec 100644--- a/apps/erp/app/hooks/useCustomColumns.tsx+++ b/apps/erp/app/hooks/useCustomColumns.tsx@@ -12,12 +12,18 @@ import {LuCaseSensitive,LuContainer,LuHash,+ LuLink,LuList,LuSquareUser,LuToggleLeft,LuUser} from "react-icons/lu";-import { CustomerAvatar, EmployeeAvatar, SupplierAvatar } from "~/components";+import {+ CustomerAvatar,+ EmployeeAvatar,+ LinkValue,+ SupplierAvatar+} from "~/components";import { Enumerable } from "~/components/Enumerable";import { DataType } from "~/modules/shared";import { useCustomers, usePeople, useSuppliers } from "~/stores";@@ -74,7 +80,8 @@ export function useCustomColumns<T extends { customFields: Json }>(label: person.name}))}- : field.dataTypeId === DataType.Text+ : field.dataTypeId === DataType.Text ||+ field.dataTypeId === DataType.Link? {type: "fetcher",endpoint: path.to.api.customFieldOptions(@@ -133,6 +140,14 @@ export function useCustomColumns<T extends { customFields: Json }>(field.id in item.row.original.customFields? item.row.original?.customFields[field.id]: null;+ case DataType.Link: {+ const value = isObject(item.row.original.customFields)+ ? item.row.original.customFields[field.id]+ : null;+ return typeof value === "string" && value ? (+ <LinkValue value={value} />+ ) : null;+ }case DataType.User:if (isObject(item.row.original.customFields) &&@@ -199,6 +214,8 @@ function ColumnIcon({ dataTypeId }: { dataTypeId: DataType }) {return <LuHash />;case DataType.Text:return <LuCaseSensitive />;+ case DataType.Link:+ return <LuLink />;case DataType.User:return <LuUser />;case DataType.Customer:diff --git a/apps/erp/app/modules/people/people.models.ts b/apps/erp/app/modules/people/people.models.tsindex c171f6a069..e2f6eb14ea 100644--- a/apps/erp/app/modules/people/people.models.ts+++ b/apps/erp/app/modules/people/people.models.ts@@ -26,6 +26,11 @@ export const attributeValidator = zreturn false;return true;+ })+ // Link is a custom field type only; person attributes cannot store one.+ .refine((input) => input.attributeDataTypeId !== DataType.Link, {+ message: "Link is not available for attributes",+ path: ["attributeDataTypeId"]});export const attributeCategoryValidator = z.object({diff --git a/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx b/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsxindex 195fb6bc25..acab070ad3 100644--- a/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx+++ b/apps/erp/app/modules/people/ui/Attributes/AttributeForm.tsx@@ -53,11 +53,15 @@ const AttributeForm = ({const { t } = useLingui();const permissions = usePermissions();+ // Link is a custom field type only; person attributes have no Link input+ // and no column to store one in.const options =- dataTypes?.map((dt) => ({- value: dt.id.toString(),- label: dt.label- })) ?? [];+ dataTypes+ ?.filter((dt) => dt.id !== DataType.Link)+ .map((dt) => ({+ value: dt.id.toString(),+ label: dt.label+ })) ?? [];const isEditing = initialValues.id !== undefined;const isDisabled = isEditingdiff --git a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsxindex d08b77bb2a..9462b66efe 100644--- a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx+++ b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldForm.tsx@@ -22,6 +22,7 @@ import {LuContainer,LuFile,LuHash,+ LuLink,LuList,LuSquareUser,LuToggleLeft,@@ -191,6 +192,8 @@ function CustomFieldDataTypeIcon({);case DataType.File:return <LuFile className={cn("w-4 h-4 text-indigo-600", className)} />;+ case DataType.Link:+ return <LuLink className={cn("w-4 h-4 text-sky-600", className)} />;default:return null;}diff --git a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsxindex a074b1fff4..2a88fd7be2 100644--- a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx+++ b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTableDetail.tsx@@ -30,6 +30,7 @@ import { CgProfile } from "react-icons/cg";import {LuContainer,LuGripVertical,+ LuLink,LuPencil,LuSquareUser,LuTrash@@ -258,6 +259,7 @@ function getIcon(props: AttributeDataType) {isDate,isNumeric,isText,+ isLink,isUser,isCustomer,isSupplier@@ -266,6 +268,7 @@ function getIcon(props: AttributeDataType) {if (isDate) return <BsCalendarDate />;if (isNumeric) return <AiOutlineNumber />;if (isText) return <BiText />;+ if (isLink) return <LuLink />;if (isUser) return <CgProfile />;if (isCustomer) return <LuSquareUser />;if (isSupplier) return <LuContainer />;diff --git a/packages/form/src/components/InputControlled.tsx b/packages/form/src/components/InputControlled.tsxindex 398684e95a..6e26925216 100644--- a/packages/form/src/components/InputControlled.tsx+++ b/packages/form/src/components/InputControlled.tsx@@ -38,6 +38,8 @@ type FormInputControlledProps = Omit<InputProps, "value" | "onChange"> & {prefix?: string;suffix?: string;inline?: boolean;+ /** Inline mode only: how the saved value is shown. Defaults to the plain text. */+ renderInlineValue?: (value: string) => ReactNode;value: string;onChange?: (newValue: string) => void;onConfigure?: () => void;@@ -61,6 +63,7 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>(onChange,isUppercase,inline = false,+ renderInlineValue,isReadOnly: isReadOnlyProp,isDisabled: isDisabledProp,onBlur,@@ -116,7 +119,9 @@ const InputControlled = forwardRef<HTMLInputElement, FormInputControlledProps>()}<HStack spacing={0} className="w-full justify-between">{value && (- <span className="flex-grow text-sm line-clamp-1">{value}</span>+ <span className="flex-grow text-sm line-clamp-1">+ {renderInlineValue ? renderInlineValue(value) : value}+ </span>)}<IconButtonicon={value ? <LuSettings2 /> : <LuPlus />}diff --git a/packages/utils/src/url.test.ts b/packages/utils/src/url.test.tsnew file mode 100644index 0000000000..7647b6b1dc--- /dev/null+++ b/packages/utils/src/url.test.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { toLinkLabel, toSafeHref } from "./url";++describe("toSafeHref", () => {+ it("returns http and https links", () => {+ expect(toSafeHref("https://www.example.com/parts/SKU-1001")).toBe(+ "https://www.example.com/parts/SKU-1001"+ );+ expect(toSafeHref("http://example.com")).toBe("http://example.com/");+ expect(toSafeHref("HTTPS://Example.com/A")).toBe("https://example.com/A");+ expect(toSafeHref("http://localhost:3000/x")).toBe(+ "http://localhost:3000/x"+ );+ });++ it("adds https to a value with no scheme", () => {+ expect(toSafeHref("www.example.com/parts/SKU-1001")).toBe(+ "https://www.example.com/parts/SKU-1001"+ );+ expect(toSafeHref("example.com")).toBe("https://example.com/");+ expect(toSafeHref("www.example.com:8080/x")).toBe(+ "https://www.example.com:8080/x"+ );+ expect(toSafeHref("//example.com/x")).toBe("https://example.com/x");+ expect(toSafeHref(" example.com/x ")).toBe("https://example.com/x");+ });++ it("refuses every other scheme", () => {+ for (const value of [+ "javascript:alert(1)",+ "JavaScript:alert(1)",+ "javascript://example.com/%0Aalert(1)",+ "data:text/html,<script>alert(1)</script>",+ "vbscript:msgbox(1)",+ "file:///etc/passwd",+ "mailto:[email protected]",+ "ftp://example.com/file"+ ]) {+ expect(toSafeHref(value), value).toBeNull();+ }+ });++ it("refuses a value that is not a web address", () => {+ for (const value of [+ "",+ " ",+ "hello",+ "hello world",+ "https://example.com/a b",+ "/x/part/123",+ "https://"+ ]) {+ expect(toSafeHref(value), value).toBeNull();+ }+ });++ it("refuses anything that is not a string", () => {+ for (const value of [null, undefined, 42, true, {}, ["https://a.com"]]) {+ expect(toSafeHref(value)).toBeNull();+ }+ });+});++describe("toLinkLabel", () => {+ it("drops the scheme, a leading www. and a trailing slash", () => {+ expect(toLinkLabel("https://www.example.com/parts/SKU-1001")).toBe(+ "example.com/parts/SKU-1001"+ );+ expect(toLinkLabel("HTTP://WWW.Example.com/")).toBe("Example.com");+ expect(toLinkLabel(" www.example.com/parts/ ")).toBe("example.com/parts");+ expect(toLinkLabel("//example.com/x")).toBe("example.com/x");+ });++ it("keeps the rest of the address as typed", () => {+ expect(toLinkLabel("shop.example.com:8080/a?b=1#c")).toBe(+ "shop.example.com:8080/a?b=1#c"+ );+ expect(toLinkLabel("example.com/www.thing")).toBe("example.com/www.thing");+ });+});diff --git a/packages/utils/src/url.ts b/packages/utils/src/url.tsindex 4db47815a9..35d41cc157 100644--- a/packages/utils/src/url.ts+++ b/packages/utils/src/url.ts@@ -14,6 +14,61 @@ export const isUrl = (str: string) => {return url.protocol === "http:" || url.protocol === "https:";};+// A leading `word:` is a scheme only when the word has no dot: `javascript:` and+// `mailto:` are schemes, `www.example.com:8080` is a host with a port.+const SCHEME = /^([a-z][a-z0-9+.-]*):/i;++/**+ * The href to render for a stored link value, or null when it must render as+ * plain text. Values reach the database from forms, the API, MCP and workflows,+ * so this runs at render time, never only at input.+ *+ * - Only http and https links are returned; `javascript:`, `data:` and every+ * other scheme are refused.+ * - A value with no scheme (`www.example.com/part`) gets `https://`, so it+ * cannot resolve as a path inside the app. It must have a dotted host.+ * - A value with whitespace inside it is refused.+ */+export function toSafeHref(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ if (!trimmed || /\s/.test(trimmed)) return null;++ const scheme = SCHEME.exec(trimmed)?.[1];+ const hasScheme = scheme !== undefined && !scheme.includes(".");+ const candidate = hasScheme+ ? trimmed+ : `https://${trimmed.replace(/^\/+/, "")}`;++ let url: URL;+ try {+ url = new URL(candidate);+ } catch {+ return null;+ }++ if (url.protocol !== "http:" && url.protocol !== "https:") return null;+ if (!hasScheme && !url.hostname.includes(".")) return null;++ return url.href;+}++/**+ * A stored link value as shown in a table or panel: without the scheme, a+ * leading `www.` or a trailing slash, so the part that tells two links apart+ * fits in a narrow column. `https://www.example.com/parts/` → `example.com/parts`.+ * The full address stays in the href and the tooltip.+ */+export function toLinkLabel(value: string): string {+ const label = value+ .trim()+ .replace(/^https?:\/\//i, "")+ .replace(/^\/+/, "")+ .replace(/^www\./i, "")+ .replace(/\/$/, "");+ return label || value.trim();+}+/*** Get favicon URL for a given website URL*/