feat: category filter includes subcategories
This commit is contained in:
@@ -203,6 +203,27 @@ defmodule ComponentsElixir.Inventory do
|
||||
Category.changeset(category, attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets all category IDs that are descendants of the given category ID, including the category itself.
|
||||
This is used for filtering components by category and all its subcategories.
|
||||
Returns an empty list if the category doesn't exist.
|
||||
|
||||
Note: This implementation loads all categories into memory for traversal, which is efficient
|
||||
for typical category tree sizes (hundreds of categories). For very large category trees,
|
||||
a recursive CTE query could be used instead.
|
||||
"""
|
||||
def get_category_and_descendant_ids(category_id) when is_integer(category_id) do
|
||||
categories = list_categories()
|
||||
|
||||
# Verify the category exists before getting descendants
|
||||
case Enum.find(categories, &(&1.id == category_id)) do
|
||||
nil -> []
|
||||
_category -> ComponentsElixir.Inventory.Hierarchical.descendant_ids(categories, category_id, &(&1.parent_id))
|
||||
end
|
||||
end
|
||||
|
||||
def get_category_and_descendant_ids(_), do: []
|
||||
|
||||
## Components
|
||||
|
||||
@doc """
|
||||
@@ -219,7 +240,9 @@ defmodule ComponentsElixir.Inventory do
|
||||
defp apply_component_filters(query, opts) do
|
||||
Enum.reduce(opts, query, fn
|
||||
{:category_id, category_id}, query when not is_nil(category_id) ->
|
||||
where(query, [c], c.category_id == ^category_id)
|
||||
# Get the category and all its descendant category IDs
|
||||
category_ids = get_category_and_descendant_ids(category_id)
|
||||
where(query, [c], c.category_id in ^category_ids)
|
||||
|
||||
{:storage_location_id, storage_location_id}, query when not is_nil(storage_location_id) ->
|
||||
where(query, [c], c.storage_location_id == ^storage_location_id)
|
||||
|
||||
Reference in New Issue
Block a user