feat(category): include products from all descendant categories in paginated response

This commit is contained in:
2026-09-24 16:28:15 -03:00
parent 41c0902b83
commit cf3f0ceb1b
2 changed files with 63 additions and 6 deletions

View File

@@ -2,8 +2,6 @@
namespace App\Domains\Commerce\Catalog\Services;
use App\Shared\Attachable\Models\Attachment;
use App\Shared\Attachable\Services\AttachmentService;
use App\Domains\Commerce\Catalog\Enums\CatalogItemType;
use App\Domains\Commerce\Catalog\Models\Attribute;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
@@ -11,8 +9,10 @@ use App\Domains\Commerce\Catalog\Models\Category;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\ItemAttribute;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Shared\Attachable\Models\Attachment;
use App\Shared\Attachable\Services\AttachmentService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
@@ -286,9 +286,11 @@ class CatalogService
int $perPage,
int $page,
): LengthAwarePaginator {
$categoryIds = $this->categoryAndDescendantIds($tenant, $category);
return CatalogItem::query()
->forTenantCatalog($tenant)
->where('category_id', $category->id)
->whereIn('category_id', $categoryIds)
->whereAvailable()
->with([
'attachments',
@@ -306,6 +308,34 @@ class CatalogService
->paginate(perPage: $perPage, pageName: 'page', page: $page);
}
/** @return array<int, int> */
private function categoryAndDescendantIds(Tenant $tenant, Category $category): array
{
$childrenByParent = Category::query()
->where('tenant_code', $tenant->codigo)
->get(['id', 'categoria_id'])
->groupBy('categoria_id');
$categoryIds = [];
$pendingIds = [$category->id];
while ($pendingIds !== []) {
$categoryId = array_shift($pendingIds);
if (isset($categoryIds[$categoryId])) {
continue;
}
$categoryIds[$categoryId] = $categoryId;
foreach ($childrenByParent->get($categoryId, collect()) as $child) {
$pendingIds[] = $child->id;
}
}
return array_values($categoryIds);
}
public function delete(CatalogItem $catalogItem): void
{
DB::transaction(function () use ($catalogItem): void {