Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

- cleanup

Gaurav Bhatt56aa3c804f73
diff --git a/apps/erp/app/components/AttachmentsList.tsx b/apps/erp/app/components/AttachmentsList.tsx
index 3570e054bd..960d8a9d7b 100644
--- a/apps/erp/app/components/AttachmentsList.tsx
+++ b/apps/erp/app/components/AttachmentsList.tsx
@@ -1,7 +1,6 @@
import { useCarbon } from "@carbon/auth";
import {
Badge,
- Checkbox,
HStack,
IconButton,
Spinner,
@@ -12,41 +11,37 @@ import { convertKbToString } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useMemo, useState } from "react";
import { useDropzone } from "react-dropzone";
-import { LuCloudUpload, LuFileText, LuLock, LuX } from "react-icons/lu";
-import { useFetcher, useRevalidator, useSubmit } from "react-router";
+import { LuCloudUpload, LuFileText, LuX } from "react-icons/lu";
+import { useRevalidator } from "react-router";
import { useUser } from "~/hooks";
-import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
export type ResolvedAttachmentItem = {
- documentId: string;
- /** When source === "po", the id of the purchaseOrderAttachment row (for delete). */
- attachmentRowId: string | null;
source: "po" | "company" | "supplier" | "item";
sourceLabel: string;
- shareOnSend: boolean;
- isLocked: boolean;
name: string;
size: number | null;
+ /** Full storage path under the `private` bucket. Used as a stable key. */
+ path: string;
};
type AttachmentsListProps = {
- purchaseOrderId: string;
- /** Pinned, non-removable. Always sent regardless of selection state. */
+ /**
+ * Supplier interaction id — used as the upload destination for ad-hoc files
+ * dropped at finalize time. Files go to
+ * `{companyId}/supplier-interaction/{supplierInteractionId}/` and are
+ * auto-attached by the existing supplier-quote/RFQ flow conventions.
+ */
+ supplierInteractionId: string | null;
+ /** Pinned, non-removable. Always sent. Used for the PO PDF preview row. */
pinned?: Array<{ name: string; sizeKb?: number; label?: string }>;
- /** Resolved attachments (Company + Supplier + Item + PO ad-hoc, deduped). */
+ /** Resolved attachments (Company + Supplier + Item + PO ad-hoc). */
attachments: ResolvedAttachmentItem[];
- /** Form field name for the hidden inputs carrying included documentIds. */
- fieldName?: string;
};
const WARN_KB = 20 * 1024;
const LIMIT_KB = 25 * 1024;
-// Map of attachment source → Carbon Badge variant. Uses built-in semantic
-// color variants from packages/react/src/Badge.tsx so dark mode + the
-// rest of the design system stays consistent. Do not introduce custom
-// `bg-*`/`text-*` Tailwind classes for status colors here.
const sourceBadgeVariant: Record<
ResolvedAttachmentItem["source"],
"blue" | "green" | "orange" | "purple"
@@ -57,97 +52,62 @@ const sourceBadgeVariant: Record<
company: "purple"
};
+/**
+ * Read-only preview of every file that's about to ride along on a PO send,
+ * plus a drag-drop zone for ad-hoc uploads. No selection UI — everything in
+ * the four scope folders auto-attaches, matching the supplier-quote/RFQ flows.
+ */
export default function AttachmentsList({
- purchaseOrderId,
+ supplierInteractionId,
pinned = [],
- attachments,
- fieldName = "attachmentDocumentIds"
+ attachments
}: AttachmentsListProps) {
const { t } = useLingui();
const { carbon } = useCarbon();
const { company } = useUser();
const revalidator = useRevalidator();
- const submit = useSubmit();
const [uploading, setUploading] = useState(false);
- // Track which document IDs the user has explicitly excluded for THIS send.
- // Default: all shareOnSend=true items are included; shareOnSend=false items
- // are visible-but-greyed-out and never selectable for this send.
- const [excluded, setExcluded] = useState<Set<string>>(new Set());
-
- // Locked attachments cannot be excluded — they're always included if shareOnSend=true.
- const isIncluded = (a: ResolvedAttachmentItem) =>
- a.shareOnSend && (a.isLocked || !excluded.has(a.documentId));
-
- const includedIds = useMemo(() => {
- return attachments.filter(isIncluded).map((a) => a.documentId);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [attachments, excluded]);
-
const totalKb = useMemo(() => {
const pinnedKb = pinned.reduce((sum, p) => sum + (p.sizeKb ?? 0), 0);
- const attKb = attachments
- .filter(isIncluded)
- .reduce((sum, a) => sum + (a.size ?? 0), 0);
+ const attKb = attachments.reduce((sum, a) => sum + (a.size ?? 0), 0);
return pinnedKb + attKb;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [attachments, excluded, pinned]);
+ }, [attachments, pinned]);
const overLimit = totalKb > LIMIT_KB;
const warning = totalKb > WARN_KB && !overLimit;
- const toggle = (docId: string, checked: boolean) => {
- setExcluded((prev) => {
- const next = new Set(prev);
- if (checked) next.delete(docId);
- else next.add(docId);
- return next;
- });
- };
-
const onDrop = useCallback(
async (acceptedFiles: File[]) => {
if (!carbon) {
toast.error(t`Storage client not available`);
return;
}
+ if (!supplierInteractionId) {
+ toast.error(t`Cannot upload — supplier interaction not yet created`);
+ return;
+ }
setUploading(true);
try {
for (const file of acceptedFiles) {
const safeName = stripSpecialCharacters(file.name);
- const storagePath = `${company.id}/purchase-order/${purchaseOrderId}/${safeName}`;
-
+ const storagePath = `${company.id}/supplier-interaction/${supplierInteractionId}/${safeName}`;
const upload = await carbon.storage
.from("private")
.upload(storagePath, file, {
cacheControl: `${12 * 60 * 60}`,
upsert: true
});
-
if (upload.error) {
toast.error(t`Failed to upload ${file.name}`);
- continue;
}
-
- const fd = new FormData();
- fd.append("path", storagePath);
- fd.append("name", file.name);
- fd.append("size", Math.round(file.size / 1024).toString());
-
- submit(fd, {
- method: "post",
- action: path.to.purchaseOrderAttachments(purchaseOrderId),
- navigate: false,
- fetcherKey: `po-att:${purchaseOrderId}:${safeName}`
- });
}
- // Revalidate to pick up new server-side rows
- setTimeout(() => revalidator.revalidate(), 250);
+ revalidator.revalidate();
} finally {
setUploading(false);
}
},
- [carbon, company.id, purchaseOrderId, revalidator, submit, t]
+ [carbon, company.id, supplierInteractionId, revalidator, t]
);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
@@ -155,6 +115,19 @@ export default function AttachmentsList({
multiple: true
});
+ const onRemovePoFile = useCallback(
+ async (a: ResolvedAttachmentItem) => {
+ if (!carbon) return;
+ const result = await carbon.storage.from("private").remove([a.path]);
+ if (result.error) {
+ toast.error(result.error.message || t`Error removing file`);
+ } else {
+ revalidator.revalidate();
+ }
+ },
+ [carbon, revalidator, t]
+ );
+
return (
<VStack spacing={2} className="w-full">
<div className="text-[11px] font-semibold uppercase text-muted-foreground">
@@ -162,111 +135,67 @@ export default function AttachmentsList({
</div>
<VStack spacing={1} className="w-full">
- {/* Pinned items: always sent */}
{pinned.map((p) => (
<HStack
key={`pinned-${p.name}`}
className="w-full justify-between border rounded-md px-3 py-2 bg-muted/30"
>
- <HStack className="gap-2">
- <Checkbox checked disabled />
- <LuFileText className="text-muted-foreground" />
- <span className="text-sm font-medium truncate max-w-[260px]">
+ <HStack className="gap-2 min-w-0 flex-1">
+ <LuFileText className="flex-shrink-0 text-muted-foreground" />
+ <span className="text-sm font-medium truncate min-w-0 flex-1">
{p.name}
</span>
- <Badge variant="gray">{p.label ?? t`PO PDF`}</Badge>
+ <Badge variant="gray" className="flex-shrink-0">
+ {p.label ?? t`PO PDF`}
+ </Badge>
</HStack>
- <span className="text-xs font-mono text-muted-foreground whitespace-nowrap">
+ <span className="text-xs font-mono text-muted-foreground flex-shrink-0 ml-2 whitespace-nowrap">
{p.sizeKb ? convertKbToString(p.sizeKb) : "--"}
</span>
</HStack>
))}
- {/* Cascaded + ad-hoc attachments */}
{attachments.length === 0 && pinned.length === 0 && (
<div className="text-sm text-muted-foreground italic px-3 py-2">
- <Trans>No attachments yet.</Trans>
+ <Trans>No attachments.</Trans>
</div>
)}
- {[...attachments]
- .sort((a, b) => {
- // Sort priority:
- // 1. Locked first (mandatory attachments float to top)
- // 2. Source: Company → Supplier → Item → PO (broadest-scope first,
- // most-specific last). Within each, alphabetical by name.
- if (a.isLocked !== b.isLocked) return a.isLocked ? -1 : 1;
- const sourceRank: Record<ResolvedAttachmentItem["source"], number> =
- {
- company: 0,
- supplier: 1,
- item: 2,
- po: 3
- };
- if (a.source !== b.source)
- return sourceRank[a.source] - sourceRank[b.source];
- return a.name.localeCompare(b.name);
- })
- .map((a) => {
- const included = isIncluded(a);
- return (
- <HStack
- key={a.documentId}
- className={`w-full justify-between border rounded-md px-3 py-2 ${
- a.shareOnSend ? "" : "opacity-50"
- }`}
- >
- <HStack className="gap-2">
- <Checkbox
- checked={included}
- disabled={!a.shareOnSend || a.isLocked}
- onCheckedChange={(c) => toggle(a.documentId, c === true)}
- />
- <LuFileText className="text-muted-foreground" />
- <span className="text-sm truncate max-w-[200px]">
- {a.name}
- </span>
- <Badge variant={sourceBadgeVariant[a.source]}>
- {a.sourceLabel}
- </Badge>
- {a.isLocked && (
- <LuLock
- className="w-3 h-3 text-amber-600"
- aria-label={t`Locked`}
- />
- )}
- {!a.shareOnSend && (
- <Badge variant="secondary">
- <Trans>Internal only</Trans>
- </Badge>
- )}
- </HStack>
- <HStack className="gap-2">
- <span className="text-xs font-mono text-muted-foreground whitespace-nowrap">
- {a.size ? convertKbToString(a.size) : "--"}
- </span>
- {a.source === "po" && a.attachmentRowId && !a.isLocked && (
- <DeletePoAttachmentButton
- purchaseOrderId={purchaseOrderId}
- attachmentRowId={a.attachmentRowId}
- />
- )}
- </HStack>
- </HStack>
- );
- })}
- {/* Hidden inputs carrying the included document IDs to the form action */}
- {includedIds.map((id, i) => (
- <input
- key={id}
- type="hidden"
- name={`${fieldName}[${i}]`}
- value={id}
- />
+ {attachments.map((a) => (
+ <HStack
+ key={a.path}
+ className="w-full justify-between border rounded-md px-3 py-2"
+ >
+ <HStack className="gap-2 min-w-0 flex-1">
+ <LuFileText className="flex-shrink-0 text-muted-foreground" />
+ <span className="text-sm truncate min-w-0 flex-1">{a.name}</span>
+ <Badge
+ variant={sourceBadgeVariant[a.source]}
+ className="flex-shrink-0"
+ >
+ {a.sourceLabel}
+ </Badge>
+ </HStack>
+ <HStack className="gap-2 flex-shrink-0 ml-2">
+ <span className="text-xs font-mono text-muted-foreground whitespace-nowrap">
+ {a.size != null ? convertKbToString(a.size) : "--"}
+ </span>
+ {a.source === "po" && (
+ <IconButton
+ aria-label={t`Remove`}
+ icon={<LuX />}
+ size="sm"
+ variant="ghost"
+ onClick={() => onRemovePoFile(a)}
+ />
+ )}
+ </HStack>
+ </HStack>
))}
</VStack>
- {/* Drag-and-drop */}
+ {/* Drag-and-drop — uploads to the supplier-interaction folder, which the
+ send action automatically picks up. */}
<div
{...getRootProps()}
className={`mt-2 w-full border-2 border-dashed rounded-md p-4 text-center cursor-pointer transition-colors ${
@@ -288,7 +217,6 @@ export default function AttachmentsList({
)}
</div>
- {/* Size meter */}
<div
className={`w-full text-xs font-mono ${
overLimit
@@ -315,36 +243,3 @@ export default function AttachmentsList({
</VStack>
);
}
-
-function DeletePoAttachmentButton({
- purchaseOrderId,
- attachmentRowId
-}: {
- purchaseOrderId: string;
- attachmentRowId: string;
-}) {
- const fetcher = useFetcher<{ success: boolean }>();
- const { t } = useLingui();
-
- return (
- <IconButton
- aria-label={t`Remove`}
- icon={<LuX />}
- size="sm"
- variant="ghost"
- isDisabled={fetcher.state !== "idle"}
- onClick={() =>
- fetcher.submit(
- {},
- {
- method: "post",
- action: path.to.purchaseOrderAttachmentDelete(
- purchaseOrderId,
- attachmentRowId
- )
- }
- )
- }
- />
- );
-}
diff --git a/apps/erp/app/components/CompanyDefaultAttachmentsCard.tsx b/apps/erp/app/components/CompanyDefaultAttachmentsCard.tsx
index 77f6601a8a..78f25869ef 100644
--- a/apps/erp/app/components/CompanyDefaultAttachmentsCard.tsx
+++ b/apps/erp/app/components/CompanyDefaultAttachmentsCard.tsx
@@ -1,22 +1,17 @@
import { Trans } from "@lingui/react/macro";
-import { path } from "~/utils/path";
import DefaultAttachmentsPanel, {
- type DefaultAttachment
+ type StorageFile
} from "./DefaultAttachmentsPanel";
type Props = {
- attachments: DefaultAttachment[];
+ files: StorageFile[];
};
-export default function CompanyDefaultAttachmentsCard({ attachments }: Props) {
+export default function CompanyDefaultAttachmentsCard({ files }: Props) {
return (
<DefaultAttachmentsPanel
- attachments={attachments}
+ files={files}
storagePathPrefix="default-attachments/company"
- uploadAction={path.to.companyDefaultAttachments}
- deleteAction={path.to.companyDefaultAttachmentDelete}
- lockAction={path.to.companyDefaultAttachmentLock}
- fetcherKeyPrefix="company-default"
title={<Trans>Default Attachments</Trans>}
description={
<Trans>
diff --git a/apps/erp/app/components/DefaultAttachmentsPanel.tsx b/apps/erp/app/components/DefaultAttachmentsPanel.tsx
index 7d6b6a3e27..711718c4d6 100644
--- a/apps/erp/app/components/DefaultAttachmentsPanel.tsx
+++ b/apps/erp/app/components/DefaultAttachmentsPanel.tsx
@@ -1,6 +1,5 @@
import { useCarbon } from "@carbon/auth";
import {
- Badge,
Card,
CardContent,
CardDescription,
@@ -31,11 +30,9 @@ import {
LuCloudUpload,
LuDownload,
LuEllipsisVertical,
- LuLock,
- LuLockOpen,
LuTrash
} from "react-icons/lu";
-import { useFetcher, useRevalidator, useSubmit } from "react-router";
+import { useRevalidator } from "react-router";
import DocumentIcon from "~/components/DocumentIcon";
import DocumentPreview from "~/components/DocumentPreview";
import { useDateFormatter, useUser } from "~/hooks";
@@ -43,63 +40,53 @@ import { getDocumentType } from "~/modules/shared";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
-export type DefaultAttachment = {
- id: string;
- documentId: string;
- shareOnSend: boolean;
- isLocked: boolean;
- document: {
- name: string;
- size: number | null;
- path: string | null;
- createdAt: string | null;
- } | null;
+/**
+ * Shape returned by Supabase `storage.from("private").list(...)`.
+ * Trimmed to the bits this component actually uses.
+ */
+export type StorageFile = {
+ name: string;
+ created_at?: string | null;
+ metadata?: { size?: number } | null;
};
type Props = {
- attachments: DefaultAttachment[];
- /** Where uploaded files are stored, relative to the company root. */
+ files: StorageFile[];
+ /**
+ * Storage path under the `private` bucket where files live (and uploads
+ * go). Should NOT include the leading `{companyId}/` prefix — that's added
+ * automatically from the current user's company.
+ *
+ * Example: "default-attachments/company", "default-attachments/supplier/sup_123"
+ */
storagePathPrefix: string;
- /** Action URL the metadata POSTs to after upload. */
- uploadAction: string;
- /** Builder for the per-attachment delete action URL. */
- deleteAction: (attachmentId: string) => string;
- /** Builder for the per-attachment lock-toggle action URL. */
- lockAction: (attachmentId: string) => string;
- /** Card title text. */
title: ReactNode;
- /** Card description text. */
description: ReactNode;
- /** Stable prefix for fetcherKey (avoids cross-panel collisions). */
- fetcherKeyPrefix: string;
};
const PREVIEWABLE = new Set(["PDF", "Image"]);
/**
* Generic management UI for default attachments at any scope
- * (company / supplier / item). Drag-and-drop upload + list + per-row
- * download/delete actions, with hover preview for PDF/image.
+ * (company / supplier / item). Drag-and-drop upload, list, download, delete —
+ * all directly against Supabase storage. Same pattern as Documents.tsx.
*/
export default function DefaultAttachmentsPanel({
- attachments,
+ files,
storagePathPrefix,
- uploadAction,
- deleteAction,
- lockAction,
title,
- description,
- fetcherKeyPrefix
+ description
}: Props) {
const { t } = useLingui();
const { formatDate } = useDateFormatter();
const { carbon } = useCarbon();
const { company } = useUser();
const revalidator = useRevalidator();
- const submit = useSubmit();
- const deleteFetcher = useFetcher();
- const lockFetcher = useFetcher();
const [uploading, setUploading] = useState(false);
+ const [deletingPath, setDeletingPath] = useState<string | null>(null);
+
+ const fullPath = (name: string) =>
+ `${company.id}/${storagePathPrefix}/${name}`;
const onDrop = useCallback(
async (acceptedFiles: File[]) => {
@@ -111,7 +98,7 @@ export default function DefaultAttachmentsPanel({
try {
for (const file of acceptedFiles) {
const safeName = stripSpecialCharacters(file.name);
- const storagePath = `${company.id}/${storagePathPrefix}/${safeName}`;
+ const storagePath = fullPath(safeName);
const upload = await carbon.storage
.from("private")
@@ -122,36 +109,15 @@ export default function DefaultAttachmentsPanel({
if (upload.error) {
toast.error(t`Failed to upload ${file.name}`);
- continue;
}
-
- const fd = new FormData();
- fd.append("path", storagePath);
- fd.append("name", file.name);
- fd.append("size", Math.round(file.size / 1024).toString());
-
- submit(fd, {
- method: "post",
- action: uploadAction,
- navigate: false,
- fetcherKey: `${fetcherKeyPrefix}:${safeName}`
- });
}
- setTimeout(() => revalidator.revalidate(), 250);
+ revalidator.revalidate();
} finally {
setUploading(false);
}
},
- [
- carbon,
- company.id,
- fetcherKeyPrefix,
- revalidator,
- storagePathPrefix,
- submit,
- t,
- uploadAction
- ]
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [carbon, company.id, storagePathPrefix, revalidator, t]
);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
@@ -159,9 +125,9 @@ export default function DefaultAttachmentsPanel({
multiple: true
});
- const download = useCallback(
- async (file: { name: string; path: string }) => {
- const url = path.to.file.previewFile(`private/${file.path}`);
+ const onDownload = useCallback(
+ async (name: string) => {
+ const url = path.to.file.previewFile(`private/${fullPath(name)}`);
try {
const response = await fetch(url);
const blob = await response.blob();
@@ -169,7 +135,7 @@ export default function DefaultAttachmentsPanel({
const a = document.createElement("a");
document.body.appendChild(a);
a.href = blobUrl;
- a.download = file.name;
+ a.download = name;
a.click();
window.URL.revokeObjectURL(blobUrl);
document.body.removeChild(a);
@@ -178,7 +144,34 @@ export default function DefaultAttachmentsPanel({
console.error(err);
}
},
- [t]
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [company.id, storagePathPrefix, t]
+ );
+
+ const onDelete = useCallback(
+ async (name: string) => {
+ if (!carbon) {
+ toast.error(t`Storage client not available`);
+ return;
+ }
+ const storagePath = fullPath(name);
+ setDeletingPath(storagePath);
+ try {
+ const result = await carbon.storage
+ .from("private")
+ .remove([storagePath]);
+ if (result.error) {
+ toast.error(result.error.message || t`Error deleting file`);
+ } else {
+ toast.success(t`${name} deleted`);
+ revalidator.revalidate();
+ }
+ } finally {
+ setDeletingPath(null);
+ }
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [carbon, company.id, storagePathPrefix, revalidator, t]
);
return (
@@ -204,70 +197,56 @@ export default function DefaultAttachmentsPanel({
</Tr>
</Thead>
<Tbody>
- {[...attachments]
- .sort((a, b) => {
- // Locked first, then by name for stable ordering.
- if (a.isLocked !== b.isLocked) return a.isLocked ? -1 : 1;
- const an = a.document?.name ?? "";
- const bn = b.document?.name ?? "";
- return an.localeCompare(bn);
- })
- .map((a) => {
- const doc = a.document;
- if (!doc) return null;
- const type = getDocumentType(doc.name);
+ {files
+ .slice()
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((f) => {
+ const type = getDocumentType(f.name);
const isPreviewable = PREVIEWABLE.has(type);
- const filePath = doc.path ?? "";
+ const filePath = fullPath(f.name);
+ const sizeKb =
+ f.metadata?.size != null
+ ? Math.round(f.metadata.size / 1024)
+ : null;
return (
- <Tr key={a.id}>
+ <Tr key={f.name}>
<Td className="max-w-0">
<HStack className="gap-2 min-w-0 w-full">
<DocumentIcon type={type} />
<span
className="font-medium truncate cursor-pointer min-w-0 flex-1"
onClick={() => {
- if (isPreviewable && filePath) {
+ if (isPreviewable) {
window.open(
path.to.file.previewFile(`private/${filePath}`),
"_blank"
);
- } else if (filePath) {
- download({ name: doc.name, path: filePath });
+ } else {
+ onDownload(f.name);
}
}}
>
- {isPreviewable && filePath ? (
+ {isPreviewable ? (
<DocumentPreview
bucket="private"
pathToFile={filePath}
// @ts-ignore — type is a string union the preview accepts
type={type}
>
- {doc.name}
+ {f.name}
</DocumentPreview>
) : (
- doc.name
+ f.name
)}
</span>
- {a.isLocked && (
- <LuLock
- className="w-3 h-3 text-amber-600"
- aria-label={t`Locked`}
- />
- )}
- {!a.shareOnSend && (
- <Badge variant="secondary">
- <Trans>Internal only</Trans>
- </Badge>
- )}
</HStack>
</Td>
<Td className="text-xs font-mono whitespace-nowrap">
- {doc.size ? convertKbToString(doc.size) : "--"}
+ {sizeKb != null ? convertKbToString(sizeKb) : "--"}
</Td>
<Td className="text-xs font-mono whitespace-nowrap">
- {doc.createdAt ? formatDate(doc.createdAt) : "--"}
+ {f.created_at ? formatDate(f.created_at) : "--"}
</Td>
<Td>
<div className="flex justify-end w-full">
@@ -281,50 +260,15 @@ export default function DefaultAttachmentsPanel({
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
- disabled={lockFetcher.state !== "idle"}
- onClick={() =>
- lockFetcher.submit(
- { locked: a.isLocked ? "false" : "true" },
- {
- method: "post",
- action: lockAction(a.id)
- }
- )
- }
- >
- <DropdownMenuIcon
- icon={a.isLocked ? <LuLockOpen /> : <LuLock />}
- />
- {a.isLocked ? (
- <Trans>Unlock</Trans>
- ) : (
- <Trans>Lock</Trans>
- )}
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!filePath}
- onClick={() =>
- filePath &&
- download({ name: doc.name, path: filePath })
- }
+ onClick={() => onDownload(f.name)}
>
<DropdownMenuIcon icon={<LuDownload />} />
<Trans>Download</Trans>
</DropdownMenuItem>
<DropdownMenuItem
destructive
- disabled={
- a.isLocked || deleteFetcher.state !== "idle"
- }
- onClick={() =>
- deleteFetcher.submit(
- {},
- {
- method: "post",
- action: deleteAction(a.id)
- }
- )
- }
+ disabled={deletingPath === filePath}
+ onClick={() => onDelete(f.name)}
>
<DropdownMenuIcon icon={<LuTrash />} />
<Trans>Delete</Trans>
@@ -336,7 +280,7 @@ export default function DefaultAttachmentsPanel({
</Tr>
);
})}
- {attachments.length === 0 && (
+ {files.length === 0 && (
<Tr>
<Td
colSpan={4}
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index e23ded1293..9151d16d38 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -269,10 +269,7 @@ export const purchaseOrderFinalizeValidator = z
.object({
notification: z.enum(["Email", "None"]).optional(),
supplierContact: zfd.text(z.string().optional()),
- cc: z.array(z.string()).optional(),
- // documentIds the user chose to include on this send. When omitted, every
- // resolved attachment with shareOnSend=true is attached.
- attachmentDocumentIds: z.array(z.string()).optional()
+ cc: z.array(z.string()).optional()
})
.refine(
(data) => (data.notification === "Email" ? data.supplierContact : true),
@@ -282,12 +279,6 @@ export const purchaseOrderFinalizeValidator = z
}
);
-// Validator for adding a default attachment at any scope.
-export const defaultAttachmentValidator = z.object({
- documentId: z.string().min(1, { message: "Document is required" }),
- shareOnSend: zfd.checkbox()
-});
-
export const purchaseOrderApprovalValidator = z
.object({
approvalRequestId: z
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 06bd1199a1..6b28c8e36c 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -2220,338 +2220,155 @@ export async function getPurchasingRFQSuppliersWithLinks(
}
// ===========================================================================
-// PO + default attachments
+// PO attachments (storage-list pattern)
+//
+// Matches the convention used by Supplier Quote / Purchasing RFQ flows
+// (see getSupplierInteractionDocuments / getSupplierInteractionLineDocuments).
+// Files are stored under predictable storage paths and listed at send time.
+// No DB tables, no per-file metadata, no picker.
// ===========================================================================
export type ResolvedAttachment = {
- documentId: string;
- /** When source === "po", the id of the purchaseOrderAttachment row so the UI can delete it. */
- attachmentRowId: string | null;
source: "po" | "company" | "supplier" | "item";
sourceLabel: string;
- shareOnSend: boolean;
- /** When true, the buyer cannot uncheck this attachment on the finalize modal. */
- isLocked: boolean;
name: string;
size: number | null;
+ /** Full storage path under the `private` bucket — pass to createSignedUrl. */
path: string;
};
-const documentSelect = "id, name, size, path, type, createdAt, createdBy";
-
-export async function getPurchaseOrderAttachments(
- client: SupabaseClient<Database>,
- purchaseOrderId: string
-) {
- return client
- .from("purchaseOrderAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("purchaseOrderId", purchaseOrderId);
-}
-
-export async function insertPurchaseOrderAttachment(
- client: SupabaseClient<Database>,
- args: {
- purchaseOrderId: string;
- documentId: string;
- shareOnSend?: boolean;
- companyId: string;
- createdBy: string;
- }
-) {
- return client.from("purchaseOrderAttachment").insert({
- purchaseOrderId: args.purchaseOrderId,
- documentId: args.documentId,
- shareOnSend: args.shareOnSend ?? true,
- companyId: args.companyId,
- createdBy: args.createdBy
- });
-}
-
-export async function deletePurchaseOrderAttachment(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("purchaseOrderAttachment").delete().eq("id", id);
-}
-
-export async function getCompanyDefaultAttachments(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client
- .from("companyDefaultAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("companyId", companyId);
-}
-
-export async function insertCompanyDefaultAttachment(
- client: SupabaseClient<Database>,
- args: {
- companyId: string;
- documentId: string;
- shareOnSend?: boolean;
- createdBy: string;
- }
-) {
- return client.from("companyDefaultAttachment").insert({
- companyId: args.companyId,
- documentId: args.documentId,
- shareOnSend: args.shareOnSend ?? true,
- createdBy: args.createdBy
- });
-}
-
-export async function deleteCompanyDefaultAttachment(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("companyDefaultAttachment").delete().eq("id", id);
-}
-
-export async function getSupplierDefaultAttachments(
- client: SupabaseClient<Database>,
- supplierId: string
-) {
- return client
- .from("supplierDefaultAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("supplierId", supplierId);
-}
-
-export async function insertSupplierDefaultAttachment(
- client: SupabaseClient<Database>,
- args: {
- supplierId: string;
- documentId: string;
- shareOnSend?: boolean;
- companyId: string;
- createdBy: string;
- }
-) {
- return client.from("supplierDefaultAttachment").insert({
- supplierId: args.supplierId,
- documentId: args.documentId,
- shareOnSend: args.shareOnSend ?? true,
- companyId: args.companyId,
- createdBy: args.createdBy
- });
-}
-
-export async function deleteSupplierDefaultAttachment(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("supplierDefaultAttachment").delete().eq("id", id);
-}
-
-export async function getItemDefaultAttachments(
- client: SupabaseClient<Database>,
- itemId: string
-) {
- return client
- .from("itemDefaultAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("itemId", itemId);
-}
-
-export async function insertItemDefaultAttachment(
- client: SupabaseClient<Database>,
- args: {
- itemId: string;
- documentId: string;
- shareOnSend?: boolean;
- companyId: string;
- createdBy: string;
- }
-) {
- return client.from("itemDefaultAttachment").insert({
- itemId: args.itemId,
- documentId: args.documentId,
- shareOnSend: args.shareOnSend ?? true,
- companyId: args.companyId,
- createdBy: args.createdBy
- });
-}
-
-export async function deleteItemDefaultAttachment(
- client: SupabaseClient<Database>,
- id: string
-) {
- return client.from("itemDefaultAttachment").delete().eq("id", id);
-}
+const listAtPath = async (
+ client: SupabaseClient<Database>,
+ path: string
+): Promise<{ name: string; size: number | null }[]> => {
+ const result = await client.storage.from("private").list(path);
+ return (result.data ?? []).map((f) => ({
+ name: f.name,
+ size:
+ (f.metadata as { size?: number } | null | undefined)?.size != null
+ ? Math.round(((f.metadata as { size?: number }).size as number) / 1024)
+ : null
+ }));
+};
/**
- * Resolve the full cascaded attachment list for a PO:
- * Per-PO ad-hoc + Company defaults + Supplier defaults + per-Item defaults
- *
- * Deduped by documentId, with the most-specific source winning the label.
- * Specificity: po > item > supplier > company.
+ * Resolve every attachment that should ride along on a PO finalize email,
+ * by listing the four canonical storage folders:
+ * - Company defaults: {companyId}/default-attachments/company/*
+ * - Supplier defaults: {companyId}/default-attachments/supplier/{supplierId}/*
+ * - Item defaults: {companyId}/default-attachments/item/{itemId}/*
+ * - PO ad-hoc: {companyId}/supplier-interaction/{interactionId}/* (sans the PO PDF itself)
*
- * Pass `shareOnSendOnly=true` to filter to only the rows that should actually
- * ride along on an outbound email; otherwise every attachment is returned (for
- * UI display).
+ * Deduped by absolute storage path. Same-named files in different scopes count
+ * as separate attachments (different folders).
*/
export async function getResolvedPoAttachments(
client: SupabaseClient<Database>,
args: {
- purchaseOrderId: string;
- supplierId: string | null;
companyId: string;
- shareOnSendOnly?: boolean;
+ supplierId: string | null;
+ supplierInteractionId: string | null;
+ itemIds: string[];
+ /** Filename of the freshly-generated PO PDF — excluded from ad-hoc listing
+ * since the action attaches it separately. */
+ excludePoPdfFileName?: string;
}
): Promise<ResolvedAttachment[]> {
- const { purchaseOrderId, supplierId, companyId, shareOnSendOnly } = args;
-
- const linesResult = await client
- .from("purchaseOrderLine")
- .select("itemId, item:itemId(readableIdWithRevision)")
- .eq("purchaseOrderId", purchaseOrderId);
-
- const itemIds = Array.from(
- new Set(
- (linesResult.data ?? [])
- .map((l) => l.itemId)
- .filter((id): id is string => !!id)
- )
+ const {
+ companyId,
+ supplierId,
+ supplierInteractionId,
+ itemIds,
+ excludePoPdfFileName
+ } = args;
+
+ const companyPrefix = `${companyId}/default-attachments/company`;
+ const supplierPrefix = supplierId
+ ? `${companyId}/default-attachments/supplier/${supplierId}`
+ : null;
+ const itemPrefixes = (itemIds ?? []).map(
+ (id) => `${companyId}/default-attachments/item/${id}`
);
- const itemLabelById = new Map<string, string>();
- for (const line of linesResult.data ?? []) {
- if (line.itemId && line.item) {
- // @ts-expect-error supabase nested-select shape
- itemLabelById.set(line.itemId, line.item.readableIdWithRevision ?? "");
- }
- }
+ const poPrefix = supplierInteractionId
+ ? `${companyId}/supplier-interaction/${supplierInteractionId}`
+ : null;
- const [poAtt, companyAtt, supplierAtt, itemAtt] = await Promise.all([
- client
- .from("purchaseOrderAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("purchaseOrderId", purchaseOrderId),
- client
- .from("companyDefaultAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("companyId", companyId),
- supplierId
- ? client
- .from("supplierDefaultAttachment")
- .select(`*, document:documentId(${documentSelect})`)
- .eq("supplierId", supplierId)
- : Promise.resolve({ data: [], error: null } as {
- data: any[];
- error: null;
- }),
- itemIds.length > 0
- ? client
- .from("itemDefaultAttachment")
- .select(`*, itemId, document:documentId(${documentSelect})`)
- .in("itemId", itemIds)
- : Promise.resolve({ data: [], error: null } as {
- data: any[];
- error: null;
- })
- ]);
+ const [companyFiles, supplierFiles, itemFilesByItem, poFiles] =
+ await Promise.all([
+ listAtPath(client, companyPrefix),
+ supplierPrefix ? listAtPath(client, supplierPrefix) : Promise.resolve([]),
+ Promise.all(itemPrefixes.map((p) => listAtPath(client, p))),
+ poPrefix ? listAtPath(client, poPrefix) : Promise.resolve([])
+ ]);
- const byDocId = new Map<string, ResolvedAttachment>();
- const specificity: Record<ResolvedAttachment["source"], number> = {
- company: 0,
- supplier: 1,
- item: 2,
- po: 3
- };
+ const byPath = new Map<string, ResolvedAttachment>();
+
+ for (const f of companyFiles) {
+ const path = `${companyPrefix}/${f.name}`;
+ if (!byPath.has(path))
+ byPath.set(path, {
+ source: "company",
+ sourceLabel: "From Company",
+ name: f.name,
+ size: f.size,
+ path
+ });
+ }
- const push = (entry: ResolvedAttachment) => {
- if (shareOnSendOnly && !entry.shareOnSend) return;
- if (!entry.documentId || !entry.path) return;
- const existing = byDocId.get(entry.documentId);
- if (!existing || specificity[entry.source] > specificity[existing.source]) {
- byDocId.set(entry.documentId, entry);
+ if (supplierPrefix) {
+ for (const f of supplierFiles) {
+ const path = `${supplierPrefix}/${f.name}`;
+ if (!byPath.has(path))
+ byPath.set(path, {
+ source: "supplier",
+ sourceLabel: "From Supplier",
+ name: f.name,
+ size: f.size,
+ path
+ });
}
- };
+ }
- for (const row of (companyAtt.data ?? []) as any[]) {
- if (!row.document) continue;
- push({
- documentId: row.documentId,
- attachmentRowId: null,
- source: "company",
- sourceLabel: "From Company",
- shareOnSend: row.shareOnSend,
- isLocked: row.isLocked ?? false,
- name: row.document.name,
- size: row.document.size ?? null,
- path: row.document.path
- });
- }
-
- for (const row of (supplierAtt.data ?? []) as any[]) {
- if (!row.document) continue;
- push({
- documentId: row.documentId,
- attachmentRowId: null,
- source: "supplier",
- sourceLabel: "From Supplier",
- shareOnSend: row.shareOnSend,
- isLocked: row.isLocked ?? false,
- name: row.document.name,
- size: row.document.size ?? null,
- path: row.document.path
- });
- }
-
- for (const row of (itemAtt.data ?? []) as any[]) {
- if (!row.document) continue;
- const label = itemLabelById.get(row.itemId);
- push({
- documentId: row.documentId,
- attachmentRowId: null,
- source: "item",
- sourceLabel: label ? `From Part ${label}` : "From Part",
- shareOnSend: row.shareOnSend,
- isLocked: row.isLocked ?? false,
- name: row.document.name,
- size: row.document.size ?? null,
- path: row.document.path
- });
- }
-
- for (const row of (poAtt.data ?? []) as any[]) {
- if (!row.document) continue;
- push({
- documentId: row.documentId,
- attachmentRowId: row.id,
- source: "po",
- sourceLabel: "Ad-hoc",
- shareOnSend: row.shareOnSend,
- isLocked: row.isLocked ?? false,
- name: row.document.name,
- size: row.document.size ?? null,
- path: row.document.path
- });
- }
-
- return Array.from(byDocId.values()).sort((a, b) =>
- a.name.localeCompare(b.name)
- );
-}
+ itemPrefixes.forEach((prefix, idx) => {
+ for (const f of itemFilesByItem[idx] ?? []) {
+ const path = `${prefix}/${f.name}`;
+ if (!byPath.has(path))
+ byPath.set(path, {
+ source: "item",
+ sourceLabel: "From Item",
+ name: f.name,
+ size: f.size,
+ path
+ });
+ }
+ });
-export async function setAttachmentLock(
- client: SupabaseClient<Database>,
- args: {
- table:
- | "purchaseOrderAttachment"
- | "companyDefaultAttachment"
- | "supplierDefaultAttachment"
- | "itemDefaultAttachment";
- id: string;
- isLocked: boolean;
+ if (poPrefix) {
+ for (const f of poFiles) {
+ // Skip the PO PDF we just generated — the action attaches it separately.
+ if (excludePoPdfFileName && f.name === excludePoPdfFileName) continue;
+ const path = `${poPrefix}/${f.name}`;
+ if (!byPath.has(path))
+ byPath.set(path, {
+ source: "po",
+ sourceLabel: "Ad-hoc",
+ name: f.name,
+ size: f.size,
+ path
+ });
+ }
}
-) {
- // @ts-expect-error column added in 20260518000001 migration; types regenerate later
- return client
- .from(args.table)
- .update({ isLocked: args.isLocked })
- .eq("id", args.id);
+
+ return Array.from(byPath.values()).sort((a, b) => {
+ const rank: Record<ResolvedAttachment["source"], number> = {
+ company: 0,
+ supplier: 1,
+ item: 2,
+ po: 3
+ };
+ if (a.source !== b.source) return rank[a.source] - rank[b.source];
+ return a.name.localeCompare(b.name);
+ });
}
// Hard upper bound for total outbound attachments. Most SMTP providers cap
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx
index f00e74a0f1..b01700f0ac 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderFinalizeModal.tsx
@@ -119,7 +119,9 @@ const PurchaseOrderFinalizeModal = ({
helperText={t`Type an email and press Enter to add an external recipient`}
/>
<AttachmentsList
- purchaseOrderId={orderId}
+ supplierInteractionId={
+ purchaseOrder?.supplierInteractionId ?? null
+ }
attachments={resolvedAttachments}
/>
</>
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index c0d5d43268..eb77e42c72 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-05-21T09:30:45.232Z",
+ "generated": "2026-05-22T05:14:46.487Z",
"totalTools": 1075,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/items+/default-attachments.$itemId.$attachmentId.delete.tsx b/apps/erp/app/routes/x+/items+/default-attachments.$itemId.$attachmentId.delete.tsx
deleted file mode 100644
index b591dfd456..0000000000
--- a/apps/erp/app/routes/x+/items+/default-attachments.$itemId.$attachmentId.delete.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { deleteItemDefaultAttachment } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- delete: "parts"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const result = await deleteItemDefaultAttachment(client, attachmentId);
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to delete attachment"))
- );
- }
- return data(
- { success: true },
- await flash(request, success("Default attachment removed"))
- );
-}
diff --git a/apps/erp/app/routes/x+/items+/default-attachments.$itemId.$attachmentId.lock.tsx b/apps/erp/app/routes/x+/items+/default-attachments.$itemId.$attachmentId.lock.tsx
deleted file mode 100644
index 5d22addae6..0000000000
--- a/apps/erp/app/routes/x+/items+/default-attachments.$itemId.$attachmentId.lock.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { setAttachmentLock } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "parts"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const formData = await request.formData();
- const isLocked = formData.get("locked") === "true";
-
- const result = await setAttachmentLock(client, {
- table: "itemDefaultAttachment",
- id: attachmentId,
- isLocked
- });
-
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to update lock"))
- );
- }
- return data(
- { success: true },
- await flash(
- request,
- success(isLocked ? "Attachment locked" : "Attachment unlocked")
- )
- );
-}
diff --git a/apps/erp/app/routes/x+/items+/default-attachments.$itemId.tsx b/apps/erp/app/routes/x+/items+/default-attachments.$itemId.tsx
deleted file mode 100644
index b94035c166..0000000000
--- a/apps/erp/app/routes/x+/items+/default-attachments.$itemId.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { upsertDocument } from "~/modules/documents";
-import { insertItemDefaultAttachment } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "parts"
- });
-
- const { itemId } = params;
- if (!itemId) throw new Error("Missing itemId");
-
- const formData = await request.formData();
- const documentPath = formData.get("path");
- const name = formData.get("name");
- const sizeRaw = formData.get("size");
-
- if (typeof documentPath !== "string" || typeof name !== "string") {
- return data(
- { success: false, message: "Missing fields" },
- await flash(request, error("Missing fields", "Failed to add attachment"))
- );
- }
-
- const created = await upsertDocument(client, {
- path: documentPath,
- name,
- size: Number(sizeRaw),
- // @ts-expect-error enum value added in 20260518000001 migration; types regenerate later
- sourceDocument: "Item",
- sourceDocumentId: itemId,
- readGroups: [userId],
- writeGroups: [userId],
- createdBy: userId,
- companyId
- });
-
- if (created.error || !created.data?.id) {
- return data(
- { success: false, message: "Failed to create document" },
- await flash(request, error(created.error, "Failed to create document"))
- );
- }
-
- const linked = await insertItemDefaultAttachment(client, {
- itemId,
- documentId: created.data.id,
- shareOnSend: true,
- companyId,
- createdBy: userId
- });
-
- if (linked.error) {
- return data(
- { success: false, message: "Failed to link" },
- await flash(request, error(linked.error, "Failed to link attachment"))
- );
- }
-
- return { success: true, documentId: created.data.id };
-}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
index 693a641a25..e0be92304a 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
@@ -15,7 +15,7 @@ import type {
import { Await, redirect, useLoaderData, useParams } from "react-router";
import { CadModel, DeferredFiles } from "~/components";
import DefaultAttachmentsPanel, {
- type DefaultAttachment
+ type StorageFile
} from "~/components/DefaultAttachmentsPanel";
import { usePermissions, useRouteData } from "~/hooks";
import type { ItemFile, MakeMethod, PartSummary } from "~/modules/items";
@@ -42,7 +42,6 @@ import {
} from "~/modules/items/ui/Item";
import ItemManufacturingForm from "~/modules/items/ui/Item/ItemManufacturingForm";
import { ConfigurationParametersForm } from "~/modules/items/ui/Parts";
-import { getItemDefaultAttachments } from "~/modules/purchasing/purchasing.service";
import type { MethodItemType, MethodType } from "~/modules/shared";
import { getTagsList } from "~/modules/shared";
import { getCustomFields, setCustomFields } from "~/utils/form";
@@ -69,8 +68,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
: (makeMethods.data?.find((m) => m.status === "Active") ??
makeMethods.data?.[0]);
+ const listDefaultAttachments = () =>
+ client.storage
+ .from("private")
+ .list(`${companyId}/default-attachments/item/${itemId}`);
+
if (!makeMethod) {
- const fallback = await getItemDefaultAttachments(client, itemId);
+ const fallback = await listDefaultAttachments();
return {
methodData: null,
tags: [],
@@ -80,7 +84,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);
if (fullMethod.error || !fullMethod.data) {
- const fallback = await getItemDefaultAttachments(client, itemId);
+ const fallback = await listDefaultAttachments();
return {
methodData: null,
tags: [],
@@ -93,13 +97,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
methodOperations,
tags,
partManufacturing,
- defaultAttachments
+ defaultAttachmentsResult
] = await Promise.all([
getMethodMaterialsByMakeMethod(client, fullMethod.data.id),
getMethodOperationsByMakeMethodId(client, fullMethod.data.id),
getTagsList(client, companyId, "operation"),
getItemManufacturing(client, itemId, companyId),
- getItemDefaultAttachments(client, itemId)
+ listDefaultAttachments()
]);
const configData = partManufacturing.data?.requiresConfiguration
@@ -142,7 +146,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
...configData
},
tags: tags.data ?? [],
- defaultAttachments: defaultAttachments.data ?? []
+ defaultAttachments: defaultAttachmentsResult.data ?? []
};
}
@@ -350,16 +354,8 @@ export default function PartDetailsRoute() {
</DeferredFiles>
<DefaultAttachmentsPanel
- attachments={(defaultAttachments ?? []) as DefaultAttachment[]}
+ files={(defaultAttachments ?? []) as StorageFile[]}
storagePathPrefix={`default-attachments/item/${itemId}`}
- uploadAction={path.to.itemDefaultAttachments(itemId)}
- deleteAction={(attachmentId) =>
- path.to.itemDefaultAttachmentDelete(itemId, attachmentId)
- }
- lockAction={(attachmentId) =>
- path.to.itemDefaultAttachmentLock(itemId, attachmentId)
- }
- fetcherKeyPrefix={`item-default:${itemId}`}
title={t`Default Attachments on Purchase Orders`}
description={t`Files attached here ride along whenever this item appears on a purchase order email.`}
/>
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.$attachmentId.delete.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.$attachmentId.delete.tsx
deleted file mode 100644
index 010df16928..0000000000
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.$attachmentId.delete.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { deletePurchaseOrderAttachment } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- delete: "purchasing"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const result = await deletePurchaseOrderAttachment(client, attachmentId);
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to delete attachment"))
- );
- }
-
- return data(
- { success: true },
- await flash(request, success("Attachment removed"))
- );
-}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.$attachmentId.lock.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.$attachmentId.lock.tsx
deleted file mode 100644
index 88942d840d..0000000000
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.$attachmentId.lock.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { setAttachmentLock } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "purchasing"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const formData = await request.formData();
- const isLocked = formData.get("locked") === "true";
-
- const result = await setAttachmentLock(client, {
- table: "purchaseOrderAttachment",
- id: attachmentId,
- isLocked
- });
-
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to update lock"))
- );
- }
- return data(
- { success: true },
- await flash(
- request,
- success(isLocked ? "Attachment locked" : "Attachment unlocked")
- )
- );
-}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.tsx
deleted file mode 100644
index 785d63437b..0000000000
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.attachments.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { upsertDocument } from "~/modules/documents";
-import { insertPurchaseOrderAttachment } from "~/modules/purchasing";
-
-/**
- * Link an ad-hoc attachment to a purchase order.
- *
- * Flow: client first uploads the file to Supabase storage at the canonical
- * path, then POSTs the metadata here. We create the document record + the
- * purchaseOrderAttachment junction row in one shot.
- */
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing"
- });
-
- const { orderId } = params;
- if (!orderId) throw new Error("Missing orderId");
-
- const formData = await request.formData();
- const documentPath = formData.get("path");
- const name = formData.get("name");
- const sizeRaw = formData.get("size");
-
- if (typeof documentPath !== "string" || !documentPath) {
- return data(
- { success: false, message: "Missing path" },
- await flash(request, error("Missing path", "Failed to add attachment"))
- );
- }
- if (typeof name !== "string" || !name) {
- return data(
- { success: false, message: "Missing name" },
- await flash(request, error("Missing name", "Failed to add attachment"))
- );
- }
- const size = Number(sizeRaw);
-
- const created = await upsertDocument(client, {
- path: documentPath,
- name,
- size,
- sourceDocument: "Purchase Order",
- sourceDocumentId: orderId,
- readGroups: [userId],
- writeGroups: [userId],
- createdBy: userId,
- companyId
- });
-
- if (created.error || !created.data?.id) {
- return data(
- { success: false, message: "Failed to create document" },
- await flash(request, error(created.error, "Failed to create document"))
- );
- }
-
- const linked = await insertPurchaseOrderAttachment(client, {
- purchaseOrderId: orderId,
- documentId: created.data.id,
- shareOnSend: true,
- companyId,
- createdBy: userId
- });
-
- if (linked.error) {
- return data(
- { success: false, message: "Failed to link attachment" },
- await flash(
- request,
- error(linked.error, "Failed to link attachment to purchase order")
- )
- );
- }
-
- return { success: true, documentId: created.data.id };
-}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index 15407e6022..445face6ae 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -273,12 +273,7 @@ export async function action(args: ActionFunctionArgs) {
return validationError(validation.error);
}
- const {
- notification,
- supplierContact,
- cc: ccSelections,
- attachmentDocumentIds
- } = validation.data;
+ const { notification, supplierContact, cc: ccSelections } = validation.data;
const logPrefix = `[finalize PO ${orderId}]`;
@@ -286,8 +281,7 @@ export async function action(args: ActionFunctionArgs) {
case "Email":
console.log(`${logPrefix} email branch entered`, {
supplierContact,
- ccCount: ccSelections?.length ?? 0,
- attachmentDocumentIdsCount: attachmentDocumentIds?.length ?? 0
+ ccCount: ccSelections?.length ?? 0
});
try {
if (!supplierContact) throw new Error("Supplier contact is required");
@@ -371,11 +365,20 @@ export async function action(args: ActionFunctionArgs) {
const signedUrlData = signedMainPdf.data;
// Resolve cascaded attachments (Company + Supplier + Item + PO ad-hoc).
+ const itemIds = Array.from(
+ new Set(
+ (purchaseOrderLines.data ?? [])
+ .map((l) => l.itemId)
+ .filter((id): id is string => !!id)
+ )
+ );
const resolved = await getResolvedPoAttachments(serviceRole, {
- purchaseOrderId: orderId,
- supplierId: purchaseOrder.data.supplierId ?? null,
companyId,
- shareOnSendOnly: true
+ supplierId: purchaseOrder.data.supplierId ?? null,
+ supplierInteractionId:
+ purchaseOrder.data.supplierInteractionId ?? null,
+ itemIds,
+ excludePoPdfFileName: fileName
});
console.log(`${logPrefix} resolved cascaded attachments`, {
total: resolved.length,
@@ -385,20 +388,9 @@ export async function action(args: ActionFunctionArgs) {
}, {})
});
- const selectedSet = attachmentDocumentIds?.length
- ? new Set(attachmentDocumentIds)
- : null;
- const filtered = selectedSet
- ? resolved.filter((r) => selectedSet.has(r.documentId))
- : resolved;
- console.log(`${logPrefix} after user selection filter`, {
- kept: filtered.length,
- dropped: resolved.length - filtered.length
- });
-
- // Enforce 25 MB total cap (PO PDF + cascaded attachments + optional T&C PDF).
+ // Enforce 25 MB total cap (PO PDF + cascaded attachments).
const poPdfSizeKb = Math.round(file.byteLength / 1024);
- const cascadedSizeKb = filtered.reduce(
+ const cascadedSizeKb = resolved.reduce(
(sum, r) => sum + (r.size ?? 0),
0
);
@@ -417,7 +409,7 @@ export async function action(args: ActionFunctionArgs) {
// Sign every cascaded attachment for the email job.
const cascadedAttachments = (
await Promise.all(
- filtered.map(async (r) => {
+ resolved.map(async (r) => {
const { data, error: signErr } = await serviceRole.storage
.from("private")
.createSignedUrl(r.path, 3600);
@@ -425,7 +417,6 @@ export async function action(args: ActionFunctionArgs) {
console.error(
`${logPrefix} failed to sign cascaded attachment`,
{
- documentId: r.documentId,
source: r.source,
name: r.name,
path: r.path,
@@ -439,7 +430,7 @@ export async function action(args: ActionFunctionArgs) {
)
).filter((a): a is { path: string; filename: string } => a !== null);
console.log(`${logPrefix} signed cascaded attachments`, {
- requested: filtered.length,
+ requested: resolved.length,
successful: cascadedAttachments.length
});
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 6b87a2a6a3..2f5366006e 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -427,10 +427,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
canDelete = isRequester;
}
+ const itemIds = Array.from(
+ new Set(
+ (lines.data ?? []).map((l) => l.itemId).filter((id): id is string => !!id)
+ )
+ );
const resolvedAttachments = await getResolvedPoAttachments(serviceRole, {
- purchaseOrderId: orderId,
+ companyId,
supplierId: purchaseOrder.data?.supplierId ?? null,
- companyId
+ supplierInteractionId: purchaseOrder.data?.supplierInteractionId ?? null,
+ itemIds
});
return {
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.$attachmentId.delete.tsx b/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.$attachmentId.delete.tsx
deleted file mode 100644
index b81c522817..0000000000
--- a/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.$attachmentId.delete.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { deleteCompanyDefaultAttachment } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- delete: "settings"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const result = await deleteCompanyDefaultAttachment(client, attachmentId);
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to delete attachment"))
- );
- }
- return data(
- { success: true },
- await flash(request, success("Default attachment removed"))
- );
-}
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.$attachmentId.lock.tsx b/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.$attachmentId.lock.tsx
deleted file mode 100644
index 4a0040a906..0000000000
--- a/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.$attachmentId.lock.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { setAttachmentLock } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "settings"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const formData = await request.formData();
- const isLocked = formData.get("locked") === "true";
-
- const result = await setAttachmentLock(client, {
- table: "companyDefaultAttachment",
- id: attachmentId,
- isLocked
- });
-
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to update lock"))
- );
- }
- return data(
- { success: true },
- await flash(
- request,
- success(isLocked ? "Attachment locked" : "Attachment unlocked")
- )
- );
-}
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.tsx b/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.tsx
deleted file mode 100644
index c016d8a2cc..0000000000
--- a/apps/erp/app/routes/x+/settings+/purchasing.default-attachments.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { upsertDocument } from "~/modules/documents";
-import { insertCompanyDefaultAttachment } from "~/modules/purchasing";
-
-/**
- * Add a new company-level default attachment.
- * Client first uploads to storage, then POSTs metadata here.
- */
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "settings"
- });
-
- const formData = await request.formData();
- const documentPath = formData.get("path");
- const name = formData.get("name");
- const sizeRaw = formData.get("size");
-
- if (typeof documentPath !== "string" || !documentPath) {
- return data(
- { success: false, message: "Missing path" },
- await flash(request, error("Missing path", "Failed to add attachment"))
- );
- }
- if (typeof name !== "string" || !name) {
- return data(
- { success: false, message: "Missing name" },
- await flash(request, error("Missing name", "Failed to add attachment"))
- );
- }
-
- const created = await upsertDocument(client, {
- path: documentPath,
- name,
- size: Number(sizeRaw),
- sourceDocument: "Company",
- sourceDocumentId: companyId,
- readGroups: [userId],
- writeGroups: [userId],
- createdBy: userId,
- companyId
- });
-
- if (created.error || !created.data?.id) {
- return data(
- { success: false, message: "Failed to create document" },
- await flash(request, error(created.error, "Failed to create document"))
- );
- }
-
- const linked = await insertCompanyDefaultAttachment(client, {
- companyId,
- documentId: created.data.id,
- shareOnSend: true,
- createdBy: userId
- });
-
- if (linked.error) {
- return data(
- { success: false, message: "Failed to link" },
- await flash(request, error(linked.error, "Failed to link attachment"))
- );
- }
-
- return { success: true, documentId: created.data.id };
-}
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsx
index bfad2a25cc..46b3f8c38c 100644
--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx
@@ -41,7 +41,6 @@ import CompanyDefaultAttachmentsCard from "~/components/CompanyDefaultAttachment
import { EmailRecipients, Users } from "~/components/Form";
import Country from "~/components/Form/Country";
import { usePermissions, useUser } from "~/hooks";
-import { getCompanyDefaultAttachments } from "~/modules/purchasing";
import {
accountsPayableBillingAddressValidator,
defaultSupplierCcValidator,
@@ -72,12 +71,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
view: "settings"
});
- const [companySettings, terms, apBillingAddress, defaultAttachments] =
+ const [companySettings, terms, apBillingAddress, defaultAttachmentsResult] =
await Promise.all([
getCompanySettings(client, companyId),
getTerms(client, companyId),
getAccountsPayableBillingAddress(client, companyId),
- getCompanyDefaultAttachments(client, companyId)
+ client.storage
+ .from("private")
+ .list(`${companyId}/default-attachments/company`)
]);
if (companySettings.error) {
@@ -101,7 +102,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
companySettings: companySettings.data,
terms: terms.data,
apBillingAddress: apBillingAddress.data,
- defaultAttachments: defaultAttachments.data ?? []
+ defaultAttachments: defaultAttachmentsResult.data ?? []
};
}
@@ -455,7 +456,7 @@ export default function PurchasingSettingsRoute() {
</CardContent>
</Card>
<CompanyDefaultAttachmentsCard
- attachments={(defaultAttachments ?? []) as any}
+ files={(defaultAttachments ?? []) as any}
/>
<Card>
<CardHeader>
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.$attachmentId.delete.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.$attachmentId.delete.tsx
deleted file mode 100644
index d9bf4739d0..0000000000
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.$attachmentId.delete.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { deleteSupplierDefaultAttachment } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- delete: "purchasing"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const result = await deleteSupplierDefaultAttachment(client, attachmentId);
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to delete attachment"))
- );
- }
- return data(
- { success: true },
- await flash(request, success("Default attachment removed"))
- );
-}
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.$attachmentId.lock.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.$attachmentId.lock.tsx
deleted file mode 100644
index d770720c8f..0000000000
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.$attachmentId.lock.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs } from "react-router";
-import { data } from "react-router";
-import { setAttachmentLock } from "~/modules/purchasing";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "purchasing"
- });
-
- const { attachmentId } = params;
- if (!attachmentId) throw new Error("Missing attachmentId");
-
- const formData = await request.formData();
- const isLocked = formData.get("locked") === "true";
-
- const result = await setAttachmentLock(client, {
- table: "supplierDefaultAttachment",
- id: attachmentId,
- isLocked
- });
-
- if (result.error) {
- return data(
- { success: false },
- await flash(request, error(result.error, "Failed to update lock"))
- );
- }
- return data(
- { success: true },
- await flash(
- request,
- success(isLocked ? "Attachment locked" : "Attachment unlocked")
- )
- );
-}
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx
index b29bb8c675..b354896487 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.default-attachments.tsx
@@ -1,107 +1,35 @@
-import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import { Trans } from "@lingui/react/macro";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, useLoaderData, useParams } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData } from "react-router";
import DefaultAttachmentsPanel, {
- type DefaultAttachment
+ type StorageFile
} from "~/components/DefaultAttachmentsPanel";
-import { upsertDocument } from "~/modules/documents";
-import {
- getSupplierDefaultAttachments,
- insertSupplierDefaultAttachment
-} from "~/modules/purchasing";
-import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "purchasing"
});
const { supplierId } = params;
if (!supplierId) throw new Error("Missing supplierId");
- const attachments = await getSupplierDefaultAttachments(client, supplierId);
- return { attachments: (attachments.data ?? []) as DefaultAttachment[] };
-}
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing"
- });
-
- const { supplierId } = params;
- if (!supplierId) throw new Error("Missing supplierId");
-
- const formData = await request.formData();
- const documentPath = formData.get("path");
- const name = formData.get("name");
- const sizeRaw = formData.get("size");
-
- if (typeof documentPath !== "string" || typeof name !== "string") {
- return data(
- { success: false, message: "Missing fields" },
- await flash(request, error("Missing fields", "Failed to add attachment"))
- );
- }
-
- const created = await upsertDocument(client, {
- path: documentPath,
- name,
- size: Number(sizeRaw),
- // @ts-expect-error enum value added in 20260518000001 migration; types regenerate later
- sourceDocument: "Supplier",
- sourceDocumentId: supplierId,
- readGroups: [userId],
- writeGroups: [userId],
- createdBy: userId,
- companyId
- });
-
- if (created.error || !created.data?.id) {
- return data(
- { success: false, message: "Failed to create document" },
- await flash(request, error(created.error, "Failed to create document"))
- );
- }
+ const result = await client.storage
+ .from("private")
+ .list(`${companyId}/default-attachments/supplier/${supplierId}`);
- const linked = await insertSupplierDefaultAttachment(client, {
+ return {
supplierId,
- documentId: created.data.id,
- shareOnSend: true,
- companyId,
- createdBy: userId
- });
-
- if (linked.error) {
- return data(
- { success: false, message: "Failed to link" },
- await flash(request, error(linked.error, "Failed to link attachment"))
- );
- }
-
- return { success: true, documentId: created.data.id };
+ files: (result.data ?? []) as StorageFile[]
+ };
}
export default function SupplierDefaultAttachmentsRoute() {
- const { supplierId } = useParams();
- if (!supplierId) throw new Error("Missing supplierId");
-
- const { attachments } = useLoaderData<typeof loader>();
+ const { supplierId, files } = useLoaderData<typeof loader>();
return (
<DefaultAttachmentsPanel
- attachments={attachments}
+ files={files}
storagePathPrefix={`default-attachments/supplier/${supplierId}`}
- uploadAction={path.to.supplierDefaultAttachments(supplierId)}
- deleteAction={(attachmentId) =>
- path.to.supplierDefaultAttachmentDelete(supplierId, attachmentId)
- }
- lockAction={(attachmentId) =>
- path.to.supplierDefaultAttachmentLock(supplierId, attachmentId)
- }
- fetcherKeyPrefix={`supplier-default:${supplierId}`}
title={<Trans>Default Attachments</Trans>}
description={
<Trans>
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 23da3312fa..e33a03cb26 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1393,48 +1393,8 @@ export const path = {
generatePath(`${x}/purchase-order/${id}/payment`),
purchaseOrderFinalize: (id: string) =>
generatePath(`${x}/purchase-order/${id}/finalize`),
- purchaseOrderAttachments: (id: string) =>
- generatePath(`${x}/purchase-order/${id}/attachments`),
- purchaseOrderAttachmentDelete: (orderId: string, attachmentId: string) =>
- generatePath(
- `${x}/purchase-order/${orderId}/attachments/${attachmentId}/delete`
- ),
- companyDefaultAttachments: `${x}/settings/purchasing/default-attachments`,
- companyDefaultAttachmentDelete: (attachmentId: string) =>
- generatePath(
- `${x}/settings/purchasing/default-attachments/${attachmentId}/delete`
- ),
supplierDefaultAttachments: (supplierId: string) =>
generatePath(`${x}/supplier/${supplierId}/default-attachments`),
- supplierDefaultAttachmentDelete: (
- supplierId: string,
- attachmentId: string
- ) =>
- generatePath(
- `${x}/supplier/${supplierId}/default-attachments/${attachmentId}/delete`
- ),
- itemDefaultAttachments: (itemId: string) =>
- generatePath(`${x}/items/default-attachments/${itemId}`),
- itemDefaultAttachmentDelete: (itemId: string, attachmentId: string) =>
- generatePath(
- `${x}/items/default-attachments/${itemId}/${attachmentId}/delete`
- ),
- purchaseOrderAttachmentLock: (orderId: string, attachmentId: string) =>
- generatePath(
- `${x}/purchase-order/${orderId}/attachments/${attachmentId}/lock`
- ),
- companyDefaultAttachmentLock: (attachmentId: string) =>
- generatePath(
- `${x}/settings/purchasing/default-attachments/${attachmentId}/lock`
- ),
- supplierDefaultAttachmentLock: (supplierId: string, attachmentId: string) =>
- generatePath(
- `${x}/supplier/${supplierId}/default-attachments/${attachmentId}/lock`
- ),
- itemDefaultAttachmentLock: (itemId: string, attachmentId: string) =>
- generatePath(
- `${x}/items/default-attachments/${itemId}/${attachmentId}/lock`
- ),
purchaseOrderRoot: `${x}/purchase-order`,
purchaseOrderStatus: (id: string) =>
generatePath(`${x}/purchase-order/${id}/status`),
diff --git a/packages/database/supabase/migrations/20260519000001_po-attachments.sql b/packages/database/supabase/migrations/20260519000001_po-attachments.sql
deleted file mode 100644
index 25d0a327f9..0000000000
--- a/packages/database/supabase/migrations/20260519000001_po-attachments.sql
+++ /dev/null
@@ -1,205 +0,0 @@
--- New documentSourceType values used by the cascading-default-attachment system.
--- "Company" tags company-wide defaults; "Supplier" tags per-supplier defaults;
--- "Item" tags per-item defaults. Used to scope storage paths + audit context.
-ALTER TYPE "documentSourceType" ADD VALUE IF NOT EXISTS 'Company';
-ALTER TYPE "documentSourceType" ADD VALUE IF NOT EXISTS 'Supplier';
-ALTER TYPE "documentSourceType" ADD VALUE IF NOT EXISTS 'Item';
-
-
--- ============================================================================
--- Per-PO ad-hoc attachments (drag-and-drop on the finalize modal)
--- ============================================================================
-CREATE TABLE "purchaseOrderAttachment" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "purchaseOrderId" TEXT NOT NULL,
- "documentId" TEXT NOT NULL,
- "shareOnSend" BOOLEAN NOT NULL DEFAULT true,
- "isLocked" BOOLEAN NOT NULL DEFAULT false,
- "companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
-
- CONSTRAINT "purchaseOrderAttachment_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "purchaseOrderAttachment_unique" UNIQUE ("purchaseOrderId", "documentId"),
- CONSTRAINT "purchaseOrderAttachment_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder"("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrderAttachment_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrderAttachment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrderAttachment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE SET NULL
-);
-
-CREATE INDEX "purchaseOrderAttachment_purchaseOrderId_idx" ON "purchaseOrderAttachment" ("purchaseOrderId");
-CREATE INDEX "purchaseOrderAttachment_companyId_idx" ON "purchaseOrderAttachment" ("companyId");
-
-ALTER TABLE "purchaseOrderAttachment" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Employees with purchasing_view can view purchaseOrderAttachment"
- ON "purchaseOrderAttachment" FOR SELECT USING (
- has_company_permission('purchasing_view', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with purchasing_create can insert purchaseOrderAttachment"
- ON "purchaseOrderAttachment" FOR INSERT WITH CHECK (
- has_company_permission('purchasing_create', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with purchasing_update can update purchaseOrderAttachment"
- ON "purchaseOrderAttachment" FOR UPDATE USING (
- has_company_permission('purchasing_update', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with purchasing_delete can delete purchaseOrderAttachment"
- ON "purchaseOrderAttachment" FOR DELETE USING (
- has_company_permission('purchasing_delete', "companyId") AND
- has_role('employee', "companyId")
- );
-
-
--- ============================================================================
--- Company-level default attachments (cascade to every PO)
--- ============================================================================
-CREATE TABLE "companyDefaultAttachment" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "companyId" TEXT NOT NULL,
- "documentId" TEXT NOT NULL,
- "shareOnSend" BOOLEAN NOT NULL DEFAULT true,
- "isLocked" BOOLEAN NOT NULL DEFAULT false,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
-
- CONSTRAINT "companyDefaultAttachment_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "companyDefaultAttachment_unique" UNIQUE ("companyId", "documentId"),
- CONSTRAINT "companyDefaultAttachment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
- CONSTRAINT "companyDefaultAttachment_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
- CONSTRAINT "companyDefaultAttachment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE SET NULL
-);
-
-CREATE INDEX "companyDefaultAttachment_companyId_idx" ON "companyDefaultAttachment" ("companyId");
-
-ALTER TABLE "companyDefaultAttachment" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Employees can view companyDefaultAttachment"
- ON "companyDefaultAttachment" FOR SELECT USING (
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with settings_create can insert companyDefaultAttachment"
- ON "companyDefaultAttachment" FOR INSERT WITH CHECK (
- has_company_permission('settings_create', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with settings_update can update companyDefaultAttachment"
- ON "companyDefaultAttachment" FOR UPDATE USING (
- has_company_permission('settings_update', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with settings_delete can delete companyDefaultAttachment"
- ON "companyDefaultAttachment" FOR DELETE USING (
- has_company_permission('settings_delete', "companyId") AND
- has_role('employee', "companyId")
- );
-
-
--- ============================================================================
--- Supplier-level default attachments (cascade to POs for that supplier)
--- ============================================================================
-CREATE TABLE "supplierDefaultAttachment" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "supplierId" TEXT NOT NULL,
- "documentId" TEXT NOT NULL,
- "shareOnSend" BOOLEAN NOT NULL DEFAULT true,
- "isLocked" BOOLEAN NOT NULL DEFAULT false,
- "companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
-
- CONSTRAINT "supplierDefaultAttachment_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "supplierDefaultAttachment_unique" UNIQUE ("supplierId", "documentId"),
- CONSTRAINT "supplierDefaultAttachment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE,
- CONSTRAINT "supplierDefaultAttachment_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
- CONSTRAINT "supplierDefaultAttachment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
- CONSTRAINT "supplierDefaultAttachment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE SET NULL
-);
-
-CREATE INDEX "supplierDefaultAttachment_supplierId_idx" ON "supplierDefaultAttachment" ("supplierId");
-CREATE INDEX "supplierDefaultAttachment_companyId_idx" ON "supplierDefaultAttachment" ("companyId");
-
-ALTER TABLE "supplierDefaultAttachment" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Employees with purchasing_view can view supplierDefaultAttachment"
- ON "supplierDefaultAttachment" FOR SELECT USING (
- has_company_permission('purchasing_view', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with purchasing_create can insert supplierDefaultAttachment"
- ON "supplierDefaultAttachment" FOR INSERT WITH CHECK (
- has_company_permission('purchasing_create', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with purchasing_update can update supplierDefaultAttachment"
- ON "supplierDefaultAttachment" FOR UPDATE USING (
- has_company_permission('purchasing_update', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with purchasing_delete can delete supplierDefaultAttachment"
- ON "supplierDefaultAttachment" FOR DELETE USING (
- has_company_permission('purchasing_delete', "companyId") AND
- has_role('employee', "companyId")
- );
-
-
--- ============================================================================
--- Item-level default attachments (cascade to POs containing that item)
--- ============================================================================
-CREATE TABLE "itemDefaultAttachment" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "itemId" TEXT NOT NULL,
- "documentId" TEXT NOT NULL,
- "shareOnSend" BOOLEAN NOT NULL DEFAULT true,
- "isLocked" BOOLEAN NOT NULL DEFAULT false,
- "companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
- "createdBy" TEXT NOT NULL,
-
- CONSTRAINT "itemDefaultAttachment_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "itemDefaultAttachment_unique" UNIQUE ("itemId", "documentId"),
- CONSTRAINT "itemDefaultAttachment_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
- CONSTRAINT "itemDefaultAttachment_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "document"("id") ON DELETE CASCADE,
- CONSTRAINT "itemDefaultAttachment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
- CONSTRAINT "itemDefaultAttachment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE SET NULL
-);
-
-CREATE INDEX "itemDefaultAttachment_itemId_idx" ON "itemDefaultAttachment" ("itemId");
-CREATE INDEX "itemDefaultAttachment_companyId_idx" ON "itemDefaultAttachment" ("companyId");
-
-ALTER TABLE "itemDefaultAttachment" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "Employees can view itemDefaultAttachment"
- ON "itemDefaultAttachment" FOR SELECT USING (
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with parts_create can insert itemDefaultAttachment"
- ON "itemDefaultAttachment" FOR INSERT WITH CHECK (
- has_company_permission('parts_create', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with parts_update can update itemDefaultAttachment"
- ON "itemDefaultAttachment" FOR UPDATE USING (
- has_company_permission('parts_update', "companyId") AND
- has_role('employee', "companyId")
- );
-
-CREATE POLICY "Employees with parts_delete can delete itemDefaultAttachment"
- ON "itemDefaultAttachment" FOR DELETE USING (
- has_company_permission('parts_delete', "companyId") AND
- has_role('employee', "companyId")
- );
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 5e267e93bd..f7ccddcacc 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} erfolgreich hochgeladen"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB-Limit"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} Berechtigungen"
@@ -1181,6 +1184,9 @@ msgstr "Kann nicht gebucht werden – Sendung enthält abgelaufene nachverfölgt
msgid "Cannot send RFQ"
msgstr "RFQ kann nicht gesendet werden"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Kann nicht in den Teile-Bucket ohne Element-ID hochgeladen werden"
@@ -3010,6 +3016,9 @@ msgstr "Fehler beim Laden der Herstellungsmethode"
msgid "Error moving file"
msgstr "Fehler beim Verschieben der Datei"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Fehler beim Entfernen des Modells aus {sourceDocument}"
@@ -3876,9 +3885,6 @@ msgstr "Intern"
msgid "Internal Notes"
msgstr "Interne Notizen"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Ungültige Einladung"
@@ -4271,9 +4277,6 @@ msgstr "Standorte"
msgid "Lock"
msgstr "Sperren"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Anmelden"
@@ -4995,7 +4998,7 @@ msgstr "Keine Adressen gefunden"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "Noch keine archivierten Protokolle. Protokolle älter als {0} Tage werden automatisch archiviert und sind hier zum Download verfügbar."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "Verknüpfung aufheben"
msgid "Unlink job from sales order?"
msgstr "Auftrag von Verkaufsauftrag trennen?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Nicht unterstützter Quelldokumenttyp: {sourceDocument}"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 34f2316966..e431a56e31 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} uploaded successfully"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
+msgid "{name} deleted"
+msgstr "{name} deleted"
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} permissions"
@@ -1163,6 +1166,9 @@ msgstr "Cannot post — shipment contains expired tracked entities."
msgid "Cannot send RFQ"
msgstr "Cannot send RFQ"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr "Cannot upload — supplier interaction not yet created"
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Cannot upload to parts bucket without item ID"
@@ -2983,6 +2989,9 @@ msgstr "Error loading make method"
msgid "Error moving file"
msgstr "Error moving file"
+msgid "Error removing file"
+msgstr "Error removing file"
+
msgid "Error removing model from {sourceDocument}"
msgstr "Error removing model from {sourceDocument}"
@@ -3840,9 +3849,6 @@ msgstr "Internal"
msgid "Internal Notes"
msgstr "Internal Notes"
-msgid "Internal only"
-msgstr "Internal only"
-
msgid "Invalid Invite"
msgstr "Invalid Invite"
@@ -4235,9 +4241,6 @@ msgstr "Locations"
msgid "Lock"
msgstr "Lock"
-msgid "Locked"
-msgstr "Locked"
-
msgid "Log In"
msgstr "Log In"
@@ -4953,8 +4956,8 @@ msgstr "No addresses found"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
-msgid "No attachments yet."
-msgstr "No attachments yet."
+msgid "No attachments."
+msgstr "No attachments."
msgid "No available filters"
msgstr "No available filters"
@@ -7863,9 +7866,6 @@ msgstr "Unlimited Functional Support"
msgid "Unlink"
msgstr "Unlink"
-msgid "Unlock"
-msgstr "Unlock"
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Unsupported source document type: {sourceDocument}"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index aadbf7b4a9..d16c81032d 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} cargado exitosamente"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB límite"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} permisos"
@@ -1163,6 +1166,9 @@ msgstr "No se puede registrar — el envío contiene entidades rastreadas vencid
msgid "Cannot send RFQ"
msgstr "No se puede enviar RFQ"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "No se puede cargar en el depósito de piezas sin ID de artículo"
@@ -2983,6 +2989,9 @@ msgstr "Error al cargar el método de fabricaciÃÂÂ
msgid "Error moving file"
msgstr "Error al mover archivo"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Error al eliminar el modelo de {sourceDocument}"
@@ -3840,9 +3849,6 @@ msgstr "Interno"
msgid "Internal Notes"
msgstr "Notas Internas"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Invitación Inválida"
@@ -4235,9 +4241,6 @@ msgstr "Ubicaciones"
msgid "Lock"
msgstr "Bloquear"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Iniciar sesión"
@@ -4953,7 +4956,7 @@ msgstr "No se encontraron direcciones"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "No hay registros archivados aún. Los registros más antiguos de {0} días se archivarán automáticamente y estarán disponibles para descargar aquí."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7863,9 +7866,6 @@ msgstr "Soporte Funcional Ilimitado"
msgid "Unlink"
msgstr "Desenlazar"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Tipo de documento de origen no compatible: {sourceDocument}"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 1252a16d70..a81fce52ff 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} téléchargé avec s
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limite"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} permissions"
@@ -1163,6 +1166,9 @@ msgstr "Impossible de publier — l'expédition contient des entités suivies ex
msgid "Cannot send RFQ"
msgstr "Impossible d'envoyer la demande de devis"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Impossible de télécharger vers le compartiment des pièces sans ID d'article"
@@ -2983,6 +2989,9 @@ msgstr "Erreur lors du chargement de la méthode de fabrication"
msgid "Error moving file"
msgstr "Erreur lors du déplacement du fichier"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Erreur lors de la suppression du modèle de {sourceDocument}"
@@ -3840,9 +3849,6 @@ msgstr "Interne"
msgid "Internal Notes"
msgstr "Notes internes"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Invitation invalide"
@@ -4235,9 +4241,6 @@ msgstr "Emplacements"
msgid "Lock"
msgstr "Verrouiller"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Se connecter"
@@ -4953,7 +4956,7 @@ msgstr "Aucune adresse trouvée"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "Aucun journal archivé pour le moment. Les journaux antérieurs à {0} jours seront automatiquement archivés et disponibles au téléchargement ici."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7863,9 +7866,6 @@ msgstr "Support fonctionnel illimité"
msgid "Unlink"
msgstr "Dissocier"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Type de document source non pris en charge : {sourceDocument}"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 84780c5047..87329c1f80 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} सफलतापूर्वक अपलोड हो गया"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB सीमा"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} अनुमतियाँ"
@@ -1181,6 +1184,9 @@ msgstr "पोस्ट नहीं कर सकते — शिपमें
msgid "Cannot send RFQ"
msgstr "RFQ नहीं भेज सकते"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "आइटम आईडी के बिना पार्ट्स बकेट में अपलोड नहीं कर सकते"
@@ -3010,6 +3016,9 @@ msgstr "मेक विधि लोड करने में त्रुट
msgid "Error moving file"
msgstr "फ़ाइल स्थानांतरित करने में त्रुटि"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "{sourceDocument} से मॉडल हटाने में त्रुटि"
@@ -3876,9 +3885,6 @@ msgstr "आंतरिक"
msgid "Internal Notes"
msgstr "आंतरिक नोट्स"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "अमान्य निमंत्रण"
@@ -4271,9 +4277,6 @@ msgstr "स्थान"
msgid "Lock"
msgstr "लॉक करें"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "लॉग इन करें"
@@ -4995,7 +4998,7 @@ msgstr "कोई पता नहीं मिला"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "अभी तक कोई संग्रहीत लॉग नहीं है। {0} दिन से पुराने लॉग स्वचालित रूप से संग्रहीत किए जाएंगे और यहां डाउनलोड के लिए उपलब्ध होंगे।"
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "अनलिंक करें"
msgid "Unlink job from sales order?"
msgstr "बिक्रय आदेश से नौकरी को अनलिंक करें?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "असमर्थित स्रोत दस्तावेज़ प्रकार: {sourceDocument}"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 6974a7a9e3..ce2556e1f5 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} caricato con successo"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limite"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} autorizzazioni"
@@ -1163,6 +1166,9 @@ msgstr "Impossibile pubblicare — la spedizione contiene entità tracciate scad
msgid "Cannot send RFQ"
msgstr "Impossibile inviare RFQ"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Impossibile caricare nel bucket delle parti senza ID elemento"
@@ -2983,6 +2989,9 @@ msgstr "Errore nel caricamento del metodo di produzione"
msgid "Error moving file"
msgstr "Errore durante lo spostamento del file"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Errore nella rimozione del modello da {sourceDocument}"
@@ -3840,9 +3849,6 @@ msgstr "Interno"
msgid "Internal Notes"
msgstr "Note Interne"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Invito Non Valido"
@@ -4235,9 +4241,6 @@ msgstr "Posizioni"
msgid "Lock"
msgstr "Blocca"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Accedi"
@@ -4953,7 +4956,7 @@ msgstr "Nessun indirizzo trovato"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "Nessun log archiviato ancora. I log più vecchi di {0} giorni verranno archiviati automaticamente e disponibili per il download qui."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7863,9 +7866,6 @@ msgstr "Supporto Funzionale Illimitato"
msgid "Unlink"
msgstr "Scollega"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Tipo di documento di origine non supportato: {sourceDocument}"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 78e4e88741..eaa0e35222 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -49,6 +49,9 @@ msgstr "{0}が正常にアップロードされました"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB制限"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} 個の権限"
@@ -1181,6 +1184,9 @@ msgstr "投稿できません — 出荷に期限切れの追跡対象エンテ
msgid "Cannot send RFQ"
msgstr "RFQを送信できません"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "アイテムIDなしでパーツバケットにアップロードできません"
@@ -3010,6 +3016,9 @@ msgstr "メイク方法の読み込みエラー"
msgid "Error moving file"
msgstr "ファイルの移動エラー"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "{sourceDocument}からモデルを削除するときにエラーが発生しました"
@@ -3876,9 +3885,6 @@ msgstr "内部"
msgid "Internal Notes"
msgstr "内部メモ"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "無効な招待"
@@ -4271,9 +4277,6 @@ msgstr "ロケーション"
msgid "Lock"
msgstr "ロック"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "ログイン"
@@ -4995,7 +4998,7 @@ msgstr "住所が見つかりません"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "まだアーカイブされたログはありません。{0}日以上前のログは自動的にアーカイブされ、ここからダウンロードできます。"
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "リンク解除"
msgid "Unlink job from sales order?"
msgstr "販売注文からジョブのリンクを解除しますか?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "サポートされていないソースドキュメントタイプ: {sourceDocument}"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 342dee9897..7f491b4762 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} przesłano pomyślnie"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} uprawnień"
@@ -1181,6 +1184,9 @@ msgstr "Nie można wysłać — przesyłka zawiera wygasłe jednostki śledzenia
msgid "Cannot send RFQ"
msgstr "Nie można wysłać ZZO"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Nie można przesłać do zasobnika części bez identyfikatora elementu"
@@ -3010,6 +3016,9 @@ msgstr "Błąd podczas ładowania metody produkcji"
msgid "Error moving file"
msgstr "Błąd podczas przenoszenia pliku"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Błąd podczas usuwania modelu z {sourceDocument}"
@@ -3876,9 +3885,6 @@ msgstr "Wewnętrzne"
msgid "Internal Notes"
msgstr "Notatki wewnętrzne"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Nieprawidłowe zaproszenie"
@@ -4271,9 +4277,6 @@ msgstr "Lokalizacje"
msgid "Lock"
msgstr "Zablokuj"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Zaloguj się"
@@ -4995,7 +4998,7 @@ msgstr "Nie znaleziono adresów"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "Brak zarchiwizowanych dzienników. Dzienniki starsze niż {0} dni będą automatycznie archiwizowane i dostępne do pobrania tutaj."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "Odłącz"
msgid "Unlink job from sales order?"
msgstr "Odłączyć zadanie od zamówienia sprzedaży?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Nieobsługiwany typ dokumentu źródłowego: {sourceDocument}"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index db8fb21b75..b4af163f87 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} enviado com sucesso"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} permissões"
@@ -1181,6 +1184,9 @@ msgstr "Não é possível postar — o envio contém entidades rastreadas expira
msgid "Cannot send RFQ"
msgstr "Não é possível enviar RFQ"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Não é possível fazer upload para o bucket de peças sem ID do item"
@@ -3010,6 +3016,9 @@ msgstr "Erro ao carregar método de fabricação"
msgid "Error moving file"
msgstr "Erro ao mover arquivo"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Erro ao remover modelo de {sourceDocument}"
@@ -3876,9 +3885,6 @@ msgstr "Interno"
msgid "Internal Notes"
msgstr "Notas Internas"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Convite Inválido"
@@ -4271,9 +4277,6 @@ msgstr "Localizações"
msgid "Lock"
msgstr "Bloquear"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Entrar"
@@ -4995,7 +4998,7 @@ msgstr "Nenhum endereço encontrado"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "Nenhum log arquivado ainda. Logs com mais de {0} dias serão automaticamente arquivados e disponíveis para download aqui."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "Desvinculação"
msgid "Unlink job from sales order?"
msgstr "Desassociar trabalho da ordem de venda?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Tipo de documento de origem não suportado: {sourceDocument}"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index cea4a723dd..9eb0308895 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} успешно загружен"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}МБ максимум"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} разрешений"
@@ -1181,6 +1184,9 @@ msgstr "Невозможно отправить — отправка содер
msgid "Cannot send RFQ"
msgstr "Невозможно отправить РФП"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "Невозможно загрузить в корзину деталей без ID элемента"
@@ -3010,6 +3016,9 @@ msgstr "Ошибка загрузки метода производства"
msgid "Error moving file"
msgstr "Ошибка при перемещении файла"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "Ошибка при удалении модели из {sourceDocument}"
@@ -3876,9 +3885,6 @@ msgstr "Внутренние"
msgid "Internal Notes"
msgstr "Внутренние примечания"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "Недействительное приглашение"
@@ -4271,9 +4277,6 @@ msgstr "Местоположения"
msgid "Lock"
msgstr "Заблокировать"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "Войти"
@@ -4995,7 +4998,7 @@ msgstr "Адреса не найдены"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "Нет архивированных логов. Логи старше {0} дней будут автоматически архивированы и доступны для скачивания здесь."
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "Отменить связь"
msgid "Unlink job from sales order?"
msgstr "Отменить связь задания с заказом на продажу?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "Неподдерживаемый тип исходного документа: {sourceDocument}"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 103cf772b4..f695794f1d 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -49,6 +49,9 @@ msgstr "{0} 上传成功"
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB 限制"
+msgid "{name} deleted"
+msgstr ""
+
msgid "{scopeCount} permissions"
msgstr "{scopeCount} 个权限"
@@ -1181,6 +1184,9 @@ msgstr "无法发布 — 货运单包含已过期的追踪实体。"
msgid "Cannot send RFQ"
msgstr "无法发送询价单"
+msgid "Cannot upload — supplier interaction not yet created"
+msgstr ""
+
msgid "Cannot upload to parts bucket without item ID"
msgstr "无法在没有项目ID的情况下上传到零件存储桶"
@@ -3010,6 +3016,9 @@ msgstr "加载制造方法出错"
msgid "Error moving file"
msgstr "移动文件出错"
+msgid "Error removing file"
+msgstr ""
+
msgid "Error removing model from {sourceDocument}"
msgstr "从{sourceDocument}中删除模型时出错"
@@ -3876,9 +3885,6 @@ msgstr "内部"
msgid "Internal Notes"
msgstr "内部备注"
-msgid "Internal only"
-msgstr ""
-
msgid "Invalid Invite"
msgstr "无效邀请"
@@ -4271,9 +4277,6 @@ msgstr "位置"
msgid "Lock"
msgstr "锁定"
-msgid "Locked"
-msgstr ""
-
msgid "Log In"
msgstr "登录"
@@ -4995,7 +4998,7 @@ msgstr "未找到地址"
msgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."
msgstr "还没有存档日志。超过 {0} 天的日志将自动存档,并可在此处下载。"
-msgid "No attachments yet."
+msgid "No attachments."
msgstr ""
msgid "No available filters"
@@ -7934,9 +7937,6 @@ msgstr "取消链接"
msgid "Unlink job from sales order?"
msgstr "从销售订单取消关联工作?"
-msgid "Unlock"
-msgstr ""
-
msgid "Unsupported source document type: {sourceDocument}"
msgstr "不支持的源文档类型:{sourceDocument}"