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: fix next id for alphabetic sequences

Brad Barbin7c847b778280
diff --git a/apps/erp/app/hooks/useNextItemId.tsx b/apps/erp/app/hooks/useNextItemId.tsx
index bc3b55f841..795758ce85 100644
--- a/apps/erp/app/hooks/useNextItemId.tsx
+++ b/apps/erp/app/hooks/useNextItemId.tsx
@@ -18,26 +18,23 @@ export function useNextItemId(
if (prefix) {
try {
- const { data } = await carbon
- ?.from("item")
- .select("readableId")
- .eq("companyId", company.id)
- .eq("type", table)
- .ilike("readableId", `${prefix}%`)
- .order("readableId", { ascending: false })
- .limit(1)
- .maybeSingle();
+ const nextIdRpc = await carbon?.rpc("get_next_prefixed_sequence", {
+ company_id: company.id,
+ item_type: table,
+ prefix,
+ });
+
+ console.log(nextIdRpc);
- if (data?.readableId) {
- const sequence = data.readableId.slice(prefix.length);
+ if (nextIdRpc.data) {
+ const sequence = nextIdRpc.data.slice(prefix.length);
const currentSequence = parseInt(sequence);
const nextSequence = currentSequence + 1;
const nextId = `${prefix}${nextSequence
.toString()
.padStart(
sequence.length -
- (data.readableId.split(`${currentSequence}`)?.[1].length ??
- 0),
+ (nextIdRpc.data.split(`${currentSequence}`)?.[1].length ?? 0),
"0"
)}`;
setId(nextId);
@@ -55,8 +52,6 @@ export function useNextItemId(
item_type: table,
});
- console.log(nextIdRpc);
-
if (nextIdRpc.data) {
const sequence = nextIdRpc.data.slice(prefix.length);
const currentSequence = parseInt(sequence);
diff --git a/packages/database/supabase/migrations/20250130220642_prefixed-sequences.sql b/packages/database/supabase/migrations/20250130220642_prefixed-sequences.sql
new file mode 100644
index 0000000000..5f534e537b
--- /dev/null
+++ b/packages/database/supabase/migrations/20250130220642_prefixed-sequences.sql
@@ -0,0 +1,15 @@
+CREATE OR REPLACE FUNCTION get_next_prefixed_sequence(company_id text, item_type "itemType", prefix text)
+RETURNS text AS $$
+BEGIN
+ RETURN (
+ SELECT "readableId"
+ FROM "item"
+ WHERE "companyId" = company_id
+ AND "type" = item_type
+ AND "readableId" LIKE prefix || '%'
+ AND substring("readableId" from (length(prefix) + 1)) ~ '^[0-9]+$'
+ ORDER BY "readableId" DESC
+ LIMIT 1
+ );
+END;
+$$ LANGUAGE plpgsql;
\ No newline at end of file