Skip to content

fix(search): align global search telemetry with search_analytics schema#338

Merged
adm01-debug merged 1 commit into
mainfrom
fix/search-analytics-global-search-2026-05-25
May 25, 2026
Merged

fix(search): align global search telemetry with search_analytics schema#338
adm01-debug merged 1 commit into
mainfrom
fix/search-analytics-global-search-2026-05-25

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 25, 2026

Contexto

Follow-up cirúrgico do #329 (já mergeado). O PR #329 corrigiu o mesmo bug em useProductAnalytics.ts, mas passou batido em useGlobalSearch.ts (linha ~713) — que tem o mesmo insert quebrado em search_analytics.

Bug

O insert estava enviando duas colunas que não existem em public.search_analytics:

Código antes Schema real
seller_id: sellerId coluna correta é user_id
filters_used: { ... } (jsonb-like) coluna correta é search_context text

Schema confirmado via SQL contra o banco vivo (`doufsxqlfjyuvxuezpln`):

```
search_analytics columns:
id uuid NOT NULL
user_id uuid NULL
search_term text NOT NULL
results_count integer NOT NULL
search_context text NULL
created_at timestamptz NOT NULL
```

Impacto runtime: todo insert da busca global retornava `PGRST204` (column not found) silenciosamente, quebrando completamente a telemetria de busca. O `.then(() => undefined, () => undefined)` engolia o erro.

Fix

```diff

  •      const sellerId = data.user?.id;
    
  •      if (!sellerId) return;
    
  •      const userId = data.user?.id;
    
  •      if (!userId) return;
         return supabase
           .from('search_analytics')
           .insert({
    
  •          seller_id: sellerId,
    
  •          user_id: userId,
             search_term: searchQuery.toLowerCase().trim().slice(0, 200),
             results_count: finalResults.length,
    
  •          filters_used: { latency_ms: latencyMs, intent_type: intent.type },
    
  •          search_context: JSON.stringify({ latency_ms: latencyMs, intent_type: intent.type }),
           })
    

```

O payload (`latency_ms` + `intent_type`) é serializado como JSON dentro de `search_context` porque a coluna é `text`, não `jsonb`. Quem for consumir essa telemetria depois pode fazer `(search_context::jsonb)->>'intent_type'` no SQL.

Validação

  • ✅ 4 inserções / 4 deleções (mesmo arquivo, mesmo bloco)
  • ✅ ESLint baseline gate no pre-push: zero regressões (drift positivo: −8 erros)
  • ⏳ Typecheck completo + build deixados para o CI (gateway timeout no run local com 3600 arquivos)
  • ⚠️ Não foi possível exercitar a UI ao vivo neste ambiente

Por que não foi no #329

O #329 tocou `useProductAnalytics.ts` (telemetria de visualização de produto) mas não `useGlobalSearch.ts` (telemetria de busca global). Mesma tabela, mesma raiz, dois call sites — o segundo foi descoberto na auditoria pós-merge.

Próximo (não escopo deste PR)

A descrição do #329 menciona drift de schema na personalização (`product_group_` / `product_component_` referenciando colunas que não existem no DB). Continua aberto e requer decisão de produto.


Summary by cubic

Fixes global search telemetry to match the public.search_analytics schema, preventing PGRST204 column errors and restoring metrics collection. Applies the same fix missed in useGlobalSearch.ts that was done in #329.

  • Bug Fixes
    • Use user_id instead of seller_id.
    • Write payload to search_context (text) as a JSON string: { latency_ms, intent_type }.
    • Keep early return if no userId to avoid invalid inserts.

Written for commit 07e9b9f. Summary will update on new commits. Review in cubic

Same bug as #329 fixed in useProductAnalytics.ts but missed in
useGlobalSearch.ts. Insert was sending columns that do not exist in
public.search_analytics:

  - seller_id      → user_id      (column name mismatch)
  - filters_used   → search_context  (column does not exist; the
                                      schema has search_context text)

Validated against live DB (doufsxqlfjyuvxuezpln):
  search_analytics columns are id, user_id, search_term, results_count,
  search_context, created_at — no seller_id, no filters_used.

Without this fix every global search insert was rejected with PGRST204
(column not found), silently breaking search telemetry.

The latency+intent payload is now serialized as JSON into search_context
(text) since the new column type is text, not jsonb.
Copilot AI review requested due to automatic review settings May 25, 2026 13:37
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 25, 2026

Warning

Review limit reached

@adm01-debug, we couldn't start this review because you've used your available PR reviews for now.

Your plan includes 5 reviews of capacity. Refill in 22 minutes and 51 seconds.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more review capacity refills, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1fd1e5f9-0735-4a49-93d3-743b2c87bc12

📥 Commits

Reviewing files that changed from the base of the PR and between 0277526 and 07e9b9f.

📒 Files selected for processing (1)
  • src/components/search/useGlobalSearch.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/search-analytics-global-search-2026-05-25

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel
Copy link
Copy Markdown

vercel Bot commented May 25, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 25, 2026 1:38pm

@supabase
Copy link
Copy Markdown

supabase Bot commented May 25, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR restores global search telemetry by aligning the search_analytics insert in useGlobalSearch.ts with the live public.search_analytics schema (matching the fix previously applied elsewhere in #329), preventing PGRST204 “column not found” failures and allowing metrics to be recorded again.

Changes:

  • Writes user_id instead of the non-existent seller_id.
  • Serializes the telemetry payload into search_context (text) instead of the non-existent filters_used.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants