Files
opensourcepos/app/Controllers/Attributes.php
T
objecttothisandOllama 1b8ee2e3c1 feat(items): optimize search, attribute filtering, and sort for items view (#4652)
feat(items): optimize search, attribute filtering, and sort for items view (#4652)

BREAKING CHANGE: none

## Search & Query Optimization
- Split item search into two-phase query: Phase A resolves qualifying IDs,
  Phase B joins scoped display tables for better performance and readability
- Sanitize `definition_ids` via `array_map` to prevent injection vulnerabilities
- Introduce subquery for SUM aggregation to prevent over-counting across joins
- Add validation requiring both start and end dates before applying date range filter

## Attribute Search (fixes #2919, #2722)
- Add `SHOW_IN_SEARCH` flag (value 8) to Attribute model to separate
  searchability from table visibility
- Add `parse_attribute_search()` to parse syntax like `color:blue AND size:large`
- Add `applyNamedAttributeSearch()` supporting decimal and date types with
  locale-aware parsing
- Support AND/OR logic for multi-attribute queries

## Sorting
- Add `get_attribute_sort_definition_id()` to detect attribute column sorting
- Join attribute tables dynamically when sorting by attribute columns
- Use `MAX()` for consistent results when sorting by attribute values
- Replace static sort column list with dynamic headers via `itemSortColumns()`
- Add `sanitizeSortColumnAttribute()` to validate attribute definition IDs as sort columns

## Tax & Data Row
- Streamline tax computation in `getItemDataRow()`

## Low Inventory Filter
- Require valid `stock_location_id` before applying low inventory filter
- Add conditional logic to sort by sum of quantities across all locations
  when `stock_location_id` is invalid

## Localization
- Add `show_in_search` / `show_in_search_visibility` strings to all language files
- Translated: de-DE, es-ES, fr, it; English placeholder for remaining locales
- Unify single-quote style across all attribute language files

## Refactoring & Style
- Adopt camelCase naming throughout (variables, helpers, methods)
- Replace `sanitizeSortColumnAttribute` with reusable `sanitizeSortColumn`
  from `Secure_Controller`
- Simplify column key extraction using `array_key_first`
- Apply PSR-12 formatting

## Tests
- Add tests for tax computation, quantity aggregation (single- and multi-location),
  named attribute search, free-text parsing, and date/decimal type handling
- Add `ensureStockLocation` helper to auto-create missing stock locations in tests
- Refactor tests to handle config cache issues

Co-authored-by: Ollama <ollama@steganos.dev>
2026-10-02 14:56:20 +04:00

300 lines
11 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\Attribute;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use JsonException;
require_once('Secure_Controller.php');
/**
* Attributes controls the custom attributes assigned to items
**/
class Attributes extends Secure_Controller
{
private Attribute $attribute;
public function __construct()
{
parent::__construct('attributes');
$this->attribute = model(Attribute::class);
}
/**
* Gets and sends the main view for Attributes to the browser.
*
* @return string
**/
public function getIndex(): string
{
$data['table_headers'] = get_attribute_definition_manage_table_headers();
return view('attributes/manage', $data);
}
/**
* Returns attribute table data rows. This will be called with AJAX.
*/
public function getSearch(): ResponseInterface
{
$search = $this->request->getGet('search');
$limit = $this->request->getGet('limit', FILTER_SANITIZE_NUMBER_INT);
$offset = $this->request->getGet('offset', FILTER_SANITIZE_NUMBER_INT);
$sort = $this->sanitizeSortColumn(attribute_definition_headers(), $this->request->getGet('sort', FILTER_SANITIZE_FULL_SPECIAL_CHARS), 'definition_id');
$order = $this->request->getGet('order', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$attributes = $this->attribute->search($search, $limit, $offset, $sort, $order);
$total_rows = $this->attribute->get_found_rows($search);
$data_rows = [];
foreach ($attributes->getResult() as $attribute_row) {
$attribute_row->definition_flags = $this->get_attributes($attribute_row->definition_flags);
$data_rows[] = get_attribute_definition_data_row($attribute_row);
}
return $this->response->setJSON(['total' => $total_rows, 'rows' => $data_rows]);
}
/**
* AJAX called function which saves the attribute value sent via POST by using the model save function.
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postSaveAttributeValue(): ResponseInterface
{
$attributeValue = $this->request->getPost('attribute_value');
if (!is_string($attributeValue) || $attributeValue === '') {
return $this->response->setJSON(['success' => false]);
}
$success = $this->attribute->saveAttributeValue(
$attributeValue,
$this->request->getPost('definition_id', FILTER_SANITIZE_NUMBER_INT),
$this->request->getPost('item_id', FILTER_SANITIZE_NUMBER_INT) ?? false,
$this->request->getPost('attribute_id', FILTER_SANITIZE_NUMBER_INT) ?? false
);
return $this->response->setJSON(['success' => $success != 0]);
}
/**
* AJAX called function deleting an attribute value using the model delete function.
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postDeleteDropdownAttributeValue(): ResponseInterface
{
$attributeValue = $this->request->getPost('attribute_value');
if (!is_string($attributeValue) || $attributeValue === '') {
return $this->response->setJSON(['success' => false]);
}
$success = $this->attribute->deleteDropdownAttributeValue(
$attributeValue,
$this->request->getPost('definition_id', FILTER_SANITIZE_NUMBER_INT)
);
return $this->response->setJSON(['success' => $success]);
}
/**
* AJAX called function which saves the attribute definition.
*
* @param int $definition_id
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function postSaveDefinition(int $definition_id = NO_DEFINITION_ID): ResponseInterface
{
$definition_flags = 0;
$flags = (empty($this->request->getPost('definition_flags'))) ? [] : $this->request->getPost('definition_flags', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
foreach ($flags as $flag) {
$definition_flags |= $flag;
}
// Validate definition_group (definition_fk) foreign key
$definition_group_input = $this->request->getPost('definition_group');
$definition_fk = $this->validateDefinitionGroup($definition_group_input);
if ($definition_fk === false) {
return $this->response->setJSON([
'success' => false,
'message' => lang('Attributes.definition_invalid_group'),
'id' => NEW_ENTRY
]);
}
// Save definition data
$definition_data = [
'definition_name' => $this->request->getPost('definition_name'),
'definition_unit' => $this->request->getPost('definition_unit') != '' ? $this->request->getPost('definition_unit') : null,
'definition_flags' => $definition_flags,
'definition_fk' => $definition_fk
];
if ($this->request->getPost('definition_type') != null) {
$definition_data['definition_type'] = DEFINITION_TYPES[$this->request->getPost('definition_type')];
}
$definition_name = $definition_data['definition_name'];
if ($definition_id == NO_DEFINITION_ID) {
try {
$definition_values = json_decode($this->request->getPost('definition_values') ?? '', false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
$definition_values = null;
}
if (!is_array($definition_values) || array_filter($definition_values, static fn ($value) => !is_string($value)) !== []) {
return $this->response->setJSON([
'success' => false,
'message' => lang('Attributes.definition_error_adding_updating', [$definition_name]),
'id' => NEW_ENTRY
]);
}
}
if ($this->attribute->saveDefinition($definition_data, $definition_id)) {
// New definition
if ($definition_id == NO_DEFINITION_ID) {
foreach ($definition_values as $definition_value) {
$this->attribute->saveAttributeValue($definition_value, $definition_data['definition_id']);
}
return $this->response->setJSON([
'success' => true,
'message' => lang('Attributes.definition_successful_adding') . ' ' . $definition_name,
'id' => $definition_data['definition_id']
]);
} else { // Existing definition
return $this->response->setJSON([
'success' => true,
'message' => lang('Attributes.definition_successful_updating') . ' ' . $definition_name,
'id' => $definition_id
]);
}
} else { // Failure
return $this->response->setJSON([
'success' => false,
'message' => lang('Attributes.definition_error_adding_updating', [$definition_name]),
'id' => NEW_ENTRY
]);
}
}
/**
* Validates a definition_group foreign key.
* Returns the validated integer ID, null if empty, or false if invalid.
*
* @param mixed $definition_group_input
* @return int|null|false
*/
private function validateDefinitionGroup(mixed $definition_group_input): int|null|false
{
if ($definition_group_input === '' || $definition_group_input === null) {
return null;
}
$definition_group_id = (int) $definition_group_input;
// Must be a positive integer, exist in attribute_definitions, and be of type GROUP
if ($definition_group_id <= 0
|| !$this->attribute->exists($definition_group_id)
|| $this->attribute->getAttributeInfo($definition_group_id)->definition_type !== GROUP
) {
return false;
}
return $definition_group_id;
}
/**
*
* @param int $definition_id
* @return ResponseInterface
* @noinspection PhpUnused
*/
public function getSuggestAttribute(int $definition_id): ResponseInterface
{
$suggestions = $this->attribute->get_suggestions($definition_id, html_entity_decode($this->request->getGet('term')));
return $this->response->setJSON($suggestions);
}
/**
* @param int $row_id
* @return ResponseInterface
*/
public function getRow(int $row_id): ResponseInterface
{
$attribute_definition_info = $this->attribute->getAttributeInfo($row_id);
$attribute_definition_info->definition_flags = $this->get_attributes($attribute_definition_info->definition_flags);
$data_row = get_attribute_definition_data_row($attribute_definition_info);
return $this->response->setJSON($data_row);
}
/**
* @param int $definition_flags
* @return array
*/
private function get_attributes(int $definition_flags = 0): array
{
$definition_flag_names = [];
foreach (Attribute::getDefinitionFlags() as $id => $term) {
if ($id & $definition_flags) {
$definition_flag_names[$id] = lang('Attributes.' . strtolower($term) . '_visibility');
}
}
return $definition_flag_names;
}
/**
* @param int $definitionId
* @return string
*/
public function getView(int $definitionId = NO_DEFINITION_ID): string
{
$info = $this->attribute->getAttributeInfo($definitionId);
foreach (get_object_vars($info) as $property => $value) {
$info->$property = $value;
}
$data['definition_id'] = $definitionId;
$data['definition_values'] = $this->attribute->getDefinitionValues($definitionId);
$data['definition_group'] = $this->attribute->getDefinitionsByType(GROUP, $definitionId);
$data['definition_group'][''] = lang('Common.none_selected_text');
$data['definition_info'] = $info;
$showAll = Attribute::SHOW_IN_ITEMS | Attribute::SHOW_IN_RECEIVINGS | Attribute::SHOW_IN_SALES | Attribute::SHOW_IN_SEARCH;
$data['definition_flags'] = $this->get_attributes($showAll);
$selectedFlags = $info->definition_flags === '' ? $showAll : $info->definition_flags;
$data['selected_definition_flags'] = $this->get_attributes($selectedFlags);
return view('attributes/form', $data);
}
/**
* Deletes an attribute definition
* @return ResponseInterface
*/
public function postDelete(): ResponseInterface
{
$attributes_to_delete = $this->request->getPost('ids', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if($this->attribute->deleteDefinitionList($attributes_to_delete)) {
$message = lang('Attributes.definition_successful_deleted') . ' ' . count($attributes_to_delete) . ' ' . lang('Attributes.definition_one_or_multiple');
return $this->response->setJSON(['success' => true, 'message' => $message]);
} else {
return $this->response->setJSON(['success' => false, 'message' => lang('Attributes.definition_cannot_be_deleted')]);
}
}
}