Spaces:
Running

File size: 6,532 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { BrainIcon, ShieldAlertIcon, Trash2Icon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";

import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { formatDateTime } from "@/lib/format";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";

import type { MemoryItem, MemoryKind } from "./types";

const KINDS: (MemoryKind | "all")[] = ["all", "customer", "prefs", "case"];

function summarize(value: Record<string, unknown> | null): string {
  if (!value) return "";
  return Object.entries(value)
    .map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
    .join(" · ");
}

function ForgetCustomer({ onDone }: { onDone: () => void }) {
  const { t } = useI18n();
  const [id, setId] = useState("");
  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (!id.trim()) return;
    try {
      const r = await api<{ deleted: number }>(`/memory/customers/${encodeURIComponent(id.trim())}`, {
        method: "DELETE",
      });
      toast.success(t("memory.forgetCustomerDone", { n: r.deleted }));
      setId("");
      onDone();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.detail : t("common.error"));
    }
  };
  return (
    <form onSubmit={submit} className="flex flex-wrap items-end gap-2">

      <div className="space-y-1.5">

        <Label htmlFor="mem-customer">{t("memory.customerId")}</Label>

        <Input id="mem-customer" dir="ltr" value={id} onChange={(e) => setId(e.target.value)} className="w-64" />

      </div>

      <Button type="submit" variant="outline" disabled={!id.trim()}>

        {t("memory.forgetCustomer")}

      </Button>

    </form>
  );
}

export function MemoryView() {
  const { t, m, locale } = useI18n();
  const { hasRole, me } = useAuth();
  const [kind, setKind] = useState<MemoryKind | "all">("all");
  const allowed = hasRole("manager");
  const items = useApi<MemoryItem[]>(allowed ? "/memory/items" : null, {
    query: kind === "all" ? {} : { kind },
  });

  const forget = async (item: MemoryItem) => {
    try {
      await api(`/memory/items/${item.id}`, { method: "DELETE" });
      toast.success(t("memory.forgotten"));
      items.reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.detail : t("common.error"));
    }
  };

  let body;
  if (me && !allowed) {
    body = <EmptyState icon={BrainIcon} title={t("memory.managerOnly")} />;
  } else if (items.error && !items.data) {
    body = <ErrorState error={items.error} onRetry={items.reload} />;
  } else if (!items.data) {
    body = <Skeleton className="h-32 w-full" />;
  } else if (items.data.length === 0) {
    body = <EmptyState icon={BrainIcon} title={t("memory.empty")} hint={t("memory.emptyHint")} />;
  } else {
    body = (
      <div className="rounded-lg border bg-card">

        <Table data-testid="memory-table">

          <TableHeader>

            <TableRow>

              <TableHead>{t("memory.namespace")}</TableHead>

              <TableHead>{t("memory.key")}</TableHead>

              <TableHead>{t("memory.value")}</TableHead>

              <TableHead>{t("memory.expires")}</TableHead>

              <TableHead className="w-10" />

            </TableRow>

          </TableHeader>

          <TableBody>

            {items.data.map((it) => (

              <TableRow key={it.id}>

                <TableCell>

                  <Badge variant="secondary">

                    {it.kind === "other" ? it.namespace.slice(2).join(" / ") : m.memory.kinds[it.kind]}

                  </Badge>

                  {it.namespace.length > 3 && (

                    <span className="ms-2 font-mono text-xs text-muted-foreground" dir="ltr">

                      {it.namespace.slice(3).join("/")}

                    </span>

                  )}

                </TableCell>

                <TableCell className="font-mono text-xs" dir="ltr">

                  {it.key}

                </TableCell>

                <TableCell className="max-w-md whitespace-normal text-sm" dir="auto">

                  {it.integrity_ok ? (

                    summarize(it.value)

                  ) : (

                    <span className="inline-flex items-center gap-1 text-destructive">

                      <ShieldAlertIcon className="size-3.5" aria-hidden />

                      {t("memory.tampered")}

                    </span>

                  )}

                </TableCell>

                <TableCell className="text-xs text-muted-foreground">

                  {formatDateTime(it.expires_at, locale)}

                </TableCell>

                <TableCell>

                  <Button variant="ghost" size="icon" aria-label={`${t("memory.forget")} ${it.key}`} onClick={() => void forget(it)}>

                    <Trash2Icon className="size-4" aria-hidden />

                  </Button>

                </TableCell>

              </TableRow>

            ))}

          </TableBody>

        </Table>

      </div>
    );
  }

  return (
    <div className="space-y-5">

      <PageHeader title={t("memory.title")} subtitle={t("memory.subtitle")} />

      {allowed && (

        <div className="flex flex-wrap items-end justify-between gap-3">

          <div className="flex flex-wrap gap-1" role="group" aria-label={t("memory.namespace")}>

            {KINDS.map((k) => (

              <Button

                key={k}

                size="sm"

                variant={kind === k ? "default" : "outline"}

                aria-pressed={kind === k}

                onClick={() => setKind(k)}

                className={cn(kind === k && "pointer-events-none")}

              >

                {m.memory.kinds[k]}

              </Button>

            ))}

          </div>

          <ForgetCustomer onDone={items.reload} />

        </div>

      )}

      {body}

    </div>
  );
}