feat: implement NotePopover component for managing user notes and integrate it into UsersTable and RichiesteTable

This commit is contained in:
Marco Pedone 2026-03-27 18:10:17 +01:00
parent b0c00e2d0f
commit 9452535a9f
6 changed files with 328 additions and 99 deletions

View file

@ -0,0 +1,71 @@
import { NotebookPen } from "lucide-react";
import { useState } from "react";
import LoadingButton from "~/components/custom_ui/loading-button";
import { Button } from "~/components/ui/button";
import {
Popover,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
} from "~/components/ui/popover";
import { Textarea } from "~/components/ui/textarea";
import type { UsersId } from "~/schemas/public/Users";
export const NotePopover = ({
userId,
note,
mutate,
isPending,
}: {
userId: UsersId;
note: string | null;
mutate: (data: { id: UsersId; data: { note: string | null } }) => void;
isPending: boolean;
}) => {
const [newNote, setNewNote] = useState<string | null>(note);
return (
<Popover>
<PopoverTrigger asChild>
<div className="relative inline-flex">
<Button className="inline-flex" size="sm" variant="orange">
<NotebookPen className="size-4" />
</Button>
{note && note.trim().length > 0 && (
<span className="absolute top-0 right-0 -mt-1 -mr-1 flex size-3">
<span className="relative inline-flex size-3 rounded-full bg-green-500"></span>
</span>
)}
</div>
</PopoverTrigger>
<PopoverContent
align="start"
className="max-h-[50vh] w-[80vw] overflow-y-auto sm:max-h-full sm:w-lg"
>
<PopoverHeader>
<PopoverTitle>Annunci Inseriti</PopoverTitle>
<PopoverDescription className="sr-only">Desc</PopoverDescription>
</PopoverHeader>
<div className="flex w-full flex-col gap-4">
<Textarea
className="min-h-64"
id="note"
onChange={(e) => setNewNote(e.target.value)}
placeholder=""
value={newNote || ""}
/>
<LoadingButton
disabled={newNote === note}
loading={isPending}
onClick={() => mutate({ id: userId, data: { note: newNote } })}
variant="success"
>
Salva
</LoadingButton>
</div>
</PopoverContent>
</Popover>
);
};

View file

