feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat: vínculo Empresa+Filial e DRE detalhado por empresa - #379

Merged
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre
Jun 3, 2026
Merged

feat: vínculo Empresa+Filial e DRE detalhado por empresa#379
GRHInvDev merged 1 commit into
mainfrom
378-intranet---relatorio-dre

Conversation

@rbxyz

@rbxyzrbxyz commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator
  • DRE: linha de empresa/setor expansível com lista de pessoas (nome, empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
  • Vínculo por Empresa + Filial no onboarding e na tela de Usuários; enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
  • DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de e-mail dedicado na aba de Pedidos (1.32.0)
  • Backfill SQL de filialId para colaboradores Cristallux_Filial

Summary by CodeRabbit

  • New Features

    • Expandable DRE report rows showing enterprise-sector details with order drill-down
    • Email-based filtering for orders
    • Direct navigation from DRE report to orders with pre-filled filters
  • Improvements

    • User management and profile setup now use branch (filial) selection for simplified organization
    • Version bumped to 1.32.0

- DRE: linha de empresa/setor expansível com lista de pessoas (nome,
empresa, setor, valor) e botão "Ir para o pedido" (1.30.0)
- Vínculo por Empresa + Filial no onboarding e na tela de Usuários;
enterprise derivado/sincronizado no servidor a partir da filial (1.31.0)
- DRE agrupa/exibe pela Empresa cadastrada (nome real) e novo filtro de
e-mail dedicado na aba de Pedidos (1.32.0)
- Backfill SQL de filialId para colaboradores Cristallux_Filial
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@rbxyzrbxyz linked an issue Jun 3, 2026 that may be closed by this pull request
@vercel

vercelBot commented Jun 3, 2026

Copy link
Copy Markdown

Deployment failed with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: elo.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@coderabbitai

coderabbitaiBot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors enterprise/filial management across the entire platform: enterprises are no longer provided as direct user input but are instead derived from the selected filial, affecting user profiles, the food order reporting API, and admin UI for user and DRE data management, with a historical backfill for Cristallux_Filial users.

Changes

Enterprise-from-Filial Migration

Layer / File(s)Summary
Filial-enterprise derivation contract and version update
src/server/validators/filial-enterprise.ts, package.json, src/const/app-release-notes.ts
New resolveEnterpriseFromFilial function derives enterprise directly from filial; old validator functions removed. Version bumped to 1.32.0 with release notes for 1.32.0, 1.31.0, 1.30.0.
User profile endpoints: enterprise derivation from filial
src/server/api/routers/user.ts
updateProfile, updateBasicInfo, and updateUserFilial now derive enterprise from filialId instead of accepting it as input; filialId becomes the driver for enterprise assignment.
Profile completion modal: empresa and filial selection UI
src/components/ui/complete-profile-modal.tsx
Modal reworked to support sequential empresa then filial selection with dynamic filtering and validation; setor selection added; payload updated to send filialId instead of enterprise.
Food order API: DRE period resolution and enterprise identity fields
src/server/api/routers/food-order.ts
New resolveDrePeriod helper computes UTC-normalized date ranges; DRE rows augmented with empresaId and empresaName; list endpoint filters by userEmail; new getEnterpriseSectorOrders endpoint provides order-level details for a given enterprise-sector; grouping and sorting updated to use filial-derived enterprise keys.
User management: empresa and filial linkage with unified edit
src/app/(authenticated)/admin/users/page.tsx
Fetch empresas; UserManagementCard "Dados Básicos" edit changed from single enterprise select to empresa + filial pair with dynamic filtering; old standalone "Alterar Filial" dialog and mutation removed; displayed empresa label derives from selected filial.
DRE report: expandable enterprise-sector rows with order drill-down
src/app/(authenticated)/admin/food/_components/dre-report.tsx
Added empresaKey and empresaLabel helpers for stable enterprise identity; expandedGroup state and detailQuery enable expanding rows to show nested order details; expand/collapse UI column added; "Ir para o pedido" action invokes onOpenOrder callback.
Orders tab: email filtering and food page state coordination
src/app/(authenticated)/admin/food/_components/orders-tab.tsx, src/app/(authenticated)/admin/food/page.tsx
OrdersTab accepts userEmail and filters results; collaborator filter UI split into name and email inputs; food page manages activeTab and userEmail state; handleOpenOrderFromDre sets filters and switches to orders tab when called from DRE drill-down.
Data migration: Cristallux_Filial user backfill
scripts/sql/backfill-cristallux-filial-users.sql
Backfill script links Cristallux_Filial enterprise users to target filialId with optional pre-check and EXISTS guard.

Sequence Diagrams

sequenceDiagram
participant Client
participant FoodOrderRouter
participant DREFlow
participant Database
Client->>FoodOrderRouter: getDREData(year, period, grouping)
FoodOrderRouter->>DREFlow: resolveDrePeriod(inputs)
DREFlow->>Database: query orders with date range
Database-->>DREFlow: orders with filial/empresa data
DREFlow->>DREFlow: group by empresaId+sector
DREFlow->>Database: fetch related entities (usuario, menuItem, restaurant)
Database-->>DREFlow: enriched order data
DREFlow-->>FoodOrderRouter: aggregated rows with empresaId, empresaName
FoodOrderRouter-->>Client: DRE response
Loading
sequenceDiagram
participant User
participant DREReport
participant OrdersAPI
participant OrdersTab
User->>DREReport: click expand chevron on empresa-sector row
DREReport->>DREReport: set expandedGroup state
DREReport->>OrdersAPI: getEnterpriseSectorOrders(empresa, sector, date range)
OrdersAPI-->>DREReport: list of orders with user, filial, menuItem
DREReport->>DREReport: render nested order details table
User->>DREReport: click "Ir para o pedido" action
DREReport->>OrdersTab: onOpenOrder({date, email})
OrdersTab->>OrdersTab: set userEmail and activeTab
OrdersTab->>OrdersAPI: list(userEmail=email)
OrdersAPI-->>OrdersTab: filtered orders for that user
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • GRHInvDev/elo#290: Modifies DRE report enterprise-sector grouping and allocation logic in dre-report.tsx, overlapping with this PR's enterprise identity refactoring.
  • GRHInvDev/elo#368: Earlier filial-enterprise validation changes in user.ts; this PR replaces that approach with enterprise derivation from filial via resolveEnterpriseFromFilial.
  • GRHInvDev/elo#84: Prior changes to updateProfile flow in user.ts accepting enterprise and setor; this PR refactors that same endpoint to derive enterprise from filial instead.

Poem

🐰 From input fields to filial threads,
Enterprise flows where filial leads,
Nested tables bloom with drill-down deeds,
Email filters guide the orders that breads,
A cohesive dance of linked enterprise threads! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 50.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title clearly and accurately summarizes the main changes: introducing a company-filial linkage system and detailed DRE reporting by company, which are the primary objectives of the changeset.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 378-intranet---relatorio-dre

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
scripts/sql/backfill-cristallux-filial-users.sql (1)

17-24: ⚡ Quick win

Wrap UPDATE in a transaction for safer backfill execution.

For data migration scripts, wrapping the operation in an explicit transaction provides better control and rollback capability if validation fails or errors occur.

🛡️ Proposed transaction wrapper
+BEGIN;+
-- 2) Aplicação do backfill:
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);
++-- Conferir quantas linhas foram afetadas antes de commitar:+-- Se o número estiver correto, execute: COMMIT;+-- Caso contrário, execute: ROLLBACK;

