Skip to content

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

feat: batches able

Brad Barbin2f7e14563259
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 3eb560d7e3..1b70bf12ef 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -76,6 +76,32 @@ export async function insertManualInventoryAdjustment(
return client.from("itemLedger").insert([data]).select("*").single();
}
+export async function getBatches(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GenericQueryFilters & {
+ search: string | null;
+ }
+) {
+ let query = client
+ .from("batchNumbers")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("companyId", companyId);
+
+ if (args.search) {
+ query = query.or(
+ `number.ilike.%${args.search}%,itemName.ilike.%${args.search}%,itemReadableId.ilike.%${args.search}%`
+ );
+ }
+
+ query = setGenericQueryFilters(query, args, [
+ { column: "number", ascending: false },
+ ]);
+ return query;
+}
+
export async function getItemLedgerPage(
client: SupabaseClient<Database>,
itemId: string,
diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.ts
index edf983b4ea..61b0d023a7 100644
--- a/apps/erp/app/modules/inventory/types.ts
+++ b/apps/erp/app/modules/inventory/types.ts
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import type {
+ getBatches,
getInventoryItems,
getItemLedgerPage,
getReceiptLines,
@@ -8,6 +9,10 @@ import type {
getShippingMethods,
} from "./inventory.service";
+export type BatchTableRow = NonNullable<
+ Awaited<ReturnType<typeof getBatches>>["data"]
+>[number];
+
export type InventoryItem = NonNullable<
Awaited<ReturnType<typeof getInventoryItems>>["data"]
>[number];
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
index af2684c5ab..d500a7f825 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx
@@ -8,7 +8,9 @@ const getActivityText = (ledgerRecord: ItemLedger) => {
switch (ledgerRecord.documentType) {
case "Purchase Receipt":
return `received ${ledgerRecord.quantity} units${
- ledgerRecord.batchNumber ? ` from lot ${ledgerRecord.batchNumber}` : ""
+ ledgerRecord.batchNumber
+ ? ` from batch ${ledgerRecord.batchNumber}`
+ : ""
}${
ledgerRecord.serialNumber
? ` with serial number ${ledgerRecord.serialNumber}`
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
index c03967f497..cd6975eb03 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
@@ -32,16 +32,14 @@ import {
receiptStatusType,
} from "~/modules/inventory";
import { usePeople, useSuppliers } from "~/stores";
-import type { ListItem } from "~/types";
import { path } from "~/utils/path";
type ReceiptsTableProps = {
data: Receipt[];
count: number;
- locations: ListItem[];
};
-const ReceiptsTable = memo(({ data, count, locations }: ReceiptsTableProps) => {
+const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
useRealtime("receipt", `id=in.(${data.map((d) => d.id).join(",")})`);
const [params] = useUrlParams();
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/index.ts b/apps/erp/app/modules/inventory/ui/Receipts/index.ts
index 9461044b58..7d1a055f44 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/index.ts
+++ b/apps/erp/app/modules/inventory/ui/Receipts/index.ts
@@ -12,6 +12,6 @@ export {
ReceiptLines,
ReceiptPostModal,
ReceiptSidebar,
- ReceiptStatus,
ReceiptsTable,
+ ReceiptStatus,
};
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index 9684ff01c9..e494e526b4 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -1,4 +1,4 @@
-import { LuBox, LuHandCoins, LuTruck } from "react-icons/lu";
+import { LuBox, LuGroup, LuHandCoins, LuTruck } from "react-icons/lu";
import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -44,6 +44,11 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [
to: path.to.receipts,
icon: <LuHandCoins />,
},
+ {
+ name: "Batches",
+ to: path.to.batches,
+ icon: <LuGroup />,
+ },
// {
// name: "Shipments",
// to: path.to.shipments,
diff --git a/apps/erp/app/routes/x+/inventory+/receipts.tsx b/apps/erp/app/routes/x+/inventory+/receipts.tsx
index d025bf80f7..62eef858b5 100644
--- a/apps/erp/app/routes/x+/inventory+/receipts.tsx
+++ b/apps/erp/app/routes/x+/inventory+/receipts.tsx
@@ -6,7 +6,6 @@ import { Outlet, useLoaderData } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { ReceiptsTable, getReceipts } from "~/modules/inventory";
-import { getLocationsList } from "~/modules/resources";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -27,7 +26,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [receipts, locations] = await Promise.all([
+ const [receipts] = await Promise.all([
getReceipts(client, companyId, {
search,
limit,
@@ -35,7 +34,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
sorts,
filters,
}),
- getLocationsList(client, companyId),
]);
if (receipts.error) {
@@ -48,16 +46,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
return json({
receipts: receipts.data ?? [],
count: receipts.count ?? 0,
- locations: locations.data ?? [],
});
}
export default function ReceiptsRoute() {
- const { receipts, count, locations } = useLoaderData<typeof loader>();
+ const { receipts, count } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ReceiptsTable data={receipts} count={count ?? 0} locations={locations} />
+ <ReceiptsTable data={receipts} count={count ?? 0} />
<Outlet />
</VStack>
);
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3688cf3e71..795f90a1b7 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -140,6 +140,8 @@ export const path = {
generatePath(`${x}/people/attributes/${id}`),
attributeCategoryList: (id: string) =>
generatePath(`${x}/people/attributes/list/${id}`),
+ batches: `${x}/inventory/batches`,
+ batch: (id: string) => generatePath(`${x}/inventory/batches/${id}`),
bulkEditPermissions: `${x}/users/bulk-edit-permissions`,
bulkUpdateItems: `${x}/items/update`,
bulkUpdateJob: `${x}/job/update`,
@@ -506,9 +508,9 @@ export const path = {
newAttributeCategory: `${x}/people/attributes/new`,
newAttributeForCategory: (id: string) =>
generatePath(`${x}/people/attributes/list/${id}/new`),
+ newBatch: `${x}/inventory/batches/new`,
newChartOfAccount: `${x}/accounting/charts/new`,
newCompany: `${x}/settings/company/new`,
-
newConsumable: `${x}/consumable/new`,
newConsumableSupplier: (id: string) =>
generatePath(`${x}/consumable/${id}/purchasing/new`),
@@ -814,6 +816,9 @@ export const path = {
scrapReason: (id: string) =>
generatePath(`${x}/production/scrap-reasons/${id}`),
scrapReasons: `${x}/production/scrap-reasons`,
+ serialNumbers: `${x}/inventory/serial-numbers`,
+ serialNumber: (id: string) =>
+ generatePath(`${x}/inventory/serial-numbers/${id}`),
service: (id: string) => generatePath(`${x}/service/${id}`),
services: `${x}/items/services`,
serviceDetails: (id: string) => `${x}/service/${id}/details`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b10734bbad..b43f910f8d 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -27894,6 +27894,168 @@ export default {
tags: ["receiptLineTracking"],
},
},
+ "/jobProductionTracking": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.serialNumberId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.batchNumberId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.producedAt",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/jobProductionTracking",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["jobProductionTracking"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.jobProductionTracking",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["jobProductionTracking"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.serialNumberId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.batchNumberId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.producedAt",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobProductionTracking"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.serialNumberId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.batchNumberId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobProductionTracking.producedAt",
+ },
+ {
+ $ref: "#/parameters/body.jobProductionTracking",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobProductionTracking"],
+ },
+ },
"/employeeJob": {
get: {
parameters: [
@@ -56096,6 +56258,65 @@ export default {
},
type: "object",
},
+ jobProductionTracking: {
+ required: [
+ "id",
+ "jobId",
+ "itemId",
+ "quantity",
+ "companyId",
+ "producedAt",
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ jobId: {
+ description:
+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ serialNumberId: {
+ description:
+ "Note:\nThis is a Foreign Key to `serialNumber.id`.<fk table='serialNumber' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ batchNumberId: {
+ description:
+ "Note:\nThis is a Foreign Key to `batchNumber.id`.<fk table='batchNumber' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ quantity: {
+ default: 1,
+ format: "numeric",
+ type: "number",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ producedAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
employeeJob: {
required: ["id", "companyId"],
properties: {
@@ -78576,6 +78797,71 @@ export default {
in: "query",
type: "string",
},
+ "body.jobProductionTracking": {
+ name: "jobProductionTracking",
+ description: "jobProductionTracking",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobProductionTracking",
+ },
+ },
+ "rowFilter.jobProductionTracking.id": {
+ name: "id",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.jobId": {
+ name: "jobId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.itemId": {
+ name: "itemId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.serialNumberId": {
+ name: "serialNumberId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.batchNumberId": {
+ name: "batchNumberId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.quantity": {
+ name: "quantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.companyId": {
+ name: "companyId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobProductionTracking.producedAt": {
+ name: "producedAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
"body.employeeJob": {
name: "employeeJob",
description: "employeeJob",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 40ec441271..18a2591db8 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -6902,6 +6902,13 @@ export type Database = {
referencedRelation: "batchNumber";
referencedColumns: ["number", "itemId"];
},
+ {
+ foreignKeyName: "itemLedger_batchNumber_fkey";
+ columns: ["batchNumber", "itemId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumbers";
+ referencedColumns: ["number", "itemId"];
+ },
{
foreignKeyName: "itemLedger_createdBy_fkey";
columns: ["createdBy"];
@@ -8599,6 +8606,13 @@ export type Database = {
referencedRelation: "batchNumber";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "jobMaterialTracking_batchNumberId_fkey";
+ columns: ["batchNumberId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumbers";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "jobMaterialTracking_companyId_fkey";
columns: ["companyId"];
@@ -9320,6 +9334,47 @@ export type Database = {
quantity?: number;
serialNumberId?: string | null;
};
+ Relationships: [
+ {
+ foreignKeyName: "jobProductionTracking_batchNumberId_fkey";
+ columns: ["batchNumberId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumber";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
+ jobProductionTracking: {
+ Row: {
+ batchNumberId: string | null;
+ companyId: string;
+ id: string;
+ itemId: string;
+ jobId: string;
+ producedAt: string;
+ quantity: number;
+ serialNumberId: string | null;
+ };
+ Insert: {
+ batchNumberId?: string | null;
+ companyId: string;
+ id?: string;
+ itemId: string;
+ jobId: string;
+ producedAt?: string;
+ quantity?: number;
+ serialNumberId?: string | null;
+ };
+ Update: {
+ batchNumberId?: string | null;
+ companyId?: string;
+ id?: string;
+ itemId?: string;
+ jobId?: string;
+ producedAt?: string;
+ quantity?: number;
+ serialNumberId?: string | null;
+ };
Relationships: [
{
foreignKeyName: "jobProductionTracking_batchNumberId_fkey";
@@ -9363,41 +9418,6 @@ export type Database = {
referencedRelation: "integrations";
referencedColumns: ["companyId"];
},
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "employees";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "employeesAcrossCompanies";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "employeeSummary";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "user";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "userDefaults";
- referencedColumns: ["userId"];
- },
{
foreignKeyName: "jobProductionTracking_itemId_fkey";
columns: ["itemId"];
@@ -18473,6 +18493,13 @@ export type Database = {
referencedRelation: "batchNumber";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "receiptLineTracking_batchNumberId_fkey";
+ columns: ["batchNumberId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumbers";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "receiptLineTracking_companyId_fkey";
columns: ["companyId"];
@@ -25899,6 +25926,28 @@ export type Database = {
source: Database["public"]["Enums"]["trackingSource"] | null;
supplierId: string | null;
};
+ Relationships: [
+ {
+ foreignKeyName: "batchNumber_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
+ batchNumbers: {
+ Row: {
+ companyId: string | null;
+ expirationDate: string | null;
+ id: string | null;
+ itemId: string | null;
+ itemName: string | null;
+ itemReadableId: string | null;
+ manufacturingDate: string | null;
+ number: string | null;
+ supplierId: string | null;
+ };
Relationships: [
{
foreignKeyName: "batchNumber_companyId_fkey";
@@ -30927,14 +30976,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey";
- columns: ["paymentCountryCode"];
+ columns: ["customerCountryCode"];
isOneToOne: false;
referencedRelation: "country";
referencedColumns: ["alpha2"];
},
{
foreignKeyName: "address_countryCode_fkey";
- columns: ["customerCountryCode"];
+ columns: ["paymentCountryCode"];
isOneToOne: false;
referencedRelation: "country";
referencedColumns: ["alpha2"];
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 40ec441271..18a2591db8 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -6902,6 +6902,13 @@ export type Database = {
referencedRelation: "batchNumber";
referencedColumns: ["number", "itemId"];
},
+ {
+ foreignKeyName: "itemLedger_batchNumber_fkey";
+ columns: ["batchNumber", "itemId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumbers";
+ referencedColumns: ["number", "itemId"];
+ },
{
foreignKeyName: "itemLedger_createdBy_fkey";
columns: ["createdBy"];
@@ -8599,6 +8606,13 @@ export type Database = {
referencedRelation: "batchNumber";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "jobMaterialTracking_batchNumberId_fkey";
+ columns: ["batchNumberId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumbers";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "jobMaterialTracking_companyId_fkey";
columns: ["companyId"];
@@ -9320,6 +9334,47 @@ export type Database = {
quantity?: number;
serialNumberId?: string | null;
};
+ Relationships: [
+ {
+ foreignKeyName: "jobProductionTracking_batchNumberId_fkey";
+ columns: ["batchNumberId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumber";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
+ jobProductionTracking: {
+ Row: {
+ batchNumberId: string | null;
+ companyId: string;
+ id: string;
+ itemId: string;
+ jobId: string;
+ producedAt: string;
+ quantity: number;
+ serialNumberId: string | null;
+ };
+ Insert: {
+ batchNumberId?: string | null;
+ companyId: string;
+ id?: string;
+ itemId: string;
+ jobId: string;
+ producedAt?: string;
+ quantity?: number;
+ serialNumberId?: string | null;
+ };
+ Update: {
+ batchNumberId?: string | null;
+ companyId?: string;
+ id?: string;
+ itemId?: string;
+ jobId?: string;
+ producedAt?: string;
+ quantity?: number;
+ serialNumberId?: string | null;
+ };
Relationships: [
{
foreignKeyName: "jobProductionTracking_batchNumberId_fkey";
@@ -9363,41 +9418,6 @@ export type Database = {
referencedRelation: "integrations";
referencedColumns: ["companyId"];
},
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "employees";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "employeesAcrossCompanies";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "employeeSummary";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "user";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "jobProductionTracking_createdBy_fkey";
- columns: ["createdBy"];
- isOneToOne: false;
- referencedRelation: "userDefaults";
- referencedColumns: ["userId"];
- },
{
foreignKeyName: "jobProductionTracking_itemId_fkey";
columns: ["itemId"];
@@ -18473,6 +18493,13 @@ export type Database = {
referencedRelation: "batchNumber";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "receiptLineTracking_batchNumberId_fkey";
+ columns: ["batchNumberId"];
+ isOneToOne: false;
+ referencedRelation: "batchNumbers";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "receiptLineTracking_companyId_fkey";
columns: ["companyId"];
@@ -25899,6 +25926,28 @@ export type Database = {
source: Database["public"]["Enums"]["trackingSource"] | null;
supplierId: string | null;
};
+ Relationships: [
+ {
+ foreignKeyName: "batchNumber_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
+ batchNumbers: {
+ Row: {
+ companyId: string | null;
+ expirationDate: string | null;
+ id: string | null;
+ itemId: string | null;
+ itemName: string | null;
+ itemReadableId: string | null;
+ manufacturingDate: string | null;
+ number: string | null;
+ supplierId: string | null;
+ };
Relationships: [
{
foreignKeyName: "batchNumber_companyId_fkey";
@@ -30927,14 +30976,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey";
- columns: ["paymentCountryCode"];
+ columns: ["customerCountryCode"];
isOneToOne: false;
referencedRelation: "country";
referencedColumns: ["alpha2"];
},
{
foreignKeyName: "address_countryCode_fkey";
- columns: ["customerCountryCode"];
+ columns: ["paymentCountryCode"];
isOneToOne: false;
referencedRelation: "country";
referencedColumns: ["alpha2"];
diff --git a/packages/database/supabase/migrations/20250128094053_traceability.sql b/packages/database/supabase/migrations/20250128094053_traceability.sql
index c4da4c7a5d..964befcb33 100644
--- a/packages/database/supabase/migrations/20250128094053_traceability.sql
+++ b/packages/database/supabase/migrations/20250128094053_traceability.sql
@@ -153,9 +153,7 @@ CREATE TABLE "receiptLineTracking" (
)
);
-
-
--- Create table to track serial/batch numbers used in job operations
+-- Create table to track serial/batch numbers from job operations
CREATE TABLE "jobMaterialTracking" (
"id" TEXT NOT NULL DEFAULT xid(),
"jobMaterialId" TEXT NOT NULL,
@@ -179,6 +177,50 @@ CREATE TABLE "jobMaterialTracking" (
)
);
+-- Create table to track serial/batch numbers produced in job operations
+CREATE TABLE "jobProductionTracking" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "jobId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "serialNumberId" TEXT,
+ "batchNumberId" TEXT,
+ "quantity" NUMERIC(12, 4) NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "producedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+
+ CONSTRAINT "jobProductionTracking_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "jobProductionTracking_job_fkey" FOREIGN KEY ("jobId") REFERENCES "job"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobProductionTracking_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobProductionTracking_serialNumberId_fkey" FOREIGN KEY ("serialNumberId") REFERENCES "serialNumber"("id") ON DELETE RESTRICT,
+ CONSTRAINT "jobProductionTracking_batchNumberId_fkey" FOREIGN KEY ("batchNumberId") REFERENCES "batchNumber"("id") ON DELETE RESTRICT,
+ CONSTRAINT "jobProductionTracking_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobProductionTracking_serial_quantity_check" CHECK (
+ ("serialNumberId" IS NULL AND "batchNumberId" IS NOT NULL) OR ("serialNumberId" IS NOT NULL AND "quantity" = 1)
+ )
+);
+
+-- -- Create table to track serial/batch numbers for deliveries
+-- CREATE TABLE "deliveryTracking" (
+-- "id" TEXT NOT NULL DEFAULT xid(),
+-- "deliveryId" TEXT NOT NULL,
+-- "itemId" TEXT NOT NULL,
+-- "serialNumberId" TEXT,
+-- "batchNumberId" TEXT,
+-- "quantity" NUMERIC(12, 4) NOT NULL DEFAULT 1,
+-- "companyId" TEXT NOT NULL,
+-- "deliveredAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+
+-- CONSTRAINT "deliveryTracking_pkey" PRIMARY KEY ("id"),
+-- CONSTRAINT "deliveryTracking_delivery_fkey" FOREIGN KEY ("deliveryId") REFERENCES "delivery"("id") ON DELETE CASCADE,
+-- CONSTRAINT "deliveryTracking_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+-- CONSTRAINT "deliveryTracking_serialNumberId_fkey" FOREIGN KEY ("serialNumberId") REFERENCES "serialNumber"("id") ON DELETE RESTRICT,
+-- CONSTRAINT "deliveryTracking_batchNumberId_fkey" FOREIGN KEY ("batchNumberId") REFERENCES "batchNumber"("id") ON DELETE RESTRICT,
+-- CONSTRAINT "deliveryTracking_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+-- CONSTRAINT "deliveryTracking_serial_quantity_check" CHECK (
+-- ("serialNumberId" IS NULL AND "batchNumberId" IS NOT NULL) OR ("serialNumberId" IS NOT NULL AND "quantity" = 1)
+-- )
+-- );
+
-- Add helpful indexes
CREATE INDEX "receiptLineTracking_receiptLine_idx" ON "receiptLineTracking" ("receiptLineId");
CREATE INDEX "receiptLineTracking_receipt_idx" ON "receiptLineTracking" ("receiptId");
@@ -191,9 +233,19 @@ CREATE INDEX "jobMaterialTracking_jobOperation_idx" ON "jobMaterialTracking" ("j
CREATE INDEX "jobMaterialTracking_serialNumberId_idx" ON "jobMaterialTracking" ("serialNumberId");
CREATE INDEX "jobMaterialTracking_batchNumberId_idx" ON "jobMaterialTracking" ("batchNumberId");
+CREATE INDEX "jobProductionTracking_jobOperation_idx" ON "jobProductionTracking" ("jobId");
+CREATE INDEX "jobProductionTracking_serialNumberId_idx" ON "jobProductionTracking" ("serialNumberId");
+CREATE INDEX "jobProductionTracking_batchNumberId_idx" ON "jobProductionTracking" ("batchNumberId");
+
+-- CREATE INDEX "deliveryTracking_delivery_idx" ON "deliveryTracking" ("deliveryId");
+-- CREATE INDEX "deliveryTracking_serialNumberId_idx" ON "deliveryTracking" ("serialNumberId");
+-- CREATE INDEX "deliveryTracking_batchNumberId_idx" ON "deliveryTracking" ("batchNumberId");
+
-- Add RLS policies
ALTER TABLE "receiptLineTracking" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "jobMaterialTracking" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "jobProductionTracking" ENABLE ROW LEVEL SECURITY;
+-- ALTER TABLE "deliveryTracking" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Anyone can view receipt tracking" ON "receiptLineTracking"
FOR SELECT USING (
@@ -226,7 +278,9 @@ CREATE POLICY "Anyone can view job material tracking" ON "jobMaterialTracking"
CREATE POLICY "Users with production_create can insert job material tracking" ON "jobMaterialTracking"
FOR INSERT WITH CHECK (
- has_company_permission('production_create', "companyId")
+ "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
);
CREATE POLICY "Users with production_update can update job material tracking" ON "jobMaterialTracking"
@@ -239,6 +293,49 @@ CREATE POLICY "Users with production_delete can delete job material tracking" ON
has_company_permission('production_delete', "companyId")
);
+CREATE POLICY "Anyone can view job production tracking" ON "jobProductionTracking"
+ FOR SELECT USING (
+ "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+ )
+ );
+
+CREATE POLICY "Users with production_create can insert job production tracking" ON "jobProductionTracking"
+ FOR INSERT WITH CHECK (
+ has_company_permission('production_create', "companyId")
+ );
+
+CREATE POLICY "Users with production_update can update job production tracking" ON "jobProductionTracking"
+ FOR UPDATE USING (
+ has_company_permission('production_update', "companyId")
+ );
+
+CREATE POLICY "Users with production_delete can delete job production tracking" ON "jobProductionTracking"
+ FOR DELETE USING (
+ has_company_permission('production_delete', "companyId")
+ );
+
+-- CREATE POLICY "Anyone can view delivery tracking" ON "deliveryTracking"
+-- FOR SELECT USING (
+-- "companyId" = ANY(
+-- SELECT "companyId" from "userToCompany" where "userId" = (SELECT auth.uid())::text
+-- )
+-- );
+
+-- CREATE POLICY "Users with shipping_create can insert delivery tracking" ON "deliveryTracking"
+-- FOR INSERT WITH CHECK (
+-- has_company_permission('shipping_create', "companyId")
+-- );
+
+-- CREATE POLICY "Users with shipping_update can update delivery tracking" ON "deliveryTracking"
+-- FOR UPDATE USING (
+-- has_company_permission('shipping_update', "companyId")
+-- );
+
+-- CREATE POLICY "Users with shipping_delete can delete delivery tracking" ON "deliveryTracking"
+-- FOR DELETE USING (
+-- has_company_permission('shipping_delete', "companyId")
+-- );
CREATE POLICY "Inventory document view requires inventory_view" ON storage.objects USING (
bucket_id = 'private'
@@ -471,4 +568,36 @@ BEGIN
loc."name",
i."unitOfMeasureCode";
END;
-$$ LANGUAGE plpgsql SECURITY INVOKER;
\ No newline at end of file
+$$ LANGUAGE plpgsql SECURITY INVOKER;
+
+
+CREATE OR REPLACE VIEW "batchNumbers" WITH(SECURITY_INVOKER=true) AS
+ SELECT DISTINCT
+ bn."id",
+ bn."number",
+ bn."manufacturingDate",
+ bn."expirationDate",
+ bn."supplierId",
+ bn."companyId",
+ bn."itemId",
+ i."name" AS "itemName",
+ i."readableId" AS "itemReadableId"
+ FROM "batchNumber" bn
+ JOIN "item" i ON i."id" = bn."itemId"
+ WHERE EXISTS (
+ SELECT 1 FROM "receiptLineTracking" rlt
+ WHERE rlt."batchNumberId" = bn."id"
+ ) OR EXISTS (
+ SELECT 1 FROM "jobProductionTracking" jpt
+ WHERE jpt."batchNumberId" = bn."id"
+ )
+ GROUP BY
+ bn."id",
+ bn."number",
+ bn."manufacturingDate",
+ bn."expirationDate",
+ bn."supplierId",
+ bn."companyId",
+ bn."itemId",
+ i."name",
+ i."readableId";
\ No newline at end of file