Skip to content

[Technical Debt] Refactor Item Attribute Search to Fix Pagination, Sorting, and Multi-Attribute Search #4441

Open

Description

@jekkos

Problem Summary

The current attribute search implementation uses GROUP_CONCAT to aggregate attribute values into concatenated strings for search. This approach has several critical issues:

  1. Broken Pagination (Fix Item->search() to resolve issues with attributes #2819) - Row counts are incorrect when searching attributes, showing wrong pagination totals
  2. No Multi-Attribute Search ([Feature]: Search with multiple attributes (AND logic) #2407) - Searching multiple attributes returns no results
  3. Sorting by Attribute Columns Impossible (Bug in items table sort #2722) - Cannot sort by attribute columns
  4. GROUP_CONCAT Limits - Requires SET SESSION group_concat_max_len=49152 workarounds
  5. Visibility vs Searchability ("Search Attributes" only searches attributes with Item Visibility Flag set #2919) - Attributes can only be searched if "show in items" flag is set

Current Architecture Issues

Location: app/Models/Item.php lines 213-239

// Current problematic approach:
$builder->select('GROUP_CONCAT(DISTINCT CONCAT_WS(\'_\', definition_id, attribute_value) ORDER BY definition_id SEPARATOR \'|\') AS attribute_values');
$builder->havingLike('attribute_values', $search);

Problems:

  • HAVING LIKE on concatenated string produces incorrect COUNT(DISTINCT items.item_id) results
  • Multi-attribute queries need proper AND/OR logic, not string concatenation
  • Sort columns for attributes need individual columns, not concatenated values
  • group_concat_max_len truncates on large result sets

Phase 1: Core Search Refactor (Priority: Critical)

Scope: Refactor Item::search() to eliminate GROUP_CONCAT dependency

Files to Modify:

  • app/Models/Item.php - Primary refactor
  • app/Controllers/Items.php - Pass correct filter parameters

New Architecture

1. New Method: search_by_attributes()

/**
 * Get item_ids matching attribute search criteria
 * 
 * @param string $search Search term
 * @param array $definition_ids Attribute definition IDs to search
 * @param string $logic 'AND' or 'OR' for multi-attribute matching
 * @return array Array of matching item_ids
 */
public function search_by_attributes(string $search, array $definition_ids, string $logic = 'OR'): array
{
    $builder = $this->db->table('attribute_links');
    $builder->join('attribute_values', 'attribute_values.attribute_id = attribute_links.attribute_id');
    $builder->select('DISTINCT attribute_links.item_id');
    $builder->groupStart();
    $builder->like('attribute_value', $search);
    $builder->orWhere('attribute_decimal', $search);
    // Handle date format conversion for search
    $builder->groupEnd();
    $builder->whereIn('definition_id', $definition_ids);
    $builder->where('sale_id', null);
    $builder->where('receiving_id', null);
    
    return array_column($builder->get()->getResultArray(), 'item_id');
}

2. Refactored Item::search() Method

public function search(string $search, array $filters, ?int $rows = 0, ?int $limit_from = 0, ?string $sort = 'items.name', ?string $order = 'asc', ?bool $count_only = false)
{
    // ... existing setup code ...
    
    $matching_item_ids = null;
    
    // When attribute search is enabled, get matching item_ids first
    if ($attributes_enabled && $filters['search_custom'] && !empty($search)) {
        $matching_item_ids = $this->search_by_attributes($search, $filters['definition_ids']);
        
        // If no matches and we're only searching attributes, return early
        if (empty($matching_item_ids) && $filters['search_custom']) {
            return $count_only ? 0 : $this->db->table('items')->where('1', '0')->get();
        }
    }
    
    // Build main query
    $builder = $this->db->table('items AS items');
    // ... existing select/join code ...
    
    // Apply item_id filter if we have attribute matches
    if ($matching_item_ids !== null) {
        if (count($matching_item_ids) > 0) {
            $builder->whereIn('items.item_id', $matching_item_ids);
        }
    }
    
    // Apply standard search (name, item_number, etc.)
    if (!empty($search) && !$filters['search_custom']) {
        $builder->groupStart();
        $builder->like('name', $search);
        // ... existing search conditions ...
        $builder->groupEnd();
    }
    
    // Combined search: both regular fields AND attributes
    if (!empty($search) && $filters['search_custom'] && $matching_item_ids !== null) {
        $builder->groupStart();
        $builder->whereIn('items.item_id', $matching_item_ids);
        $builder->orWhereLike('name', $search);
        // ... other fields ...
        $builder->groupEnd();
    }
    
    // ... rest of existing logic ...
}

3. Attribute Column Sorting Support

/**
 * Apply sorting by attribute column
 * 
 * @param BaseBuilder $builder Query builder reference
 * @param string $sort Sort column name
 * @param string $order 'asc' or 'desc'
 * @param array $definition_ids Attribute definitions to consider for sorting
 * @return void
 */
private function apply_attribute_sort(&$builder, string $sort, string $order, array $definition_ids): void
{
    // Check if sort column is an attribute (format: attr_NNN where NNN is definition_id)
    if (preg_match('/^attr_(\d+)$/', $sort, $matches)) {
        $definition_id = (int)$matches[1];
        
        // Join attribute tables for sorting
        $alias = "sort_attr_{$definition_id}";
        $builder->join(
            "attribute_links AS {$alias}",
            "{$alias}.item_id = items.item_id AND {$alias}.definition_id = {$definition_id} AND {$alias}.sale_id IS NULL AND {$alias}.receiving_id IS NULL",
            'left'
        );
        $builder->join(
            "attribute_values AS {$alias}_val",
            "{$alias}_val.attribute_id = {$alias}.attribute_id",
            'left'
        );
        $builder->orderBy("{$alias}_val.attribute_value", $order);
    }
}

Phase 2: Enable All Attributes in Search (Priority: High)

Scope: Separate searchability from visibility in Items table

Files to Modify:

  • app/Models/Attribute.php - Add SHOW_IN_SEARCH constant
  • app/Controllers/Items.php - Use all searchable attributes for filter
  • app/Database/Migrations/ - New migration for definition_flags column

New Constant:

public const SHOW_IN_SEARCH = 8;  // New flag value

Controller Update:

// Current: Only shows attributes with SHOW_IN_ITEMS flag
$definition_names = $this->attribute->get_definitions_by_flags(Attribute::SHOW_IN_ITEMS);

// New: Include all searchable attributes  
$definition_names = $this->attribute->get_definitions_by_flags(Attribute::SHOW_IN_ITEMS | Attribute::SHOW_IN_SEARCH);

Phase 3: Multi-Attribute Search UI (Priority: Medium)

Scope: Add syntax for searching multiple attributes

Search Syntax Options:

  1. color: blue size: large - Attribute-specific search
  2. color: blue AND size: large - Explicit AND logic
  3. color: blue OR size: large - Explicit OR logic

Files to Modify:

  • public/js/items.js - Parse search syntax
  • app/Models/Item.php - Handle parsed attribute queries

Database Schema Changes

Migration Required: None for Phase 1 (uses existing schema)

Future Enhancement (Phase 2):

ALTER TABLE ospos_attribute_definitions 
MODIFY COLUMN definition_flags INT;
-- Add SHOW_IN_SEARCH = 8 bitmask value

Testing Checklist

  • Single attribute search returns correct results
  • Multi-attribute search (AND logic) returns correct results
  • Multi-attribute search (OR logic) returns correct results
  • Pagination count matches actual result rows
  • Sorting by name/category still works
  • Sorting by attribute column works (after Phase 3)
  • Search with no results shows "No items found"
  • Performance acceptable with 1000+ items
  • No group_concat_max_len warnings in logs

Related Issues


Estimated Effort

Phase Effort Priority
Phase 1: Core Refactor 3-5 days Critical
Phase 2: Searchable Attributes 1 day High
Phase 3: Multi-Attribute UI 2 days Medium
Phase 4: Sort by Attribute 2 days Medium

Activity

  1. added this to the 3.5.0 milestone on Mar 16, 2026
  2. jekkos commented on Mar 16, 2026

    @jekkos
    MemberAuthor

    Implementation Started - Phase 1 Complete

    I've pushed the initial implementation for Phase 1 (Core Search Refactor) to branch fix/attribute-search-refactor.

    Changes Made

    New Method: Item::search_by_attributes()

    • Returns array of item_ids matching attribute search criteria
    • Properly joins attribute_links, attribute_values, and items tables
    • Searches both TEXT and DECIMAL attribute values
    • Respects deleted status filter

    Refactored Item::search()

    • Removed GROUP_CONCAT from WHERE/HAVING clause logic
    • Uses subquery approach: first gets matching item_ids from attributes, then applies to main query
    • Count query now returns correct pagination totals
    • Combined search: attributes OR regular fields (name, item_number, category, etc.)

    Key Fixes

    What Still Needs Testing

    • Multi-attribute AND logic (currently uses OR)
    • Sorting by attribute columns
    • Performance with large datasets

    Code Location

    app/Models/Item.php - lines 133-162 (new method), lines 164-315 (refactored search)

    Branch: https://github.com/opensourcepos/opensourcepos/tree/fix/attribute-search-refactor

  3. jekkos commented on Mar 16, 2026

    @jekkos
    MemberAuthor

    Phase 2 Complete - SHOW_IN_SEARCH Flag

    Phase 2 has been implemented and pushed to the branch.

    Changes Made

    New Constant in Attribute Model:

    public const SHOW_IN_ITEMS = 1;
    public const SHOW_IN_SALES = 2;
    public const SHOW_IN_RECEIVINGS = 4;
    public const SHOW_IN_SEARCH = 8;  // NEW

    Items Controller Update:
    When search_custom filter is enabled, the search now includes attributes marked with either SHOW_IN_ITEMS OR SHOW_IN_SEARCH flag:

    if (!empty($filters['search_custom'])) {
        $searchable_definitions = $this->attribute->get_definitions_by_flags(
            Attribute::SHOW_IN_ITEMS | Attribute::SHOW_IN_SEARCH
        );
        $filters['definition_ids'] = array_keys($searchable_definitions);
    }

    Language Updates:

    • Added show_in_search and show_in_search_visibility strings to en/Attributes.php and en-GB/Attributes.php

    Attributes Controller Update:

    • Added SHOW_IN_SEARCH to the available flags in the attribute form

    How It Works

    1. Attributes can now have a "Show in search" checkbox in the visibility flags
    2. When searching items with "Search Attributes" filter enabled, the search will include:
      • All attributes with SHOW_IN_ITEMS flag (visible in table)
      • All attributes with SHOW_IN_SEARCH flag (searchable but not necessarily visible)
    3. This solves issue "Search Attributes" only searches attributes with Item Visibility Flag set #2919 where users wanted to search attributes without cluttering the items table

    Files Changed

    • app/Models/Attribute.php - Added SHOW_IN_SEARCH constant
    • app/Controllers/Items.php - Updated search filter logic
    • app/Controllers/Attributes.php - Added flag to form
    • app/Language/en/Attributes.php - Added language strings
    • app/Language/en-GB/Attributes.php - Added language strings

    Fixes #2919

  4. jekkos commented on Mar 16, 2026

    @jekkos
    MemberAuthor

    All Phases Complete

    All four phases of the attribute search improvement have been implemented.

    Commits Summary

    Commit Phase Description
    5b77911 1 Refactor attribute search to fix pagination and multi-attribute search
    9827a79 2 Add SHOW_IN_SEARCH flag to separate attribute search from visibility
    b574bdc 3 & 4 Implement multi-attribute search AND logic and sort by attribute columns

    Phase 3: Multi-Attribute Search

    New Syntax Support:

    • color: blue - Search for items where color attribute contains "blue"
    • color: blue size: large - Search with AND logic (not yet exposed in UI)
    • The parser extracts attribute-specific queries from the search string

    Code Added:

    • parse_attribute_search() - Parses search syntax like color:blue
    • Updated search_by_attributes() - Supports AND logic for multiple attributes
    • search_by_attribute_value() - Private method for single value searches

    Phase 4: Sort by Attribute Columns

    Changes Made:

    • Added get_attribute_sort_definition_id() to detect attribute column sorting
    • Updated Item::search() to join attribute tables when sorting
    • Updated tabular_helper.php to make attribute columns sortable ('sortable' => true)
    • Added sanitizeSortColumnAttribute() in Items controller to validate attribute IDs

    Files Changed Summary

    File Changes
    app/Models/Item.php New methods: parse_attribute_search(), search_by_attributes() (expanded), search_by_attribute_value(), get_attribute_sort_definition_id(). Updated search() for attribute sorting.
    app/Controllers/Items.php Added sanitizeSortColumnAttribute(), updated getSearch() to validate attribute sort columns
    app/Helpers/tabular_helper.php Changed attribute columns to be sortable
    app/Models/Attribute.php Added SHOW_IN_SEARCH = 8 constant
    app/Language/en/Attributes.php Added show_in_search translations
    app/Language/en-GB/Attributes.php Added show_in_search translations

    Issues Fixed

    Remaining Work

    The following items from the original plan could be addressed in future PRs:

    1. Search syntax UI - Add UI hints or help text for attribute: value syntax
    2. OR/AND toggle - Add toggle in UI to choose between AND/OR logic
    3. Date attribute search - Parse date values in search syntax
    4. DECIMAL attribute search - Handle decimal comparisons

    Branch: https://github.com/opensourcepos/opensourcepos/tree/fix/attribute-search-refactor

  5. self-assigned this
    on Mar 18, 2026
  6. objecttothis commented on Oct 22, 2026

    @objecttothis
    Member

    Claude Issue Checker Agent (cc @objecttothis)

    Investigated against current master.

    Status: Appears resolved (though via a different, apparently later implementation than the one described in this issue's progress comments).

    Current app/Models/Item.php and app/Models/Attribute.php already contain working equivalents of everything this issue asked for:

    • Pagination fix: Item::search() now does a two-phase approach — resolves matching item_ids first ($idBuilder, with a $countOnly short-circuit calling $idBuilder->countAllResults()), then joins display-only tables scoped to just those IDs. get_found_rows() calls search(..., true), giving an accurate count independent of the GROUP_CONCAT display logic.
    • Multi-attribute search: Item::parseAttributeSearch() parses name:value pairs (supporting comma/AND/OR separators) and applyNamedAttributeSearch() ANDs them together via per-attribute joins — this resolves what the issue calls Phase 3.
    • Sorting by attribute columns: Item::getAttributeSortDefinitionId() + applyAttributeSort() join and sort by a given attribute definition's value/decimal/date column — this resolves Phase 4.
    • SHOW_IN_SEARCH flag: Attribute::SHOW_IN_SEARCH = 8 exists in app/Models/Attribute.php, and Items::getSearch() in app/Controllers/Items.php uses getDefinitionsByFlags(Attribute::SHOW_IN_ITEMS | Attribute::SHOW_IN_SEARCH) when search_custom is enabled — this resolves Phase 2.

    The method names differ from what was described in the fix/attribute-search-refactor branch comments (e.g. parseAttributeSearch/applyNamedAttributeSearch/applyAttributeSort vs. the originally proposed parse_attribute_search/search_by_attributes), suggesting this was reimplemented later (possibly via #4652 and related attribute-search PRs) rather than merged from that specific branch, but the functional gaps described in this issue (pagination count, multi-attribute search, sorting, searchable-but-hidden attributes) all appear addressed in current master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions