refactor: streamline conditional logic and improve readability across multiple components

This commit is contained in:
Marco Pedone 2025-09-01 16:48:03 +02:00
parent 0bc1a0915c
commit 1426f0efef
24 changed files with 271 additions and 271 deletions

View file

@ -68,6 +68,7 @@
"linter": { "linter": {
"domains": { "domains": {
"next": "recommended", "next": "recommended",
"project": "recommended",
"react": "recommended" "react": "recommended"
}, },
"enabled": true, "enabled": true,
@ -82,19 +83,33 @@
}, },
"correctness": { "correctness": {
"noUndeclaredVariables": "on",
"useExhaustiveDependencies": "off", "useExhaustiveDependencies": "off",
"useHookAtTopLevel": "off", "useHookAtTopLevel": "off",
"useParseIntRadix": "off" "useParseIntRadix": "off"
}, },
"nursery": {
"useExhaustiveSwitchCases": "on"
},
"performance": { "performance": {
"noImgElement": "off" "noImgElement": "off",
"useGoogleFontPreconnect": "on"
}, },
"recommended": true, "recommended": true,
"security": { "security": {
"noDangerouslySetInnerHtml": "off" "noDangerouslySetInnerHtml": "off"
}, },
"style": {
"noNestedTernary": "info",
"noUselessElse": "on",
"noYodaExpression": "on",
"useThrowNewError": "on",
"useThrowOnlyError": "on"
},
"suspicious": { "suspicious": {
"noArrayIndexKey": "off", "noArrayIndexKey": "off",
"noDocumentImportInPage": "on",
"noHeadImportInDocument": "on",
"noUnknownAtRules": "off", "noUnknownAtRules": "off",
"useIterableCallbackReturn": "off" "useIterableCallbackReturn": "off"
} }

View file

