Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { format, startOfMonth, endOfMonth } from "date-fns"
import { ptBR } from "date-fns/locale"
import { Calculator, FileText, Eye, FileSpreadsheet, ChevronDown, ChevronRight, ExternalLink } from "lucide-react"
import * as XLSX from "xlsx"
import { formatOrderDate } from "@/lib/date-utils"
import {
Dialog,
DialogContent,
Expand Down Expand Up @@ -731,7 +732,7 @@ export default function DREReport({ selectedDate, onOpenOrder }: DREReportProps)
</TableCell>
<TableCell>{order.sector ?? "Não informado"}</TableCell>
<TableCell>
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
{formatOrderDate(order.orderDate)}
</TableCell>
<TableCell>{order.menuItemName}</TableCell>
<TableCell className="text-right">R$ {order.price.toFixed(2)}</TableCell>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { CheckCircle, Loader2 } from "lucide-react"
import { useDebounce } from "@/hooks/use-debounce"
import { type UserMinimal } from "@/trpc/react"
import { cn } from "@/lib/utils"
import { formatOrderDate } from "@/lib/date-utils"

interface OrdersTabProps {
selectedDate: Date
Expand Down Expand Up @@ -916,7 +917,7 @@ export default function OrdersTab({
</div>
<p className="text-sm">{order.menuItem.name}</p>
<p className="text-xs text-muted-foreground">
Pedido do dia {format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })} - feito às {format(new Date(order.orderTime), "HH:mm", { locale: ptBR })}
Pedido do dia {formatOrderDate(order.orderDate)} - feito às {format(new Date(order.orderTime), "HH:mm", { locale: ptBR })}
</p>
{order.observations && (
<p className="text-xs text-muted-foreground">
Expand Down
10 changes: 5 additions & 5 deletions src/app/(authenticated)/food/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { toast } from "sonner"
import { format } from "date-fns"
import { ptBR } from "date-fns/locale"
import { addDays, startOfDay } from "date-fns"
import { formatOrderDate } from "@/lib/date-utils"

const FOOD_ORDER_DEADLINE_HOUR = Number(process.env.NEXT_PUBLIC_FOOD_ORDER_DEADLINE_HOUR ?? 9)

Expand Down Expand Up @@ -138,11 +139,10 @@ export default function FoodPage() {
const restaurants = api.restaurant.listActive.useQuery()

// Buscar itens do menu do restaurante selecionado
// Definir a data do pedido conforme a regra de horário (UTC-3)
// Definir a data do pedido conforme a regra de horário
const now = new Date()
const brasiliaTime = new Date(now.getTime() - 3 * 60 * 60 * 1000) // UTC-3
const today = startOfDay(brasiliaTime)
const tomorrow = startOfDay(addDays(brasiliaTime, 1))
const today = startOfDay(now)
const tomorrow = startOfDay(addDays(now, 1))
const menuDate = now.getHours() < FOOD_ORDER_DEADLINE_HOUR ? today : tomorrow;
const menuItems = api.menuItem.byRestaurant.useQuery(
{ restaurantId: selectedRestaurant, date: menuDate },
Expand Down Expand Up @@ -607,7 +607,7 @@ export default function FoodPage() {
<p className="font-semibold text-sm md:text-base text-foreground">{order.restaurant?.name}</p>
<p className="text-xs md:text-sm text-foreground">{order.menuItem.name}</p>
<p className="text-xs text-muted-foreground font-medium">
{format(new Date(order.orderDate), "dd/MM/yyyy", { locale: ptBR })}
{formatOrderDate(order.orderDate)}
</p>
{order.observations && (
<p className="text-xs text-muted-foreground italic">Obs: {order.observations}</p>
Expand Down
140 changes: 88 additions & 52 deletions src/components/forms/create-manual-response-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client"

import { useState } from "react"
import { useState, useMemo, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
Expand All @@ -25,6 +25,7 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, Command
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Check, ChevronsUpDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { matchesSearch } from "@/lib/search-utils"
import type { Field } from "@/lib/form-types"

interface CreateManualResponseDialogProps {
Expand All @@ -47,8 +48,17 @@ export function CreateManualResponseDialog({
const [userSearchOpen, setUserSearchOpen] = useState(false)
const [userSearchValue, setUserSearchValue] = useState("")

// Buscar todos os usuários
const { data: allUsers = [], isLoading: isLoadingUsers } = api.user.listAll.useQuery()
// Buscar todos os usuários ativos com revalidação garantida
const { data: allUsers = [], isLoading: isLoadingUsers, refetch: refetchUsers } = api.user.listAll.useQuery(undefined, {
staleTime: 0,
refetchOnWindowFocus: true,
})

useEffect(() => {
if (open) {
void refetchUsers()
}
}, [open, refetchUsers])

// Criar schema dinâmico baseado nos campos do formulário
const createSchema = () => {
Expand Down Expand Up @@ -174,17 +184,29 @@ export function CreateManualResponseDialog({
}
}

// Filtrar usuários baseado na busca
const filteredUsers = allUsers.filter((user) => {
if (!userSearchValue.trim()) return true
const search = userSearchValue.toLowerCase()
const fullName = `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim().toLowerCase()
return (
fullName.includes(search) ||
user.email.toLowerCase().includes(search) ||
(user.setor?.toLowerCase().includes(search))
)
})
// Filtrar usuários baseado na busca normalizada (sem acento, case-insensitive, sem caracteres especiais)
const filteredUsers = useMemo(() => {
if (!userSearchValue.trim()) return allUsers

return allUsers.filter((user) => {
const fullName = `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim()
const filialName = user.filial?.name ?? ""
const filialCode = user.filial?.code ?? ""
const matricula = user.matricula ?? ""
const email = user.email ?? ""
const setor = user.setor ?? ""

return matchesSearch(
userSearchValue,
fullName,
email,
setor,
matricula,
filialName,
filialCode
)
})
}, [allUsers, userSearchValue])

const selectedUser = allUsers.find((u) => u.id === selectedUserId)

Expand Down Expand Up @@ -220,47 +242,61 @@ export function CreateManualResponseDialog({
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-full p-0" align="start">
<Command>
<PopoverContent className="w-[--radix-popover-trigger-width] min-w-[320px] p-0" align="start">
<Command shouldFilter={false} className="w-full">
<CommandInput
placeholder="Buscar usuário por nome, email ou setor..."
placeholder="Buscar usuário por nome, email, setor ou filial..."
value={userSearchValue}
onValueChange={setUserSearchValue}
/>
<CommandList>
<CommandEmpty>
{isLoadingUsers ? "Carregando..." : "Nenhum usuário encontrado."}
</CommandEmpty>
<CommandGroup>
{filteredUsers.map((user) => (
<CommandItem
key={user.id}
value={user.id}
onSelect={() => {
setSelectedUserId(user.id)
setUserSearchOpen(false)
setUserSearchValue("")
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedUserId === user.id ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span>
{user.firstName || user.lastName
? `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim()
: user.email}
</span>
<span className="text-xs text-muted-foreground">
{user.email} {user.setor && `• ${user.setor}`}
</span>
</div>
</CommandItem>
))}
</CommandGroup>
<CommandList className="max-h-[300px] overflow-y-auto">
{isLoadingUsers ? (
<div className="p-4 text-sm text-center text-muted-foreground flex items-center justify-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Carregando usuários ativos...
</div>
) : filteredUsers.length === 0 ? (
<CommandEmpty className="p-4 text-sm text-center text-muted-foreground">
Nenhum usuário ativo encontrado.
</CommandEmpty>
) : (
<CommandGroup heading={`Usuários Ativos (${filteredUsers.length})`}>
{filteredUsers.map((user) => {
const displayName = `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim() || user.email
const isSelected = selectedUserId === user.id
return (
<CommandItem
key={user.id}
value={user.id}
onSelect={() => {
setSelectedUserId(user.id)
setUserSearchOpen(false)
setUserSearchValue("")
}}
className="cursor-pointer flex items-center py-2 px-3 hover:bg-muted/80"
>
<Check
className={cn(
"mr-2 h-4 w-4 shrink-0 text-primary",
isSelected ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col min-w-0">
<span className="font-medium text-sm text-foreground truncate">
{displayName}
</span>
<span className="text-xs text-muted-foreground truncate">
{user.email}
{user.setor ? ` • ${user.setor}` : ""}
{user.filial?.code ? ` • ${user.filial.code}` : ""}
{user.matricula ? ` • Matrícula: ${user.matricula}` : ""}
</span>
</div>
</CommandItem>
)
})}
</CommandGroup>
)}
</CommandList>
</Command>
</PopoverContent>
Expand Down
7 changes: 7 additions & 0 deletions src/lib/date-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ export function getUtcMonthDay(date: Date): { month: number; day: number } {
}
}

export function formatOrderDate(date: Date | string): string {
const d = typeof date === "string" ? new Date(date) : date
const day = String(d.getUTCDate()).padStart(2, "0")
const month = String(d.getUTCMonth() + 1).padStart(2, "0")
const year = d.getUTCFullYear()
return `${day}/${month}/${year}`
}
23 changes: 23 additions & 0 deletions src/lib/search-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export function normalizeSearch(text: string | null | undefined): string {
return (text ?? "")
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^\w\s]/g, " ")
.replace(/\s+/g, " ")
.trim()
}

export function matchesSearch(
query: string | null | undefined,
...targets: (string | null | undefined)[]
): boolean {
const normalizedQuery = normalizeSearch(query)
if (!normalizedQuery) return true

const terms = normalizedQuery.split(/\s+/).filter(Boolean)
if (terms.length === 0) return true

const combinedTarget = normalizeSearch(targets.filter(Boolean).join(" "))
return terms.every((term) => combinedTarget.includes(term))
}
42 changes: 38 additions & 4 deletions src/server/api/routers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,32 @@ export const userRouter = createTRPCRouter({
return user;
}),

listAll: adminProcedure.query(async ({ ctx }) => {
listAll: protectedProcedure.query(async ({ ctx }) => {
const currentUser = await ctx.db.user.findUnique({
where: { id: ctx.auth.userId },
select: { role_config: true, is_active: true },
});

if (!currentUser?.is_active) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Usuário inativo",
});
}

const effectiveConfig = getEffectiveRoleConfig(currentUser);
const isSudo = !!effectiveConfig.sudo;
const hasAdminAccess = Array.isArray(effectiveConfig.admin_pages) && effectiveConfig.admin_pages.includes("/admin");
const canCreateSolicitacoes = !!effectiveConfig.can_create_solicitacoes;
const canCreateForm = !!effectiveConfig.can_create_form;

if (!isSudo && !hasAdminAccess && !canCreateSolicitacoes && !canCreateForm) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Você não tem permissão para listar usuários",
});
}

return await ctx.db.user.findMany({
where: {
is_active: true,
Expand All @@ -178,10 +203,19 @@ export const userRouter = createTRPCRouter({
setor: true,
extension: true,
emailExtension: true,
matricula: true,
filial: {
select: {
id: true,
name: true,
code: true,
},
},
},
orderBy: {
firstName: "asc",
},
orderBy: [
{ firstName: "asc" },
{ lastName: "asc" },
],
});
}),

Expand Down
Loading