Catalog
catalogProducts 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.
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, the modules it needs.
npx better-supabase add catalogConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by catalog; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
// Modes: "managed", "custom". The default is "managed".
catalog: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add catalog writes into your declarative schema with the default layout.9 files
supabase/schemas/900_better_supabase_069_catalog.sqlschema3984 lines-- better-supabase module: catalog
-- @bsb-block catalog@6 managed
-- @bsb-hash sha256:ae6151d88f831540dadc2c06e566380d5b047248c46c65faedcdf7502e6aa365
-- 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.
-- 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.
-- Products with options, variants and prices in minor units, plus
-- categories, collections, price lists, sales channels, translations,
-- product media and an optional public storefront.
create or replace function "better_supabase"."currency_minor_units"(code text)
returns integer
language sql
immutable
parallel safe
set search_path = ''
as $$
select c.units from (values ('AED', 2), ('AFN', 2), ('ALL', 2), ('AMD', 2), ('AOA', 2), ('ARS', 2), ('AUD', 2), ('AWG', 2), ('AZN', 2), ('BAM', 2), ('BBD', 2), ('BDT', 2), ('BHD', 3), ('BIF', 0), ('BMD', 2), ('BND', 2), ('BOB', 2), ('BOV', 2), ('BRL', 2), ('BSD', 2), ('BTN', 2), ('BWP', 2), ('BYN', 2), ('BZD', 2), ('CAD', 2), ('CDF', 2), ('CHE', 2), ('CHF', 2), ('CHW', 2), ('CLF', 4), ('CLP', 0), ('CNY', 2), ('COP', 2), ('COU', 2), ('CRC', 2), ('CUP', 2), ('CVE', 2), ('CZK', 2), ('DJF', 0), ('DKK', 2), ('DOP', 2), ('DZD', 2), ('EGP', 2), ('ERN', 2), ('ETB', 2), ('EUR', 2), ('FJD', 2), ('FKP', 2), ('GBP', 2), ('GEL', 2), ('GHS', 2), ('GIP', 2), ('GMD', 2), ('GNF', 0), ('GTQ', 2), ('GYD', 2), ('HKD', 2), ('HNL', 2), ('HTG', 2), ('HUF', 2), ('IDR', 2), ('ILS', 2), ('INR', 2), ('IQD', 3), ('IRR', 2), ('ISK', 0), ('JMD', 2), ('JOD', 3), ('JPY', 0), ('KES', 2), ('KGS', 2), ('KHR', 2), ('KMF', 0), ('KPW', 2), ('KRW', 0), ('KWD', 3), ('KYD', 2), ('KZT', 2), ('LAK', 2), ('LBP', 2), ('LKR', 2), ('LRD', 2), ('LSL', 2), ('LYD', 3), ('MAD', 2), ('MDL', 2), ('MGA', 2), ('MKD', 2), ('MMK', 2), ('MNT', 2), ('MOP', 2), ('MRU', 2), ('MUR', 2), ('MVR', 2), ('MWK', 2), ('MXN', 2), ('MXV', 2), ('MYR', 2), ('MZN', 2), ('NAD', 2), ('NGN', 2), ('NIO', 2), ('NOK', 2), ('NPR', 2), ('NZD', 2), ('OMR', 3), ('PAB', 2), ('PEN', 2), ('PGK', 2), ('PHP', 2), ('PKR', 2), ('PLN', 2), ('PYG', 0), ('QAR', 2), ('RON', 2), ('RSD', 2), ('RUB', 2), ('RWF', 0), ('SAR', 2), ('SBD', 2), ('SCR', 2), ('SDG', 2), ('SEK', 2), ('SGD', 2), ('SHP', 2), ('SLE', 2), ('SOS', 2), ('SRD', 2), ('SSP', 2), ('STN', 2), ('SVC', 2), ('SYP', 2), ('SZL', 2), ('THB', 2), ('TJS', 2), ('TMT', 2), ('TND', 3), ('TOP', 2), ('TRY', 2), ('TTD', 2), ('TWD', 2), ('TZS', 2), ('UAH', 2), ('UGX', 0), ('USD', 2), ('USN', 2), ('UYI', 0), ('UYU', 2), ('UYW', 4), ('UZS', 2), ('VED', 2), ('VES', 2), ('VND', 0), ('VUV', 0), ('WST', 2), ('XAD', 2), ('XAF', 0), ('XCD', 2), ('XCG', 2), ('XOF', 0), ('XPF', 0), ('YER', 2), ('ZAR', 2), ('ZMW', 2), ('ZWG', 2)) as c (code, units) where c.code = $1
$$;
grant execute on function "better_supabase"."currency_minor_units"(text) to anon, authenticated, service_role;
create table "better_supabase"."products" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"slug" text not null constraint bsb_products_slug_check check ("slug" ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'),
"title" text not null constraint bsb_products_title_check check (length("title") >= 1 and length("title") <= 500),
"description" text,
"kind" text not null default 'physical' constraint bsb_products_kind_check check ("kind" in ('physical', 'digital', 'service')),
"status" text not null default 'draft',
"manufacturer" text,
"model" text,
"tax_code" text,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "slug")
);
create index products_status_idx on "better_supabase"."products" ("tenant_id", "status");
alter table "better_supabase"."products" enable row level security;
revoke all on "better_supabase"."products" from public, anon, authenticated;
grant select on "better_supabase"."products" to authenticated;
grant all on "better_supabase"."products" to service_role;
create policy bsb_products_read on "better_supabase"."products"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_options" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"product_id" uuid not null references "better_supabase"."products" ("id") on delete cascade,
"name" text not null constraint bsb_product_options_name_check check (length("name") >= 1 and length("name") <= 80),
"rank" text collate "C" not null default 'V',
unique ("product_id", "name")
);
alter table "better_supabase"."product_options" enable row level security;
revoke all on "better_supabase"."product_options" from public, anon, authenticated;
grant select on "better_supabase"."product_options" to authenticated;
grant all on "better_supabase"."product_options" to service_role;
create policy bsb_product_options_read on "better_supabase"."product_options"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_option_values" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"option_id" uuid not null references "better_supabase"."product_options" ("id") on delete cascade,
"value" text not null constraint bsb_product_option_values_value_check check (length("value") >= 1 and length("value") <= 80),
"rank" text collate "C" not null default 'V',
unique ("option_id", "value")
);
alter table "better_supabase"."product_option_values" enable row level security;
revoke all on "better_supabase"."product_option_values" from public, anon, authenticated;
grant select on "better_supabase"."product_option_values" to authenticated;
grant all on "better_supabase"."product_option_values" to service_role;
create policy bsb_product_option_values_read on "better_supabase"."product_option_values"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_variants" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"product_id" uuid not null references "better_supabase"."products" ("id") on delete cascade,
"sku" text not null constraint bsb_product_variants_sku_check check (length("sku") >= 1 and length("sku") <= 100),
"title" text,
"barcode" text,
"weight_grams" integer constraint bsb_product_variants_weight_grams_check check ("weight_grams" >= 0),
"track_inventory" boolean not null default true,
"allow_backorder" boolean not null default false,
"rank" text collate "C" not null default 'V',
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "sku")
);
create index product_variants_product_idx on "better_supabase"."product_variants" ("product_id");
alter table "better_supabase"."product_variants" enable row level security;
revoke all on "better_supabase"."product_variants" from public, anon, authenticated;
grant select on "better_supabase"."product_variants" to authenticated;
grant all on "better_supabase"."product_variants" to service_role;
create policy bsb_product_variants_read on "better_supabase"."product_variants"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_variant_values" (
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"option_value_id" uuid not null references "better_supabase"."product_option_values" ("id"),
primary key ("variant_id", "option_value_id")
);
create index product_variant_values_value_idx on "better_supabase"."product_variant_values" ("option_value_id");
alter table "better_supabase"."product_variant_values" enable row level security;
revoke all on "better_supabase"."product_variant_values" from public, anon, authenticated;
grant select on "better_supabase"."product_variant_values" to authenticated;
grant all on "better_supabase"."product_variant_values" to service_role;
create policy bsb_product_variant_values_read on "better_supabase"."product_variant_values"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."catalog_price_lists" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"name" text not null constraint bsb_catalog_price_lists_name_check check (length("name") >= 1 and length("name") <= 200),
"customer_group" text,
"created_at" timestamptz not null default now(),
unique ("tenant_id", "name")
);
alter table "better_supabase"."catalog_price_lists" enable row level security;
revoke all on "better_supabase"."catalog_price_lists" from public, anon, authenticated;
grant select on "better_supabase"."catalog_price_lists" to authenticated;
grant all on "better_supabase"."catalog_price_lists" to service_role;
create policy bsb_catalog_price_lists_read on "better_supabase"."catalog_price_lists"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_prices" (
"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,
"price_list_id" uuid references "better_supabase"."catalog_price_lists" ("id") on delete cascade,
"currency" char(3) not null constraint bsb_product_prices_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"amount" bigint not null constraint bsb_product_prices_amount_check check ("amount" >= 0),
"compare_at_amount" bigint constraint bsb_product_prices_check check ("compare_at_amount" > "amount"),
"starts_at" timestamptz,
"expires_at" timestamptz constraint bsb_product_prices_check1 check ("expires_at" > "starts_at"),
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now()
);
create index product_prices_variant_idx on "better_supabase"."product_prices" ("variant_id", "currency");
create index product_prices_price_list_idx on "better_supabase"."product_prices" ("price_list_id");
alter table "better_supabase"."product_prices" enable row level security;
revoke all on "better_supabase"."product_prices" from public, anon, authenticated;
grant select on "better_supabase"."product_prices" to authenticated;
grant all on "better_supabase"."product_prices" to service_role;
create policy bsb_product_prices_read on "better_supabase"."product_prices"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."catalog_categories" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"parent_id" uuid references "better_supabase"."catalog_categories" ("id"),
"name" text not null constraint bsb_catalog_categories_name_check check (length("name") >= 1 and length("name") <= 200),
"slug" text not null constraint bsb_catalog_categories_slug_check check ("slug" ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'),
"description" text,
"rank" text collate "C" not null default 'V',
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "slug")
);
create index "catalog_categories_parent_idx" on "better_supabase"."catalog_categories" ("parent_id");
alter table "better_supabase"."catalog_categories" enable row level security;
revoke all on "better_supabase"."catalog_categories" from public, anon, authenticated;
grant select on "better_supabase"."catalog_categories" to authenticated;
grant all on "better_supabase"."catalog_categories" to service_role;
create policy bsb_catalog_categories_read on "better_supabase"."catalog_categories"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_categories" (
"tenant_id" uuid not null,
"product_id" uuid not null references "better_supabase"."products" ("id") on delete cascade,
"category_id" uuid not null references "better_supabase"."catalog_categories" ("id") on delete cascade,
primary key ("product_id", "category_id")
);
create index product_categories_category_idx on "better_supabase"."product_categories" ("category_id");
alter table "better_supabase"."product_categories" enable row level security;
revoke all on "better_supabase"."product_categories" from public, anon, authenticated;
grant select on "better_supabase"."product_categories" to authenticated;
grant all on "better_supabase"."product_categories" to service_role;
create policy bsb_product_categories_read on "better_supabase"."product_categories"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_collections" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"title" text not null constraint bsb_product_collections_title_check check (length("title") >= 1 and length("title") <= 200),
"slug" text not null constraint bsb_product_collections_slug_check check ("slug" ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'),
"kind" text not null default 'manual' constraint bsb_product_collections_kind_check check ("kind" in ('manual', 'rule')),
"rule" jsonb,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "slug"),
constraint bsb_product_collections_check check (("kind" = 'rule') = ("rule" is not null))
);
alter table "better_supabase"."product_collections" enable row level security;
revoke all on "better_supabase"."product_collections" from public, anon, authenticated;
grant select on "better_supabase"."product_collections" to authenticated;
grant all on "better_supabase"."product_collections" to service_role;
create policy bsb_product_collections_read on "better_supabase"."product_collections"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."collection_products" (
"tenant_id" uuid not null,
"collection_id" uuid not null references "better_supabase"."product_collections" ("id") on delete cascade,
"product_id" uuid not null references "better_supabase"."products" ("id") on delete cascade,
"rank" text collate "C" not null default 'V',
primary key ("collection_id", "product_id")
);
create index collection_products_product_idx on "better_supabase"."collection_products" ("product_id");
alter table "better_supabase"."collection_products" enable row level security;
revoke all on "better_supabase"."collection_products" from public, anon, authenticated;
grant select on "better_supabase"."collection_products" to authenticated;
grant all on "better_supabase"."collection_products" to service_role;
create policy bsb_collection_products_read on "better_supabase"."collection_products"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."catalog_storefronts" (
"tenant_id" uuid primary key,
"published_at" timestamptz
);
alter table "better_supabase"."catalog_storefronts" enable row level security;
revoke all on "better_supabase"."catalog_storefronts" from public, anon, authenticated;
grant select on "better_supabase"."catalog_storefronts" to authenticated;
grant all on "better_supabase"."catalog_storefronts" to service_role;
create policy bsb_catalog_storefronts_read on "better_supabase"."catalog_storefronts"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."catalog_channels" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"key" text not null constraint bsb_catalog_channels_key_check check ("key" ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'),
"name" text not null constraint bsb_catalog_channels_name_check check (length("name") >= 1 and length("name") <= 200),
"currency" char(3) constraint bsb_catalog_channels_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"price_list_id" uuid references "better_supabase"."catalog_price_lists" ("id") on delete set null,
"active" boolean not null default true,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "key")
);
create index catalog_channels_price_list_idx on "better_supabase"."catalog_channels" ("price_list_id");
alter table "better_supabase"."catalog_channels" enable row level security;
revoke all on "better_supabase"."catalog_channels" from public, anon, authenticated;
grant select on "better_supabase"."catalog_channels" to authenticated;
grant all on "better_supabase"."catalog_channels" to service_role;
create policy bsb_catalog_channels_read on "better_supabase"."catalog_channels"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."catalog_channel_products" (
"tenant_id" uuid not null,
"channel_id" uuid not null references "better_supabase"."catalog_channels" ("id") on delete cascade,
"product_id" uuid not null references "better_supabase"."products" ("id") on delete cascade,
"listed_at" timestamptz not null default now(),
primary key ("channel_id", "product_id")
);
create index catalog_channel_products_product_idx on "better_supabase"."catalog_channel_products" ("product_id");
alter table "better_supabase"."catalog_channel_products" enable row level security;
revoke all on "better_supabase"."catalog_channel_products" from public, anon, authenticated;
grant select on "better_supabase"."catalog_channel_products" to authenticated;
grant all on "better_supabase"."catalog_channel_products" to service_role;
create policy bsb_catalog_channel_products_read on "better_supabase"."catalog_channel_products"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_translations" (
"tenant_id" uuid not null,
"product_id" uuid not null references "better_supabase"."products" ("id") on delete cascade,
"locale" text not null constraint bsb_product_translations_locale_check check ("locale" ~ '^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$'),
"title" text constraint bsb_product_translations_title_check check (length("title") >= 1 and length("title") <= 500),
"description" text,
"updated_at" timestamptz not null default now(),
primary key ("product_id", "locale")
);
alter table "better_supabase"."product_translations" enable row level security;
revoke all on "better_supabase"."product_translations" from public, anon, authenticated;
grant select on "better_supabase"."product_translations" to authenticated;
grant all on "better_supabase"."product_translations" to service_role;
create policy bsb_product_translations_read on "better_supabase"."product_translations"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_variant_translations" (
"tenant_id" uuid not null,
"variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"locale" text not null constraint bsb_product_variant_translations_locale_check check ("locale" ~ '^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$'),
"title" text constraint bsb_product_variant_translations_title_check check (length("title") >= 1 and length("title") <= 500),
"updated_at" timestamptz not null default now(),
primary key ("variant_id", "locale")
);
alter table "better_supabase"."product_variant_translations" enable row level security;
revoke all on "better_supabase"."product_variant_translations" from public, anon, authenticated;
grant select on "better_supabase"."product_variant_translations" to authenticated;
grant all on "better_supabase"."product_variant_translations" to service_role;
create policy bsb_product_variant_translations_read on "better_supabase"."product_variant_translations"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
create table "better_supabase"."product_identifiers" (
"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,
"type" text not null constraint bsb_product_identifiers_type_check check ("type" in ('ean', 'supplier', 'manufacturer', 'other')),
"value" text not null constraint bsb_product_identifiers_value_check check (length("value") >= 1 and length("value") <= 100),
-- The supplier or manufacturer the code belongs to; a soft reference, so the
-- contacts block stays optional.
"party_id" uuid,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now()
);
create unique index product_identifiers_key on "better_supabase"."product_identifiers" ("variant_id", "type", "value", coalesce("party_id", '00000000-0000-0000-0000-000000000000'::uuid));
create index product_identifiers_lookup_idx on "better_supabase"."product_identifiers" ("tenant_id", "type", "value");
alter table "better_supabase"."product_identifiers" enable row level security;
revoke all on "better_supabase"."product_identifiers" from public, anon, authenticated;
grant select on "better_supabase"."product_identifiers" to authenticated;
grant all on "better_supabase"."product_identifiers" to service_role;
create policy bsb_product_identifiers_read on "better_supabase"."product_identifiers"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- A relation points from a variant to another: the variant "from" has the
-- alternative, is superseded by the variant "to", or has it as an accessory.
create table "better_supabase"."product_relations" (
"tenant_id" uuid not null,
"from_variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"to_variant_id" uuid not null references "better_supabase"."product_variants" ("id") on delete cascade,
"kind" text not null constraint bsb_product_relations_kind_check check ("kind" in ('alternative', 'superseded_by', 'accessory')),
"created_at" timestamptz not null default now(),
primary key ("from_variant_id", "to_variant_id", "kind"),
constraint bsb_product_relations_check check ("from_variant_id" <> "to_variant_id")
);
create index product_relations_to_idx on "better_supabase"."product_relations" ("to_variant_id", "kind");
alter table "better_supabase"."product_relations" enable row level security;
revoke all on "better_supabase"."product_relations" from public, anon, authenticated;
grant select on "better_supabase"."product_relations" to authenticated;
grant all on "better_supabase"."product_relations" to service_role;
create policy bsb_product_relations_read on "better_supabase"."product_relations"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- What a supplier sells under its own code. A row becomes a catalog variant
-- when it is first used (promote_supplier_item).
create table "better_supabase"."supplier_items" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"supplier_id" uuid not null,
"code" text not null constraint bsb_supplier_items_code_check check (length("code") >= 1 and length("code") <= 100),
"description" text,
"price" bigint constraint bsb_supplier_items_price_check check ("price" >= 0),
"currency" char(3) constraint bsb_supplier_items_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"unit" text,
"keywords_text" text,
"keywords" tsvector generated always as (to_tsvector('simple', "code" || ' ' || coalesce("description", '') || ' ' || coalesce("keywords_text", ''))) stored,
"variant_id" uuid references "better_supabase"."product_variants" ("id") on delete set null,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "supplier_id", "code")
);
create index supplier_items_keywords_idx on "better_supabase"."supplier_items" using gin ("keywords");
create index supplier_items_variant_idx on "better_supabase"."supplier_items" ("variant_id");
alter table "better_supabase"."supplier_items" enable row level security;
revoke all on "better_supabase"."supplier_items" from public, anon, authenticated;
grant select on "better_supabase"."supplier_items" to authenticated;
grant all on "better_supabase"."supplier_items" to service_role;
create policy bsb_supplier_items_read on "better_supabase"."supplier_items"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- Which column of a supplier's price list fills which field: columns maps
-- code, description, price, currency, unit and keywords to source column names
-- (keywords may list several); defaults holds the currency and unit for rows
-- that carry none.
create table "better_supabase"."supplier_item_mappings" (
"tenant_id" uuid not null,
"supplier_id" uuid not null,
"columns" jsonb not null constraint bsb_supplier_item_mappings_columns_check check (jsonb_typeof("columns") = 'object'),
"defaults" jsonb not null default '{}'::jsonb constraint bsb_supplier_item_mappings_defaults_check check (jsonb_typeof("defaults") = 'object'),
"updated_at" timestamptz not null default now(),
primary key ("tenant_id", "supplier_id")
);
alter table "better_supabase"."supplier_item_mappings" enable row level security;
revoke all on "better_supabase"."supplier_item_mappings" from public, anon, authenticated;
grant select on "better_supabase"."supplier_item_mappings" to authenticated;
grant all on "better_supabase"."supplier_item_mappings" to service_role;
create policy bsb_supplier_item_mappings_read on "better_supabase"."supplier_item_mappings"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- Customer groups and product groups. A rule of the matrix pairs one of each.
create table "better_supabase"."discount_groups" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"kind" text not null constraint bsb_discount_groups_kind_check check ("kind" in ('customer', 'product')),
"code" text not null constraint bsb_discount_groups_code_check check (length("code") >= 1 and length("code") <= 50),
"name" text not null constraint bsb_discount_groups_name_check check (length("name") >= 1 and length("name") <= 200),
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "kind", "code")
);
alter table "better_supabase"."discount_groups" enable row level security;
revoke all on "better_supabase"."discount_groups" from public, anon, authenticated;
grant select on "better_supabase"."discount_groups" to authenticated;
grant all on "better_supabase"."discount_groups" to service_role;
create policy bsb_discount_groups_read on "better_supabase"."discount_groups"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- The customers of a customer group; a party is in one group.
create table "better_supabase"."discount_group_parties" (
"tenant_id" uuid not null,
"group_id" uuid not null references "better_supabase"."discount_groups" ("id") on delete cascade,
"party_id" text not null constraint bsb_discount_group_parties_party_id_check check (length("party_id") >= 1 and length("party_id") <= 200),
"created_at" timestamptz not null default now(),
primary key ("tenant_id", "party_id")
);
create index discount_group_parties_group_idx on "better_supabase"."discount_group_parties" ("group_id");
alter table "better_supabase"."discount_group_parties" enable row level security;
revoke all on "better_supabase"."discount_group_parties" from public, anon, authenticated;
grant select on "better_supabase"."discount_group_parties" to authenticated;
grant all on "better_supabase"."discount_group_parties" to service_role;
create policy bsb_discount_group_parties_read on "better_supabase"."discount_group_parties"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- The discount matrix. A rule without a customer group or without a product
-- group applies to every customer or product; a quantity break is another rule
-- with a higher min_quantity. A fixed price replaces the unit amount, in its
-- currency; the discount still applies to it.
create table "better_supabase"."discount_rules" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"customer_group_id" uuid references "better_supabase"."discount_groups" ("id") on delete restrict,
"product_group_id" uuid references "better_supabase"."discount_groups" ("id") on delete restrict,
"valid_from" date,
"valid_to" date,
"min_quantity" numeric(18, 4) not null default 0 constraint bsb_discount_rules_min_quantity_check check ("min_quantity" >= 0),
"discount_bps" integer not null default 0 constraint bsb_discount_rules_discount_bps_check check ("discount_bps" >= 0 and "discount_bps" <= 10000),
"fixed_price" bigint constraint bsb_discount_rules_fixed_price_check check ("fixed_price" >= 0),
"currency" char(3) constraint bsb_discount_rules_currency_check check ("currency" ~ '^[A-Z]{3}$'),
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
constraint bsb_discount_rules_check check ("valid_to" is null or "valid_from" is null or "valid_to" >= "valid_from"),
constraint bsb_discount_rules_check1 check (("fixed_price" is null) = ("currency" is null))
);
create unique index discount_rules_key on "better_supabase"."discount_rules" ("tenant_id", coalesce("customer_group_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("product_group_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("valid_from", date '0001-01-01'), "min_quantity");
create index discount_rules_customer_group_idx on "better_supabase"."discount_rules" ("customer_group_id") where "customer_group_id" is not null;
create index discount_rules_product_group_idx on "better_supabase"."discount_rules" ("product_group_id") where "product_group_id" is not null;
alter table "better_supabase"."discount_rules" enable row level security;
revoke all on "better_supabase"."discount_rules" from public, anon, authenticated;
grant select on "better_supabase"."discount_rules" to authenticated;
grant all on "better_supabase"."discount_rules" to service_role;
create policy bsb_discount_rules_read on "better_supabase"."discount_rules"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('catalog.read')));
-- The Combined Nomenclature code (4 to 10 digits) customs and Intrastat use.
alter table "better_supabase"."product_variants" add column "trade_code" text;
alter table "better_supabase"."product_variants" add constraint bsb_product_variants_trade_code_check check ("trade_code" ~ '^[0-9]{4,10}$');
-- The product group a variant belongs to for the discount matrix.
alter table "better_supabase"."product_variants" add column "discount_group_id" uuid references "better_supabase"."discount_groups" ("id") on delete set null;
create index product_variants_discount_group_idx on "better_supabase"."product_variants" ("discount_group_id") where "discount_group_id" is not null;
-- Creates a product (product null) or updates one. Returns its id, slug and
-- status. On an update a null argument keeps the column and clear names the
-- columns to empty; a cleared slug is derived from the title again.
create or replace function "better_supabase"."upsert_product"(tenant uuid, product uuid, title text, slug text, description text, kind text, clear text[] default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_product.product;
v_title text := upsert_product.title;
v_slug text := nullif(upsert_product.slug, '');
v_status text;
v_created boolean := upsert_product.product is null;
v_defaults 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 v_created then
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', upsert_product.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
else
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', upsert_product.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
end if;
if exists (select 1 from unnest(coalesce(upsert_product.clear, '{}'::text[])) c where c <> all ('{slug,description}'::text[])) then
raise exception 'clear names only slug, description' using errcode = '22023', hint = 'CATALOG_CLEAR_INVALID';
end if;
if not v_created then
select coalesce(v_title, x."title"), case when v_slug is null and not 'slug' = any (coalesce(upsert_product.clear, '{}'::text[])) then x."slug" else v_slug end
into v_title, v_slug
from "better_supabase"."products" x where x."id" = upsert_product.product and x."tenant_id" = upsert_product.tenant;
if not found then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
end if;
v_slug := coalesce(v_slug, trim(both '-' from regexp_replace(lower(v_title), '[^a-z0-9]+', '-', 'g')));
if v_slug is null or v_slug !~ '^[a-z0-9]+(?:-[a-z0-9]+)*$' then
raise exception 'the slug must be lower-case letters, digits and hyphens' using errcode = '22023', hint = 'CATALOG_SLUG_INVALID';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_product_save"(uuid, uuid, text, text, text)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid, $3::text, $4::text, $5::text)', v_hook::oid::regproc)
using upsert_product.tenant, upsert_product.product, v_title, v_slug, upsert_product.kind;
end if;
end;
begin
if v_created then
execute coalesce((select 'select jsonb_build_object(' || string_agg(pg_catalog.quote_literal(a.attname) || ', ' || pg_catalog.pg_get_expr(d.adbin, d.adrelid), ', ') || ')'
from pg_catalog.pg_attrdef d join pg_catalog.pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum
where d.adrelid = '"better_supabase"."products"'::regclass and a.attname = any (array[case when upsert_product.description is null then 'description' end]::text[])), 'select ''{}''::jsonb') into v_defaults;
insert into "better_supabase"."products" ("tenant_id", "title", "slug", "description", "kind")
values (upsert_product.tenant, v_title, v_slug, coalesce(upsert_product.description, (jsonb_populate_record(null::"better_supabase"."products", v_defaults))."description"), coalesce(upsert_product.kind, 'physical'))
returning "id", "status" into v_id, v_status;
else
update "better_supabase"."products" x set "title" = v_title, "slug" = v_slug, "description" = case when 'description' = any (coalesce(upsert_product.clear, '{}'::text[])) then null else coalesce(upsert_product.description, x."description") end, "kind" = coalesce(upsert_product.kind, x."kind"), "updated_at" = now()
where x."id" = upsert_product.product and x."tenant_id" = upsert_product.tenant
returning x."status" into v_status;
if not found then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
end if;
exception when unique_violation then
declare
v_constraint text;
begin
get stacked diagnostics v_constraint = constraint_name;
if exists (
select 1 from pg_catalog.pg_index i
join pg_catalog.pg_class c on c.oid = i.indexrelid
where i.indrelid = '"better_supabase"."products"'::regclass and c.relname = v_constraint
and (exists (select 1 from pg_catalog.pg_attribute a where a.attrelid = i.indrelid and a.attnum = any (i.indkey) and a.attname = 'slug')
or coalesce(pg_catalog.pg_get_expr(i.indexprs, i.indrelid), '') ~ ('\m' || 'slug' || '\M'))
) then
raise exception 'another product has this slug' using errcode = '23505', hint = 'CATALOG_SLUG_TAKEN';
end if;
raise;
end;
end;
if v_created then
null;
else
null;
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."after_product_save"(uuid, boolean)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::boolean)', v_hook::oid::regproc)
using v_id, v_created;
end if;
end;
return jsonb_build_object('id', v_id, 'slug', v_slug, 'status', v_status);
end;
$$;
revoke execute on function "better_supabase"."upsert_product"(uuid, uuid, text, text, text, text, text[]) from public, anon;
grant execute on function "better_supabase"."upsert_product"(uuid, uuid, text, text, text, text, text[]) to authenticated, service_role;
-- Moves a product to another status: draft, active or archived.
create or replace function "better_supabase"."set_product_status"(product uuid, status text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_from text;
v_from_raw text;
v_to text := set_product_status.status;
v_to_raw 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", x."status"::text into v_tenant, v_from, v_from_raw from "better_supabase"."products" x where x."id" = set_product_status.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if v_to is null or v_to not in ('draft', 'active', 'archived') then
raise exception 'the status must be draft, active or archived' using errcode = '22023', hint = 'CATALOG_STATUS_INVALID';
end if;
v_to_raw := (set_product_status.status)::text;
if v_from_raw = v_to_raw then
return jsonb_build_object('id', set_product_status.product, 'status', v_from, 'from', v_from);
end if;
if v_from <> v_to and not (case v_from
when 'draft' then v_to = any ('{active,archived}'::text[])
when 'active' then v_to = any ('{draft,archived}'::text[])
when 'archived' then v_to = any ('{draft}'::text[])
else false
end) then
raise exception 'the product can''t move to this status' using errcode = '22023', hint = 'CATALOG_TRANSITION_INVALID';
end if;
update "better_supabase"."products" x set "status" = set_product_status.status, "updated_at" = now()
where x."id" = set_product_status.product;
null;
if v_to = 'archived' then
null;
elsif v_from = 'archived' then
null;
end if;
return jsonb_build_object('id', set_product_status.product, 'status', v_to, 'from', v_from);
end;
$$;
revoke execute on function "better_supabase"."set_product_status"(uuid, text) from public, anon;
grant execute on function "better_supabase"."set_product_status"(uuid, text) to authenticated, service_role;
-- Archives a product: it takes status archived, which takes it off the
-- storefront and out of carts, and records product.archived. Its variants,
-- prices and stock stay. Does nothing when it is archived already.
create or replace function "better_supabase"."archive_product"(product uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
begin
return "better_supabase"."set_product_status"(archive_product.product, 'archived');
end;
$$;
revoke execute on function "better_supabase"."archive_product"(uuid) from public, anon;
grant execute on function "better_supabase"."archive_product"(uuid) to authenticated, service_role;
-- Brings an archived product back as a draft (as active when the app has no
-- draft status), so it is published again on purpose, and records
-- product.restored. Does nothing when it is not archived.
create or replace function "better_supabase"."restore_product"(product uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_status text;
begin
select x."status" into v_status from "better_supabase"."products" x where x."id" = restore_product.product;
if v_status is distinct from 'archived' then
return "better_supabase"."set_product_status"(restore_product.product, coalesce(v_status, 'archived'));
end if;
return "better_supabase"."set_product_status"(restore_product.product, 'draft');
end;
$$;
revoke execute on function "better_supabase"."restore_product"(uuid) from public, anon;
grant execute on function "better_supabase"."restore_product"(uuid) to authenticated, service_role;
-- Removes a product for good with its options, variants and prices; false
-- when it was already gone. Needs permissions.purge, which falls back to
-- catalog.manage.
create or replace function "better_supabase"."purge_product"(product uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."products" x where x."id" = purge_product.product;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."products" x where x."id" = purge_product.product;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."purge_product"(uuid) from public, anon;
grant execute on function "better_supabase"."purge_product"(uuid) to authenticated, service_role;
-- Creates a variant (variant null) or updates one. option_values holds one
-- option value id per product option; no two variants share a combination.
-- On an update a null argument keeps the column and clear names the columns
-- to empty. fields: the extra columns (columns your schema files add) to set.
create or replace function "better_supabase"."upsert_variant"(product uuid, variant uuid, sku text, option_values uuid[], title text, barcode text, weight_grams integer, track_inventory boolean, allow_backorder boolean, clear text[] default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_id uuid := upsert_variant.variant;
v_created boolean := upsert_variant.variant is null;
v_wanted uuid[];
v_last text;
v_rank text;
v_sku text := upsert_variant.sku;
v_defaults 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;
select x."tenant_id" into v_tenant from "better_supabase"."products" x where x."id" = upsert_variant.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if v_created then
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
else
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
end if;
if exists (select 1 from unnest(coalesce(upsert_variant.clear, '{}'::text[])) c where c <> all ('{sku,title,barcode,weight}'::text[])) then
raise exception 'clear names only sku, title, barcode, weight' using errcode = '22023', hint = 'CATALOG_CLEAR_INVALID';
end if;
if v_created or upsert_variant.option_values is not null then
v_wanted := coalesce((select array_agg(distinct x order by x) from unnest(upsert_variant.option_values) x), '{}'::uuid[]);
if cardinality(v_wanted) <> coalesce(cardinality(upsert_variant.option_values), 0)
or exists (
select 1 from unnest(v_wanted) x
where not exists (
select 1 from "better_supabase"."product_option_values" ov join "better_supabase"."product_options" o on o."id" = ov."option_id"
where ov."id" = x and o."product_id" = upsert_variant.product
)
)
or (select count(distinct ov."option_id") from "better_supabase"."product_option_values" ov where ov."id" = any (v_wanted)) <> cardinality(v_wanted)
or (select count(*) from "better_supabase"."product_options" o where o."product_id" = upsert_variant.product) <> cardinality(v_wanted) then
raise exception 'a variant needs exactly one value of each product option' using errcode = '22023', hint = 'CATALOG_VARIANT_OPTIONS';
end if;
if exists (
select 1 from "better_supabase"."product_variants" x
where x."product_id" = upsert_variant.product
and x."id" is distinct from upsert_variant.variant
and coalesce((select array_agg(y."option_value_id" order by y."option_value_id") from "better_supabase"."product_variant_values" y where y."variant_id" = x."id"), '{}'::uuid[]) = v_wanted
) then
raise exception 'another variant has these option values' using errcode = '23505', hint = 'CATALOG_VARIANT_DUPLICATE';
end if;
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_variant_save"(uuid, uuid, text, uuid[])');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid, $3::text, $4::uuid[])', v_hook::oid::regproc)
using upsert_variant.product, upsert_variant.variant, upsert_variant.sku, v_wanted;
end if;
end;
begin
if v_created then
select max(x."rank" collate "C") into v_last from "better_supabase"."product_variants" x where x."product_id" = upsert_variant.product;
v_rank := case
when v_last is null then 'V'
when length(substring(v_last from '^z*')) = length(v_last) then v_last || 'V'
else left(v_last, length(substring(v_last from '^z*'))) || substr('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', (strpos('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', substr(v_last, length(substring(v_last from '^z*')) + 1, 1)) - 1 + 62) / 2 + 1, 1)
end;
execute coalesce((select 'select jsonb_build_object(' || string_agg(pg_catalog.quote_literal(a.attname) || ', ' || pg_catalog.pg_get_expr(d.adbin, d.adrelid), ', ') || ')'
from pg_catalog.pg_attrdef d join pg_catalog.pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum
where d.adrelid = '"better_supabase"."product_variants"'::regclass and a.attname = any (array[case when upsert_variant.sku is null then 'sku' end, case when upsert_variant.title is null then 'title' end, case when upsert_variant.barcode is null then 'barcode' end, case when upsert_variant.weight_grams is null then 'weight_grams' end]::text[])), 'select ''{}''::jsonb') into v_defaults;
insert into "better_supabase"."product_variants" as x ("tenant_id", "product_id", "sku", "title", "barcode", "weight_grams", "track_inventory", "allow_backorder", "rank")
values (v_tenant, upsert_variant.product, coalesce(upsert_variant.sku, (jsonb_populate_record(null::"better_supabase"."product_variants", v_defaults))."sku"), coalesce(upsert_variant.title, (jsonb_populate_record(null::"better_supabase"."product_variants", v_defaults))."title"), coalesce(upsert_variant.barcode, (jsonb_populate_record(null::"better_supabase"."product_variants", v_defaults))."barcode"), coalesce(upsert_variant.weight_grams, (jsonb_populate_record(null::"better_supabase"."product_variants", v_defaults))."weight_grams"), coalesce(upsert_variant.track_inventory, true), coalesce(upsert_variant.allow_backorder, false), v_rank)
returning x."id", x."sku" into v_id, v_sku;
else
update "better_supabase"."product_variants" x set "sku" = case when 'sku' = any (coalesce(upsert_variant.clear, '{}'::text[])) then null else coalesce(upsert_variant.sku, x."sku") end, "title" = case when 'title' = any (coalesce(upsert_variant.clear, '{}'::text[])) then null else coalesce(upsert_variant.title, x."title") end, "barcode" = case when 'barcode' = any (coalesce(upsert_variant.clear, '{}'::text[])) then null else coalesce(upsert_variant.barcode, x."barcode") end, "weight_grams" = case when 'weight' = any (coalesce(upsert_variant.clear, '{}'::text[])) then null else coalesce(upsert_variant.weight_grams, x."weight_grams") end, "track_inventory" = coalesce(upsert_variant.track_inventory, x."track_inventory"), "allow_backorder" = coalesce(upsert_variant.allow_backorder, x."allow_backorder"), "updated_at" = now()
where x."id" = upsert_variant.variant and x."product_id" = upsert_variant.product
returning x."rank", x."sku" into v_rank, v_sku;
if not found then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
end if;
exception when unique_violation then
declare
v_constraint text;
begin
get stacked diagnostics v_constraint = constraint_name;
if exists (
select 1 from pg_catalog.pg_index i
join pg_catalog.pg_class c on c.oid = i.indexrelid
where i.indrelid = '"better_supabase"."product_variants"'::regclass and c.relname = v_constraint
and (exists (select 1 from pg_catalog.pg_attribute a where a.attrelid = i.indrelid and a.attnum = any (i.indkey) and a.attname = 'sku')
or coalesce(pg_catalog.pg_get_expr(i.indexprs, i.indrelid), '') ~ ('\m' || 'sku' || '\M'))
) then
raise exception 'another variant has this SKU' using errcode = '23505', hint = 'CATALOG_SKU_TAKEN';
end if;
raise;
end;
end;
if v_wanted is not null then
delete from "better_supabase"."product_variant_values" x where x."variant_id" = v_id and not (x."option_value_id" = any (v_wanted));
insert into "better_supabase"."product_variant_values" ("tenant_id", "variant_id", "option_value_id")
select v_tenant, v_id, x from unnest(v_wanted) x
on conflict do nothing;
end if;
if v_created then
null;
else
null;
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."after_variant_save"(uuid, boolean)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::boolean)', v_hook::oid::regproc)
using v_id, v_created;
end if;
end;
return jsonb_build_object('id', v_id, 'sku', v_sku, 'rank', v_rank);
end;
$$;
revoke execute on function "better_supabase"."upsert_variant"(uuid, uuid, text, uuid[], text, text, integer, boolean, boolean, text[]) from public, anon;
grant execute on function "better_supabase"."upsert_variant"(uuid, uuid, text, uuid[], text, text, integer, boolean, boolean, text[]) to authenticated, service_role;
-- Sets a variant's rank key among the product's variants.
create or replace function "better_supabase"."rank_variant"(variant uuid, rank text)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 rank_variant.rank is null or rank_variant.rank !~ '^[0-9A-Za-z]*[1-9A-Za-z]$' then
raise exception 'not a rank key' using errcode = '22023', hint = 'CATALOG_RANK_INVALID';
end if;
select x."tenant_id" into v_tenant from "better_supabase"."product_variants" x where x."id" = rank_variant.variant;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
update "better_supabase"."product_variants" x set "rank" = rank_variant.rank, "updated_at" = now() where x."id" = rank_variant.variant;
return true;
end;
$$;
revoke execute on function "better_supabase"."rank_variant"(uuid, text) from public, anon;
grant execute on function "better_supabase"."rank_variant"(uuid, text) to authenticated, service_role;
-- Removes a variant for good with its prices; false when it was already gone.
-- Needs permissions.purge, which falls back to catalog.manage.
create or replace function "better_supabase"."purge_variant"(variant uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_product 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."product_id" into v_tenant, v_product from "better_supabase"."product_variants" x where x."id" = purge_variant.variant;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."product_variants" x where x."id" = purge_variant.variant;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."purge_variant"(uuid) from public, anon;
grant execute on function "better_supabase"."purge_variant"(uuid) to authenticated, service_role;
-- One product and its default variant. The price is data.price, then
-- data.listPrice, then the last purchase price times the markup when
-- options.priceFallback is set. A name that is mostly control characters is
-- refused. A sku already used by another product is refused. A taken slug
-- gains the item key.
create or replace function "better_supabase"."import_product"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_data jsonb := import_product.item -> 'data';
v_tenant uuid := (import_product.item ->> 'tenant')::uuid;
v_raw text := coalesce(v_data ->> 'name', v_data ->> 'title', '');
v_name text;
v_slug text;
v_sku text := nullif(btrim(v_data ->> 'sku'), '');
v_price bigint;
v_id uuid := nullif(import_product.subject_id, '')::uuid;
v_updated timestamptz;
v_fallback boolean := coalesce((import_product.item -> 'options' ->> 'priceFallback')::boolean, false);
begin
if length(regexp_replace(v_raw, '[[:cntrl:][:space:]]', '', 'g')) * 2 < length(regexp_replace(coalesce(v_raw, ''), '[[:space:]]', '', 'g')) then
raise exception 'a product name is mostly control characters' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
v_name := btrim(regexp_replace(regexp_replace(v_raw, '[[:cntrl:]]', '', 'g'), U&'[\+00E000-\+00F8FF]', '', 'g'));
if v_name is null or length(v_name) = 0 then
raise exception 'a product needs a name' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
v_price := coalesce(
nullif(v_data ->> 'price', '')::bigint,
nullif(v_data ->> 'listPrice', '')::bigint,
case when v_fallback then round(nullif(v_data ->> 'lastPurchasePrice', '')::numeric * coalesce(nullif(v_data ->> 'markup', '')::numeric, 1))::bigint end);
v_slug := trim(both '-' from lower(regexp_replace(coalesce(nullif(v_data ->> 'slug', ''), v_name), '[^a-zA-Z0-9]+', '-', 'g')));
if v_id is not null and exists (
select 1 from "better_supabase"."products" x
where x."id" = v_id and x."tenant_id" = v_tenant and x."title" is not distinct from v_name
and x."slug" is not distinct from v_slug
) and (v_sku is null or exists (
select 1 from "better_supabase"."product_variants" y where y."product_id" = v_id and y."sku" is not distinct from v_sku
)) then
return jsonb_build_object('subjectId', v_id, 'updatedAt', (select x."updated_at" from "better_supabase"."products" x where x."id" = v_id));
end if;
if v_sku is not null and exists (
select 1 from "better_supabase"."product_variants" y where y."tenant_id" = v_tenant and y."sku" = v_sku and y."product_id" is distinct from v_id
) then
raise exception 'a sku is already used by another product' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if exists (select 1 from "better_supabase"."products" x where x."tenant_id" = v_tenant and x."slug" = v_slug and x."id" is distinct from v_id) then
v_slug := left(v_slug, 40) || '-' || left(coalesce(import_product.item ->> 'key', 'item'), 8);
end if;
if v_id is null then
insert into "better_supabase"."products" ("tenant_id", "title", "slug", "manufacturer", "model", "tax_code")
values (v_tenant, v_name, v_slug, nullif(btrim(v_data ->> 'manufacturer'), ''), nullif(btrim(v_data ->> 'model'), ''), nullif(coalesce(import_product.item -> 'resolved' ->> 'tax', v_data ->> 'taxCode'), ''))
returning "id", "updated_at" into v_id, v_updated;
else
update "better_supabase"."products" x set "title" = v_name, "slug" = v_slug, "updated_at" = now(), "manufacturer" = coalesce(nullif(btrim(v_data ->> 'manufacturer'), ''), x."manufacturer"), "model" = coalesce(nullif(btrim(v_data ->> 'model'), ''), x."model"), "tax_code" = coalesce(nullif(coalesce(import_product.item -> 'resolved' ->> 'tax', v_data ->> 'taxCode'), ''), x."tax_code")
where x."id" = v_id and x."tenant_id" = v_tenant
returning x."updated_at" into v_updated;
end if;
if not exists (select 1 from "better_supabase"."product_variants" y where y."product_id" = v_id) then
insert into "better_supabase"."product_variants" ("tenant_id", "product_id", "sku", "barcode")
values (v_tenant, v_id, coalesce(v_sku, v_slug), nullif(btrim(v_data ->> 'ean'), ''));
elsif v_sku is not null then
update "better_supabase"."product_variants" y set "sku" = v_sku, "barcode" = coalesce(nullif(btrim(v_data ->> 'ean'), ''), y."barcode")
where y."id" = (select y2."id" from "better_supabase"."product_variants" y2 where y2."product_id" = v_id order by y2."created_at" limit 1);
end if;
return jsonb_build_object('subjectId', v_id, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_product"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_product"(uuid, jsonb, text) to service_role;
-- The batch form of import_product (ADR 1217): new products without the price
-- fallback, whose slug and sku no other item of the batch and no stored
-- product uses, are written in one statement with their default variant.
-- Every other item goes through import_product.
create or replace function "better_supabase"."import_product_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, (e ->> 'tenant')::uuid as tenant, e -> 'data' as d,
coalesce(e -> 'data' ->> 'name', e -> 'data' ->> 'title', '') as raw,
nullif(btrim(e -> 'data' ->> 'sku'), '') as sku
from jsonb_array_elements(items) with ordinality t(e, o)
where jsonb_typeof(e -> 'data') = 'object'
), named as (
select i.*, btrim(regexp_replace(regexp_replace(i.raw, '[[:cntrl:]]', '', 'g'), U&'[\+00E000-\+00F8FF]', '', 'g')) as name
from i
), slugged as (
select named.*, trim(both '-' from lower(regexp_replace(coalesce(nullif(named.d ->> 'slug', ''), named.name), '[^a-zA-Z0-9]+', '-', 'g'))) as slug
from named
), counted as (
select s.*, count(*) over (partition by s.tenant, s.slug) as slugs,
count(*) over (partition by s.tenant, coalesce(s.sku, s.slug)) as skus,
count(*) over (partition by s.tenant, s.sku) as own_skus
from slugged s
), f as (
select c.n, c.id, c.tenant, c.d, c.name, c.slug, c.sku, c.e,
coalesce(case when pg_input_is_valid(coalesce(nullif(c.d ->> 'price', ''), ''), 'bigint') then (nullif(c.d ->> 'price', ''))::bigint end, case when pg_input_is_valid(coalesce(nullif(c.d ->> 'listPrice', ''), ''), 'bigint') then (nullif(c.d ->> 'listPrice', ''))::bigint end) as price
from counted c
where nullif(c.e ->> 'subjectId', '') is null
and coalesce(c.e -> 'options' ->> 'priceFallback', 'false') = 'false'
and pg_input_is_valid(coalesce(nullif(c.d ->> 'price', ''), '0'), 'bigint')
and pg_input_is_valid(coalesce(nullif(c.d ->> 'listPrice', ''), '0'), 'bigint')
and length(regexp_replace(c.raw, '[[:cntrl:][:space:]]', '', 'g')) * 2 >= length(regexp_replace(c.raw, '[[:space:]]', '', 'g'))
and length(c.name) > 0
and c.slugs = 1 and c.skus = 1 and (c.sku is null or c.own_skus = 1)
and (select x."id" from "better_supabase"."products" x where x."tenant_id" = c.tenant and x."slug" = c.slug limit 1) is null
and (select y."id" from "better_supabase"."product_variants" y where y."tenant_id" = c.tenant and y."sku" = coalesce(c.sku, c.slug) limit 1) is null
), written as (
insert into "better_supabase"."products" as x ("id", "tenant_id", "title", "slug", "manufacturer", "model", "tax_code")
select f.id, f.tenant, f.name, f.slug, nullif(btrim(f.d ->> 'manufacturer'), ''), nullif(btrim(f.d ->> 'model'), ''), nullif(coalesce(f.e -> 'resolved' ->> 'tax', f.d ->> 'taxCode'), '')
from f
returning x."id" as id, x."updated_at" as updated_at
), variant as (
insert into "better_supabase"."product_variants" ("tenant_id", "product_id", "sku", "barcode")
select f.tenant, f.id, coalesce(f.sku, f.slug), nullif(btrim(f.d ->> 'ean'), '')
from f
)
select f.n, jsonb_build_object('subjectId', f.id, '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_product"(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_product_batch"(uuid, jsonb) from public, anon, authenticated;
grant execute on function "better_supabase"."import_product_batch"(uuid, jsonb) to service_role;
create or replace function "better_supabase"."product_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."products" x where x."id" = better_supabase.try_column_type(product_updated_at.subject_id, (null::"better_supabase"."products")."id")
$$;
revoke execute on function "better_supabase"."product_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."product_updated_at"(text) to service_role;
create or replace function "better_supabase"."import_product_category"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_data jsonb := import_product_category.item -> 'data';
v_product uuid := nullif(coalesce(import_product_category.item -> 'resolved' ->> 'product', v_data ->> 'productId'), '')::uuid;
v_category uuid := nullif(coalesce(import_product_category.item -> 'resolved' ->> 'category', v_data ->> 'categoryId'), '')::uuid;
begin
if v_category is null and nullif(btrim(v_data ->> 'name'), '') is not null then
select x."id" into v_category from "better_supabase"."catalog_categories" x
where x."tenant_id" = (import_product_category.item ->> 'tenant')::uuid and x."name" = btrim(v_data ->> 'name');
end if;
if v_product is null or v_category is null then
raise exception 'a product category needs a product and a category' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
insert into "better_supabase"."product_categories" ("tenant_id", "product_id", "category_id")
values ((import_product_category.item ->> 'tenant')::uuid, v_product, v_category)
on conflict do nothing;
return jsonb_build_object('subjectId', v_product::text || ':' || v_category::text, 'updatedAt', now());
end;
$$;
revoke execute on function "better_supabase"."import_product_category"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_product_category"(uuid, jsonb, text) to service_role;
create or replace function "better_supabase"."product_category_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select now()
$$;
revoke execute on function "better_supabase"."product_category_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."product_category_updated_at"(text) to service_role;
-- Variants have no status column (columns.variants.status), so this refuses.
create or replace function "better_supabase"."set_variant_status"(variant uuid, status text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
begin
raise exception 'this variants table has no status column' using errcode = '22023', hint = 'CATALOG_VARIANT_STATUS_UNSUPPORTED';
end;
$$;
revoke execute on function "better_supabase"."set_variant_status"(uuid, text) from public, anon;
grant execute on function "better_supabase"."set_variant_status"(uuid, text) to authenticated, service_role;
-- Archives a variant through its status, so it refuses without a status column.
create or replace function "better_supabase"."archive_variant"(variant uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
begin
raise exception 'this variants table has no status column' using errcode = '22023', hint = 'CATALOG_VARIANT_STATUS_UNSUPPORTED';
end;
$$;
revoke execute on function "better_supabase"."archive_variant"(uuid) from public, anon;
grant execute on function "better_supabase"."archive_variant"(uuid) to authenticated, service_role;
-- Restores a variant through its status, so it refuses without a status column.
create or replace function "better_supabase"."restore_variant"(variant uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
begin
raise exception 'this variants table has no status column' using errcode = '22023', hint = 'CATALOG_VARIANT_STATUS_UNSUPPORTED';
end;
$$;
revoke execute on function "better_supabase"."restore_variant"(uuid) from public, anon;
grant execute on function "better_supabase"."restore_variant"(uuid) to authenticated, service_role;
-- Creates an option (option null) or updates one, with its values in order.
-- Values missing from the list are removed with the variants that use them;
-- a variant something still references is archived instead.
create or replace function "better_supabase"."upsert_product_option"(product uuid, option uuid, name text, option_values text[])
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_id uuid := upsert_product_option.option;
v_last text;
v_rank text;
v_value text;
v_variant uuid;
v_new boolean := upsert_product_option.option is null;
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"."products" x where x."id" = upsert_product_option.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if coalesce(cardinality(upsert_product_option.option_values), 0) = 0 then
raise exception 'an option needs at least one value' using errcode = '22023', hint = 'CATALOG_OPTION_EMPTY';
end if;
if (select count(distinct x) from unnest(upsert_product_option.option_values) x) <> cardinality(upsert_product_option.option_values) then
raise exception 'an option lists the same value twice' using errcode = '22023', hint = 'CATALOG_OPTION_DUPLICATE';
end if;
begin
if v_id is null then
select max(x."rank" collate "C") into v_last from "better_supabase"."product_options" x where x."product_id" = upsert_product_option.product;
insert into "better_supabase"."product_options" ("tenant_id", "product_id", "name", "rank")
values (v_tenant, upsert_product_option.product, upsert_product_option.name, case
when v_last is null then 'V'
when length(substring(v_last from '^z*')) = length(v_last) then v_last || 'V'
else left(v_last, length(substring(v_last from '^z*'))) || substr('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', (strpos('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', substr(v_last, length(substring(v_last from '^z*')) + 1, 1)) - 1 + 62) / 2 + 1, 1)
end)
returning "id" into v_id;
else
update "better_supabase"."product_options" x set "name" = upsert_product_option.name
where x."id" = upsert_product_option.option and x."product_id" = upsert_product_option.product;
if not found then
raise exception 'option not found' using errcode = 'P0002', hint = 'CATALOG_OPTION_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'the product has another option with this name' using errcode = '23505', hint = 'CATALOG_OPTION_TAKEN';
end;
for v_variant in
select distinct x."variant_id" from "better_supabase"."product_variant_values" x
join "better_supabase"."product_option_values" y on y."id" = x."option_value_id"
where y."option_id" = v_id and not (y."value" = any (upsert_product_option.option_values))
loop
begin
delete from "better_supabase"."product_variants" x where x."id" = v_variant;
null;
exception when foreign_key_violation then
raise exception 'a variant this list removes is still in use' using errcode = '23503', hint = 'CATALOG_OPTION_VALUE_IN_USE';
end;
end loop;
begin
delete from "better_supabase"."product_option_values" x where x."option_id" = v_id and not (x."value" = any (upsert_product_option.option_values));
exception when foreign_key_violation then
raise exception 'a variant uses a value this list removes' using errcode = '23503', hint = 'CATALOG_OPTION_VALUE_IN_USE';
end;
v_rank := null;
foreach v_value in array upsert_product_option.option_values loop
v_rank := case
when v_rank is null then 'V'
when length(substring(v_rank from '^z*')) = length(v_rank) then v_rank || 'V'
else left(v_rank, length(substring(v_rank from '^z*'))) || substr('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', (strpos('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', substr(v_rank, length(substring(v_rank from '^z*')) + 1, 1)) - 1 + 62) / 2 + 1, 1)
end;
update "better_supabase"."product_option_values" x set "rank" = v_rank where x."option_id" = v_id and x."value" = v_value;
if not found then
insert into "better_supabase"."product_option_values" ("tenant_id", "option_id", "value", "rank")
values (v_tenant, v_id, v_value, v_rank);
end if;
end loop;
if v_new then
insert into "better_supabase"."product_variant_values" ("tenant_id", "variant_id", "option_value_id")
select v_tenant, x."id", (select y."id" from "better_supabase"."product_option_values" y where y."option_id" = v_id and y."value" = upsert_product_option.option_values[1])
from "better_supabase"."product_variants" x where x."product_id" = upsert_product_option.product;
end if;
return jsonb_build_object(
'id', v_id,
'values', (select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'value', x."value") order by x."rank" collate "C"), '[]'::jsonb) from "better_supabase"."product_option_values" x where x."option_id" = v_id)
);
end;
$$;
revoke execute on function "better_supabase"."upsert_product_option"(uuid, uuid, text, text[]) from public, anon;
grant execute on function "better_supabase"."upsert_product_option"(uuid, uuid, text, text[]) to authenticated, service_role;
-- Puts a product's options in the given order; the list names each once.
create or replace function "better_supabase"."reorder_product_options"(product uuid, options uuid[])
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_rank text;
v_option 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" into v_tenant from "better_supabase"."products" x where x."id" = reorder_product_options.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if coalesce(cardinality(reorder_product_options.options), 0) <> (select count(*) from "better_supabase"."product_options" x where x."product_id" = reorder_product_options.product)
or (select count(distinct y) from unnest(reorder_product_options.options) y) <> cardinality(reorder_product_options.options)
or exists (select 1 from unnest(reorder_product_options.options) y where not exists (select 1 from "better_supabase"."product_options" x where x."id" = y and x."product_id" = reorder_product_options.product)) then
raise exception 'the list must name each option of the product once' using errcode = '22023', hint = 'CATALOG_OPTION_ORDER_INVALID';
end if;
foreach v_option in array reorder_product_options.options loop
v_rank := case
when v_rank is null then 'V'
when length(substring(v_rank from '^z*')) = length(v_rank) then v_rank || 'V'
else left(v_rank, length(substring(v_rank from '^z*'))) || substr('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', (strpos('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', substr(v_rank, length(substring(v_rank from '^z*')) + 1, 1)) - 1 + 62) / 2 + 1, 1)
end;
update "better_supabase"."product_options" x set "rank" = v_rank where x."id" = v_option;
end loop;
return true;
end;
$$;
revoke execute on function "better_supabase"."reorder_product_options"(uuid, uuid[]) from public, anon;
grant execute on function "better_supabase"."reorder_product_options"(uuid, uuid[]) to authenticated, service_role;
-- Deletes an option and its values; refused while a variant uses one.
create or replace function "better_supabase"."delete_product_option"(option uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_options" x where x."id" = delete_product_option.option;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
begin
delete from "better_supabase"."product_options" x where x."id" = delete_product_option.option;
exception when foreign_key_violation then
raise exception 'a variant uses a value of this option' using errcode = '23503', hint = 'CATALOG_OPTION_VALUE_IN_USE';
end;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_product_option"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_product_option"(uuid) to authenticated, service_role;
-- Replaces a product's options by name and makes its variants the full matrix
-- of their values in one transaction.
create or replace function "better_supabase"."set_product_options"(product uuid, options jsonb, title_separator text default ' / ')
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_slug text;
v_item jsonb;
v_option uuid;
v_ids uuid[] := '{}';
v_variant uuid;
v_combo uuid[];
v_label text;
v_count numeric := 1;
v_sku_required 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."slug" into v_tenant, v_slug from "better_supabase"."products" x where x."id" = set_product_options.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if jsonb_typeof(set_product_options.options) is distinct from 'array'
or exists (
select 1 from jsonb_array_elements(set_product_options.options) e
where jsonb_typeof(e) is distinct from 'object'
or jsonb_typeof(e -> 'name') is distinct from 'string'
or jsonb_typeof(e -> 'values') is distinct from 'array'
or exists (select 1 from jsonb_array_elements(e -> 'values') y where jsonb_typeof(y) <> 'string')
) then
raise exception 'options is a list of { name, values } with text values' using errcode = '22023', hint = 'CATALOG_OPTIONS_INVALID';
end if;
if (select count(distinct e ->> 'name') from jsonb_array_elements(set_product_options.options) e) <> jsonb_array_length(set_product_options.options) then
raise exception 'the list names an option twice' using errcode = '23505', hint = 'CATALOG_OPTION_TAKEN';
end if;
for v_item in select e from jsonb_array_elements(set_product_options.options) e loop
v_count := v_count * jsonb_array_length(v_item -> 'values');
end loop;
if v_count > 100 then
raise exception 'a product has at most 100 variants' using errcode = '22023', hint = 'CATALOG_VARIANT_LIMIT';
end if;
for v_option in
select x."id" from "better_supabase"."product_options" x
where x."product_id" = set_product_options.product
and not (x."name" = any (array(select e ->> 'name' from jsonb_array_elements(set_product_options.options) e)))
loop
delete from "better_supabase"."product_variant_values" y using "better_supabase"."product_option_values" z where y."option_value_id" = z."id" and z."option_id" = v_option;
delete from "better_supabase"."product_options" x where x."id" = v_option;
end loop;
for v_variant in
select d.id from (
select x."id" as id, row_number() over (partition by coalesce((select array_agg(y."option_value_id" order by y."option_value_id") from "better_supabase"."product_variant_values" y where y."variant_id" = x."id"), '{}'::uuid[]) order by x."rank" collate "C", x."id") as n
from "better_supabase"."product_variants" x where x."product_id" = set_product_options.product
) d where d.n > 1
loop
begin
delete from "better_supabase"."product_variants" x where x."id" = v_variant;
null;
exception when foreign_key_violation then
raise exception 'a variant this list removes is still in use' using errcode = '23503', hint = 'CATALOG_OPTION_VALUE_IN_USE';
end;
end loop;
for v_item in select e from jsonb_array_elements(set_product_options.options) with ordinality as a(e, n) order by a.n loop
select x."id" into v_option from "better_supabase"."product_options" x where x."product_id" = set_product_options.product and x."name" = v_item ->> 'name';
v_option := ("better_supabase"."upsert_product_option"(set_product_options.product, v_option, v_item ->> 'name', array(select y from jsonb_array_elements_text(v_item -> 'values') with ordinality as b(y, n) order by b.n)) ->> 'id')::uuid;
v_ids := v_ids || v_option;
end loop;
if cardinality(v_ids) > 0 then
perform "better_supabase"."reorder_product_options"(set_product_options.product, v_ids);
end if;
select a.attnotnull into v_sku_required from pg_catalog.pg_attribute a
where a.attrelid = '"better_supabase"."product_variants"'::regclass and a.attname = 'sku';
for v_combo, v_label in
with recursive k as (
select x."id" as id, row_number() over (order by x."rank" collate "C") as n
from "better_supabase"."product_options" x where x."product_id" = set_product_options.product
), z as (
select y."id" as id, y."value" as value, y."option_id" as option, row_number() over (partition by y."option_id" order by y."rank" collate "C") as n
from "better_supabase"."product_option_values" y where y."option_id" in (select k.id from k)
), c(depth, ids, labels, sort) as (
select 0::bigint, '{}'::uuid[], '{}'::text[], '{}'::bigint[]
union all
select k.n, c.ids || z.id, c.labels || z.value, c.sort || z.n
from c join k on k.n = c.depth + 1 join z on z.option = k.id
)
select c.ids, array_to_string(c.labels, '-') from c where c.depth = (select count(*) from k) order by c.sort
loop
if not exists (
select 1 from "better_supabase"."product_variants" x
where x."product_id" = set_product_options.product
and coalesce((select array_agg(y."option_value_id" order by y."option_value_id") from "better_supabase"."product_variant_values" y where y."variant_id" = x."id"), '{}'::uuid[]) = (select coalesce(array_agg(u order by u), '{}'::uuid[]) from unnest(v_combo) u)
) then
perform "better_supabase"."upsert_variant"(set_product_options.product, null, case when v_sku_required then upper(trim(both '-' from regexp_replace(concat_ws('-', v_slug, nullif(v_label, '')), '[^A-Za-z0-9]+', '-', 'g'))) end, v_combo, null, null, null, null, null);
end if;
end loop;
if set_product_options.title_separator is not null then
update "better_supabase"."product_variants" x set "title" = t.title, "updated_at" = now()
from (
select y."variant_id" as variant, string_agg(z."value", set_product_options.title_separator order by k."rank" collate "C") as title
from "better_supabase"."product_variant_values" y
join "better_supabase"."product_option_values" z on z."id" = y."option_value_id"
join "better_supabase"."product_options" k on k."id" = z."option_id"
where k."product_id" = set_product_options.product
group by y."variant_id"
) t
where x."id" = t.variant and x."title" is distinct from t.title;
end if;
return jsonb_build_object(
'options', (
select coalesce(jsonb_agg(jsonb_build_object(
'id', k."id",
'name', k."name",
'values', (select coalesce(jsonb_agg(jsonb_build_object('id', z."id", 'value', z."value") order by z."rank" collate "C"), '[]'::jsonb) from "better_supabase"."product_option_values" z where z."option_id" = k."id")
) order by k."rank" collate "C"), '[]'::jsonb)
from "better_supabase"."product_options" k where k."product_id" = set_product_options.product
),
'variants', (
select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'sku', x."sku", 'optionValueIds', to_jsonb(coalesce((select array_agg(y."option_value_id" order by y."option_value_id") from "better_supabase"."product_variant_values" y where y."variant_id" = x."id"), '{}'::uuid[]))) order by x."rank" collate "C"), '[]'::jsonb)
from "better_supabase"."product_variants" x where x."product_id" = set_product_options.product
)
);
end;
$$;
revoke execute on function "better_supabase"."set_product_options"(uuid, jsonb, text) from public, anon;
grant execute on function "better_supabase"."set_product_options"(uuid, jsonb, text) to authenticated, service_role;
-- Creates a price list (price_list null) or renames one. customer_group
-- names the customers it is for, such as a B2B tier.
create or replace function "better_supabase"."upsert_price_list"(tenant uuid, price_list uuid, name text, customer_group text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_price_list.price_list;
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_price_list.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
begin
if v_id is null then
insert into "better_supabase"."catalog_price_lists" ("tenant_id", "name", "customer_group")
values (upsert_price_list.tenant, upsert_price_list.name, upsert_price_list.customer_group)
returning "id" into v_id;
else
update "better_supabase"."catalog_price_lists" x set "name" = upsert_price_list.name, "customer_group" = upsert_price_list.customer_group
where x."id" = v_id and x."tenant_id" = upsert_price_list.tenant;
if not found then
raise exception 'price list not found' using errcode = 'P0002', hint = 'CATALOG_PRICE_LIST_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'another price list has this name' using errcode = '23505', hint = 'CATALOG_PRICE_LIST_TAKEN';
end;
return jsonb_build_object('id', v_id);
end;
$$;
revoke execute on function "better_supabase"."upsert_price_list"(uuid, uuid, text, text) from public, anon;
grant execute on function "better_supabase"."upsert_price_list"(uuid, uuid, text, text) to authenticated, service_role;
-- Deletes a price list and its prices.
create or replace function "better_supabase"."delete_price_list"(price_list uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."catalog_price_lists" x where x."id" = delete_price_list.price_list;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."catalog_price_lists" x where x."id" = delete_price_list.price_list;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_price_list"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_price_list"(uuid) to authenticated, service_role;
-- Sets a variant's price in a currency, in minor units, for a price list
-- (null for the base price) and a validity window. The same window is
-- updated in place; a window that overlaps another price is refused.
create or replace function "better_supabase"."set_price"(variant uuid, currency text, amount text, compare_at text, price_list uuid, starts_at timestamptz, expires_at timestamptz)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_amount bigint := case when set_price.amount ~ '^[0-9]{1,18}$' then set_price.amount::bigint end;
v_compare bigint := case when set_price.compare_at ~ '^[0-9]{1,18}$' then set_price.compare_at::bigint end;
v_id uuid;
v_previous bigint;
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"."product_variants" x where x."id" = set_price.variant for update;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if "better_supabase"."currency_minor_units"(set_price.currency) is null then
raise exception 'not an ISO 4217 currency code' using errcode = '22023', hint = 'CATALOG_CURRENCY_INVALID';
end if;
if v_amount is null then
raise exception 'the amount must be a whole number of minor units' using errcode = '22023', hint = 'CATALOG_AMOUNT_INVALID';
end if;
if set_price.compare_at is not null and (v_compare is null or v_compare <= v_amount) then
raise exception 'the compare-at amount must be above the amount' using errcode = '22023', hint = 'CATALOG_COMPARE_AT_INVALID';
end if;
if set_price.expires_at is not null and set_price.expires_at <= coalesce(set_price.starts_at, '-infinity'::timestamptz) then
raise exception 'expires_at must be after starts_at' using errcode = '22023', hint = 'CATALOG_VALIDITY_INVALID';
end if;
if set_price.price_list is not null and not exists (select 1 from "better_supabase"."catalog_price_lists" x where x."id" = set_price.price_list and x."tenant_id" = v_tenant) then
raise exception 'price list not found' using errcode = 'P0002', hint = 'CATALOG_PRICE_LIST_NOT_FOUND';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_price_set"(uuid, text, bigint, uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::text, $3::bigint, $4::uuid)', v_hook::oid::regproc)
using set_price.variant, set_price.currency, v_amount, set_price.price_list;
end if;
end;
select x."id", x."amount" into v_id, v_previous from "better_supabase"."product_prices" x
where x."variant_id" = set_price.variant and x."currency" = set_price.currency and x."price_list_id" is not distinct from set_price.price_list
and x."starts_at" is not distinct from set_price.starts_at and x."expires_at" is not distinct from set_price.expires_at;
if exists (
select 1 from "better_supabase"."product_prices" x
where x."variant_id" = set_price.variant and x."currency" = set_price.currency and x."price_list_id" is not distinct from set_price.price_list
and x."id" is distinct from v_id
and tstzrange(coalesce(x."starts_at", '-infinity'::timestamptz), coalesce(x."expires_at", 'infinity'::timestamptz), '[)') && tstzrange(coalesce(set_price.starts_at, '-infinity'::timestamptz), coalesce(set_price.expires_at, 'infinity'::timestamptz), '[)')
) then
raise exception 'another price of this variant, currency and list covers part of this window' using errcode = '23P01', hint = 'CATALOG_PRICE_OVERLAP';
end if;
if v_id is null then
insert into "better_supabase"."product_prices" ("tenant_id", "variant_id", "currency", "amount", "price_list_id", "compare_at_amount", "starts_at", "expires_at")
values (v_tenant, set_price.variant, set_price.currency, v_amount, set_price.price_list, v_compare, set_price.starts_at, set_price.expires_at)
returning "id" into v_id;
else
update "better_supabase"."product_prices" x set "amount" = v_amount, "compare_at_amount" = v_compare, "updated_at" = now()
where x."id" = v_id;
end if;
if v_previous is distinct from v_amount then
null;
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."after_price_set"(uuid, bigint)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::bigint)', v_hook::oid::regproc)
using v_id, v_previous;
end if;
end;
return jsonb_build_object('id', v_id, 'amount', v_amount::text, 'previousAmount', v_previous::text);
end;
$$;
revoke execute on function "better_supabase"."set_price"(uuid, text, text, text, uuid, timestamptz, timestamptz) from public, anon;
grant execute on function "better_supabase"."set_price"(uuid, text, text, text, uuid, timestamptz, timestamptz) to authenticated, service_role;
-- Deletes a price.
create or replace function "better_supabase"."delete_price"(price uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_prices" x where x."id" = delete_price.price;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."product_prices" x where x."id" = delete_price.price;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_price"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_price"(uuid) to authenticated, service_role;
-- The price a variant sells at in a currency at a time: the price list's
-- price when it has one, otherwise the base price. Runs as the caller, so
-- the read policies decide which prices it sees. Amounts are text: JSON
-- numbers lose bigint precision.
create or replace function "better_supabase"."variant_price"(variant uuid, currency text, price_list uuid default null, as_of timestamptz default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object(
'id', x."id",
'variantId', x."variant_id",
'currency', x."currency",
'amount', x."amount"::text,
'compareAt', x."compare_at_amount"::text,
'priceListId', x."price_list_id"
)
from "better_supabase"."product_prices" x
where x."variant_id" = $1 and x."currency" = $2
and (x."price_list_id" is null or x."price_list_id" = $3)
and tstzrange(coalesce(x."starts_at", '-infinity'::timestamptz), coalesce(x."expires_at", 'infinity'::timestamptz), '[)') @> coalesce($4, now())
order by (x."price_list_id" is null), x."updated_at" desc
limit 1
$$;
revoke execute on function "better_supabase"."variant_price"(uuid, text, uuid, timestamptz) from public;
grant execute on function "better_supabase"."variant_price"(uuid, text, uuid, timestamptz) to anon, authenticated, service_role;
-- Creates a category (category null) or updates one, under parent (null
-- for the top level). A new category goes after its siblings. fields: the
-- extra columns (columns your schema files add) to set.
create or replace function "better_supabase"."upsert_category"(tenant uuid, category uuid, parent uuid, name text, slug text, description text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_category.category;
v_slug text := coalesce(nullif(upsert_category.slug, ''), trim(both '-' from regexp_replace(lower(upsert_category.name), '[^a-z0-9]+', '-', 'g')));
v_last text;
v_rank text;
v_defaults 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 v_id is null then
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', upsert_category.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
else
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', upsert_category.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
end if;
if v_slug is null or v_slug !~ '^[a-z0-9]+(?:-[a-z0-9]+)*$' then
raise exception 'the slug must be lower-case letters, digits and hyphens' using errcode = '22023', hint = 'CATALOG_SLUG_INVALID';
end if;
if upsert_category.parent is not null and not exists (select 1 from "better_supabase"."catalog_categories" x where x."id" = upsert_category.parent and x."tenant_id" = upsert_category.tenant) then
raise exception 'parent category not found' using errcode = 'P0002', hint = 'CATALOG_CATEGORY_NOT_FOUND';
end if;
if upsert_category.parent is not null and exists (
with recursive up (id) as (
select upsert_category.parent
union
select x."parent_id" from "better_supabase"."catalog_categories" x join up on x."id" = up.id where x."parent_id" is not null
)
select 1 from up where up.id = v_id
) then
raise exception 'a category can''t sit under itself' using errcode = '22023', hint = 'CATALOG_CATEGORY_CYCLE';
end if;
begin
if v_id is null then
select max(x."rank" collate "C") into v_last from "better_supabase"."catalog_categories" x
where x."tenant_id" = upsert_category.tenant and x."parent_id" is not distinct from upsert_category.parent;
v_rank := case
when v_last is null then 'V'
when length(substring(v_last from '^z*')) = length(v_last) then v_last || 'V'
else left(v_last, length(substring(v_last from '^z*'))) || substr('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', (strpos('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', substr(v_last, length(substring(v_last from '^z*')) + 1, 1)) - 1 + 62) / 2 + 1, 1)
end;
execute coalesce((select 'select jsonb_build_object(' || string_agg(pg_catalog.quote_literal(a.attname) || ', ' || pg_catalog.pg_get_expr(d.adbin, d.adrelid), ', ') || ')'
from pg_catalog.pg_attrdef d join pg_catalog.pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum
where d.adrelid = '"better_supabase"."catalog_categories"'::regclass and a.attname = any (array[case when upsert_category.description is null then 'description' end]::text[])), 'select ''{}''::jsonb') into v_defaults;
insert into "better_supabase"."catalog_categories" ("tenant_id", "parent_id", "name", "slug", "description", "rank")
values (upsert_category.tenant, upsert_category.parent, upsert_category.name, v_slug, coalesce(upsert_category.description, (jsonb_populate_record(null::"better_supabase"."catalog_categories", v_defaults))."description"), v_rank)
returning "id" into v_id;
else
update "better_supabase"."catalog_categories" x set "parent_id" = upsert_category.parent, "name" = upsert_category.name, "slug" = v_slug,
"description" = upsert_category.description, "updated_at" = now()
where x."id" = v_id and x."tenant_id" = upsert_category.tenant
returning x."rank" into v_rank;
if not found then
raise exception 'category not found' using errcode = 'P0002', hint = 'CATALOG_CATEGORY_NOT_FOUND';
end if;
end if;
exception when unique_violation then
declare
v_constraint text;
begin
get stacked diagnostics v_constraint = constraint_name;
if exists (
select 1 from pg_catalog.pg_index i
join pg_catalog.pg_class c on c.oid = i.indexrelid
where i.indrelid = '"better_supabase"."catalog_categories"'::regclass and c.relname = v_constraint
and (exists (select 1 from pg_catalog.pg_attribute a where a.attrelid = i.indrelid and a.attnum = any (i.indkey) and a.attname = 'slug')
or coalesce(pg_catalog.pg_get_expr(i.indexprs, i.indrelid), '') ~ ('\m' || 'slug' || '\M'))
) then
raise exception 'another category has this slug' using errcode = '23505', hint = 'CATALOG_SLUG_TAKEN';
end if;
raise;
end;
end;
return jsonb_build_object('id', v_id, 'slug', v_slug, 'rank', v_rank);
end;
$$;
revoke execute on function "better_supabase"."upsert_category"(uuid, uuid, uuid, text, text, text) from public, anon;
grant execute on function "better_supabase"."upsert_category"(uuid, uuid, uuid, text, text, text) to authenticated, service_role;
-- Moves a category under parent (null for the top level) at rank, a key
-- from rankBetween over its new siblings' keys.
create or replace function "better_supabase"."move_category"(category uuid, parent uuid, rank text)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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 move_category.rank is null or move_category.rank !~ '^[0-9A-Za-z]*[1-9A-Za-z]$' then
raise exception 'not a rank key' using errcode = '22023', hint = 'CATALOG_RANK_INVALID';
end if;
select x."tenant_id" into v_tenant from "better_supabase"."catalog_categories" x where x."id" = move_category.category for update;
if v_tenant is null then
raise exception 'category not found' using errcode = 'P0002', hint = 'CATALOG_CATEGORY_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if move_category.parent is not null and not exists (select 1 from "better_supabase"."catalog_categories" x where x."id" = move_category.parent and x."tenant_id" = v_tenant) then
raise exception 'parent category not found' using errcode = 'P0002', hint = 'CATALOG_CATEGORY_NOT_FOUND';
end if;
if move_category.parent is not null and exists (
with recursive up (id) as (
select move_category.parent
union
select x."parent_id" from "better_supabase"."catalog_categories" x join up on x."id" = up.id where x."parent_id" is not null
)
select 1 from up where up.id = move_category.category
) then
raise exception 'a category can''t sit under itself' using errcode = '22023', hint = 'CATALOG_CATEGORY_CYCLE';
end if;
update "better_supabase"."catalog_categories" x set "parent_id" = move_category.parent, "rank" = move_category.rank, "updated_at" = now()
where x."id" = move_category.category;
return true;
end;
$$;
revoke execute on function "better_supabase"."move_category"(uuid, uuid, text) from public, anon;
grant execute on function "better_supabase"."move_category"(uuid, uuid, text) to authenticated, service_role;
-- Deletes a category without subcategories; products leave it.
create or replace function "better_supabase"."delete_category"(category uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."catalog_categories" x where x."id" = delete_category.category;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
begin
delete from "better_supabase"."catalog_categories" x where x."id" = delete_category.category;
exception when foreign_key_violation then
raise exception 'move or delete the subcategories first' using errcode = '23503', hint = 'CATALOG_CATEGORY_HAS_CHILDREN';
end;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_category"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_category"(uuid) to authenticated, service_role;
-- Replaces the categories a product is filed under.
create or replace function "better_supabase"."set_product_categories"(product uuid, categories uuid[])
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."products" x where x."id" = set_product_categories.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if exists (
select 1 from unnest(coalesce(set_product_categories.categories, '{}'::uuid[])) c
where not exists (select 1 from "better_supabase"."catalog_categories" x where x."id" = c and x."tenant_id" = v_tenant)
) then
raise exception 'category not found' using errcode = 'P0002', hint = 'CATALOG_CATEGORY_NOT_FOUND';
end if;
delete from "better_supabase"."product_categories" x
where x."product_id" = set_product_categories.product
and not (x."category_id" = any (coalesce(set_product_categories.categories, '{}'::uuid[])));
insert into "better_supabase"."product_categories" ("tenant_id", "product_id", "category_id")
select distinct v_tenant, set_product_categories.product, c from unnest(coalesce(set_product_categories.categories, '{}'::uuid[])) c
on conflict do nothing;
return true;
end;
$$;
revoke execute on function "better_supabase"."set_product_categories"(uuid, uuid[]) from public, anon;
grant execute on function "better_supabase"."set_product_categories"(uuid, uuid[]) to authenticated, service_role;
-- Creates a collection (collection null) or updates one. A manual
-- collection lists ranked products; a rule collection stores a filter tree
-- (a FilterQuery group) that picks them.
create or replace function "better_supabase"."upsert_collection"(tenant uuid, collection uuid, title text, slug text, kind text, rule jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_collection.collection;
v_kind text := coalesce(upsert_collection.kind, 'manual');
v_slug text := coalesce(nullif(upsert_collection.slug, ''), trim(both '-' from regexp_replace(lower(upsert_collection.title), '[^a-z0-9]+', '-', 'g')));
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_collection.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if v_slug is null or v_slug !~ '^[a-z0-9]+(?:-[a-z0-9]+)*$' then
raise exception 'the slug must be lower-case letters, digits and hyphens' using errcode = '22023', hint = 'CATALOG_SLUG_INVALID';
end if;
if v_kind not in ('manual', 'rule') then
raise exception 'the kind must be manual or rule' using errcode = '22023', hint = 'CATALOG_COLLECTION_KIND';
end if;
if (v_kind = 'rule') <> (upsert_collection.rule is not null) then
raise exception 'a rule collection needs a rule and a manual one none' using errcode = '22023', hint = 'CATALOG_COLLECTION_RULE';
end if;
if v_kind = 'rule' and not (
jsonb_typeof(upsert_collection.rule) = 'object'
and upsert_collection.rule ->> 'type' = 'group'
and upsert_collection.rule ->> 'combinator' in ('and', 'or')
and jsonb_typeof(upsert_collection.rule -> 'rules') = 'array'
) then
raise exception 'the rule must be a filter group with a combinator and rules' using errcode = '22023', hint = 'CATALOG_COLLECTION_RULE';
end if;
begin
if v_id is null then
insert into "better_supabase"."product_collections" ("tenant_id", "title", "slug", "kind", "rule")
values (upsert_collection.tenant, upsert_collection.title, v_slug, v_kind, upsert_collection.rule)
returning "id" into v_id;
else
update "better_supabase"."product_collections" x set "title" = upsert_collection.title, "slug" = v_slug, "kind" = v_kind,
"rule" = upsert_collection.rule, "updated_at" = now()
where x."id" = v_id and x."tenant_id" = upsert_collection.tenant;
if not found then
raise exception 'collection not found' using errcode = 'P0002', hint = 'CATALOG_COLLECTION_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'another collection has this slug' using errcode = '23505', hint = 'CATALOG_SLUG_TAKEN';
end;
if v_kind = 'rule' then
delete from "better_supabase"."collection_products" x where x."collection_id" = v_id;
end if;
return jsonb_build_object('id', v_id, 'slug', v_slug, 'kind', v_kind);
end;
$$;
revoke execute on function "better_supabase"."upsert_collection"(uuid, uuid, text, text, text, jsonb) from public, anon;
grant execute on function "better_supabase"."upsert_collection"(uuid, uuid, text, text, text, jsonb) to authenticated, service_role;
-- Deletes a collection.
create or replace function "better_supabase"."delete_collection"(collection uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_collections" x where x."id" = delete_collection.collection;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."product_collections" x where x."id" = delete_collection.collection;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_collection"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_collection"(uuid) to authenticated, service_role;
-- Adds a product to a manual collection at rank (null to append), or moves
-- it there. Returns its rank key.
create or replace function "better_supabase"."add_to_collection"(collection uuid, product uuid, rank text)
returns text
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_kind text;
v_last text;
v_rank text := add_to_collection.rank;
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."kind" into v_tenant, v_kind from "better_supabase"."product_collections" x where x."id" = add_to_collection.collection for update;
if v_tenant is null then
raise exception 'collection not found' using errcode = 'P0002', hint = 'CATALOG_COLLECTION_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if v_kind <> 'manual' then
raise exception 'a rule collection picks its products from its rule' using errcode = '22023', hint = 'CATALOG_COLLECTION_RULE';
end if;
if not exists (select 1 from "better_supabase"."products" x where x."id" = add_to_collection.product and x."tenant_id" = v_tenant) then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if v_rank is not null and v_rank !~ '^[0-9A-Za-z]*[1-9A-Za-z]$' then
raise exception 'not a rank key' using errcode = '22023', hint = 'CATALOG_RANK_INVALID';
end if;
if v_rank is null then
select max(x."rank" collate "C") into v_last from "better_supabase"."collection_products" x where x."collection_id" = add_to_collection.collection;
v_rank := case
when v_last is null then 'V'
when length(substring(v_last from '^z*')) = length(v_last) then v_last || 'V'
else left(v_last, length(substring(v_last from '^z*'))) || substr('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', (strpos('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', substr(v_last, length(substring(v_last from '^z*')) + 1, 1)) - 1 + 62) / 2 + 1, 1)
end;
end if;
insert into "better_supabase"."collection_products" as x ("tenant_id", "collection_id", "product_id", "rank")
values (v_tenant, add_to_collection.collection, add_to_collection.product, v_rank)
on conflict ("collection_id", "product_id") do update set "rank" = excluded."rank";
return v_rank;
end;
$$;
revoke execute on function "better_supabase"."add_to_collection"(uuid, uuid, text) from public, anon;
grant execute on function "better_supabase"."add_to_collection"(uuid, uuid, text) to authenticated, service_role;
-- Removes a product from a manual collection.
create or replace function "better_supabase"."remove_from_collection"(collection uuid, product uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_collections" x where x."id" = remove_from_collection.collection;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."collection_products" x where x."collection_id" = remove_from_collection.collection and x."product_id" = remove_from_collection.product;
return found;
end;
$$;
revoke execute on function "better_supabase"."remove_from_collection"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."remove_from_collection"(uuid, uuid) to authenticated, service_role;
-- Tenants whose storefront is published. The storefront read policies
-- call it, so it runs as its owner and returns nothing else.
create or replace function "better_supabase"."storefront_tenants"()
returns setof uuid
language sql
stable
security definer
set search_path = ''
as $$
select x."tenant_id" from "better_supabase"."catalog_storefronts" x where x."published_at" is not null
$$;
revoke execute on function "better_supabase"."storefront_tenants"() from public;
grant execute on function "better_supabase"."storefront_tenants"() to anon, authenticated, service_role;
-- Active products of published storefronts, for the storefront policies.
create or replace function "better_supabase"."storefront_products"()
returns setof uuid
language sql
stable
security definer
set search_path = ''
as $$
select x."id" from "better_supabase"."products" x
where x."status" = 'active'
and x."tenant_id" in (select y."tenant_id" from "better_supabase"."catalog_storefronts" y where y."published_at" is not null)
$$;
revoke execute on function "better_supabase"."storefront_products"() from public;
grant execute on function "better_supabase"."storefront_products"() to anon, authenticated, service_role;
-- Publishes or unpublishes a tenant's storefront. With options.storefront
-- "public", anyone can read the active products of a published storefront.
create or replace function "better_supabase"."publish_storefront"(tenant uuid, published boolean)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
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', publish_storefront.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
insert into "better_supabase"."catalog_storefronts" as x ("tenant_id", "published_at")
values (publish_storefront.tenant, case when publish_storefront.published then now() end)
on conflict ("tenant_id") do update
set "published_at" = case when publish_storefront.published then coalesce(x."published_at", now()) end;
if publish_storefront.published then
null;
else
null;
end if;
return publish_storefront.published;
end;
$$;
revoke execute on function "better_supabase"."publish_storefront"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."publish_storefront"(uuid, boolean) to authenticated, service_role;
-- Creates a sales channel (channel null) or updates one. A channel has a
-- key, unique per organization, and optionally a currency and a price list
-- its prices come from.
create or replace function "better_supabase"."upsert_catalog_channel"(tenant uuid, channel uuid, key text, name text, currency text, price_list uuid, active boolean)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_id uuid := upsert_catalog_channel.channel;
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_catalog_channel.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if upsert_catalog_channel.key is null or upsert_catalog_channel.key !~ '^[a-z0-9]+(?:-[a-z0-9]+)*$' then
raise exception 'the channel key must be lower-case letters, digits and hyphens' using errcode = '22023', hint = 'CATALOG_CHANNEL_KEY_INVALID';
end if;
if upsert_catalog_channel.currency is not null and "better_supabase"."currency_minor_units"(upsert_catalog_channel.currency) is null then
raise exception 'not an ISO 4217 currency code' using errcode = '22023', hint = 'CATALOG_CURRENCY_INVALID';
end if;
if upsert_catalog_channel.price_list is not null and not exists (select 1 from "better_supabase"."catalog_price_lists" x where x."id" = upsert_catalog_channel.price_list and x."tenant_id" = upsert_catalog_channel.tenant) then
raise exception 'price list not found' using errcode = 'P0002', hint = 'CATALOG_PRICE_LIST_NOT_FOUND';
end if;
begin
if v_id is null then
insert into "better_supabase"."catalog_channels" as x ("tenant_id", "key", "name", "currency", "price_list_id", "active")
values (upsert_catalog_channel.tenant, upsert_catalog_channel.key, upsert_catalog_channel.name, upsert_catalog_channel.currency, upsert_catalog_channel.price_list, coalesce(upsert_catalog_channel.active, true))
returning x."id", x."active" into v_id, v_active;
else
update "better_supabase"."catalog_channels" x set "key" = upsert_catalog_channel.key, "name" = upsert_catalog_channel.name, "currency" = upsert_catalog_channel.currency, "price_list_id" = upsert_catalog_channel.price_list, "active" = coalesce(upsert_catalog_channel.active, x."active"), "updated_at" = now()
where x."id" = v_id and x."tenant_id" = upsert_catalog_channel.tenant
returning x."active" into v_active;
if not found then
raise exception 'channel not found' using errcode = 'P0002', hint = 'CATALOG_CHANNEL_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'another channel has this key' using errcode = '23505', hint = 'CATALOG_CHANNEL_TAKEN';
end;
return jsonb_build_object('id', v_id, 'key', upsert_catalog_channel.key, 'active', v_active);
end;
$$;
revoke execute on function "better_supabase"."upsert_catalog_channel"(uuid, uuid, text, text, text, uuid, boolean) from public, anon;
grant execute on function "better_supabase"."upsert_catalog_channel"(uuid, uuid, text, text, text, uuid, boolean) to authenticated, service_role;
-- Deletes a channel and its listings.
create or replace function "better_supabase"."delete_catalog_channel"(channel uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."catalog_channels" x where x."id" = delete_catalog_channel.channel;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."catalog_channels" x where x."id" = delete_catalog_channel.channel;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_catalog_channel"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_catalog_channel"(uuid) to authenticated, service_role;
-- The price a variant sells at on a channel: variant_price in the channel's
-- currency and price list. Null when the channel has no currency.
create or replace function "better_supabase"."channel_price"(channel uuid, variant uuid, as_of timestamptz default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select "better_supabase"."variant_price"($2, k."currency", k."price_list_id", $3)
from "better_supabase"."catalog_channels" k
where k."id" = $1 and k."currency" is not null
$$;
revoke execute on function "better_supabase"."channel_price"(uuid, uuid, timestamptz) from public;
grant execute on function "better_supabase"."channel_price"(uuid, uuid, timestamptz) to anon, authenticated, service_role;
-- Lists products on a channel (listed true) or takes them off it. Returns
-- how many listings changed.
create or replace function "better_supabase"."set_channel_listing"(channel uuid, products uuid[], listed boolean)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_count 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;
select x."tenant_id" into v_tenant from "better_supabase"."catalog_channels" x where x."id" = set_channel_listing.channel for update;
if v_tenant is null then
raise exception 'channel not found' using errcode = 'P0002', hint = 'CATALOG_CHANNEL_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if exists (
select 1 from unnest(coalesce(set_channel_listing.products, '{}'::uuid[])) i
where not exists (select 1 from "better_supabase"."products" x where x."id" = i and x."tenant_id" = v_tenant)
) then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if coalesce(set_channel_listing.listed, true) then
insert into "better_supabase"."catalog_channel_products" ("tenant_id", "channel_id", "product_id")
select distinct v_tenant, set_channel_listing.channel, i from unnest(coalesce(set_channel_listing.products, '{}'::uuid[])) i
on conflict do nothing;
else
delete from "better_supabase"."catalog_channel_products" x
where x."channel_id" = set_channel_listing.channel
and x."product_id" = any (coalesce(set_channel_listing.products, '{}'::uuid[]));
end if;
get diagnostics v_count = row_count;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."set_channel_listing"(uuid, uuid[], boolean) from public, anon;
grant execute on function "better_supabase"."set_channel_listing"(uuid, uuid[], boolean) to authenticated, service_role;
-- The products listed on a channel by slug, with their text in locale
-- (the default text where a translation is missing). after is the last
-- slug of the previous page. archived false (the default) leaves out archived
-- products and true lists only them. Runs as the caller, so the read policies
-- decide what it sees.
create or replace function "better_supabase"."channel_products"(channel uuid, locale text default null, page_size integer default null, after text default null, archived boolean default false)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(item order by slug collate "C"), '[]'::jsonb)
from (
select jsonb_build_object(
'id', p."id",
'slug', p."slug",
'status', p."status",
'kind', p."kind",
'locale', (case when $2 = any ('{en}'::text[]) then $2 when split_part($2, '-', 1) = any ('{en}'::text[]) then split_part($2, '-', 1) else 'en' end),
'title', coalesce(t."title", p."title"),
'description', coalesce(t."description", p."description"),
'listedAt', l."listed_at"
) as item, p."slug" as slug
from "better_supabase"."catalog_channel_products" l
join "better_supabase"."products" p on p."id" = l."product_id"
left join "better_supabase"."product_translations" t on t."product_id" = p."id" and t."locale" = (case when $2 = any ('{en}'::text[]) then $2 when split_part($2, '-', 1) = any ('{en}'::text[]) then split_part($2, '-', 1) else 'en' end)
where l."channel_id" = $1
and ($4 is null or p."slug" collate "C" > $4 collate "C")
and (case when coalesce($5, false) then p."status" = 'archived' else p."status" <> 'archived' end)
order by p."slug" collate "C"
limit least(greatest(coalesce($3, 100), 1), 500)
) items
$$;
revoke execute on function "better_supabase"."channel_products"(uuid, text, integer, text, boolean) from public;
grant execute on function "better_supabase"."channel_products"(uuid, text, integer, text, boolean) to anon, authenticated, service_role;
-- Sets a product's title and description in a locale other than the
-- default. Null text falls back to the default text; both null removes the
-- translation. Returns whether one is stored.
create or replace function "better_supabase"."set_product_translation"(product uuid, locale text, title text, description text)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_tenant 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" into v_tenant from "better_supabase"."products" x where x."id" = set_product_translation.product for update;
if v_tenant is null then
raise exception 'product not found' using errcode = 'P0002', hint = 'CATALOG_PRODUCT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if set_product_translation.locale is null or not (set_product_translation.locale = any ('{en}'::text[])) then
raise exception 'the locale is not one of blocks.catalog.options.locales' using errcode = '22023', hint = 'CATALOG_LOCALE_INVALID';
end if;
if set_product_translation.locale = 'en' then
raise exception 'the default locale''s text lives on the record itself' using errcode = '22023', hint = 'CATALOG_LOCALE_DEFAULT';
end if;
if set_product_translation.title is not null and length(set_product_translation.title) not between 1 and 500 then
raise exception 'a title has 1 to 500 characters' using errcode = '22023', hint = 'CATALOG_TITLE_INVALID';
end if;
if set_product_translation.title is null and set_product_translation.description is null then
delete from "better_supabase"."product_translations" x
where x."product_id" = set_product_translation.product and x."locale" = set_product_translation.locale;
return false;
end if;
insert into "better_supabase"."product_translations" as x ("tenant_id", "product_id", "locale", "title", "description")
values (v_tenant, set_product_translation.product, set_product_translation.locale, set_product_translation.title, set_product_translation.description)
on conflict ("product_id", "locale") do update
set "title" = excluded."title", "description" = excluded."description", "updated_at" = now();
return true;
end;
$$;
revoke execute on function "better_supabase"."set_product_translation"(uuid, text, text, text) from public, anon;
grant execute on function "better_supabase"."set_product_translation"(uuid, text, text, text) to authenticated, service_role;
-- Sets a variant's title in a locale other than the default; a null title
-- removes the translation. Returns whether one is stored.
create or replace function "better_supabase"."set_variant_translation"(variant uuid, locale text, title text)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_tenant 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" into v_tenant from "better_supabase"."product_variants" x where x."id" = set_variant_translation.variant for update;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if set_variant_translation.locale is null or not (set_variant_translation.locale = any ('{en}'::text[])) then
raise exception 'the locale is not one of blocks.catalog.options.locales' using errcode = '22023', hint = 'CATALOG_LOCALE_INVALID';
end if;
if set_variant_translation.locale = 'en' then
raise exception 'the default locale''s text lives on the record itself' using errcode = '22023', hint = 'CATALOG_LOCALE_DEFAULT';
end if;
if set_variant_translation.title is not null and length(set_variant_translation.title) not between 1 and 500 then
raise exception 'a title has 1 to 500 characters' using errcode = '22023', hint = 'CATALOG_TITLE_INVALID';
end if;
if set_variant_translation.title is null then
delete from "better_supabase"."product_variant_translations" x
where x."variant_id" = set_variant_translation.variant and x."locale" = set_variant_translation.locale;
return false;
end if;
insert into "better_supabase"."product_variant_translations" as x ("tenant_id", "variant_id", "locale", "title")
values (v_tenant, set_variant_translation.variant, set_variant_translation.locale, set_variant_translation.title)
on conflict ("variant_id", "locale") do update
set "title" = excluded."title", "updated_at" = now();
return true;
end;
$$;
revoke execute on function "better_supabase"."set_variant_translation"(uuid, text, text) from public, anon;
grant execute on function "better_supabase"."set_variant_translation"(uuid, text, text) to authenticated, service_role;
-- A product's text and its variants' titles in locale: the locale itself,
-- then its language, then the default locale's text on the product. Runs
-- as the caller, so the read policies decide what it sees.
create or replace function "better_supabase"."product_text"(product uuid, locale text default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object(
'id', p."id",
'slug', p."slug",
'locale', (case when $2 = any ('{en}'::text[]) then $2 when split_part($2, '-', 1) = any ('{en}'::text[]) then split_part($2, '-', 1) else 'en' end),
'title', coalesce(t."title", p."title"),
'description', coalesce(t."description", p."description"),
'variants', coalesce((
select jsonb_agg(jsonb_build_object('id', w."id", 'sku', w."sku", 'title', coalesce((select y."title" from "better_supabase"."product_variant_translations" y where y."variant_id" = w."id" and y."locale" = (case when $2 = any ('{en}'::text[]) then $2 when split_part($2, '-', 1) = any ('{en}'::text[]) then split_part($2, '-', 1) else 'en' end)), w."title")) order by w."rank" collate "C", w."id")
from "better_supabase"."product_variants" w where w."product_id" = p."id"
), '[]'::jsonb)
)
from "better_supabase"."products" p
left join "better_supabase"."product_translations" t on t."product_id" = p."id" and t."locale" = (case when $2 = any ('{en}'::text[]) then $2 when split_part($2, '-', 1) = any ('{en}'::text[]) then split_part($2, '-', 1) else 'en' end)
where p."id" = $1
$$;
revoke execute on function "better_supabase"."product_text"(uuid, text) from public;
grant execute on function "better_supabase"."product_text"(uuid, text) to anon, authenticated, service_role;
-- Adds an identifier (an EAN, a supplier's or manufacturer's code) to a
-- variant. A code is stored once per variant, type and party, so a second
-- call returns the existing row with created false.
create or replace function "better_supabase"."upsert_product_identifier"(tenant uuid, variant uuid, type text, value text, party uuid default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
v_created boolean := false;
v_value text := btrim(upsert_product_identifier.value);
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_product_identifier.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if upsert_product_identifier.type is null or upsert_product_identifier.type not in ('ean', 'supplier', 'manufacturer', 'other') then
raise exception 'the type must be one of ean, supplier, manufacturer, other' using errcode = '22023', hint = 'CATALOG_IDENTIFIER_TYPE_INVALID';
end if;
if v_value is null or length(v_value) not between 1 and 100 then
raise exception 'the value must be 1 to 100 characters' using errcode = '22023', hint = 'CATALOG_IDENTIFIER_INVALID';
end if;
if upsert_product_identifier.type = 'ean' and v_value !~ '^([0-9]{8}|[0-9]{12,14})$' then
raise exception 'an EAN has 8, 12, 13 or 14 digits' using errcode = '22023', hint = 'CATALOG_IDENTIFIER_INVALID';
end if;
if not exists (select 1 from "better_supabase"."product_variants" x where x."id" = upsert_product_identifier.variant and x."tenant_id" = upsert_product_identifier.tenant) then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
select x."id" into v_id from "better_supabase"."product_identifiers" x
where x."variant_id" = upsert_product_identifier.variant and x."type" = upsert_product_identifier.type and x."value" = v_value
and coalesce(x."party_id", '00000000-0000-0000-0000-000000000000'::uuid) = coalesce(upsert_product_identifier.party, '00000000-0000-0000-0000-000000000000'::uuid);
if v_id is null then
begin
insert into "better_supabase"."product_identifiers" as x ("tenant_id", "variant_id", "type", "value", "party_id")
values (upsert_product_identifier.tenant, upsert_product_identifier.variant, upsert_product_identifier.type, v_value, upsert_product_identifier.party)
returning x."id" into v_id;
v_created := true;
exception when unique_violation then
select x."id" into v_id from "better_supabase"."product_identifiers" x
where x."variant_id" = upsert_product_identifier.variant and x."type" = upsert_product_identifier.type and x."value" = v_value
and coalesce(x."party_id", '00000000-0000-0000-0000-000000000000'::uuid) = coalesce(upsert_product_identifier.party, '00000000-0000-0000-0000-000000000000'::uuid);
end;
end if;
return jsonb_build_object('id', v_id, 'created', v_created);
end;
$$;
revoke execute on function "better_supabase"."upsert_product_identifier"(uuid, uuid, text, text, uuid) from public, anon;
grant execute on function "better_supabase"."upsert_product_identifier"(uuid, uuid, text, text, uuid) to authenticated, service_role;
-- Removes an identifier.
create or replace function "better_supabase"."delete_product_identifier"(identifier uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_identifiers" x where x."id" = delete_product_identifier.identifier;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."product_identifiers" x where x."id" = delete_product_identifier.identifier;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_product_identifier"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_product_identifier"(uuid) to authenticated, service_role;
-- The variants that carry a code, with the identifier that matched. type and
-- party narrow the search; the caller's read access limits the rows.
create or replace function "better_supabase"."find_variants_by_identifier"(tenant uuid, value text, type text default null, party uuid default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('identifierId', x."id", 'variantId', y."id", 'productId', y."product_id", 'sku', y."sku", 'type', x."type", 'value', x."value", 'partyId', x."party_id") order by y."sku", x."type"), '[]'::jsonb)
from "better_supabase"."product_identifiers" x join "better_supabase"."product_variants" y on y."id" = x."variant_id"
where x."tenant_id" = $1 and x."value" = btrim($2)
and ($3 is null or x."type" = $3)
and ($4 is null or x."party_id" = $4)
$$;
revoke execute on function "better_supabase"."find_variants_by_identifier"(uuid, text, text, uuid) from public, anon;
grant execute on function "better_supabase"."find_variants_by_identifier"(uuid, text, text, uuid) to authenticated, service_role;
-- Every identifier of a variant.
create or replace function "better_supabase"."variant_identifiers"(variant uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'type', x."type", 'value', x."value", 'partyId', x."party_id") order by x."type", x."value"), '[]'::jsonb)
from "better_supabase"."product_identifiers" x where x."variant_id" = $1
$$;
revoke execute on function "better_supabase"."variant_identifiers"(uuid) from public, anon;
grant execute on function "better_supabase"."variant_identifiers"(uuid) to authenticated, service_role;
-- Links the variant "from" to the variant "to": "from" has "to" as an
-- alternative or an accessory, or is superseded by it. A repeated call
-- returns created false. A supersession can't point back along its own chain.
create or replace function "better_supabase"."upsert_product_relation"(tenant uuid, from_variant uuid, to_variant uuid, kind text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_created 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_product_relation.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if upsert_product_relation.kind is null or upsert_product_relation.kind not in ('alternative', 'superseded_by', 'accessory') then
raise exception 'the kind must be one of alternative, superseded_by, accessory' using errcode = '22023', hint = 'CATALOG_RELATION_KIND_INVALID';
end if;
if upsert_product_relation.from_variant = upsert_product_relation.to_variant then
raise exception 'a variant can''t relate to itself' using errcode = '22023', hint = 'CATALOG_RELATION_INVALID';
end if;
if (select count(*) from "better_supabase"."product_variants" x where x."tenant_id" = upsert_product_relation.tenant and x."id" in (upsert_product_relation.from_variant, upsert_product_relation.to_variant)) <> 2 then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
if upsert_product_relation.kind = 'superseded_by' and exists (
with recursive chain(id, depth) as (
select upsert_product_relation.to_variant, 0
union all
select y."to_variant_id", c.depth + 1 from "better_supabase"."product_relations" y join chain c on y."from_variant_id" = c.id and y."kind" = 'superseded_by' where c.depth < 50
)
select 1 from chain where id = upsert_product_relation.from_variant
) then
raise exception 'the replacement already points back at this variant' using errcode = '22023', hint = 'CATALOG_RELATION_CYCLE';
end if;
insert into "better_supabase"."product_relations" ("tenant_id", "from_variant_id", "to_variant_id", "kind")
values (upsert_product_relation.tenant, upsert_product_relation.from_variant, upsert_product_relation.to_variant, upsert_product_relation.kind)
on conflict do nothing;
v_created := found;
return jsonb_build_object('created', v_created);
end;
$$;
revoke execute on function "better_supabase"."upsert_product_relation"(uuid, uuid, uuid, text) from public, anon;
grant execute on function "better_supabase"."upsert_product_relation"(uuid, uuid, uuid, text) to authenticated, service_role;
-- Removes one relation.
create or replace function "better_supabase"."delete_product_relation"(from_variant uuid, to_variant uuid, kind text)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_relations" x
where x."from_variant_id" = delete_product_relation.from_variant and x."to_variant_id" = delete_product_relation.to_variant and x."kind" = delete_product_relation.kind;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."product_relations" x
where x."from_variant_id" = delete_product_relation.from_variant and x."to_variant_id" = delete_product_relation.to_variant and x."kind" = delete_product_relation.kind;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_product_relation"(uuid, uuid, text) from public, anon;
grant execute on function "better_supabase"."delete_product_relation"(uuid, uuid, text) to authenticated, service_role;
-- The relations a variant is part of. direction is outgoing where the variant
-- is "from" (it is superseded by, or has as an alternative or accessory, the
-- variant named) and incoming where it is "to".
create or replace function "better_supabase"."variant_relations"(variant uuid, kind text default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('kind', q.kind, 'direction', q.direction, 'variantId', q.other, 'sku', y."sku") order by q.kind, q.direction, y."sku"), '[]'::jsonb)
from (
select x."kind" as kind, 'outgoing' as direction, x."to_variant_id" as other from "better_supabase"."product_relations" x where x."from_variant_id" = $1
union all
select x."kind", 'incoming', x."from_variant_id" from "better_supabase"."product_relations" x where x."to_variant_id" = $1
) q
join "better_supabase"."product_variants" y on y."id" = q.other
where $2 is null or q.kind = $2
$$;
revoke execute on function "better_supabase"."variant_relations"(uuid, text) from public, anon;
grant execute on function "better_supabase"."variant_relations"(uuid, text) to authenticated, service_role;
-- The variant at the end of a variant's superseded_by chain: the variant
-- itself when nothing replaces it.
create or replace function "better_supabase"."replacement_variant"(variant uuid)
returns uuid
language sql
stable
security invoker
set search_path = ''
as $$
with recursive chain(id, depth) as (
select $1, 0
union all
select x."to_variant_id", c.depth + 1 from "better_supabase"."product_relations" x join chain c on x."from_variant_id" = c.id and x."kind" = 'superseded_by' where c.depth < 50
)
select id from chain order by depth desc, id limit 1
$$;
revoke execute on function "better_supabase"."replacement_variant"(uuid) from public, anon;
grant execute on function "better_supabase"."replacement_variant"(uuid) to authenticated, service_role;
-- Sets how a supplier's price list columns fill supplier items. columns maps
-- code, description, price, currency, unit, keywords to source column names (keywords
-- may list several); defaults may hold currency and unit.
create or replace function "better_supabase"."set_supplier_item_mapping"(tenant uuid, supplier uuid, columns jsonb, defaults jsonb default '{}'::jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_key text;
v_value jsonb;
v_defaults jsonb := coalesce(set_supplier_item_mapping.defaults, '{}'::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 not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', set_supplier_item_mapping.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if jsonb_typeof(set_supplier_item_mapping.columns) is distinct from 'object' or jsonb_typeof(v_defaults) <> 'object' then
raise exception 'columns and defaults must be objects' using errcode = '22023', hint = 'CATALOG_SUPPLIER_MAPPING_INVALID';
end if;
for v_key, v_value in select e.key, e.value from jsonb_each(set_supplier_item_mapping.columns) e loop
if v_key <> all (array['code', 'description', 'price', 'currency', 'unit', 'keywords']) then
raise exception 'a mapping fills only code, description, price, currency, unit, keywords' using errcode = '22023', hint = 'CATALOG_SUPPLIER_MAPPING_INVALID';
end if;
if not (jsonb_typeof(v_value) = 'string' or (v_key = 'keywords' and jsonb_typeof(v_value) = 'array' and not exists (select 1 from jsonb_array_elements(v_value) a where jsonb_typeof(a.value) <> 'string'))) then
raise exception 'a mapping value is a source column name (keywords may list several)' using errcode = '22023', hint = 'CATALOG_SUPPLIER_MAPPING_INVALID';
end if;
end loop;
if not (set_supplier_item_mapping.columns ? 'code') then
raise exception 'a mapping needs a code column' using errcode = '22023', hint = 'CATALOG_SUPPLIER_MAPPING_INVALID';
end if;
if exists (select 1 from jsonb_object_keys(v_defaults) k where k <> all (array['currency', 'unit'])) then
raise exception 'defaults may hold currency and unit' using errcode = '22023', hint = 'CATALOG_SUPPLIER_MAPPING_INVALID';
end if;
if v_defaults ? 'currency' and "better_supabase"."currency_minor_units"(v_defaults ->> 'currency') is null then
raise exception 'not an ISO 4217 currency code' using errcode = '22023', hint = 'CATALOG_CURRENCY_INVALID';
end if;
insert into "better_supabase"."supplier_item_mappings" as x ("tenant_id", "supplier_id", "columns", "defaults")
values (set_supplier_item_mapping.tenant, set_supplier_item_mapping.supplier, set_supplier_item_mapping.columns, v_defaults)
on conflict ("tenant_id", "supplier_id") do update set "columns" = excluded."columns", "defaults" = excluded."defaults", "updated_at" = now();
return jsonb_build_object('supplierId', set_supplier_item_mapping.supplier, 'columns', set_supplier_item_mapping.columns, 'defaults', v_defaults);
end;
$$;
revoke execute on function "better_supabase"."set_supplier_item_mapping"(uuid, uuid, jsonb, jsonb) from public, anon;
grant execute on function "better_supabase"."set_supplier_item_mapping"(uuid, uuid, jsonb, jsonb) to authenticated, service_role;
-- A supplier's mapping, or null.
create or replace function "better_supabase"."supplier_item_mapping"(tenant uuid, supplier uuid)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select jsonb_build_object('supplierId', x."supplier_id", 'columns', x."columns", 'defaults', x."defaults")
from "better_supabase"."supplier_item_mappings" x where x."tenant_id" = $1 and x."supplier_id" = $2
$$;
revoke execute on function "better_supabase"."supplier_item_mapping"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."supplier_item_mapping"(uuid, uuid) to authenticated, service_role;
-- Removes a supplier's mapping.
create or replace function "better_supabase"."delete_supplier_item_mapping"(tenant uuid, supplier uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
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', delete_supplier_item_mapping.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."supplier_item_mappings" x where x."tenant_id" = delete_supplier_item_mapping.tenant and x."supplier_id" = delete_supplier_item_mapping.supplier;
return found;
end;
$$;
revoke execute on function "better_supabase"."delete_supplier_item_mapping"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."delete_supplier_item_mapping"(uuid, uuid) to authenticated, service_role;
-- One source row of a supplier's price list as supplier item fields, through
-- the supplier's mapping. price is in minor units: the source value is a
-- decimal in major units, with a comma or a dot as the decimal separator.
create or replace function "better_supabase"."supplier_item_from_row"(tenant uuid, supplier uuid, source jsonb)
returns jsonb
language plpgsql
stable
security invoker
set search_path = ''
as $$
declare
v_columns jsonb;
v_defaults jsonb;
v_code text;
v_description text;
v_unit text;
v_currency text;
v_price text;
v_amount bigint;
v_scale integer;
v_keywords text;
v_source jsonb;
begin
select x."columns", x."defaults" into v_columns, v_defaults
from "better_supabase"."supplier_item_mappings" x where x."tenant_id" = supplier_item_from_row.tenant and x."supplier_id" = supplier_item_from_row.supplier;
if v_columns is null then
raise exception 'this supplier has no column mapping' using errcode = 'P0002', hint = 'CATALOG_SUPPLIER_MAPPING_NOT_FOUND';
end if;
if jsonb_typeof(supplier_item_from_row.source) is distinct from 'object' then
raise exception 'a row is an object of source columns' using errcode = '22023', hint = 'CATALOG_SUPPLIER_ROW_INVALID';
end if;
v_code := nullif(btrim(supplier_item_from_row.source ->> (v_columns ->> 'code')), '');
v_description := nullif(btrim(supplier_item_from_row.source ->> (v_columns ->> 'description')), '');
v_unit := coalesce(nullif(btrim(supplier_item_from_row.source ->> (v_columns ->> 'unit')), ''), v_defaults ->> 'unit');
v_currency := upper(coalesce(nullif(btrim(supplier_item_from_row.source ->> (v_columns ->> 'currency')), ''), v_defaults ->> 'currency'));
v_price := nullif(btrim(supplier_item_from_row.source ->> (v_columns ->> 'price')), '');
if v_currency is not null and "better_supabase"."currency_minor_units"(v_currency) is null then
raise exception 'not an ISO 4217 currency code' using errcode = '22023', hint = 'CATALOG_CURRENCY_INVALID';
end if;
if v_price is not null then
v_price := regexp_replace(v_price, '[^0-9.,-]', '', 'g');
if position(',' in v_price) > 0 and position('.' in v_price) > 0 then
-- The separator that comes last is the decimal one.
if length(v_price) - length(regexp_replace(v_price, '^.*,', '')) > length(v_price) - length(regexp_replace(v_price, '^.*\.', '')) then
v_price := replace(replace(v_price, '.', ''), ',', '.');
else
v_price := replace(v_price, ',', '');
end if;
else
v_price := replace(v_price, ',', '.');
end if;
v_scale := coalesce("better_supabase"."currency_minor_units"(v_currency), 2);
begin
v_amount := round(v_price::numeric * power(10::numeric, v_scale))::bigint;
exception when others then
raise exception 'the price is not a number' using errcode = '22023', hint = 'CATALOG_SUPPLIER_PRICE_INVALID';
end;
if v_amount < 0 then
raise exception 'the price can''t be negative' using errcode = '22023', hint = 'CATALOG_SUPPLIER_PRICE_INVALID';
end if;
end if;
v_source := case jsonb_typeof(v_columns -> 'keywords') when 'array' then v_columns -> 'keywords' when 'string' then jsonb_build_array(v_columns -> 'keywords') else '[]'::jsonb end;
select nullif(string_agg(btrim(supplier_item_from_row.source ->> (a.value #>> '{}')), ' ') filter (where nullif(btrim(supplier_item_from_row.source ->> (a.value #>> '{}')), '') is not null), '')
into v_keywords from jsonb_array_elements(v_source) a;
return jsonb_strip_nulls(jsonb_build_object('code', v_code, 'description', v_description, 'price', v_amount, 'currency', v_currency, 'unit', v_unit, 'keywords', v_keywords));
end;
$$;
revoke execute on function "better_supabase"."supplier_item_from_row"(uuid, uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."supplier_item_from_row"(uuid, uuid, jsonb) to authenticated, service_role;
-- Creates a supplier item (item null) or updates one; on an update a null
-- argument keeps the column. price is in minor units.
create or replace function "better_supabase"."upsert_supplier_item"(tenant uuid, item uuid, supplier uuid, code text, description text, price bigint, currency text, unit text, keywords text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid := upsert_supplier_item.item;
v_code text := btrim(upsert_supplier_item.code);
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_supplier_item.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if v_code is null or length(v_code) not between 1 and 100 then
raise exception 'the code must be 1 to 100 characters' using errcode = '22023', hint = 'CATALOG_SUPPLIER_ITEM_INVALID';
end if;
if upsert_supplier_item.price is not null and upsert_supplier_item.price < 0 then
raise exception 'the price can''t be negative' using errcode = '22023', hint = 'CATALOG_SUPPLIER_ITEM_INVALID';
end if;
if upsert_supplier_item.currency is not null and "better_supabase"."currency_minor_units"(upsert_supplier_item.currency) is null then
raise exception 'not an ISO 4217 currency code' using errcode = '22023', hint = 'CATALOG_CURRENCY_INVALID';
end if;
begin
if v_id is null then
insert into "better_supabase"."supplier_items" as x ("tenant_id", "supplier_id", "code", "description", "price", "currency", "unit", "keywords_text")
values (upsert_supplier_item.tenant, upsert_supplier_item.supplier, v_code, upsert_supplier_item.description, upsert_supplier_item.price, upsert_supplier_item.currency, upsert_supplier_item.unit, upsert_supplier_item.keywords)
returning x."id" into v_id;
else
update "better_supabase"."supplier_items" x set "supplier_id" = coalesce(upsert_supplier_item.supplier, x."supplier_id"), "code" = v_code,
"description" = coalesce(upsert_supplier_item.description, x."description"), "price" = coalesce(upsert_supplier_item.price, x."price"),
"currency" = coalesce(upsert_supplier_item.currency, x."currency"), "unit" = coalesce(upsert_supplier_item.unit, x."unit"),
"keywords_text" = coalesce(upsert_supplier_item.keywords, x."keywords_text"), "updated_at" = now()
where x."id" = upsert_supplier_item.item and x."tenant_id" = upsert_supplier_item.tenant;
if not found then
raise exception 'supplier item not found' using errcode = 'P0002', hint = 'CATALOG_SUPPLIER_ITEM_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'this supplier already has an item with this code' using errcode = '23505', hint = 'CATALOG_SUPPLIER_ITEM_TAKEN';
end;
return jsonb_build_object('id', v_id, 'code', v_code);
end;
$$;
revoke execute on function "better_supabase"."upsert_supplier_item"(uuid, uuid, uuid, text, text, bigint, text, text, text) from public, anon;
grant execute on function "better_supabase"."upsert_supplier_item"(uuid, uuid, uuid, text, text, bigint, text, text, text) to authenticated, service_role;
-- Deletes a supplier item. The variant it was promoted to stays.
create or replace function "better_supabase"."delete_supplier_item"(item uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."supplier_items" x where x."id" = delete_supplier_item.item;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."supplier_items" x where x."id" = delete_supplier_item.item;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_supplier_item"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_supplier_item"(uuid) to authenticated, service_role;
-- Searches supplier items by words in the code, the description and the
-- keywords, and by the start of a code. The caller's read access limits the
-- rows; the best matches come first.
create or replace function "better_supabase"."search_supplier_items"(tenant uuid, query text, supplier uuid default null, row_limit integer default 25)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(r.item order by r.rank desc, r.code), '[]'::jsonb)
from (
select x."code" as code,
ts_rank(x."keywords", websearch_to_tsquery('simple', $2)) + case when x."code" ilike replace(replace($2, '%', ''), '_', '') || '%' then 1 else 0 end as rank,
jsonb_build_object('id', x."id", 'supplierId', x."supplier_id", 'code', x."code", 'description', x."description", 'price', x."price", 'currency', x."currency", 'unit', x."unit", 'variantId', x."variant_id") as item
from "better_supabase"."supplier_items" x
where x."tenant_id" = $1 and ($3 is null or x."supplier_id" = $3)
and (x."keywords" @@ websearch_to_tsquery('simple', $2) or x."code" ilike replace(replace($2, '%', ''), '_', '') || '%')
order by 2 desc, 1
limit least(greatest(coalesce($4, 25), 1), 200)
) r
$$;
revoke execute on function "better_supabase"."search_supplier_items"(uuid, text, uuid, integer) from public, anon;
grant execute on function "better_supabase"."search_supplier_items"(uuid, text, uuid, integer) to authenticated, service_role;
-- Makes a supplier item a catalog product on first use: a product and a variant
-- (sku defaults to the supplier's code), the supplier's code as an identifier,
-- and the link back on the item. A second call returns the same variant with
-- created false.
create or replace function "better_supabase"."promote_supplier_item"(item uuid, sku text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_item "better_supabase"."supplier_items";
v_sku text;
v_slug text;
v_product uuid;
v_variant 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 * into v_item from "better_supabase"."supplier_items" x where x."id" = promote_supplier_item.item for update;
if not found then
raise exception 'supplier item not found' using errcode = 'P0002', hint = 'CATALOG_SUPPLIER_ITEM_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_item."tenant_id", 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if v_item."variant_id" is not null then
select y."product_id" into v_product from "better_supabase"."product_variants" y where y."id" = v_item."variant_id";
return jsonb_build_object('productId', v_product, 'variantId', v_item."variant_id", 'created', false);
end if;
v_sku := btrim(coalesce(nullif(promote_supplier_item.sku, ''), v_item."code"));
if length(v_sku) not between 1 and 100 then
raise exception 'the SKU must be 1 to 100 characters' using errcode = '22023', hint = 'CATALOG_SKU_INVALID';
end if;
v_slug := trim(both '-' from regexp_replace(lower(v_sku), '[^a-z0-9]+', '-', 'g'));
if v_slug = '' then
v_slug := 'item';
end if;
if exists (select 1 from "better_supabase"."products" x where x."tenant_id" = v_item."tenant_id" and x."slug" = v_slug) then
v_slug := v_slug || '-' || substr(v_item."id"::text, 1, 8);
end if;
begin
insert into "better_supabase"."products" as x ("tenant_id", "title", "slug", "description")
values (v_item."tenant_id", left(coalesce(nullif(v_item."description", ''), v_item."code"), 500), v_slug, v_item."description")
returning x."id" into v_product;
insert into "better_supabase"."product_variants" as y ("tenant_id", "product_id", "sku")
values (v_item."tenant_id", v_product, v_sku)
returning y."id" into v_variant;
exception when unique_violation then
raise exception 'another variant has this SKU' using errcode = '23505', hint = 'CATALOG_SKU_TAKEN';
end;
update "better_supabase"."supplier_items" x set "variant_id" = v_variant, "updated_at" = now() where x."id" = v_item."id";
insert into "better_supabase"."product_identifiers" ("tenant_id", "variant_id", "type", "value", "party_id")
values (v_item."tenant_id", v_variant, 'supplier', v_item."code", v_item."supplier_id")
on conflict do nothing;
null;
null;
return jsonb_build_object('productId', v_product, 'variantId', v_variant, 'created', true);
end;
$$;
revoke execute on function "better_supabase"."promote_supplier_item"(uuid, text) from public, anon;
grant execute on function "better_supabase"."promote_supplier_item"(uuid, text) to authenticated, service_role;
-- Sets a variant's Combined Nomenclature code (4 to 10 digits; spaces are
-- dropped), or clears it with null.
create or replace function "better_supabase"."set_variant_trade_code"(variant uuid, trade_code text)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_code text := nullif(replace(btrim(set_variant_trade_code.trade_code), ' ', ''), '');
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"."product_variants" x where x."id" = set_variant_trade_code.variant;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if v_code is not null and v_code !~ '^[0-9]{4,10}$' then
raise exception 'a trade code has 4 to 10 digits' using errcode = '22023', hint = 'CATALOG_TRADE_CODE_INVALID';
end if;
update "better_supabase"."product_variants" x set "trade_code" = v_code, "updated_at" = now() where x."id" = set_variant_trade_code.variant;
return true;
end;
$$;
revoke execute on function "better_supabase"."set_variant_trade_code"(uuid, text) from public, anon;
grant execute on function "better_supabase"."set_variant_trade_code"(uuid, text) to authenticated, service_role;
-- The import target of the supplier_item entity (ADR 0141): item.data is {
-- supplierId, row?, code?, description?, price?, currency?, unit?, keywords? }.
-- A row goes through the supplier's column mapping; the fields named next to
-- it win. Without supplierId the supplier or customer ref the item names, once
-- an earlier entity imported it, gives the supplier. price is in minor units. A key that is new but names a code the
-- supplier already has takes over that row.
create or replace function "better_supabase"."import_supplier_item"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_supplier_item.item ->> 'tenant')::uuid;
v_data jsonb := import_supplier_item.item -> 'data';
v_supplier uuid;
v_merged jsonb;
v_code text;
v_price text;
v_id uuid;
v_updated timestamptz;
begin
begin
v_supplier := coalesce(
nullif(v_data ->> 'supplierId', '')::uuid,
nullif(import_supplier_item.item -> 'resolved' ->> 'supplier', '')::uuid,
nullif(import_supplier_item.item -> 'resolved' ->> 'customer', '')::uuid
);
exception when invalid_text_representation then
raise exception 'supplierId must be a uuid' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_supplier is null then
raise exception 'a supplier item needs a supplierId, or a supplier or customer ref that an earlier entity imported' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
v_merged := (case when jsonb_typeof(v_data -> 'row') = 'object' then "better_supabase"."supplier_item_from_row"(v_tenant, v_supplier, v_data -> 'row') else '{}'::jsonb end) || (v_data - 'row' - 'supplierId');
v_code := nullif(btrim(v_merged ->> 'code'), '');
v_price := v_merged ->> 'price';
if v_code is null or length(v_code) > 100 then
raise exception 'a supplier item needs a code of up to 100 characters' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_price is not null and v_price !~ '^[0-9]{1,18}$' then
raise exception 'price is a whole number of minor units' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_merged ->> 'currency' is not null and "better_supabase"."currency_minor_units"(upper(v_merged ->> 'currency')) is null then
raise exception 'not an ISO 4217 currency code' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if import_supplier_item.subject_id is null then
insert into "better_supabase"."supplier_items" as x ("tenant_id", "supplier_id", "code", "description", "price", "currency", "unit", "keywords_text")
values (v_tenant, v_supplier, v_code, v_merged ->> 'description', v_price::bigint, upper(v_merged ->> 'currency'), v_merged ->> 'unit', v_merged ->> 'keywords')
on conflict ("tenant_id", "supplier_id", "code") do update set "description" = excluded."description", "price" = excluded."price",
"currency" = excluded."currency", "unit" = excluded."unit", "keywords_text" = excluded."keywords_text", "updated_at" = now()
returning x."id", x."updated_at" into v_id, v_updated;
else
update "better_supabase"."supplier_items" x set "supplier_id" = v_supplier, "code" = v_code, "description" = v_merged ->> 'description', "price" = v_price::bigint,
"currency" = upper(v_merged ->> 'currency'), "unit" = v_merged ->> 'unit', "keywords_text" = v_merged ->> 'keywords', "updated_at" = now()
where x."id" = import_supplier_item.subject_id::uuid and x."tenant_id" = v_tenant
returning x."id", x."updated_at" into v_id, v_updated;
if not found then
raise exception 'the supplier item no longer exists' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
end if;
return jsonb_build_object('subjectId', v_id::text, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_supplier_item"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_supplier_item"(uuid, jsonb, text) to service_role;
-- When a supplier item last changed, for the conflict check of imports.
create or replace function "better_supabase"."supplier_item_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."supplier_items" x where x."id" = $1::uuid
$$;
revoke execute on function "better_supabase"."supplier_item_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."supplier_item_updated_at"(text) to service_role;
-- The import target of the product_identifier entity: item.data is { sku or
-- variantId, type, value, partyId? }. A key that is new but names a code the
-- variant already has takes over that row.
create or replace function "better_supabase"."import_product_identifier"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_product_identifier.item ->> 'tenant')::uuid;
v_data jsonb := import_product_identifier.item -> 'data';
v_variant uuid;
v_type text := v_data ->> 'type';
v_value text := btrim(v_data ->> 'value');
v_party uuid;
v_id uuid;
v_updated timestamptz;
begin
begin
v_variant := nullif(v_data ->> 'variantId', '')::uuid;
v_party := nullif(v_data ->> 'partyId', '')::uuid;
exception when invalid_text_representation then
raise exception 'variantId and partyId must be uuids' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_variant is null and nullif(v_data ->> 'sku', '') is not 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 variant isn''t in this organization; name it with sku or variantId' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_type is null or v_type not in ('ean', 'supplier', 'manufacturer', 'other') then
raise exception 'the type must be one of ean, supplier, manufacturer, other' using errcode = '22023', hint = 'CATALOG_IDENTIFIER_TYPE_INVALID';
end if;
if v_value is null or length(v_value) not between 1 and 100 then
raise exception 'the value must be 1 to 100 characters' using errcode = '22023', hint = 'CATALOG_IDENTIFIER_INVALID';
end if;
if v_type = 'ean' and v_value !~ '^([0-9]{8}|[0-9]{12,14})$' then
raise exception 'an EAN has 8, 12, 13 or 14 digits' using errcode = '22023', hint = 'CATALOG_IDENTIFIER_INVALID';
end if;
if import_product_identifier.subject_id is null then
insert into "better_supabase"."product_identifiers" as x ("tenant_id", "variant_id", "type", "value", "party_id")
values (v_tenant, v_variant, v_type, v_value, v_party)
on conflict ("variant_id", "type", "value", coalesce("party_id", '00000000-0000-0000-0000-000000000000'::uuid)) do update set "updated_at" = now()
returning x."id", x."updated_at" into v_id, v_updated;
else
update "better_supabase"."product_identifiers" x set "variant_id" = v_variant, "type" = v_type, "value" = v_value, "party_id" = v_party, "updated_at" = now()
where x."id" = import_product_identifier.subject_id::uuid and x."tenant_id" = v_tenant
returning x."id", x."updated_at" into v_id, v_updated;
if not found then
raise exception 'the identifier no longer exists' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
end if;
return jsonb_build_object('subjectId', v_id::text, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_product_identifier"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_product_identifier"(uuid, jsonb, text) to service_role;
create or replace function "better_supabase"."product_identifier_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."product_identifiers" x where x."id" = $1::uuid
$$;
revoke execute on function "better_supabase"."product_identifier_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."product_identifier_updated_at"(text) to service_role;
-- Creates a discount group (group null) or renames one. kind is customer or
-- product and can't change; the code is unique per tenant and kind. Returns
-- its id and whether it was created.
create or replace function "better_supabase"."upsert_discount_group"(tenant uuid, "group" uuid, kind text, code text, name text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
v_created boolean := upsert_discount_group."group" is null;
v_code text := btrim(upsert_discount_group.code);
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_discount_group.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if upsert_discount_group.kind is null or upsert_discount_group.kind not in ('customer', 'product') then
raise exception 'the kind is customer or product' using errcode = '22023', hint = 'CATALOG_DISCOUNT_GROUP_INVALID';
end if;
if v_code is null or length(v_code) not between 1 and 50 or length(btrim(coalesce(upsert_discount_group.name, ''))) not between 1 and 200 then
raise exception 'a group needs a code of up to 50 and a name of up to 200 characters' using errcode = '22023', hint = 'CATALOG_DISCOUNT_GROUP_INVALID';
end if;
begin
if v_created then
insert into "better_supabase"."discount_groups" as x ("tenant_id", "kind", "code", "name")
values (upsert_discount_group.tenant, upsert_discount_group.kind, v_code, btrim(upsert_discount_group.name))
returning x."id" into v_id;
else
update "better_supabase"."discount_groups" x set "code" = v_code, "name" = btrim(upsert_discount_group.name), "updated_at" = now()
where x."id" = upsert_discount_group."group" and x."tenant_id" = upsert_discount_group.tenant and x."kind" = upsert_discount_group.kind
returning x."id" into v_id;
if v_id is null then
raise exception 'discount group not found' using errcode = 'P0002', hint = 'CATALOG_DISCOUNT_GROUP_NOT_FOUND';
end if;
end if;
exception when unique_violation then
raise exception 'a group of this kind already has this code' using errcode = '23505', hint = 'CATALOG_DISCOUNT_GROUP_EXISTS';
end;
return jsonb_build_object('id', v_id, 'created', v_created);
end;
$$;
revoke execute on function "better_supabase"."upsert_discount_group"(uuid, uuid, text, text, text) from public, anon;
grant execute on function "better_supabase"."upsert_discount_group"(uuid, uuid, text, text, text) to authenticated, service_role;
-- Deletes a group no rule uses. Its customers leave it and its variants lose
-- the group.
create or replace function "better_supabase"."delete_discount_group"("group" uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."discount_groups" x where x."id" = delete_discount_group."group";
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if exists (select 1 from "better_supabase"."discount_rules" y where y."customer_group_id" = delete_discount_group."group" or y."product_group_id" = delete_discount_group."group") then
raise exception 'a rule of the matrix still uses this group' using errcode = '23503', hint = 'CATALOG_DISCOUNT_GROUP_IN_USE';
end if;
delete from "better_supabase"."discount_groups" x where x."id" = delete_discount_group."group";
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_discount_group"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_discount_group"(uuid) to authenticated, service_role;
-- Puts a party (a company or person id) in a customer group, or takes it out
-- with null. A party is in one group; setting another moves it.
create or replace function "better_supabase"."set_party_discount_group"(tenant uuid, party text, "group" uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
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', set_party_discount_group.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if set_party_discount_group.party is null or length(btrim(set_party_discount_group.party)) not between 1 and 200 then
raise exception 'name the party by its id' using errcode = '22023', hint = 'CATALOG_DISCOUNT_PARTY_INVALID';
end if;
if set_party_discount_group."group" is null then
delete from "better_supabase"."discount_group_parties" x where x."tenant_id" = set_party_discount_group.tenant and x."party_id" = btrim(set_party_discount_group.party);
return true;
end if;
if not exists (select 1 from "better_supabase"."discount_groups" y where y."id" = set_party_discount_group."group" and y."tenant_id" = set_party_discount_group.tenant and y."kind" = 'customer') then
raise exception 'a party takes a customer group of its organization' using errcode = 'P0002', hint = 'CATALOG_DISCOUNT_GROUP_NOT_FOUND';
end if;
insert into "better_supabase"."discount_group_parties" as x ("tenant_id", "group_id", "party_id")
values (set_party_discount_group.tenant, set_party_discount_group."group", btrim(set_party_discount_group.party))
on conflict ("tenant_id", "party_id") do update set "group_id" = excluded."group_id";
return true;
end;
$$;
revoke execute on function "better_supabase"."set_party_discount_group"(uuid, text, uuid) from public, anon;
grant execute on function "better_supabase"."set_party_discount_group"(uuid, text, uuid) to authenticated, service_role;
-- Puts a variant in a product group, or takes it out with null.
create or replace function "better_supabase"."set_variant_discount_group"(variant uuid, "group" uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."product_variants" x where x."id" = set_variant_discount_group.variant;
if v_tenant is null then
raise exception 'variant not found' using errcode = 'P0002', hint = 'CATALOG_VARIANT_NOT_FOUND';
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
if set_variant_discount_group."group" is not null and not exists (
select 1 from "better_supabase"."discount_groups" y where y."id" = set_variant_discount_group."group" and y."tenant_id" = v_tenant and y."kind" = 'product') then
raise exception 'a variant takes a product group of its organization' using errcode = 'P0002', hint = 'CATALOG_DISCOUNT_GROUP_NOT_FOUND';
end if;
update "better_supabase"."product_variants" x set "discount_group_id" = set_variant_discount_group."group", "updated_at" = now() where x."id" = set_variant_discount_group.variant;
return true;
end;
$$;
revoke execute on function "better_supabase"."set_variant_discount_group"(uuid, uuid) from public, anon;
grant execute on function "better_supabase"."set_variant_discount_group"(uuid, uuid) to authenticated, service_role;
-- The checks of a rule's attributes, shared by the function and the import.
create or replace function "better_supabase"."discount_rule_check"(tenant uuid, attrs jsonb)
returns void
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_customer uuid;
v_product uuid;
begin
begin
v_customer := nullif(discount_rule_check.attrs ->> 'customerGroupId', '')::uuid;
v_product := nullif(discount_rule_check.attrs ->> 'productGroupId', '')::uuid;
perform (discount_rule_check.attrs ->> 'validFrom')::date, (discount_rule_check.attrs ->> 'validTo')::date;
exception when invalid_text_representation or invalid_datetime_format or datetime_field_overflow then
raise exception 'group ids are uuids and dates are YYYY-MM-DD' using errcode = '22023', hint = 'CATALOG_DISCOUNT_RULE_INVALID';
end;
if v_customer is not null and not exists (select 1 from "better_supabase"."discount_groups" y where y."id" = v_customer and y."tenant_id" = discount_rule_check.tenant and y."kind" = 'customer') then
raise exception 'customerGroupId isn''t a customer group of this organization' using errcode = 'P0002', hint = 'CATALOG_DISCOUNT_GROUP_NOT_FOUND';
end if;
if v_product is not null and not exists (select 1 from "better_supabase"."discount_groups" y where y."id" = v_product and y."tenant_id" = discount_rule_check.tenant and y."kind" = 'product') then
raise exception 'productGroupId isn''t a product group of this organization' using errcode = 'P0002', hint = 'CATALOG_DISCOUNT_GROUP_NOT_FOUND';
end if;
if coalesce(discount_rule_check.attrs ->> 'discountBps', '0') !~ '^[0-9]{1,5}$' or coalesce(discount_rule_check.attrs ->> 'discountBps', '0')::integer > 10000 then
raise exception 'discountBps is a whole number from 0 to 10000' using errcode = '22023', hint = 'CATALOG_DISCOUNT_RULE_INVALID';
end if;
if coalesce(discount_rule_check.attrs ->> 'minQuantity', '0') !~ '^[0-9]{1,14}([.][0-9]{1,4})?$' then
raise exception 'minQuantity is zero or more' using errcode = '22023', hint = 'CATALOG_DISCOUNT_RULE_INVALID';
end if;
if (discount_rule_check.attrs ->> 'fixedPrice') is not null and discount_rule_check.attrs ->> 'fixedPrice' !~ '^[0-9]{1,18}$' then
raise exception 'fixedPrice is a whole number of minor units' using errcode = '22023', hint = 'CATALOG_DISCOUNT_RULE_INVALID';
end if;
if ((discount_rule_check.attrs ->> 'fixedPrice') is null) <> ((discount_rule_check.attrs ->> 'currency') is null)
or ((discount_rule_check.attrs ->> 'currency') is not null and (discount_rule_check.attrs ->> 'currency') !~ '^[A-Z]{3}$') then
raise exception 'a fixed price comes with its ISO 4217 currency, and neither without the other' using errcode = '22023', hint = 'CATALOG_DISCOUNT_RULE_INVALID';
end if;
if (discount_rule_check.attrs ->> 'validFrom') is not null and (discount_rule_check.attrs ->> 'validTo') is not null
and (discount_rule_check.attrs ->> 'validTo')::date < (discount_rule_check.attrs ->> 'validFrom')::date then
raise exception 'validTo is on or after validFrom' using errcode = '22023', hint = 'CATALOG_DISCOUNT_RULE_INVALID';
end if;
end;
$$;
revoke execute on function "better_supabase"."discount_rule_check"(uuid, jsonb) from public, anon, authenticated;
-- Creates a rule of the discount matrix (rule null) or replaces one. attrs: {
-- customerGroupId?, productGroupId?, validFrom?, validTo?, minQuantity?,
-- discountBps?, fixedPrice? (minor units as text), currency? }. A rule with the
-- same groups, start date and minimum quantity is one rule: the call updates
-- it. Returns its id and whether it was created.
create or replace function "better_supabase"."upsert_discount_rule"(tenant uuid, rule uuid, attrs jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_attrs jsonb := coalesce(upsert_discount_rule.attrs, '{}'::jsonb);
v_id uuid;
v_created boolean := true;
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_discount_rule.tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
perform "better_supabase"."discount_rule_check"(upsert_discount_rule.tenant, v_attrs);
if upsert_discount_rule.rule is not null then
update "better_supabase"."discount_rules" x set
"customer_group_id" = nullif(v_attrs ->> 'customerGroupId', '')::uuid, "product_group_id" = nullif(v_attrs ->> 'productGroupId', '')::uuid,
"valid_from" = (v_attrs ->> 'validFrom')::date, "valid_to" = (v_attrs ->> 'validTo')::date,
"min_quantity" = coalesce((v_attrs ->> 'minQuantity')::numeric, 0), "discount_bps" = coalesce((v_attrs ->> 'discountBps')::integer, 0),
"fixed_price" = (v_attrs ->> 'fixedPrice')::bigint, "currency" = v_attrs ->> 'currency', "updated_at" = now()
where x."id" = upsert_discount_rule.rule and x."tenant_id" = upsert_discount_rule.tenant
returning x."id" into v_id;
if v_id is null then
raise exception 'discount rule not found' using errcode = 'P0002', hint = 'CATALOG_DISCOUNT_RULE_NOT_FOUND';
end if;
return jsonb_build_object('id', v_id, 'created', false);
end if;
insert into "better_supabase"."discount_rules" as x ("tenant_id", "customer_group_id", "product_group_id", "valid_from", "valid_to", "min_quantity", "discount_bps", "fixed_price", "currency")
values (upsert_discount_rule.tenant, nullif(v_attrs ->> 'customerGroupId', '')::uuid, nullif(v_attrs ->> 'productGroupId', '')::uuid,
(v_attrs ->> 'validFrom')::date, (v_attrs ->> 'validTo')::date, coalesce((v_attrs ->> 'minQuantity')::numeric, 0),
coalesce((v_attrs ->> 'discountBps')::integer, 0), (v_attrs ->> 'fixedPrice')::bigint, v_attrs ->> 'currency')
on conflict ("tenant_id", coalesce("customer_group_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("product_group_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("valid_from", date '0001-01-01'), "min_quantity") do update set
"valid_to" = excluded."valid_to", "discount_bps" = excluded."discount_bps", "fixed_price" = excluded."fixed_price",
"currency" = excluded."currency", "updated_at" = now()
returning x."id", (xmax = 0) into v_id, v_created;
return jsonb_build_object('id', v_id, 'created', v_created);
end;
$$;
revoke execute on function "better_supabase"."upsert_discount_rule"(uuid, uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."upsert_discount_rule"(uuid, uuid, jsonb) to authenticated, service_role;
-- Deletes a rule of the matrix.
create or replace function "better_supabase"."delete_discount_rule"(rule uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant 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" into v_tenant from "better_supabase"."discount_rules" x where x."id" = delete_discount_rule.rule;
if v_tenant is null then
return false;
end if;
if not (auth.role() = 'service_role' or coalesce(better_supabase.can('tenant', v_tenant, 'catalog.manage'), false)) then
raise exception 'not allowed to manage the catalog' using errcode = '42501', hint = 'CATALOG_FORBIDDEN';
end if;
delete from "better_supabase"."discount_rules" x where x."id" = delete_discount_rule.rule;
return true;
end;
$$;
revoke execute on function "better_supabase"."delete_discount_rule"(uuid) from public, anon;
grant execute on function "better_supabase"."delete_discount_rule"(uuid) to authenticated, service_role;
-- The discount a line gets: { discountBps, fixedPrice, currency, ruleId }.
-- party is the customer's id, product a catalog variant, quantity the line's
-- and on the date the document prices at. A rule applies when its customer
-- group is the party's (or it has none), its product group is the variant's
-- (or it has none), the date is inside its window and quantity reaches its
-- minimum. The most specific rule wins: both groups, then the customer group,
-- then the product group, then neither. Among rules equally specific the
-- highest quantity break wins, then the latest start date. With a currency, a
-- rule whose fixed price is in another currency is skipped. No rule gives a
-- discountBps of 0 and a null ruleId. It reads as the caller.
create or replace function "better_supabase"."resolve_line_discount"(tenant uuid, party text, product uuid, quantity numeric, "on" date, currency text default null)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
with scope as (
select (select x."group_id" from "better_supabase"."discount_group_parties" x where x."tenant_id" = $1 and x."party_id" = $2) as customer_group,
(select y."discount_group_id" from "better_supabase"."product_variants" y where y."id" = $3 and y."tenant_id" = $1) as item_group
),
matched as (
select r."id" as id, r."discount_bps" as discount_bps, r."fixed_price" as fixed_price, r."currency" as currency
from "better_supabase"."discount_rules" r cross join scope s
where r."tenant_id" = $1
and (r."customer_group_id" is null or r."customer_group_id" = s.customer_group)
and (r."product_group_id" is null or r."product_group_id" = s.item_group)
and (r."valid_from" is null or r."valid_from" <= coalesce($5, current_date))
and (r."valid_to" is null or r."valid_to" >= coalesce($5, current_date))
and r."min_quantity" <= coalesce($4, 1)
and (r."fixed_price" is null or $6 is null or r."currency" = upper($6))
order by (case when r."customer_group_id" is not null then 2 else 0 end) + (case when r."product_group_id" is not null then 1 else 0 end) desc,
r."min_quantity" desc, r."valid_from" desc nulls last, r."created_at", r."id"
limit 1
)
select coalesce((select jsonb_build_object('discountBps', m.discount_bps, 'fixedPrice', m.fixed_price::text, 'currency', m.currency, 'ruleId', m.id) from matched m),
jsonb_build_object('discountBps', 0, 'fixedPrice', null, 'currency', null, 'ruleId', null))
$$;
revoke execute on function "better_supabase"."resolve_line_discount"(uuid, text, uuid, numeric, date, text) from public, anon;
grant execute on function "better_supabase"."resolve_line_discount"(uuid, text, uuid, numeric, date, text) to authenticated, service_role;
-- The import target of the discount_group entity: item.data is { kind, code,
-- name, parties? } where parties lists the ids of a customer group's members
-- and replaces them. A new key with a code the tenant already has for that kind
-- takes over that group.
create or replace function "better_supabase"."import_discount_group"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_discount_group.item ->> 'tenant')::uuid;
v_data jsonb := import_discount_group.item -> 'data';
v_kind text := v_data ->> 'kind';
v_code text := btrim(v_data ->> 'code');
v_name text := btrim(coalesce(v_data ->> 'name', v_data ->> 'code'));
v_id uuid;
v_updated timestamptz;
begin
if v_kind is null or v_kind not in ('customer', 'product') or v_code is null or length(v_code) not between 1 and 50 or length(v_name) not between 1 and 200 then
raise exception 'a discount group needs a kind (customer or product), a code and a name' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_data ? 'parties' and (v_kind <> 'customer' or jsonb_typeof(v_data -> 'parties') <> 'array') then
raise exception 'parties is a list on a customer group' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if import_discount_group.subject_id is null then
insert into "better_supabase"."discount_groups" as x ("tenant_id", "kind", "code", "name")
values (v_tenant, v_kind, v_code, v_name)
on conflict ("tenant_id", "kind", "code") do update set "name" = excluded."name", "updated_at" = now()
returning x."id", x."updated_at" into v_id, v_updated;
else
begin
update "better_supabase"."discount_groups" x set "kind" = v_kind, "code" = v_code, "name" = v_name, "updated_at" = now()
where x."id" = import_discount_group.subject_id::uuid and x."tenant_id" = v_tenant
returning x."id", x."updated_at" into v_id, v_updated;
exception when unique_violation then
raise exception 'another group of this kind has this code' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_id is null then
raise exception 'the discount group no longer exists' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
end if;
if v_data ? 'parties' then
delete from "better_supabase"."discount_group_parties" x where x."group_id" = v_id and x."party_id" not in (select jsonb_array_elements_text(v_data -> 'parties'));
insert into "better_supabase"."discount_group_parties" as x ("tenant_id", "group_id", "party_id")
select v_tenant, v_id, btrim(p) from jsonb_array_elements_text(v_data -> 'parties') p where length(btrim(p)) between 1 and 200
on conflict ("tenant_id", "party_id") do update set "group_id" = excluded."group_id";
end if;
return jsonb_build_object('subjectId', v_id::text, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_discount_group"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_discount_group"(uuid, jsonb, text) to service_role;
-- When a discount group last changed, for the conflict check of imports.
create or replace function "better_supabase"."discount_group_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."discount_groups" x where x."id" = $1::uuid
$$;
revoke execute on function "better_supabase"."discount_group_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."discount_group_updated_at"(text) to service_role;
-- The import target of the discount_rule entity: item.data is {
-- customerGroup?, productGroup? (group codes) or customerGroupId?,
-- productGroupId?, validFrom?, validTo?, minQuantity?, discountBps?,
-- fixedPrice?, currency? }. Import groups first.
create or replace function "better_supabase"."import_discount_rule"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_discount_rule.item ->> 'tenant')::uuid;
v_data jsonb := import_discount_rule.item -> 'data';
v_customer_id uuid;
v_product_id uuid;
v_customer_code text := nullif(btrim(v_data ->> 'customerGroup'), '');
v_product_code text := nullif(btrim(v_data ->> 'productGroup'), '');
v_customer uuid;
v_product uuid;
v_attrs jsonb;
v_id uuid;
v_updated timestamptz;
begin
begin
v_customer_id := nullif(v_data ->> 'customerGroupId', '')::uuid;
v_product_id := nullif(v_data ->> 'productGroupId', '')::uuid;
exception when invalid_text_representation then
raise exception 'group ids are uuids' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
v_customer := (select y."id" from "better_supabase"."discount_groups" y
where y."tenant_id" = v_tenant and y."kind" = 'customer'
and ((v_customer_id is not null and y."id" = v_customer_id) or (v_customer_id is null and v_customer_code is not null and y."code" = v_customer_code)));
v_product := (select y."id" from "better_supabase"."discount_groups" y
where y."tenant_id" = v_tenant and y."kind" = 'product'
and ((v_product_id is not null and y."id" = v_product_id) or (v_product_id is null and v_product_code is not null and y."code" = v_product_code)));
if (v_customer_id is not null or v_customer_code is not null) and v_customer is null then
raise exception 'the customer group isn''t in this organization; import the groups first' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if (v_product_id is not null or v_product_code is not null) and v_product is null then
raise exception 'the product group isn''t in this organization; import the groups first' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
v_attrs := jsonb_strip_nulls(jsonb_build_object('customerGroupId', v_customer, 'productGroupId', v_product, 'validFrom', v_data -> 'validFrom', 'validTo', v_data -> 'validTo',
'minQuantity', v_data -> 'minQuantity', 'discountBps', v_data -> 'discountBps', 'fixedPrice', v_data -> 'fixedPrice', 'currency', v_data -> 'currency'));
begin
perform "better_supabase"."discount_rule_check"(v_tenant, v_attrs);
exception when sqlstate '22023' or sqlstate 'P0002' then
raise exception 'the rule isn''t valid: check the groups, dates, discountBps, minQuantity and fixed price' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if import_discount_rule.subject_id is null then
insert into "better_supabase"."discount_rules" as x ("tenant_id", "customer_group_id", "product_group_id", "valid_from", "valid_to", "min_quantity", "discount_bps", "fixed_price", "currency")
values (v_tenant, v_customer, v_product, (v_attrs ->> 'validFrom')::date, (v_attrs ->> 'validTo')::date, coalesce((v_attrs ->> 'minQuantity')::numeric, 0),
coalesce((v_attrs ->> 'discountBps')::integer, 0), (v_attrs ->> 'fixedPrice')::bigint, v_attrs ->> 'currency')
on conflict ("tenant_id", coalesce("customer_group_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("product_group_id", '00000000-0000-4000-8000-000000000000'::uuid), coalesce("valid_from", date '0001-01-01'), "min_quantity") do update set
"valid_to" = excluded."valid_to", "discount_bps" = excluded."discount_bps", "fixed_price" = excluded."fixed_price",
"currency" = excluded."currency", "updated_at" = now()
returning x."id", x."updated_at" into v_id, v_updated;
else
begin
update "better_supabase"."discount_rules" x set "customer_group_id" = v_customer, "product_group_id" = v_product, "valid_from" = (v_attrs ->> 'validFrom')::date, "valid_to" = (v_attrs ->> 'validTo')::date,
"min_quantity" = coalesce((v_attrs ->> 'minQuantity')::numeric, 0), "discount_bps" = coalesce((v_attrs ->> 'discountBps')::integer, 0),
"fixed_price" = (v_attrs ->> 'fixedPrice')::bigint, "currency" = v_attrs ->> 'currency', "updated_at" = now()
where x."id" = import_discount_rule.subject_id::uuid and x."tenant_id" = v_tenant
returning x."id", x."updated_at" into v_id, v_updated;
exception when unique_violation then
raise exception 'another rule has the same groups, start date and minimum quantity' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end;
if v_id is null then
raise exception 'the discount rule no longer exists' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
end if;
return jsonb_build_object('subjectId', v_id::text, 'updatedAt', v_updated);
end;
$$;
revoke execute on function "better_supabase"."import_discount_rule"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_discount_rule"(uuid, jsonb, text) to service_role;
create or replace function "better_supabase"."discount_rule_updated_at"(subject_id text)
returns timestamptz
language sql
stable
security definer
set search_path = ''
as $$
select x."updated_at" from "better_supabase"."discount_rules" x where x."id" = $1::uuid
$$;
revoke execute on function "better_supabase"."discount_rule_updated_at"(text) from public, anon, authenticated;
grant execute on function "better_supabase"."discount_rule_updated_at"(text) to service_role;
-- Puts a party in a customer group from an import. item.data is { party,
-- groupId? , groupCode? }. A missing group removes the party from its group.
create or replace function "better_supabase"."import_party_discount_group"(run uuid, item jsonb, subject_id text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid := (import_party_discount_group.item ->> 'tenant')::uuid;
v_data jsonb := import_party_discount_group.item -> 'data';
v_party text := btrim(coalesce(nullif(v_data ->> 'party', ''), import_party_discount_group.subject_id));
v_group uuid := nullif(v_data ->> 'groupId', '')::uuid;
v_code text := nullif(btrim(v_data ->> 'groupCode'), '');
begin
if v_party is null or length(v_party) not between 1 and 200 then
raise exception 'a party discount group names the party' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
if v_group is null and v_code is not null then
select x."id" into v_group
from "better_supabase"."discount_groups" x
where x."tenant_id" = v_tenant and x."kind" = 'customer' and x."code" = v_code;
end if;
if v_group is null and v_code is not null then
raise exception 'no customer discount group has this code' using errcode = '22023', hint = 'IMPORT_ITEM_INVALID';
end if;
perform "better_supabase"."set_party_discount_group"(v_tenant, v_party, v_group);
return jsonb_build_object(
'subjectId', v_party,
'updatedAt', (select x."created_at" from "better_supabase"."discount_group_parties" x where x."tenant_id" = v_tenant and x."party_id" = v_party)
);
end;
$$;
revoke execute on function "better_supabase"."import_party_discount_group"(uuid, jsonb, text) from public, anon, authenticated;
grant execute on function "better_supabase"."import_party_discount_group"(uuid, jsonb, text) to 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"."products" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."products" 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"."products" 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"."products" 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"."product_options" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_options" 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"."product_options" 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"."product_options" 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"."product_option_values" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_option_values" 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"."product_option_values" 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"."product_option_values" 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"."product_variants" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_variants" 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"."product_variants" 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"."product_variants" 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"."product_variant_values" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_variant_values" 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"."product_variant_values" 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"."product_variant_values" 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"."catalog_price_lists" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."catalog_price_lists" 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"."catalog_price_lists" 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"."catalog_price_lists" 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"."product_prices" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_prices" 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"."product_prices" 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"."product_prices" 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"."catalog_categories" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."catalog_categories" 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"."catalog_categories" 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"."catalog_categories" 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"."product_categories" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_categories" 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"."product_categories" 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"."product_categories" 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"."product_collections" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_collections" 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"."product_collections" 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"."product_collections" 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"."collection_products" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."collection_products" 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"."collection_products" 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"."collection_products" 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"."catalog_storefronts" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."catalog_storefronts" 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"."catalog_storefronts" 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"."catalog_storefronts" 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"."catalog_channels" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."catalog_channels" 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"."catalog_channels" 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"."catalog_channels" 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"."catalog_channel_products" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."catalog_channel_products" 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"."catalog_channel_products" 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"."catalog_channel_products" 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"."product_translations" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_translations" 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"."product_translations" 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"."product_translations" 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"."product_variant_translations" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_variant_translations" 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"."product_variant_translations" 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"."product_variant_translations" 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"."product_identifiers" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_identifiers" 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"."product_identifiers" 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"."product_identifiers" 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"."product_relations" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."product_relations" 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"."product_relations" 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"."product_relations" 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"."supplier_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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."supplier_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"."supplier_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"."supplier_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"."supplier_item_mappings" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."supplier_item_mappings" 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"."supplier_item_mappings" 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"."supplier_item_mappings" 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"."discount_groups" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."discount_groups" 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"."discount_groups" 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"."discount_groups" 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"."discount_group_parties" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."discount_group_parties" 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"."discount_group_parties" 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"."discount_group_parties" 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"."discount_rules" 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('catalog.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."discount_rules" 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"."discount_rules" 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"."discount_rules" 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/catalog, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- catalog.price_changed
- product.archived
- product.created
- product.purged
- product.restored
- product.status_changed
- product.updated
- product_variant.created
- product_variant.purged
- product_variant.updated
- storefront.published
- storefront.unpublished
Dependencies
- Required: the install command adds it too
- Works with: optional
Requires
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 Inventoryinventory 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. 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.