laravel-vuexy-store-manager/Services/StoreCatalogService.php
2025-03-05 20:43:35 -06:00

118 lines
3.5 KiB
PHP

<?php
namespace Koneko\VuexyStoreManager\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class StoreCatalogService
{
/**
* Definición de catálogos disponibles.
*/
protected array $catalogs = [
'stores' => [
'table' => 'stores',
'key' => 'id',
'value' => 'name AS item',
'order_by' => 'name',
'search_columns' => ['code', 'name'],
'use_status' => true,
'limit' => 50
],
'work_centers' => [
'table' => 'store_work_centers',
'key' => 'id',
'value' => "CONCAT_WS(' - ', code , name) as item",
'search_columns' => ['code', 'name'],
'extra_conditions' => ['store_id'],
'limit' => 50
],
'currencies' => [
'table' => 'currencies',
'key' => 'code',
'value' => "CONCAT_WS(' - ', code , name) as item",
'order_by' => 'name',
'search_columns' => ['code', 'name'],
'limit' => 20
],
'email_transactions' => [
'table' => 'email_transactions',
'key' => 'id',
'value' => "CONCAT('Email ', id) as item",
'order_by' => 'created_at',
'limit' => 10
]
];
/**
* Busca en un catálogo definido.
*
* @param string $catalog Nombre del catálogo.
* @param string $searchTerm Término de búsqueda opcional.
* @param array $options Opciones adicionales de filtrado.
* @return array
*/
public function searchCatalog(string $catalog, string $searchTerm = '', array $options = []): array
{
if (!isset($this->catalogs[$catalog])) {
return [];
}
$config = $this->catalogs[$catalog];
$query = DB::table($config['table']);
// Selección de columnas
$query->selectRaw("{$config['key']}, {$config['value']}");
// Filtrar por estado si es necesario
if (($config['use_status'] ?? false) === true) {
$query->where('status', $options['status'] ?? true);
}
// Aplicar filtros adicionales
if (!empty($config['extra_conditions'])) {
foreach ($config['extra_conditions'] as $field) {
if (isset($options[$field])) {
$query->where($field, $options[$field]);
}
}
}
// Aplicar búsqueda si se proporciona un término
if (!empty($searchTerm) && !empty($config['search_columns'])) {
$query->where(function ($subQuery) use ($config, $searchTerm) {
foreach ($config['search_columns'] as $column) {
$subQuery->orWhere($column, 'LIKE', "%{$searchTerm}%");
}
});
}
// Ordenación
$query->orderBy($config['order_by'] ?? $config['key'], 'asc');
// Límite de resultados
if (isset($config['limit'])) {
$query->limit($config['limit']);
}
// Modos de salida: `raw`, `select2`, `pluck`
$rawMode = $options['rawMode'] ?? false;
$select2Mode = $options['select2Mode'] ?? false;
if ($rawMode) {
return $query->get()->toArray();
}
if ($select2Mode) {
return $query->get()->map(fn ($row) => [
'id' => $row->{$config['key']},
'text' => $row->item
])->toArray();
}
return $query->pluck('item', $config['key'])->toArray();
}
}