This allows you to review the affected row count before committing, and provides an explicit rollback path if needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 17 - 24, Wrap
the UPDATE that sets "filialId" for rows in "users" (WHERE "enterprise" =
'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais" WHERE "id" =
'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the transaction,
run the UPDATE, capture the affected row count for verification, and then COMMIT
if the count is as expected or ROLLBACK on error/unexpected counts to ensure
safe backfill execution; reference the UPDATE statement, the "users" table, the
"filiais" existence check, and the "filialId"/"updatedAt" assignments when
making the change.
src/app/(authenticated)/admin/food/page.tsx (1)

31-39: ⚡ Quick win

Wrap handleOpenOrderFromDre in useCallback to prevent unnecessary re-renders.

Per coding guidelines, functions passed as props should use useCallback. Currently, handleOpenOrderFromDre is recreated on every render, causing DREReport to potentially re-render unnecessarily.

♻️ Proposed fix
+import { useState, useCallback } from "react"-import { useState } from "react"
- const handleOpenOrderFromDre = ({ date, email }: { date: Date; email: string }) => {- setSelectedDate(date)- setUserEmail(email)- setUserName("")- setSelectedRestaurant("")- setSelectedStatus("")- setActiveTab("orders")- }+ const handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email: string }) => {+ setSelectedDate(date)+ setUserEmail(email)+ setUserName("")+ setSelectedRestaurant("")+ setSelectedStatus("")+ setActiveTab("orders")+ }, [])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/page.tsx around lines 31 - 39, Wrap the
handleOpenOrderFromDre function in React's useCallback to avoid recreation on
every render and prevent unnecessary re-renders of child components like
DREReport; specifically, replace the inline function declaration of
handleOpenOrderFromDre with a const handleOpenOrderFromDre = useCallback(({
date, email }: { date: Date; email: string }) => { setSelectedDate(date);
setUserEmail(email); setUserName(""); setSelectedRestaurant("");
setSelectedStatus(""); setActiveTab("orders"); }, [setSelectedDate,
setUserEmail, setUserName, setSelectedRestaurant, setSelectedStatus,
setActiveTab]) so the callback only changes when its setter dependencies change.
src/app/(authenticated)/admin/food/_components/orders-tab.tsx (1)

853-859: ⚖️ Poor tradeoff

Consider adding debounce to search inputs.

Both the name and email filter inputs trigger API calls on every keystroke. As per coding guidelines, search inputs and expensive async operations should implement debounce. While this follows the existing pattern for userName, adding debounce would reduce unnecessary API calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx around lines
853 - 859, The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 22-24: Update the EXISTS condition so it verifies the filial's
empresa has enterprise = 'Cristallux_Filial' rather than just checking the
filial exists; specifically, change the subquery against "filiais" (for id
'cmpxzjlta000gjk04dvipce45') to join the related empresa row and assert
empresa.enterprise = 'Cristallux_Filial' (ensuring consistency with
resolveEnterpriseFromFilial logic that derives enterprise from
filial.empresa.enterprise).
- Around line 18-21: The UPDATE statement for table "users" currently updates
every row with "enterprise" = 'Cristallux_Filial'; modify the UPDATE so it
matches the pre-check by adding an idempotency guard comparing "filialId" to the
target value using IS DISTINCT FROM (i.e., only update rows where "filialId" IS
DISTINCT FROM 'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW()
assignment; this ensures only users that actually need the change are updated
and makes the script safe to re-run.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx:
- Around line 694-761: The expanded nested row is using a hardcoded colSpan={7}
which is too small when groupBy === "enterprise_sector" (table has 8 columns);
modify the TableCell that currently uses colSpan={7} to compute the span
dynamically—e.g. replace it with colSpan={groupBy === "enterprise_sector" ? 8 :
7} or compute a visibleColumns count and use colSpan={visibleColumns} so the
nested table always spans the full width (update the TableCell in the isExpanded
block where detailQuery is rendered).
---
Nitpick comments:
In `@scripts/sql/backfill-cristallux-filial-users.sql`:
- Around line 17-24: Wrap the UPDATE that sets "filialId" for rows in "users"
(WHERE "enterprise" = 'Cristallux_Filial' AND EXISTS (SELECT 1 FROM "filiais"
WHERE "id" = 'cmpxzjlta000gjk04dvipce45')) in an explicit transaction: BEGIN the
transaction, run the UPDATE, capture the affected row count for verification,
and then COMMIT if the count is as expected or ROLLBACK on error/unexpected
counts to ensure safe backfill execution; reference the UPDATE statement, the
"users" table, the "filiais" existence check, and the "filialId"/"updatedAt"
assignments when making the change.
In `@src/app/`(authenticated)/admin/food/_components/orders-tab.tsx:
- Around line 853-859: The userEmail input currently updates on every keystroke
(value={userEmail}, onChange={e => setUserEmail(e.target.value)}), causing
immediate API calls; implement debounce for the email filter analogous to the
existing userName pattern by introducing a debouncedEmail (via the same
useDebounce hook or lodash.debounce) and use the debounced value to trigger the
orders fetch instead of userEmail, or debounce the function that performs the
API call (e.g., fetchOrders); update the Input handler to still setUserEmail
immediately but ensure API calls read debouncedEmail so rapid keystrokes do not
fire requests.
In `@src/app/`(authenticated)/admin/food/page.tsx:
- Around line 31-39: Wrap the handleOpenOrderFromDre function in React's
useCallback to avoid recreation on every render and prevent unnecessary
re-renders of child components like DREReport; specifically, replace the inline
function declaration of handleOpenOrderFromDre with a const
handleOpenOrderFromDre = useCallback(({ date, email }: { date: Date; email:
string }) => { setSelectedDate(date); setUserEmail(email); setUserName("");
setSelectedRestaurant(""); setSelectedStatus(""); setActiveTab("orders"); },
[setSelectedDate, setUserEmail, setUserName, setSelectedRestaurant,
setSelectedStatus, setActiveTab]) so the callback only changes when its setter
dependencies change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c554e447-4569-47a6-a143-5fcdd2b4a713

📥 Commits

Reviewing files that changed from the base of the PR and between 04eb3db and 0f35f5a.

📒 Files selected for processing (11)
  • package.json
  • scripts/sql/backfill-cristallux-filial-users.sql
  • src/app/(authenticated)/admin/food/_components/dre-report.tsx
  • src/app/(authenticated)/admin/food/_components/orders-tab.tsx
  • src/app/(authenticated)/admin/food/page.tsx
  • src/app/(authenticated)/admin/users/page.tsx
  • src/components/ui/complete-profile-modal.tsx
  • src/const/app-release-notes.ts
  • src/server/api/routers/food-order.ts
  • src/server/api/routers/user.ts
  • src/server/validators/filial-enterprise.ts

Comment on lines +18 to +21
UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add idempotency filter to match the pre-check query.

The UPDATE lacks the IS DISTINCT FROM filter that appears in the pre-check query (line 15), causing inconsistent behavior:

  • Pre-check counts users whose filialId differs from the target
  • UPDATE modifies all enterprise='Cristallux_Filial' users, even those already linked to the target filial
  • Running the script multiple times will unnecessarily update updatedAt for already-correct rows
♻️ Proposed fix to add idempotency guard
 UPDATE "users"
SET "filialId" = 'cmpxzjlta000gjk04dvipce45',
"updatedAt" = NOW()
WHERE "enterprise" = 'Cristallux_Filial'
+ AND ("filialId" IS DISTINCT FROM 'cmpxzjlta000gjk04dvipce45')
AND EXISTS (

This ensures the script only updates users who need the change, making it safely re-runnable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 18 - 21, The
UPDATE statement for table "users" currently updates every row with "enterprise"
= 'Cristallux_Filial'; modify the UPDATE so it matches the pre-check by adding
an idempotency guard comparing "filialId" to the target value using IS DISTINCT
FROM (i.e., only update rows where "filialId" IS DISTINCT FROM
'cmpxzjlta000gjk04dvipce45'), and keep the "updatedAt" = NOW() assignment; this
ensures only users that actually need the change are updated and makes the
script safe to re-run.

Comment on lines +22 to +24
AND EXISTS (
SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate that the target filial's empresa matches Cristallux_Filial.

The EXISTS check verifies that the filial exists but doesn't validate that its empresa.enterprise corresponds to 'Cristallux_Filial'. This creates a critical data integrity risk:

  • After backfill, users will have enterprise='Cristallux_Filial' but filialId pointing to a filial whose empresa.enterprise might differ
  • When these users are updated via the API, enterprise will be synced to match the filial's empresa (per resolveEnterpriseFromFilial logic in context)
  • This could break reports or queries filtering by enterprise='Cristallux_Filial'
🔒 Proposed fix to validate empresa compatibility
 WHERE "enterprise" = 'Cristallux_Filial'
AND EXISTS (
- SELECT 1 FROM "filiais" WHERE "id" = 'cmpxzjlta000gjk04dvipce45'+ SELECT 1 + FROM "filiais" f+ JOIN "empresas" e ON f."empresaId" = e."id"+ WHERE f."id" = 'cmpxzjlta000gjk04dvipce45'+ AND e."enterprise" = 'Cristallux_Filial'
);

This ensures the target filial belongs to an empresa with enterprise='Cristallux_Filial', preventing data inconsistency.

Based on learnings from context: resolveEnterpriseFromFilial derives enterprise from filial.empresa.enterprise, and API updates sync the enterprise field when filialId changes.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
AND EXISTS (
SELECT1FROM"filiais"WHERE"id"='cmpxzjlta000gjk04dvipce45'
);
AND EXISTS (
SELECT1
FROM"filiais" f
JOIN"empresas" e ON f."empresaId"= e."id"
WHERE f."id"='cmpxzjlta000gjk04dvipce45'
AND e."enterprise"='Cristallux_Filial'
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@scripts/sql/backfill-cristallux-filial-users.sql` around lines 22 - 24,
Update the EXISTS condition so it verifies the filial's empresa has enterprise =
'Cristallux_Filial' rather than just checking the filial exists; specifically,
change the subquery against "filiais" (for id 'cmpxzjlta000gjk04dvipce45') to
join the related empresa row and assert empresa.enterprise = 'Cristallux_Filial'
(ensuring consistency with resolveEnterpriseFromFilial logic that derives
enterprise from filial.empresa.enterprise).

Comment on lines +694 to +761
{isExpanded ? (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={7} className="bg-muted/30 p-0">
<div className="p-3">
{detailQuery.isLoading ? (
<p className="py-2 text-sm text-muted-foreground">Carregando pedidos...</p>
) : detailQuery.isError ? (
<p className="py-2 text-sm text-muted-foreground">
Erro ao carregar os pedidos deste grupo.
</p>
) : detailQuery.data && detailQuery.data.length > 0 ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>Pessoa</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Setor</TableHead>
<TableHead>Data do pedido</TableHead>
<TableHead>Prato</TableHead>
<TableHead className="text-right">Valor (R$)</TableHead>
<TableHead className="text-right">Pedido</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{detailQuery.data.map((order) => (
<TableRow key={order.id}>
<TableCell>
<div className="font-medium">{order.userName || "—"}</div>
<div className="text-xs text-muted-foreground">{order.email}</div>
</TableCell>
<TableCell>
<Badge variant="outline">{order.empresaName ?? order.enterprise}</Badge>
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
<TableCell className="text-right">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={(e) => {
e.stopPropagation()
onOpenOrder?.({
date: new Date(order.orderDate),
email: order.email,
})
}}
>
<ExternalLink className="h-3.5 w-3.5" />
Ir para o pedido
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<p className="py-2 text-sm text-muted-foreground">
Nenhum pedido encontrado para este grupo.
</p>
)}
</div>
</TableCell>
</TableRow>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Incorrect colSpan value for expanded row.

The expanded row uses colSpan={7}, but when groupBy === "enterprise_sector", the table has 8 columns: expand icon + Empresa + Setor + Pedidos + Valor + Representatividade + Rateio = 7 visible data columns, plus the new expand column = 8 total. This mismatch may cause the nested table to not span the full width.

🐛 Proposed fix
- <TableCell colSpan={7} className="bg-muted/30 p-0">+ <TableCell colSpan={8} className="bg-muted/30 p-0">
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`(authenticated)/admin/food/_components/dre-report.tsx around lines
694 - 761, The expanded nested row is using a hardcoded colSpan={7} which is too
small when groupBy === "enterprise_sector" (table has 8 columns); modify the
TableCell that currently uses colSpan={7} to compute the span dynamically—e.g.
replace it with colSpan={groupBy === "enterprise_sector" ? 8 : 7} or compute a
visibleColumns count and use colSpan={visibleColumns} so the nested table always
spans the full width (update the TableCell in the isExpanded block where
detailQuery is rendered).

@GRHInvDev
GRHInvDev merged commit 623fbdb into mainJun 3, 2026
7 of 9 checks passed
Sign up for freeto 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.

INTRANET - relatorio DRE

2 participants

@rbxyz@GRHInvDev