- health.ts: deleteWeightLog/deleteVetVisit/deleteVaccine checked pet ownership but deleted the target row by id alone, never verifying it belonged to that pet — any owner could delete another pet's health records. Fixed with fetch-then-check (same pattern as comments.ts). - notifications.ts: list/unreadCount/markAllRead/markRead had zero assertPetOwnership calls — any owner could read or clear another pet's notification inbox by supplying its (publicly-visible) petId. - ads.ts: toggleReaction/addComment/toggleRepost never verified petId ownership, unlike the near-identical post reactions/comments/reposts routers — allowed attributing ad interactions to arbitrary pets. - FollowButton.tsx: early return before 3 hooks violated Rules of Hooks, crashing React when the active pet switched to one already rendered in the same list/grid (explore, followers list). Added regression tests for all 4 (health.ts and notifications.ts had zero test coverage before this — not a coincidence, per the audit).
190 lines
5.9 KiB
TypeScript
190 lines
5.9 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
import { Check, Loader2 } from "lucide-react";
|
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { toast } from "sonner";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogAction,
|
|
AlertDialogCancel,
|
|
AlertDialogContent,
|
|
AlertDialogDescription,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
} from "@/components/ui/alert-dialog";
|
|
import { useTRPC } from "@/trpc/client";
|
|
import { useTranslations } from "next-intl";
|
|
|
|
/**
|
|
* FollowButton — optimistic follow/unfollow toggle (SOCL-01, SOCL-02)
|
|
*
|
|
* Props:
|
|
* - followerPetId: the active pet performing the follow action
|
|
* - followeePetId: the target pet being followed
|
|
* - followeeName: display name for unfollow confirmation dialog
|
|
*
|
|
* Hidden when followerPetId === followeePetId (own pet profile).
|
|
*
|
|
* States per UI-SPEC:
|
|
* - Not following: "Follow" bg-orange-500 text-white
|
|
* - Following: "Following" variant outline + Check icon
|
|
* - Pending: disabled spinner opacity-60
|
|
*
|
|
* Optimistic update (RESEARCH Pattern 6):
|
|
* onMutate: cancel inflight + setData immediately
|
|
* onError: revert + toast "Something went wrong. Try again."
|
|
* onSettled: invalidate query
|
|
*
|
|
* Unfollow opens AlertDialog confirmation per UI-SPEC copy.
|
|
*/
|
|
|
|
interface FollowButtonProps {
|
|
followerPetId: string;
|
|
followeePetId: string;
|
|
followeeName: string;
|
|
}
|
|
|
|
export function FollowButton({
|
|
followerPetId,
|
|
followeePetId,
|
|
followeeName,
|
|
}: FollowButtonProps) {
|
|
const t = useTranslations("Follow");
|
|
const trpc = useTRPC();
|
|
const queryClient = useQueryClient();
|
|
const [showUnfollowDialog, setShowUnfollowDialog] = useState(false);
|
|
|
|
const isOwnPet = followerPetId === followeePetId;
|
|
|
|
const isFollowingQueryOptions = trpc.follows.isFollowing.queryOptions({
|
|
followerPetId,
|
|
followeePetId,
|
|
});
|
|
|
|
const { data: isFollowing, isPending: isLoadingStatus } = useQuery({
|
|
...isFollowingQueryOptions,
|
|
enabled: !isOwnPet,
|
|
});
|
|
|
|
const followMutation = useMutation(
|
|
trpc.follows.create.mutationOptions({
|
|
onMutate: async () => {
|
|
// Cancel any in-flight isFollowing queries
|
|
await queryClient.cancelQueries({ queryKey: isFollowingQueryOptions.queryKey });
|
|
// Snapshot previous value
|
|
const prev = queryClient.getQueryData(isFollowingQueryOptions.queryKey);
|
|
// Optimistically set to following
|
|
queryClient.setQueryData(isFollowingQueryOptions.queryKey, true);
|
|
return { prev };
|
|
},
|
|
onError: (_err, _vars, context) => {
|
|
// Revert on error
|
|
queryClient.setQueryData(
|
|
isFollowingQueryOptions.queryKey,
|
|
context?.prev
|
|
);
|
|
toast.error(t("followError"));
|
|
},
|
|
onSettled: () => {
|
|
queryClient.invalidateQueries({ queryKey: isFollowingQueryOptions.queryKey });
|
|
},
|
|
onSuccess: () => {
|
|
toast.success(t("nowFollowing", { name: followeeName }));
|
|
},
|
|
})
|
|
);
|
|
|
|
const unfollowMutation = useMutation(
|
|
trpc.follows.delete.mutationOptions({
|
|
onMutate: async () => {
|
|
await queryClient.cancelQueries({ queryKey: isFollowingQueryOptions.queryKey });
|
|
const prev = queryClient.getQueryData(isFollowingQueryOptions.queryKey);
|
|
queryClient.setQueryData(isFollowingQueryOptions.queryKey, false);
|
|
return { prev };
|
|
},
|
|
onError: (_err, _vars, context) => {
|
|
queryClient.setQueryData(
|
|
isFollowingQueryOptions.queryKey,
|
|
context?.prev
|
|
);
|
|
toast.error(t("followError"));
|
|
},
|
|
onSettled: () => {
|
|
queryClient.invalidateQueries({ queryKey: isFollowingQueryOptions.queryKey });
|
|
},
|
|
onSuccess: () => {
|
|
toast(t("unfollowed", { name: followeeName }));
|
|
},
|
|
})
|
|
);
|
|
|
|
const isPending = followMutation.isPending || unfollowMutation.isPending;
|
|
|
|
// Hidden on own pet profile (T-02-11 guard) — after all hooks, per Rules of Hooks
|
|
if (isOwnPet) return null;
|
|
|
|
function handleClick() {
|
|
if (isPending || isLoadingStatus) return;
|
|
|
|
if (isFollowing) {
|
|
// Show unfollow confirmation dialog
|
|
setShowUnfollowDialog(true);
|
|
} else {
|
|
followMutation.mutate({ followerPetId, followeePetId });
|
|
}
|
|
}
|
|
|
|
function handleUnfollowConfirm() {
|
|
unfollowMutation.mutate({ followerPetId, followeePetId });
|
|
setShowUnfollowDialog(false);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<Button
|
|
onClick={handleClick}
|
|
disabled={isPending || isLoadingStatus}
|
|
variant={isFollowing ? "outline" : "default"}
|
|
className={
|
|
isFollowing
|
|
? "min-h-[44px] transition-colors duration-150"
|
|
: "min-h-[44px] bg-orange-500 hover:bg-orange-600 text-white transition-colors duration-150"
|
|
}
|
|
aria-label={isFollowing ? `${t("unfollow")} ${followeeName}` : `${t("follow")} ${followeeName}`}
|
|
>
|
|
{isPending ? (
|
|
<Loader2 className="h-4 w-4 animate-spin opacity-60" />
|
|
) : isFollowing ? (
|
|
<>
|
|
<Check className="h-4 w-4 mr-1" />
|
|
{t("following")}
|
|
</>
|
|
) : (
|
|
t("follow")
|
|
)}
|
|
</Button>
|
|
|
|
{/* Unfollow confirmation dialog per UI-SPEC copy */}
|
|
<AlertDialog open={showUnfollowDialog} onOpenChange={setShowUnfollowDialog}>
|
|
<AlertDialogContent>
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>{t("unfollowTitle", { name: followeeName })}</AlertDialogTitle>
|
|
<AlertDialogDescription>
|
|
{t("unfollowDesc", { name: followeeName })}
|
|
</AlertDialogDescription>
|
|
</AlertDialogHeader>
|
|
<AlertDialogFooter>
|
|
<AlertDialogCancel>{t("keepFollowing")}</AlertDialogCancel>
|
|
<AlertDialogAction onClick={handleUnfollowConfirm}>
|
|
{t("unfollow")}
|
|
</AlertDialogAction>
|
|
</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
</>
|
|
);
|
|
}
|