File size: 6,265 Bytes
af1bee9
fb43301
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { Button, CopyButton, Group, Text } from '@mantine/core';
import { IconBrandTelegram, IconCheck, IconCopy, IconLink, IconLinkOff } from '@/components/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { getJson, sendJson } from '../api/client';
import { ErrorAlert, fmtTs } from '../components/common';

/** GET /api/channels/me: the signed-in person's own linked channels. */
export interface MyChannels { telegram: { linked: boolean; username: string | null; linked_at: string | null } }
interface LinkCode { code: string; expires_at: string; bot_username: string | null }

const COMMANDS: [string, string][] = [
  ['/status', 'what is running and what waits for you'],
  ['/run Procure-to-Pay quick', 'start a quick simulation (you confirm it first)'],
  ['Is P2P ready for 26C?', 'any question, answered like on the Ask page'],
  ['/unlink', 'stop this chat acting as you'],
];

/** Seconds left until `iso`, ticking once a second; 0 when past. */
function useSecondsLeft(iso: string | null): number {
  const left = () => (iso ? Math.max(0, Math.round((new Date(iso).getTime() - Date.now()) / 1000)) : 0);
  const [s, setS] = useState(left);
  useEffect(() => {
    setS(left());
    if (!iso) return undefined;
    const t = window.setInterval(() => setS(left()), 1000);
    return () => window.clearInterval(t);
  }, [iso]); // eslint-disable-line react-hooks/exhaustive-deps -- left() reads iso only
  return s;
}

/**

 * "Astra in Telegram" on the Account page: each person links their own chat with a one-time code sent to the bot.

 * The chat then acts as them, with their permissions (status, starting runs after a confirm, questions).

 */
export function TelegramLinkCard() {
  const qc = useQueryClient();
  const [code, setCode] = useState<LinkCode | null>(null);
  const me = useQuery({
    queryKey: ['my-channels'], queryFn: () => getJson<MyChannels>('/api/channels/me'),
    refetchInterval: code ? 3000 : false,                       // while a code is shown, watch for the /link message
  });
  const linked = me.data?.telegram?.linked ?? false;   // an older server (or none yet) answers without it: not linked
  useEffect(() => { if (linked && code) setCode(null); }, [linked, code]);
  const secondsLeft = useSecondsLeft(code?.expires_at ?? null);
  const expired = !!code && secondsLeft === 0;
  const newCode = useMutation({
    mutationFn: () => sendJson<LinkCode>('POST', '/api/channels/telegram/link-code'),
    onSuccess: (c) => setCode(c),
  });
  const unlink = useMutation({
    mutationFn: () => sendJson<unknown>('DELETE', '/api/channels/telegram/link'),
    onSuccess: () => { void qc.invalidateQueries({ queryKey: ['my-channels'] }); },
  });
  const tg = me.data?.telegram ?? null;
  const problem = me.error || newCode.error || unlink.error;
  const mmss = `${Math.floor(secondsLeft / 60)}:${String(secondsLeft % 60).padStart(2, '0')}`;

  return (
    <section className="pw-card pw-bot" aria-labelledby="acc-tg-h" data-testid="tg-link-card">

      <h2 id="acc-tg-h" className="trio-card-h"><IconBrandTelegram size={18} aria-hidden /> Astra in Telegram</h2>

      <div aria-live="polite" className="pw-bot-state">

        {linked && tg ? (

          <div className="pw-bot-linked" data-testid="tg-linked">

            <span className="pw-tg-ok">Linked as <b>@{tg.username ?? 'unknown'}</b>{tg.linked_at ? ` since ${fmtTs(tg.linked_at)}` : ''}</span>

            <Button variant="subtle" leftSection={<IconLinkOff size={15} aria-hidden />} loading={unlink.isPending} data-testid="tg-unlink"

              onClick={() => { if (window.confirm('Unlink Telegram? That chat will stop getting updates and can no longer act as you.')) unlink.mutate(); }}>

              Unlink

            </Button>

          </div>

        ) : code && code.bot_username === null ? (

          <Text size="sm" data-testid="tg-not-setup">Telegram isn't set up yet: ask an administrator.</Text>

        ) : code && !expired ? (

          <div className="pw-bot-code" data-testid="tg-code-step">

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

              <li>Open <a href={`https://t.me/${code.bot_username}`} target="_blank" rel="noreferrer">t.me/{code.bot_username}</a> in Telegram.</li>

              <li>Send <code>/link {code.code}</code> to the bot.</li>

            </ol>

            <div className="pw-bot-codebox" role="group" aria-label="Your one-time link code">

              <span className="pw-bot-codeval" data-testid="tg-code">{code.code}</span>

              <CopyButton value={`/link ${code.code}`} timeout={2000}>

                {({ copied, copy }) => (

                  <Button size="xs" variant="default" onClick={copy} leftSection={copied ? <IconCheck size={14} aria-hidden /> : <IconCopy size={14} aria-hidden />}>

                    {copied ? 'Copied' : 'Copy the code'}

                  </Button>

                )}

              </CopyButton>

            </div>

            <Text size="xs" c="dimmed">The code works once and expires in {mmss}. This page updates when the bot has linked you.</Text>

          </div>

        ) : (

          <div className="pw-bot-intro">

            <Text size="sm">Get test-run updates and start runs from Telegram. Your chat acts as you, with your permissions.</Text>

            {expired && <Text size="sm" role="status" data-testid="tg-expired">That code expired. Get a new one.</Text>}

            <Group mt="xs">

              <Button leftSection={<IconLink size={15} aria-hidden />} onClick={() => newCode.mutate()} loading={newCode.isPending} data-testid="tg-link">

                Link my Telegram

              </Button>

            </Group>

          </div>

        )}

      </div>

      <div className="pw-bot-help">

        <h3 className="pw-bot-help-h">What you can say to the bot</h3>

        <dl className="pw-bot-cmds">

          {COMMANDS.map(([say, does]) => <div key={say}><dt><code>{say}</code></dt><dd>{does}</dd></div>)}

        </dl>

      </div>

      {problem ? <ErrorAlert error={problem} title="Telegram linking did not work" /> : null}

    </section>
  );
}