Admin: widacznosc konta usera - lastLoginAt + IP w logach logowania + kafel historii konta (kto edytowal dane, historia kar) ; GET /admin/users/:id/activity
This commit is contained in:
@@ -36,6 +36,8 @@ export interface User {
|
||||
status: 'ACTIVE' | 'SUSPENDED' | 'BANNED';
|
||||
suspensionUntil: string | null;
|
||||
restrictionReason: string | null;
|
||||
/** Data ostatniego udanego logowania (login, nie odświeżanie tokenu); null = nigdy. */
|
||||
lastLoginAt?: string | null;
|
||||
createdAt: string;
|
||||
memberships?: { gymId: string; roles: GymRole[]; gym: Gym }[];
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"userId": "user",
|
||||
"date": "date",
|
||||
"client": "client",
|
||||
"ip": "IP address",
|
||||
"isAdmin": "admin",
|
||||
"suspensionUntil": "suspended until",
|
||||
"restrictionReason": "restriction reason",
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
"statKillstreak": "Killstreak",
|
||||
"statVolume7d": "7-day volume",
|
||||
"statSessions": "Sessions",
|
||||
"statLastLogin": "Last login",
|
||||
"accountHistory": "Account history",
|
||||
"noActivity": "No account events.",
|
||||
"byActor": "by {{actor}}",
|
||||
"lastLoginWord": "login: {{date}}",
|
||||
"ageValue": "{{age}} years",
|
||||
"personalInfo": "Personal details",
|
||||
"bodyParams": "Body parameters",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"userId": "użytkownik",
|
||||
"date": "data",
|
||||
"client": "klient",
|
||||
"ip": "adres IP",
|
||||
"isAdmin": "admin",
|
||||
"suspensionUntil": "zawieszenie do",
|
||||
"restrictionReason": "powód kary",
|
||||
|
||||
@@ -19,6 +19,11 @@
|
||||
"statKillstreak": "Killstreak",
|
||||
"statVolume7d": "Objętość 7 dni",
|
||||
"statSessions": "Sesje",
|
||||
"statLastLogin": "Ostatnie logowanie",
|
||||
"accountHistory": "Historia konta",
|
||||
"noActivity": "Brak zdarzeń konta.",
|
||||
"byActor": "przez {{actor}}",
|
||||
"lastLoginWord": "log: {{date}}",
|
||||
"ageValue": "{{age}} lat",
|
||||
"personalInfo": "Dane osobowe",
|
||||
"bodyParams": "Parametry ciała",
|
||||
|
||||
@@ -93,7 +93,7 @@ export function actionLabel(action: string) {
|
||||
return t(`actions.${action}`, { defaultValue: action });
|
||||
}
|
||||
|
||||
function actionColor(action: string): BadgeColor {
|
||||
export function actionColor(action: string): BadgeColor {
|
||||
if (action.startsWith('plan.')) return 'blue';
|
||||
if (action.startsWith('session.')) return 'green';
|
||||
if (action.startsWith('gym.')) return 'gray';
|
||||
@@ -108,7 +108,7 @@ export function formatLogDate(iso: string) {
|
||||
return fmtDateTime(iso);
|
||||
}
|
||||
|
||||
function actorName(log: ActivityLog) {
|
||||
export function actorName(log: ActivityLog) {
|
||||
const { firstName, lastName, email } = log.actor;
|
||||
return [firstName, lastName].filter(Boolean).join(' ') || email;
|
||||
}
|
||||
@@ -144,7 +144,7 @@ function formatDetailValue(log: ActivityLog, key: string, value: unknown): strin
|
||||
}
|
||||
|
||||
/** Szczegóły wpisu jako naturalny tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */
|
||||
function detailsText(log: ActivityLog) {
|
||||
export function detailsText(log: ActivityLog) {
|
||||
const d = log.details;
|
||||
if (!d) return null;
|
||||
const parts = Object.entries(d)
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
FileText,
|
||||
Flame,
|
||||
History,
|
||||
LogIn,
|
||||
Pause,
|
||||
Pencil,
|
||||
Scale,
|
||||
@@ -18,12 +19,23 @@ import {
|
||||
} from 'lucide-react';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { api } from '../../api/client';
|
||||
import { BackButton, Badge, Card, ConfirmDialog, ErrorText, Loading } from '../../components/ui';
|
||||
import {
|
||||
BackButton,
|
||||
Badge,
|
||||
Card,
|
||||
ConfirmDialog,
|
||||
ErrorText,
|
||||
Loading,
|
||||
Muted,
|
||||
SectionHeader,
|
||||
} from '../../components/ui';
|
||||
import { Avatar } from '../../components/Avatar';
|
||||
import { displayName, fmtDate, fmtDateTime, fmtVolume } from '../../lib/format';
|
||||
import { actionColor, actionLabel, actorName, detailsText, formatLogDate } from '../Logs';
|
||||
import { UserRestrictionModal } from './UserRestrictionModal';
|
||||
import {
|
||||
useAdminUser,
|
||||
useUserActivity,
|
||||
useUserBodyParameters,
|
||||
useUserClaims,
|
||||
useUserExerciseProgress,
|
||||
@@ -117,6 +129,7 @@ export default function UserDetail() {
|
||||
const { data: ks } = useUserKillstreak(id);
|
||||
const { data: claimsData } = useUserClaims(id);
|
||||
const { data: progressData } = useUserExerciseProgress(id);
|
||||
const { data: activityData } = useUserActivity(id);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [removeError, setRemoveError] = useState('');
|
||||
@@ -213,6 +226,7 @@ export default function UserDetail() {
|
||||
: t('resolvedClaims', { count: claims.length });
|
||||
|
||||
const progressCount = (progressData?.exercises ?? []).length;
|
||||
const activityLogs = activityData?.logs ?? [];
|
||||
const progressSummary =
|
||||
progressCount > 0
|
||||
? `${progressCount} ${
|
||||
@@ -276,6 +290,11 @@ export default function UserDetail() {
|
||||
label={t('statSessions')}
|
||||
value={sessions.length > 0 ? String(sessions.length) : '—'}
|
||||
/>
|
||||
<MiniStat
|
||||
icon={LogIn}
|
||||
label={t('statLastLogin')}
|
||||
value={user.lastLoginAt ? fmtDateTime(user.lastLoginAt) : '—'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sekcje: wiersze-listy; mobile kolumna (divide-y), sm+ siatka 2 kol. */}
|
||||
@@ -331,6 +350,30 @@ export default function UserDetail() {
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Historia konta: logi audytu NA użytkowniku (logowania z IP, kto edytował dane, kary/bany) */}
|
||||
<Card className="mt-4">
|
||||
<SectionHeader title={t('accountHistory')} />
|
||||
{activityLogs.length === 0 ? (
|
||||
<Muted>{t('noActivity')}</Muted>
|
||||
) : (
|
||||
<div className="divide-y divide-line">
|
||||
{activityLogs.map((log) => {
|
||||
const details = detailsText(log);
|
||||
return (
|
||||
<div key={log.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5">
|
||||
<span className="font-display text-dim text-[0.8rem] tabular-nums">
|
||||
{formatLogDate(log.createdAt)}
|
||||
</span>
|
||||
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
|
||||
<span className="text-[0.875rem]">{t('byActor', { actor: actorName(log) })}</span>
|
||||
{details && <span className="text-[0.8rem] text-dim">{details}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmOpen}
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Badge, Card, EmptyState, ErrorText, ListRow, Loading } from '../../comp
|
||||
import { Avatar } from '../../components/Avatar';
|
||||
import { useListSearch } from '../../store/list-search';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { fmtDate } from '../../lib/format';
|
||||
import { userDisplayName } from './UserDetail';
|
||||
|
||||
export default function UsersList() {
|
||||
@@ -66,6 +67,9 @@ export default function UsersList() {
|
||||
<>
|
||||
{u.email}
|
||||
{u.age != null ? ` · ${t('ageWord', { age: u.age })}` : ''}
|
||||
{u.lastLoginAt
|
||||
? ` · ${t('lastLoginWord', { date: fmtDate(u.lastLoginAt) })}`
|
||||
: ''}
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '../../api/client';
|
||||
import type {
|
||||
ActivityLogPage,
|
||||
CircumferenceSeries,
|
||||
ExerciseProgress,
|
||||
Gym,
|
||||
@@ -85,3 +86,12 @@ export function useUserClaims(id?: string) {
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
/** Historia konta: logi audytu wykonane NA użytkowniku (logowania/IP, edycje, kary, role). */
|
||||
export function useUserActivity(id?: string, limit = 10) {
|
||||
return useQuery({
|
||||
queryKey: ['user-activity', id, limit],
|
||||
queryFn: () => api<ActivityLogPage>(`/admin/users/${id}/activity?limit=${limit}`),
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
expect(await screen.findByText('Zablokowane')).toBeInTheDocument();
|
||||
@@ -123,6 +124,7 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
expect(await screen.findByText(/Zawieszone do/)).toBeInTheDocument();
|
||||
@@ -142,6 +144,7 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [{ id: 'e1' }] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
|
||||
@@ -186,12 +189,74 @@ describe('admin UserDetail (przegląd profilu)', () => {
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
const row = await screen.findByRole('link', { name: /Członkostwa w siłowniach/ });
|
||||
expect(row).toHaveTextContent('Gym A');
|
||||
expect(row).toHaveTextContent('OWNER, TRAINER');
|
||||
});
|
||||
|
||||
it('kafel historii konta: aktor, akcja, IP logowania i kara z powodem', async () => {
|
||||
const logs = [
|
||||
{
|
||||
id: 'l1',
|
||||
action: 'user.status.changed',
|
||||
entityType: 'user',
|
||||
entityId: 'u1',
|
||||
details: { actorId: 'a1', status: 'BANNED', restrictionReason: 'Sprzedaż kont' },
|
||||
createdAt: '2026-10-20T08:00:00.000Z',
|
||||
actor: { id: 'a1', email: 'ada@test.local', firstName: 'Ada', lastName: 'Admin' },
|
||||
},
|
||||
{
|
||||
id: 'l2',
|
||||
action: 'user.logged_in',
|
||||
entityType: 'user',
|
||||
entityId: 'u1',
|
||||
details: { actorId: 'u1', client: 'app', ip: '203.0.113.9' },
|
||||
createdAt: '2026-10-19T18:30:00.000Z',
|
||||
actor: { id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' },
|
||||
},
|
||||
];
|
||||
mockFetchRoutes([
|
||||
['/admin/users', () => ({ users: [{ ...U1, lastLoginAt: '2026-10-19T18:30:00.000Z' }] })],
|
||||
['/killstreak', () => ({ killstreak: 0 })],
|
||||
['/body-parameters', () => ({ weight: [], circumferences: [] })],
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs, total: logs.length })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
|
||||
// mini-statystyka ostatniego logowania (ten sam dzień występuje też w wierszu logowania)
|
||||
expect(await screen.findByText('Ostatnie logowanie')).toBeInTheDocument();
|
||||
expect(screen.getAllByText(/19\.10\.2026/).length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// historia: kto (aktor-admin) wykonał akcję + szczegóły kary
|
||||
expect(screen.getByText('Historia konta')).toBeInTheDocument();
|
||||
expect(screen.getByText('przez Ada Admin')).toBeInTheDocument();
|
||||
expect(screen.getByText('Zmiana statusu konta')).toBeInTheDocument();
|
||||
expect(screen.getByText(/powód kary: Sprzedaż kont/)).toBeInTheDocument();
|
||||
// logowanie z adresem IP
|
||||
expect(screen.getByText('Logowanie')).toBeInTheDocument();
|
||||
expect(screen.getByText(/adres IP: 203\.0\.113\.9/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('kafel historii konta: stan pusty', async () => {
|
||||
mockFetchRoutes([
|
||||
['/admin/users', () => ({ users: [U1] })],
|
||||
['/killstreak', () => ({ killstreak: 0 })],
|
||||
['/body-parameters', () => ({ weight: [], circumferences: [] })],
|
||||
['/history', () => ({ sessions: [] })],
|
||||
['/claims', () => ({ claims: [] })],
|
||||
['/exercise-progress', () => ({ exercises: [] })],
|
||||
['/activity', () => ({ logs: [], total: 0 })],
|
||||
]);
|
||||
renderUserDetail();
|
||||
expect(await screen.findByText('Historia konta')).toBeInTheDocument();
|
||||
expect(screen.getByText('Brak zdarzeń konta.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// tytuł sekcji → memberships | claims | info | body-parameters | history | progress
|
||||
|
||||
@@ -328,6 +328,50 @@ test('podstrony usera: topbar = Profil [nazwa], nazwa sekcji dopiero w treści (
|
||||
await expect(page.getByRole('heading', { name: 'Historia treningów' })).toHaveCount(1);
|
||||
});
|
||||
|
||||
test('historia konta: ostatnie logowanie, IP i kara z aktorem-adminem', async ({ page }) => {
|
||||
mockApi(page, {
|
||||
gyms: { gyms: [TEST_GYM] },
|
||||
users: {
|
||||
users: [{ ...TEST_USER, lastLoginAt: '2026-10-19T18:30:00.000Z' }],
|
||||
},
|
||||
activity: {
|
||||
logs: [
|
||||
{
|
||||
id: 'a-1',
|
||||
action: 'user.status.changed',
|
||||
entityType: 'user',
|
||||
entityId: 'user-1',
|
||||
details: { actorId: 'admin-1', status: 'BANNED', restrictionReason: 'Sprzedaż kont' },
|
||||
createdAt: '2026-10-20T08:00:00.000Z',
|
||||
actor: { id: 'admin-1', email: 'admin@fitos.pl', firstName: 'Admin', lastName: 'FitOS' },
|
||||
},
|
||||
{
|
||||
id: 'a-2',
|
||||
action: 'user.logged_in',
|
||||
entityType: 'user',
|
||||
entityId: 'user-1',
|
||||
details: { actorId: 'user-1', client: 'app', ip: '203.0.113.9' },
|
||||
createdAt: '2026-10-19T18:30:00.000Z',
|
||||
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
},
|
||||
});
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Użytkownicy' }).click();
|
||||
// lista: data ostatniego logowania przy wierszu użytkownika
|
||||
await expect(page.getByText(/log: 19\.10\.2026/)).toBeVisible();
|
||||
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
|
||||
|
||||
// mini-statystyka + kafel historii
|
||||
await expect(page.getByText('Ostatnie logowanie')).toBeVisible();
|
||||
await expect(page.getByText('Historia konta')).toBeVisible();
|
||||
await expect(page.getByText('przez Admin FitOS')).toBeVisible();
|
||||
await expect(page.getByText(/powód kary: Sprzedaż kont/)).toBeVisible();
|
||||
await expect(page.getByText(/adres IP: 203\.0\.113\.9/)).toBeVisible();
|
||||
});
|
||||
|
||||
test('kreator edycji: zapis bez zmian członkostw wysyła tylko PATCH konta', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM, TEST_GYM_2] }, users: { users: [TEST_USER] } });
|
||||
await loginAsAdmin(page);
|
||||
|
||||
@@ -250,6 +250,8 @@ export interface MockApiOptions {
|
||||
users?: unknown;
|
||||
/** Ciało odpowiedzi GET /admin/logs. */
|
||||
logs?: unknown;
|
||||
/** Ciało odpowiedzi GET /admin/users/:id/activity (historia konta). */
|
||||
activity?: unknown;
|
||||
/** Ciało odpowiedzi GET /admin/gyms/claims. */
|
||||
claims?: unknown;
|
||||
/** Startowy stan GET /admin/announcements (stateful CRUD w teście). */
|
||||
@@ -268,6 +270,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
gyms = { gyms: [] },
|
||||
users = { users: [] },
|
||||
logs = { logs: TEST_LOGS, total: TEST_LOGS.length },
|
||||
activity = { logs: [], total: 0 },
|
||||
claims = { claims: [] as GymClaim[] },
|
||||
announcements = [] as AdminAnnouncement[],
|
||||
} = opts;
|
||||
@@ -620,6 +623,14 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
}),
|
||||
);
|
||||
|
||||
page.route('**/api/v1/admin/users/*/activity*', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(activity ?? { logs: [], total: 0 }),
|
||||
}),
|
||||
);
|
||||
|
||||
page.route('**/api/v1/admin/users/*/history', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
|
||||
Reference in New Issue
Block a user