Repository navigation
Open
Description
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:
- Broken Pagination (Fix Item->search() to resolve issues with attributes #2819) - Row counts are incorrect when searching attributes, showing wrong pagination totals
- No Multi-Attribute Search ([Feature]: Search with multiple attributes (AND logic) #2407) - Searching multiple attributes returns no results
- Sorting by Attribute Columns Impossible (Bug in items table sort #2722) - Cannot sort by attribute columns
GROUP_CONCATLimits - RequiresSET SESSION group_concat_max_len=49152workarounds- 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 LIKEon concatenated string produces incorrectCOUNT(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_lentruncates 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 refactorapp/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- AddSHOW_IN_SEARCHconstantapp/Controllers/Items.php- Use all searchable attributes for filterapp/Database/Migrations/- New migration fordefinition_flagscolumn
New Constant:
public const SHOW_IN_SEARCH = 8; // New flag valueController 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:
color: blue size: large- Attribute-specific searchcolor: blue AND size: large- Explicit AND logiccolor: blue OR size: large- Explicit OR logic
Files to Modify:
public/js/items.js- Parse search syntaxapp/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 valueTesting 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_lenwarnings in logs
Related Issues
- Fixes Fix Item->search() to resolve issues with attributes #2819
- Fixes [Feature]: Search with multiple attributes (AND logic) #2407
- Fixes Bug in items table sort #2722
- Related "Search Attributes" only searches attributes with Item Visibility Flag set #2919
- Related Suggestion: Adding Attributes searching in the Sales Modules #2600
- Related [Feature]: Attributes in sales register search suggestions #2890
- Related [Feature]: Show custom attributes in sales register search #3293
- Related [Feature]: Attribute module enhancements for quantity tracking #2564
- Related [Feature]: Multi-select capability for dropdown attributes #2663
- Related [Enhancement]: LONGTEXT attribute type #2470
- Related [Enhancement]: Precision in DECIMAL attribute type #2847
- Related [Feature]: Supplier/Customer/User attributes #2244
- Related [Feature]: Default required attributes #2817
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
jekkos commentedon Mar 16, 2026
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()attribute_links,attribute_values, anditemstablesRefactored
Item::search()GROUP_CONCATfrom WHERE/HAVING clause logicKey Fixes
get_found_rows()now returns correct countGROUP_CONCATis retained only for display purposes (showing attribute values in items table)What Still Needs Testing
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
jekkos commentedon Mar 16, 2026
Phase 2 Complete - SHOW_IN_SEARCH Flag
Phase 2 has been implemented and pushed to the branch.
Changes Made
New Constant in Attribute Model:
Items Controller Update:
When
search_customfilter is enabled, the search now includes attributes marked with eitherSHOW_IN_ITEMSORSHOW_IN_SEARCHflag:Language Updates:
show_in_searchandshow_in_search_visibilitystrings to en/Attributes.php and en-GB/Attributes.phpAttributes Controller Update:
SHOW_IN_SEARCHto the available flags in the attribute formHow It Works
Files Changed
app/Models/Attribute.php- Added SHOW_IN_SEARCH constantapp/Controllers/Items.php- Updated search filter logicapp/Controllers/Attributes.php- Added flag to formapp/Language/en/Attributes.php- Added language stringsapp/Language/en-GB/Attributes.php- Added language stringsFixes #2919
jekkos commentedon Mar 16, 2026
All Phases Complete
All four phases of the attribute search improvement have been implemented.
Commits Summary
5b779119827a79b574bdcPhase 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)Code Added:
parse_attribute_search()- Parses search syntax likecolor:bluesearch_by_attributes()- Supports AND logic for multiple attributessearch_by_attribute_value()- Private method for single value searchesPhase 4: Sort by Attribute Columns
Changes Made:
get_attribute_sort_definition_id()to detect attribute column sortingItem::search()to join attribute tables when sortingtabular_helper.phpto make attribute columns sortable ('sortable' => true)sanitizeSortColumnAttribute()in Items controller to validate attribute IDsFiles Changed Summary
app/Models/Item.phpparse_attribute_search(),search_by_attributes()(expanded),search_by_attribute_value(),get_attribute_sort_definition_id(). Updatedsearch()for attribute sorting.app/Controllers/Items.phpsanitizeSortColumnAttribute(), updatedgetSearch()to validate attribute sort columnsapp/Helpers/tabular_helper.phpapp/Models/Attribute.phpSHOW_IN_SEARCH = 8constantapp/Language/en/Attributes.phpshow_in_searchtranslationsapp/Language/en-GB/Attributes.phpshow_in_searchtranslationsIssues Fixed
Remaining Work
The following items from the original plan could be addressed in future PRs:
attribute: valuesyntaxBranch: https://github.com/opensourcepos/opensourcepos/tree/fix/attribute-search-refactor
objecttothis commentedon Oct 22, 2026
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.phpandapp/Models/Attribute.phpalready contain working equivalents of everything this issue asked for:Item::search()now does a two-phase approach — resolves matchingitem_ids first ($idBuilder, with a$countOnlyshort-circuit calling$idBuilder->countAllResults()), then joins display-only tables scoped to just those IDs.get_found_rows()callssearch(..., true), giving an accurate count independent of theGROUP_CONCATdisplay logic.Item::parseAttributeSearch()parsesname:valuepairs (supporting comma/AND/OR separators) andapplyNamedAttributeSearch()ANDs them together via per-attribute joins — this resolves what the issue calls Phase 3.Item::getAttributeSortDefinitionId()+applyAttributeSort()join and sort by a given attribute definition's value/decimal/date column — this resolves Phase 4.SHOW_IN_SEARCHflag:Attribute::SHOW_IN_SEARCH = 8exists inapp/Models/Attribute.php, andItems::getSearch()inapp/Controllers/Items.phpusesgetDefinitionsByFlags(Attribute::SHOW_IN_ITEMS | Attribute::SHOW_IN_SEARCH)whensearch_customis enabled — this resolves Phase 2.The method names differ from what was described in the
fix/attribute-search-refactorbranch comments (e.g.parseAttributeSearch/applyNamedAttributeSearch/applyAttributeSortvs. the originally proposedparse_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 currentmaster.