File size: 8,278 Bytes
ec4551b | 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | 'use client';
import React, { FC, useCallback, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
import { Button } from '@gitroom/react/form/button';
import { LoadingComponent } from '@gitroom/frontend/components/layout/loading';
interface PerSocial {
provider: string;
count: number;
}
interface StatsBlock {
total: number;
perSocial: PerSocial[];
}
interface StatsResponse {
from: string;
to: string;
errors: StatsBlock;
posts: StatsBlock;
connected: StatsBlock;
}
const isoDaysAgo = (days: number) => {
const d = new Date();
d.setDate(d.getDate() - days);
return d.toISOString().slice(0, 10);
};
const today = () => new Date().toISOString().slice(0, 10);
const startOfWeek = () => {
const d = new Date();
// ISO week: Monday = 0
const day = (d.getDay() + 6) % 7;
d.setDate(d.getDate() - day);
return d.toISOString().slice(0, 10);
};
const startOfMonth = () => {
const d = new Date();
d.setDate(1);
return d.toISOString().slice(0, 10);
};
const PRESETS: { label: string; range: () => { from: string; to: string } }[] = [
{ label: 'Today', range: () => ({ from: today(), to: today() }) },
{ label: 'This week', range: () => ({ from: startOfWeek(), to: today() }) },
{ label: 'This month', range: () => ({ from: startOfMonth(), to: today() }) },
{ label: 'Last 7 days', range: () => ({ from: isoDaysAgo(7), to: today() }) },
{ label: 'Last 30 days', range: () => ({ from: isoDaysAgo(30), to: today() }) },
];
const useStats = (params: {
from: string;
to: string;
unknownOnly: boolean;
}) => {
const fetch = useFetch();
const query = new URLSearchParams({
from: params.from,
to: params.to,
...(params.unknownOnly ? { unknownOnly: 'true' } : {}),
});
const key = `/admin/stats?${query.toString()}`;
return useSWR<StatsResponse>(
key,
async (url: string) => {
const res = await fetch(url);
if (!res.ok) {
throw new Error('Failed to load stats');
}
return res.json();
},
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
};
const SummaryCard: FC<{ label: string; value: number }> = ({
label,
value,
}) => (
<div className="border border-newTableBorder rounded-[8px] p-[16px] bg-newBgColorInner">
<div className="text-[12px] opacity-70">{label}</div>
<div className="text-[28px] font-[600]">{value.toLocaleString()}</div>
</div>
);
const PerSocialTable: FC<{ title: string; block: StatsBlock }> = ({
title,
block,
}) => (
<div className="border border-newTableBorder rounded-[8px] overflow-hidden">
<div className="grid grid-cols-[1fr_120px] gap-[12px] px-[12px] py-[10px] bg-newBgColorInner text-[12px] uppercase opacity-70 border-b border-newTableBorder">
<div>{title}</div>
<div className="text-right">Count</div>
</div>
{block.perSocial.length === 0 ? (
<div className="px-[12px] py-[10px] text-[13px] opacity-70">
No data for this timeframe.
</div>
) : (
block.perSocial.map((row) => (
<div
key={row.provider}
className="grid grid-cols-[1fr_120px] gap-[12px] px-[12px] py-[10px] text-[13px] border-b border-newTableBorder last:border-b-0"
>
<div className="capitalize">{row.provider}</div>
<div className="text-right">{row.count.toLocaleString()}</div>
</div>
))
)}
</div>
);
export const AdminStatsComponent: FC = () => {
const user = useUser();
const [fromInput, setFromInput] = useState(today());
const [toInput, setToInput] = useState(today());
const [range, setRange] = useState({ from: today(), to: today() });
const [unknownOnly, setUnknownOnly] = useState(false);
const { data, isLoading, error } = useStats({ ...range, unknownOnly });
const applyRange = useCallback((next: { from: string; to: string }) => {
setFromInput(next.from);
setToInput(next.to);
setRange(next);
}, []);
if (!user?.isSuperAdmin) {
return (
<div className="text-textColor p-[20px]">
You do not have access to this page.
</div>
);
}
return (
<div className="flex flex-col gap-[16px] text-textColor">
<div className="flex items-center justify-between">
<div className="text-[20px] font-[600]">Admin Stats</div>
{data && (
<div className="text-[13px] opacity-70">
{new Date(data.from).toLocaleDateString()} —{' '}
{new Date(data.to).toLocaleDateString()}
</div>
)}
</div>
<div className="flex flex-wrap gap-[8px]">
{PRESETS.map((preset) => {
const next = preset.range();
const active = range.from === next.from && range.to === next.to;
return (
<button
key={preset.label}
type="button"
onClick={() => applyRange(next)}
className={`h-[32px] px-[12px] rounded-[8px] text-[13px] border cursor-pointer whitespace-nowrap ${
active
? 'bg-forth text-white border-forth'
: 'bg-newBgColorInner text-textColor border-newTableBorder hover:bg-tableBorder'
}`}
>
{preset.label}
</button>
);
})}
</div>
<div className="flex flex-wrap gap-[12px] items-end bg-newBgColorInner border border-newTableBorder rounded-[8px] p-[12px]">
<div className="flex flex-col gap-[6px]">
<div className="text-[12px] opacity-70">From</div>
<input
type="date"
value={fromInput}
max={toInput}
onChange={(e) => setFromInput(e.target.value)}
className="bg-newBgColorInner h-[38px] border border-newTableBorder rounded-[8px] px-[10px] text-[14px] text-textColor"
/>
</div>
<div className="flex flex-col gap-[6px]">
<div className="text-[12px] opacity-70">To</div>
<input
type="date"
value={toInput}
min={fromInput}
max={today()}
onChange={(e) => setToInput(e.target.value)}
className="bg-newBgColorInner h-[38px] border border-newTableBorder rounded-[8px] px-[10px] text-[14px] text-textColor"
/>
</div>
<Button
onClick={() => setRange({ from: fromInput, to: toInput })}
disabled={!fromInput || !toInput || fromInput > toInput}
>
Apply
</Button>
<label
className="flex items-center gap-[6px] text-[13px] cursor-pointer h-[38px]"
title='Only count errors whose message matches "message":"Unknown Error" (affects the error stats only)'
>
<input
type="checkbox"
checked={unknownOnly}
onChange={(e) => setUnknownOnly(e.target.checked)}
/>
Unknown errors only
</label>
</div>
{isLoading ? (
<LoadingComponent />
) : error || !data ? (
<div className="text-red-400">Failed to load stats.</div>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-3 gap-[12px]">
<SummaryCard label="Total posts published" value={data.posts.total} />
<SummaryCard
label="Total connected accounts"
value={data.connected.total}
/>
<SummaryCard
label={unknownOnly ? 'Total unknown errors' : 'Total errors'}
value={data.errors.total}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-[12px]">
<PerSocialTable
title="Posts published per social"
block={data.posts}
/>
<PerSocialTable
title="Connected accounts per social"
block={data.connected}
/>
<PerSocialTable
title={
unknownOnly ? 'Unknown errors per social' : 'Errors per social'
}
block={data.errors}
/>
</div>
</>
)}
</div>
);
};
|