feat(quotes): migrate updateQuote to transactional backend RPC#404
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
More reviews will be available in 48 minutes and 48 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
There was a problem hiding this comment.
Pull request overview
Este PR migra o fluxo de atualização de orçamentos (quotes) do frontend para uma RPC transacional no Postgres/Supabase, com o objetivo de garantir atomicidade (update + delete + reinsert de itens/personalizações) e retornar erros mais seguros para a UI.
Changes:
- Adiciona a RPC
public.update_quote_transactionalem migration SQL para executar update/delete/insert em uma única transação. - Refatora
quoteService.updateQuotepara montar payloads e chamarsupabase.rpc('update_quote_transactional', ...)em vez de múltiplas operações client-side. - Passa a sanitizar mensagens de erro via
sanitizeMessagee ajusta tipos TS (any→ tipos mais estritos).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| supabase/migrations/20260526103000_quote_update_transactional_rpc.sql | Implementa a RPC transacional para atualizar quote + recriar itens/personalizações. |
| src/services/quoteService.ts | Troca o update client-side por chamada RPC e aplica sanitização de erro + ajustes de tipagem. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| discount_value = coalesce((_quote_patch->>'discount_value')::numeric, discount_value), | ||
| subtotal = coalesce((_quote_patch->>'subtotal')::numeric, subtotal), | ||
| total_amount = coalesce((_quote_patch->>'total_amount')::numeric, total_amount), | ||
| quote_number = coalesce(_quote_patch->>'quote_number', quote_number), | ||
| expires_at = coalesce((_quote_patch->>'expires_at')::timestamptz, expires_at), |
| insert into public.quote_items ( | ||
| quote_id, product_id, product_name, quantity, unit_price, discount_percent, | ||
| discount_value, line_total, sort_order, notes | ||
| ) | ||
| values ( | ||
| _quote_id, | ||
| nullif(_item->>'product_id', '')::uuid, | ||
| _item->>'product_name', | ||
| coalesce((_item->>'quantity')::integer, 0), | ||
| coalesce((_item->>'unit_price')::numeric, 0), | ||
| coalesce((_item->>'discount_percent')::numeric, 0), | ||
| coalesce((_item->>'discount_value')::numeric, 0), | ||
| coalesce((_item->>'line_total')::numeric, 0), | ||
| coalesce((_item->>'sort_order')::integer, 0), | ||
| _item->>'notes' | ||
| ) |
| insert into public.quote_item_personalizations ( | ||
| quote_item_id, technique_id, technique_name, location, colors, dimensions, | ||
| quantity, unit_cost, total_cost, notes | ||
| ) | ||
| values ( | ||
| _new_item_id, | ||
| nullif(_pers->>'technique_id', '')::uuid, | ||
| _pers->>'technique_name', | ||
| _pers->>'location', | ||
| _pers->>'colors', | ||
| _pers->>'dimensions', | ||
| coalesce((_pers->>'quantity')::integer, 0), | ||
| coalesce((_pers->>'unit_cost')::numeric, 0), | ||
| coalesce((_pers->>'total_cost')::numeric, 0), | ||
| _pers->>'notes' | ||
| ); |
| personalizations: buildPersonalizationsInsertPayload( | ||
| items[index]?.personalizations || [], | ||
| quoteId, | ||
| ), | ||
| })); |
7e4f795 to
3af7786
Compare
…TS2322 quoteService) (#421) Rebaseado sobre o main atual (e14f8f0). Regressões pré-existentes que bloqueavam todos os PRs no CI (nenhuma introduzida por mim): - SidebarReorganized.tsx: anotação `// rls-allow` reposicionada para imediatamente acima do `.from('discount_approval_requests')` (o checker não a reconhecia 2 linhas acima). Sem mudança de comportamento. - CoverageInsightsDashboardPage.tsx: removido non-null assertion redundante (acesso já guardado por `values.length < 2`). - quoteService.ts (logHistory): `options?: Record<string,unknown>` gerava `{}` ao inserir em colunas tipadas (TS2322 ×4, vindo do #404). Campos string agora são narrowed via typeof; `metadata` cast para `Json`. Nota: o fix anterior de useUserManagement.ts foi descartado — o main já corrigiu via `untypedFrom`. Gates verdes localmente: tsc 484/486 (sem regressão), eslint (sem regressão), seller-scope (pass). https://claude.ai/code/session_01HjiGVkF3Df9GiFjDbfxDYn Co-authored-by: Claude <noreply@anthropic.com>
Motivation
quotes, remove itens/personalizações e recria itens/personalizações em uma única transação para permitir rollback completo em erro.Description
public.update_quote_transactionalemsupabase/migrations/20260526103000_quote_update_transactional_rpc.sqlque executaUPDATE quotes,DELETE quote_item_personalizations,DELETE quote_items,INSERT quote_itemseINSERT quote_item_personalizationsdentro da mesma transação.src/services/quoteService.tspara montar payloads saneados/formatados de itens e chamarsupabase.rpc('update_quote_transactional', ...)em vez de executar multiplas operações separadas no cliente.sanitizeMessagepara mapear/retornar um fallback público quando a RPC falhar, e adicionada verificação explícita de retorno vazio do RPC.src/services/quoteService.ts(any→Array<Record<string, unknown>>eoptions?: Record<string, unknown>) para satisfazer as regras de lint/TypeScript nos arquivos alterados.Testing
npm run typecheckque falhou devido a uma regressão de baseline de TypeScript em um arquivo não relacionado (src/components/admin/users/useUserManagement.ts).prettiereeslint --fix) foram executadas e passaram nos arquivos modificados após ajustes; o commit foi criado com sucesso.Codex Task
Summary by cubic
Migrated the quote update flow to a single transactional Supabase RPC to guarantee atomic writes and avoid partial updates. The service now calls the RPC with sanitized item/personalization payloads and returns user‑friendly errors.
Refactors
public.update_quote_transactionalRPC to update the quote, remove old items/personalizations, and insert new ones in one transaction (returns the updated quote row).quoteService.updateQuoteto build sanitized payloads (trimproduct_name/notes,round2unit_price, include nested personalizations), callsupabase.rpc('update_quote_transactional'), map errors viasanitizeMessage, and throw on empty RPC response.options.Migration
supabase/migrations/20260526103000_quote_update_transactional_rpc.sql.UPDATE/INSERT/DELETEfor authorized users.Written for commit 3af7786. Summary will update on new commits. Review in cubic