All files / src/components/nav NotificationBell.tsx

100% Statements 34/34
83.87% Branches 26/31
100% Functions 11/11
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177                                                            2x   2x                   2x 3x 2x       2x 17x                   2x 17x 17x 17x 17x   12x     17x 17x 2x   17x 1x     17x 1x       17x 1x 1x 1x     17x 17x                                                       1x 1x                             5x 5x     1x                                                                                
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { AppNotification, Inbox } from "@/objects/Notification";
import { pathIn, workspaceFromKey } from "@/routes/workspace";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { parseServerDate } from "@/util/time";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Bell,
  FileSpreadsheet,
  MessageCircleQuestion,
  Network,
  ShieldAlert,
  TrendingUp,
  Wallet,
} from "lucide-react";
import moment from "moment";
import React from "react";
// The router's own, not the app's workspace-aware one: a notification names
// its workspace, and its link must open there, not in the one being viewed.
import { useNavigate } from "react-router";
 
/** How often the inbox is read again while a page is open. */
export const INBOX_POLL_MS = 60_000;
 
const ICONS: Record<string, React.ElementType> = {
  budget_threshold: Wallet,
  budget_projected: TrendingUp,
  allowance_threshold: ShieldAlert,
  statement_ready: FileSpreadsheet,
  swarm_attention: MessageCircleQuestion,
  swarm_finished: Network,
};
 
/** Where a notification opens: its page, in its own workspace. */
export const notificationHref = (n: AppNotification): string | null => {
  if (!n.link) return null;
  return n.workspace_key ? pathIn(workspaceFromKey(n.workspace_key), n.link) : n.link;
};
 
/** What the inbox holds: a well-formed answer, or nothing. */
const inboxOf = (data: unknown): Inbox =>
  data && typeof data === "object" && Array.isArray((data as Inbox).items)
    ? (data as Inbox)
    : { items: [], unread: 0 };
 
/**
 * The inbox, beside the workspace menu (cost-control plan A2): budget alerts
 * and statements ready to read, across every workspace the person belongs to
 * (svc-core `/app/notifications`). Each names its workspace and opens its
 * page there; opening one marks it read.
 */
const NotificationBell: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const { data } = useQuery<Inbox | null>({
    queryKey: [QUERY_KEYS.GET.NOTIFICATIONS],
    queryFn: () => getApiHandler().notification_router.list(),
    refetchInterval: INBOX_POLL_MS,
  });
  const inbox = inboxOf(data);
  const refresh = () =>
    void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.NOTIFICATIONS] });
 
  const read = useMutation({
    mutationFn: (id: string) => getApiHandler().notification_router.markRead(id),
    onSuccess: refresh,
  });
  const readAll = useMutation({
    mutationFn: () => getApiHandler().notification_router.markAllRead(),
    onSuccess: refresh,
  });
 
  const open = (n: AppNotification) => {
    Eif (!n.read_at) read.mutate(n.id);
    const href = notificationHref(n);
    Eif (href) void navigate(href);
  };
 
  const unread = inbox.unread;
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          aria-label={
            unread ? `Notifications, ${unread} unread` : "Notifications"
          }
          className="relative text-white rounded-lg border border-white bg-gray-900 p-2 flex items-center cursor-pointer hover:bg-gray-800 transition-colors"
        >
          <Bell className="size-5" />
          {unread > 0 && (
            <span
              aria-hidden
              className="absolute -top-1.5 -right-1.5 min-w-4 h-4 px-1 rounded-full bg-red-600 text-[10px] font-semibold leading-4 text-center"
            >
              {unread > 9 ? "9+" : unread}
            </span>
          )}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-80 max-h-[70vh] overflow-y-auto">
        <DropdownMenuLabel className="flex items-center justify-between gap-2">
          <span>Notifications</span>
          {unread > 0 && (
            <button
              type="button"
              onClick={(e) => {
                e.preventDefault();
                readAll.mutate();
              }}
              className="text-xs font-normal text-[var(--primary-color)] hover:underline"
            >
              Mark all read
            </button>
          )}
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        {inbox.items.length === 0 ? (
          <p className="px-2 py-3 text-xs text-muted-foreground">
            Nothing yet. Budget alerts and monthly statements appear here.
          </p>
        ) : (
          inbox.items.map((n) => {
            const Icon = ICONS[n.kind] ?? Bell;
            return (
              <DropdownMenuItem
                key={n.id}
                onSelect={() => open(n)}
                className="cursor-pointer items-start gap-2 py-2"
              >
                <Icon className="size-4 mt-0.5 shrink-0" />
                <span className="min-w-0 flex-1">
                  <span
                    className={`block text-sm ${n.read_at ? "" : "font-semibold"}`}
                  >
                    {n.title}
                  </span>
                  {n.body && (
                    <span className="block text-xs text-muted-foreground line-clamp-2">
                      {n.body}
                    </span>
                  )}
                  <span className="block text-[10px] text-muted-foreground mt-0.5">
                    {[
                      n.workspace_name,
                      moment(parseServerDate(n.created_at)).fromNow(),
                    ]
                      .filter(Boolean)
                      .join(" ยท ")}
                  </span>
                </span>
                {!n.read_at && (
                  <span
                    aria-label="Unread"
                    className="size-2 mt-1.5 rounded-full bg-[var(--primary-color)] shrink-0"
                  />
                )}
              </DropdownMenuItem>
            );
          })
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
 
export default NotificationBell;