
-- KBX v8 reference process coverage. Source modules remain owners of their business state.
create schema if not exists oms;
create schema if not exists erp;

create table if not exists oms.claims (
  id uuid primary key,
  tenant_id uuid not null,
  claim_no varchar(50) not null,
  order_id uuid not null,
  order_no varchar(50) not null,
  channel_name varchar(100) not null,
  type varchar(20) not null,
  reason varchar(300) not null,
  requested_qty numeric(18,4) not null check (requested_qty > 0),
  status varchar(30) not null,
  owner_name varchar(100),
  requested_at timestamptz not null,
  version bigint not null default 1,
  unique(tenant_id, claim_no)
);
create or replace view oms.claim_search_projection as
select id,claim_no,order_no,channel_name,type,reason,requested_qty,status,owner_name,requested_at from oms.claims;

create table if not exists erp.purchase_orders (
  id uuid primary key,
  tenant_id uuid not null,
  purchase_no varchar(50) not null,
  purchase_date date not null,
  supplier_id uuid not null,
  warehouse_id uuid not null,
  status varchar(30) not null,
  version bigint not null default 1,
  unique(tenant_id,purchase_no)
);
create table if not exists erp.purchase_order_lines (
  id uuid primary key, purchase_order_id uuid not null references erp.purchase_orders(id), item_id uuid not null,
  quantity numeric(18,4) not null check(quantity>0), unit_price numeric(18,4) not null check(unit_price>=0), due_date date
);

create table if not exists erp.inventory_moves (
  id uuid primary key, tenant_id uuid not null, move_no varchar(50) not null, move_date date not null,
  from_warehouse_id uuid not null, to_warehouse_id uuid not null, status varchar(30) not null, version bigint not null default 1,
  check(from_warehouse_id <> to_warehouse_id), unique(tenant_id,move_no)
);
create table if not exists erp.inventory_move_lines (
  id uuid primary key, move_id uuid not null references erp.inventory_moves(id), item_id uuid not null,
  move_qty numeric(18,4) not null check(move_qty>0), lot_no varchar(100), remark varchar(500)
);
