Projeto bot pontos
This commit is contained in:
209
web/app/(painel)/usuarios/[id]/forms.tsx
Normal file
209
web/app/(painel)/usuarios/[id]/forms.tsx
Normal file
@@ -0,0 +1,209 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState, type ChangeEvent, type FormEvent } from "react";
|
||||
import { WindowFields } from "@/components/WindowFields";
|
||||
import { apiFetch, errorMessage } from "@/lib/client-api";
|
||||
import { dayStatusLabel, fmtClock, fmtMinutes } from "@/lib/format";
|
||||
import type { QueryWindow, Schedule, Today } from "@/lib/types";
|
||||
|
||||
/** Grava e valida a credencial na PontoMais; a anterior é mantida se a validação falhar. */
|
||||
export function CredentialsForm({ userId }: { userId: number }) {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await apiFetch(`/users/${userId}/credentials`, { method: "PUT", body: { email, password } });
|
||||
setPassword("");
|
||||
setMessage({ ok: true, text: "Credencial validada na PontoMais e gravada." });
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setMessage({ ok: false, text: errorMessage(err) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="inline-form" onSubmit={submit} autoComplete="off">
|
||||
<label className="field">
|
||||
<span>E-mail de login na PontoMais</span>
|
||||
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Senha da PontoMais</span>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" required />
|
||||
</label>
|
||||
<button className="btn primary" type="submit" disabled={busy}>
|
||||
{busy ? "Validando…" : "Validar e salvar"}
|
||||
</button>
|
||||
{message && <p className={message.ok ? "ok-text" : "error-text"}>{message.text}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScheduleForm({
|
||||
userId,
|
||||
schedule,
|
||||
timezone,
|
||||
effectiveWindow,
|
||||
disabled,
|
||||
}: {
|
||||
userId: number;
|
||||
schedule: Schedule;
|
||||
timezone: string;
|
||||
effectiveWindow: QueryWindow;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [form, setForm] = useState({
|
||||
lunch_minutes: schedule.lunch_minutes,
|
||||
daily_work_minutes: schedule.daily_work_minutes,
|
||||
entrada2_lead_minutes: schedule.entrada2_lead_minutes,
|
||||
saida2_lead_minutes: schedule.saida2_lead_minutes,
|
||||
timezone,
|
||||
});
|
||||
const [useGlobal, setUseGlobal] = useState(schedule.window === null);
|
||||
const [windowValue, setWindowValue] = useState<QueryWindow>(schedule.window ?? effectiveWindow);
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
function number(key: keyof typeof form) {
|
||||
return (e: ChangeEvent<HTMLInputElement>) => setForm({ ...form, [key]: Number(e.target.value) });
|
||||
}
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await apiFetch(`/users/${userId}/schedule`, {
|
||||
method: "PUT",
|
||||
body: { ...form, window: useGlobal ? null : windowValue },
|
||||
});
|
||||
setMessage({ ok: true, text: "Jornada salva. Vale a partir da próxima consulta." });
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setMessage({ ok: false, text: errorMessage(err) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit}>
|
||||
<div className="grid-4">
|
||||
<label className="field">
|
||||
<span>Almoço (min)</span>
|
||||
<input type="number" min={15} max={180} value={form.lunch_minutes} onChange={number("lunch_minutes")} disabled={disabled} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Jornada (min) — {fmtMinutes(form.daily_work_minutes)}</span>
|
||||
<input type="number" min={60} max={720} value={form.daily_work_minutes} onChange={number("daily_work_minutes")} disabled={disabled} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Antecedência retorno (min)</span>
|
||||
<input type="number" min={0} max={60} value={form.entrada2_lead_minutes} onChange={number("entrada2_lead_minutes")} disabled={disabled} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Antecedência saída (min)</span>
|
||||
<input type="number" min={0} max={60} value={form.saida2_lead_minutes} onChange={number("saida2_lead_minutes")} disabled={disabled} />
|
||||
</label>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Fuso horário</span>
|
||||
<input value={form.timezone} onChange={(e) => setForm({ ...form, timezone: e.target.value })} disabled={disabled} />
|
||||
</label>
|
||||
|
||||
<fieldset className="fieldset">
|
||||
<legend>Janela de consulta</legend>
|
||||
<label className="checkbox">
|
||||
<input type="checkbox" checked={useGlobal} onChange={(e) => setUseGlobal(e.target.checked)} disabled={disabled} />
|
||||
Usar padrão global
|
||||
</label>
|
||||
{useGlobal ? (
|
||||
<p className="muted">
|
||||
Janela global: {effectiveWindow.query_window_start} às {effectiveWindow.query_window_end} (confirmação{" "}
|
||||
{effectiveWindow.day_check_deadline}, reverificações até {effectiveWindow.no_points_recheck_until}).
|
||||
</p>
|
||||
) : (
|
||||
<WindowFields value={windowValue} onChange={setWindowValue} disabled={disabled} />
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{!disabled && (
|
||||
<button className="btn primary" type="submit" disabled={busy}>
|
||||
{busy ? "Salvando…" : "Salvar jornada"}
|
||||
</button>
|
||||
)}
|
||||
{message && <p className={message.ok ? "ok-text" : "error-text"}>{message.text}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Consulta ao vivo na PontoMais (não é automática para não gastar consultas à toa). */
|
||||
export function TodayPanel({ userId, canTest }: { userId: number; canTest: boolean }) {
|
||||
const [today, setToday] = useState<Today | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function load(test: boolean) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const path = test ? `/users/${userId}/credentials/test` : `/users/${userId}/today`;
|
||||
setToday(await apiFetch<Today>(path, { method: test ? "POST" : "GET" }));
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="actions">
|
||||
<button className="btn secondary" type="button" onClick={() => load(false)} disabled={busy}>
|
||||
{busy ? "Consultando…" : "Consultar PontoMais agora"}
|
||||
</button>
|
||||
{canTest && (
|
||||
<button className="btn secondary" type="button" onClick={() => load(true)} disabled={busy}>
|
||||
Testar credencial
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="error-text">{error}</p>}
|
||||
{today && (
|
||||
<dl className="kv">
|
||||
<dt>Pontos</dt>
|
||||
<dd>{today.points.length ? today.points.map((p) => fmtClock(p, today.timezone)).join(" · ") : "nenhum"}</dd>
|
||||
{today.invalid && (
|
||||
<>
|
||||
<dt>Atenção</dt>
|
||||
<dd className="error-text">pontos repetidos ou fora de ordem</dd>
|
||||
</>
|
||||
)}
|
||||
{today.overtime && (
|
||||
<>
|
||||
<dt>Atenção</dt>
|
||||
<dd>mais de quatro pontos (hora extra, fora do escopo)</dd>
|
||||
</>
|
||||
)}
|
||||
<dt>Retorno previsto</dt>
|
||||
<dd>{fmtClock(today.entrada2_at, today.timezone)}</dd>
|
||||
<dt>Saída prevista</dt>
|
||||
<dd>{today.saida2_error ? <span className="error-text">{today.saida2_error}</span> : fmtClock(today.saida2_at, today.timezone)}</dd>
|
||||
<dt>Situação do dia</dt>
|
||||
<dd>{dayStatusLabel[today.day_state.status]}</dd>
|
||||
</dl>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
137
web/app/(painel)/usuarios/[id]/page.tsx
Normal file
137
web/app/(painel)/usuarios/[id]/page.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import Link from "next/link";
|
||||
import { apiGet } from "@/lib/server-api";
|
||||
import { badgeClass, dayStatusLabel, fmtDateTime, pauseReasonLabel, userStatusLabel } from "@/lib/format";
|
||||
import { isRestricted } from "@/lib/access";
|
||||
import type { Me, UserDetail } from "@/lib/types";
|
||||
import { ActionButton } from "@/components/ActionButton";
|
||||
import { CredentialsForm, ScheduleForm, TodayPanel } from "./forms";
|
||||
|
||||
export default async function UserPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const [detail, me] = await Promise.all([apiGet<UserDetail>(`/users/${id}`), apiGet<Me>("/auth/me")]);
|
||||
const { user, credential, today } = detail;
|
||||
const restricted = isRestricted(me.account);
|
||||
const canAdmin = me.account.role !== "viewer";
|
||||
// Conta de leitura ligada a este usuário também altera as próprias configurações.
|
||||
const canEdit = canAdmin || me.account.user_id === user.id;
|
||||
const base = `/users/${user.id}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
{!restricted && (
|
||||
<p>
|
||||
<Link href="/usuarios">← Usuários</Link>
|
||||
</p>
|
||||
)}
|
||||
<h1>
|
||||
{user.display_name} <span className={badgeClass(user.status)}>{userStatusLabel[user.status]}</span>
|
||||
</h1>
|
||||
<p className="muted">
|
||||
ID {user.id} · chat {user.telegram_chat_id} · cadastrado em {fmtDateTime(user.created_at)}
|
||||
</p>
|
||||
|
||||
<section className="card">
|
||||
<h2>Cadastro e lembretes</h2>
|
||||
<dl className="kv">
|
||||
<dt>Lembretes</dt>
|
||||
<dd>
|
||||
{user.notifications_enabled
|
||||
? "ligados"
|
||||
: user.paused_reason
|
||||
? pauseReasonLabel[user.paused_reason]
|
||||
: "desligados"}
|
||||
</dd>
|
||||
<dt>Admin do bot</dt>
|
||||
<dd>{user.is_bot_admin ? "sim" : "não"}</dd>
|
||||
<dt>Hoje ({today.day})</dt>
|
||||
<dd>
|
||||
<span className={badgeClass(today.status)}>{dayStatusLabel[today.status]}</span>{" "}
|
||||
<span className="muted">
|
||||
{today.last_point_count} ponto(s) na última consulta · próxima consulta: {fmtDateTime(today.next_check_at)}
|
||||
</span>
|
||||
</dd>
|
||||
</dl>
|
||||
{canEdit && (
|
||||
<div className="actions">
|
||||
{canAdmin && user.status !== "active" && <ActionButton path={`${base}/activate`} label="Ativar" variant="primary" />}
|
||||
{canAdmin && user.status !== "disabled" && (
|
||||
<ActionButton
|
||||
path={`${base}/disable`}
|
||||
label="Desativar"
|
||||
variant="danger"
|
||||
confirm="Desativar este usuário? Os lembretes agendados serão cancelados."
|
||||
/>
|
||||
)}
|
||||
{user.status === "active" &&
|
||||
(user.notifications_enabled ? (
|
||||
<ActionButton path={`${base}/notifications/disable`} label="Pausar lembretes" />
|
||||
) : (
|
||||
<ActionButton path={`${base}/notifications/enable`} label="Ligar lembretes" variant="primary" />
|
||||
))}
|
||||
{canAdmin && (
|
||||
<ActionButton
|
||||
path={`${base}/bot-admin`}
|
||||
method="PUT"
|
||||
body={{ enabled: !user.is_bot_admin }}
|
||||
label={user.is_bot_admin ? "Remover admin do bot" : "Tornar admin do bot"}
|
||||
/>
|
||||
)}
|
||||
{canAdmin && (today.status === "no_points" || today.status === "not_working") && (
|
||||
<ActionButton path={`${base}/today/resume`} label="Retomar consultas de hoje" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<h2>Credencial PontoMais</h2>
|
||||
{credential ? (
|
||||
<dl className="kv">
|
||||
<dt>E-mail</dt>
|
||||
<dd>{credential.api_email}</dd>
|
||||
<dt>Situação</dt>
|
||||
<dd>
|
||||
{credential.validated ? (
|
||||
<span className="badge ok">validada em {fmtDateTime(credential.last_validated_at)}</span>
|
||||
) : (
|
||||
<span className="badge warn">não validada</span>
|
||||
)}
|
||||
</dd>
|
||||
<dt>Falhas seguidas</dt>
|
||||
<dd>{credential.consecutive_failures}</dd>
|
||||
{credential.last_error && (
|
||||
<>
|
||||
<dt>Último erro</dt>
|
||||
<dd className="error-text">{credential.last_error}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
) : (
|
||||
<p className="muted">Nenhuma credencial configurada. Sem ela o usuário não pode ser ativado.</p>
|
||||
)}
|
||||
{canEdit && <CredentialsForm userId={user.id} />}
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<h2>Jornada e janela de consulta</h2>
|
||||
<ScheduleForm
|
||||
userId={user.id}
|
||||
schedule={detail.schedule}
|
||||
timezone={user.timezone}
|
||||
effectiveWindow={detail.effective_window}
|
||||
disabled={!canEdit}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<h2>Pontos de hoje</h2>
|
||||
<TodayPanel userId={user.id} canTest={canEdit} />
|
||||
</section>
|
||||
|
||||
<p>
|
||||
<Link href={`/notificacoes?user_id=${user.id}`}>Lembretes deste usuário</Link> ·{" "}
|
||||
{!restricted && <Link href={`/auditoria?target_user_id=${user.id}`}>Auditoria deste usuário</Link>}
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user