@ -19,11 +19,6 @@ const EmailContattoInteressato = ({
indirizzo, indirizzo,
sesso, sesso,
}: EmailContattoInteressatoProps) => { }: EmailContattoInteressatoProps) => {
const sig = sesso
? sesso === "M"
? "Il Sig."
: "La Sig.ra"
: "Il/La Sig./Sig.ra";
return ( return (
<Base preview="Contatto Email"> <Base preview="Contatto Email">
<> <>
@ -34,9 +29,15 @@ const EmailContattoInteressato = ({
<Row> <Row>
<Text className="text-base"> <Text className="text-base">
Gentile proprietario {nome_cognome}, le comunichiamo che a breve Gentile proprietario {nome_cognome}, le comunichiamo che a breve
la contatterà {sig} {nome_cognome_utente} (tel: {telefono}), la contatterà {(() => {
cliente Arca abbonato tramite il nostro servizio online if (sesso) {
Infoalloggi.it interessato a vedere il Suo immobile{" "} if (sesso === "M") return "il Sig.";
if (sesso === "F") return "la Sig.ra";
}
return "il Sig./la Sig.ra";
})()} {nome_cognome_utente} (tel: {telefono}), cliente Arca
abbonato tramite il nostro servizio online Infoalloggi.it
interessato a vedere il Suo immobile{" "}
{indirizzo ? `di ${indirizzo}` : ""}. {indirizzo ? `di ${indirizzo}` : ""}.
</Text> </Text>
<Text className="text-base"> <Text className="text-base">

View file

@ -202,6 +202,8 @@ export const IconMatrix = ({ type, ...rest }: IconMatrixProps) => {
return <Target {...rest} />; return <Target {...rest} />;
case "thumbs-up": case "thumbs-up":
return <ThumbsUp {...rest} />; return <ThumbsUp {...rest} />;
default:
return <div>Icon not found</div>;
} }
}; };

View file

@ -56,7 +56,9 @@ export const AcquistoProcessing = ({
<h3 className="mt-2 text-center text-2xl font-bold tracking-wide text-neutral-700 uppercase"> <h3 className="mt-2 text-center text-2xl font-bold tracking-wide text-neutral-700 uppercase">
{t.acquisto.titolo} {t.acquisto.titolo}
</h3> </h3>
{!generatedIntent ? ( {(() => {
if (!generatedIntent) {
return (
<PricePreparation <PricePreparation
onProcedi={() => { onProcedi={() => {
setGeneratedIntent(true); setGeneratedIntent(true);
@ -66,10 +68,13 @@ export const AcquistoProcessing = ({
}} }}
packId={packId} packId={packId}
/> />
) : isPending ? ( );
<LoadingPage /> }
) : ( if (isPending) {
stripeIntent?.clientSecret && ( return <LoadingPage />;
}
if (stripeIntent?.clientSecret) {
return (
<> <>
<Elements <Elements
options={{ options={{
@ -91,8 +96,9 @@ export const AcquistoProcessing = ({
/> />
</Elements> </Elements>
</> </>
) );
)} }
})()}
</div> </div>
); );
}; };

View file

@ -256,7 +256,7 @@ export const CarouselAnnuncio = ({
if (!video) return null; if (!video) return null;
if (video.includes("youtu")) { if (video.includes("youtu")) {
return null; return null;
} else { }
return ( return (
<CarouselItem <CarouselItem
className={cn( className={cn(
@ -282,7 +282,6 @@ export const CarouselAnnuncio = ({
/> />
</CarouselItem> </CarouselItem>
); );
}
})} })}
</CarouselContent> </CarouselContent>
@ -322,7 +321,7 @@ export const CarouselAnnuncio = ({
if (!video) return null; if (!video) return null;
if (video.includes("youtu")) { if (video.includes("youtu")) {
return null; return null;
} else { }
return ( return (
<CarouselItem <CarouselItem
className="relative flex items-center justify-center" className="relative flex items-center justify-center"
@ -335,7 +334,6 @@ export const CarouselAnnuncio = ({
/> />
</CarouselItem> </CarouselItem>
); );
}
})} })}
</CarouselContent> </CarouselContent>

View file

@ -193,36 +193,37 @@ export const ExtIcon = ({
if (!ext) return <File className={cn("size-5 text-gray-500", className)} />; if (!ext) return <File className={cn("size-5 text-gray-500", className)} />;
if (ext.includes("pdf")) { if (ext.includes("pdf")) {
return <FileText className={cn("size-5 text-red-500", className)} />; return <FileText className={cn("size-5 text-red-500", className)} />;
} else if ( }
if (
ext.includes("image") || ext.includes("image") ||
["jpg", "jpeg", "png", "gif", "svg", "webp"].some((ext) => ["jpg", "jpeg", "png", "gif", "svg", "webp"].some((ext) =>
ext.includes(ext), ext.includes(ext),
) )
) { ) {
return <ImageIcon className={cn("size-5 text-blue-500", className)} />; return <ImageIcon className={cn("size-5 text-blue-500", className)} />;
} else if ( }
if (
["html", "css", "js", "jsx", "ts", "tsx", "json", "xml"].some((ext) => ["html", "css", "js", "jsx", "ts", "tsx", "json", "xml"].some((ext) =>
ext.includes(ext), ext.includes(ext),
) )
) { ) {
return <FileCode className={cn("size-5 text-emerald-500", className)} />; return <FileCode className={cn("size-5 text-emerald-500", className)} />;
} else if (["xls", "xlsx", "csv"].some((ext) => ext.includes(ext))) { }
if (["xls", "xlsx", "csv"].some((ext) => ext.includes(ext))) {
return ( return (
<FileSpreadsheet className={cn("size-5 text-green-600", className)} /> <FileSpreadsheet className={cn("size-5 text-green-600", className)} />
); );
} else if (
["zip", "rar", "7z", "tar", "gz"].some((ext) => ext.includes(ext))
) {
return <FileArchive className={cn("size-5 text-amber-600", className)} />;
} else if (["mp3", "wav", "ogg", "flac"].some((ext) => ext.includes(ext))) {
return <FileAudio className={cn("size-5 text-purple-500", className)} />;
} else if (
["mp4", "avi", "mov", "wmv", "webm"].some((ext) => ext.includes(ext))
) {
return <FileVideo className={cn("size-5 text-pink-500", className)} />;
} else {
return <File className={cn("size-5 text-gray-500", className)} />;
} }
if (["zip", "rar", "7z", "tar", "gz"].some((ext) => ext.includes(ext))) {
return <FileArchive className={cn("size-5 text-amber-600", className)} />;
}
if (["mp3", "wav", "ogg", "flac"].some((ext) => ext.includes(ext))) {
return <FileAudio className={cn("size-5 text-purple-500", className)} />;
}
if (["mp4", "avi", "mov", "wmv", "webm"].some((ext) => ext.includes(ext))) {
return <FileVideo className={cn("size-5 text-pink-500", className)} />;
}
return <File className={cn("size-5 text-gray-500", className)} />;
}; };
const EditFileDialog = ({ const EditFileDialog = ({

View file

@ -6,6 +6,7 @@ import { IconMatrix, type IconType } from "~/components/IconComponents";
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
import type { Banners } from "~/schemas/public/Banners"; import type { Banners } from "~/schemas/public/Banners";
const defaultHideDuration = 365; // days
export const BannerFactory = (bannerData: Banners) => { export const BannerFactory = (bannerData: Banners) => {
const NEW_BANNER_KEY = `bannercookie_${bannerData.idbanner}`; const NEW_BANNER_KEY = `bannercookie_${bannerData.idbanner}`;
@ -55,7 +56,7 @@ export const BannerFactory = (bannerData: Banners) => {
e.preventDefault(); e.preventDefault();
Cookies.set(NEW_BANNER_KEY, "true", { Cookies.set(NEW_BANNER_KEY, "true", {
expires: bannerData.hide_duration || 365, expires: bannerData.hide_duration || defaultHideDuration,
}); });
setIsBannerToShow(false); setIsBannerToShow(false);
}; };

View file

@ -60,9 +60,8 @@ type ChatBubbleReadStatusProps = {
export const ChatBubbleReadStatus = ({ isread }: ChatBubbleReadStatusProps) => { export const ChatBubbleReadStatus = ({ isread }: ChatBubbleReadStatusProps) => {
if (isread) { if (isread) {
return <CheckCheck className="mt-2 size-4 text-green-500" />; return <CheckCheck className="mt-2 size-4 text-green-500" />;
} else {
return <Check className="text-muted-foreground mt-2 size-4" />;
} }
return <Check className="text-muted-foreground mt-2 size-4" />;
}; };
// ChatBubbleMessage // ChatBubbleMessage

View file

@ -41,13 +41,13 @@ export function DataTableColumnHeader<TData, TValue>({
variant="ghost" variant="ghost"
> >
<span>{title}</span> <span>{title}</span>
{column.getIsSorted() === "desc" ? ( {(() => {
<ArrowDownIcon className="ml-2 size-4" /> if (column.getIsSorted() === "desc")
) : column.getIsSorted() === "asc" ? ( return <ArrowDownIcon className="ml-2 size-4" />;
<ArrowUpIcon className="ml-2 size-4" /> if (column.getIsSorted() === "asc")
) : ( return <ArrowUpIcon className="ml-2 size-4" />;
<ChevronsUpDown className="ml-2 size-4" /> return <ChevronsUpDown className="ml-2 size-4" />;
)} })()}
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="start"> <DropdownMenuContent align="start">

View file

@ -916,13 +916,13 @@ const FileUploadItem = forwardRef<HTMLDivElement, FileUploadItemProps>(
if (!fileState) return null; if (!fileState) return null;
const statusText = fileState.error const statusText = (() => {
? `Error: ${fileState.error}` if (fileState.error) return `Error: ${fileState.error}`;
: fileState.status === "uploading" if (fileState.status === "uploading")
? `Uploading: ${fileState.progress}% complete` return `Uploading: ${fileState.progress}% complete`;
: fileState.status === "success" if (fileState.status === "success") return "Upload complete";
? "Upload complete" return "Ready to upload";
: "Ready to upload"; })();
const ItemPrimitive = asChild ? Slot : "div"; const ItemPrimitive = asChild ? Slot : "div";

View file

@ -37,9 +37,8 @@ const getCoordsFromPointExpression = (expression?: PointExpression) => {
if (!expression) return []; if (!expression) return [];
if (Array.isArray(expression)) { if (Array.isArray(expression)) {
return expression; return expression;
} else {
return [expression.x, expression.y] as PointTuple;
} }
return [expression.x, expression.y] as PointTuple;
}; };
const useCoordsFromPointExpression = (expression?: PointExpression) => const useCoordsFromPointExpression = (expression?: PointExpression) =>

View file

@ -199,10 +199,9 @@ const parseContrattoImport = (ingest: string) => {
? new Date(parsed.data.contratto_scadenza) ? new Date(parsed.data.contratto_scadenza)
: null, : null,
}; };
} else { }
console.error("Invalid format:", parsed.error); console.error("Invalid format:", parsed.error);
return undefined; return undefined;
}
}; };
const ContrattoImport = ({ const ContrattoImport = ({
@ -950,10 +949,9 @@ const parseCaparra = (ingest: string) => {
const parsed = CaparraSchema.safeParse(parsedJson); const parsed = CaparraSchema.safeParse(parsedJson);
if (parsed.success) { if (parsed.success) {
return parsed.data; return parsed.data;
} else { }
console.error("Invalid caparra format:", parsed.error); console.error("Invalid caparra format:", parsed.error);
return undefined; return undefined;
}
}; };
const Caparra = ({ const Caparra = ({
@ -1165,19 +1163,16 @@ const SendConferma = ({
</p> </p>
</> </>
); );
} else { }
return ( return (
<> <>
<p> <p>Budget (da preferenze): {formatCurrency(servizio.budget)}</p>
Budget (da preferenze): {formatCurrency(servizio.budget)}
</p>
<p> <p>
Canone Mensile (da descrizione):{" "} Canone Mensile (da descrizione):{" "}
{formatCurrency(data.prezzo / 100)} {formatCurrency(data.prezzo / 100)}
</p> </p>
</> </>
); );
}
})()} })()}
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">

View file

@ -144,14 +144,13 @@ export const OrdiniTable = ({ data, isAdmin, userId }: PaymentsTableProps) => {
Pagato Pagato
</span> </span>
); );
} else { }
return ( return (
<span className="inline-flex items-center gap-1 text-red-500"> <span className="inline-flex items-center gap-1 text-red-500">
<CircleCheck className="size-5" /> <CircleCheck className="size-5" />
Non pagato Non pagato
</span> </span>
); );
}
}, },
filterFn: (row, id, value) => { filterFn: (row, id, value) => {

View file

@ -102,13 +102,13 @@ export const PrezzarioTable = ({
cell: ({ row }) => { cell: ({ row }) => {
return ( return (
<div> <div>
{row.original.isTransitorio {(() => {
? row.original.isStabile if (row.original.isTransitorio && row.original.isStabile)
? "Transitorio/Stabile" return "Transitorio/Stabile";
: "Transitorio" if (row.original.isTransitorio) return "Transitorio";
: row.original.isStabile if (row.original.isStabile) return "Stabile";
? "Stabile" return "";
: ""} })()}
</div> </div>
); );
}, },

View file

@ -79,13 +79,14 @@ const Row = ({
Affitto {servizio.tipologia} Affitto {servizio.tipologia}
</div> </div>
<div className="col-span-2"> <div className="col-span-2">
{servizio.isInterrotto ? ( {(() => {
<span className="text-red-500">Interrotto</span> if (servizio.isInterrotto)
) : servizio.isOkAcconto && servizio.decorrenza !== null ? ( return <span className="text-red-500">Interrotto</span>;
<span className="text-green-500">Attivo</span> if (servizio.isOkAcconto && servizio.decorrenza !== null) {
) : ( return <span className="text-green-500">Attivo</span>;
<span className="text-neutral-500">Inattivo</span> }
)} return <span className="text-neutral-500">Inattivo</span>;
})()}
</div> </div>
<div className="hidden text-sm sm:col-span-2 sm:contents sm:text-base"> <div className="hidden text-sm sm:col-span-2 sm:contents sm:text-base">
{servizio.created_at.toLocaleDateString("it", { {servizio.created_at.toLocaleDateString("it", {

View file

@ -132,13 +132,13 @@ export const TabServizio = ({
)} )}
</TableCell> </TableCell>
<TableCell> <TableCell>
{servizio.isInterrotto ? ( {(() => {
<span className="text-red-500">Interrotto</span> if (servizio.isInterrotto)
) : servizio.isOkAcconto && servizio.decorrenza !== null ? ( return <span className="text-red-500">Interrotto</span>;
<span className="text-green-500">Attivo</span> if (servizio.isOkAcconto && servizio.decorrenza !== null)
) : ( return <span className="text-green-500">Attivo</span>;
<span className="text-neutral-500">Inattivo</span> return <span className="text-neutral-500">Inattivo</span>;
)} })()}
</TableCell> </TableCell>
<TableCell> <TableCell>
<AnnunciSection <AnnunciSection

View file

@ -18,15 +18,11 @@ function Slider({
max = 100, max = 100,
...props ...props
}: React.ComponentProps<typeof SliderPrimitive.Root> & SliderProps) { }: React.ComponentProps<typeof SliderPrimitive.Root> & SliderProps) {
const _values = React.useMemo( const _values = React.useMemo(() => {
() => if (Array.isArray(value)) return value;
Array.isArray(value) if (Array.isArray(defaultValue)) return defaultValue;
? value return [min, max];
: Array.isArray(defaultValue) }, [value, defaultValue, min, max]);
? defaultValue
: [min, max],
[value, defaultValue, min, max],
);
return ( return (
<SliderPrimitive.Root <SliderPrimitive.Root

View file

@ -9,11 +9,10 @@ export const getUserColor = (str: string) => {
if (colorOptions.has(str)) { if (colorOptions.has(str)) {
// biome-ignore lint/style/noNonNullAssertion: <exists> // biome-ignore lint/style/noNonNullAssertion: <exists>
return colorOptions.get(str)!; return colorOptions.get(str)!;
} else { }
const usercolor = getHexColorFromString(str); const usercolor = getHexColorFromString(str);
colorOptions.set(str, usercolor); colorOptions.set(str, usercolor);
return usercolor; return usercolor;
}
}; };
export const UserAvatar = ({ export const UserAvatar = ({

View file

@ -79,12 +79,11 @@ export const authMiddleware = async (req: NextRequest) => {
return NextResponse.redirect( return NextResponse.redirect(
new URL("/area-riservata/dashboard", req.nextUrl), new URL("/area-riservata/dashboard", req.nextUrl),
); );
} else { }
return NextResponse.redirect( return NextResponse.redirect(
new URL("/area-riservata/dashboard", req.nextUrl), new URL("/area-riservata/dashboard", req.nextUrl),
); );
} }
}
// If access token is invalid, delete it // If access token is invalid, delete it
const destination = new URL("/login", req.nextUrl); const destination = new URL("/login", req.nextUrl);
destination.searchParams.set("redirect", path); destination.searchParams.set("redirect", path);

View file

@ -198,10 +198,9 @@ const RicercaFilters = () => {
if (t.preferenze.mesi.includes(value)) { if (t.preferenze.mesi.includes(value)) {
await setConsegna(t.preferenze.mesi.indexOf(value)); await setConsegna(t.preferenze.mesi.indexOf(value));
return; return;
} else { }
console.warn("Value not found in preferenze.mesi"); console.warn("Value not found in preferenze.mesi");
await setConsegna(null); await setConsegna(null);
}
}} }}
options={mappedConsegnaOptions} options={mappedConsegnaOptions}
placeholder={t.seleziona_placeholder} placeholder={t.seleziona_placeholder}

View file

@ -309,7 +309,7 @@ const Pricing = ({
} }
/> />
); );
} else { }
return ( return (
<Accordion className="w-full" collapsible type="single"> <Accordion className="w-full" collapsible type="single">
<AccordionItem value="item-1"> <AccordionItem value="item-1">
@ -334,7 +334,6 @@ const Pricing = ({
</AccordionItem> </AccordionItem>
</Accordion> </Accordion>
); );
}
}; };
const TestiAnnuncio = ({ const TestiAnnuncio = ({
@ -459,11 +458,13 @@ const CardInfos = ({ data }: { data: Annunci }) => {
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div className="flex justify-center gap-2 rounded-md bg-neutral-100 p-2"> <div className="flex justify-center gap-2 rounded-md bg-neutral-100 p-2">
<BedDouble /> <BedDouble />
{data.numero_camere && data.numero_camere {(() => {
? data.numero_camere > 1 if (!data.numero_camere) return "N/A";
? `${data.numero_camere} ${t.card.camere2}` if (data.numero_camere > 1)
: `${data.numero_camere} ${t.card.camere1}` return `${data.numero_camere} ${t.card.camere2}`;
: "N/A"} if (data.numero_camere === 1)
return `${data.numero_camere} ${t.card.camere1}`;
})()}
</div> </div>
<div className="flex justify-center gap-2 rounded-md bg-neutral-100 p-2"> <div className="flex justify-center gap-2 rounded-md bg-neutral-100 p-2">
<Bath /> <Bath />
@ -492,11 +493,12 @@ const CardInfos = ({ data }: { data: Annunci }) => {
<div className="flex justify-center gap-2 rounded-md bg-neutral-100 p-2"> <div className="flex justify-center gap-2 rounded-md bg-neutral-100 p-2">
<Building2 /> <Building2 />
<span> <span>
{data.piano && data.piano === "0" {(() => {
? "piano terra" if (data.piano === "0") return "piano terra";
: data.piano === "0.5" if (data.piano === "0.5") return "piano rialz.";
? "piano rialz." if (data.piano) return `${data.piano}° piano`;
: `${data.piano}° piano`} return "";
})()}
</span> </span>
</div> </div>
</div> </div>
@ -635,18 +637,7 @@ const AnnuncioFooter = ({
if (!video) return null; if (!video) return null;
if (video.includes("youtu")) { if (video.includes("youtu")) {
return null; return null;
/*return ( }
<iframe
title="video"
className={cn("h-96 w-auto rounded-md")}
src={video}
//src={`https://www.youtube-nocookie.com/embed/${video.split(/[/ ]+/).pop()}`}
allow=" autoplay; encrypted-media"
allowFullScreen
key={`ytplayer-${video}`}
/>
);*/
} else {
return ( return (
<VideoPlayer <VideoPlayer
className="h-96 max-w-96" className="h-96 max-w-96"
@ -655,7 +646,6 @@ const AnnuncioFooter = ({
videoSrc={video} videoSrc={video}
/> />
); );
}
})} })}
</div> </div>

View file

@ -59,12 +59,11 @@ export const getServerSideProps = (async (context) => {
token, token,
}, },
}; };
} else { }
return { return {
redirect: { redirect: {
destination: "/auth/nonvalid-password-reset-token", destination: "/auth/nonvalid-password-reset-token",
permanent: false, permanent: false,
}, },
}; };
}
}) satisfies GetServerSideProps<ResetWTokenProps>; }) satisfies GetServerSideProps<ResetWTokenProps>;

View file

@ -277,7 +277,7 @@ export const getCursor_AnnunciHandler = async ({
if (consegna) { if (consegna) {
query = query.where("consegna", "=", consegna); query = query.where("consegna", "=", consegna);
} }
if (sort) {
switch (sort) { switch (sort) {
case "Recenti": case "Recenti":
query = query.orderBy("modificato_il", "desc"); query = query.orderBy("modificato_il", "desc");
@ -291,8 +291,10 @@ export const getCursor_AnnunciHandler = async ({
case "Mq": case "Mq":
query = query.orderBy("mq", "asc"); query = query.orderBy("mq", "asc");
break; break;
case undefined:
break;
} }
}
query = query.orderBy("id", "asc"); query = query.orderBy("id", "asc");
const annunci = await query const annunci = await query

View file

@ -158,7 +158,7 @@ export const upsertAnagrafica = async ({
.where("userid", "=", userid) .where("userid", "=", userid)
.returningAll() .returningAll()
.executeTakeFirst(); .executeTakeFirst();
} else { }
return await db return await db
.insertInto("users_anagrafica") .insertInto("users_anagrafica")
.values({ .values({
@ -168,7 +168,6 @@ export const upsertAnagrafica = async ({
.onConflict((oc) => oc.column("userid").doNothing()) .onConflict((oc) => oc.column("userid").doNothing())
.returningAll() .returningAll()
.executeTakeFirst(); .executeTakeFirst();
}
} catch (e) { } catch (e) {
throw new TRPCError({ throw new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",