Inventory
inventoryStock per catalog variant and location in a unit with decimals: movements posted to the ledger block, lots, serial numbers, expiry, bins, weighted average cost, reservations with expiry, allocations with backorders, transfers, purchase requisitions with approval, and purchase orders with partial receiving into goods receipts.
Billing & commercemanagedcustom
Invoice INV-0042paid
Pro plan€49.00
Seats × 3€27.00
Usage€4.20
Total€80.20
Install
The command also installs updated-at, memberships, permissions, catalog, ledger, the modules it needs.
npx better-supabase add inventoryConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by inventory; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
catalog: {},
ledger: {},
// Modes: "managed", "custom". The default is "managed".
inventory: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add inventory writes into your declarative schema with the default layout.13 files
supabase/schemas/900_better_supabase_081_inventory.sqlschema5623 lines-- better-supabase module: inventory
-- @bsb-block inventory@6 managed
-- @bsb-hash sha256:a88f21cdd9f93d153f3d38053421771d093db10485e9a349ce38f281e519b941
-- Stock per catalog variant and location in a unit with decimals: movements posted to the ledger block, lots, serial numbers, expiry, bins, weighted average cost, reservations with expiry, allocations with backorders, transfers, purchase requisitions with approval, and purchase orders with partial receiving into goods receipts.
-- Managed by `better-supabase add`; re-running it rewrites this file unless it was edited by hand.
-- Change it through `blocks` in better-supabase.config.ts and the module's SQL hooks.
-- Stock per catalog variant and location in a unit with decimals: movements
-- posted to the ledger in base units, lots, serial numbers, expiry, bins,
-- weighted average cost, reservations with expiry, allocations with
-- backorders, transfers, purchase requisitions and purchase orders with
-- receiving into goods receipts.
create table "better_supabase"."inventory_locations" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"code" text not null,
"name" text not null constraint bsb_inventory_locations_name_check check (length("name") >= 1 and length("name") <= 200),
"kind" text not null default 'warehouse' constraint bsb_inventory_locations_kind_check check ("kind" in ('warehouse', 'store', 'virtual')),
"active" boolean not null default true,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "code"),
unique ("id", "tenant_id")
);
alter table "better_supabase"."inventory_locations" enable row level security;
revoke all on "better_supabase"."inventory_locations" from public, anon, authenticated;
grant select on "better_supabase"."inventory_locations" to authenticated;
grant all on "better_supabase"."inventory_locations" to service_role;
create policy bsb_inventory_locations_read on "better_supabase"."inventory_locations"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_levels" (
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"on_hand" numeric(20, 6) not null default 0,
"reserved" numeric(20, 6) not null default 0 constraint bsb_stock_levels_reserved_check check ("reserved" >= 0),
"held" numeric(20, 6) not null default 0 constraint bsb_stock_levels_held_check check ("held" >= 0),
"incoming" numeric(20, 6) not null default 0 constraint bsb_stock_levels_incoming_check check ("incoming" >= 0),
"available" numeric(20, 6) generated always as ("on_hand" - "reserved" - "held") stored,
"reorder_point" numeric(20, 6) constraint bsb_stock_levels_reorder_point_check check ("reorder_point" >= 0),
"reorder_quantity" numeric(20, 6) constraint bsb_stock_levels_reorder_quantity check ("reorder_quantity" > 0),
"updated_at" timestamptz not null default now(),
primary key ("variant_id", "location_id")
);
create index stock_levels_location_idx on "better_supabase"."stock_levels" ("location_id");
create index stock_levels_tenant_idx on "better_supabase"."stock_levels" ("tenant_id", "variant_id");
alter table "better_supabase"."stock_levels" enable row level security;
revoke all on "better_supabase"."stock_levels" from public, anon, authenticated;
grant select on "better_supabase"."stock_levels" to authenticated;
grant all on "better_supabase"."stock_levels" to service_role;
create policy bsb_stock_levels_read on "better_supabase"."stock_levels"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_reservations" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"quantity" numeric(20, 6) not null constraint bsb_stock_reservations_quantity_check check ("quantity" > 0),
"status" text not null default 'active' constraint bsb_stock_reservations_status_check check ("status" in ('active', 'committed', 'released', 'expired')),
"reference_type" text,
"reference_id" text,
"expires_at" timestamptz not null,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("id", "tenant_id")
);
create index stock_reservations_active_idx on "better_supabase"."stock_reservations" ("expires_at") where "status" = 'active';
create index stock_reservations_level_idx on "better_supabase"."stock_reservations" ("variant_id", "location_id");
create index stock_reservations_location_idx on "better_supabase"."stock_reservations" ("location_id");
alter table "better_supabase"."stock_reservations" enable row level security;
revoke all on "better_supabase"."stock_reservations" from public, anon, authenticated;
grant select on "better_supabase"."stock_reservations" to authenticated;
grant all on "better_supabase"."stock_reservations" to service_role;
create policy bsb_stock_reservations_read on "better_supabase"."stock_reservations"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_transfers" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"from_location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"to_location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"status" text not null default 'draft' constraint bsb_stock_transfers_status_check check ("status" in ('draft', 'in_transit', 'received', 'cancelled')),
"note" text,
"created_at" timestamptz not null default now(),
"shipped_at" timestamptz,
"received_at" timestamptz,
constraint bsb_stock_transfers_check check ("from_location_id" <> "to_location_id"),
unique ("id", "tenant_id")
);
create index stock_transfers_from_idx on "better_supabase"."stock_transfers" ("from_location_id");
create index stock_transfers_to_idx on "better_supabase"."stock_transfers" ("to_location_id");
alter table "better_supabase"."stock_transfers" enable row level security;
revoke all on "better_supabase"."stock_transfers" from public, anon, authenticated;
grant select on "better_supabase"."stock_transfers" to authenticated;
grant all on "better_supabase"."stock_transfers" to service_role;
create policy bsb_stock_transfers_read on "better_supabase"."stock_transfers"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_transfer_lines" (
"tenant_id" uuid not null,
"transfer_id" uuid not null references "better_supabase"."stock_transfers" ("id") on delete cascade,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"quantity" numeric(20, 6) not null constraint bsb_stock_transfer_lines_quantity_check check ("quantity" > 0),
-- The lots and serial numbers the transfer took out, so receiving puts the same ones in.
"detail" jsonb,
primary key ("transfer_id", "variant_id")
);
create index stock_transfer_lines_variant_idx on "better_supabase"."stock_transfer_lines" ("variant_id");
alter table "better_supabase"."stock_transfer_lines" enable row level security;
revoke all on "better_supabase"."stock_transfer_lines" from public, anon, authenticated;
grant select on "better_supabase"."stock_transfer_lines" to authenticated;
grant all on "better_supabase"."stock_transfer_lines" to service_role;
create policy bsb_stock_transfer_lines_read on "better_supabase"."stock_transfer_lines"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."purchase_orders" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"supplier_type" text,
"supplier_id" text,
"status" text not null default 'draft' constraint bsb_purchase_orders_status_check check ("status" in ('draft', 'ordered', 'partially_received', 'received', 'cancelled')),
"currency" char(3) not null constraint bsb_purchase_orders_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"exchange_rate" numeric constraint bsb_purchase_orders_exchange_rate_check check ("exchange_rate" is null or "exchange_rate" > 0),
"number" text,
"expected_at" timestamptz,
"note" text,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
"placed_at" timestamptz,
"ship_to" jsonb constraint bsb_purchase_orders_ship_to_check check ("ship_to" is null or jsonb_typeof("ship_to") = 'object'),
"origin_type" text,
"origin_id" text,
constraint bsb_purchase_orders_check check (("supplier_type" is null) = ("supplier_id" is null)),
unique ("id", "tenant_id")
);
create index purchase_orders_location_idx on "better_supabase"."purchase_orders" ("location_id");
create index purchase_orders_status_idx on "better_supabase"."purchase_orders" ("tenant_id", "status");
create unique index purchase_orders_number_idx on "better_supabase"."purchase_orders" ("tenant_id", "number") where "number" is not null;
alter table "better_supabase"."purchase_orders" enable row level security;
revoke all on "better_supabase"."purchase_orders" from public, anon, authenticated;
grant select on "better_supabase"."purchase_orders" to authenticated;
grant all on "better_supabase"."purchase_orders" to service_role;
create policy bsb_purchase_orders_read on "better_supabase"."purchase_orders"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."purchase_order_lines" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"purchase_order_id" uuid not null references "better_supabase"."purchase_orders" ("id") on delete cascade,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"quantity_ordered" numeric(20, 6) not null constraint bsb_purchase_order_lines_quantity_ordered_check check ("quantity_ordered" > 0),
"quantity_received" numeric(20, 6) not null default 0 constraint bsb_purchase_order_lines_check check ("quantity_received" >= 0 and "quantity_received" <= "quantity_ordered" - "quantity_canceled"),
"quantity_canceled" numeric(20, 6) not null default 0 constraint bsb_purchase_order_lines_check1 check ("quantity_canceled" >= 0 and "quantity_canceled" <= "quantity_ordered"),
"tax_code" text,
"tax_rate_bps" integer constraint bsb_purchase_order_lines_tax_rate_bps_check check ("tax_rate_bps" >= 0 and "tax_rate_bps" <= 100000),
"unit_cost" bigint not null constraint bsb_purchase_order_lines_unit_cost_check check ("unit_cost" >= 0),
unique ("purchase_order_id", "variant_id")
);
create index purchase_order_lines_variant_idx on "better_supabase"."purchase_order_lines" ("variant_id");
alter table "better_supabase"."purchase_order_lines" enable row level security;
revoke all on "better_supabase"."purchase_order_lines" from public, anon, authenticated;
grant select on "better_supabase"."purchase_order_lines" to authenticated;
grant all on "better_supabase"."purchase_order_lines" to service_role;
create policy bsb_purchase_order_lines_read on "better_supabase"."purchase_order_lines"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
-- The tax of a purchase order per tax code and rate, rebuilt from its lines
-- each time the draft is saved. Amounts are minor units of the order's currency.
create table "better_supabase"."purchase_order_tax_lines" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"purchase_order_id" uuid not null references "better_supabase"."purchase_orders" ("id") on delete cascade,
"tax_code" text,
"tax_rate_bps" integer not null constraint bsb_purchase_order_tax_lines_tax_rate_bps_check check ("tax_rate_bps" >= 0 and "tax_rate_bps" <= 100000),
"net" bigint not null constraint bsb_purchase_order_tax_lines_net_check check ("net" >= 0),
"tax" bigint not null constraint bsb_purchase_order_tax_lines_tax_check check ("tax" >= 0),
"gross" bigint not null constraint bsb_purchase_order_tax_lines_gross_check check ("gross" >= 0)
);
create index purchase_order_tax_lines_order_idx on "better_supabase"."purchase_order_tax_lines" ("purchase_order_id");
alter table "better_supabase"."purchase_order_tax_lines" enable row level security;
revoke all on "better_supabase"."purchase_order_tax_lines" from public, anon, authenticated;
grant select on "better_supabase"."purchase_order_tax_lines" to authenticated;
grant all on "better_supabase"."purchase_order_tax_lines" to service_role;
create policy bsb_purchase_order_tax_lines_read on "better_supabase"."purchase_order_tax_lines"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."purchase_requisitions" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"supplier_type" text,
"supplier_id" text,
"currency" char(3) constraint bsb_purchase_requisitions_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"status" text not null default 'pending' constraint bsb_purchase_requisitions_status_check check ("status" in ('pending', 'approved', 'rejected', 'ordered', 'cancelled')),
"reason" text constraint bsb_purchase_requisitions_reason_check check (length("reason") <= 2000),
"requested_by" uuid default auth.uid(),
"decided_by" uuid,
"decided_at" timestamptz,
"approval_id" uuid,
"purchase_order_id" uuid references "better_supabase"."purchase_orders" ("id") on delete set null,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
constraint bsb_purchase_requisitions_check check (("supplier_type" is null) = ("supplier_id" is null))
);
create index purchase_requisitions_status_idx on "better_supabase"."purchase_requisitions" ("tenant_id", "status");
create index purchase_requisitions_location_idx on "better_supabase"."purchase_requisitions" ("location_id");
create index purchase_requisitions_purchase_order_idx on "better_supabase"."purchase_requisitions" ("purchase_order_id");
alter table "better_supabase"."purchase_requisitions" enable row level security;
revoke all on "better_supabase"."purchase_requisitions" from public, anon, authenticated;
grant select on "better_supabase"."purchase_requisitions" to authenticated;
grant all on "better_supabase"."purchase_requisitions" to service_role;
create policy bsb_purchase_requisitions_read on "better_supabase"."purchase_requisitions"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."purchase_requisition_lines" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"requisition_id" uuid not null references "better_supabase"."purchase_requisitions" ("id") on delete cascade,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"quantity" numeric(20, 6) not null constraint bsb_purchase_requisition_lines_quantity_check check ("quantity" > 0),
"unit_cost" bigint constraint bsb_purchase_requisition_lines_unit_cost_check check ("unit_cost" >= 0),
unique ("requisition_id", "variant_id")
);
create index purchase_requisition_lines_variant_idx on "better_supabase"."purchase_requisition_lines" ("variant_id");
alter table "better_supabase"."purchase_requisition_lines" enable row level security;
revoke all on "better_supabase"."purchase_requisition_lines" from public, anon, authenticated;
grant select on "better_supabase"."purchase_requisition_lines" to authenticated;
grant all on "better_supabase"."purchase_requisition_lines" to service_role;
create policy bsb_purchase_requisition_lines_read on "better_supabase"."purchase_requisition_lines"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."inventory_receipts" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"purchase_order_id" uuid not null references "better_supabase"."purchase_orders" ("id") on delete cascade,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"inspection_id" uuid,
"received_by" uuid default auth.uid(),
"received_at" timestamptz not null default now()
);
create index inventory_receipts_purchase_order_idx on "better_supabase"."inventory_receipts" ("purchase_order_id");
create index inventory_receipts_location_idx on "better_supabase"."inventory_receipts" ("location_id");
alter table "better_supabase"."inventory_receipts" enable row level security;
revoke all on "better_supabase"."inventory_receipts" from public, anon, authenticated;
grant select on "better_supabase"."inventory_receipts" to authenticated;
grant all on "better_supabase"."inventory_receipts" to service_role;
create policy bsb_inventory_receipts_read on "better_supabase"."inventory_receipts"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."inventory_receipt_lines" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"receipt_id" uuid not null references "better_supabase"."inventory_receipts" ("id") on delete cascade,
"purchase_order_line_id" uuid not null references "better_supabase"."purchase_order_lines" ("id") on delete cascade,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"quantity" numeric(20, 6) not null constraint bsb_inventory_receipt_lines_quantity_check check ("quantity" > 0),
"unit_cost" bigint not null constraint bsb_inventory_receipt_lines_unit_cost_check check ("unit_cost" >= 0),
"detail" jsonb
);
create index inventory_receipt_lines_receipt_idx on "better_supabase"."inventory_receipt_lines" ("receipt_id");
create index inventory_receipt_lines_order_line_idx on "better_supabase"."inventory_receipt_lines" ("purchase_order_line_id");
create index inventory_receipt_lines_variant_idx on "better_supabase"."inventory_receipt_lines" ("variant_id");
alter table "better_supabase"."inventory_receipt_lines" enable row level security;
revoke all on "better_supabase"."inventory_receipt_lines" from public, anon, authenticated;
grant select on "better_supabase"."inventory_receipt_lines" to authenticated;
grant all on "better_supabase"."inventory_receipt_lines" to service_role;
create policy bsb_inventory_receipt_lines_read on "better_supabase"."inventory_receipt_lines"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_items" (
"variant_id" uuid primary key references "better_supabase"."product_variants" ("id") on delete cascade,
"tenant_id" uuid not null,
"unit" text not null default 'item' constraint bsb_stock_items_unit_check check ("unit" ~ '^[a-z][a-z0-9_]{0,31}$'),
"scale" smallint not null default 0 constraint bsb_stock_items_scale_check check ("scale" >= 0 and "scale" <= 6),
"tracking" text not null default 'none' constraint bsb_stock_items_tracking_check check ("tracking" in ('none', 'lot', 'serial')),
"tracks_expiry" boolean not null default false,
"costing" text not null default 'none' constraint bsb_stock_items_costing_check check ("costing" in ('none', 'average')),
"currency" char(3) constraint bsb_stock_items_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"average_cost" numeric(24, 6) constraint bsb_stock_items_average_cost_check check ("average_cost" >= 0),
"updated_at" timestamptz not null default now(),
constraint bsb_stock_items_check check ("tracking" <> 'serial' or "scale" = 0),
constraint bsb_stock_items_check1 check ("costing" = 'none' or "currency" is not null)
);
create index stock_items_tenant_idx on "better_supabase"."stock_items" ("tenant_id");
alter table "better_supabase"."stock_items" enable row level security;
revoke all on "better_supabase"."stock_items" from public, anon, authenticated;
grant select on "better_supabase"."stock_items" to authenticated;
grant all on "better_supabase"."stock_items" to service_role;
create policy bsb_stock_items_read on "better_supabase"."stock_items"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_bins" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"code" text not null constraint bsb_stock_bins_code_check check ("code" ~ '^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$'),
"name" text constraint bsb_stock_bins_name_check check (length("name") >= 1 and length("name") <= 200),
"hold" boolean not null default false,
"active" boolean not null default true,
"created_at" timestamptz not null default now(),
unique ("location_id", "code")
);
create index stock_bins_tenant_idx on "better_supabase"."stock_bins" ("tenant_id");
alter table "better_supabase"."stock_bins" enable row level security;
revoke all on "better_supabase"."stock_bins" from public, anon, authenticated;
grant select on "better_supabase"."stock_bins" to authenticated;
grant all on "better_supabase"."stock_bins" to service_role;
create policy bsb_stock_bins_read on "better_supabase"."stock_bins"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_lots" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"code" text not null constraint bsb_stock_lots_code_check check (length("code") >= 1 and length("code") <= 100),
"expires_on" date,
"created_at" timestamptz not null default now(),
unique ("variant_id", "code")
);
create index stock_lots_expiry_idx on "better_supabase"."stock_lots" ("tenant_id", "expires_on") where "expires_on" is not null;
alter table "better_supabase"."stock_lots" enable row level security;
revoke all on "better_supabase"."stock_lots" from public, anon, authenticated;
grant select on "better_supabase"."stock_lots" to authenticated;
grant all on "better_supabase"."stock_lots" to service_role;
create policy bsb_stock_lots_read on "better_supabase"."stock_lots"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_serials" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"serial" text not null constraint bsb_stock_serials_serial_check check (length("serial") >= 1 and length("serial") <= 100),
"lot_id" uuid references "better_supabase"."stock_lots" ("id") on delete set null,
"location_id" uuid references "better_supabase"."inventory_locations" ("id") on delete set null,
"bin_id" uuid references "better_supabase"."stock_bins" ("id") on delete set null,
"status" text not null default 'in_stock' constraint bsb_stock_serials_status_check check ("status" in ('in_stock', 'out', 'scrapped')),
"movement_id" uuid,
"updated_at" timestamptz not null default now(),
unique ("variant_id", "serial")
);
create index stock_serials_location_id_idx on "better_supabase"."stock_serials" ("location_id");
create index stock_serials_bin_idx on "better_supabase"."stock_serials" ("bin_id");
create index stock_serials_lot_idx on "better_supabase"."stock_serials" ("lot_id");
create index stock_serials_movement_idx on "better_supabase"."stock_serials" ("movement_id");
create index stock_serials_tenant_idx on "better_supabase"."stock_serials" ("tenant_id");
alter table "better_supabase"."stock_serials" enable row level security;
revoke all on "better_supabase"."stock_serials" from public, anon, authenticated;
grant select on "better_supabase"."stock_serials" to authenticated;
grant all on "better_supabase"."stock_serials" to service_role;
create policy bsb_stock_serials_read on "better_supabase"."stock_serials"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_buckets" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"bin_id" uuid references "better_supabase"."stock_bins" ("id") on delete restrict,
"lot_id" uuid references "better_supabase"."stock_lots" ("id") on delete restrict,
"on_hand" numeric(20, 6) not null default 0,
"updated_at" timestamptz not null default now(),
constraint bsb_stock_buckets_check check ("bin_id" is not null or "lot_id" is not null),
unique nulls not distinct ("variant_id", "location_id", "bin_id", "lot_id")
);
create index stock_buckets_location_idx on "better_supabase"."stock_buckets" ("location_id");
create index stock_buckets_bin_idx on "better_supabase"."stock_buckets" ("bin_id");
create index stock_buckets_lot_idx on "better_supabase"."stock_buckets" ("lot_id");
create index stock_buckets_tenant_idx on "better_supabase"."stock_buckets" ("tenant_id");
alter table "better_supabase"."stock_buckets" enable row level security;
revoke all on "better_supabase"."stock_buckets" from public, anon, authenticated;
grant select on "better_supabase"."stock_buckets" to authenticated;
grant all on "better_supabase"."stock_buckets" to service_role;
create policy bsb_stock_buckets_read on "better_supabase"."stock_buckets"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
create table "better_supabase"."stock_allocations" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"document_type" text not null constraint bsb_stock_allocations_document_type_check check ("document_type" ~ '^[a-z][a-z0-9_]{0,62}$'),
"document_id" text not null constraint bsb_stock_allocations_document_id_check check (length("document_id") >= 1 and length("document_id") <= 200),
"line_id" text,
"quantity" numeric(20, 6) not null constraint bsb_stock_allocations_quantity_check check ("quantity" > 0),
"allocated" numeric(20, 6) not null default 0 constraint bsb_stock_allocations_allocated_check check ("allocated" >= 0),
"fulfilled" numeric(20, 6) not null default 0 constraint bsb_stock_allocations_fulfilled_check check ("fulfilled" >= 0),
"backordered" numeric(20, 6) generated always as (case when "status" = 'open' then "quantity" - "allocated" - "fulfilled" else 0 end) stored,
"status" text not null default 'open' constraint bsb_stock_allocations_status_check check ("status" in ('open', 'fulfilled', 'released')),
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
constraint bsb_stock_allocations_check check ("allocated" + "fulfilled" <= "quantity")
);
create index stock_allocations_document_idx on "better_supabase"."stock_allocations" ("tenant_id", "document_type", "document_id");
create index stock_allocations_open_idx on "better_supabase"."stock_allocations" ("variant_id", "location_id", "created_at") where "status" = 'open';
create index stock_allocations_location_idx on "better_supabase"."stock_allocations" ("location_id");
create index stock_allocations_variant_idx on "better_supabase"."stock_allocations" ("variant_id");
alter table "better_supabase"."stock_allocations" enable row level security;
revoke all on "better_supabase"."stock_allocations" from public, anon, authenticated;
grant select on "better_supabase"."stock_allocations" to authenticated;
grant all on "better_supabase"."stock_allocations" to service_role;
create policy bsb_stock_allocations_read on "better_supabase"."stock_allocations"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
-- A stock count: the stock of one location, counted line by line. Posting it
-- writes each line's variance to the ledger as one 'count' movement.
create table "better_supabase"."stock_counts" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"location_id" uuid not null references "better_supabase"."inventory_locations" ("id") on delete cascade,
"status" text not null default 'open' constraint bsb_stock_counts_status_check check ("status" in ('open', 'posted', 'cancelled')),
"note" text,
"opened_by" uuid default auth.uid(),
"posted_by" uuid,
"opened_at" timestamptz not null default now(),
"posted_at" timestamptz,
"updated_at" timestamptz not null default now()
);
create index stock_counts_location_idx on "better_supabase"."stock_counts" ("location_id");
create index stock_counts_status_idx on "better_supabase"."stock_counts" ("tenant_id", "status");
alter table "better_supabase"."stock_counts" enable row level security;
revoke all on "better_supabase"."stock_counts" from public, anon, authenticated;
grant select on "better_supabase"."stock_counts" to authenticated;
grant all on "better_supabase"."stock_counts" to service_role;
create policy bsb_stock_counts_read on "better_supabase"."stock_counts"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
-- One counted position: a variant in a bin, a lot or neither, or one serial
-- number. expected is the stock when the line was opened; variance is
-- counted minus expected and stays null until the line is counted.
create table "better_supabase"."stock_count_lines" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"count_id" uuid not null references "better_supabase"."stock_counts" ("id") on delete cascade,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"bin_id" uuid references "better_supabase"."stock_bins" ("id") on delete restrict,
"lot_id" uuid references "better_supabase"."stock_lots" ("id") on delete restrict,
"serial" text constraint bsb_stock_count_lines_serial_check check (length("serial") >= 1 and length("serial") <= 100),
"expected" numeric(20, 6) not null default 0 constraint bsb_stock_count_lines_expected_check check ("expected" >= 0),
"counted" numeric(20, 6) constraint bsb_stock_count_lines_counted_check check ("counted" >= 0),
"variance" numeric(20, 6) generated always as ("counted" - "expected") stored,
"movement_id" uuid,
"updated_at" timestamptz not null default now()
);
create unique index stock_count_lines_key on "better_supabase"."stock_count_lines" ("count_id", "variant_id", coalesce("bin_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("lot_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("serial", ''));
create index stock_count_lines_variant_idx on "better_supabase"."stock_count_lines" ("variant_id");
create index stock_count_lines_bin_idx on "better_supabase"."stock_count_lines" ("bin_id") where "bin_id" is not null;
create index stock_count_lines_lot_idx on "better_supabase"."stock_count_lines" ("lot_id") where "lot_id" is not null;
alter table "better_supabase"."stock_count_lines" enable row level security;
revoke all on "better_supabase"."stock_count_lines" from public, anon, authenticated;
grant select on "better_supabase"."stock_count_lines" to authenticated;
grant all on "better_supabase"."stock_count_lines" to service_role;
create policy bsb_stock_count_lines_read on "better_supabase"."stock_count_lines"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')));
-- Posts a stock movement to the ledger and applies it to its level and
-- buckets. detail is null or an object with binId, lotId or lot ({ code,
-- expiresOn }), serials (an array, one per unit of a serial-tracked
-- variant), and unitCost and currency for a receipt under average costing.
-- Without a bin or lot, stock leaves first-expiry-first-out: the lot that
-- expires first, then the stock outside any lot; a sale or a transfer out
-- skips hold bins and expired lots. A tracked variant without backorders
-- can't go below zero on hand in any bucket, and a sale or a transfer out
-- can't take available below zero. Returns the ledger transaction, the
-- movement's id.
create or replace function "better_supabase"."move_stock"(tenant uuid, variant uuid, location uuid, quantity numeric, reason text, reference_type text default null, reference_id text default null, note text default null, detail jsonb default null)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_unit text;
v_scale smallint;
v_tracking text;
v_expiry boolean;
v_costing text;
v_currency text;
v_average numeric;
v_factor numeric;
v_bin uuid;
v_lot uuid;
v_serials text[];
v_parts jsonb := '[]'::jsonb;
v_part record;
v_rest numeric;
v_take numeric;
v_lines jsonb := '[]'::jsonb;
v_held numeric := 0;
v_bucket numeric;
v_strict boolean;
v_id uuid;
v_on_hand numeric;
v_after numeric;
v_point numeric;
v_unbinned numeric;
v_total numeric;
v_value bigint := 0;
v_balance bigint;
v_value_account uuid;
v_suffix text;
begin
if move_stock.quantity is null or move_stock.quantity = 0 then
raise exception 'the quantity must not be zero' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
if move_stock.reason is null or move_stock.reason not in ('adjustment', 'damage', 'loss', 'count', 'expired', 'scrap', 'receipt', 'sale', 'return', 'transfer_out', 'transfer_in', 'consumption', 'production') then
raise exception 'unknown stock movement reason' using errcode = '22023', hint = 'INVENTORY_REASON_INVALID';
end if;
if move_stock.detail is not null and jsonb_typeof(move_stock.detail) <> 'object' then
raise exception 'detail must be an object' using errcode = '22023', hint = 'INVENTORY_DETAIL_INVALID';
end if;
select x."unit", x."scale", x."tracking", x."tracks_expiry", x."costing", x."currency", x."average_cost"
into v_unit, v_scale, v_tracking, v_expiry, v_costing, v_currency, v_average
from "better_supabase"."stock_items" x where x."variant_id" = move_stock.variant for update;
v_unit := coalesce(v_unit, 'item');
v_scale := coalesce(v_scale, 0);
v_tracking := coalesce(v_tracking, 'none');
v_costing := coalesce(v_costing, 'none');
v_factor := power(10::numeric, v_scale);
if move_stock.quantity * v_factor <> trunc(move_stock.quantity * v_factor) then
raise exception 'the quantity has more decimals than the variant''s scale' using errcode = '22023', hint = 'INVENTORY_QUANTITY_PRECISION';
end if;
v_strict := exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = move_stock.variant and cv."track_inventory" and not cv."allow_backorder");
v_bin := nullif(move_stock.detail ->> 'binId', '')::uuid;
v_lot := nullif(move_stock.detail ->> 'lotId', '')::uuid;
if v_lot is null and jsonb_typeof(move_stock.detail -> 'lot') = 'object' then
v_lot := "better_supabase"."stock_lot_for"(move_stock.tenant, move_stock.variant, move_stock.detail -> 'lot' ->> 'code',
nullif(move_stock.detail -> 'lot' ->> 'expiresOn', '')::date);
end if;
if v_lot is not null and not exists (select 1 from "better_supabase"."stock_lots" x where x."id" = v_lot and x."variant_id" = move_stock.variant) then
raise exception 'the lot isn''t a lot of this variant' using errcode = 'P0002', hint = 'INVENTORY_LOT_NOT_FOUND';
end if;
if v_bin is not null and not exists (select 1 from "better_supabase"."stock_bins" x where x."id" = v_bin and x."location_id" = move_stock.location) then
raise exception 'the bin isn''t at this location' using errcode = 'P0002', hint = 'INVENTORY_BIN_NOT_FOUND';
end if;
if jsonb_typeof(move_stock.detail -> 'serials') = 'array' then
v_serials := array(select jsonb_array_elements_text(move_stock.detail -> 'serials'));
end if;
if v_tracking = 'serial' then
if v_serials is null or cardinality(v_serials) <> abs(move_stock.quantity)
or (select count(distinct e) from unnest(v_serials) e where length(e) between 1 and 100) <> cardinality(v_serials) then
raise exception 'a serial-tracked variant needs one distinct serial number per unit' using errcode = '22023', hint = 'INVENTORY_SERIALS_REQUIRED';
end if;
elsif coalesce(cardinality(v_serials), 0) > 0 then
raise exception 'the variant doesn''t track serial numbers' using errcode = '22023', hint = 'INVENTORY_SERIALS_UNTRACKED';
end if;
if move_stock.quantity > 0 then
if v_tracking = 'lot' and v_lot is null and move_stock.reason in ('receipt', 'production') then
raise exception 'a lot-tracked variant receives stock into a lot' using errcode = '22023', hint = 'INVENTORY_LOT_REQUIRED';
end if;
if v_expiry and v_lot is not null and move_stock.reason in ('receipt', 'production')
and (select x."expires_on" from "better_supabase"."stock_lots" x where x."id" = v_lot) is null then
raise exception 'the variant tracks expiry, so its lots need an expiry date' using errcode = '22023', hint = 'INVENTORY_EXPIRY_REQUIRED';
end if;
if v_tracking = 'serial' then
if exists (select 1 from "better_supabase"."stock_serials" x where x."variant_id" = move_stock.variant and x."serial" = any (v_serials) and x."status" = 'in_stock') then
raise exception 'a serial number is already in stock' using errcode = '23505', hint = 'INVENTORY_SERIAL_IN_STOCK';
end if;
insert into "better_supabase"."stock_serials" as x ("tenant_id", "variant_id", "serial", "lot_id", "location_id", "bin_id", "status")
select move_stock.tenant, move_stock.variant, e, v_lot, move_stock.location, v_bin, 'in_stock' from unnest(v_serials) e
on conflict ("variant_id", "serial") do update
set "lot_id" = coalesce(excluded."lot_id", x."lot_id"), "location_id" = excluded."location_id",
"bin_id" = excluded."bin_id", "status" = 'in_stock', "updated_at" = now();
select jsonb_agg(jsonb_build_object('bin', v_bin, 'lot', g.lot, 'quantity', g.n)) into v_parts
from (select x."lot_id" as lot, count(*) as n from "better_supabase"."stock_serials" x
where x."variant_id" = move_stock.variant and x."serial" = any (v_serials) group by x."lot_id") g;
else
v_parts := jsonb_build_array(jsonb_build_object('bin', v_bin, 'lot', v_lot, 'quantity', move_stock.quantity));
end if;
elsif v_tracking = 'serial' then
if (select count(*) from "better_supabase"."stock_serials" x where x."variant_id" = move_stock.variant and x."serial" = any (v_serials)
and x."status" = 'in_stock' and x."location_id" = move_stock.location and (v_bin is null or x."bin_id" = v_bin)) <> cardinality(v_serials) then
raise exception 'a serial number isn''t in stock at this location' using errcode = 'P0002', hint = 'INVENTORY_SERIAL_NOT_IN_STOCK';
end if;
select jsonb_agg(jsonb_build_object('bin', g.bin, 'lot', g.lot, 'quantity', -g.n)) into v_parts
from (select x."bin_id" as bin, x."lot_id" as lot, count(*) as n from "better_supabase"."stock_serials" x
where x."variant_id" = move_stock.variant and x."serial" = any (v_serials) group by x."bin_id", x."lot_id") g;
update "better_supabase"."stock_serials" x set "status" = case when move_stock.reason = 'scrap' then 'scrapped' else 'out' end,
"location_id" = null, "bin_id" = null, "updated_at" = now()
where x."variant_id" = move_stock.variant and x."serial" = any (v_serials);
elsif v_bin is not null or v_lot is not null then
if v_lot is not null and move_stock.reason in ('sale', 'transfer_out', 'consumption')
and (select x."expires_on" from "better_supabase"."stock_lots" x where x."id" = v_lot) < current_date then
raise exception 'the lot has expired' using errcode = '55000', hint = 'INVENTORY_LOT_EXPIRED';
end if;
v_parts := jsonb_build_array(jsonb_build_object('bin', v_bin, 'lot', v_lot, 'quantity', move_stock.quantity));
else
v_rest := -move_stock.quantity;
for v_part in
select y."bin_id" as bin, y."lot_id" as lot, y."on_hand" as on_hand
from "better_supabase"."stock_buckets" y
left join "better_supabase"."stock_bins" bn on bn."id" = y."bin_id"
left join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id"
where y."variant_id" = move_stock.variant and y."location_id" = move_stock.location and y."on_hand" > 0
and (move_stock.reason not in ('sale', 'transfer_out', 'consumption')
or (not coalesce(bn."hold", false) and (lo."expires_on" is null or lo."expires_on" >= current_date)))
order by coalesce(bn."hold", false), lo."expires_on" nulls last, lo."code" nulls last, bn."code"
for update of y
loop
exit when v_rest <= 0;
v_take := least(v_rest, v_part.on_hand);
v_parts := v_parts || jsonb_build_array(jsonb_build_object('bin', v_part.bin, 'lot', v_part.lot, 'quantity', -v_take));
v_rest := v_rest - v_take;
end loop;
if v_rest > 0 then
v_parts := v_parts || jsonb_build_array(jsonb_build_object('bin', null, 'lot', null, 'quantity', -v_rest));
end if;
end if;
for v_part in
select nullif(p ->> 'bin', '')::uuid as bin, nullif(p ->> 'lot', '')::uuid as lot, (p ->> 'quantity')::numeric as quantity
from jsonb_array_elements(v_parts) p
loop
v_lines := v_lines || jsonb_build_array(jsonb_build_object('account', "better_supabase"."ledger_account_for"(move_stock.tenant, 'stock',
'stock:' || move_stock.variant::text || ':' || move_stock.location::text
|| case when v_part.bin is null and v_part.lot is null then '' else ':' || coalesce(v_part.bin::text, '-') || ':' || coalesce(v_part.lot::text, '-') end,
'Stock', v_unit, v_scale, 'product-variants', move_stock.variant::text, null, true, 'inventory.read', 'inventory',
jsonb_strip_nulls(jsonb_build_object('variantId', move_stock.variant, 'locationId', move_stock.location, 'binId', v_part.bin, 'lotId', v_part.lot))),
'amount', (v_part.quantity * v_factor)::bigint));
if v_part.bin is not null or v_part.lot is not null then
insert into "better_supabase"."stock_buckets" as x ("tenant_id", "variant_id", "location_id", "bin_id", "lot_id", "on_hand")
values (move_stock.tenant, move_stock.variant, move_stock.location, v_part.bin, v_part.lot, v_part.quantity)
on conflict ("variant_id", "location_id", "bin_id", "lot_id") do update
set "on_hand" = x."on_hand" + excluded."on_hand", "updated_at" = now()
returning x."on_hand" into v_bucket;
if v_bucket < 0 and v_strict then
raise exception 'not enough stock in this bin or lot' using errcode = '23514', hint = 'INVENTORY_INSUFFICIENT';
end if;
if v_part.bin is not null and (select x."hold" from "better_supabase"."stock_bins" x where x."id" = v_part.bin) then
v_held := v_held + v_part.quantity;
end if;
end if;
end loop;
v_suffix := case when v_unit = 'item' and v_scale = 0 then '' else ':' || v_unit || ':' || v_scale::text end;
v_lines := v_lines || jsonb_build_array(jsonb_build_object('account', "better_supabase"."ledger_account_for"(move_stock.tenant, 'stock_counter',
case move_stock.reason when 'adjustment' then 'stock:adjustments' when 'damage' then 'stock:adjustments' when 'loss' then 'stock:adjustments' when 'count' then 'stock:adjustments' when 'expired' then 'stock:adjustments' when 'scrap' then 'stock:adjustments' when 'receipt' then 'stock:suppliers' when 'sale' then 'stock:customers' when 'return' then 'stock:customers' when 'transfer_out' then 'stock:transit' when 'transfer_in' then 'stock:transit' when 'consumption' then 'stock:production' when 'production' then 'stock:production' end || v_suffix, case move_stock.reason when 'adjustment' then 'Adjustments' when 'damage' then 'Adjustments' when 'loss' then 'Adjustments' when 'count' then 'Adjustments' when 'expired' then 'Adjustments' when 'scrap' then 'Adjustments' when 'receipt' then 'Suppliers' when 'sale' then 'Customers' when 'return' then 'Customers' when 'transfer_out' then 'In transit' when 'transfer_in' then 'In transit' when 'consumption' then 'Production' when 'production' then 'Production' end, v_unit, v_scale,
null, null, null, true, 'inventory.read', 'inventory', null), 'amount', -(move_stock.quantity * v_factor)::bigint));
if v_costing = 'average' and move_stock.reason not in ('transfer_in', 'transfer_out') then
if move_stock.detail ? 'currency' and upper(move_stock.detail ->> 'currency') is distinct from v_currency then
raise exception 'the unit cost is in another currency than the variant''s costing' using errcode = '22023', hint = 'INVENTORY_COST_CURRENCY_MISMATCH';
end if;
select coalesce(sum(x."on_hand"), 0) into v_total from "better_supabase"."stock_levels" x where x."variant_id" = move_stock.variant;
v_value_account := "better_supabase"."ledger_account_for"(move_stock.tenant, 'stock_value', 'stock_value:' || move_stock.variant::text, 'Stock value',
v_currency, 0::smallint, 'product-variants', move_stock.variant::text, null, true, 'inventory.read', 'inventory',
jsonb_build_object('variantId', move_stock.variant));
v_balance := coalesce((select y."balance" from "better_supabase"."ledger_balances" y where y."account_id" = v_value_account), 0);
if move_stock.quantity > 0 then
v_value := round(move_stock.quantity * coalesce(nullif(move_stock.detail ->> 'unitCost', '')::numeric, v_average, 0));
elsif v_total + move_stock.quantity <= 0 then
v_value := -v_balance;
else
v_value := -round(-move_stock.quantity * coalesce(v_average, 0));
end if;
if v_value <> 0 then
v_lines := v_lines || jsonb_build_array(
jsonb_build_object('account', v_value_account, 'amount', v_value),
jsonb_build_object('account', "better_supabase"."ledger_account_for"(move_stock.tenant, 'stock_value_counter', case move_stock.reason when 'receipt' then 'stock_value:suppliers' when 'sale' then 'stock_value:cogs' when 'return' then 'stock_value:cogs' when 'consumption' then 'stock_value:production' when 'production' then 'stock_value:production' else 'stock_value:adjustments' end || ':' || v_currency,
case move_stock.reason when 'receipt' then 'Stock purchases' when 'sale' then 'Cost of goods sold' when 'return' then 'Cost of goods sold' when 'consumption' then 'Work in progress' when 'production' then 'Work in progress' else 'Stock adjustments' end || ' ' || v_currency, v_currency, 0::smallint, null, null, null, true, 'inventory.read', 'inventory', null),
'amount', -v_value));
end if;
update "better_supabase"."stock_items" x set "average_cost" = case when v_total + move_stock.quantity > 0
then round((v_balance + v_value)::numeric / (v_total + move_stock.quantity), 6) else x."average_cost" end,
"updated_at" = now()
where x."variant_id" = move_stock.variant;
end if;
v_id := "better_supabase"."ledger_post"(move_stock.tenant, 'stock.' || move_stock.reason, v_lines,
move_stock.reference_type, move_stock.reference_id, move_stock.note, null, null,
jsonb_strip_nulls(jsonb_build_object('variantId', move_stock.variant, 'locationId', move_stock.location, 'binId', v_bin, 'lotId', v_lot, 'reason', move_stock.reason,
'quantity', move_stock.quantity::text, 'unit', nullif(v_unit, 'item'))));
if v_serials is not null then
update "better_supabase"."stock_serials" x set "movement_id" = v_id
where x."variant_id" = move_stock.variant and x."serial" = any (v_serials);
end if;
insert into "better_supabase"."stock_levels" as x ("tenant_id", "variant_id", "location_id", "on_hand", "held")
values (move_stock.tenant, move_stock.variant, move_stock.location, move_stock.quantity, greatest(v_held, 0))
on conflict ("variant_id", "location_id") do update
set "on_hand" = x."on_hand" + excluded."on_hand", "held" = greatest(x."held" + v_held, 0), "updated_at" = now()
returning x."on_hand", x."available", x."reorder_point" into v_on_hand, v_after, v_point;
if move_stock.quantity < 0 and v_strict then
select v_on_hand - coalesce(sum(y."on_hand"), 0) into v_unbinned from "better_supabase"."stock_buckets" y
where y."variant_id" = move_stock.variant and y."location_id" = move_stock.location;
if v_on_hand < 0 or v_unbinned < 0 or (v_after < 0 and move_stock.reason in ('sale', 'transfer_out', 'consumption')) then
raise exception 'not enough stock at this location' using errcode = '23514', hint = 'INVENTORY_INSUFFICIENT';
end if;
end if;
if v_point is not null and (v_after - move_stock.quantity + v_held) > v_point and v_after <= v_point then
null;
end if;
if move_stock.quantity > 0 then
perform "better_supabase"."fill_backorders"(move_stock.tenant, move_stock.variant, move_stock.location);
end if;
return v_id;
end;
$$;
revoke execute on function "better_supabase"."move_stock"(uuid, uuid, uuid, numeric, text, text, text, text, jsonb) from public, anon, authenticated;
-- Sets how a variant's stock is counted: its unit and decimal scale, lot or
-- serial tracking, expiry dates and weighted average costing. Null keeps a
-- setting. The unit, scale, tracking and costing are fixed once the variant
-- has stock history. Returns the item.
create or replace function "better_supabase"."set_stock_item"(variant uuid, unit text, scale smallint, tracking text, tracks_expiry boolean, costing text, currency text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_tenant uuid;
v_row "better_supabase"."stock_items"%rowtype;
v_old "better_supabase"."stock_items"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select cv."tenant_id" into v_tenant from "better_supabase"."product_variants" cv where cv."id" = set_stock_item.variant;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
select * into v_old from "better_supabase"."stock_items" x where x."variant_id" = set_stock_item.variant for update;
v_row."variant_id" := set_stock_item.variant;
v_row."tenant_id" := v_tenant;
v_row."unit" := coalesce(set_stock_item.unit, v_old."unit", 'item');
v_row."scale" := coalesce(set_stock_item.scale, v_old."scale", 0);
v_row."tracking" := coalesce(set_stock_item.tracking, v_old."tracking", 'none');
v_row."tracks_expiry" := coalesce(set_stock_item.tracks_expiry, v_old."tracks_expiry", false);
v_row."costing" := coalesce(set_stock_item.costing, v_old."costing", 'none');
v_row."currency" := coalesce(upper(set_stock_item.currency), v_old."currency");
v_row."average_cost" := v_old."average_cost";
if v_row."unit" !~ '^[a-z][a-z0-9_]{0,31}$' then
raise exception 'the unit must be 1 to 32 lowercase letters, digits or underscores' using errcode = '22023', hint = 'INVENTORY_UNIT_INVALID';
end if;
if v_row."scale" not between 0 and 6 then
raise exception 'the scale must be 0 to 6 decimals' using errcode = '22023', hint = 'INVENTORY_SCALE_INVALID';
end if;
if v_row."tracking" not in ('none', 'lot', 'serial') then
raise exception 'tracking must be one of none, lot, serial' using errcode = '22023', hint = 'INVENTORY_TRACKING_INVALID';
end if;
if v_row."tracking" = 'serial' and v_row."scale" <> 0 then
raise exception 'serial tracking counts whole units, so the scale must be 0' using errcode = '22023', hint = 'INVENTORY_SCALE_INVALID';
end if;
if v_row."costing" not in ('none', 'average') then
raise exception 'costing must be one of none, average' using errcode = '22023', hint = 'INVENTORY_COSTING_INVALID';
end if;
if v_row."costing" <> 'none' and (v_row."currency" is null or "better_supabase"."currency_minor_units"(v_row."currency") is null) then
raise exception 'average costing needs an ISO 4217 currency' using errcode = '22023', hint = 'INVENTORY_CURRENCY_INVALID';
end if;
if (v_row."unit", v_row."scale", v_row."tracking", v_row."costing", v_row."currency")
is distinct from (coalesce(v_old."unit", 'item'), coalesce(v_old."scale", 0), coalesce(v_old."tracking", 'none'),
coalesce(v_old."costing", 'none'), v_old."currency")
and exists (select 1 from "better_supabase"."ledger_accounts" sa where sa."managed_by" = 'inventory' and sa."kind" = 'stock' and (case when sa."kind" = 'stock' then (sa."metadata" ->> 'variantId')::uuid end) = set_stock_item.variant) then
raise exception 'the variant has stock history; its unit, scale, tracking and costing are fixed' using errcode = '55000', hint = 'INVENTORY_ITEM_LOCKED';
end if;
v_row."updated_at" := now();
insert into "better_supabase"."stock_items" as x select v_row.*
on conflict ("variant_id") do update set "unit" = excluded."unit", "scale" = excluded."scale",
"tracking" = excluded."tracking", "tracks_expiry" = excluded."tracks_expiry", "costing" = excluded."costing",
"currency" = excluded."currency", "updated_at" = now();
return jsonb_build_object('variantId', v_row."variant_id", 'unit', v_row."unit", 'scale', v_row."scale",
'tracking', v_row."tracking", 'tracksExpiry', v_row."tracks_expiry", 'costing', v_row."costing",
'currency', v_row."currency", 'averageCost', v_row."average_cost"::text);
end;
$$;
revoke execute on function "better_supabase"."set_stock_item"(uuid, text, smallint, text, boolean, text, text) from public, anon;
grant execute on function "better_supabase"."set_stock_item"(uuid, text, smallint, text, boolean, text, text) to authenticated, service_role;
-- Creates a bin at a location (bin null) or updates one. Stock in a hold bin
-- counts as held: on hand, but not available to sell.
create or replace function "better_supabase"."upsert_bin"(location uuid, bin uuid, code text, name text, hold boolean, active boolean)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_tenant uuid;
v_id uuid := upsert_bin.bin;
v_hold boolean;
v_was boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" into v_tenant from "better_supabase"."inventory_locations" x where x."id" = upsert_bin.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if upsert_bin.code is null or upsert_bin.code !~ '^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$' then
raise exception 'the code must be 1 to 40 letters, digits, dots, dashes or underscores' using errcode = '22023', hint = 'INVENTORY_BIN_CODE_INVALID';
end if;
begin
if v_id is null then
insert into "better_supabase"."stock_bins" ("tenant_id", "location_id", "code", "name", "hold", "active")
values (v_tenant, upsert_bin.location, upsert_bin.code, upsert_bin.name, coalesce(upsert_bin.hold, false), coalesce(upsert_bin.active, true))
returning "id", "hold" into v_id, v_hold;
v_was := v_hold;
else
select x."hold" into v_was from "better_supabase"."stock_bins" x where x."id" = v_id and x."location_id" = upsert_bin.location for update;
if not found then
raise exception 'bin not found at this location' using errcode = 'P0002', hint = 'INVENTORY_BIN_NOT_FOUND';
end if;
update "better_supabase"."stock_bins" x set "code" = upsert_bin.code, "name" = upsert_bin.name,
"hold" = coalesce(upsert_bin.hold, x."hold"), "active" = coalesce(upsert_bin.active, x."active")
where x."id" = v_id
returning x."hold" into v_hold;
end if;
exception when unique_violation then
raise exception 'another bin at this location has this code' using errcode = '23505', hint = 'INVENTORY_BIN_CODE_TAKEN';
end;
if v_hold <> v_was then
update "better_supabase"."stock_levels" x set "held" = greatest(x."held" + case when v_hold then y.on_hand else -y.on_hand end, 0), "updated_at" = now()
from (select z."variant_id" as variant, sum(z."on_hand") as on_hand from "better_supabase"."stock_buckets" z
where z."bin_id" = v_id and z."on_hand" > 0 group by z."variant_id") y
where x."variant_id" = y.variant and x."location_id" = upsert_bin.location;
end if;
return jsonb_build_object('id', v_id, 'code', upsert_bin.code, 'hold', v_hold, 'active', coalesce(upsert_bin.active, true));
end;
$$;
revoke execute on function "better_supabase"."upsert_bin"(uuid, uuid, text, text, boolean, boolean) from public, anon;
grant execute on function "better_supabase"."upsert_bin"(uuid, uuid, text, text, boolean, boolean) to authenticated, service_role;
-- The lot of a variant with this code, created when missing. A given
-- expires_on replaces the stored one.
create or replace function "better_supabase"."stock_lot_for"(tenant uuid, variant uuid, code text, expires_on date)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_id uuid;
begin
if stock_lot_for.code is null or length(stock_lot_for.code) not between 1 and 100 then
raise exception 'a lot code is 1 to 100 characters' using errcode = '22023', hint = 'INVENTORY_LOT_INVALID';
end if;
insert into "better_supabase"."stock_lots" as x ("tenant_id", "variant_id", "code", "expires_on")
values (stock_lot_for.tenant, stock_lot_for.variant, stock_lot_for.code, stock_lot_for.expires_on)
on conflict ("variant_id", "code") do update
set "expires_on" = coalesce(excluded."expires_on", x."expires_on")
returning x."id" into v_id;
return v_id;
end;
$$;
revoke execute on function "better_supabase"."stock_lot_for"(uuid, uuid, text, date) from public, anon, authenticated;
-- Creates a lot of a variant or updates its expiry date. Returns the lot.
create or replace function "better_supabase"."upsert_lot"(variant uuid, code text, expires_on date)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_id uuid;
begin
select cv."tenant_id" into v_tenant from "better_supabase"."product_variants" cv where cv."id" = upsert_lot.variant;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
v_id := "better_supabase"."stock_lot_for"(v_tenant, upsert_lot.variant, upsert_lot.code, upsert_lot.expires_on);
return (select jsonb_build_object('id', x."id", 'code', x."code", 'expiresOn', x."expires_on")
from "better_supabase"."stock_lots" x where x."id" = v_id);
end;
$$;
revoke execute on function "better_supabase"."upsert_lot"(uuid, text, date) from public, anon;
grant execute on function "better_supabase"."upsert_lot"(uuid, text, date) to authenticated, service_role;
-- A variant's stock at a location: the level, each bin and lot bucket, the
-- stock outside any bin or lot, and the serial numbers in stock there.
create or replace function "better_supabase"."stock_detail"(variant uuid, location uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_level record;
v_buckets jsonb;
v_bucketed numeric;
begin
select x."tenant_id" into v_tenant from "better_supabase"."inventory_locations" x where x."id" = stock_detail.location;
if v_tenant is null or not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.read'), false)) then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
select x."on_hand" as on_hand, x."reserved" as reserved, x."held" as held, x."available" as available
into v_level from "better_supabase"."stock_levels" x where x."variant_id" = stock_detail.variant and x."location_id" = stock_detail.location;
select coalesce(jsonb_agg(jsonb_build_object('binId', y."bin_id", 'binCode', bn."code", 'hold', coalesce(bn."hold", false),
'lotId', y."lot_id", 'lotCode', lo."code", 'expiresOn', lo."expires_on", 'onHand', y."on_hand"::text)
order by lo."expires_on" nulls last, bn."code" nulls first, lo."code"), '[]'::jsonb),
coalesce(sum(y."on_hand"), 0)
into v_buckets, v_bucketed
from "better_supabase"."stock_buckets" y
left join "better_supabase"."stock_bins" bn on bn."id" = y."bin_id"
left join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id"
where y."variant_id" = stock_detail.variant and y."location_id" = stock_detail.location and y."on_hand" <> 0;
return jsonb_build_object('variantId', stock_detail.variant, 'locationId', stock_detail.location,
'onHand', coalesce(v_level.on_hand, 0)::text, 'reserved', coalesce(v_level.reserved, 0)::text,
'held', coalesce(v_level.held, 0)::text, 'available', coalesce(v_level.available, 0)::text,
'unbinned', (coalesce(v_level.on_hand, 0) - v_bucketed)::text, 'buckets', v_buckets,
'serials', coalesce((select jsonb_agg(z."serial" order by z."serial") from "better_supabase"."stock_serials" z
where z."variant_id" = stock_detail.variant and z."location_id" = stock_detail.location and z."status" = 'in_stock'), '[]'::jsonb));
end;
$$;
revoke execute on function "better_supabase"."stock_detail"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."stock_detail"(uuid, uuid) to authenticated, service_role;
create or replace function "better_supabase"."pick_serials"(variant uuid, location uuid, quantity integer, lot uuid default null)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_serials jsonb;
begin
select x."tenant_id" into v_tenant from "better_supabase"."inventory_locations" x where x."id" = pick_serials.location;
if v_tenant is null or not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.read'), false)) then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if pick_serials.quantity is null or pick_serials.quantity <= 0 then
raise exception 'the quantity must be greater than zero' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
select jsonb_agg(z."serial" order by z."updated_at", z."serial") into v_serials from (
select y."serial", y."updated_at" from "better_supabase"."stock_serials" y
where y."variant_id" = pick_serials.variant and y."location_id" = pick_serials.location
and y."status" = 'in_stock' and (pick_serials.lot is null or y."lot_id" = pick_serials.lot)
order by y."updated_at", y."serial" limit pick_serials.quantity
) z;
if coalesce(jsonb_array_length(v_serials), 0) < pick_serials.quantity then
raise exception 'not enough stock available' using errcode = '23514', hint = 'INVENTORY_INSUFFICIENT';
end if;
return v_serials;
end;
$$;
revoke execute on function "better_supabase"."pick_serials"(uuid, uuid, integer, uuid) from public, anon;
grant execute on function "better_supabase"."pick_serials"(uuid, uuid, integer, uuid) to authenticated, service_role;
-- The lots with stock that expire on or before a date, soonest first.
create or replace function "better_supabase"."expiring_lots"(tenant uuid, before date)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
begin
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', expiring_lots.tenant, 'inventory.read'), false)) then
raise exception 'not allowed to read this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
return coalesce((select jsonb_agg(jsonb_build_object('lotId', lo."id", 'code', lo."code", 'variantId', lo."variant_id",
'locationId', y."location_id", 'binId', y."bin_id", 'expiresOn', lo."expires_on", 'onHand', y."on_hand"::text)
order by lo."expires_on", lo."code", y."location_id")
from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id"
where y."tenant_id" = expiring_lots.tenant and y."on_hand" > 0
and lo."expires_on" <= coalesce(expiring_lots.before, current_date)), '[]'::jsonb);
end;
$$;
revoke execute on function "better_supabase"."expiring_lots"(uuid, date) from public, anon;
grant execute on function "better_supabase"."expiring_lots"(uuid, date) to authenticated, service_role;
-- Writes off the stock of every lot that expired before as_of (today by
-- default) with an expired movement. Returns how many buckets it emptied.
create or replace function "better_supabase"."expire_lots"(tenant uuid, as_of date)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_count integer := 0;
begin
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', expire_lots.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
for v_row in
select y."variant_id" as variant, y."location_id" as location, y."bin_id" as bin, y."lot_id" as lot, y."on_hand" as on_hand,
(select array_agg(z."serial") from "better_supabase"."stock_serials" z where z."variant_id" = y."variant_id" and z."lot_id" = y."lot_id"
and z."location_id" = y."location_id" and z."bin_id" is not distinct from y."bin_id" and z."status" = 'in_stock') as serials
from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id"
where y."tenant_id" = expire_lots.tenant and y."on_hand" > 0 and lo."expires_on" < coalesce(expire_lots.as_of, current_date)
order by lo."expires_on"
for update of y
loop
perform "better_supabase"."move_stock"(expire_lots.tenant, v_row.variant, v_row.location, -v_row.on_hand, 'expired', 'stock_lot', v_row.lot::text, null, jsonb_strip_nulls(jsonb_build_object('binId', v_row.bin, 'lotId', v_row.lot, 'serials', to_jsonb(v_row.serials))));
v_count := v_count + 1;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."expire_lots"(uuid, date) from public, anon;
grant execute on function "better_supabase"."expire_lots"(uuid, date) to authenticated, service_role;
-- A variant's weighted average cost, its stock across locations and the value
-- of that stock in minor units of the cost currency.
create or replace function "better_supabase"."stock_valuation"(variant uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_item record;
begin
select cv."tenant_id" into v_tenant from "better_supabase"."product_variants" cv where cv."id" = stock_valuation.variant;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.read'), false)) then
raise exception 'not allowed to read this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
select x."costing" as costing, x."currency" as currency, x."average_cost" as average_cost
into v_item from "better_supabase"."stock_items" x where x."variant_id" = stock_valuation.variant;
return jsonb_build_object('variantId', stock_valuation.variant, 'costing', coalesce(v_item.costing, 'none'),
'currency', v_item.currency, 'averageCost', v_item.average_cost::text,
'onHand', (select coalesce(sum(x."on_hand"), 0) from "better_supabase"."stock_levels" x where x."variant_id" = stock_valuation.variant)::text,
'value', coalesce((select y."balance" from "better_supabase"."ledger_accounts" a join "better_supabase"."ledger_balances" y on y."account_id" = a."id"
where a."tenant_id" = v_tenant and a."code" = 'stock_value:' || stock_valuation.variant::text), 0)::text);
end;
$$;
revoke execute on function "better_supabase"."stock_valuation"(uuid) from public, anon;
grant execute on function "better_supabase"."stock_valuation"(uuid) to authenticated, service_role;
-- Gives open backorders of a variant at a location the stock that became
-- available, oldest allocation first. Returns how much it allocated.
create or replace function "better_supabase"."fill_backorders"(tenant uuid, variant uuid, location uuid)
returns numeric
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_available numeric;
v_take numeric;
v_total numeric := 0;
begin
select x."available" into v_available from "better_supabase"."stock_levels" x
where x."variant_id" = fill_backorders.variant and x."location_id" = fill_backorders.location for update;
if coalesce(v_available, 0) <= 0 then
return 0;
end if;
for v_row in
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."backordered" as quantity
from "better_supabase"."stock_allocations" x
where x."variant_id" = fill_backorders.variant and x."location_id" = fill_backorders.location
and x."status" = 'open' and x."backordered" > 0
order by x."created_at", x."id"
for update
loop
exit when v_available <= 0;
v_take := least(v_available, v_row.quantity);
update "better_supabase"."stock_allocations" x set "allocated" = x."allocated" + v_take, "updated_at" = now() where x."id" = v_row.id;
v_available := v_available - v_take;
v_total := v_total + v_take;
null;
end loop;
if v_total > 0 then
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" + v_total, 0), "updated_at" = now()
where x."variant_id" = fill_backorders.variant and x."location_id" = fill_backorders.location;
end if;
return v_total;
end;
$$;
revoke execute on function "better_supabase"."fill_backorders"(uuid, uuid, uuid) from public, anon, authenticated;
-- Allocates stock of a variant to a document line. location null picks the
-- active location with the most available. What isn't available stays on
-- backorder; backorder false raises INVENTORY_INSUFFICIENT instead for a
-- variant that can't go below zero. Returns the allocation.
create or replace function "better_supabase"."allocate_stock"(tenant uuid, variant uuid, location uuid, quantity numeric, document_type text, document_id text, line_id text, backorder boolean default true)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_location uuid := allocate_stock.location;
v_available numeric;
v_take numeric;
v_row record;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', allocate_stock.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = allocate_stock.variant and cv."tenant_id" = allocate_stock.tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if allocate_stock.quantity is null or allocate_stock.quantity <= 0 then
raise exception 'the quantity must be greater than zero' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
if allocate_stock.document_type is null or allocate_stock.document_id is null then
raise exception 'an allocation names its document type and id' using errcode = '22023', hint = 'INVENTORY_DOCUMENT_INVALID';
end if;
if v_location is null then
select y."id" into v_location from "better_supabase"."inventory_locations" y
left join "better_supabase"."stock_levels" s on s."location_id" = y."id" and s."variant_id" = allocate_stock.variant
where y."tenant_id" = allocate_stock.tenant and y."active"
order by coalesce(s."available", 0) desc, y."code"
limit 1;
if v_location is null then
raise exception 'the organization has no active location' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
elsif not exists (select 1 from "better_supabase"."inventory_locations" y where y."id" = v_location and y."tenant_id" = allocate_stock.tenant and y."active") then
raise exception 'location not found or inactive' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
insert into "better_supabase"."stock_levels" ("tenant_id", "variant_id", "location_id")
values (allocate_stock.tenant, allocate_stock.variant, v_location)
on conflict ("variant_id", "location_id") do nothing;
select x."available" into v_available from "better_supabase"."stock_levels" x
where x."variant_id" = allocate_stock.variant and x."location_id" = v_location for update;
v_take := least(allocate_stock.quantity, greatest(v_available, 0));
if v_take < allocate_stock.quantity and not coalesce(allocate_stock.backorder, true) and exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = allocate_stock.variant and cv."track_inventory" and not cv."allow_backorder") then
raise exception 'not enough stock available' using errcode = '23514', hint = 'INVENTORY_INSUFFICIENT';
end if;
insert into "better_supabase"."stock_allocations" as x ("tenant_id", "variant_id", "location_id", "document_type", "document_id", "line_id", "quantity", "allocated")
values (allocate_stock.tenant, allocate_stock.variant, v_location, allocate_stock.document_type, allocate_stock.document_id,
allocate_stock.line_id, allocate_stock.quantity, v_take)
returning x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity
into v_row;
if v_take > 0 then
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" + v_take, 0), "updated_at" = now()
where x."variant_id" = allocate_stock.variant and x."location_id" = v_location;
end if;
null;
return (select jsonb_build_object('id', x."id", 'variantId', x."variant_id", 'locationId', x."location_id",
'documentType', x."document_type", 'documentId', x."document_id", 'lineId', x."line_id",
'quantity', x."quantity"::text, 'allocated', x."allocated"::text, 'fulfilled', x."fulfilled"::text,
'backordered', x."backordered"::text, 'status', x."status", 'createdAt', x."created_at") from "better_supabase"."stock_allocations" x where x."id" = v_row.id);
end;
$$;
revoke execute on function "better_supabase"."allocate_stock"(uuid, uuid, uuid, numeric, text, text, text, boolean) from public, anon;
grant execute on function "better_supabase"."allocate_stock"(uuid, uuid, uuid, numeric, text, text, text, boolean) to authenticated, service_role;
-- Takes quantity of an allocation out of stock with a movement of reason,
-- first from what it holds, then from what's available. The caller checks
-- permissions; fulfill_allocation and the production functions call it.
create or replace function "better_supabase"."take_allocation"(allocation uuid, quantity numeric, reason text, detail jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row record;
v_from_held numeric;
v_movement uuid;
begin
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity,
x."allocated" as allocated, x."fulfilled" as fulfilled, x."status" as status
into v_row from "better_supabase"."stock_allocations" x where x."id" = take_allocation.allocation for update;
if not found then
raise exception 'allocation not found' using errcode = 'P0002', hint = 'INVENTORY_ALLOCATION_NOT_FOUND';
end if;
if v_row.status <> 'open' then
raise exception 'the allocation is no longer open' using errcode = '55000', hint = 'INVENTORY_ALLOCATION_CLOSED';
end if;
if take_allocation.quantity is null or take_allocation.quantity <= 0
or take_allocation.quantity > v_row.quantity - v_row.fulfilled then
raise exception 'the quantity must be more than zero and at most what the allocation has left' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
v_from_held := least(take_allocation.quantity, v_row.allocated);
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" + -v_from_held, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
update "better_supabase"."stock_allocations" x set "allocated" = x."allocated" - v_from_held,
"fulfilled" = x."fulfilled" + take_allocation.quantity,
"status" = case when x."fulfilled" + take_allocation.quantity >= x."quantity" then 'fulfilled' else 'open' end,
"updated_at" = now()
where x."id" = v_row.id;
v_movement := "better_supabase"."move_stock"(v_row.tenant, v_row.variant, v_row.location, -take_allocation.quantity, take_allocation.reason, v_row.document_type, v_row.document_id, null, take_allocation.detail);
return (select jsonb_build_object('id', x."id", 'variantId', x."variant_id", 'locationId', x."location_id",
'documentType', x."document_type", 'documentId', x."document_id", 'lineId', x."line_id",
'quantity', x."quantity"::text, 'allocated', x."allocated"::text, 'fulfilled', x."fulfilled"::text,
'backordered', x."backordered"::text, 'status', x."status", 'createdAt', x."created_at") || jsonb_build_object('movementId', v_movement) from "better_supabase"."stock_allocations" x where x."id" = v_row.id);
end;
$$;
revoke execute on function "better_supabase"."take_allocation"(uuid, numeric, text, jsonb) from public, anon, authenticated;
-- Takes quantity of an allocation out of stock as a sale, first from what it
-- holds, then from what's available. detail picks the bin, lot or serial
-- numbers, as for move_stock. Returns the allocation and the movement id.
create or replace function "better_supabase"."fulfill_allocation"(allocation uuid, quantity numeric, detail jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row record;
begin
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity,
x."allocated" as allocated, x."fulfilled" as fulfilled, x."status" as status
into v_row from "better_supabase"."stock_allocations" x where x."id" = fulfill_allocation.allocation for update;
if not found then
raise exception 'allocation not found' using errcode = 'P0002', hint = 'INVENTORY_ALLOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
return "better_supabase"."take_allocation"(fulfill_allocation.allocation, fulfill_allocation.quantity, 'sale', fulfill_allocation.detail);
end;
$$;
revoke execute on function "better_supabase"."fulfill_allocation"(uuid, numeric, jsonb) from public, anon;
grant execute on function "better_supabase"."fulfill_allocation"(uuid, numeric, jsonb) to authenticated, service_role;
-- Puts fulfilled stock of an allocation back, as a return movement: a
-- cancelled shipment. The allocation reopens and the stock fills it (or an
-- older backorder) again. Returns the allocation and the movement id.
create or replace function "better_supabase"."restore_allocation"(allocation uuid, quantity numeric, detail jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row record;
v_movement uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity,
x."allocated" as allocated, x."fulfilled" as fulfilled, x."status" as status
into v_row from "better_supabase"."stock_allocations" x where x."id" = restore_allocation.allocation for update;
if not found then
raise exception 'allocation not found' using errcode = 'P0002', hint = 'INVENTORY_ALLOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status = 'released' then
raise exception 'the allocation was released' using errcode = '55000', hint = 'INVENTORY_ALLOCATION_CLOSED';
end if;
if restore_allocation.quantity is null or restore_allocation.quantity <= 0 or restore_allocation.quantity > v_row.fulfilled then
raise exception 'the quantity must be more than zero and at most what was fulfilled' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
update "better_supabase"."stock_allocations" x set "fulfilled" = x."fulfilled" - restore_allocation.quantity, "status" = 'open', "updated_at" = now()
where x."id" = v_row.id;
v_movement := "better_supabase"."move_stock"(v_row.tenant, v_row.variant, v_row.location, restore_allocation.quantity, 'return', v_row.document_type, v_row.document_id, null, restore_allocation.detail);
return (select jsonb_build_object('id', x."id", 'variantId', x."variant_id", 'locationId', x."location_id",
'documentType', x."document_type", 'documentId', x."document_id", 'lineId', x."line_id",
'quantity', x."quantity"::text, 'allocated', x."allocated"::text, 'fulfilled', x."fulfilled"::text,
'backordered', x."backordered"::text, 'status', x."status", 'createdAt', x."created_at") || jsonb_build_object('movementId', v_movement) from "better_supabase"."stock_allocations" x where x."id" = v_row.id);
end;
$$;
revoke execute on function "better_supabase"."restore_allocation"(uuid, numeric, jsonb) from public, anon;
grant execute on function "better_supabase"."restore_allocation"(uuid, numeric, jsonb) to authenticated, service_role;
-- Releases a document's open allocations: what they hold goes back to
-- available and their backorders close. Returns how many it released.
create or replace function "better_supabase"."release_allocations"(tenant uuid, document_type text, document_id text)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row record;
v_count integer := 0;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', release_allocations.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
for v_row in
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity, x."allocated" as allocated
from "better_supabase"."stock_allocations" x
where x."tenant_id" = release_allocations.tenant and x."document_type" = release_allocations.document_type
and x."document_id" = release_allocations.document_id and x."status" = 'open'
order by x."created_at"
for update
loop
if v_row.allocated > 0 then
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" + -v_row.allocated, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
end if;
update "better_supabase"."stock_allocations" x set "allocated" = 0, "status" = 'released', "updated_at" = now() where x."id" = v_row.id;
null;
if v_row.allocated > 0 then
perform "better_supabase"."fill_backorders"(v_row.tenant, v_row.variant, v_row.location);
end if;
v_count := v_count + 1;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."release_allocations"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."release_allocations"(uuid, text, text) to authenticated, service_role;
-- Releases one open allocation: what it holds goes back to available and its
-- backorder closes. A quantity below what the allocation has left releases only
-- that much, backorder first, and shrinks the allocation. Returns the allocation.
create or replace function "better_supabase"."release_allocation"(allocation uuid, quantity numeric default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row record;
v_left numeric;
v_backorder numeric;
v_held numeric;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity,
x."allocated" as allocated, x."fulfilled" as fulfilled, x."status" as status
into v_row from "better_supabase"."stock_allocations" x where x."id" = release_allocation.allocation for update;
if not found then
raise exception 'allocation not found' using errcode = 'P0002', hint = 'INVENTORY_ALLOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'open' then
raise exception 'the allocation is no longer open' using errcode = '55000', hint = 'INVENTORY_ALLOCATION_CLOSED';
end if;
v_left := v_row.quantity - v_row.fulfilled;
if release_allocation.quantity is not null
and (release_allocation.quantity <= 0 or release_allocation.quantity > v_left) then
raise exception 'the quantity must be more than zero and at most what the allocation has left' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
if release_allocation.quantity is null or release_allocation.quantity = v_left then
v_held := v_row.allocated;
if v_held > 0 then
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" + -v_held, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
end if;
update "better_supabase"."stock_allocations" x set "allocated" = 0, "status" = 'released', "updated_at" = now() where x."id" = v_row.id;
else
v_backorder := v_left - v_row.allocated;
v_held := greatest(release_allocation.quantity - v_backorder, 0);
if v_held > 0 then
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" + -v_held, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
end if;
update "better_supabase"."stock_allocations" x set "allocated" = x."allocated" - v_held,
"quantity" = x."quantity" - release_allocation.quantity, "updated_at" = now()
where x."id" = v_row.id;
end if;
null;
if v_held > 0 then
perform "better_supabase"."fill_backorders"(v_row.tenant, v_row.variant, v_row.location);
end if;
return (select jsonb_build_object('id', x."id", 'variantId', x."variant_id", 'locationId', x."location_id",
'documentType', x."document_type", 'documentId', x."document_id", 'lineId', x."line_id",
'quantity', x."quantity"::text, 'allocated', x."allocated"::text, 'fulfilled', x."fulfilled"::text,
'backordered', x."backordered"::text, 'status', x."status", 'createdAt', x."created_at") from "better_supabase"."stock_allocations" x where x."id" = v_row.id);
end;
$$;
revoke execute on function "better_supabase"."release_allocation"(uuid, numeric) from public, anon;
grant execute on function "better_supabase"."release_allocation"(uuid, numeric) to authenticated, service_role;
-- Moves an open allocation to another document (a quote that became an order),
-- keeping what it holds. line_id names the line on the new document. A quantity
-- below what the allocation has left moves only that much, holding stock first,
-- into a new allocation and leaves the rest where it was. Returns the moved
-- allocation.
create or replace function "better_supabase"."transfer_allocation"(allocation uuid, document_type text, document_id text, line_id text default null, quantity numeric default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row record;
v_left numeric;
v_held numeric;
v_new uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."document_type" as document_type, x."document_id" as document_id, x."quantity" as quantity,
x."allocated" as allocated, x."fulfilled" as fulfilled, x."status" as status
into v_row from "better_supabase"."stock_allocations" x where x."id" = transfer_allocation.allocation for update;
if not found then
raise exception 'allocation not found' using errcode = 'P0002', hint = 'INVENTORY_ALLOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'open' then
raise exception 'the allocation is no longer open' using errcode = '55000', hint = 'INVENTORY_ALLOCATION_CLOSED';
end if;
if transfer_allocation.document_type is null or transfer_allocation.document_id is null then
raise exception 'an allocation names its document type and id' using errcode = '22023', hint = 'INVENTORY_DOCUMENT_INVALID';
end if;
v_left := v_row.quantity - v_row.fulfilled;
if transfer_allocation.quantity is not null
and (transfer_allocation.quantity <= 0 or transfer_allocation.quantity > v_left) then
raise exception 'the quantity must be more than zero and at most what the allocation has left' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
if transfer_allocation.quantity is null or transfer_allocation.quantity = v_left then
update "better_supabase"."stock_allocations" x set "document_type" = transfer_allocation.document_type, "document_id" = transfer_allocation.document_id,
"line_id" = transfer_allocation.line_id, "updated_at" = now()
where x."id" = v_row.id;
v_new := v_row.id;
else
v_held := least(transfer_allocation.quantity, v_row.allocated);
update "better_supabase"."stock_allocations" x set "allocated" = x."allocated" - v_held,
"quantity" = x."quantity" - transfer_allocation.quantity, "updated_at" = now()
where x."id" = v_row.id;
insert into "better_supabase"."stock_allocations" ("tenant_id", "variant_id", "location_id", "document_type", "document_id", "line_id", "quantity", "allocated")
values (v_row.tenant, v_row.variant, v_row.location, transfer_allocation.document_type, transfer_allocation.document_id,
transfer_allocation.line_id, transfer_allocation.quantity, v_held)
returning "id" into v_new;
end if;
null;
return (select jsonb_build_object('id', x."id", 'variantId', x."variant_id", 'locationId', x."location_id",
'documentType', x."document_type", 'documentId', x."document_id", 'lineId', x."line_id",
'quantity', x."quantity"::text, 'allocated', x."allocated"::text, 'fulfilled', x."fulfilled"::text,
'backordered', x."backordered"::text, 'status', x."status", 'createdAt', x."created_at") from "better_supabase"."stock_allocations" x where x."id" = v_new);
end;
$$;
revoke execute on function "better_supabase"."transfer_allocation"(uuid, text, text, text, numeric) from public, anon;
grant execute on function "better_supabase"."transfer_allocation"(uuid, text, text, text, numeric) to authenticated, service_role;
-- A document's allocations, oldest first.
create or replace function "better_supabase"."list_allocations"(tenant uuid, document_type text, document_id text)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
begin
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', list_allocations.tenant, 'inventory.read'), false)) then
raise exception 'not allowed to read this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
return coalesce((select jsonb_agg(jsonb_build_object('id', x."id", 'variantId', x."variant_id", 'locationId', x."location_id",
'documentType', x."document_type", 'documentId', x."document_id", 'lineId', x."line_id",
'quantity', x."quantity"::text, 'allocated', x."allocated"::text, 'fulfilled', x."fulfilled"::text,
'backordered', x."backordered"::text, 'status', x."status", 'createdAt', x."created_at") order by x."created_at", x."id")
from "better_supabase"."stock_allocations" x where x."tenant_id" = list_allocations.tenant
and x."document_type" = list_allocations.document_type and x."document_id" = list_allocations.document_id), '[]'::jsonb);
end;
$$;
revoke execute on function "better_supabase"."list_allocations"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."list_allocations"(uuid, text, text) to authenticated, service_role;
-- The import target of the stock_allocation entity: item.data is { variantId or
-- sku, locationId or location (a code), documentType, documentId, lineId?,
-- quantity, allocated?, fulfilled?, status? (open, fulfilled or released) }.
-- allocated is the part held for the document now and fulfilled the part that
-- already shipped; both default to zero, and a fulfilled or released
-- allocation holds nothing. An open allocation adds what it holds to the
-- location's reserved stock, and nothing else moves: no movement, no event.
-- Importing the same key again replaces an open allocation and keeps a
-- fulfilled or released one as it is, with a warning.
create or replace function "better_supabase"."import_stock_allocation"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_stock_allocation.item ->> 'tenant')::uuid;
v_data jsonb := import_stock_allocation.item -> 'data';
v_variant uuid;
v_location uuid;
v_quantity numeric;
v_allocated numeric;
v_fulfilled numeric;
v_status text := coalesce(nullif(v_data ->> 'status', ''), 'open');
v_row record;
v_id uuid;
v_updated timestamptz;
begin
begin
v_variant := nullif(v_data ->> 'variantId', '')::uuid;
v_location := nullif(v_data ->> 'locationId', '')::uuid;
v_quantity := (v_data ->> 'quantity')::numeric;
v_allocated := coalesce((v_data ->> 'allocated')::numeric, 0);
v_fulfilled := coalesce((v_data ->> 'fulfilled')::numeric, 0);
exception when invalid_text_representation or numeric_value_out_of_range then
raise exception 'ids are uuids and quantity, allocated and fulfilled are numbers' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_status not in ('open', 'fulfilled', 'released') then
raise exception 'status is open, fulfilled or released' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_quantity is null or v_quantity <= 0 or v_allocated < 0 or v_fulfilled < 0 or v_allocated + v_fulfilled > v_quantity then
raise exception 'quantity is above zero and allocated plus fulfilled isn''t more than the quantity' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if coalesce(v_data ->> 'documentType', '') !~ '^[a-z][a-z0-9_]{0,62}$' or length(coalesce(v_data ->> 'documentId', '')) not between 1 and 200 then
raise exception 'an allocation names its document type (lower case, with underscores) and its document id' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_variant is null then
select y."id" into v_variant from "better_supabase"."product_variants" y where y."tenant_id" = v_tenant and y."sku" = v_data ->> 'sku';
end if;
if v_variant is null or not exists (select 1 from "better_supabase"."product_variants" y where y."id" = v_variant and y."tenant_id" = v_tenant) then
raise exception 'the allocation''s variant isn''t in this organization' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_location is null then
select x."id" into v_location from "better_supabase"."inventory_locations" x where x."tenant_id" = v_tenant and x."code" = v_data ->> 'location';
elsif not exists (select 1 from "better_supabase"."inventory_locations" x where x."id" = v_location and x."tenant_id" = v_tenant) then
v_location := null;
end if;
if v_location is null then
raise exception 'the allocation''s location isn''t in this organization' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_status <> 'open' then
v_allocated := 0;
end if;
if v_status = 'fulfilled' then
v_fulfilled := v_quantity;
end if;
insert into "better_supabase"."stock_levels" ("tenant_id", "variant_id", "location_id")
values (v_tenant, v_variant, v_location)
on conflict ("variant_id", "location_id") do nothing;
if import_stock_allocation.subject_id is not null then
select x."id" as id, x."variant_id" as variant, x."location_id" as location, x."allocated" as allocated,
x."status" as status, x."updated_at" as updated_at
into v_row from "better_supabase"."stock_allocations" x
where x."id" = import_stock_allocation.subject_id::uuid and x."tenant_id" = v_tenant for update;
if v_row.id is null then
raise exception 'the stock allocation no longer exists' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_row.status <> 'open' then
return jsonb_build_object('subjectId', v_row.id::text, 'updatedAt', v_row.updated_at, 'warnings', jsonb_build_array(jsonb_build_object(
'code', 'IMPORT_DOCUMENT_CHANGED', 'message', 'a fulfilled or released stock allocation is kept as imported')));
end if;
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" - v_row.allocated, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
update "better_supabase"."stock_allocations" x set "variant_id" = v_variant, "location_id" = v_location, "document_type" = v_data ->> 'documentType',
"document_id" = v_data ->> 'documentId', "line_id" = nullif(v_data ->> 'lineId', ''), "quantity" = v_quantity,
"allocated" = v_allocated, "fulfilled" = v_fulfilled, "status" = v_status, "updated_at" = now()
where x."id" = v_row.id returning x."id", x."updated_at" into v_id, v_updated;
else
insert into "better_supabase"."stock_allocations" as x ("tenant_id", "variant_id", "location_id", "document_type", "document_id", "line_id",
"quantity", "allocated", "fulfilled", "status")
values (v_tenant, v_variant, v_location, v_data ->> 'documentType', v_data ->> 'documentId', nullif(v_data ->> 'lineId', ''),
v_quantity, v_allocated, v_fulfilled, v_status)
returning x."id", x."updated_at" into v_id, v_updated;
end if;
update "better_supabase"."stock_levels" x set "reserved" = x."reserved" + v_allocated, "updated_at" = now()
where x."variant_id" = v_variant and x."location_id" = v_location;
return jsonb_build_object('subjectId', v_id::text, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_stock_allocation"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_stock_allocation"(uuid, jsonb, text) to service_role;
-- The batch form of import_stock_allocation (ADR 1217): new allocations that
-- name their variant and location by id are written in one statement, and the
-- location's reserved stock grows once per variant and location. Every other
-- item goes through import_stock_allocation.
create or replace function "better_supabase"."import_stock_allocation_batch"(run uuid, items jsonb)
returns jsonb
language plpgsql
security invoker
set search_path = ''
-- CTE row counts are guesses; a nested loop over 2,000 items costs seconds.
set enable_nestloop = off
as $$
declare
v_done jsonb[] := array_fill(null::jsonb, array[jsonb_array_length(items)]);
v_row record;
v_call jsonb;
v_message text;
v_hint text;
begin
for v_row in
with i as (
select o::int as n, gen_random_uuid() as id, (e ->> 'tenant')::uuid as tenant, e -> 'data' as d,
case when pg_input_is_valid(coalesce(e -> 'data' ->> 'variantId', ''), 'uuid') then (e -> 'data' ->> 'variantId')::uuid end as variant,
case when pg_input_is_valid(coalesce(e -> 'data' ->> 'locationId', ''), 'uuid') then (e -> 'data' ->> 'locationId')::uuid end as location,
case when pg_input_is_valid(coalesce(e -> 'data' ->> 'quantity', ''), 'numeric') then (e -> 'data' ->> 'quantity')::numeric end as quantity,
case when pg_input_is_valid(coalesce(coalesce(e -> 'data' ->> 'allocated', '0'), ''), 'numeric') then (coalesce(e -> 'data' ->> 'allocated', '0'))::numeric end as allocated,
case when pg_input_is_valid(coalesce(coalesce(e -> 'data' ->> 'fulfilled', '0'), ''), 'numeric') then (coalesce(e -> 'data' ->> 'fulfilled', '0'))::numeric end as fulfilled,
coalesce(nullif(e -> 'data' ->> 'status', ''), 'open') as status
from jsonb_array_elements(items) with ordinality t(e, o)
where nullif(e ->> 'subjectId', '') is null
), f as (
select i.n, i.id, i.tenant, i.variant, i.location, i.quantity, i.status,
i.d ->> 'documentType' as document_type, i.d ->> 'documentId' as document_id, nullif(i.d ->> 'lineId', '') as line,
case when i.status <> 'open' then 0 else i.allocated end as allocated,
case when i.status = 'fulfilled' then i.quantity else i.fulfilled end as fulfilled
from i
where (select y."id" from "better_supabase"."product_variants" y where y."id" = i.variant and y."tenant_id" = i.tenant) is not null
and (select x."id" from "better_supabase"."inventory_locations" x where x."id" = i.location and x."tenant_id" = i.tenant) is not null
and i.status in ('open', 'fulfilled', 'released')
and i.quantity > 0 and i.allocated >= 0 and i.fulfilled >= 0 and i.allocated + i.fulfilled <= i.quantity
and coalesce(i.d ->> 'documentType', '') ~ '^[a-z][a-z0-9_]{0,62}$'
and length(coalesce(i.d ->> 'documentId', '')) between 1 and 200
), levels as (
insert into "better_supabase"."stock_levels" as x ("tenant_id", "variant_id", "location_id", "reserved")
select f.tenant, f.variant, f.location, sum(f.allocated) from f group by 1, 2, 3
on conflict ("variant_id", "location_id") do update
set "reserved" = x."reserved" + excluded."reserved", "updated_at" = now()
), written as (
insert into "better_supabase"."stock_allocations" as x ("id", "tenant_id", "variant_id", "location_id", "document_type", "document_id", "line_id",
"quantity", "allocated", "fulfilled", "status")
select f.id, f.tenant, f.variant, f.location, f.document_type, f.document_id, f.line, f.quantity, f.allocated, f.fulfilled, f.status from f
returning x."id" as id, x."updated_at" as updated_at
)
select f.n, jsonb_build_object('subjectId', f.id::text, 'updatedAt', w.updated_at) as answer
from f join written w on w.id = f.id
loop
v_done[v_row.n] := v_row.answer;
end loop;
for v_i in 1 .. jsonb_array_length(items) loop
if v_done[v_i] is null then
v_call := items -> (v_i - 1);
begin
v_done[v_i] := "better_supabase"."import_stock_allocation"(run, v_call, nullif(v_call ->> 'subjectId', ''));
exception when others then
get stacked diagnostics v_message = message_text, v_hint = pg_exception_hint;
v_done[v_i] := jsonb_build_object('error', jsonb_build_object('code', coalesce(nullif(v_hint, ''), 'IMPORT_ITEM_INVALID'), 'message', v_message));
end;
end if;
end loop;
return to_jsonb(v_done);
end;
$$;
revoke execute on function "better_supabase"."import_stock_allocation_batch"(uuid, jsonb) from public, anon, authenticated;
grant execute on function "better_supabase"."import_stock_allocation_batch"(uuid, jsonb) to service_role;
create or replace function "better_supabase"."stock_allocation_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."stock_allocations" x where x."id" = $1::uuid
$$;
revoke execute on function "better_supabase"."stock_allocation_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."stock_allocation_updated_at"(text) to service_role;
-- Where the location is: line1, line2, postalCode, city, region and country
-- (a two-letter ISO 3166 code).
alter table "better_supabase"."inventory_locations" add column "address" jsonb;
alter table "better_supabase"."inventory_locations" add constraint bsb_inventory_locations_address_check check ("address" is null or jsonb_typeof("address") = 'object');
-- Creates a location (location null) or updates one, with the extra columns
-- in fields by name. Returns its id, code and active flag.
create or replace function "better_supabase"."upsert_location"(tenant uuid, location uuid, code text, name text, kind text, fields jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_location.location;
v_active boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', upsert_location.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if upsert_location.code is null or upsert_location.code !~ '^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$' then
raise exception 'the code must be 1 to 40 letters, digits, dots, dashes or underscores' using errcode = '22023', hint = 'INVENTORY_LOCATION_CODE_INVALID';
end if;
if coalesce(upsert_location.kind, 'warehouse') not in ('warehouse', 'store', 'virtual') then
raise exception 'the kind must be warehouse, store or virtual' using errcode = '22023', hint = 'INVENTORY_LOCATION_KIND_INVALID';
end if;
begin
if v_id is null then
insert into "better_supabase"."inventory_locations" ("tenant_id", "code", "name", "kind")
values (upsert_location.tenant, upsert_location.code, upsert_location.name, coalesce(upsert_location.kind, 'warehouse'))
returning "id", "active" into v_id, v_active;
else
update "better_supabase"."inventory_locations" x set "code" = upsert_location.code, "name" = upsert_location.name,
"kind" = coalesce(upsert_location.kind, x."kind"), "updated_at" = now()
where x."id" = upsert_location.location and x."tenant_id" = upsert_location.tenant
returning x."active" into v_active;
if not found then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'another location has this code' using errcode = '23505', hint = 'INVENTORY_LOCATION_CODE_TAKEN';
end;
return jsonb_build_object('id', v_id, 'code', upsert_location.code, 'active', v_active);
end;
$$;
revoke execute on function "better_supabase"."upsert_location"(uuid, uuid, text, text, text, jsonb) from public, anon;
grant execute on function "better_supabase"."upsert_location"(uuid, uuid, text, text, text, jsonb) to authenticated, service_role;
-- Turns a location on or off. Reservations need an active location.
create or replace function "better_supabase"."set_location_active"(location uuid, active boolean)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id", x."active" into v_tenant, v_active from "better_supabase"."inventory_locations" x where x."id" = set_location_active.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
update "better_supabase"."inventory_locations" x set "active" = coalesce(set_location_active.active, true), "updated_at" = now()
where x."id" = set_location_active.location;
return true;
end;
$$;
revoke execute on function "better_supabase"."set_location_active"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."set_location_active"(uuid, boolean) to authenticated, service_role;
-- Deletes a location without stock history. Deactivate one that has some.
create or replace function "better_supabase"."delete_location"(location uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" into v_tenant from "better_supabase"."inventory_locations" x where x."id" = delete_location.location;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if exists (select 1 from "better_supabase"."ledger_accounts" x join "better_supabase"."ledger_entries" y on y."account_id" = x."id"
where x."tenant_id" = v_tenant and x."managed_by" = 'inventory' and x."kind" = 'stock'
and x."metadata" ->> 'locationId' = delete_location.location::text)
or exists (select 1 from "better_supabase"."stock_reservations" x where x."location_id" = delete_location.location and x."status" = 'active') then
raise exception 'the location has stock history; deactivate it instead' using errcode = '23503', hint = 'INVENTORY_LOCATION_IN_USE';
end if;
delete from "better_supabase"."inventory_locations" x where x."id" = delete_location.location;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_location"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_location"(uuid) to authenticated, service_role;
-- Sets a location's address, or clears it with null. The keys are
-- line1, line2, postalCode, city, region, country; each value is text, and country is a
-- two-letter code.
create or replace function "better_supabase"."set_location_address"(location uuid, address jsonb)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_address jsonb := set_location_address.address;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" into v_tenant from "better_supabase"."inventory_locations" x where x."id" = set_location_address.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_address is not null and jsonb_typeof(v_address) = 'null' then
v_address := null;
end if;
if v_address is not null then
if jsonb_typeof(v_address) <> 'object'
or exists (select 1 from jsonb_each(v_address) e where e.key <> all (array['line1', 'line2', 'postalCode', 'city', 'region', 'country']) or jsonb_typeof(e.value) <> 'string') then
raise exception 'an address is an object of text values with the keys line1, line2, postalCode, city, region, country' using errcode = '22023', hint = 'INVENTORY_ADDRESS_INVALID';
end if;
if v_address ? 'country' and (v_address ->> 'country') !~ '^[A-Z]{2}$' then
raise exception 'country is a two-letter ISO 3166 code in capitals' using errcode = '22023', hint = 'INVENTORY_ADDRESS_INVALID';
end if;
end if;
update "better_supabase"."inventory_locations" x set "address" = v_address, "updated_at" = now() where x."id" = set_location_address.location;
return true;
end;
$$;
revoke execute on function "better_supabase"."set_location_address"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."set_location_address"(uuid, jsonb) to authenticated, service_role;
-- Adds or removes stock at a location through the ledger. detail names the
-- bin, lot, serial numbers or unit cost, as for move_stock. Returns the
-- movement id and the level's on-hand and available quantities.
create or replace function "better_supabase"."adjust_stock"(variant uuid, location uuid, quantity numeric, reason text, note text, detail jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
v_movement uuid;
v_on_hand numeric;
v_available numeric;
begin
select x."tenant_id", x."active" into v_tenant, v_active from "better_supabase"."inventory_locations" x where x."id" = adjust_stock.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = adjust_stock.variant and cv."tenant_id" = v_tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if adjust_stock.quantity is null or adjust_stock.quantity = 0 then
raise exception 'the quantity must not be zero' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
if adjust_stock.reason is null or adjust_stock.reason not in ('adjustment', 'damage', 'loss', 'return', 'receipt', 'scrap') then
raise exception 'the reason must be one of adjustment, damage, loss, return, receipt, scrap' using errcode = '22023', hint = 'INVENTORY_REASON_INVALID';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_stock_adjust"(uuid, uuid, numeric, text)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid, $3::numeric, $4::text)', v_hook::oid::regproc)
using adjust_stock.variant, adjust_stock.location, adjust_stock.quantity, adjust_stock.reason;
end if;
end;
v_movement := "better_supabase"."move_stock"(v_tenant, adjust_stock.variant, adjust_stock.location, adjust_stock.quantity, adjust_stock.reason, null, null, adjust_stock.note, adjust_stock.detail);
select x."on_hand", x."available" into v_on_hand, v_available from "better_supabase"."stock_levels" x
where x."variant_id" = adjust_stock.variant and x."location_id" = adjust_stock.location;
null;
declare
v_hook regprocedure := to_regprocedure('"public"."after_stock_adjust"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_movement;
end if;
end;
return jsonb_build_object('movementId', v_movement, 'onHand', v_on_hand, 'available', v_available);
end;
$$;
revoke execute on function "better_supabase"."adjust_stock"(uuid, uuid, numeric, text, text, jsonb) from public, anon;
grant execute on function "better_supabase"."adjust_stock"(uuid, uuid, numeric, text, text, jsonb) to authenticated, service_role;
-- Sets on-hand to a counted quantity, writing the difference to the ledger.
-- With a binId or lotId in detail it counts that bin or lot only; without,
-- the stock outside any bin or lot.
create or replace function "better_supabase"."count_stock"(variant uuid, location uuid, counted numeric, note text, detail jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
v_movement uuid;
v_delta numeric;
v_available numeric;
v_bin uuid := nullif(count_stock.detail ->> 'binId', '')::uuid;
v_lot uuid := nullif(count_stock.detail ->> 'lotId', '')::uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id", x."active" into v_tenant, v_active from "better_supabase"."inventory_locations" x where x."id" = count_stock.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = count_stock.variant and cv."tenant_id" = v_tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if count_stock.counted is null or count_stock.counted < 0 then
raise exception 'the counted quantity must be zero or more' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
insert into "better_supabase"."stock_levels" ("tenant_id", "variant_id", "location_id")
values (v_tenant, count_stock.variant, count_stock.location)
on conflict ("variant_id", "location_id") do nothing;
perform 1 from "better_supabase"."stock_levels" x where x."variant_id" = count_stock.variant and x."location_id" = count_stock.location for update;
if v_bin is null and v_lot is null then
select count_stock.counted - x."on_hand" + coalesce((select sum(y."on_hand") from "better_supabase"."stock_buckets" y
where y."variant_id" = count_stock.variant and y."location_id" = count_stock.location), 0)
into v_delta from "better_supabase"."stock_levels" x
where x."variant_id" = count_stock.variant and x."location_id" = count_stock.location;
else
v_delta := count_stock.counted - coalesce((select y."on_hand" from "better_supabase"."stock_buckets" y
where y."variant_id" = count_stock.variant and y."location_id" = count_stock.location
and y."bin_id" is not distinct from v_bin and y."lot_id" is not distinct from v_lot), 0);
end if;
if v_delta <> 0 then
v_movement := "better_supabase"."move_stock"(v_tenant, count_stock.variant, count_stock.location, v_delta, 'count', null, null, count_stock.note, jsonb_strip_nulls(jsonb_build_object('binId', v_bin, 'lotId', v_lot, 'serials', count_stock.detail -> 'serials')));
select x."available" into v_available from "better_supabase"."stock_levels" x
where x."variant_id" = count_stock.variant and x."location_id" = count_stock.location;
null;
end if;
return jsonb_build_object('movementId', v_movement, 'delta', v_delta, 'onHand', count_stock.counted);
end;
$$;
revoke execute on function "better_supabase"."count_stock"(uuid, uuid, numeric, text, jsonb) from public, anon;
grant execute on function "better_supabase"."count_stock"(uuid, uuid, numeric, text, jsonb) to authenticated, service_role;
-- Sets the available quantity at or below which stock.reorder_point_reached fires.
create or replace function "better_supabase"."set_reorder_point"(variant uuid, location uuid, reorder_point numeric)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id", x."active" into v_tenant, v_active from "better_supabase"."inventory_locations" x where x."id" = set_reorder_point.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = set_reorder_point.variant and cv."tenant_id" = v_tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if set_reorder_point.reorder_point < 0 then
raise exception 'the reorder point must be zero or more' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
insert into "better_supabase"."stock_levels" as x ("tenant_id", "variant_id", "location_id", "reorder_point")
values (v_tenant, set_reorder_point.variant, set_reorder_point.location, set_reorder_point.reorder_point)
on conflict ("variant_id", "location_id") do update
set "reorder_point" = excluded."reorder_point", "updated_at" = now();
return true;
end;
$$;
revoke execute on function "better_supabase"."set_reorder_point"(uuid, uuid, numeric) from public, anon;
grant execute on function "better_supabase"."set_reorder_point"(uuid, uuid, numeric) to authenticated, service_role;
create or replace function "better_supabase"."set_reorder_quantity"(variant uuid, location uuid, reorder_quantity numeric)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id", x."active" into v_tenant, v_active from "better_supabase"."inventory_locations" x where x."id" = set_reorder_quantity.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = set_reorder_quantity.variant and cv."tenant_id" = v_tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if set_reorder_quantity.reorder_quantity is not null and set_reorder_quantity.reorder_quantity <= 0 then
raise exception 'the quantity must be greater than zero' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
insert into "better_supabase"."stock_levels" as x ("tenant_id", "variant_id", "location_id", "reorder_quantity")
values (v_tenant, set_reorder_quantity.variant, set_reorder_quantity.location, set_reorder_quantity.reorder_quantity)
on conflict ("variant_id", "location_id") do update
set "reorder_quantity" = excluded."reorder_quantity", "updated_at" = now();
return true;
end;
$$;
revoke execute on function "better_supabase"."set_reorder_quantity"(uuid, uuid, numeric) from public, anon;
grant execute on function "better_supabase"."set_reorder_quantity"(uuid, uuid, numeric) to authenticated, service_role;
-- What the books say is at a position now: a serial number counts 1 when it is
-- in stock at the location; a bin or lot is that bucket; neither is the level's
-- stock outside any bin or lot.
create or replace function "better_supabase"."count_expected"(variant uuid, location uuid, bin uuid, lot uuid, serial text)
returns numeric
language sql
stable
security definer
set search_path = ''
as $$
select case
when $5 is not null then
(select count(*) from "better_supabase"."stock_serials" y where y."variant_id" = $1 and y."serial" = $5 and y."location_id" = $2 and y."status" = 'in_stock')::numeric
when $3 is null and $4 is null then
coalesce((select x."on_hand" from "better_supabase"."stock_levels" x where x."variant_id" = $1 and x."location_id" = $2), 0)
- coalesce((select sum(y."on_hand") from "better_supabase"."stock_buckets" y where y."variant_id" = $1 and y."location_id" = $2), 0)
else
coalesce((select y."on_hand" from "better_supabase"."stock_buckets" y where y."variant_id" = $1 and y."location_id" = $2
and y."bin_id" is not distinct from $3 and y."lot_id" is not distinct from $4), 0)
end
$$;
revoke execute on function "better_supabase"."count_expected"(uuid, uuid, uuid, uuid, text) from public, anon, authenticated;
-- Opens a count of a location and snapshots its stock into lines: each bin and
-- lot bucket, the stock outside any bin or lot, and each serial number in stock.
-- attrs: { note?, variantIds? } counts only those variants. A line starts with
-- no counted quantity. Returns the count's id and its number of lines.
create or replace function "better_supabase"."open_stock_count"(tenant uuid, location uuid, attrs jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_attrs jsonb := coalesce(open_stock_count.attrs, '{}'::jsonb);
v_variants uuid[];
v_id uuid;
v_lines integer;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', open_stock_count.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."inventory_locations" x where x."id" = open_stock_count.location and x."tenant_id" = open_stock_count.tenant) then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
begin
if jsonb_typeof(v_attrs -> 'variantIds') = 'array' then
v_variants := array(select jsonb_array_elements_text(v_attrs -> 'variantIds'))::uuid[];
end if;
exception when invalid_text_representation then
raise exception 'variantIds is a list of uuids' using errcode = '22023', hint = 'INVENTORY_COUNT_INVALID';
end;
insert into "better_supabase"."stock_counts" as x ("tenant_id", "location_id", "note")
values (open_stock_count.tenant, open_stock_count.location, nullif(btrim(v_attrs ->> 'note'), ''))
returning x."id" into v_id;
insert into "better_supabase"."stock_count_lines" ("tenant_id", "count_id", "variant_id", "bin_id", "lot_id", "serial", "expected")
select open_stock_count.tenant, v_id, p.variant, p.bin, p.lot, p.serial, p.expected
from (
select y."variant_id" as variant, y."bin_id" as bin, y."lot_id" as lot, null::text as serial, y."on_hand" as expected
from "better_supabase"."stock_buckets" y
where y."location_id" = open_stock_count.location and y."tenant_id" = open_stock_count.tenant and y."on_hand" > 0
and not exists (select 1 from "better_supabase"."stock_items" q where q."variant_id" = y."variant_id" and q."tracking" = 'serial')
union all
select x."variant_id", null, null, null,
x."on_hand" - coalesce((select sum(y."on_hand") from "better_supabase"."stock_buckets" y where y."variant_id" = x."variant_id" and y."location_id" = x."location_id"), 0)
from "better_supabase"."stock_levels" x
where x."location_id" = open_stock_count.location and x."tenant_id" = open_stock_count.tenant
and not exists (select 1 from "better_supabase"."stock_items" q where q."variant_id" = x."variant_id" and q."tracking" = 'serial')
union all
select z."variant_id", z."bin_id", z."lot_id", z."serial", 1
from "better_supabase"."stock_serials" z
where z."location_id" = open_stock_count.location and z."tenant_id" = open_stock_count.tenant and z."status" = 'in_stock'
) p
where (v_variants is null or p.variant = any (v_variants)) and p.expected > 0
on conflict do nothing;
get diagnostics v_lines = row_count;
return jsonb_build_object('id', v_id, 'lines', v_lines);
end;
$$;
revoke execute on function "better_supabase"."open_stock_count"(uuid, uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."open_stock_count"(uuid, uuid, jsonb) to authenticated, service_role;
-- Records what was counted at a position of an open count. attrs: { variantId,
-- binId?, lotId?, serial?, counted }. A position that isn't a line yet (stock
-- the books don't know of) becomes one, with expected taken from the stock now.
-- A serial number is counted 0 or 1. Returns the line's id, expected, counted
-- and variance.
create or replace function "better_supabase"."record_count_line"(count uuid, attrs jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_attrs jsonb := coalesce(record_count_line.attrs, '{}'::jsonb);
v_count record;
v_variant uuid;
v_bin uuid;
v_lot uuid;
v_serial text := nullif(btrim(v_attrs ->> 'serial'), '');
v_counted numeric;
v_row record;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."location_id" as location, x."status" as status into v_count
from "better_supabase"."stock_counts" x where x."id" = record_count_line.count for update;
if not found then
raise exception 'stock count not found' using errcode = 'P0002', hint = 'INVENTORY_COUNT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_count.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_count.status <> 'open' then
raise exception 'a posted or cancelled count takes no more lines' using errcode = '22023', hint = 'INVENTORY_COUNT_CLOSED';
end if;
begin
v_variant := (v_attrs ->> 'variantId')::uuid;
v_bin := nullif(v_attrs ->> 'binId', '')::uuid;
v_lot := nullif(v_attrs ->> 'lotId', '')::uuid;
v_counted := (v_attrs ->> 'counted')::numeric;
exception when invalid_text_representation or numeric_value_out_of_range then
raise exception 'variantId, binId and lotId are uuids and counted is a number' using errcode = '22023', hint = 'INVENTORY_COUNT_INVALID';
end;
if v_variant is null or v_counted is null or v_counted < 0 then
raise exception 'a line needs a variantId and a counted quantity of zero or more' using errcode = '22023', hint = 'INVENTORY_COUNT_INVALID';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = v_variant and cv."tenant_id" = v_count.tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if exists (select 1 from "better_supabase"."stock_items" q where q."variant_id" = v_variant and q."tracking" = 'serial') and (v_serial is null or v_counted not in (0, 1)) then
raise exception 'a serial-tracked variant is counted per serial number, 0 or 1' using errcode = '22023', hint = 'INVENTORY_COUNT_INVALID';
end if;
if v_serial is not null and (v_counted not in (0, 1) or v_bin is not null or v_lot is not null) then
raise exception 'a serial number is counted 0 or 1, without a bin or lot' using errcode = '22023', hint = 'INVENTORY_COUNT_INVALID';
end if;
if v_bin is not null and not exists (select 1 from "better_supabase"."stock_bins" b where b."id" = v_bin and b."location_id" = v_count.location) then
raise exception 'the bin isn''t at this location' using errcode = 'P0002', hint = 'INVENTORY_BIN_NOT_FOUND';
end if;
if v_lot is not null and not exists (select 1 from "better_supabase"."stock_lots" b where b."id" = v_lot and b."variant_id" = v_variant) then
raise exception 'the lot isn''t a lot of this variant' using errcode = 'P0002', hint = 'INVENTORY_LOT_NOT_FOUND';
end if;
insert into "better_supabase"."stock_count_lines" as x ("tenant_id", "count_id", "variant_id", "bin_id", "lot_id", "serial", "expected", "counted")
values (v_count.tenant, record_count_line.count, v_variant, v_bin, v_lot, v_serial,
"better_supabase"."count_expected"(v_variant, v_count.location, v_bin, v_lot, v_serial), v_counted)
on conflict ("count_id", "variant_id", coalesce("bin_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("lot_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("serial", '')) do update
set "counted" = excluded."counted", "updated_at" = now()
returning x."id", x."expected", x."counted", x."variance" into v_row;
update "better_supabase"."stock_counts" x set "updated_at" = now() where x."id" = record_count_line.count;
return jsonb_build_object('id', v_row."id", 'expected', v_row."expected"::text, 'counted', v_row."counted"::text, 'variance', v_row."variance"::text);
end;
$$;
revoke execute on function "better_supabase"."record_count_line"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."record_count_line"(uuid, jsonb) to authenticated, service_role;
-- Posts an open count: each counted line with a variance becomes one 'count'
-- movement of that variance (counted minus the snapshot, so stock that moved
-- since the snapshot stays), referenced to the count. Lines not counted post
-- nothing. A second call changes nothing and returns posted: false. Returns the
-- number of movements and the sum of the absolute variances.
create or replace function "better_supabase"."post_stock_count"(count uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_count record;
v_line record;
v_movement uuid;
v_moves integer := 0;
v_total numeric := 0;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."location_id" as location, x."status" as status, x."note" as note into v_count
from "better_supabase"."stock_counts" x where x."id" = post_stock_count.count for update;
if not found then
raise exception 'stock count not found' using errcode = 'P0002', hint = 'INVENTORY_COUNT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_count.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_count.status = 'posted' then
return jsonb_build_object('posted', false, 'movements', (select count(*) from "better_supabase"."stock_count_lines" y where y."count_id" = post_stock_count.count and y."movement_id" is not null), 'variance', null);
end if;
if v_count.status <> 'open' then
raise exception 'a cancelled count can''t be posted' using errcode = '22023', hint = 'INVENTORY_COUNT_CLOSED';
end if;
for v_line in
select y."id" as id, y."variant_id" as variant, y."bin_id" as bin, y."lot_id" as lot, y."serial" as serial, y."variance" as variance
from "better_supabase"."stock_count_lines" y
where y."count_id" = post_stock_count.count and y."variance" is not null and y."variance" <> 0 and y."movement_id" is null
order by y."variant_id", y."id"
loop
insert into "better_supabase"."stock_levels" ("tenant_id", "variant_id", "location_id")
values (v_count.tenant, v_line.variant, v_count.location)
on conflict ("variant_id", "location_id") do nothing;
v_movement := "better_supabase"."move_stock"(v_count.tenant, v_line.variant, v_count.location, v_line.variance, 'count', 'stock_count', post_stock_count.count::text, coalesce(v_count.note, 'Stock count'), jsonb_strip_nulls(jsonb_build_object('binId', v_line.bin, 'lotId', v_line.lot, 'serials', case when v_line.serial is not null then jsonb_build_array(v_line.serial) end)));
update "better_supabase"."stock_count_lines" y set "movement_id" = v_movement, "updated_at" = now() where y."id" = v_line.id;
v_moves := v_moves + 1;
v_total := v_total + abs(v_line.variance);
end loop;
update "better_supabase"."stock_counts" x set "status" = 'posted', "posted_at" = now(), "posted_by" = auth.uid(), "updated_at" = now() where x."id" = post_stock_count.count;
return jsonb_build_object('posted', true, 'movements', v_moves, 'variance', v_total::text);
end;
$$;
revoke execute on function "better_supabase"."post_stock_count"(uuid) from public, anon;
grant execute on function "better_supabase"."post_stock_count"(uuid) to authenticated, service_role;
-- Cancels an open count; its lines stay for the record and nothing is posted.
create or replace function "better_supabase"."cancel_stock_count"(count uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_status text;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id", x."status" into v_tenant, v_status from "better_supabase"."stock_counts" x where x."id" = cancel_stock_count.count for update;
if v_tenant is null then
raise exception 'stock count not found' using errcode = 'P0002', hint = 'INVENTORY_COUNT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_status = 'cancelled' then
return false;
end if;
if v_status <> 'open' then
raise exception 'a posted count can''t be cancelled' using errcode = '22023', hint = 'INVENTORY_COUNT_CLOSED';
end if;
update "better_supabase"."stock_counts" x set "status" = 'cancelled', "updated_at" = now() where x."id" = cancel_stock_count.count;
return true;
end;
$$;
revoke execute on function "better_supabase"."cancel_stock_count"(uuid) from public, anon;
grant execute on function "better_supabase"."cancel_stock_count"(uuid) to authenticated, service_role;
-- The import target of the stock_count entity: item.data is { locationId or
-- location (a code), or neither when the organization has one active location, note?, lines: [{ variantId or sku, binId or bin (a code)?,
-- lotId or lot (a code)?, serial?, counted, expected? }] }. A line without
-- expected takes the stock now. An imported count stays open; post it with
-- post_stock_count, which posts once. Importing the same key again replaces the
-- lines of an open count and refuses a posted one.
create or replace function "better_supabase"."import_stock_count"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_stock_count.item ->> 'tenant')::uuid;
v_data jsonb := import_stock_count.item -> 'data';
v_location uuid;
v_id uuid;
v_status text;
v_updated timestamptz;
v_entry jsonb;
v_variant uuid;
v_bin uuid;
v_lot uuid;
v_serial text;
v_counted numeric;
v_expected numeric;
begin
if jsonb_typeof(v_data -> 'lines') is distinct from 'array' then
raise exception 'a stock count needs a list of lines' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
begin
v_location := nullif(v_data ->> 'locationId', '')::uuid;
exception when invalid_text_representation then
raise exception 'locationId is a uuid' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_location is null and nullif(v_data ->> 'location', '') is null then
-- Without a location the count goes to the organization's only active one.
select min(x."id"::text)::uuid into v_location from "better_supabase"."inventory_locations" x
where x."tenant_id" = v_tenant and x."active"
having count(*) = 1;
elsif v_location is null then
select x."id" into v_location from "better_supabase"."inventory_locations" x where x."tenant_id" = v_tenant and x."code" = v_data ->> 'location';
elsif not exists (select 1 from "better_supabase"."inventory_locations" x where x."id" = v_location and x."tenant_id" = v_tenant) then
v_location := null;
end if;
if v_location is null then
raise exception 'the count''s location isn''t in this organization, or the count names none and the organization has more than one active location' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if import_stock_count.subject_id is null then
insert into "better_supabase"."stock_counts" as x ("tenant_id", "location_id", "note")
values (v_tenant, v_location, nullif(btrim(v_data ->> 'note'), ''))
returning x."id", x."updated_at" into v_id, v_updated;
else
select x."id", x."status" into v_id, v_status from "better_supabase"."stock_counts" x
where x."id" = import_stock_count.subject_id::uuid and x."tenant_id" = v_tenant for update;
if v_id is null then
raise exception 'the stock count no longer exists' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_status <> 'open' then
raise exception 'a posted or cancelled count can''t be imported again' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
update "better_supabase"."stock_counts" x set "location_id" = v_location, "note" = nullif(btrim(v_data ->> 'note'), ''), "updated_at" = now()
where x."id" = v_id returning x."updated_at" into v_updated;
delete from "better_supabase"."stock_count_lines" y where y."count_id" = v_id and y."movement_id" is null;
end if;
for v_entry in select e from jsonb_array_elements(v_data -> 'lines') e loop
begin
v_variant := nullif(v_entry ->> 'variantId', '')::uuid;
v_bin := nullif(v_entry ->> 'binId', '')::uuid;
v_lot := nullif(v_entry ->> 'lotId', '')::uuid;
v_counted := (v_entry ->> 'counted')::numeric;
v_expected := (v_entry ->> 'expected')::numeric;
exception when invalid_text_representation or numeric_value_out_of_range then
raise exception 'ids are uuids and counted and expected are numbers' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_variant is null then
select y."id" into v_variant from "better_supabase"."product_variants" y where y."tenant_id" = v_tenant and y."sku" = v_entry ->> 'sku';
end if;
if v_variant is null or not exists (select 1 from "better_supabase"."product_variants" y where y."id" = v_variant and y."tenant_id" = v_tenant) then
raise exception 'a line''s variant isn''t in this organization' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_bin is null and nullif(v_entry ->> 'bin', '') is not null then
select y."id" into v_bin from "better_supabase"."stock_bins" y where y."tenant_id" = v_tenant and y."location_id" = v_location and y."code" = v_entry ->> 'bin';
if v_bin is null then
raise exception 'a line''s bin isn''t at the location' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
end if;
if v_lot is null and nullif(v_entry ->> 'lot', '') is not null then
select y."id" into v_lot from "better_supabase"."stock_lots" y where y."tenant_id" = v_tenant and y."variant_id" = v_variant and y."code" = v_entry ->> 'lot';
if v_lot is null then
raise exception 'a line''s lot isn''t a lot of its variant' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
end if;
v_serial := nullif(btrim(v_entry ->> 'serial'), '');
if v_counted is null or v_counted < 0 or (v_serial is not null and (v_counted not in (0, 1) or v_bin is not null or v_lot is not null)) then
raise exception 'a line needs a counted quantity of zero or more, and a serial is counted 0 or 1' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
insert into "better_supabase"."stock_count_lines" as x ("tenant_id", "count_id", "variant_id", "bin_id", "lot_id", "serial", "expected", "counted")
values (v_tenant, v_id, v_variant, v_bin, v_lot, v_serial,
coalesce(v_expected, "better_supabase"."count_expected"(v_variant, v_location, v_bin, v_lot, v_serial)), v_counted)
on conflict ("count_id", "variant_id", coalesce("bin_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("lot_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("serial", '')) do update
set "counted" = excluded."counted", "expected" = excluded."expected", "updated_at" = now();
end loop;
return jsonb_build_object('subjectId', v_id::text, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_stock_count"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_stock_count"(uuid, jsonb, text) to service_role;
-- The batch form of import_stock_count (ADR 1217): new counts that name their
-- location by id, whose lines name a variant by id at most once each and no
-- bin, lot or serial, are written in one statement, with the expected
-- quantity count_expected gives such a line. Every other item goes through
-- import_stock_count.
create or replace function "better_supabase"."import_stock_count_batch"(run uuid, items jsonb)
returns jsonb
language plpgsql
security invoker
set search_path = ''
-- CTE row counts are guesses; a nested loop over 2,000 items costs seconds.
set enable_nestloop = off
as $$
declare
v_done jsonb[] := array_fill(null::jsonb, array[jsonb_array_length(items)]);
v_row record;
v_call jsonb;
v_message text;
v_hint text;
begin
for v_row in
with i as (
select o::int as n, gen_random_uuid() as id, (e ->> 'tenant')::uuid as tenant, e -> 'data' as d,
case when pg_input_is_valid(coalesce(e -> 'data' ->> 'locationId', ''), 'uuid') then (e -> 'data' ->> 'locationId')::uuid end as location
from jsonb_array_elements(items) with ordinality t(e, o)
where nullif(e ->> 'subjectId', '') is null and jsonb_typeof(e -> 'data' -> 'lines') = 'array'
), f as (
select i.n, i.id, i.tenant, i.location, i.d, nullif(btrim(i.d ->> 'note'), '') as note
from i
where (select x."id" from "better_supabase"."inventory_locations" x where x."id" = i.location and x."tenant_id" = i.tenant) is not null
and (select count(*) = count(distinct case when pg_input_is_valid(coalesce(e.entry ->> 'variantId', ''), 'uuid') then (e.entry ->> 'variantId')::uuid end)
and bool_and(jsonb_typeof(e.entry) = 'object'
and not e.entry ?| array['binId', 'bin', 'lotId', 'lot', 'serial', 'sku']
and pg_input_is_valid(coalesce(e.entry ->> 'counted', ''), 'numeric')
and pg_input_is_valid(coalesce(e.entry ->> 'expected', '0'), 'numeric')
and coalesce(case when pg_input_is_valid(coalesce(e.entry ->> 'counted', ''), 'numeric') then (e.entry ->> 'counted')::numeric end >= 0, false)
and (select y."id" from "better_supabase"."product_variants" y
where y."id" = case when pg_input_is_valid(coalesce(e.entry ->> 'variantId', ''), 'uuid') then (e.entry ->> 'variantId')::uuid end and y."tenant_id" = i.tenant) is not null)
from jsonb_array_elements(i.d -> 'lines') e(entry))
), written as (
insert into "better_supabase"."stock_counts" as x ("id", "tenant_id", "location_id", "note")
select f.id, f.tenant, f.location, f.note from f
returning x."id" as id, x."updated_at" as updated_at
), counted as (
insert into "better_supabase"."stock_count_lines" ("tenant_id", "count_id", "variant_id", "expected", "counted")
select f.tenant, f.id, (e.entry ->> 'variantId')::uuid,
coalesce((e.entry ->> 'expected')::numeric,
coalesce((select lv."on_hand" from "better_supabase"."stock_levels" lv where lv."variant_id" = (e.entry ->> 'variantId')::uuid and lv."location_id" = f.location), 0)
- coalesce((select sum(y."on_hand") from "better_supabase"."stock_buckets" y where y."variant_id" = (e.entry ->> 'variantId')::uuid and y."location_id" = f.location), 0)),
(e.entry ->> 'counted')::numeric
from f cross join lateral jsonb_array_elements(f.d -> 'lines') e(entry)
)
select f.n, jsonb_build_object('subjectId', f.id::text, 'updatedAt', w.updated_at) as answer
from f join written w on w.id = f.id
loop
v_done[v_row.n] := v_row.answer;
end loop;
for v_i in 1 .. jsonb_array_length(items) loop
if v_done[v_i] is null then
v_call := items -> (v_i - 1);
begin
v_done[v_i] := "better_supabase"."import_stock_count"(run, v_call, nullif(v_call ->> 'subjectId', ''));
exception when others then
get stacked diagnostics v_message = message_text, v_hint = pg_exception_hint;
v_done[v_i] := jsonb_build_object('error', jsonb_build_object('code', coalesce(nullif(v_hint, ''), 'IMPORT_ITEM_INVALID'), 'message', v_message));
end;
end if;
end loop;
return to_jsonb(v_done);
end;
$$;
revoke execute on function "better_supabase"."import_stock_count_batch"(uuid, jsonb) from public, anon, authenticated;
grant execute on function "better_supabase"."import_stock_count_batch"(uuid, jsonb) to service_role;
create or replace function "better_supabase"."stock_count_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."stock_counts" x where x."id" = $1::uuid
$$;
revoke execute on function "better_supabase"."stock_count_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."stock_count_updated_at"(text) to service_role;
-- Holds stock for a cart or an order until expires_at (15 minutes by default).
-- Releases the level's expired reservations first. Returns the reservation id,
-- its expiry and the level's available quantity.
create or replace function "better_supabase"."reserve_stock"(variant uuid, location uuid, quantity numeric, reference_type text, reference_id text, expires_at timestamptz)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_active boolean;
v_id uuid;
v_before numeric;
v_after numeric;
v_point numeric;
v_expires timestamptz := coalesce(reserve_stock.expires_at, now() + interval '15 minutes');
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id", x."active" into v_tenant, v_active from "better_supabase"."inventory_locations" x where x."id" = reserve_stock.location;
if v_tenant is null then
raise exception 'location not found' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not v_active then
raise exception 'the location is inactive' using errcode = '55000', hint = 'INVENTORY_LOCATION_INACTIVE';
end if;
if not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = reserve_stock.variant and cv."tenant_id" = v_tenant) then
raise exception 'variant not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if reserve_stock.quantity is null or reserve_stock.quantity <= 0 then
raise exception 'the quantity must be greater than zero' using errcode = '22023', hint = 'INVENTORY_QUANTITY_INVALID';
end if;
if v_expires <= now() then
raise exception 'the reservation must expire in the future' using errcode = '22023', hint = 'INVENTORY_EXPIRY_INVALID';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_stock_reserve"(uuid, uuid, numeric, text, text)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid, $3::numeric, $4::text, $5::text)', v_hook::oid::regproc)
using reserve_stock.variant, reserve_stock.location, reserve_stock.quantity, reserve_stock.reference_type, reserve_stock.reference_id;
end if;
end;
insert into "better_supabase"."stock_levels" ("tenant_id", "variant_id", "location_id")
values (v_tenant, reserve_stock.variant, reserve_stock.location)
on conflict ("variant_id", "location_id") do nothing;
perform 1 from "better_supabase"."stock_levels" x where x."variant_id" = reserve_stock.variant and x."location_id" = reserve_stock.location for update;
with expired as (
update "better_supabase"."stock_reservations" x set "status" = 'expired', "updated_at" = now()
where x."variant_id" = reserve_stock.variant and x."location_id" = reserve_stock.location
and x."status" = 'active' and x."expires_at" <= now()
returning x."quantity" as quantity
)
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" - (select coalesce(sum(e.quantity), 0) from expired e), 0)
where x."variant_id" = reserve_stock.variant and x."location_id" = reserve_stock.location;
select x."available", x."reorder_point" into v_before, v_point from "better_supabase"."stock_levels" x
where x."variant_id" = reserve_stock.variant and x."location_id" = reserve_stock.location;
if v_before < reserve_stock.quantity and exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = reserve_stock.variant and cv."track_inventory" and not cv."allow_backorder") then
raise exception 'not enough stock available' using errcode = '23514', hint = 'INVENTORY_INSUFFICIENT';
end if;
insert into "better_supabase"."stock_reservations" ("tenant_id", "variant_id", "location_id", "quantity", "reference_type", "reference_id", "expires_at")
values (v_tenant, reserve_stock.variant, reserve_stock.location, reserve_stock.quantity, reserve_stock.reference_type, reserve_stock.reference_id, v_expires)
returning "id" into v_id;
update "better_supabase"."stock_levels" x set "reserved" = x."reserved" + reserve_stock.quantity, "updated_at" = now()
where x."variant_id" = reserve_stock.variant and x."location_id" = reserve_stock.location
returning x."available" into v_after;
if v_point is not null and v_before > v_point and v_after <= v_point then
null;
end if;
null;
declare
v_hook regprocedure := to_regprocedure('"public"."after_stock_reserve"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_id;
end if;
end;
return jsonb_build_object('id', v_id, 'expiresAt', v_expires, 'available', v_after);
end;
$$;
revoke execute on function "better_supabase"."reserve_stock"(uuid, uuid, numeric, text, text, timestamptz) from public, anon;
grant execute on function "better_supabase"."reserve_stock"(uuid, uuid, numeric, text, text, timestamptz) to authenticated, service_role;
-- Turns an active reservation into a sale: the ledger takes the stock out.
create or replace function "better_supabase"."commit_reservation"(reservation uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_movement uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."quantity" as quantity, x."status" as status, x."expires_at" as expires_at,
x."reference_type" as reference_type, x."reference_id" as reference_id
into v_row from "better_supabase"."stock_reservations" x where x."id" = commit_reservation.reservation for update;
if not found then
raise exception 'reservation not found' using errcode = 'P0002', hint = 'INVENTORY_RESERVATION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'active' then
raise exception 'the reservation is no longer active' using errcode = '55000', hint = 'INVENTORY_RESERVATION_CLOSED';
end if;
if v_row.expires_at <= now() then
raise exception 'the reservation has expired' using errcode = '55000', hint = 'INVENTORY_RESERVATION_EXPIRED';
end if;
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" - v_row.quantity, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
update "better_supabase"."stock_reservations" x set "status" = 'committed', "updated_at" = now()
where x."id" = commit_reservation.reservation;
v_movement := "better_supabase"."move_stock"(v_row.tenant, v_row.variant, v_row.location, -v_row.quantity, 'sale', v_row.reference_type, v_row.reference_id, null, null);
null;
return jsonb_build_object('id', commit_reservation.reservation, 'movementId', v_movement);
end;
$$;
revoke execute on function "better_supabase"."commit_reservation"(uuid) from public, anon;
grant execute on function "better_supabase"."commit_reservation"(uuid) to authenticated, service_role;
-- Gives an active reservation's stock back. False when it isn't active.
create or replace function "better_supabase"."release_reservation"(reservation uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant, x."location_id" as location,
x."quantity" as quantity, x."status" as status
into v_row from "better_supabase"."stock_reservations" x where x."id" = release_reservation.reservation for update;
if not found then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.reserve'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'active' then
return false;
end if;
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" - v_row.quantity, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
update "better_supabase"."stock_reservations" x set "status" = 'released', "updated_at" = now()
where x."id" = release_reservation.reservation;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."release_reservation"(uuid) from public, anon;
grant execute on function "better_supabase"."release_reservation"(uuid) to authenticated, service_role;
-- Releases active reservations past their expiry, oldest first, up to
-- max_rows. Service only; run it on a schedule. Returns how many it released.
create or replace function "better_supabase"."expire_reservations"(max_rows integer)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_count integer := 0;
begin
for v_row in
select x."id" as id, x."tenant_id" as tenant, x."variant_id" as variant,
x."location_id" as location, x."quantity" as quantity
from "better_supabase"."stock_reservations" x
where x."status" = 'active' and x."expires_at" <= now()
order by x."expires_at"
limit greatest(coalesce(expire_reservations.max_rows, 500), 1)
for update skip locked
loop
update "better_supabase"."stock_reservations" x set "status" = 'expired', "updated_at" = now() where x."id" = v_row.id;
update "better_supabase"."stock_levels" x set "reserved" = greatest(x."reserved" - v_row.quantity, 0), "updated_at" = now()
where x."variant_id" = v_row.variant and x."location_id" = v_row.location;
null;
v_count := v_count + 1;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."expire_reservations"(integer) from public, anon, authenticated;
grant execute on function "better_supabase"."expire_reservations"(integer) to service_role;
-- Drafts a transfer of stock between two locations of one organization.
-- lines: [{ "variantId": uuid, "quantity": n, "detail"?: { binId, lotId,
-- serials } }]; detail picks the stock to take, as for move_stock.
create or replace function "better_supabase"."create_transfer"(tenant uuid, from_location uuid, to_location uuid, lines jsonb, note text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', create_transfer.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if create_transfer.from_location is not distinct from create_transfer.to_location then
raise exception 'a transfer needs two different locations' using errcode = '22023', hint = 'INVENTORY_TRANSFER_SAME_LOCATION';
end if;
if (select count(*) from "better_supabase"."inventory_locations" x where x."id" in (create_transfer.from_location, create_transfer.to_location) and x."tenant_id" = create_transfer.tenant) <> 2 then
raise exception 'location not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if jsonb_typeof(create_transfer.lines) is distinct from 'array' or jsonb_array_length(create_transfer.lines) = 0
or exists (
select 1 from jsonb_array_elements(create_transfer.lines) e
where jsonb_typeof(e) <> 'object'
or coalesce(e ->> 'variantId', '') !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
or case when coalesce(e ->> 'quantity', '') ~ '^[0-9]{1,14}([.][0-9]{1,6})?$' then (e ->> 'quantity')::numeric <= 0 else true end
)
or (select count(distinct e ->> 'variantId') from jsonb_array_elements(create_transfer.lines) e) <> jsonb_array_length(create_transfer.lines) then
raise exception 'lines must be a non-empty list with a unique variantId and a positive quantity each' using errcode = '22023', hint = 'INVENTORY_LINES_INVALID';
end if;
if exists (
select 1 from jsonb_array_elements(create_transfer.lines) e
where not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = (e ->> 'variantId')::uuid and cv."tenant_id" = create_transfer.tenant)
) then
raise exception 'a line names a variant outside this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
insert into "better_supabase"."stock_transfers" ("tenant_id", "from_location_id", "to_location_id", "note")
values (create_transfer.tenant, create_transfer.from_location, create_transfer.to_location, create_transfer.note)
returning "id" into v_id;
insert into "better_supabase"."stock_transfer_lines" ("tenant_id", "transfer_id", "variant_id", "quantity", "detail")
select create_transfer.tenant, v_id, (e ->> 'variantId')::uuid, (e ->> 'quantity')::numeric,
case when jsonb_typeof(e -> 'detail') = 'object' then e -> 'detail' end
from jsonb_array_elements(create_transfer.lines) e;
return jsonb_build_object('id', v_id, 'status', 'draft');
end;
$$;
revoke execute on function "better_supabase"."create_transfer"(uuid, uuid, uuid, jsonb, text) from public, anon;
grant execute on function "better_supabase"."create_transfer"(uuid, uuid, uuid, jsonb, text) to authenticated, service_role;
-- Takes a draft transfer's stock out of its source location.
create or replace function "better_supabase"."ship_transfer"(transfer uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_line record;
v_movement uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."from_location_id" as from_location, x."to_location_id" as to_location, x."status" as status
into v_row from "better_supabase"."stock_transfers" x where x."id" = ship_transfer.transfer for update;
if not found then
raise exception 'transfer not found' using errcode = 'P0002', hint = 'INVENTORY_TRANSFER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'draft' then
raise exception 'the transfer can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_TRANSFER_STATUS';
end if;
for v_line in
select x."variant_id" as variant, x."quantity" as quantity, x."detail" as detail
from "better_supabase"."stock_transfer_lines" x where x."transfer_id" = ship_transfer.transfer
loop
v_movement := "better_supabase"."move_stock"(v_row.tenant, v_line.variant, v_row.from_location, -v_line.quantity, 'transfer_out', 'transfer', ship_transfer.transfer::text, null, v_line.detail);
update "better_supabase"."stock_transfer_lines" x set "detail" = jsonb_strip_nulls(jsonb_build_object('serials', v_line.detail -> 'serials',
'parts', (select jsonb_agg(jsonb_build_object('lotId', g.lot, 'quantity', g.quantity::text))
from (select a."metadata" ->> 'lotId' as lot, (sum(-e."amount" / power(10::numeric, a."scale")))::numeric(20, 6) as quantity
from "better_supabase"."ledger_entries" e join "better_supabase"."ledger_accounts" a on a."id" = e."account_id"
where e."transaction_id" = v_movement and a."kind" = 'stock'
group by a."metadata" ->> 'lotId') g)))
where x."transfer_id" = ship_transfer.transfer and x."variant_id" = v_line.variant;
end loop;
update "better_supabase"."stock_transfers" x set "status" = 'in_transit', "shipped_at" = now() where x."id" = ship_transfer.transfer;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."ship_transfer"(uuid) from public, anon;
grant execute on function "better_supabase"."ship_transfer"(uuid) to authenticated, service_role;
-- Puts an in-transit transfer's stock into its destination.
create or replace function "better_supabase"."receive_transfer"(transfer uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_line record;
v_part record;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."from_location_id" as from_location, x."to_location_id" as to_location, x."status" as status
into v_row from "better_supabase"."stock_transfers" x where x."id" = receive_transfer.transfer for update;
if not found then
raise exception 'transfer not found' using errcode = 'P0002', hint = 'INVENTORY_TRANSFER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'in_transit' then
raise exception 'the transfer can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_TRANSFER_STATUS';
end if;
for v_line in
select x."variant_id" as variant, x."quantity" as quantity, x."detail" as detail
from "better_supabase"."stock_transfer_lines" x where x."transfer_id" = receive_transfer.transfer
loop
for v_part in
select nullif(p ->> 'lotId', '')::uuid as lot, (p ->> 'quantity')::numeric as quantity
from jsonb_array_elements(coalesce(v_line.detail -> 'parts', jsonb_build_array(jsonb_build_object('quantity', v_line.quantity)))) p
loop
perform "better_supabase"."move_stock"(v_row.tenant, v_line.variant, v_row.to_location, v_part.quantity, 'transfer_in', 'transfer', receive_transfer.transfer::text, null, jsonb_strip_nulls(jsonb_build_object('lotId', v_part.lot, 'serials', (select jsonb_agg(z."serial") from "better_supabase"."stock_serials" z
where z."variant_id" = v_line.variant and z."serial" in (select jsonb_array_elements_text(v_line.detail -> 'serials'))
and z."lot_id" is not distinct from v_part.lot))));
end loop;
end loop;
update "better_supabase"."stock_transfers" x set "status" = 'received', "received_at" = now() where x."id" = receive_transfer.transfer;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."receive_transfer"(uuid) from public, anon;
grant execute on function "better_supabase"."receive_transfer"(uuid) to authenticated, service_role;
-- Cancels a draft or in-transit transfer; in-transit stock goes back to the source.
create or replace function "better_supabase"."cancel_transfer"(transfer uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_line record;
v_part record;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."from_location_id" as from_location, x."to_location_id" as to_location, x."status" as status
into v_row from "better_supabase"."stock_transfers" x where x."id" = cancel_transfer.transfer for update;
if not found then
raise exception 'transfer not found' using errcode = 'P0002', hint = 'INVENTORY_TRANSFER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.manage'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status not in ('draft', 'in_transit') then
raise exception 'the transfer can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_TRANSFER_STATUS';
end if;
if v_row.status = 'in_transit' then
for v_line in
select x."variant_id" as variant, x."quantity" as quantity, x."detail" as detail
from "better_supabase"."stock_transfer_lines" x where x."transfer_id" = cancel_transfer.transfer
loop
for v_part in
select nullif(p ->> 'lotId', '')::uuid as lot, (p ->> 'quantity')::numeric as quantity
from jsonb_array_elements(coalesce(v_line.detail -> 'parts', jsonb_build_array(jsonb_build_object('quantity', v_line.quantity)))) p
loop
perform "better_supabase"."move_stock"(v_row.tenant, v_line.variant, v_row.from_location, v_part.quantity, 'transfer_in', 'transfer', cancel_transfer.transfer::text, null, jsonb_strip_nulls(jsonb_build_object('lotId', v_part.lot, 'serials', (select jsonb_agg(z."serial") from "better_supabase"."stock_serials" z
where z."variant_id" = v_line.variant and z."serial" in (select jsonb_array_elements_text(v_line.detail -> 'serials'))
and z."lot_id" is not distinct from v_part.lot))));
end loop;
end loop;
end if;
update "better_supabase"."stock_transfers" x set "status" = 'cancelled' where x."id" = cancel_transfer.transfer;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."cancel_transfer"(uuid) from public, anon;
grant execute on function "better_supabase"."cancel_transfer"(uuid) to authenticated, service_role;
-- Creates a draft purchase order (purchase_order null) or replaces a draft's
-- fields and lines. lines: [{ "variantId": uuid, "quantity": n, "unitCost": "minor units"
-- }], and per line "taxRateBps" and "taxCode" when the order keeps tax lines.
-- supplier_type and supplier_id name a config.recordTypes record, or are both null.
create or replace function "better_supabase"."upsert_purchase_order"(tenant uuid, purchase_order uuid, location uuid, supplier_type text, supplier_id text, currency text, expected_at timestamptz, lines jsonb, note text, number text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_purchase_order.purchase_order;
v_number text := nullif(btrim(upsert_purchase_order.number), '');
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', upsert_purchase_order.tenant, 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."inventory_locations" x where x."id" = upsert_purchase_order.location and x."tenant_id" = upsert_purchase_order.tenant) then
raise exception 'location not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if (upsert_purchase_order.supplier_type is null) <> (upsert_purchase_order.supplier_id is null) then
raise exception 'supplier_type and supplier_id go together' using errcode = '22023', hint = 'INVENTORY_SUPPLIER_INVALID';
end if;
if v_number is not null and length(v_number) > 50 then
raise exception 'a purchase order number is up to 50 characters' using errcode = '22023', hint = 'INVENTORY_PURCHASE_ORDER_NUMBER_INVALID';
end if;
if upsert_purchase_order.currency is null or "better_supabase"."currency_minor_units"(upsert_purchase_order.currency) is null then
raise exception 'the currency must be an ISO 4217 code' using errcode = '22023', hint = 'INVENTORY_CURRENCY_INVALID';
end if;
if jsonb_typeof(upsert_purchase_order.lines) is distinct from 'array' or jsonb_array_length(upsert_purchase_order.lines) = 0
or exists (
select 1 from jsonb_array_elements(upsert_purchase_order.lines) e
where jsonb_typeof(e) <> 'object'
or coalesce(e ->> 'variantId', '') !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
or case when coalesce(e ->> 'quantity', '') ~ '^[0-9]{1,14}([.][0-9]{1,6})?$' then (e ->> 'quantity')::numeric <= 0 else true end
or coalesce(e ->> 'unitCost', '') !~ '^[0-9]{1,18}$'
or (e ? 'taxRateBps' and coalesce(e ->> 'taxRateBps', '') !~ '^[0-9]{1,6}$')
or (e ? 'taxRateBps' and coalesce(e ->> 'taxRateBps', '0') ~ '^[0-9]{1,6}$' and (e ->> 'taxRateBps')::integer > 100000)
)
or (select count(distinct e ->> 'variantId') from jsonb_array_elements(upsert_purchase_order.lines) e) <> jsonb_array_length(upsert_purchase_order.lines) then
raise exception 'lines must be a non-empty list with a unique variantId and a positive quantity each' using errcode = '22023', hint = 'INVENTORY_LINES_INVALID';
end if;
if exists (
select 1 from jsonb_array_elements(upsert_purchase_order.lines) e
where not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = (e ->> 'variantId')::uuid and cv."tenant_id" = upsert_purchase_order.tenant)
) then
raise exception 'a line names a variant outside this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
if v_id is null then
insert into "better_supabase"."purchase_orders" ("tenant_id", "location_id", "supplier_type", "supplier_id", "currency", "expected_at", "note", "number")
values (upsert_purchase_order.tenant, upsert_purchase_order.location, upsert_purchase_order.supplier_type, upsert_purchase_order.supplier_id,
upsert_purchase_order.currency, upsert_purchase_order.expected_at, upsert_purchase_order.note, v_number)
returning "id" into v_id;
else
perform 1 from "better_supabase"."purchase_orders" x where x."id" = v_id and x."tenant_id" = upsert_purchase_order.tenant for update;
if not found then
raise exception 'purchase order not found' using errcode = 'P0002', hint = 'INVENTORY_PURCHASE_ORDER_NOT_FOUND';
end if;
update "better_supabase"."purchase_orders" x set "location_id" = upsert_purchase_order.location, "supplier_type" = upsert_purchase_order.supplier_type,
"supplier_id" = upsert_purchase_order.supplier_id, "currency" = upsert_purchase_order.currency,
"expected_at" = upsert_purchase_order.expected_at, "note" = upsert_purchase_order.note, "number" = coalesce(v_number, x."number"), "updated_at" = now()
where x."id" = v_id and x."status" = 'draft';
if not found then
raise exception 'only a draft purchase order can change' using errcode = '55000', hint = 'INVENTORY_PURCHASE_ORDER_LOCKED';
end if;
delete from "better_supabase"."purchase_order_lines" x where x."purchase_order_id" = v_id;
end if;
insert into "better_supabase"."purchase_order_lines" ("tenant_id", "purchase_order_id", "variant_id", "quantity_ordered", "unit_cost", "tax_rate_bps", "tax_code")
select upsert_purchase_order.tenant, v_id, (e ->> 'variantId')::uuid, (e ->> 'quantity')::numeric, (e ->> 'unitCost')::bigint, (e ->> 'taxRateBps')::integer, nullif(trim(e ->> 'taxCode'), '')
from jsonb_array_elements(upsert_purchase_order.lines) e;
delete from "better_supabase"."purchase_order_tax_lines" x where x."purchase_order_id" = v_id;
insert into "better_supabase"."purchase_order_tax_lines" ("tenant_id", "purchase_order_id", "tax_code", "tax_rate_bps", "net", "tax", "gross")
select upsert_purchase_order.tenant, v_id, g.code, g.rate, sum(g.net), sum(g.tax), sum(g.net + g.tax)
from (
select nullif(trim(e ->> 'taxCode'), '') as code, coalesce((e ->> 'taxRateBps')::integer, 0) as rate,
round((e ->> 'quantity')::numeric * (e ->> 'unitCost')::bigint)::bigint as net,
round((e ->> 'quantity')::numeric * (e ->> 'unitCost')::bigint * coalesce((e ->> 'taxRateBps')::integer, 0) / 10000.0)::bigint as tax
from jsonb_array_elements(upsert_purchase_order.lines) e
) g
where g.rate > 0
group by g.code, g.rate;
return jsonb_build_object('id', v_id, 'status', 'draft', 'number', (select x."number" from "better_supabase"."purchase_orders" x where x."id" = v_id));
exception when unique_violation then
raise exception 'another purchase order has this number' using errcode = '23505', hint = 'INVENTORY_PURCHASE_ORDER_NUMBER_TAKEN';
end;
$$;
revoke execute on function "better_supabase"."upsert_purchase_order"(uuid, uuid, uuid, text, text, text, timestamptz, jsonb, text, text) from public, anon;
grant execute on function "better_supabase"."upsert_purchase_order"(uuid, uuid, uuid, text, text, text, timestamptz, jsonb, text, text) to authenticated, service_role;
-- The tax of a purchase order per code and rate, with the order's currency.
-- Amounts are text in minor units.
create or replace function "better_supabase"."purchase_order_tax_lines"(purchase_order uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row record;
begin
select x."tenant_id" as tenant, x."currency" as currency into v_row
from "better_supabase"."purchase_orders" x where x."id" = purchase_order_tax_lines.purchase_order;
if not found or not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.read'), false)) then
raise exception 'purchase order not found' using errcode = 'P0002', hint = 'INVENTORY_PURCHASE_ORDER_NOT_FOUND';
end if;
return jsonb_build_object('currency', v_row.currency::text, 'lines', coalesce((
select jsonb_agg(jsonb_build_object('taxCode', z."tax_code", 'taxRateBps', z."tax_rate_bps",
'net', z."net"::text, 'tax', z."tax"::text, 'gross', z."gross"::text) order by z."tax_rate_bps", z."tax_code")
from "better_supabase"."purchase_order_tax_lines" z where z."purchase_order_id" = purchase_order_tax_lines.purchase_order), '[]'::jsonb));
end;
$$;
revoke execute on function "better_supabase"."purchase_order_tax_lines"(uuid) from public, anon;
grant execute on function "better_supabase"."purchase_order_tax_lines"(uuid) to authenticated, service_role;
-- Sends a draft purchase order: its quantities count as incoming at its location.
-- An order without a number gets the next one: one more than the organization's
-- highest all-digit number, under a transaction lock.
create or replace function "better_supabase"."place_purchase_order"(purchase_order uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_number text;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."location_id" as location, x."status" as status,
x."supplier_type" as supplier_type, x."supplier_id" as supplier_id, x."currency" as currency
into v_row from "better_supabase"."purchase_orders" x where x."id" = place_purchase_order.purchase_order for update;
if not found then
raise exception 'purchase order not found' using errcode = 'P0002', hint = 'INVENTORY_PURCHASE_ORDER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status <> 'draft' then
raise exception 'the purchase order can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_PURCHASE_ORDER_STATUS';
end if;
select x."number" into v_number from "better_supabase"."purchase_orders" x where x."id" = place_purchase_order.purchase_order;
if v_number is null then
perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(v_row.tenant::text || ':inventory:purchase_order', 0));
select (coalesce(max(case when y."number" ~ '^[0-9]{1,15}$' then y."number"::bigint end), 0) + 1)::text into v_number
from "better_supabase"."purchase_orders" y where y."tenant_id" = v_row.tenant;
end if;
insert into "better_supabase"."stock_levels" as x ("tenant_id", "variant_id", "location_id", "incoming")
select v_row.tenant, y."variant_id", v_row.location, y."quantity_ordered"
from "better_supabase"."purchase_order_lines" y where y."purchase_order_id" = place_purchase_order.purchase_order
on conflict ("variant_id", "location_id") do update
set "incoming" = x."incoming" + excluded."incoming", "updated_at" = now();
update "better_supabase"."purchase_orders" x set "status" = 'ordered', "placed_at" = now(), "number" = v_number, "updated_at" = now()
where x."id" = place_purchase_order.purchase_order;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."place_purchase_order"(uuid) from public, anon;
grant execute on function "better_supabase"."place_purchase_order"(uuid) to authenticated, service_role;
-- Receives some or all of a placed order's lines into stock.
-- lines: [{ "lineId": uuid, "quantity": n, "lot"?: { code, expiresOn },
-- "lotId"?, "binId"?, "serials"?, "country"?, "netMassKg"? }]; the line's unit cost feeds the
-- variant's weighted average cost. Lines left short stay on
-- backorder until a later receipt or a cancel. Returns the new status and
-- the quantity still on backorder, plus receiptId: the goods receipt of
-- this delivery.
create or replace function "better_supabase"."receive_purchase_order"(purchase_order uuid, lines jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_line record;
v_backordered numeric;
v_status text;
v_receipt uuid;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."location_id" as location, x."status" as status,
x."supplier_type" as supplier_type, x."supplier_id" as supplier_id, x."currency" as currency
into v_row from "better_supabase"."purchase_orders" x where x."id" = receive_purchase_order.purchase_order for update;
if not found then
raise exception 'purchase order not found' using errcode = 'P0002', hint = 'INVENTORY_PURCHASE_ORDER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status not in ('ordered', 'partially_received') then
raise exception 'the purchase order can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_PURCHASE_ORDER_STATUS';
end if;
if jsonb_typeof(receive_purchase_order.lines) is distinct from 'array' or jsonb_array_length(receive_purchase_order.lines) = 0
or exists (
select 1 from jsonb_array_elements(receive_purchase_order.lines) e
where jsonb_typeof(e) <> 'object'
or coalesce(e ->> 'lineId', '') !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
or case when coalesce(e ->> 'quantity', '') ~ '^[0-9]{1,14}([.][0-9]{1,6})?$' then (e ->> 'quantity')::numeric <= 0 else true end
)
or (select count(distinct e ->> 'lineId') from jsonb_array_elements(receive_purchase_order.lines) e) <> jsonb_array_length(receive_purchase_order.lines) then
raise exception 'lines must be a non-empty list with a unique lineId and a positive quantity each' using errcode = '22023', hint = 'INVENTORY_LINES_INVALID';
end if;
insert into "better_supabase"."inventory_receipts" ("tenant_id", "purchase_order_id", "location_id")
values (v_row.tenant, receive_purchase_order.purchase_order, v_row.location)
returning "id" into v_receipt;
for v_line in
select y."id" as id, y."variant_id" as variant, y."quantity_ordered" - y."quantity_canceled" as ordered,
y."quantity_received" as received, (e ->> 'quantity')::numeric as quantity, y."unit_cost" as unit_cost,
jsonb_strip_nulls(jsonb_build_object('lot', e -> 'lot', 'lotId', e -> 'lotId', 'binId', e -> 'binId', 'serials', e -> 'serials', 'country', e -> 'country', 'netMassKg', e -> 'netMassKg')) as detail
from jsonb_array_elements(receive_purchase_order.lines) e
left join "better_supabase"."purchase_order_lines" y on y."id" = (e ->> 'lineId')::uuid and y."purchase_order_id" = receive_purchase_order.purchase_order
loop
if v_line.id is null then
raise exception 'a line isn''t on this purchase order' using errcode = 'P0002', hint = 'INVENTORY_LINE_NOT_FOUND';
end if;
if v_line.received + v_line.quantity > v_line.ordered then
raise exception 'a line would receive more than was ordered' using errcode = '22023', hint = 'INVENTORY_OVER_RECEIPT';
end if;
update "better_supabase"."purchase_order_lines" y set "quantity_received" = y."quantity_received" + v_line.quantity where y."id" = v_line.id;
update "better_supabase"."stock_levels" x set "incoming" = greatest(x."incoming" - v_line.quantity, 0), "updated_at" = now()
where x."variant_id" = v_line.variant and x."location_id" = v_row.location;
perform "better_supabase"."move_stock"(v_row.tenant, v_line.variant, v_row.location, v_line.quantity, 'receipt', 'purchase_order', receive_purchase_order.purchase_order::text, null, v_line.detail || jsonb_build_object('unitCost', v_line.unit_cost::text, 'currency', v_row.currency::text));
insert into "better_supabase"."inventory_receipt_lines" ("tenant_id", "receipt_id", "purchase_order_line_id", "variant_id", "quantity", "unit_cost", "detail")
values (v_row.tenant, v_receipt, v_line.id, v_line.variant, v_line.quantity, v_line.unit_cost, nullif(v_line.detail, '{}'::jsonb));
end loop;
select coalesce(sum(y."quantity_ordered" - y."quantity_canceled" - y."quantity_received"), 0) into v_backordered
from "better_supabase"."purchase_order_lines" y where y."purchase_order_id" = receive_purchase_order.purchase_order;
v_status := case when v_backordered = 0 then 'received' else 'partially_received' end;
update "better_supabase"."purchase_orders" x set "status" = v_status, "updated_at" = now()
where x."id" = receive_purchase_order.purchase_order;
null;
null;
return jsonb_build_object('status', v_status, 'backordered', v_backordered, 'receiptId', v_receipt);
end;
$$;
revoke execute on function "better_supabase"."receive_purchase_order"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."receive_purchase_order"(uuid, jsonb) to authenticated, service_role;
-- Gives up part of what is still owed on some lines of a placed order, for a
-- supplier that can't deliver it all. lines: [{ "lineId": uuid, "quantity": n }];
-- each quantity is at most what the line still owes. The units stop counting as
-- incoming. An order with nothing left owed becomes received, or cancelled when
-- nothing was received. Returns the new status and the quantity still on
-- backorder.
create or replace function "better_supabase"."cancel_purchase_order_quantity"(purchase_order uuid, lines jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
v_line record;
v_backordered numeric;
v_received numeric;
v_status text;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."location_id" as location, x."status" as status,
x."supplier_type" as supplier_type, x."supplier_id" as supplier_id, x."currency" as currency
into v_row from "better_supabase"."purchase_orders" x where x."id" = cancel_purchase_order_quantity.purchase_order for update;
if not found then
raise exception 'purchase order not found' using errcode = 'P0002', hint = 'INVENTORY_PURCHASE_ORDER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status not in ('ordered', 'partially_received') then
raise exception 'the purchase order can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_PURCHASE_ORDER_STATUS';
end if;
if jsonb_typeof(cancel_purchase_order_quantity.lines) is distinct from 'array' or jsonb_array_length(cancel_purchase_order_quantity.lines) = 0
or exists (
select 1 from jsonb_array_elements(cancel_purchase_order_quantity.lines) e
where jsonb_typeof(e) <> 'object'
or coalesce(e ->> 'lineId', '') !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
or case when coalesce(e ->> 'quantity', '') ~ '^[0-9]{1,14}([.][0-9]{1,6})?$' then (e ->> 'quantity')::numeric <= 0 else true end
)
or (select count(distinct e ->> 'lineId') from jsonb_array_elements(cancel_purchase_order_quantity.lines) e) <> jsonb_array_length(cancel_purchase_order_quantity.lines) then
raise exception 'lines must be a non-empty list with a unique lineId and a positive quantity each' using errcode = '22023', hint = 'INVENTORY_LINES_INVALID';
end if;
for v_line in
select y."id" as id, y."variant_id" as variant,
y."quantity_ordered" - y."quantity_canceled" - y."quantity_received" as owed, (e ->> 'quantity')::numeric as quantity
from jsonb_array_elements(cancel_purchase_order_quantity.lines) e
left join "better_supabase"."purchase_order_lines" y on y."id" = (e ->> 'lineId')::uuid and y."purchase_order_id" = cancel_purchase_order_quantity.purchase_order
loop
if v_line.id is null then
raise exception 'a line isn''t on this purchase order' using errcode = 'P0002', hint = 'INVENTORY_LINE_NOT_FOUND';
end if;
if v_line.quantity > v_line.owed then
raise exception 'a line would cancel more than it still owes' using errcode = '22023', hint = 'INVENTORY_OVER_CANCEL';
end if;
update "better_supabase"."purchase_order_lines" y set "quantity_canceled" = y."quantity_canceled" + v_line.quantity where y."id" = v_line.id;
update "better_supabase"."stock_levels" x set "incoming" = greatest(x."incoming" - v_line.quantity, 0), "updated_at" = now()
where x."variant_id" = v_line.variant and x."location_id" = v_row.location;
end loop;
select coalesce(sum(y."quantity_ordered" - y."quantity_canceled" - y."quantity_received"), 0), coalesce(sum(y."quantity_received"), 0)
into v_backordered, v_received from "better_supabase"."purchase_order_lines" y where y."purchase_order_id" = cancel_purchase_order_quantity.purchase_order;
v_status := case when v_backordered > 0 then v_row.status when v_received > 0 then 'received' else 'cancelled' end;
update "better_supabase"."purchase_orders" x set "status" = v_status, "updated_at" = now()
where x."id" = cancel_purchase_order_quantity.purchase_order;
null;
return jsonb_build_object('status', v_status, 'backordered', v_backordered);
end;
$$;
revoke execute on function "better_supabase"."cancel_purchase_order_quantity"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."cancel_purchase_order_quantity"(uuid, jsonb) to authenticated, service_role;
-- Cancels a purchase order that isn't fully received; what's still on
-- backorder stops counting as incoming.
create or replace function "better_supabase"."cancel_purchase_order"(purchase_order uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row record;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select x."tenant_id" as tenant, x."location_id" as location, x."status" as status,
x."supplier_type" as supplier_type, x."supplier_id" as supplier_id, x."currency" as currency
into v_row from "better_supabase"."purchase_orders" x where x."id" = cancel_purchase_order.purchase_order for update;
if not found then
raise exception 'purchase order not found' using errcode = 'P0002', hint = 'INVENTORY_PURCHASE_ORDER_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row.tenant, 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row.status not in ('draft', 'ordered', 'partially_received') then
raise exception 'the purchase order can''t do this in its current status' using errcode = '55000', hint = 'INVENTORY_PURCHASE_ORDER_STATUS';
end if;
if v_row.status <> 'draft' then
update "better_supabase"."stock_levels" x set "incoming" = greatest(x."incoming" - (y."quantity_ordered" - y."quantity_canceled" - y."quantity_received"), 0), "updated_at" = now()
from "better_supabase"."purchase_order_lines" y
where y."purchase_order_id" = cancel_purchase_order.purchase_order
and x."variant_id" = y."variant_id" and x."location_id" = v_row.location;
end if;
update "better_supabase"."purchase_orders" x set "status" = 'cancelled', "updated_at" = now()
where x."id" = cancel_purchase_order.purchase_order;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."cancel_purchase_order"(uuid) from public, anon;
grant execute on function "better_supabase"."cancel_purchase_order"(uuid) to authenticated, service_role;
-- Asks to buy stock for a location. lines: [{ "variantId": uuid, "quantity": n,
-- "unitCost"?: "minor units" }]. A pending requisition waits for its
-- decision: a holder of inventory.purchase approves or rejects it.
create or replace function "better_supabase"."request_purchase"(tenant uuid, location uuid, lines jsonb, supplier_type text default null, supplier_id text default null, currency text default null, reason text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."purchase_requisitions";
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', request_purchase.tenant, 'inventory.read'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if not exists (select 1 from "better_supabase"."inventory_locations" x where x."id" = request_purchase.location and x."tenant_id" = request_purchase.tenant) then
raise exception 'location not found in this organization' using errcode = 'P0002', hint = 'INVENTORY_LOCATION_NOT_FOUND';
end if;
if (request_purchase.supplier_type is null) <> (request_purchase.supplier_id is null) then
raise exception 'supplier_type and supplier_id go together' using errcode = '22023', hint = 'INVENTORY_SUPPLIER_INVALID';
end if;
if request_purchase.currency is not null and "better_supabase"."currency_minor_units"(request_purchase.currency) is null then
raise exception 'the currency must be an ISO 4217 code' using errcode = '22023', hint = 'INVENTORY_CURRENCY_INVALID';
end if;
if jsonb_typeof(request_purchase.lines) is distinct from 'array' or jsonb_array_length(request_purchase.lines) = 0
or exists (
select 1 from jsonb_array_elements(request_purchase.lines) e
where jsonb_typeof(e) <> 'object'
or coalesce(e ->> 'variantId', '') !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
or case when coalesce(e ->> 'quantity', '') ~ '^[0-9]{1,14}([.][0-9]{1,6})?$' then (e ->> 'quantity')::numeric <= 0 else true end
or (e ? 'unitCost' and coalesce(e ->> 'unitCost', '') !~ '^[0-9]{1,18}$')
)
or (select count(distinct e ->> 'variantId') from jsonb_array_elements(request_purchase.lines) e) <> jsonb_array_length(request_purchase.lines) then
raise exception 'lines must be a non-empty list with a unique variantId and a positive quantity each' using errcode = '22023', hint = 'INVENTORY_LINES_INVALID';
end if;
if exists (
select 1 from jsonb_array_elements(request_purchase.lines) e
where not exists (select 1 from "better_supabase"."product_variants" cv where cv."id" = (e ->> 'variantId')::uuid and cv."tenant_id" = request_purchase.tenant)
) then
raise exception 'a line names a variant outside this organization' using errcode = 'P0002', hint = 'INVENTORY_VARIANT_NOT_FOUND';
end if;
insert into "better_supabase"."purchase_requisitions" ("tenant_id", "location_id", "supplier_type", "supplier_id", "currency", "reason")
values (request_purchase.tenant, request_purchase.location, request_purchase.supplier_type, request_purchase.supplier_id,
request_purchase.currency, nullif(trim(request_purchase.reason), ''))
returning * into v_row;
insert into "better_supabase"."purchase_requisition_lines" ("tenant_id", "requisition_id", "variant_id", "quantity", "unit_cost")
select request_purchase.tenant, v_row."id", (e ->> 'variantId')::uuid, (e ->> 'quantity')::numeric, (e ->> 'unitCost')::bigint
from jsonb_array_elements(request_purchase.lines) e;
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'locationId', v_row."location_id",
'supplierType', v_row."supplier_type", 'supplierId', v_row."supplier_id", 'currency', v_row."currency",
'status', v_row."status", 'reason', v_row."reason", 'requestedBy', v_row."requested_by",
'decidedBy', v_row."decided_by", 'decidedAt', v_row."decided_at", 'approvalId', v_row."approval_id",
'createdAt', v_row."created_at",
'purchaseOrderId', v_row."purchase_order_id",
'lines', coalesce((select jsonb_agg(jsonb_build_object('id', y."id", 'variantId', y."variant_id", 'quantity', y."quantity"::text,
'unitCost', y."unit_cost"::text) order by y."variant_id") from "better_supabase"."purchase_requisition_lines" y where y."requisition_id" = v_row."id"), '[]'::jsonb));
end;
$$;
revoke execute on function "better_supabase"."request_purchase"(uuid, uuid, jsonb, text, text, text, text) from public, anon;
grant execute on function "better_supabase"."request_purchase"(uuid, uuid, jsonb, text, text, text, text) to authenticated, service_role;
-- Settles a pending requisition: approved or rejected. Approvals calls it; it
-- isn't granted to anyone.
create or replace function "better_supabase"."purchase_requisition_decided"(requisition uuid, approved boolean)
returns void
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."purchase_requisitions";
begin
update "better_supabase"."purchase_requisitions" x set "status" = case when purchase_requisition_decided.approved then 'approved' else 'rejected' end,
"decided_by" = auth.uid(), "decided_at" = now(), "updated_at" = now()
where x."id" = purchase_requisition_decided.requisition and x."status" = 'pending'
returning * into v_row;
if found and purchase_requisition_decided.approved then
null;
end if;
end;
$$;
revoke execute on function "better_supabase"."purchase_requisition_decided"(uuid, boolean) from public, anon, authenticated;
-- Approves (approve true) or rejects a pending requisition. Needs
-- inventory.purchase.
create or replace function "better_supabase"."decide_purchase_requisition"(requisition uuid, approve boolean)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."purchase_requisitions";
begin
select * into v_row from "better_supabase"."purchase_requisitions" x where x."id" = decide_purchase_requisition.requisition for update;
if not found then
raise exception 'purchase requisition not found' using errcode = 'P0002', hint = 'INVENTORY_REQUISITION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_row."status" <> 'pending' then
raise exception 'only a pending requisition is decided' using errcode = '55000', hint = 'INVENTORY_REQUISITION_STATUS';
end if;
perform "better_supabase"."purchase_requisition_decided"(v_row."id", coalesce(decide_purchase_requisition.approve, false));
return (select jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'locationId', x."location_id",
'supplierType', x."supplier_type", 'supplierId', x."supplier_id", 'currency', x."currency",
'status', x."status", 'reason', x."reason", 'requestedBy', x."requested_by",
'decidedBy', x."decided_by", 'decidedAt', x."decided_at", 'approvalId', x."approval_id",
'createdAt', x."created_at",
'purchaseOrderId', x."purchase_order_id",
'lines', coalesce((select jsonb_agg(jsonb_build_object('id', y."id", 'variantId', y."variant_id", 'quantity', y."quantity"::text,
'unitCost', y."unit_cost"::text) order by y."variant_id") from "better_supabase"."purchase_requisition_lines" y where y."requisition_id" = x."id"), '[]'::jsonb)) from "better_supabase"."purchase_requisitions" x where x."id" = v_row."id");
end;
$$;
revoke execute on function "better_supabase"."decide_purchase_requisition"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."decide_purchase_requisition"(uuid, boolean) to authenticated, service_role;
-- A draft purchase order from approved requisitions of one location: their
-- lines summed per variant, at the highest unit cost a requisition names
-- (0 when none does; edit the draft before placing it). The supplier and
-- currency default to the ones the requisitions share. The requisitions
-- become ordered.
create or replace function "better_supabase"."purchase_order_from_requisitions"(requisitions uuid[], supplier_type text default null, supplier_id text default null, currency text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_location uuid;
v_supplier_type text := purchase_order_from_requisitions.supplier_type;
v_supplier_id text := purchase_order_from_requisitions.supplier_id;
v_currency text := upper(purchase_order_from_requisitions.currency);
v_lines jsonb;
v_order jsonb;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if coalesce(cardinality(purchase_order_from_requisitions.requisitions), 0) = 0 then
raise exception 'name at least one requisition' using errcode = '22023', hint = 'INVENTORY_REQUISITION_NOT_FOUND';
end if;
perform 1 from "better_supabase"."purchase_requisitions" x where x."id" = any (purchase_order_from_requisitions.requisitions) for update;
if (select count(*) from "better_supabase"."purchase_requisitions" x where x."id" = any (purchase_order_from_requisitions.requisitions))
<> (select count(distinct r) from unnest(purchase_order_from_requisitions.requisitions) r) then
raise exception 'purchase requisition not found' using errcode = 'P0002', hint = 'INVENTORY_REQUISITION_NOT_FOUND';
end if;
if (select count(distinct x."tenant_id") + count(distinct x."location_id") from "better_supabase"."purchase_requisitions" x where x."id" = any (purchase_order_from_requisitions.requisitions)) <> 2 then
raise exception 'requisitions on one purchase order share an organization and a location' using errcode = '22023', hint = 'INVENTORY_REQUISITION_MIXED';
end if;
select x."tenant_id", x."location_id" into v_tenant, v_location
from "better_supabase"."purchase_requisitions" x where x."id" = purchase_order_from_requisitions.requisitions[1];
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.purchase'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if exists (select 1 from "better_supabase"."purchase_requisitions" x where x."id" = any (purchase_order_from_requisitions.requisitions) and x."status" <> 'approved') then
raise exception 'only approved requisitions become a purchase order' using errcode = '55000', hint = 'INVENTORY_REQUISITION_STATUS';
end if;
if v_supplier_id is null then
select min(x."supplier_type"), min(x."supplier_id") into v_supplier_type, v_supplier_id
from "better_supabase"."purchase_requisitions" x where x."id" = any (purchase_order_from_requisitions.requisitions)
having count(distinct coalesce(x."supplier_type", '') || ':' || coalesce(x."supplier_id", '')) = 1;
end if;
if v_currency is null then
select min(x."currency") into v_currency
from "better_supabase"."purchase_requisitions" x where x."id" = any (purchase_order_from_requisitions.requisitions)
having count(distinct x."currency") = 1;
end if;
select jsonb_agg(jsonb_build_object('variantId', y.variant, 'quantity', y.quantity::text, 'unitCost', y.unit_cost::text)) into v_lines
from (
select l."variant_id" as variant, sum(l."quantity") as quantity, coalesce(max(l."unit_cost"), 0) as unit_cost
from "better_supabase"."purchase_requisition_lines" l where l."requisition_id" = any (purchase_order_from_requisitions.requisitions)
group by 1
) y;
v_order := "better_supabase"."upsert_purchase_order"(v_tenant, null, v_location, v_supplier_type, v_supplier_id, v_currency, null, v_lines, null);
update "better_supabase"."purchase_requisitions" x set "status" = 'ordered', "purchase_order_id" = (v_order ->> 'id')::uuid, "updated_at" = now()
where x."id" = any (purchase_order_from_requisitions.requisitions);
return v_order;
end;
$$;
revoke execute on function "better_supabase"."purchase_order_from_requisitions"(uuid[], text, text, text) from public, anon;
grant execute on function "better_supabase"."purchase_order_from_requisitions"(uuid[], text, text, text) to authenticated, service_role;
-- A requisition with its lines, readable by a holder of inventory.read.
create or replace function "better_supabase"."get_purchase_requisition"(requisition uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."purchase_requisitions";
begin
select * into v_row from "better_supabase"."purchase_requisitions" x where x."id" = get_purchase_requisition.requisition;
if not found then
raise exception 'purchase requisition not found' using errcode = 'P0002', hint = 'INVENTORY_REQUISITION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'inventory.read'), false)) then
raise exception 'not allowed to change this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'locationId', v_row."location_id",
'supplierType', v_row."supplier_type", 'supplierId', v_row."supplier_id", 'currency', v_row."currency",
'status', v_row."status", 'reason', v_row."reason", 'requestedBy', v_row."requested_by",
'decidedBy', v_row."decided_by", 'decidedAt', v_row."decided_at", 'approvalId', v_row."approval_id",
'createdAt', v_row."created_at",
'purchaseOrderId', v_row."purchase_order_id",
'lines', coalesce((select jsonb_agg(jsonb_build_object('id', y."id", 'variantId', y."variant_id", 'quantity', y."quantity"::text,
'unitCost', y."unit_cost"::text) order by y."variant_id") from "better_supabase"."purchase_requisition_lines" y where y."requisition_id" = v_row."id"), '[]'::jsonb));
end;
$$;
revoke execute on function "better_supabase"."get_purchase_requisition"(uuid) from public, anon;
grant execute on function "better_supabase"."get_purchase_requisition"(uuid) to authenticated, service_role;
-- The stock page in one call: the level count, the levels at or below their
-- reorder point (the emptiest first) and the lots that expire soon.
create or replace function "better_supabase"."inventory_overview"(tenant uuid, row_limit integer default 20, expiry_days integer default 30)
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
declare
v_low jsonb;
v_low_count integer;
v_level_count integer;
v_expiring jsonb;
begin
select count(*)::integer into v_level_count
from "better_supabase"."stock_levels" y where y."tenant_id" = inventory_overview.tenant;
select count(*)::integer into v_low_count
from "better_supabase"."stock_levels" y
where y."tenant_id" = inventory_overview.tenant
and y."reorder_point" is not null and y."available" <= y."reorder_point";
select coalesce(jsonb_agg(jsonb_build_object(
'variantId', x."variant_id", 'locationId', x."location_id",
'onHand', x."on_hand"::text, 'available', x."available"::text,
'reorderPoint', x."reorder_point"::text)
order by x."available" - x."reorder_point", x."variant_id", x."location_id"), '[]'::jsonb)
into v_low
from (
select * from "better_supabase"."stock_levels" y
where y."tenant_id" = inventory_overview.tenant
and y."reorder_point" is not null and y."available" <= y."reorder_point"
order by y."available" - y."reorder_point", y."variant_id", y."location_id"
limit greatest(coalesce(inventory_overview.row_limit, 20), 0)
) x;
select coalesce(jsonb_agg(jsonb_build_object(
'lotId', e ->> 'lotId', 'code', e ->> 'code', 'variantId', e ->> 'variantId',
'locationId', e ->> 'locationId', 'expiresOn', e ->> 'expiresOn', 'onHand', e ->> 'onHand')), '[]'::jsonb)
into v_expiring
from jsonb_array_elements("better_supabase"."expiring_lots"(inventory_overview.tenant,
current_date + greatest(coalesce(inventory_overview.expiry_days, 30), 0))) e;
return jsonb_build_object('levelCount', v_level_count, 'lowStockCount', v_low_count,
'lowStock', v_low, 'expiring', v_expiring);
end;
$$;
revoke execute on function "better_supabase"."inventory_overview"(uuid, integer, integer) from public, anon;
grant execute on function "better_supabase"."inventory_overview"(uuid, integer, integer) to authenticated, service_role;
-- Levels for the requested variants. A null variant list reads every level of
-- the organization; a list uses the level primary key and does not scan the rest.
create or replace function "better_supabase"."inventory_levels"(tenant uuid, variant_ids uuid[] default null, location_id uuid default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object(
'variantId', y."variant_id",
'locationId', y."location_id",
'onHand', y."on_hand"::text,
'allocated', y."reserved"::text,
'available', y."available"::text,
'incoming', y."incoming"::text,
'reorderPoint', y."reorder_point"::text,
'status', case
when y."available" <= 0 then 'out'
when y."reorder_point" is not null and y."available" <= y."reorder_point" then 'low'
else 'in_stock'
end
)), '[]'::jsonb)
from "better_supabase"."stock_levels" y
where y."tenant_id" = inventory_levels.tenant
and (inventory_levels.variant_ids is null or y."variant_id" = any (inventory_levels.variant_ids))
and (inventory_levels.location_id is null or y."location_id" = inventory_levels.location_id)
$$;
revoke execute on function "better_supabase"."inventory_levels"(uuid, uuid[], uuid) from public, anon;
grant execute on function "better_supabase"."inventory_levels"(uuid, uuid[], uuid) to authenticated, service_role;
create or replace function "better_supabase"."inventory_status_counts"(tenant uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object(
'inStock', count(*) filter (where y."available" > 0 and (y."reorder_point" is null or y."available" > y."reorder_point")),
'low', count(*) filter (where y."reorder_point" is not null and y."available" <= y."reorder_point" and y."available" > 0),
'out', count(*) filter (where y."available" <= 0)
)
from "better_supabase"."stock_levels" y
where y."tenant_id" = inventory_status_counts.tenant
$$;
revoke execute on function "better_supabase"."inventory_status_counts"(uuid) from public, anon;
grant execute on function "better_supabase"."inventory_status_counts"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."list_inventory_movements"(tenant uuid, variant uuid default null, location uuid default null, bin uuid default null, lot uuid default null, document_type text default null, document_id text default null, row_limit integer default 50, row_offset integer default 0)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at"
)), '[]'::jsonb)
from (
select *
from "better_supabase"."ledger_transactions" y
where y."tenant_id" = list_inventory_movements.tenant
and y."kind" like 'stock.%'
and (list_inventory_movements.variant is null or y."metadata" ->> 'variantId' = list_inventory_movements.variant::text)
and (list_inventory_movements.location is null or y."metadata" ->> 'locationId' = list_inventory_movements.location::text)
and (list_inventory_movements.bin is null or y."metadata" ->> 'binId' = list_inventory_movements.bin::text)
and (list_inventory_movements.lot is null or y."metadata" ->> 'lotId' = list_inventory_movements.lot::text)
and (list_inventory_movements.document_type is null or y."reference_type" = list_inventory_movements.document_type)
and (list_inventory_movements.document_id is null or y."reference_id" = list_inventory_movements.document_id)
order by y."effective_at" desc, y."id"
limit least(greatest(coalesce(list_inventory_movements.row_limit, 50), 0), 200)
offset greatest(coalesce(list_inventory_movements.row_offset, 0), 0)
) x
$$;
revoke execute on function "better_supabase"."list_inventory_movements"(uuid, uuid, uuid, uuid, uuid, text, text, integer, integer) from public, anon;
grant execute on function "better_supabase"."list_inventory_movements"(uuid, uuid, uuid, uuid, uuid, text, text, integer, integer) to authenticated, service_role;
-- A keyset page of the organization's stock levels, emptiest first (ADR 1077).
-- Row security decides what the caller sees. filters is { status (in_stock,
-- low, out), variantId, locationId (each a value or a list), search (a variant
-- or location id), sort (available, onHand, variantId), direction, facet,
-- count, limit, after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_inventory_levels"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_inventory_levels.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status', 'locationId') then
raise exception 'facet is one of status, locationId' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text when 'locationId' then (x."location_id"::text)::text end) as v
from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('available', 'onHand', 'variantId') then
raise exception 'sort is one of available, onHand, variantId' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."available")::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."available", (x."variant_id"::text || ':' || x."location_id"::text)) > ((v_after ->> 0)::numeric, (v_after ->> 1)::text))
order by x."available" asc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."available")::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."available" <= (v_after ->> 0)::numeric and ((x."available" < (v_after ->> 0)::numeric) or (x."available" = (v_after ->> 0)::numeric and (x."variant_id"::text || ':' || x."location_id"::text) > (v_after ->> 1)::text))))
order by x."available" desc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'available' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."available")::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."available", (x."variant_id"::text || ':' || x."location_id"::text)) > ((v_after ->> 0)::numeric, (v_after ->> 1)::text))
order by x."available" asc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'available' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."available")::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."available" <= (v_after ->> 0)::numeric and ((x."available" < (v_after ->> 0)::numeric) or (x."available" = (v_after ->> 0)::numeric and (x."variant_id"::text || ':' || x."location_id"::text) > (v_after ->> 1)::text))))
order by x."available" desc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'onHand' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."on_hand")::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."on_hand", (x."variant_id"::text || ':' || x."location_id"::text)) > ((v_after ->> 0)::numeric, (v_after ->> 1)::text))
order by x."on_hand" asc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'onHand' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."on_hand")::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."on_hand" <= (v_after ->> 0)::numeric and ((x."on_hand" < (v_after ->> 0)::numeric) or (x."on_hand" = (v_after ->> 0)::numeric and (x."variant_id"::text || ':' || x."location_id"::text) > (v_after ->> 1)::text))))
order by x."on_hand" desc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'variantId' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."variant_id"::text)::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."variant_id"::text, (x."variant_id"::text || ':' || x."location_id"::text)) > ((v_after ->> 0)::text, (v_after ->> 1)::text))
order by x."variant_id"::text asc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'variantId' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) as j, jsonb_build_array((x."variant_id"::text)::text, ((x."variant_id"::text || ':' || x."location_id"::text))::text) as k
from (
select * from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
and (v_after is null or (x."variant_id"::text <= (v_after ->> 0)::text and ((x."variant_id"::text < (v_after ->> 0)::text) or (x."variant_id"::text = (v_after ->> 0)::text and (x."variant_id"::text || ':' || x."location_id"::text) > (v_after ->> 1)::text))))
order by x."variant_id"::text desc, (x."variant_id"::text || ':' || x."location_id"::text) asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."stock_levels" x
where x."tenant_id" = page_inventory_levels.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or (case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end)::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x."variant_id" = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x."variant_id"::text ilike v_search or x."location_id"::text ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_inventory_levels"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_inventory_levels"(uuid, jsonb) to authenticated, service_role;
-- One stock level by id, "variant:location", or INVENTORY_LEVEL_NOT_FOUND when
-- it does not exist or row security hides it.
create or replace function "better_supabase"."get_inventory_level"(level_id text)
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
declare
v_row jsonb;
begin
select jsonb_build_object(
'id', x."variant_id"::text || ':' || x."location_id"::text,
'variantId', x."variant_id",
'locationId', x."location_id",
'onHand', x."on_hand"::text,
'allocated', x."reserved"::text,
'available', x."available"::text,
'incoming', x."incoming"::text,
'reorderPoint', x."reorder_point"::text,
'status', case when x."available" <= 0 then 'out' when x."reorder_point" is not null and x."available" <= x."reorder_point" then 'low' else 'in_stock' end) into v_row
from "better_supabase"."stock_levels" x
where x."variant_id"::text || ':' || x."location_id"::text = get_inventory_level.level_id;
if v_row is null then
raise exception 'no such stock level' using errcode = 'P0002', hint = 'INVENTORY_LEVEL_NOT_FOUND';
end if;
return v_row;
end;
$$;
revoke execute on function "better_supabase"."get_inventory_level"(text) from public, anon;
grant execute on function "better_supabase"."get_inventory_level"(text) to authenticated, service_role;
-- A keyset page of the ledger's stock movements, newest first (ADR 1077). Row
-- security decides what the caller sees. filters is { kind, variantId,
-- productId, locationId, binId, lotId, documentType, documentId (each a value
-- or a list), search (the kind or the document id), sort (effectiveAt,
-- quantity), direction, facet, count, limit, after, offset, paged, total,
-- totalCap }.
create or replace function "better_supabase"."page_inventory_movements"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_inventory_movements.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('kind', 'locationId') then
raise exception 'facet is one of kind, locationId' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
with s as (
select (case v_facet when 'kind' then (x."kind")::text when 'locationId' then (x."metadata" ->> 'locationId')::text end) as v
from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('effectiveAt', 'quantity') then
raise exception 'sort is one of effectiveAt, quantity' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") as j, jsonb_build_array((x."effective_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
and (v_after is null or (x."effective_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."effective_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") as j, jsonb_build_array((x."effective_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
and (v_after is null or (x."effective_at" <= (v_after ->> 0)::timestamptz and ((x."effective_at" < (v_after ->> 0)::timestamptz) or (x."effective_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."effective_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'effectiveAt' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") as j, jsonb_build_array((x."effective_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
and (v_after is null or (x."effective_at", x."id") > ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."effective_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'effectiveAt' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") as j, jsonb_build_array((x."effective_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
and (v_after is null or (x."effective_at" <= (v_after ->> 0)::timestamptz and ((x."effective_at" < (v_after ->> 0)::timestamptz) or (x."effective_at" = (v_after ->> 0)::timestamptz and x."id" > (v_after ->> 1)::uuid))))
order by x."effective_at" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'quantity' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") as j, jsonb_build_array((abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)))::text, (x."id")::text) as k
from (
select * from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
and (v_after is null or (abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)), x."id") > ((v_after ->> 0)::numeric, (v_after ->> 1)::uuid))
order by abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)) asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'quantity' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") as j, jsonb_build_array((abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)))::text, (x."id")::text) as k
from (
select * from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
and (v_after is null or (abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)) <= (v_after ->> 0)::numeric and ((abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)) < (v_after ->> 0)::numeric) or (abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)) = (v_after ->> 0)::numeric and x."id" > (v_after ->> 1)::uuid))))
order by abs(coalesce((x."metadata" ->> 'quantity')::numeric, 0)) desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."ledger_transactions" x
where x."tenant_id" = page_inventory_movements.tenant
and x."kind" like 'stock.%'
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or (x."metadata" ->> 'variantId')::text = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::text[]))
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (x."metadata" ->> 'variantId')::uuid in (select v."id" from "better_supabase"."product_variants" v where (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or (v."product_id")::text = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::text[]))))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or (x."metadata" ->> 'locationId')::text = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::text[]))
and (not (v_filters -> 'binId' is not null and jsonb_typeof(v_filters -> 'binId') <> 'null' and not (jsonb_typeof(v_filters -> 'binId') = 'array' and jsonb_array_length(v_filters -> 'binId') = 0)) or (x."metadata" ->> 'binId')::text = any((case when jsonb_typeof(v_filters -> 'binId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'binId')) else array[v_filters ->> 'binId'] end)::text[]))
and (not (v_filters -> 'lotId' is not null and jsonb_typeof(v_filters -> 'lotId') <> 'null' and not (jsonb_typeof(v_filters -> 'lotId') = 'array' and jsonb_array_length(v_filters -> 'lotId') = 0)) or (x."metadata" ->> 'lotId')::text = any((case when jsonb_typeof(v_filters -> 'lotId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'lotId')) else array[v_filters ->> 'lotId'] end)::text[]))
and (not (v_filters -> 'documentType' is not null and jsonb_typeof(v_filters -> 'documentType') <> 'null' and not (jsonb_typeof(v_filters -> 'documentType') = 'array' and jsonb_array_length(v_filters -> 'documentType') = 0)) or (x."reference_type")::text = any((case when jsonb_typeof(v_filters -> 'documentType') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentType')) else array[v_filters ->> 'documentType'] end)::text[]))
and (not (v_filters -> 'documentId' is not null and jsonb_typeof(v_filters -> 'documentId') <> 'null' and not (jsonb_typeof(v_filters -> 'documentId') = 'array' and jsonb_array_length(v_filters -> 'documentId') = 0)) or (x."reference_id")::text = any((case when jsonb_typeof(v_filters -> 'documentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'documentId')) else array[v_filters ->> 'documentId'] end)::text[]))
and (v_search is null or x."kind" ilike v_search or x."reference_id" ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_inventory_movements"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_inventory_movements"(uuid, jsonb) to authenticated, service_role;
-- One stock movement by id, or INVENTORY_MOVEMENT_NOT_FOUND when it does not
-- exist or row security hides it.
create or replace function "better_supabase"."get_inventory_movement"(movement_id uuid)
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
declare
v_row jsonb;
begin
select jsonb_build_object(
'id', x."id",
'kind', x."kind",
'variantId', x."metadata" ->> 'variantId',
'productId', (select v."product_id" from "better_supabase"."product_variants" v where v."id" = (x."metadata" ->> 'variantId')::uuid),
'locationId', x."metadata" ->> 'locationId',
'binId', x."metadata" ->> 'binId',
'lotId', x."metadata" ->> 'lotId',
'quantity', x."metadata" ->> 'quantity',
'unit', x."metadata" ->> 'unit',
'reason', x."metadata" ->> 'reason',
'note', x."memo",
'actorId', x."actor_id",
'documentType', x."reference_type",
'documentId', x."reference_id",
'effectiveAt', x."effective_at") into v_row
from "better_supabase"."ledger_transactions" x
where x."id" = get_inventory_movement.movement_id
and x."kind" like 'stock.%';
if v_row is null then
raise exception 'no such stock movement' using errcode = 'P0002', hint = 'INVENTORY_MOVEMENT_NOT_FOUND';
end if;
return v_row;
end;
$$;
revoke execute on function "better_supabase"."get_inventory_movement"(uuid) from public, anon;
grant execute on function "better_supabase"."get_inventory_movement"(uuid) to authenticated, service_role;
-- A keyset page of the lots that hold stock, one row per lot, location and
-- bin, soonest expiry first (ADR 1077). Needs inventory.read. filters is
-- { expiry (expired, soon, later, none), variantId, locationId (each a value
-- or a list), search (the lot code), sort (expiresOn, onHand, code),
-- direction, facet, count, limit, after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_inventory_lots"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_inventory_lots.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', page_inventory_lots.tenant, 'inventory.read'), false)) then
raise exception 'not allowed to read this inventory' using errcode = '42501', hint = 'INVENTORY_FORBIDDEN';
end if;
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('expiry', 'locationId') then
raise exception 'facet is one of expiry, locationId' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
with s as (
select (case v_facet when 'expiry' then (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text when 'locationId' then (x."location_id"::text)::text end) as v
from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('expiresOn', 'onHand', 'code') then
raise exception 'sort is one of expiresOn, onHand, code' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((coalesce(x.lot_expires_on, date '9999-12-31'))::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (coalesce(x.lot_expires_on, date '9999-12-31'), (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''))) > ((v_after ->> 0)::date, (v_after ->> 1)::text))
order by coalesce(x.lot_expires_on, date '9999-12-31') asc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((coalesce(x.lot_expires_on, date '9999-12-31'))::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (coalesce(x.lot_expires_on, date '9999-12-31') <= (v_after ->> 0)::date and ((coalesce(x.lot_expires_on, date '9999-12-31') < (v_after ->> 0)::date) or (coalesce(x.lot_expires_on, date '9999-12-31') = (v_after ->> 0)::date and (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) > (v_after ->> 1)::text))))
order by coalesce(x.lot_expires_on, date '9999-12-31') desc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'expiresOn' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((coalesce(x.lot_expires_on, date '9999-12-31'))::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (coalesce(x.lot_expires_on, date '9999-12-31'), (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''))) > ((v_after ->> 0)::date, (v_after ->> 1)::text))
order by coalesce(x.lot_expires_on, date '9999-12-31') asc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'expiresOn' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((coalesce(x.lot_expires_on, date '9999-12-31'))::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (coalesce(x.lot_expires_on, date '9999-12-31') <= (v_after ->> 0)::date and ((coalesce(x.lot_expires_on, date '9999-12-31') < (v_after ->> 0)::date) or (coalesce(x.lot_expires_on, date '9999-12-31') = (v_after ->> 0)::date and (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) > (v_after ->> 1)::text))))
order by coalesce(x.lot_expires_on, date '9999-12-31') desc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'onHand' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((x."on_hand")::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (x."on_hand", (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''))) > ((v_after ->> 0)::numeric, (v_after ->> 1)::text))
order by x."on_hand" asc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'onHand' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((x."on_hand")::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (x."on_hand" <= (v_after ->> 0)::numeric and ((x."on_hand" < (v_after ->> 0)::numeric) or (x."on_hand" = (v_after ->> 0)::numeric and (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) > (v_after ->> 1)::text))))
order by x."on_hand" desc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'code' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((lower(x.lot_code))::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (lower(x.lot_code), (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''))) > ((v_after ->> 0)::text, (v_after ->> 1)::text))
order by lower(x.lot_code) asc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'code' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) as j, jsonb_build_array((lower(x.lot_code))::text, ((x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')))::text) as k
from (
select * from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
and (v_after is null or (lower(x.lot_code) <= (v_after ->> 0)::text and ((lower(x.lot_code) < (v_after ->> 0)::text) or (lower(x.lot_code) = (v_after ->> 0)::text and (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) > (v_after ->> 1)::text))))
order by lower(x.lot_code) desc, (x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '')) asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x."tenant_id" = page_inventory_lots.tenant
and (not (v_filters -> 'expiry' is not null and jsonb_typeof(v_filters -> 'expiry') <> 'null' and not (jsonb_typeof(v_filters -> 'expiry') = 'array' and jsonb_array_length(v_filters -> 'expiry') = 0)) or (case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end)::text = any((case when jsonb_typeof(v_filters -> 'expiry') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'expiry')) else array[v_filters ->> 'expiry'] end)::text[]))
and (not (v_filters -> 'variantId' is not null and jsonb_typeof(v_filters -> 'variantId') <> 'null' and not (jsonb_typeof(v_filters -> 'variantId') = 'array' and jsonb_array_length(v_filters -> 'variantId') = 0)) or x.lot_variant = any((case when jsonb_typeof(v_filters -> 'variantId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'variantId')) else array[v_filters ->> 'variantId'] end)::uuid[]))
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (v_search is null or x.lot_code ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_inventory_lots"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_inventory_lots"(uuid, jsonb) to authenticated, service_role;
-- One lot's stock by id, "lot:location:bin" (the bin may be empty), or
-- INVENTORY_LOT_NOT_FOUND when it does not exist or the caller cannot read it.
create or replace function "better_supabase"."get_inventory_lot"(lot_id text)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row jsonb;
v_tenant uuid;
begin
select x."tenant_id", jsonb_build_object('id', x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, ''), 'lotId', x.lot_pk, 'code', x.lot_code, 'variantId', x.lot_variant, 'locationId', x."location_id", 'binId', x."bin_id", 'expiresOn', x.lot_expires_on, 'onHand', x."on_hand"::text, 'expiry', case when x.lot_expires_on is null then 'none' when x.lot_expires_on < current_date then 'expired' when x.lot_expires_on <= current_date + 30 then 'soon' else 'later' end) into v_tenant, v_row
from (select y.*, lo."id" as lot_pk, lo."code" as lot_code, lo."variant_id" as lot_variant, lo."expires_on" as lot_expires_on from "better_supabase"."stock_buckets" y join "better_supabase"."stock_lots" lo on lo."id" = y."lot_id" where y."on_hand" > 0) x
where x.lot_pk::text || ':' || x."location_id"::text || ':' || coalesce(x."bin_id"::text, '') = get_inventory_lot.lot_id;
if v_row is null or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_tenant, 'inventory.read'), false)) then
raise exception 'no such lot with stock' using errcode = 'P0002', hint = 'INVENTORY_LOT_NOT_FOUND';
end if;
return v_row;
end;
$$;
revoke execute on function "better_supabase"."get_inventory_lot"(text) from public, anon;
grant execute on function "better_supabase"."get_inventory_lot"(text) to authenticated, service_role;
-- A keyset page of the stock locations, by code (ADR 1077). Row security decides what the caller sees. filters is
-- { kind (warehouse, store, virtual), active (true, false), each a value or a list; search (the code or name); sort (code, name), search, sort, direction, facet, count, limit, after, offset,
-- paged, total, totalCap }.
create or replace function "better_supabase"."page_stock_locations"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_stock_locations.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('kind', 'active') then
raise exception 'facet is one of kind, active' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
with s as (
select (case v_facet when 'kind' then (x."kind")::text when 'active' then (x."active"::text)::text end) as v
from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('code', 'name') then
raise exception 'sort is one of code, name' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'code', x."code", 'name', x."name", 'kind', x."kind", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
and (v_after is null or (x."code", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."code" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'code', x."code", 'name', x."name", 'kind', x."kind", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
and (v_after is null or (x."code" <= (v_after ->> 0)::text and ((x."code" < (v_after ->> 0)::text) or (x."code" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."code" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'code' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'code', x."code", 'name', x."name", 'kind', x."kind", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
and (v_after is null or (x."code", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."code" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'code' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'code', x."code", 'name', x."name", 'kind', x."kind", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
and (v_after is null or (x."code" <= (v_after ->> 0)::text and ((x."code" < (v_after ->> 0)::text) or (x."code" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."code" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'name' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'code', x."code", 'name', x."name", 'kind', x."kind", 'active', x."active") as j, jsonb_build_array((x."name")::text, (x."id")::text) as k
from (
select * from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
and (v_after is null or (x."name", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."name" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'name' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'code', x."code", 'name', x."name", 'kind', x."kind", 'active', x."active") as j, jsonb_build_array((x."name")::text, (x."id")::text) as k
from (
select * from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
and (v_after is null or (x."name" <= (v_after ->> 0)::text and ((x."name" < (v_after ->> 0)::text) or (x."name" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."name" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."inventory_locations" x
where x."tenant_id" = page_stock_locations.tenant
and (not (v_filters -> 'kind' is not null and jsonb_typeof(v_filters -> 'kind') <> 'null' and not (jsonb_typeof(v_filters -> 'kind') = 'array' and jsonb_array_length(v_filters -> 'kind') = 0)) or (x."kind")::text = any((case when jsonb_typeof(v_filters -> 'kind') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'kind')) else array[v_filters ->> 'kind'] end)::text[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (v_search is null or x."code" ilike v_search or x."name" ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_stock_locations"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_stock_locations"(uuid, jsonb) to authenticated, service_role;
-- A keyset page of the bins, by code (ADR 1077). Row security decides what the caller sees. filters is
-- { locationId, active, hold, each a value or a list; search (the code or name); sort (code), search, sort, direction, facet, count, limit, after, offset,
-- paged, total, totalCap }.
create or replace function "better_supabase"."page_stock_bins"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_stock_bins.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('locationId', 'active') then
raise exception 'facet is one of locationId, active' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
with s as (
select (case v_facet when 'locationId' then (x."location_id"::text)::text when 'active' then (x."active"::text)::text end) as v
from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('code') then
raise exception 'sort is one of code' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'locationId', x."location_id", 'code', x."code", 'name', x."name", 'hold', x."hold", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
and (v_after is null or (x."code", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."code" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'locationId', x."location_id", 'code', x."code", 'name', x."name", 'hold', x."hold", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
and (v_after is null or (x."code" <= (v_after ->> 0)::text and ((x."code" < (v_after ->> 0)::text) or (x."code" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."code" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'code' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'locationId', x."location_id", 'code', x."code", 'name', x."name", 'hold', x."hold", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
and (v_after is null or (x."code", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."code" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'code' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'locationId', x."location_id", 'code', x."code", 'name', x."name", 'hold', x."hold", 'active', x."active") as j, jsonb_build_array((x."code")::text, (x."id")::text) as k
from (
select * from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
and (v_after is null or (x."code" <= (v_after ->> 0)::text and ((x."code" < (v_after ->> 0)::text) or (x."code" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."code" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."stock_bins" x
where x."tenant_id" = page_stock_bins.tenant
and (not (v_filters -> 'locationId' is not null and jsonb_typeof(v_filters -> 'locationId') <> 'null' and not (jsonb_typeof(v_filters -> 'locationId') = 'array' and jsonb_array_length(v_filters -> 'locationId') = 0)) or x."location_id" = any((case when jsonb_typeof(v_filters -> 'locationId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'locationId')) else array[v_filters ->> 'locationId'] end)::uuid[]))
and (not (v_filters -> 'active' is not null and jsonb_typeof(v_filters -> 'active') <> 'null' and not (jsonb_typeof(v_filters -> 'active') = 'array' and jsonb_array_length(v_filters -> 'active') = 0)) or x."active"::text = any((case when jsonb_typeof(v_filters -> 'active') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'active')) else array[v_filters ->> 'active'] end)::text[]))
and (not (v_filters -> 'hold' is not null and jsonb_typeof(v_filters -> 'hold') <> 'null' and not (jsonb_typeof(v_filters -> 'hold') = 'array' and jsonb_array_length(v_filters -> 'hold') = 0)) or x."hold"::text = any((case when jsonb_typeof(v_filters -> 'hold') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'hold')) else array[v_filters ->> 'hold'] end)::text[]))
and (v_search is null or x."code" ilike v_search or coalesce(x."name", '') ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_stock_bins"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_stock_bins"(uuid, jsonb) to authenticated, service_role;
-- A keyset page of the catalog variants stock is kept for, by SKU (ADR 1077). Row security decides what the caller sees. filters is
-- { productId (a value or a list); search (the SKU or title); sort (sku, title), search, sort, direction, facet, count, limit, after, offset,
-- paged, total, totalCap }.
create or replace function "better_supabase"."page_stock_variants"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_stock_variants.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('sku', 'title') then
raise exception 'sort is one of sku, title' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'productId', x."product_id", 'sku', x."sku", 'title', x."title") as j, jsonb_build_array((x."sku")::text, (x."id")::text) as k
from (
select * from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
and (v_after is null or (x."sku", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."sku" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'productId', x."product_id", 'sku', x."sku", 'title', x."title") as j, jsonb_build_array((x."sku")::text, (x."id")::text) as k
from (
select * from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
and (v_after is null or (x."sku" <= (v_after ->> 0)::text and ((x."sku" < (v_after ->> 0)::text) or (x."sku" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."sku" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'sku' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'productId', x."product_id", 'sku', x."sku", 'title', x."title") as j, jsonb_build_array((x."sku")::text, (x."id")::text) as k
from (
select * from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
and (v_after is null or (x."sku", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."sku" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'sku' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'productId', x."product_id", 'sku', x."sku", 'title', x."title") as j, jsonb_build_array((x."sku")::text, (x."id")::text) as k
from (
select * from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
and (v_after is null or (x."sku" <= (v_after ->> 0)::text and ((x."sku" < (v_after ->> 0)::text) or (x."sku" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."sku" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'title' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'productId', x."product_id", 'sku', x."sku", 'title', x."title") as j, jsonb_build_array((x."title")::text, (x."id")::text) as k
from (
select * from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
and (v_after is null or (x."title", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."title" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'title' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'INVENTORY_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'productId', x."product_id", 'sku', x."sku", 'title', x."title") as j, jsonb_build_array((x."title")::text, (x."id")::text) as k
from (
select * from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
and (v_after is null or (x."title" <= (v_after ->> 0)::text and ((x."title" < (v_after ->> 0)::text) or (x."title" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."title" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."product_variants" x
where x."tenant_id" = page_stock_variants.tenant
and (not (v_filters -> 'productId' is not null and jsonb_typeof(v_filters -> 'productId') <> 'null' and not (jsonb_typeof(v_filters -> 'productId') = 'array' and jsonb_array_length(v_filters -> 'productId') = 0)) or x."product_id" = any((case when jsonb_typeof(v_filters -> 'productId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'productId')) else array[v_filters ->> 'productId'] end)::uuid[]))
and (v_search is null or x."sku" ilike v_search or coalesce(x."title", '') ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_stock_variants"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_stock_variants"(uuid, jsonb) to authenticated, service_role;
-- Tenant isolation (ADR 0099): permissive policies combine with or, so one
-- the app adds would widen the block's. These restrictive policies keep each
-- table to the caller's organizations and what the block's policies grant.
create policy bsb_tenant_scope_select on "better_supabase"."inventory_locations" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."inventory_locations" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."inventory_locations" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."inventory_locations" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_levels" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_levels" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_levels" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_levels" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_reservations" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_reservations" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_reservations" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_reservations" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_transfers" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_transfers" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_transfers" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_transfers" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_transfer_lines" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_transfer_lines" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_transfer_lines" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_transfer_lines" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."purchase_orders" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."purchase_orders" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."purchase_orders" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."purchase_orders" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."purchase_order_lines" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."purchase_order_lines" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."purchase_order_lines" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."purchase_order_lines" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."purchase_order_tax_lines" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."purchase_order_tax_lines" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."purchase_order_tax_lines" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."purchase_order_tax_lines" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."purchase_requisitions" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."purchase_requisitions" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."purchase_requisitions" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."purchase_requisitions" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."purchase_requisition_lines" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."purchase_requisition_lines" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."purchase_requisition_lines" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."purchase_requisition_lines" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."inventory_receipts" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."inventory_receipts" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."inventory_receipts" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."inventory_receipts" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."inventory_receipt_lines" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."inventory_receipt_lines" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."inventory_receipt_lines" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."inventory_receipt_lines" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_items" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_items" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_items" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_items" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_bins" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_bins" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_bins" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_bins" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_lots" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_lots" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_lots" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_lots" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_serials" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_serials" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_serials" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_serials" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_buckets" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_buckets" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_buckets" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_buckets" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_allocations" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_allocations" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_allocations" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_allocations" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_counts" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_counts" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_counts" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_counts" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."stock_count_lines" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('inventory.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."stock_count_lines" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."stock_count_lines" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."stock_count_lines" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
Client
This block has no React entry yet. Its TypeScript side is in better-supabase/blocks/inventory, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- allocation.created
- allocation.filled
- allocation.released
- allocation.transferred
- inventory_receipt.created
- purchase_order.cancelled
- purchase_order.line_cancelled
- purchase_order.placed
- purchase_order.received
- purchase_requisition.approved
- purchase_requisition.created
- reservation.committed
- reservation.created
- reservation.released
- stock.adjusted
- stock.reorder_point_reached
- transfer.cancelled
- transfer.received
- transfer.shipped
Dependencies
- Required: the install command adds it too
- Works with: optional
Recipes
More in Billing & commerce
Stripe entitlementsentitlements Active Stripe entitlements per tenant from the Stripe Sync Engine, feature_claims() for the access token hook, and has_entitlement() and tenant_ids_with_entitlement() for RLS.React hooks Usage metering and quotasusage Usage counters per tenant, meter and day with idempotent increments, quotas per tenant or plan, within_quota() for policies and consume_quota(), which raises quota_exceeded. unreported_usage() feeds reportUsageToStripe.React hooks Stripe billingbilling Each tenant's Stripe customer, seat counts (options.seatRoles) and the active subscription item from the Stripe Sync Engine, for createBilling(): checkout, the customer portal, seat sync and Stripe webhook handling.React hooks Catalogcatalog Products with options, variants and prices in minor units, price lists, a category tree, collections, sales channels, translations per locale, product media and an optional public storefront. Ordersorders Carts on anonymous or signed-in users, checkout priced from the catalog, confirmed orders from lines or an accepted quote with stock allocations, gapless order and invoice numbers, payments, fulfillments, returns and refunds, with an optional kitchen display. With invoices, a paid order gets an issued, paid invoice. Promotionspromotions Percentage, fixed and free-shipping promotions, automatic or by code, with usage limits and stacking rules, priced into orders carts.