@ -1,9 +1,10 @@
import type { Table } from "@tanstack/react-table";
import { format } from "date-fns";
import { NotebookPen, Toolbox } from "lucide-react";
import Image from "next/image";
import { useState } from "react";
import { type RefObject, useState } from "react";
import toast from "react-hot-toast";
import LoadingButton from "~/components/custom_ui/loading-button";
import { Textarea } from "~/components/custom_ui/textarea";
import {
AdminActions,
UserActions,
@ -13,13 +14,17 @@ import { Textarea } from "~/components/ui/textarea";
import { useMediaQuery } from "~/hooks/use-media-query";
import { handleConsegna } from "~/lib/annuncio_details";
import { getStorageUrl } from "~/lib/storage_utils";
import { MutationPageRestore } from "~/lib/tableUtils";
import { cn, formatCurrency } from "~/lib/utils";
import { useTranslation } from "~/providers/I18nProvider";
import { useServizio, useServizioAnnuncio } from "~/providers/ServizioProvider";
import type { AnnunciId } from "~/schemas/public/Annunci";
import type { ServizioServizioId } from "~/schemas/public/Servizio";
import type { AnnuncioRicerca } from "~/server/controllers/annunci.controller";
import type { ServizioAnnuncioData } from "~/server/controllers/servizio.controller";
import type {
RichiesteData,
ServizioAnnuncioData,
} from "~/server/controllers/servizio.controller";
import { api } from "~/utils/api";
import { Button } from "../ui/button";
import {
@ -111,6 +116,100 @@ export const AnnuncioCardContent = ({
</Card>
);
};
export const AnnuncioCardRichieste = ({
tableRef,
data,
}: {
tableRef: RefObject<Table<RichiesteData> | null>;
data: ServizioAnnuncioData;
}) => {
const [newNote, setNewNote] = useState<string | null>(data.note);
const utils = api.useUtils();
const { onMutate, onSettled } = MutationPageRestore(tableRef);
const { mutate, isPending } = api.servizio.updateServizioAnnunci.useMutation({
onMutate,
onSettled,
onSuccess: async () => {
toast.success("Note aggiornate");
await utils.servizio.invalidate();
},
onError: () => {
toast.error("Errore nell'aggiornamento note");
},
});
const isDesktop = useMediaQuery("(min-width: 40rem)");
return (
<Card className="w-full max-w-7xl gap-2 rounded-md border-none bg-muted py-3">
<CardHeader className="flex flex-row flex-wrap items-center justify-between space-y-0 px-3 pb-2">
<CardTitle className="text-2xl">Annuncio {data.codice}</CardTitle>
</CardHeader>
<CardContent className="px-3">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[2fr_1fr]">
<div
className={cn("@container flex w-full flex-col gap-4")}
id="container"
>
<AnnuncioDisplay data={data} />
<div className="flex w-full flex-col gap-4">
<div>
<p>
Visto contatti:{" "}
{data.open_contatti_at
? format(data.open_contatti_at, "dd/MM/yyyy HH:mm")
: "Non ancora visto"}
</p>
{/*TODO CAPIRE COSA AGGIUNGERE */}
</div>
</div>
</div>
<Collapsible
className={cn("space-y-2", isDesktop && "relative -top-10")}
open={isDesktop || undefined}
>
<CollapsibleTrigger asChild>
<Button
className={cn(isDesktop && "cursor-default")}
size="sm"
variant={isDesktop ? "flat" : "outline"}
>
<NotebookPen />
<span>Annotazioni</span>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="">
<div className="flex w-full flex-col gap-2">
<Textarea
className="min-h-64"
id={`note-${data.id}`}
onChange={(e) => setNewNote(e.target.value)}
placeholder=""
value={newNote || ""}
/>
<LoadingButton
disabled={newNote === data.note}
loading={isPending}
onClick={() => {
mutate({
annuncioId: data.id,
servizioId: data.servizio_id,
data: { note: newNote },
});
}}
type="button"
variant="success"
>
Salva
</LoadingButton>
</div>
</CollapsibleContent>
</Collapsible>
</div>
</CardContent>
</Card>
);
};
const AnnuncioNote = ({
servizioId,

View file

@ -1,20 +1,20 @@
import type { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import type { ColumnDef, Table } from "@tanstack/react-table";
import { add, format, formatDuration, intervalToDuration } from "date-fns";
import { it } from "date-fns/locale";
import {
CircleCheck,
CircleCheckBig,
CircleEllipsis,
ClockFading,
ExternalLink,
NotebookPen,
SearchX,
} from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { useRef } from "react";
import toast from "react-hot-toast";
import LoadingButton from "~/components/custom_ui/loading-button";
import { Textarea } from "~/components/custom_ui/textarea";
import { AnnuncioCardContent } from "~/components/servizio/annuncio_card";
import { NotePopover } from "~/components/notePopover";
import { AnnuncioCardRichieste } from "~/components/servizio/annuncio_card";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { DataTable } from "~/components/ui/data-table";
@ -37,9 +37,9 @@ import {
TooltipTrigger,
} from "~/components/ui/tooltip";
import { UserAvatar } from "~/components/user_avatar";
import { MutationPageRestore } from "~/lib/tableUtils";
import { cn } from "~/lib/utils";
import TipologiaPosizioneEnum from "~/schemas/public/TipologiaPosizioneEnum";
import type { UsersId } from "~/schemas/public/Users";
import type { RichiesteData } from "~/server/controllers/servizio.controller";
import { api } from "~/utils/api";
@ -57,6 +57,7 @@ export const RichiesteTable = ({ data }: RichiesteTableProps) => {
status: "Status",
tipologia: "Tipo",
annunci: "Annunci",
interruzione_expires_at: "Scad. interr.",
actions: "Azioni",
};
const statusOptions = [
@ -72,9 +73,13 @@ export const RichiesteTable = ({ data }: RichiesteTableProps) => {
];
type Column = (typeof tabledata)[number];
const tableRef = useRef<Table<Column> | null>(null);
const utils = api.useUtils();
const { onMutate, onSettled } = MutationPageRestore(tableRef);
const { mutate, isPending } = api.users.editUser.useMutation({
onMutate,
onSettled,
onSuccess: async () => {
toast.success("Note aggiornate con successo");
await utils.users.invalidate();
@ -276,6 +281,54 @@ export const RichiesteTable = ({ data }: RichiesteTableProps) => {
<DataTableColumnHeader column={column} title={columns_titles.status} />
),
},
{
accessorKey: "interruzione_expires_at",
cell: ({ row }) => {
if (row.original.isInterrotto) return "---";
if (!row.original.decorrenza) return "---";
const expiresAt = add(row.original.decorrenza, {
days: row.original.interruzioneDays,
});
const timeLeft = intervalToDuration({
start: new Date(),
end: expiresAt,
});
const daysLeft = timeLeft.days || 0;
let badgeColor = "";
if (daysLeft > 5) {
badgeColor = "border-green-500 bg-green-500/10 text-green-500";
} else if (daysLeft > 0) {
badgeColor = "border-yellow-500 bg-yellow-500/10 text-yellow-500";
} else {
badgeColor = "border-red-500 bg-red-500/10 text-red-500";
}
return (
<Tooltip>
<TooltipTrigger>
<Badge className={cn("px-1.5", badgeColor)} variant="outline">
{format(expiresAt, "dd/MM")}
</Badge>
</TooltipTrigger>
<TooltipContent>
{daysLeft > 0 ? (
<p>
{formatDuration(timeLeft, { locale: it, format: ["days"] })}{" "}
rimanenti
</p>
) : (
<p>Interruzione scaduta</p>
)}
</TooltipContent>
</Tooltip>
);
},
header: ({ column }) => (
<DataTableColumnHeader
column={column}
title={columns_titles.interruzione_expires_at}
/>
),
},
{
accessorKey: "annunci_servizio",
cell: ({ row }) => {
@ -289,7 +342,7 @@ export const RichiesteTable = ({ data }: RichiesteTableProps) => {
</PopoverTrigger>
<PopoverContent
align="end"
className="max-h-[50vh] w-[80vw] overflow-y-auto sm:max-h-full sm:w-4xl"
className="max-h-[50vh] w-[80vw] overflow-y-auto sm:max-h-full"
>
<PopoverHeader>
<PopoverTitle>Annunci Inseriti</PopoverTitle>
@ -299,21 +352,10 @@ export const RichiesteTable = ({ data }: RichiesteTableProps) => {
</PopoverHeader>
<div className="flex flex-col gap-4 divide-y">
{annunci.map((a) => (
<AnnuncioCardContent
<AnnuncioCardRichieste
data={a}
interactions={
<div>
<p>
Visto contatti:{" "}
{a.open_contatti_at
? format(a.open_contatti_at, "dd/MM/yyyy HH:mm")
: "Non ancora visto"}
</p>
{/*TODO CAPIRE COSA AGGIUNGERE */}
</div>
}
isAdmin
key={a.annunci_id}
tableRef={tableRef}
/>
))}
</div>
@ -370,66 +412,10 @@ export const RichiesteTable = ({ data }: RichiesteTableProps) => {
columns_titles={columns_titles}
data={tabledata}
defaultSort={[{ desc: true, id: "decorrenza" }]}
onTableInit={(t) => (tableRef.current = t)}
pinnedFiltri={pinnedFiltri}
searchColumn={searchFiltro}
/>
</div>
);
};
const NotePopover = ({
userId,
note,
mutate,
isPending,
}: {
userId: UsersId;
note: string | null;
mutate: (data: { id: UsersId; data: { note: string | null } }) => void;
isPending: boolean;
}) => {
const [newNote, setNewNote] = useState<string | null>(note);
return (
<Popover>
<PopoverTrigger asChild>
<div className="relative inline-flex">
<Button className="inline-flex" size="sm" variant="orange">
<NotebookPen className="size-4" />
</Button>
{note && note.trim().length > 0 && (
<span className="absolute top-0 right-0 -mt-1 -mr-1 flex size-3">
<span className="relative inline-flex size-3 rounded-full bg-green-500"></span>
</span>
)}
</div>
</PopoverTrigger>
<PopoverContent
align="start"
className="max-h-[50vh] w-[80vw] overflow-y-auto sm:max-h-full sm:w-lg"
>
<PopoverHeader>
<PopoverTitle>Annunci Inseriti</PopoverTitle>
<PopoverDescription className="sr-only">Desc</PopoverDescription>
</PopoverHeader>
<div className="flex w-full flex-col gap-4">
<Textarea
className="min-h-64"
id="note"
onChange={(e) => setNewNote(e.target.value)}
placeholder=""
value={newNote || ""}
/>
<LoadingButton
disabled={newNote === note}
loading={isPending}
onClick={() => mutate({ id: userId, data: { note: newNote } })}
variant="success"
>
Salva
</LoadingButton>
</div>
</PopoverContent>
</Popover>
);
};

View file

@ -1,4 +1,4 @@
import type { ColumnDef } from "@tanstack/react-table";
import type { ColumnDef, Table } from "@tanstack/react-table";
import {
Crown,
Mail,
@ -14,8 +14,9 @@ import {
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/router";
import { useState } from "react";
import { useRef, useState } from "react";
import toast from "react-hot-toast";
import { NotePopover } from "~/components/notePopover";
import { DataTable } from "~/components/ui/data-table";
import { DataTableColumnHeader } from "~/components/ui/dataTable-header";
import type {
@ -23,9 +24,11 @@ import type {
SearchFiltro,
} from "~/components/ui/dataTable-toolbar";
import { UserAvatar } from "~/components/user_avatar";
import { MutationPageRestore } from "~/lib/tableUtils";
import { cn } from "~/lib/utils";
import type { Etichette } from "~/schemas/public/Etichette";
import type { Users, UsersId } from "~/schemas/public/Users";
import type { UsersId } from "~/schemas/public/Users";
import type { UserWChatInfo } from "~/server/controllers/user.controller";
import { api } from "~/utils/api";
import { Etichetta } from "../etichette";
import { WhatsAppIcon2 } from "../svgs";
@ -45,17 +48,6 @@ import {
} from "../ui/dialog";
import { Separator } from "../ui/separator";
type UserWChatInfo = Pick<
Users,
| "id"
| "username"
| "email"
| "telefono"
| "isAdmin"
| "isBlocked"
| "created_at"
> & { chatid: string | null; etichette: Etichette[] };
export const UsersTable = (props: { data: UserWChatInfo[] }) => {
const router = useRouter();
const { mutateAsync: swap } = api.auth.swapUser.useMutation({
@ -78,6 +70,7 @@ export const UsersTable = (props: { data: UserWChatInfo[] }) => {
created_at: user.created_at,
email: user.email,
telefono: user.telefono,
note: user.note,
id: user.id,
isAdmin: user.isAdmin ? "Admin" : "Utente",
isBlocked: user.isBlocked ? "Bloccato" : "Attivo",
@ -94,6 +87,7 @@ export const UsersTable = (props: { data: UserWChatInfo[] }) => {
const columns_titles = {
created_at: "Creato il",
email: "Email",
note: "Note",
telefono: "Telefono",
isAdmin: "Ruolo",
isBlocked: "Status",
@ -102,6 +96,21 @@ export const UsersTable = (props: { data: UserWChatInfo[] }) => {
};
type Column = (typeof tabledata)[number];
const tableRef = useRef<Table<Column> | null>(null);
const utils = api.useUtils();
const { onMutate, onSettled } = MutationPageRestore(tableRef);
const { mutate, isPending } = api.users.editUser.useMutation({
onSuccess: async () => {
toast.success("Note aggiornate con successo");
await utils.users.invalidate();
},
onMutate,
onSettled,
onError: (error) => {
toast.error(error.message);
},
});
const columns: ColumnDef<Column>[] = [
{
accessorKey: "etichette",
@ -154,6 +163,24 @@ export const UsersTable = (props: { data: UserWChatInfo[] }) => {
/>
),
},
{
accessorKey: "note",
cell: ({ row }) => {
const note = row.original.note;
return (
<NotePopover
isPending={isPending}
mutate={mutate}
note={note}
userId={row.original.id}
/>
);
},
header: ({ column }) => (
<DataTableColumnHeader column={column} title={columns_titles.note} />
),
enableSorting: false,
},
{
accessorKey: "telefono",
@ -229,6 +256,7 @@ export const UsersTable = (props: { data: UserWChatInfo[] }) => {
),
},
];
const pinnedFiltri: PinnedFiltro[] = [
{
columnName: "isAdmin",
@ -377,6 +405,7 @@ export const UsersTable = (props: { data: UserWChatInfo[] }) => {
username: true,
}}
defaultSort={[{ desc: true, id: "created_at" }]}
onTableInit={(t) => (tableRef.current = t)}
pinnedFiltri={pinnedFiltri}
searchColumn={searchFiltro}
withContextMenu={true}

View file

@ -0,0 +1,28 @@
/** biome-ignore-all lint/suspicious/noExplicitAny: <intended> */
import type { Table } from "@tanstack/react-table";
import type { RefObject } from "react";
export const MutationPageRestore = (tableRef: RefObject<Table<any> | null>) => {
return {
onMutate: () => {
const pageIdx = tableRef.current?.getState().pagination.pageIndex; // 0 based index
return {
pageIdx: pageIdx === 0 ? undefined : pageIdx, // solo una pagina
};
},
onSettled: (_a: any, _b: any, _c: any, context?: { pageIdx?: number }) => {
// wait a tick to ensure the table has the latest data after invalidation
setTimeout(() => {
if (context?.pageIdx !== undefined) {
const pageCount = tableRef.current?.getPageCount() || 0;
// if the page index from context is greater than the current page count, set it to the last page
if (context.pageIdx >= pageCount) {
tableRef.current?.setPageIndex(pageCount - 1);
} else {
tableRef.current?.setPageIndex(context.pageIdx);
}
}
}, 0);
},
};
};

View file

@ -1,6 +1,7 @@
import { TRPCError } from "@trpc/server";
import { jsonArrayFrom } from "kysely/helpers/postgres";
import type { UsersId, UsersUpdate } from "~/schemas/public/Users";
import type { Etichette } from "~/schemas/public/Etichette";
import type { Users, UsersId, UsersUpdate } from "~/schemas/public/Users";
import type { UsersAnagraficaUpdate } from "~/schemas/public/UsersAnagrafica";
import { db, type Querier } from "~/server/db";
@ -168,7 +169,21 @@ export const getActiveUserWithoutChatHandler = async ({
});
};
export const getUsersWithChatInfoHandler = async () => {
export type UserWChatInfo = Pick<
Users,
| "id"
| "username"
| "email"
| "telefono"
| "isAdmin"
| "isBlocked"
| "created_at"
| "note"
> & { chatid: string | null; etichette: Etichette[] };
export const getUsersWithChatInfoHandler = async (): Promise<
UserWChatInfo[]
> => {
return await db
.selectFrom("users")
.select([
@ -179,6 +194,7 @@ export const getUsersWithChatInfoHandler = async () => {
"users.isAdmin",
"users.isBlocked",
"users.created_at",
"users.note",
])
.leftJoin("chats", "chats.user_ref", "users.id")
.select(["chats.chatid"])