File size: 5,392 Bytes
af1bee9
fb43301
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
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
import { Button, Group, Switch, Text } from '@mantine/core';
import { IconSend } from '@/components/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { getJson, sendJson } from '../api/client';
import { ErrorAlert, fmtTs } from '../components/common';
import { LoadingState } from '../components/states';
import { TelegramCard, type TelegramState } from './TelegramCard';
import { useBrowserPref } from './useNotifications';
import './notify.css';

/** GET /api/notifications/settings (admin). */
export interface NotifySettings {
  webhook_configured: boolean;
  webhook_host: string | null;
  signing: boolean;
  pending: number;
  last_delivery: { at: string; ok: boolean; status: number | null; error: string | null } | null;
  telegram?: TelegramState;
}

/** Settings > Notifications: where the coworkers' messages go (Telegram, or a webhook for n8n and other tools), and this browser. */
export function NotificationsSettings() {
  const qc = useQueryClient();
  const s = useQuery({ queryKey: ['notify-settings'], queryFn: () => getJson<NotifySettings>('/api/notifications/settings'), refetchInterval: 15_000, retry: false });
  const test = useMutation({
    mutationFn: () => sendJson<{ queued: boolean; id: number }>('POST', '/api/notifications/test'),
    onSuccess: () => { void qc.invalidateQueries({ queryKey: ['notify-settings'] }); void qc.invalidateQueries({ queryKey: ['notifications'] }); },
  });
  const browser = useBrowserPref();
  const d = s.data;
  const last = d?.last_delivery;
  return (
    <div className="pw-notify-settings" data-testid="notify-settings">

      <Text size="sm" c="dimmed">

        When a coworker needs you (scenarios to approve, a failure to decide, a finished run, a new defect), Astra sends a

        message. Each message opens the right screen; nothing is approved or changed until you confirm it there.

      </Text>



      {d && <TelegramCard tg={d.telegram} />}



      <section className="pw-card" aria-labelledby="notify-chat-h">

        <h2 id="notify-chat-h">Webhook (optional, for n8n or other tools)</h2>

        {s.isLoading ? <LoadingState label="Loading the notification settings" rows={2} />

          : s.error ? <ErrorAlert error={s.error} title="The notification settings could not be loaded" onRetry={() => void s.refetch()} />

            : d && (

              <dl className="pw-notify-dl">

                <dt>Webhook</dt>

                <dd data-testid="notify-webhook">{d.webhook_configured ? <>Set up{d.webhook_host ? <>, sends to <b>{d.webhook_host}</b></> : null}</> : 'Not set up yet'}</dd>

                <dt>Signed messages</dt>

                <dd>{d.signing ? 'On: n8n can check that each message came from Astra' : 'Off: set FPT_NOTIFY_SECRET to sign them'}</dd>

                <dt>Waiting to send</dt>

                <dd>{d.pending}</dd>

                <dt>Last delivery</dt>

                <dd>{last ? <span className="pw-status" data-tone={last.ok ? 'green' : 'red'}>{last.ok ? 'Delivered' : 'Failed'}</span> : 'None yet'}

                  {last && <> {fmtTs(last.at)}{last.status ? `, HTTP ${last.status}` : ''}{last.error ? `: ${last.error}` : ''}</>}</dd>
              </dl>
            )}
        <Group gap="sm" mt="md">
          <Button leftSection={<IconSend size={15} aria-hidden />} onClick={() => test.mutate()} loading={test.isPending} disabled={!d?.webhook_configured}

            data-testid="notify-test">Send a test message</Button>
          {test.isSuccess && <Text size="sm" role="status">Test message queued. It should arrive within a minute.</Text>}
        </Group>
        {test.error ? <ErrorAlert error={test.error} title="The test message was not sent" /> : null}
      </section>

      <section className="pw-card" aria-labelledby="notify-browser-h">

        <h2 id="notify-browser-h">This browser</h2>

        {browser.supported ? (

          <>

            <Switch label="Tell me in this browser too" description="A system notification when the app is in the background. Only for this browser and this account."

              checked={browser.on} disabled={browser.blocked} onChange={(e) => void browser.setOn(e.currentTarget.checked)} />

            {browser.blocked && <Text size="sm" c="dimmed" mt="xs">Your browser blocks notifications for this site. Allow them in the site settings to turn this on.</Text>}

          </>
        ) : <Text size="sm" c="dimmed">This browser does not support notifications.</Text>}
      </section>

      <section className="pw-card" aria-labelledby="notify-setup-h">

        <h2 id="notify-setup-h">Set up the webhook with n8n</h2>

        <ol className="pw-notify-steps">

          <li>In n8n, import the workflow <code>integrations/n8n/patchwise-telegram.json</code> and turn it on. Copy its production webhook URL.</li>

          <li>In n8n, add your Telegram bot token as a Telegram credential, and set the chat id (the workflow's README shows where).</li>

          <li>On the Astra server, set <code>FPT_NOTIFY_WEBHOOK_URL</code> to that webhook URL and <code>FPT_NOTIFY_SECRET</code> to a long random value; put the same value in the n8n workflow. Restart Astra.</li>

          <li>Come back here and press <b>Send a test message</b>.</li>

        </ol>

      </section>
    </div>
  );
}