# `PhoenixKitCatalogue.Catalogue`
[🔗](https://github.com/BeamLabEU/phoenix_kit_catalogue/blob/0.1.14/lib/phoenix_kit_catalogue/catalogue.ex#L1)

Context module for managing catalogues, manufacturers, suppliers, categories, and items.

## Soft-Delete System

Catalogues, categories, and items support soft-delete via a `status` field set to `"deleted"`.
Manufacturers and suppliers use hard-delete only (they are reference data).

### Cascade behaviour

**Downward cascade on trash/permanently_delete:**
- Trashing a catalogue → trashes all its categories and their items
- Trashing a category → trashes all its items
- Permanently deleting follows the same cascade but removes from DB

**Upward cascade on restore:**
- Restoring an item → restores its parent category if deleted
- Restoring a category → restores its parent catalogue if deleted, plus all items

All cascading operations are wrapped in database transactions.

## Usage from IEx

    alias PhoenixKitCatalogue.Catalogue

    # Create a full hierarchy
    {:ok, cat} = Catalogue.create_catalogue(%{name: "Kitchen"})
    {:ok, category} = Catalogue.create_category(%{name: "Frames", catalogue_uuid: cat.uuid})
    {:ok, item} = Catalogue.create_item(%{name: "Oak Panel", category_uuid: category.uuid, base_price: 25.50})

    # Soft-delete and restore
    {:ok, _} = Catalogue.trash_catalogue(cat)   # cascades to category + item
    {:ok, _} = Catalogue.restore_catalogue(cat)  # cascades back

    # Move operations
    {:ok, _} = Catalogue.move_category_to_catalogue(category, other_catalogue_uuid)
    {:ok, _} = Catalogue.move_item_to_category(item, other_category_uuid)

## Smart catalogues

For an end-to-end walkthrough of integrating smart catalogues
(`kind: "smart"` items priced as functions of other catalogues), see
the [Smart Catalogues guide](smart_catalogues.md).

# `catalogue_reference_count`

# `catalogue_rule_map`

# `category_count_for_catalogue`

# `category_counts_by_catalogue`

# `change_catalogue`

```elixir
@spec change_catalogue(PhoenixKitCatalogue.Schemas.Catalogue.t(), map()) ::
  Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Catalogue.t())
```

Returns a changeset for tracking catalogue changes.

# `change_catalogue_rule`

# `change_category`

```elixir
@spec change_category(PhoenixKitCatalogue.Schemas.Category.t(), map()) ::
  Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Category.t())
```

Returns a changeset for tracking category changes.

# `change_item`

```elixir
@spec change_item(PhoenixKitCatalogue.Schemas.Item.t(), map()) ::
  Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Item.t())
```

Returns a changeset for tracking item changes.

# `change_manufacturer`

# `change_supplier`

# `count_search_items`

# `count_search_items_in_catalogue`

# `count_search_items_in_category`

# `create_catalogue`

```elixir
@spec create_catalogue(
  map(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Catalogue.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Catalogue.t())}
```

Creates a catalogue.

## Required attributes

  * `:name` — catalogue name (1-255 chars)

## Optional attributes

  * `:description` — text description
  * `:status` — `"active"` (default), `"archived"`, or `"deleted"`
  * `:data` — flexible JSON map

## Examples

    Catalogue.create_catalogue(%{name: "Kitchen Furniture"})

# `create_catalogue_rule`

# `create_category`

```elixir
@spec create_category(
  map(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Category.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Category.t())}
```

Creates a category within a catalogue.

## Required attributes

  * `:name` — category name (1-255 chars)
  * `:catalogue_uuid` — the parent catalogue

## Optional attributes

  * `:description`, `:position` (default 0), `:status` (`"active"` or `"deleted"`)
  * `:data` — flexible JSON map

## Examples

    Catalogue.create_category(%{name: "Frames", catalogue_uuid: catalogue.uuid})

# `create_item`

```elixir
@spec create_item(
  map(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Item.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Item.t())}
```

Creates an item.

## Required attributes

  * `:name` — item name (1-255 chars)
  * `:catalogue_uuid` — the parent catalogue (required). Auto-derived from
    `:category_uuid` when omitted and a category is provided.

## Optional attributes

  * `:description` — text description
  * `:sku` — stock keeping unit (unique, max 100 chars)
  * `:base_price` — decimal, must be >= 0 (cost/purchase price before markup)
  * `:unit` — `"piece"` (default), `"m2"`, or `"running_meter"`
  * `:status` — `"active"` (default), `"inactive"`, `"discontinued"`, or `"deleted"`
  * `:category_uuid` — the parent category (optional — leave nil for uncategorized items)
  * `:manufacturer_uuid` — the manufacturer (optional)
  * `:data` — flexible JSON map

## Examples

    Catalogue.create_item(%{name: "Oak Panel 18mm", catalogue_uuid: cat.uuid, base_price: 25.50})
    Catalogue.create_item(%{name: "Hinge", category_uuid: category.uuid, manufacturer_uuid: m.uuid})

# `create_manufacturer`

# `create_supplier`

# `delete_catalogue`

```elixir
@spec delete_catalogue(
  PhoenixKitCatalogue.Schemas.Catalogue.t(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Catalogue.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Catalogue.t())}
```

Hard-deletes a catalogue. Prefer `trash_catalogue/1` for soft-delete.

# `delete_catalogue_rule`

# `delete_category`

```elixir
@spec delete_category(
  PhoenixKitCatalogue.Schemas.Category.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Category.t()} | {:error, term()}
```

Hard-deletes a category. Prefer `trash_category/1` for soft-delete.

# `delete_item`

```elixir
@spec delete_item(
  PhoenixKitCatalogue.Schemas.Item.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Item.t()} | {:error, term()}
```

Hard-deletes an item. Prefer `trash_item/1` for soft-delete.

# `delete_manufacturer`

# `delete_supplier`

# `deleted_catalogue_count`

```elixir
@spec deleted_catalogue_count() :: non_neg_integer()
```

Returns the count of soft-deleted catalogues.

# `deleted_category_count_for_catalogue`

# `deleted_count_for_catalogue`

# `deleted_item_count_for_catalogue`

# `fetch_catalogue!`

```elixir
@spec fetch_catalogue!(Ecto.UUID.t()) :: PhoenixKitCatalogue.Schemas.Catalogue.t()
```

Fetches a catalogue by UUID without preloading categories or items.
Raises `Ecto.NoResultsError` if not found. Prefer this over
`get_catalogue!/2` in read paths that don't need the nested preloads
(e.g. the infinite-scroll detail view, which pages categories and
items separately).

# `get_catalogue`

```elixir
@spec get_catalogue(Ecto.UUID.t()) :: PhoenixKitCatalogue.Schemas.Catalogue.t() | nil
```

Fetches a catalogue by UUID without preloads. Returns `nil` if not found.

# `get_catalogue!`

```elixir
@spec get_catalogue!(
  Ecto.UUID.t(),
  keyword()
) :: PhoenixKitCatalogue.Schemas.Catalogue.t()
```

Fetches a catalogue by UUID with preloaded categories and items.
Raises `Ecto.NoResultsError` if not found.

## Options

  * `:mode` — `:active` (default) or `:deleted`
    - `:active` — preloads non-deleted categories with non-deleted items
    - `:deleted` — preloads all categories with only deleted items
      (so you can see which categories contain trashed items)

## Examples

    Catalogue.get_catalogue!(uuid)                  # active view
    Catalogue.get_catalogue!(uuid, mode: :deleted)  # deleted view

# `get_catalogue_rule`

# `get_category`

```elixir
@spec get_category(Ecto.UUID.t()) :: PhoenixKitCatalogue.Schemas.Category.t() | nil
```

Fetches a category by UUID. Returns `nil` if not found.

# `get_category!`

```elixir
@spec get_category!(Ecto.UUID.t()) :: PhoenixKitCatalogue.Schemas.Category.t()
```

Fetches a category by UUID. Raises `Ecto.NoResultsError` if not found.

# `get_item`

```elixir
@spec get_item(Ecto.UUID.t()) :: PhoenixKitCatalogue.Schemas.Item.t() | nil
```

Fetches an item by UUID without preloads. Returns `nil` if not found.

# `get_item!`

```elixir
@spec get_item!(Ecto.UUID.t()) :: PhoenixKitCatalogue.Schemas.Item.t()
```

Fetches an item by UUID with preloaded category and manufacturer.
Raises `Ecto.NoResultsError` if not found.

# `get_manufacturer`

# `get_manufacturer!`

# `get_supplier`

# `get_supplier!`

# `get_translation`

# `item_count_for_catalogue`

# `item_count_for_category`

```elixir
@spec item_count_for_category(
  Ecto.UUID.t(),
  keyword()
) :: non_neg_integer()
```

Counts items in a single category (ignoring its catalogue scope).

Used by the infinite-scroll detail view to show the total under each
category header (the number in `"Category Name (N items)"`) without
loading the items themselves.

## Options

  * `:mode` — `:active` (default) or `:deleted`

# `item_counts_by_catalogue`

# `item_counts_by_category_for_catalogue`

```elixir
@spec item_counts_by_category_for_catalogue(
  Ecto.UUID.t(),
  keyword()
) :: %{required(Ecto.UUID.t()) =&gt; non_neg_integer()}
```

Returns a map of `%{category_uuid => item_count}` for every category
in a catalogue in a single grouped query. Used by the infinite-scroll
detail view so each category card can show its total count without a
separate per-card round trip.

Items without a category (uncategorized) are excluded here — use
`uncategorized_count_for_catalogue/2` for those.

## Options

  * `:mode` — `:active` (default) or `:deleted`

# `item_pricing`

```elixir
@spec item_pricing(PhoenixKitCatalogue.Schemas.Item.t()) :: %{
  base_price: Decimal.t() | nil,
  catalogue_markup: Decimal.t() | nil,
  item_markup: Decimal.t() | nil,
  markup_percentage: Decimal.t() | nil,
  sale_price: Decimal.t() | nil,
  catalogue_discount: Decimal.t() | nil,
  item_discount: Decimal.t() | nil,
  discount_percentage: Decimal.t() | nil,
  discount_amount: Decimal.t() | nil,
  final_price: Decimal.t() | nil
}
```

Returns the full pricing breakdown for an item within its catalogue.

Resolves both the catalogue's markup and discount (loading the
catalogue association once if needed), then computes the sale price
(after markup) and final price (after discount). The chain is
`base → markup → discount`:

    sale_price  = base_price * (1 + effective_markup   / 100)
    final_price = sale_price  * (1 -  effective_discount / 100)

Never raises — if the catalogue can't be loaded (e.g. DB hiccup), falls
back to 0% markup and 0% discount and logs a warning so the caller
still gets a renderable result instead of crashing a template.

Returns a map with every field a pricing UI needs in one hop:

  * `:base_price` — the item's stored base price (or `nil` if unset)
  * `:catalogue_markup` — the catalogue's `markup_percentage` (the
    inherited default when the item has no override)
  * `:item_markup` — the item's markup override, or `nil` when
    inheriting from the catalogue
  * `:markup_percentage` — the markup actually applied (item override
    if set, otherwise catalogue's)
  * `:sale_price` — the price after markup, before any discount
    (or `nil` if no base price)
  * `:catalogue_discount` — the catalogue's `discount_percentage`
  * `:item_discount` — the item's discount override, or `nil` when
    inheriting from the catalogue
  * `:discount_percentage` — the discount actually applied (item
    override if set, otherwise catalogue's)
  * `:discount_amount` — the Decimal amount subtracted by the discount
    (`sale_price - final_price`), or `nil` if no discount applies or
    no base price
  * `:final_price` — the price after both markup and discount (or
    `nil` if no base price)

## Examples

    # Item inherits both markup (15%) and discount (10%)
    Catalogue.item_pricing(item)
    #=> %{
    #=>   base_price: Decimal.new("100.00"),
    #=>   catalogue_markup: Decimal.new("15.0"),
    #=>   item_markup: nil,
    #=>   markup_percentage: Decimal.new("15.0"),
    #=>   sale_price: Decimal.new("115.00"),
    #=>   catalogue_discount: Decimal.new("10.0"),
    #=>   item_discount: nil,
    #=>   discount_percentage: Decimal.new("10.0"),
    #=>   discount_amount: Decimal.new("11.50"),
    #=>   final_price: Decimal.new("103.50")
    #=> }

    # Item overrides discount to 0 — sale price is charged at full
    Catalogue.item_pricing(item_with_zero_discount)
    #=> %{..., final_price: Decimal.new("115.00"), discount_amount: Decimal.new("0.00"), ...}

# `link_manufacturer_supplier`

# `linked_manufacturer_uuids`

# `linked_supplier_uuids`

# `list_all_categories`

```elixir
@spec list_all_categories() :: [PhoenixKitCatalogue.Schemas.Category.t()]
```

Lists all non-deleted categories across all non-deleted catalogues,
with breadcrumb-style names prefixed by their catalogue and every
ancestor category (e.g. `"Kitchen / Cabinets / Frames"`). Useful for
item move dropdowns where the user needs to distinguish
same-named leaves under different parents.

Entries are grouped by catalogue (catalogues ordered by name) and
within each catalogue returned in depth-first display order.

One query for catalogues + one query for all their categories — the
tree walk and breadcrumb rewrite happen in memory. Safe to call on
demand from move-dropdowns.

# `list_catalogue_rules`

# `list_catalogues`

```elixir
@spec list_catalogues(keyword()) :: [PhoenixKitCatalogue.Schemas.Catalogue.t()]
```

Lists catalogues, ordered by name. Excludes deleted by default.

## Options

  * `:status` — when provided, returns only catalogues with this exact status
    (e.g. `"active"`, `"archived"`, `"deleted"`).
    When nil (default), returns all non-deleted catalogues.
  * `:kind` — when provided, filters to a specific kind (`:standard`, `:smart`,
    or their string equivalents). When nil (default), returns all kinds.

## Examples

    Catalogue.list_catalogues()                     # active + archived
    Catalogue.list_catalogues(status: "deleted")    # only deleted
    Catalogue.list_catalogues(status: "active")     # only active
    Catalogue.list_catalogues(kind: :smart)         # only smart catalogues
    Catalogue.list_catalogues(kind: :standard)      # only standard catalogues

# `list_catalogues_by_name_prefix`

```elixir
@spec list_catalogues_by_name_prefix(
  String.t(),
  keyword()
) :: [PhoenixKitCatalogue.Schemas.Catalogue.t()]
```

Lists catalogues whose name starts with `prefix`, case-insensitive.

Anchored at the start of the name — this is a *prefix* match
(`name ILIKE 'prefix%'`), not a contains match. LIKE metacharacters
(`%`, `_`) in the prefix are escaped.

Excludes deleted catalogues by default. Useful for narrowing a search
scope: pair with `search_items/2`'s `:catalogue_uuids` to search only
the matched catalogues.

## Options

  * `:status` — when provided, returns only catalogues with this exact status.
    Defaults to non-deleted (active + archived).
  * `:limit` — max results (no limit by default).

## Examples

    Catalogue.list_catalogues_by_name_prefix("Kit")
    #=> [%Catalogue{name: "Kitchen Furniture"}, %Catalogue{name: "Kits"}]

    Catalogue.list_catalogues_by_name_prefix("Kit", limit: 5)
    Catalogue.list_catalogues_by_name_prefix("", limit: 10)  # returns first 10

    # Compose with search
    uuids =
      "Kit"
      |> Catalogue.list_catalogues_by_name_prefix()
      |> Enum.map(& &1.uuid)

    Catalogue.search_items("oak", catalogue_uuids: uuids)

# `list_categories_for_catalogue`

```elixir
@spec list_categories_for_catalogue(Ecto.UUID.t()) :: [
  PhoenixKitCatalogue.Schemas.Category.t()
]
```

Lists non-deleted categories for a catalogue, ordered by position then name.

Preloads items (non-deleted only).

# `list_categories_metadata_for_catalogue`

```elixir
@spec list_categories_metadata_for_catalogue(
  Ecto.UUID.t(),
  keyword()
) :: [PhoenixKitCatalogue.Schemas.Category.t()]
```

Lists categories for a catalogue **without** preloading items, ordered by
position then name. Used by the infinite-scroll detail view to walk
categories in display order without fetching potentially thousands of
items up front.

## Options

  * `:mode` — `:active` (default, excludes deleted categories) or
    `:deleted` (all categories — deleted categories can still contain
    trashed items we want to show).

# `list_category_ancestors`

```elixir
@spec list_category_ancestors(Ecto.UUID.t()) :: [
  PhoenixKitCatalogue.Schemas.Category.t()
]
```

Returns the list of ancestor categories from root down to (but not
including) `category_uuid`. Empty when the category is a root.
Useful for breadcrumbs.

# `list_category_tree`

```elixir
@spec list_category_tree(
  Ecto.UUID.t(),
  keyword()
) :: [{PhoenixKitCatalogue.Schemas.Category.t(), non_neg_integer()}]
```

Returns the categories in a catalogue paired with their tree depth,
in depth-first display order (position, then name, recursing into
children). Each entry is `{category, depth}` where depth `0` means a
root. Used to render flat parent-pickers and indented listings.

## Options

  * `:mode` — `:active` (default, excludes deleted categories) or
    `:deleted` (all statuses — the detail view in deleted mode still
    wants deleted categories that contain trashed items).
  * `:exclude_subtree_of` — skip a category and all its descendants
    (e.g. the category being edited — you can't parent it under
    itself or its descendants).

# `list_items`

```elixir
@spec list_items(keyword()) :: [PhoenixKitCatalogue.Schemas.Item.t()]
```

Lists all non-deleted items across all catalogues, ordered by name.

Preloads category (with catalogue) and manufacturer.

## Options

  * `:status` — filter by status (e.g. `"active"`, `"inactive"`).
    When nil (default), returns all non-deleted items.
  * `:limit` — max results to return (default: no limit)

## Examples

    Catalogue.list_items()                          # all non-deleted
    Catalogue.list_items(status: "active")          # only active
    Catalogue.list_items(limit: 100)                # first 100

# `list_items_for_catalogue`

```elixir
@spec list_items_for_catalogue(Ecto.UUID.t()) :: [
  PhoenixKitCatalogue.Schemas.Item.t()
]
```

Lists non-deleted items for a catalogue, ordered by category position then
item name. Includes uncategorized items (those with no category) at the end.

Preloads catalogue, category (with catalogue) and manufacturer.

# `list_items_for_category`

```elixir
@spec list_items_for_category(Ecto.UUID.t()) :: [PhoenixKitCatalogue.Schemas.Item.t()]
```

Lists non-deleted items for a category, ordered by name.

Preloads category (with catalogue) and manufacturer.

# `list_items_for_category_paged`

```elixir
@spec list_items_for_category_paged(
  Ecto.UUID.t(),
  keyword()
) :: [PhoenixKitCatalogue.Schemas.Item.t()]
```

Lists a page of items for a single category, ordered by name.

Used by the infinite-scroll detail view; returns at most `:limit`
items starting at `:offset`. Preloads `:catalogue` and `:manufacturer`
so the table cell renderers can access them without extra queries.

## Options

  * `:mode` — `:active` (default, excludes deleted items) or `:deleted`
    (only deleted items)
  * `:offset` — default `0`
  * `:limit` — default `50`

# `list_items_referencing_catalogue`

# `list_manufacturers`

# `list_manufacturers_for_supplier`

# `list_suppliers`

# `list_suppliers_for_manufacturer`

# `list_uncategorized_items`

```elixir
@spec list_uncategorized_items(
  Ecto.UUID.t(),
  keyword()
) :: [PhoenixKitCatalogue.Schemas.Item.t()]
```

Lists uncategorized items (no category assigned) for a specific catalogue.

## Options

  * `:mode` — `:active` (default) excludes deleted items;
    `:deleted` returns only deleted items.

## Examples

    Catalogue.list_uncategorized_items(catalogue_uuid)
    Catalogue.list_uncategorized_items(catalogue_uuid, mode: :deleted)

# `list_uncategorized_items_paged`

```elixir
@spec list_uncategorized_items_paged(
  Ecto.UUID.t(),
  keyword()
) :: [PhoenixKitCatalogue.Schemas.Item.t()]
```

Lists a page of uncategorized items for a catalogue, ordered by name.

Same shape as `list_items_for_category_paged/2`, but for items where
`category_uuid IS NULL AND catalogue_uuid = ?`. Used as the final
section of the infinite-scroll detail view.

## Options

  * `:mode` — `:active` (default) or `:deleted`
  * `:offset` — default `0`
  * `:limit` — default `50`

# `move_category_to_catalogue`

```elixir
@spec move_category_to_catalogue(
  PhoenixKitCatalogue.Schemas.Category.t(),
  Ecto.UUID.t(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Category.t()} | {:error, term()}
```

Moves a category — along with its entire subtree and every item
inside — to a different catalogue.

The moved category's `parent_uuid` is cleared (it detaches from its
former parent, which stays in the source catalogue) and it takes the
next available root-level position in the target. Internal parent
links inside the moved subtree are preserved.

Automatically assigns the next available root position in the target
catalogue.

## Examples

    {:ok, moved} = Catalogue.move_category_to_catalogue(category, target_catalogue_uuid)

# `move_category_under`

```elixir
@spec move_category_under(
  PhoenixKitCatalogue.Schemas.Category.t(),
  Ecto.UUID.t() | nil,
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Category.t()}
  | {:error,
     :would_create_cycle
     | :cross_catalogue
     | :parent_not_found
     | Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Category.t())}
```

Reparents a category within the same catalogue, placing it under
`new_parent_uuid` (or promoting it to a root with `nil`).

Rejects moves that would:
  * produce a cycle (`new_parent_uuid` is the category itself or one
    of its descendants) — returns `{:error, :would_create_cycle}`
  * cross a catalogue boundary — returns `{:error, :cross_catalogue}`.
    Callers who want that should run `move_category_to_catalogue/3`
    first, then reparent.
  * target a missing parent — returns `{:error, :parent_not_found}`

The moved category takes the next-available position among its new
siblings. Its subtree comes along untouched (parent links inside the
subtree stay valid).

Passing `new_parent_uuid = nil` promotes the category to a root within
its current catalogue.

## Examples

    {:ok, moved} = Catalogue.move_category_under(child, parent.uuid)
    {:ok, moved} = Catalogue.move_category_under(child, nil)  # promote to root

# `move_item_to_catalogue`

```elixir
@spec move_item_to_catalogue(
  PhoenixKitCatalogue.Schemas.Item.t(),
  Ecto.UUID.t(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Item.t()}
  | {:error,
     :catalogue_not_found
     | :same_catalogue
     | Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Item.t())}
```

Moves an item to a different catalogue, clearing its category.

Primarily used for **smart** items, where categories don't apply —
the "where does this item live?" question reduces to "which catalogue?".
Sets both `catalogue_uuid` and `category_uuid` in one update so the
item becomes uncategorized within its new catalogue.

Returns `{:error, :catalogue_not_found}` if the target catalogue UUID
doesn't resolve, `{:error, :same_catalogue}` if it's already there, or
`{:error, changeset}` on validation failure. Logs an `item.moved`
activity with from/to catalogue metadata.

## Examples

    {:ok, item} = Catalogue.move_item_to_catalogue(item, other_smart.uuid)

# `move_item_to_category`

```elixir
@spec move_item_to_category(
  PhoenixKitCatalogue.Schemas.Item.t(),
  Ecto.UUID.t() | nil,
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Item.t()}
  | {:error,
     :category_not_found
     | Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Item.t())}
```

Moves an item to a different category.

If the target category lives in a different catalogue, the item's
`catalogue_uuid` is updated to match. Passing `nil` for `category_uuid`
detaches the item from any category while keeping it in its current
catalogue.

## Examples

    {:ok, item} = Catalogue.move_item_to_category(item, new_category_uuid)
    {:ok, item} = Catalogue.move_item_to_category(item, nil)  # make uncategorized

# `next_category_position`

```elixir
@spec next_category_position(Ecto.UUID.t(), Ecto.UUID.t() | nil) :: non_neg_integer()
```

Returns the next available position for a new category among its
siblings. Position is scoped to `(catalogue_uuid, parent_uuid)` — the
set of categories sharing the same parent within a catalogue — since
V103's nested-category tree makes a single catalogue-wide ordering
ambiguous.

`parent_uuid` defaults to `nil`, i.e. root-level siblings. Returns 0
if no siblings exist at that level, otherwise `max_position + 1`.

# `permanently_delete_catalogue`

```elixir
@spec permanently_delete_catalogue(
  PhoenixKitCatalogue.Schemas.Catalogue.t(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Catalogue.t()}
  | {:error, {:referenced_by_smart_items, non_neg_integer()}}
  | {:error, term()}
```

Permanently deletes a catalogue and all its contents from the database.

**Cascades downward** in a transaction:
1. Hard-deletes all items in the catalogue's categories
2. Hard-deletes all categories
3. Hard-deletes the catalogue

Refuses with `{:error, {:referenced_by_smart_items, count}}` when one or
more smart-catalogue items still have rules pointing at this catalogue.
V102's `ON DELETE CASCADE` would silently wipe those rule rows;
callers should resolve the references explicitly (or remove the rules)
before retrying. Use `:force` to bypass this guard at your own risk.

This cannot be undone.

## Options

  * `:actor_uuid` — UUID to attribute on the activity log
  * `:force` — when `true`, deletes even if smart-rule references exist

## Examples

    {:ok, _} = Catalogue.permanently_delete_catalogue(catalogue)
    {:error, {:referenced_by_smart_items, 3}} =
      Catalogue.permanently_delete_catalogue(catalogue_with_refs)

# `permanently_delete_category`

```elixir
@spec permanently_delete_category(
  PhoenixKitCatalogue.Schemas.Category.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Category.t()} | {:error, term()}
```

Permanently deletes a category and its entire subtree (all descendant
categories + every item in any of them) from the database.

**Cascades downward** in a transaction, following the nested-category
tree introduced in V103. Items are hard-deleted first, then the
subtree categories from leaves up (ordered so child FKs resolve
before their parent is removed). This cannot be undone.

# `permanently_delete_item`

```elixir
@spec permanently_delete_item(
  PhoenixKitCatalogue.Schemas.Item.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Item.t()} | {:error, term()}
```

Permanently deletes an item from the database. This cannot be undone.

## Examples

    {:ok, _} = Catalogue.permanently_delete_item(item)

# `put_catalogue_rules`

# `restore_catalogue`

```elixir
@spec restore_catalogue(
  PhoenixKitCatalogue.Schemas.Catalogue.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Catalogue.t()} | {:error, term()}
```

Restores a soft-deleted catalogue by setting its status to `"active"`.

**Cascades downward** in a transaction:
1. All deleted categories → status `"active"`
2. All deleted items in those categories → status `"active"`
3. The catalogue itself → status `"active"`

## Examples

    {:ok, catalogue} = Catalogue.restore_catalogue(catalogue)

# `restore_category`

```elixir
@spec restore_category(
  PhoenixKitCatalogue.Schemas.Category.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Category.t()} | {:error, term()}
```

Restores a soft-deleted category (and its deleted subtree) by
setting status back to `"active"`.

**Cascades both directions** in a transaction:
- **Upward**: restores every deleted ancestor category so the restored
  node is reachable in the active tree, then the parent catalogue if
  it's deleted too.
- **Downward**: restores all deleted categories in this subtree and
  all deleted items inside them. Restoring a node after a prior
  trash cascade brings the whole sub-branch back as one action.

## Examples

    {:ok, _} = Catalogue.restore_category(category)

# `restore_item`

```elixir
@spec restore_item(
  PhoenixKitCatalogue.Schemas.Item.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Item.t()} | {:error, term()}
```

Restores a soft-deleted item by setting its status to `"active"`.

**Cascades upward** in a transaction: if the parent category is deleted,
restores it too (so the item is visible in the active view).

## Examples

    {:ok, item} = Catalogue.restore_item(item)

# `search_items`

# `search_items_in_catalogue`

# `search_items_in_category`

# `set_translation`

# `swap_category_positions`

```elixir
@spec swap_category_positions(
  PhoenixKitCatalogue.Schemas.Category.t(),
  PhoenixKitCatalogue.Schemas.Category.t(),
  keyword()
) :: {:ok, term()} | {:error, :not_siblings | term()}
```

Atomically swaps the positions of two categories within a transaction.

Positions are scoped to `(catalogue_uuid, parent_uuid)` sibling
groups (V103). Swapping positions of categories that are not
siblings would mix two independent ordering axes, so this function
refuses with `{:error, :not_siblings}` when the categories live
under different parents or in different catalogues. The detail-view
reorder buttons enforce the same constraint at the LV level; this
is the context-level guard for any programmatic caller.

## Examples

    {:ok, _} = Catalogue.swap_category_positions(cat_a, cat_b)
    {:error, :not_siblings} = Catalogue.swap_category_positions(root, child)

# `sync_manufacturer_suppliers`

# `sync_supplier_manufacturers`

# `trash_catalogue`

```elixir
@spec trash_catalogue(
  PhoenixKitCatalogue.Schemas.Catalogue.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Catalogue.t()} | {:error, term()}
```

Soft-deletes a catalogue by setting its status to `"deleted"`.

**Cascades downward** in a transaction:
1. All non-deleted items in the catalogue's categories → status `"deleted"`
2. All non-deleted categories → status `"deleted"`
3. The catalogue itself → status `"deleted"`

## Examples

    {:ok, catalogue} = Catalogue.trash_catalogue(catalogue)

# `trash_category`

```elixir
@spec trash_category(
  PhoenixKitCatalogue.Schemas.Category.t(),
  keyword()
) :: {:ok, PhoenixKitCatalogue.Schemas.Category.t()} | {:error, term()}
```

Soft-deletes a category and its entire subtree by setting their
status to `"deleted"`.

**Cascades downward** in a transaction, following the nested-category
tree introduced in V103:
1. All non-deleted items in this category and any descendant → status `"deleted"`
2. This category and every descendant category → status `"deleted"`

Logs a single `category.trashed` activity on the root with
`subtree_size` (categories touched, including root) and
`items_cascaded` (items touched) in the metadata.

## Examples

    {:ok, _} = Catalogue.trash_category(category)

# `trash_item`

```elixir
@spec trash_item(
  PhoenixKitCatalogue.Schemas.Item.t(),
  keyword()
) ::
  {:ok, PhoenixKitCatalogue.Schemas.Item.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Item.t())}
```

Soft-deletes an item by setting its status to `"deleted"`.

## Examples

    {:ok, item} = Catalogue.trash_item(item)

# `trash_items_in_category`

```elixir
@spec trash_items_in_category(
  Ecto.UUID.t(),
  keyword()
) :: {non_neg_integer(), nil}
```

Bulk soft-deletes all non-deleted items in a category.

Returns `{count, nil}` where count is the number of items affected.

## Examples

    {3, nil} = Catalogue.trash_items_in_category(category_uuid)

# `uncategorized_count_for_catalogue`

```elixir
@spec uncategorized_count_for_catalogue(
  Ecto.UUID.t(),
  keyword()
) :: non_neg_integer()
```

Counts non-deleted uncategorized items for a catalogue (items with
`category_uuid IS NULL`). Used to decide whether the infinite-scroll
detail view needs to show an "Uncategorized" card at all.

# `unlink_manufacturer_supplier`

# `update_catalogue`

```elixir
@spec update_catalogue(PhoenixKitCatalogue.Schemas.Catalogue.t(), map(), keyword()) ::
  {:ok, PhoenixKitCatalogue.Schemas.Catalogue.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Catalogue.t())}
```

Updates a catalogue with the given attributes.

# `update_catalogue_rule`

# `update_category`

```elixir
@spec update_category(PhoenixKitCatalogue.Schemas.Category.t(), map(), keyword()) ::
  {:ok, PhoenixKitCatalogue.Schemas.Category.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Category.t())}
```

Updates a category with the given attributes.

# `update_item`

```elixir
@spec update_item(PhoenixKitCatalogue.Schemas.Item.t(), map(), keyword()) ::
  {:ok, PhoenixKitCatalogue.Schemas.Item.t()}
  | {:error, Ecto.Changeset.t(PhoenixKitCatalogue.Schemas.Item.t())}
```

Updates an item with the given attributes.

# `update_manufacturer`

# `update_supplier`

---

*Consult [api-reference.md](api-reference.md) for complete listing*
