Feat/um 62 prisma property names (#1562)

* checkpoint

* fix pg schema

* fix mysql schema

* change property names
This commit is contained in:
Brian Cao 2022-10-10 13:42:18 -07:00 committed by GitHub
parent 36edbe2f4c
commit 78338205a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
65 changed files with 431 additions and 433 deletions

View File

@ -15,13 +15,13 @@ const initialValues = {
password: '', password: '',
}; };
const validate = ({ user_id, username, password }) => { const validate = ({ userId, username, password }) => {
const errors = {}; const errors = {};
if (!username) { if (!username) {
errors.username = <FormattedMessage id="label.required" defaultMessage="Required" />; errors.username = <FormattedMessage id="label.required" defaultMessage="Required" />;
} }
if (!user_id && !password) { if (!userId && !password) {
errors.password = <FormattedMessage id="label.required" defaultMessage="Required" />; errors.password = <FormattedMessage id="label.required" defaultMessage="Required" />;
} }
@ -33,8 +33,8 @@ export default function AccountEditForm({ values, onSave, onClose }) {
const [message, setMessage] = useState(); const [message, setMessage] = useState();
const handleSubmit = async values => { const handleSubmit = async values => {
const { user_id } = values; const { userId } = values;
const { ok, data } = await post(user_id ? `/accounts/${user_id}` : '/accounts', values); const { ok, data } = await post(userId ? `/accounts/${userId}` : '/accounts', values);
if (ok) { if (ok) {
onSave(); onSave();

View File

@ -43,7 +43,7 @@ export default function ChangePasswordForm({ values, onSave, onClose }) {
const { user } = useUser(); const { user } = useUser();
const handleSubmit = async values => { const handleSubmit = async values => {
const { ok, data } = await post(`/accounts/${user.user_id}/password`, values); const { ok, data } = await post(`/accounts/${user.userId}/password`, values);
if (ok) { if (ok) {
onSave(); onSave();

View File

@ -8,7 +8,7 @@ import CopyButton from 'components/common/CopyButton';
export default function TrackingCodeForm({ values, onClose }) { export default function TrackingCodeForm({ values, onClose }) {
const ref = useRef(); const ref = useRef();
const { basePath } = useRouter(); const { basePath } = useRouter();
const { name, share_id } = values; const { name, shareId } = values;
return ( return (
<FormLayout> <FormLayout>
@ -27,7 +27,7 @@ export default function TrackingCodeForm({ values, onClose }) {
spellCheck={false} spellCheck={false}
defaultValue={`${ defaultValue={`${
document.location.origin document.location.origin
}${basePath}/share/${share_id}/${encodeURIComponent(name)}`} }${basePath}/share/${shareId}/${encodeURIComponent(name)}`}
readOnly readOnly
/> />
</FormRow> </FormRow>

View File

@ -26,7 +26,7 @@ export default function TrackingCodeForm({ values, onClose }) {
rows={3} rows={3}
cols={60} cols={60}
spellCheck={false} spellCheck={false}
defaultValue={`<script async defer data-website-id="${values.website_uuid}" src="${ defaultValue={`<script async defer data-website-id="${values.websiteUuid}" src="${
document.location.origin document.location.origin
}${basePath}/${trackerScriptName ? `${trackerScriptName}.js` : 'umami.js'}"></script>`} }${basePath}/${trackerScriptName ? `${trackerScriptName}.js` : 'umami.js'}"></script>`}
readOnly readOnly

View File

@ -14,7 +14,6 @@ import useApi from 'hooks/useApi';
import useFetch from 'hooks/useFetch'; import useFetch from 'hooks/useFetch';
import useUser from 'hooks/useUser'; import useUser from 'hooks/useUser';
import styles from './WebsiteEditForm.module.css'; import styles from './WebsiteEditForm.module.css';
import { getRandomChars } from 'next-basics';
const initialValues = { const initialValues = {
name: '', name: '',
@ -42,14 +41,14 @@ const OwnerDropDown = ({ user, accounts }) => {
const { setFieldValue, values } = useFormikContext(); const { setFieldValue, values } = useFormikContext();
useEffect(() => { useEffect(() => {
if (values.user_id != null && values.owner === '') { if (values.userId != null && values.owner === '') {
setFieldValue('owner', values.user_id.toString()); setFieldValue('owner', values.userId.toString());
} else if (user?.user_id && values.owner === '') { } else if (user?.id && values.owner === '') {
setFieldValue('owner', user.user_id.toString()); setFieldValue('owner', user.id.toString());
} }
}, [accounts, setFieldValue, user, values]); }, [accounts, setFieldValue, user, values]);
if (user?.is_admin) { if (user?.isAdmin) {
return ( return (
<FormRow> <FormRow>
<label htmlFor="owner"> <label htmlFor="owner">
@ -58,7 +57,7 @@ const OwnerDropDown = ({ user, accounts }) => {
<div> <div>
<Field as="select" name="owner" className={styles.dropdown}> <Field as="select" name="owner" className={styles.dropdown}>
{accounts?.map(acc => ( {accounts?.map(acc => (
<option key={acc.user_id} value={acc.user_id}> <option key={acc.id} value={acc.id}>
{acc.username} {acc.username}
</option> </option>
))} ))}
@ -79,11 +78,9 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {
const [message, setMessage] = useState(); const [message, setMessage] = useState();
const handleSubmit = async values => { const handleSubmit = async values => {
const { website_id, enable_share_url, share_id } = values; const { id: websiteId } = values;
if (enable_share_url) {
values.share_id = share_id || getRandomChars(8); const { ok, data } = await post(websiteId ? `/websites/${websiteId}` : '/websites', values);
}
const { ok, data } = await post(website_id ? `/websites/${website_id}` : '/websites', values);
if (ok) { if (ok) {
onSave(); onSave();
@ -97,7 +94,7 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {
return ( return (
<FormLayout> <FormLayout>
<Formik <Formik
initialValues={{ ...initialValues, ...values, enable_share_url: !!values?.share_id }} initialValues={{ ...initialValues, ...values, enable_share_url: !!values?.shareId }}
validate={validate} validate={validate}
onSubmit={handleSubmit} onSubmit={handleSubmit}
> >
@ -121,9 +118,9 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {
name="domain" name="domain"
type="text" type="text"
placeholder="example.com" placeholder="example.com"
spellcheck="false" spellCheck="false"
autocapitalize="off" autoCapitalize="off"
autocorrect="off" autoCorrect="off"
/> />
<FormError name="domain" /> <FormError name="domain" />
</div> </div>

View File

@ -19,7 +19,7 @@ export default function Header() {
const { pathname } = useRouter(); const { pathname } = useRouter();
const { updatesDisabled } = useConfig(); const { updatesDisabled } = useConfig();
const isSharePage = pathname.includes('/share/'); const isSharePage = pathname.includes('/share/');
const allowUpdate = user?.is_admin && !updatesDisabled && !isSharePage; const allowUpdate = user?.isAdmin && !updatesDisabled && !isSharePage;
return ( return (
<> <>

View File

@ -9,8 +9,8 @@ function mapData(data) {
const arr = []; const arr = [];
data.reduce((obj, val) => { data.reduce((obj, val) => {
const { created_at } = val; const { createdAt } = val;
const t = startOfMinute(parseISO(created_at)); const t = startOfMinute(parseISO(createdAt));
if (t.getTime() > last) { if (t.getTime() > last) {
obj = { t: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 }; obj = { t: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 };
arr.push(obj); arr.push(obj);

View File

@ -11,9 +11,9 @@ export default function RealtimeHeader({ websites, data, websiteId, onSelect })
const options = [ const options = [
{ label: <FormattedMessage id="label.all-websites" defaultMessage="All websites" />, value: 0 }, { label: <FormattedMessage id="label.all-websites" defaultMessage="All websites" />, value: 0 },
].concat( ].concat(
websites.map(({ name, website_id }, index) => ({ websites.map(({ name, id }, index) => ({
label: name, label: name,
value: website_id, value: id,
divider: index === 0, divider: index === 0,
})), })),
); );
@ -22,7 +22,7 @@ export default function RealtimeHeader({ websites, data, websiteId, onSelect })
const count = useMemo(() => { const count = useMemo(() => {
return sessions.filter( return sessions.filter(
({ created_at }) => differenceInMinutes(new Date(), new Date(created_at)) <= 5, ({ createdAt }) => differenceInMinutes(new Date(), new Date(createdAt)) <= 5,
).length; ).length;
}, [sessions, websiteId]); }, [sessions, websiteId]);

View File

@ -37,7 +37,7 @@ export default function RealtimeLog({ data, websites, websiteId }) {
const logs = useMemo(() => { const logs = useMemo(() => {
const { pageviews, sessions, events } = data; const { pageviews, sessions, events } = data;
const logs = [...pageviews, ...sessions, ...events].sort(firstBy('created_at', -1)); const logs = [...pageviews, ...sessions, ...events].sort(firstBy('createdAt', -1));
if (filter) { if (filter) {
return logs.filter(row => getType(row) === filter); return logs.filter(row => getType(row) === filter);
} }
@ -45,8 +45,8 @@ export default function RealtimeLog({ data, websites, websiteId }) {
}, [data, filter]); }, [data, filter]);
const uuids = useMemo(() => { const uuids = useMemo(() => {
return data.sessions.reduce((obj, { session_id, session_uuid }) => { return data.sessions.reduce((obj, { sessionId, sessionUuid }) => {
obj[session_id] = session_uuid; obj[sessionId] = sessionUuid;
return obj; return obj;
}, {}); }, {});
}, [data]); }, [data]);
@ -70,14 +70,14 @@ export default function RealtimeLog({ data, websites, websiteId }) {
}, },
]; ];
function getType({ view_id, session_id, event_id }) { function getType({ pageviewId, sessionId, eventId }) {
if (event_id) { if (eventId) {
return TYPE_EVENT; return TYPE_EVENT;
} }
if (view_id) { if (pageviewId) {
return TYPE_PAGEVIEW; return TYPE_PAGEVIEW;
} }
if (session_id) { if (sessionId) {
return TYPE_SESSION; return TYPE_SESSION;
} }
return null; return null;
@ -87,26 +87,26 @@ export default function RealtimeLog({ data, websites, websiteId }) {
return TYPE_ICONS[getType(row)]; return TYPE_ICONS[getType(row)];
} }
function getWebsite({ website_id }) { function getWebsite({ websiteId }) {
return websites.find(n => n.website_id === website_id); return websites.find(n => n.id === websiteId);
} }
function getDetail({ function getDetail({
event_name, eventName,
view_id, pageviewId,
session_id, sessionId,
url, url,
browser, browser,
os, os,
country, country,
device, device,
website_id, websiteId,
}) { }) {
if (event_name) { if (eventName) {
return <div>{event_name}</div>; return <div>{eventName}</div>;
} }
if (view_id) { if (pageviewId) {
const domain = getWebsite({ website_id })?.domain; const domain = getWebsite({ websiteId })?.domain;
return ( return (
<a <a
className={styles.link} className={styles.link}
@ -118,7 +118,7 @@ export default function RealtimeLog({ data, websites, websiteId }) {
</a> </a>
); );
} }
if (session_id) { if (sessionId) {
return ( return (
<FormattedMessage <FormattedMessage
id="message.log.visitor" id="message.log.visitor"
@ -134,14 +134,14 @@ export default function RealtimeLog({ data, websites, websiteId }) {
} }
} }
function getTime({ created_at }) { function getTime({ createdAt }) {
return dateFormat(new Date(created_at), 'pp', locale); return dateFormat(new Date(createdAt), 'pp', locale);
} }
function getColor(row) { function getColor(row) {
const { session_id } = row; const { sessionId } = row;
return stringToColor(uuids[session_id] || `${session_id}${getWebsite(row)}`); return stringToColor(uuids[sessionId] || `${sessionId}${getWebsite(row)}`);
} }
const Row = ({ index, style }) => { const Row = ({ index, style }) => {

View File

@ -16,7 +16,7 @@ export default function RealtimeViews({ websiteId, data, websites }) {
id => id =>
websites.length === 1 websites.length === 1
? websites[0]?.domain ? websites[0]?.domain
: websites.find(({ website_id }) => website_id === id)?.domain, : websites.find(({ websiteId }) => websiteId === id)?.domain,
[websites], [websites],
); );
@ -65,10 +65,10 @@ export default function RealtimeViews({ websiteId, data, websites }) {
const pages = percentFilter( const pages = percentFilter(
pageviews pageviews
.reduce((arr, { url, website_id }) => { .reduce((arr, { url, websiteId }) => {
if (url?.startsWith('/')) { if (url?.startsWith('/')) {
if (!websiteId && websites.length > 1) { if (!websiteId && websites.length > 1) {
url = `${getDomain(website_id)}${url}`; url = `${getDomain(websiteId)}${url}`;
} }
const row = arr.find(({ x }) => x === url); const row = arr.find(({ x }) => x === url);

View File

@ -72,7 +72,7 @@ export default function WebsiteChart({
if (value === 'all') { if (value === 'all') {
const { data, ok } = await get(`/websites/${websiteId}`); const { data, ok } = await get(`/websites/${websiteId}`);
if (ok) { if (ok) {
setDateRange({ value, ...getDateRangeValues(new Date(data.created_at), Date.now()) }); setDateRange({ value, ...getDateRangeValues(new Date(data.createdAt), Date.now()) });
} }
} else { } else {
setDateRange(value); setDateRange(value);

View File

@ -17,8 +17,8 @@ export default function WebsiteHeader({ websiteId, title, domain, showLink = fal
<Favicon domain={domain} /> <Favicon domain={domain} />
<Link <Link
className={styles.titleLink} className={styles.titleLink}
href="/websites/[...id]" href="/website/[...id]"
as={`/websites/${websiteId}/${title}`} as={`/website/${websiteId}/${title}`}
> >
<OverflowText tooltipId={`${websiteId}-title`}>{title}</OverflowText> <OverflowText tooltipId={`${websiteId}-title`}>{title}</OverflowText>
</Link> </Link>
@ -41,8 +41,8 @@ export default function WebsiteHeader({ websiteId, title, domain, showLink = fal
<RefreshButton websiteId={websiteId} /> <RefreshButton websiteId={websiteId} />
{showLink && ( {showLink && (
<Link <Link
href="/websites/[...id]" href="/website/[...id]"
as={`/websites/${websiteId}/${title}`} as={`/website/${websiteId}/${title}`}
className={styles.link} className={styles.link}
icon={<Arrow />} icon={<Arrow />}
size="small" size="small"

View File

@ -24,7 +24,7 @@ export default function DashboardEdit({ websites }) {
const ordered = useMemo( const ordered = useMemo(
() => () =>
websites websites
.map(website => ({ ...website, order: order.indexOf(website.website_id) })) .map(website => ({ ...website, order: order.indexOf(website.websiteId) }))
.sort(firstBy('order')), .sort(firstBy('order')),
[websites, order], [websites, order],
); );
@ -36,7 +36,7 @@ export default function DashboardEdit({ websites }) {
const [removed] = orderedWebsites.splice(source.index, 1); const [removed] = orderedWebsites.splice(source.index, 1);
orderedWebsites.splice(destination.index, 0, removed); orderedWebsites.splice(destination.index, 0, removed);
setOrder(orderedWebsites.map((website) => website?.website_id || 0)); setOrder(orderedWebsites.map(website => website?.websiteId || 0));
} }
function handleSave() { function handleSave() {
@ -76,8 +76,8 @@ export default function DashboardEdit({ websites }) {
ref={provided.innerRef} ref={provided.innerRef}
style={{ marginBottom: snapshot.isDraggingOver ? 260 : null }} style={{ marginBottom: snapshot.isDraggingOver ? 260 : null }}
> >
{ordered.map(({ website_id, name, domain }, index) => ( {ordered.map(({ websiteId, name, domain }, index) => (
<Draggable key={website_id} draggableId={`${dragId}-${website_id}`} index={index}> <Draggable key={websiteId} draggableId={`${dragId}-${websiteId}`} index={index}>
{(provided, snapshot) => ( {(provided, snapshot) => (
<div <div
ref={provided.innerRef} ref={provided.innerRef}

View File

@ -21,11 +21,11 @@ function mergeData(state, data, time) {
const ids = state.map(({ __id }) => __id); const ids = state.map(({ __id }) => __id);
return state return state
.concat(data.filter(({ __id }) => !ids.includes(__id))) .concat(data.filter(({ __id }) => !ids.includes(__id)))
.filter(({ created_at }) => new Date(created_at).getTime() >= time); .filter(({ createdAt }) => new Date(createdAt).getTime() >= time);
} }
function filterWebsite(data, id) { function filterWebsite(data, id) {
return data.filter(({ website_id }) => website_id === id); return data.filter(({ websiteId }) => websiteId === id);
} }
export default function RealtimeDashboard() { export default function RealtimeDashboard() {

View File

@ -30,7 +30,7 @@ export default function Settings() {
{ {
label: <FormattedMessage id="label.accounts" defaultMessage="Accounts" />, label: <FormattedMessage id="label.accounts" defaultMessage="Accounts" />,
value: ACCOUNTS, value: ACCOUNTS,
hidden: !user?.is_admin, hidden: !user?.isAdmin,
}, },
{ {
label: <FormattedMessage id="label.profile" defaultMessage="Profile" />, label: <FormattedMessage id="label.profile" defaultMessage="Profile" />,

View File

@ -24,9 +24,9 @@ export default function TestConsole() {
return null; return null;
} }
const options = data.map(({ name, website_id }) => ({ label: name, value: website_id })); const options = data.map(({ name, websiteId }) => ({ label: name, value: websiteId }));
const website = data.find(({ website_id }) => website_id === +websiteId); const website = data.find(({ websiteId }) => websiteId === +websiteId);
const selectedValue = options.find(({ value }) => value === website?.website_id)?.value; const selectedValue = options.find(({ value }) => value === website?.websiteId)?.value;
function handleSelect(value) { function handleSelect(value) {
router.push(`/console/${value}`); router.push(`/console/${value}`);
@ -46,7 +46,7 @@ export default function TestConsole() {
<script <script
async async
defer defer
data-website-id={website.website_uuid} data-website-id={website.websiteUuid}
src={`${basePath}/umami.js`} src={`${basePath}/umami.js`}
data-cache="true" data-cache="true"
/> />
@ -104,13 +104,13 @@ export default function TestConsole() {
<div className="row"> <div className="row">
<div className="col-12"> <div className="col-12">
<WebsiteChart <WebsiteChart
websiteId={website.website_id} websiteId={website.websiteId}
title={website.name} title={website.name}
domain={website.domain} domain={website.domain}
showLink showLink
/> />
<PageHeader>Events</PageHeader> <PageHeader>Events</PageHeader>
<EventsChart websiteId={website.website_id} /> <EventsChart websiteId={website.websiteId} />
</div> </div>
</div> </div>
</> </>

View File

@ -27,7 +27,7 @@ export default function WebsiteList({ websites, showCharts, limit }) {
const ordered = useMemo( const ordered = useMemo(
() => () =>
websites websites
.map(website => ({ ...website, order: websiteOrder.indexOf(website.website_id) || 0 })) .map(website => ({ ...website, order: websiteOrder.indexOf(website.id) || 0 }))
.sort(firstBy('order')), .sort(firstBy('order')),
[websites, websiteOrder], [websites, websiteOrder],
); );
@ -46,11 +46,11 @@ export default function WebsiteList({ websites, showCharts, limit }) {
return ( return (
<div> <div>
{ordered.map(({ website_id, name, domain }, index) => {ordered.map(({ id, name, domain }, index) =>
index < limit ? ( index < limit ? (
<div key={website_id} className={styles.website}> <div key={id} className={styles.website}>
<WebsiteChart <WebsiteChart
websiteId={website_id} websiteId={id}
title={name} title={name}
domain={domain} domain={domain}
showChart={showCharts} showChart={showCharts}

View File

@ -27,10 +27,10 @@ export default function AccountSettings() {
const [message, setMessage] = useState(); const [message, setMessage] = useState();
const { data } = useFetch(`/accounts`, {}, [saved]); const { data } = useFetch(`/accounts`, {}, [saved]);
const Checkmark = ({ is_admin }) => (is_admin ? <Icon icon={<Check />} size="medium" /> : null); const Checkmark = ({ isAdmin }) => (isAdmin ? <Icon icon={<Check />} size="medium" /> : null);
const DashboardLink = row => ( const DashboardLink = row => (
<Link href={`/dashboard/${row.user_id}/${row.username}`}> <Link href={`/dashboard/${row.userId}/${row.username}`}>
<a> <a>
<Icon icon={<LinkIcon />} /> <Icon icon={<LinkIcon />} />
</a> </a>
@ -42,7 +42,7 @@ export default function AccountSettings() {
<Button icon={<Pen />} size="small" onClick={() => setEditAccount(row)}> <Button icon={<Pen />} size="small" onClick={() => setEditAccount(row)}>
<FormattedMessage id="label.edit" defaultMessage="Edit" /> <FormattedMessage id="label.edit" defaultMessage="Edit" />
</Button> </Button>
{!row.is_admin && ( {!row.isAdmin && (
<Button icon={<Trash />} size="small" onClick={() => setDeleteAccount(row)}> <Button icon={<Trash />} size="small" onClick={() => setDeleteAccount(row)}>
<FormattedMessage id="label.delete" defaultMessage="Delete" /> <FormattedMessage id="label.delete" defaultMessage="Delete" />
</Button> </Button>
@ -57,7 +57,7 @@ export default function AccountSettings() {
className: 'col-12 col-lg-4', className: 'col-12 col-lg-4',
}, },
{ {
key: 'is_admin', key: 'isAdmin',
label: <FormattedMessage id="label.administrator" defaultMessage="Administrator" />, label: <FormattedMessage id="label.administrator" defaultMessage="Administrator" />,
className: 'col-12 col-lg-3', className: 'col-12 col-lg-3',
render: Checkmark, render: Checkmark,
@ -121,7 +121,7 @@ export default function AccountSettings() {
title={<FormattedMessage id="label.delete-account" defaultMessage="Delete account" />} title={<FormattedMessage id="label.delete-account" defaultMessage="Delete account" />}
> >
<DeleteForm <DeleteForm
values={{ type: 'account', id: deleteAccount.user_id, name: deleteAccount.username }} values={{ type: 'accounts', id: deleteAccount.id, name: deleteAccount.username }}
onSave={handleSave} onSave={handleSave}
onClose={handleClose} onClose={handleClose}
/> />

View File

@ -32,7 +32,7 @@ export default function ProfileSettings() {
return null; return null;
} }
const { user_id, username } = user; const { userId, username } = user;
return ( return (
<> <>
@ -79,7 +79,7 @@ export default function ProfileSettings() {
title={<FormattedMessage id="label.change-password" defaultMessage="Change password" />} title={<FormattedMessage id="label.change-password" defaultMessage="Change password" />}
> >
<ChangePasswordForm <ChangePasswordForm
values={{ user_id }} values={{ userId }}
onSave={handleSave} onSave={handleSave}
onClose={() => setChangePassword(false)} onClose={() => setChangePassword(false)}
/> />

View File

@ -37,16 +37,16 @@ export default function WebsiteSettings() {
const [saved, setSaved] = useState(0); const [saved, setSaved] = useState(0);
const [message, setMessage] = useState(); const [message, setMessage] = useState();
const { data } = useFetch('/websites', { params: { include_all: !!user?.is_admin } }, [saved]); const { data } = useFetch('/websites', { params: { include_all: !!user?.isAdmin } }, [saved]);
const Buttons = row => ( const Buttons = row => (
<ButtonLayout align="right"> <ButtonLayout align="right">
{row.share_id && ( {row.shareId && (
<Button <Button
icon={<LinkIcon />} icon={<LinkIcon />}
size="small" size="small"
tooltip={<FormattedMessage id="message.get-share-url" defaultMessage="Get share URL" />} tooltip={<FormattedMessage id="message.get-share-url" defaultMessage="Get share URL" />}
tooltipId={`button-share-${row.website_id}`} tooltipId={`button-share-${row.id}`}
onClick={() => setShowUrl(row)} onClick={() => setShowUrl(row)}
/> />
)} )}
@ -56,46 +56,42 @@ export default function WebsiteSettings() {
tooltip={ tooltip={
<FormattedMessage id="message.get-tracking-code" defaultMessage="Get tracking code" /> <FormattedMessage id="message.get-tracking-code" defaultMessage="Get tracking code" />
} }
tooltipId={`button-code-${row.website_id}`} tooltipId={`button-code-${row.id}`}
onClick={() => setShowCode(row)} onClick={() => setShowCode(row)}
/> />
<Button <Button
icon={<Pen />} icon={<Pen />}
size="small" size="small"
tooltip={<FormattedMessage id="label.edit" defaultMessage="Edit" />} tooltip={<FormattedMessage id="label.edit" defaultMessage="Edit" />}
tooltipId={`button-edit-${row.website_id}`} tooltipId={`button-edit-${row.id}`}
onClick={() => setEditWebsite(row)} onClick={() => setEditWebsite(row)}
/> />
<Button <Button
icon={<Reset />} icon={<Reset />}
size="small" size="small"
tooltip={<FormattedMessage id="label.reset" defaultMessage="Reset" />} tooltip={<FormattedMessage id="label.reset" defaultMessage="Reset" />}
tooltipId={`button-reset-${row.website_id}`} tooltipId={`button-reset-${row.id}`}
onClick={() => setResetWebsite(row)} onClick={() => setResetWebsite(row)}
/> />
<Button <Button
icon={<Trash />} icon={<Trash />}
size="small" size="small"
tooltip={<FormattedMessage id="label.delete" defaultMessage="Delete" />} tooltip={<FormattedMessage id="label.delete" defaultMessage="Delete" />}
tooltipId={`button-delete-${row.website_id}`} tooltipId={`button-delete-${row.id}`}
onClick={() => setDeleteWebsite(row)} onClick={() => setDeleteWebsite(row)}
/> />
</ButtonLayout> </ButtonLayout>
); );
const DetailsLink = ({ website_id, name, domain }) => ( const DetailsLink = ({ id, name, domain }) => (
<Link <Link className={styles.detailLink} href="/website/[...id]" as={`/website/${id}/${name}`}>
className={styles.detailLink}
href="/websites/[...id]"
as={`/websites/${website_id}/${name}`}
>
<Favicon domain={domain} /> <Favicon domain={domain} />
<OverflowText tooltipId={`${website_id}-name`}>{name}</OverflowText> <OverflowText tooltipId={`${id}-name`}>{name}</OverflowText>
</Link> </Link>
); );
const Domain = ({ domain, website_id }) => ( const Domain = ({ domain, id }) => (
<OverflowText tooltipId={`${website_id}-domain`}>{domain}</OverflowText> <OverflowText tooltipId={`${id}-domain`}>{domain}</OverflowText>
); );
const adminColumns = [ const adminColumns = [
@ -187,7 +183,7 @@ export default function WebsiteSettings() {
<FormattedMessage id="label.add-website" defaultMessage="Add website" /> <FormattedMessage id="label.add-website" defaultMessage="Add website" />
</Button> </Button>
</PageHeader> </PageHeader>
<Table columns={user.is_admin ? adminColumns : columns} rows={data} empty={empty} /> <Table columns={user.isAdmin ? adminColumns : columns} rows={data} empty={empty} />
{editWebsite && ( {editWebsite && (
<Modal title={<FormattedMessage id="label.edit-website" defaultMessage="Edit website" />}> <Modal title={<FormattedMessage id="label.edit-website" defaultMessage="Edit website" />}>
<WebsiteEditForm values={editWebsite} onSave={handleSave} onClose={handleClose} /> <WebsiteEditForm values={editWebsite} onSave={handleSave} onClose={handleClose} />
@ -203,7 +199,7 @@ export default function WebsiteSettings() {
title={<FormattedMessage id="label.reset-website" defaultMessage="Reset statistics" />} title={<FormattedMessage id="label.reset-website" defaultMessage="Reset statistics" />}
> >
<ResetForm <ResetForm
values={{ type: 'website', id: resetWebsite.website_id, name: resetWebsite.name }} values={{ type: 'websites', id: resetWebsite.id, name: resetWebsite.name }}
onSave={handleSave} onSave={handleSave}
onClose={handleClose} onClose={handleClose}
/> />
@ -214,7 +210,7 @@ export default function WebsiteSettings() {
title={<FormattedMessage id="label.delete-website" defaultMessage="Delete website" />} title={<FormattedMessage id="label.delete-website" defaultMessage="Delete website" />}
> >
<DeleteForm <DeleteForm
values={{ type: 'website', id: deleteWebsite.website_id, name: deleteWebsite.name }} values={{ type: 'websites', id: deleteWebsite.id, name: deleteWebsite.name }}
onSave={handleSave} onSave={handleSave}
onClose={handleClose} onClose={handleClose}
/> />

View File

@ -8,88 +8,90 @@ datasource db {
} }
model account { model account {
user_id Int @id @default(autoincrement()) @db.UnsignedInt id Int @id @default(autoincrement()) @map("user_id") @db.UnsignedInt
username String @unique() @db.VarChar(255) username String @unique() @db.VarChar(255)
password String @db.VarChar(60) password String @db.VarChar(60)
is_admin Boolean @default(false) isAdmin Boolean @default(false) @map("is_admin")
created_at DateTime? @default(now()) @db.Timestamp(0) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
updated_at DateTime? @default(now()) @db.Timestamp(0) updatedAt DateTime? @default(now()) @map("updated_at") @db.Timestamp(0)
account_uuid String @unique() @db.VarChar(36) accountUuid String @unique() @map("account_uuid") @db.VarChar(36)
website website[] website website[]
} }
model event { model event {
event_id Int @id @default(autoincrement()) @db.UnsignedInt id Int @id @default(autoincrement()) @map("event_id") @db.UnsignedInt
website_id Int @db.UnsignedInt websiteId Int @map("website_id") @db.UnsignedInt
session_id Int @db.UnsignedInt sessionId Int @map("session_id") @db.UnsignedInt
created_at DateTime? @default(now()) @db.Timestamp(0) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
url String @db.VarChar(500) url String @db.VarChar(500)
event_name String @db.VarChar(50) eventName String @map("event_name") @db.VarChar(50)
session session @relation(fields: [session_id], references: [session_id]) session session @relation(fields: [sessionId], references: [id])
website website @relation(fields: [website_id], references: [website_id]) website website @relation(fields: [websiteId], references: [id])
event_data event_data? eventData eventData?
@@index([created_at]) @@index([createdAt])
@@index([session_id]) @@index([sessionId])
@@index([website_id]) @@index([websiteId])
} }
model event_data { model eventData {
event_data_id Int @id @default(autoincrement()) @db.UnsignedInt id Int @id @default(autoincrement()) @map("event_data_id") @db.UnsignedInt
event_id Int @unique @db.UnsignedInt eventId Int @unique @map("event_id") @db.UnsignedInt
event_data Json eventData Json @map("event_data")
event event @relation(fields: [event_id], references: [event_id]) event event @relation(fields: [eventId], references: [id])
@@map("event_data")
} }
model pageview { model pageview {
view_id Int @id @default(autoincrement()) @db.UnsignedInt id Int @id @default(autoincrement()) @map("view_id") @db.UnsignedInt
website_id Int @db.UnsignedInt websiteId Int @map("website_id") @db.UnsignedInt
session_id Int @db.UnsignedInt sessionId Int @map("session_id") @db.UnsignedInt
created_at DateTime? @default(now()) @db.Timestamp(0) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
url String @db.VarChar(500) url String @db.VarChar(500)
referrer String? @db.VarChar(500) referrer String? @db.VarChar(500)
session session @relation(fields: [session_id], references: [session_id]) session session @relation(fields: [sessionId], references: [id])
website website @relation(fields: [website_id], references: [website_id]) website website @relation(fields: [websiteId], references: [id])
@@index([created_at]) @@index([createdAt])
@@index([session_id]) @@index([sessionId])
@@index([website_id, created_at]) @@index([websiteId, createdAt])
@@index([website_id]) @@index([websiteId])
@@index([website_id, session_id, created_at]) @@index([websiteId, sessionId, createdAt])
} }
model session { model session {
session_id Int @id @default(autoincrement()) @db.UnsignedInt id Int @id @default(autoincrement()) @map("session_id") @db.UnsignedInt
session_uuid String @unique() @db.VarChar(36) sessionUuid String @unique() @map("session_uuid") @db.VarChar(36)
website_id Int @db.UnsignedInt websiteId Int @map("website_id") @db.UnsignedInt
created_at DateTime? @default(now()) @db.Timestamp(0) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
hostname String? @db.VarChar(100) hostname String? @db.VarChar(100)
browser String? @db.VarChar(20) browser String? @db.VarChar(20)
os String? @db.VarChar(20) os String? @db.VarChar(20)
device String? @db.VarChar(20) device String? @db.VarChar(20)
screen String? @db.VarChar(11) screen String? @db.VarChar(11)
language String? @db.VarChar(35) language String? @db.VarChar(35)
country String? @db.Char(2) country String? @db.Char(2)
website website @relation(fields: [website_id], references: [website_id]) website website @relation(fields: [websiteId], references: [id])
event event[] event event[]
pageview pageview[] pageview pageview[]
@@index([created_at]) @@index([createdAt])
@@index([website_id]) @@index([websiteId])
} }
model website { model website {
website_id Int @id @default(autoincrement()) @db.UnsignedInt id Int @id @default(autoincrement()) @map("website_id") @db.UnsignedInt
website_uuid String @unique() @db.VarChar(36) websiteUuid String @unique() @map("website_uuid") @db.VarChar(36)
user_id Int @db.UnsignedInt userId Int @map("user_id") @db.UnsignedInt
name String @db.VarChar(100) name String @db.VarChar(100)
domain String? @db.VarChar(500) domain String? @db.VarChar(500)
share_id String? @unique() @db.VarChar(64) shareId String? @unique() @map("share_id") @db.VarChar(64)
created_at DateTime? @default(now()) @db.Timestamp(0) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
account account @relation(fields: [user_id], references: [user_id]) account account @relation(fields: [userId], references: [id])
event event[] event event[]
pageview pageview[] pageview pageview[]
session session[] session session[]
@@index([user_id]) @@index([userId])
} }

View File

@ -8,88 +8,90 @@ datasource db {
} }
model account { model account {
user_id Int @id @default(autoincrement()) id Int @id @default(autoincrement()) @map("user_id")
username String @unique @db.VarChar(255) username String @unique @db.VarChar(255)
password String @db.VarChar(60) password String @db.VarChar(60)
is_admin Boolean @default(false) isAdmin Boolean @default(false) @map("is_admin")
created_at DateTime? @default(now()) @db.Timestamptz(6) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
updated_at DateTime? @default(now()) @db.Timestamptz(6) updatedAt DateTime? @default(now()) @map("updated_at") @db.Timestamptz(6)
account_uuid String @unique @db.Uuid accountUuid String @unique @map("account_uuid") @db.Uuid
website website[] website website[]
} }
model event { model event {
event_id Int @id @default(autoincrement()) id Int @id() @default(autoincrement()) @map("event_id")
website_id Int websiteId Int @map("website_id")
session_id Int sessionId Int @map("session_id")
created_at DateTime? @default(now()) @db.Timestamptz(6) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
url String @db.VarChar(500) url String @db.VarChar(500)
event_name String @db.VarChar(50) eventName String @map("event_name") @db.VarChar(50)
session session @relation(fields: [session_id], references: [session_id]) session session @relation(fields: [sessionId], references: [id])
website website @relation(fields: [website_id], references: [website_id]) website website @relation(fields: [websiteId], references: [id])
event_data event_data? eventData eventData?
@@index([created_at]) @@index([createdAt])
@@index([session_id]) @@index([sessionId])
@@index([website_id]) @@index([websiteId])
} }
model event_data { model eventData {
event_data_id Int @id @default(autoincrement()) id Int @id @default(autoincrement()) @map("event_data_id")
event_id Int @unique eventId Int @unique @map("event_id")
event_data Json eventData Json @map("event_data")
event event @relation(fields: [event_id], references: [event_id]) event event @relation(fields: [eventId], references: [id])
@@map("event_data")
} }
model pageview { model pageview {
view_id Int @id @default(autoincrement()) id Int @id @default(autoincrement()) @map("view_id")
website_id Int websiteId Int @map("website_id")
session_id Int sessionId Int @map("session_id")
created_at DateTime? @default(now()) @db.Timestamptz(6) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
url String @db.VarChar(500) url String @db.VarChar(500)
referrer String? @db.VarChar(500) referrer String? @db.VarChar(500)
session session @relation(fields: [session_id], references: [session_id]) session session @relation(fields: [sessionId], references: [id])
website website @relation(fields: [website_id], references: [website_id]) website website @relation(fields: [websiteId], references: [id])
@@index([created_at]) @@index([createdAt])
@@index([session_id]) @@index([sessionId])
@@index([website_id, created_at]) @@index([websiteId, createdAt])
@@index([website_id]) @@index([websiteId])
@@index([website_id, session_id, created_at]) @@index([websiteId, sessionId, createdAt])
} }
model session { model session {
session_id Int @id @default(autoincrement()) id Int @id @default(autoincrement()) @map("session_id")
session_uuid String @unique @db.Uuid sessionUuid String @unique @map("session_uuid") @db.Uuid
website_id Int websiteId Int @map("website_id")
created_at DateTime? @default(now()) @db.Timestamptz(6) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
hostname String? @db.VarChar(100) hostname String? @db.VarChar(100)
browser String? @db.VarChar(20) browser String? @db.VarChar(20)
os String? @db.VarChar(20) os String? @db.VarChar(20)
device String? @db.VarChar(20) device String? @db.VarChar(20)
screen String? @db.VarChar(11) screen String? @db.VarChar(11)
language String? @db.VarChar(35) language String? @db.VarChar(35)
country String? @db.Char(2) country String? @db.Char(2)
website website @relation(fields: [website_id], references: [website_id]) website website? @relation(fields: [websiteId], references: [id])
event event[] events event[]
pageview pageview[] pageview pageview[]
@@index([created_at]) @@index([createdAt])
@@index([website_id]) @@index([websiteId])
} }
model website { model website {
website_id Int @id @default(autoincrement()) id Int @id @default(autoincrement()) @map("website_id")
website_uuid String @unique @db.Uuid websiteUuid String @unique @map("website_uuid") @db.Uuid
user_id Int userId Int @map("user_id")
name String @db.VarChar(100) name String @db.VarChar(100)
domain String? @db.VarChar(500) domain String? @db.VarChar(500)
share_id String? @unique @db.VarChar(64) shareId String? @unique @map("share_id") @db.VarChar(64)
created_at DateTime? @default(now()) @db.Timestamptz(6) createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
account account @relation(fields: [user_id], references: [user_id]) account account @relation(fields: [userId], references: [id])
event event[] event event[]
pageview pageview[] pageview pageview[]
session session[] session session[]
@@index([user_id]) @@index([userId])
} }

View File

@ -40,19 +40,19 @@ export async function allowQuery(req, skipToken) {
const { id } = req.query; const { id } = req.query;
const token = req.headers[SHARE_TOKEN_HEADER]; const token = req.headers[SHARE_TOKEN_HEADER];
const website = await getWebsite(validate(id) ? { website_uuid: id } : { website_id: +id }); const website = await getWebsite(validate(id) ? { websiteUuid: id } : { id: +id });
if (website) { if (website) {
if (token && token !== 'undefined' && !skipToken) { if (token && token !== 'undefined' && !skipToken) {
return isValidToken(token, { website_id: website.website_id }); return isValidToken(token, { websiteId: website.id });
} }
const authToken = await getAuthToken(req); const authToken = await getAuthToken(req);
if (authToken) { if (authToken) {
const { user_id, is_admin } = authToken; const { userId, isAdmin } = authToken;
return is_admin || website.user_id === user_id; return isAdmin || website.userId === userId;
} }
} }

View File

@ -37,10 +37,10 @@ async function stageData() {
const websites = await getAllWebsites(); const websites = await getAllWebsites();
const sessionUuids = sessions.map(a => { const sessionUuids = sessions.map(a => {
return { key: `session:${a.session_uuid}`, value: 1 }; return { key: `session:${a.sessionUuid}`, value: 1 };
}); });
const websiteIds = websites.map(a => { const websiteIds = websites.map(a => {
return { key: `website:${a.website_uuid}`, value: Number(a.website_id) }; return { key: `website:${a.websiteUuid}`, value: Number(a.websiteId) };
}); });
await addSet(sessionUuids); await addSet(sessionUuids);

View File

@ -23,9 +23,9 @@ export async function getSession(req) {
} }
} }
const { website: website_uuid, hostname, screen, language } = payload; const { website: websiteUuid, hostname, screen, language } = payload;
if (!validate(website_uuid)) { if (!validate(websiteUuid)) {
return null; return null;
} }
@ -33,21 +33,21 @@ export async function getSession(req) {
// Check if website exists // Check if website exists
if (redis.enabled) { if (redis.enabled) {
websiteId = Number(await redis.get(`website:${website_uuid}`)); websiteId = Number(await redis.get(`website:${websiteUuid}`));
} }
// Check database if does not exists in Redis // Check database if does not exists in Redis
if (!websiteId) { if (!websiteId) {
const website = await getWebsiteByUuid(website_uuid); const website = await getWebsiteByUuid(websiteUuid);
websiteId = website ? website.website_id : null; websiteId = website ? website.websiteId : null;
} }
if (!websiteId || websiteId === DELETED) { if (!websiteId || websiteId === DELETED) {
throw new Error(`Website not found: ${website_uuid}`); throw new Error(`Website not found: ${websiteUuid}`);
} }
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload); const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
const session_uuid = uuid(websiteId, hostname, ip, userAgent); const sessionUuid = uuid(websiteId, hostname, ip, userAgent);
let sessionId = null; let sessionId = null;
let session = null; let session = null;
@ -55,19 +55,19 @@ export async function getSession(req) {
if (!clickhouse.enabled) { if (!clickhouse.enabled) {
// Check if session exists // Check if session exists
if (redis.enabled) { if (redis.enabled) {
sessionId = Number(await redis.get(`session:${session_uuid}`)); sessionId = Number(await redis.get(`session:${sessionUuid}`));
} }
// Check database if does not exists in Redis // Check database if does not exists in Redis
if (!sessionId) { if (!sessionId) {
session = await getSessionByUuid(session_uuid); session = await getSessionByUuid(sessionUuid);
sessionId = session ? session.session_id : null; sessionId = session ? session.sessionId : null;
} }
if (!sessionId) { if (!sessionId) {
try { try {
session = await createSession(websiteId, { session = await createSession(websiteId, {
session_uuid, sessionUuid,
hostname, hostname,
browser, browser,
os, os,
@ -84,8 +84,8 @@ export async function getSession(req) {
} }
} else { } else {
session = { session = {
session_id: sessionId, sessionId,
session_uuid, sessionUuid,
hostname, hostname,
browser, browser,
os, os,
@ -97,7 +97,7 @@ export async function getSession(req) {
} }
return { return {
website_id: websiteId, websiteId: websiteId,
session, session,
}; };
} }

View File

@ -37,7 +37,7 @@ export default async (req, res) => {
// Only admin can change these fields // Only admin can change these fields
if (currentUserIsAdmin) { if (currentUserIsAdmin) {
data.username = username; data.username = username;
data.is_admin = is_admin; data.isAdmin = is_admin;
} }
// Check when username changes // Check when username changes

View File

@ -12,7 +12,7 @@ import {
export default async (req, res) => { export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
const { user_id: currentUserId, is_admin: currentUserIsAdmin } = req.auth; const { userId: currentUserId, isAdmin: currentUserIsAdmin } = req.auth;
const { current_password, new_password } = req.body; const { current_password, new_password } = req.body;
const { id } = req.query; const { id } = req.query;
const userId = +id; const userId = +id;

View File

@ -6,9 +6,9 @@ import { createAccount, getAccountByUsername, getAccounts } from 'queries';
export default async (req, res) => { export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
const { is_admin } = req.auth; const { isAdmin } = req.auth;
if (!is_admin) { if (!isAdmin) {
return unauthorized(res); return unauthorized(res);
} }
@ -30,7 +30,7 @@ export default async (req, res) => {
const created = await createAccount({ const created = await createAccount({
username, username,
password: hashPassword(password), password: hashPassword(password),
account_uuid: account_uuid || uuid(), accountUuid: account_uuid || uuid(),
}); });
return ok(res, created); return ok(res, created);

View File

@ -12,8 +12,8 @@ export default async (req, res) => {
const account = await getAccountByUsername(username); const account = await getAccountByUsername(username);
if (account && checkPassword(password, account.password)) { if (account && checkPassword(password, account.password)) {
const { user_id, username, is_admin } = account; const { id, username, isAdmin, accountUuid } = account;
const user = { user_id, username, is_admin }; const user = { userId: id, username, isAdmin, accountUuid };
const token = createSecureToken(user, secret()); const token = createSecureToken(user, secret());
return ok(res, { token, user }); return ok(res, { token, user });

View File

@ -59,35 +59,35 @@ export default async (req, res) => {
await useSession(req, res); await useSession(req, res);
const { const {
session: { website_id, session }, session: { websiteId, session },
} = req; } = req;
const { type, payload } = getJsonBody(req); const { type, payload } = getJsonBody(req);
let { url, referrer, event_name, event_data } = payload; let { url, referrer, eventName, eventData } = payload;
if (process.env.REMOVE_TRAILING_SLASH) { if (process.env.REMOVE_TRAILING_SLASH) {
url = url.replace(/\/$/, ''); url = url.replace(/\/$/, '');
} }
const event_uuid = uuid(); const eventUuid = uuid();
if (type === 'pageview') { if (type === 'pageview') {
await savePageView(website_id, { session, url, referrer }); await savePageView(websiteId, { session, url, referrer });
} else if (type === 'event') { } else if (type === 'event') {
await saveEvent(website_id, { await saveEvent(websiteId, {
session, session,
event_uuid, eventUuid,
url, url,
event_name, eventName,
event_data, eventData,
}); });
} else { } else {
return badRequest(res); return badRequest(res);
} }
const token = createToken( const token = createToken(
{ website_id, session_id: session.session_id, session_uuid: session.session_uuid }, { websiteId, sessionId: session.sessionId, sessionUuid: session.sessionUuid },
secret(), secret(),
); );

View File

@ -8,10 +8,10 @@ export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'GET') { if (req.method === 'GET') {
const { user_id } = req.auth; const { userId } = req.auth;
const websites = await getUserWebsites(user_id); const websites = await getUserWebsites(userId);
const ids = websites.map(({ website_id }) => website_id); const ids = websites.map(({ id }) => id);
const token = createToken({ websites: ids }, secret()); const token = createToken({ websites: ids }, secret());
const data = await getRealtimeData(ids, subMinutes(new Date(), 30)); const data = await getRealtimeData(ids, subMinutes(new Date(), 30));

View File

@ -9,8 +9,8 @@ export default async (req, res) => {
const website = await getWebsiteByShareId(id); const website = await getWebsiteByShareId(id);
if (website) { if (website) {
const websiteId = website.website_id; const websiteId = website.websiteId;
const token = createToken({ website_id: websiteId }, secret()); const token = createToken({ websiteId: websiteId }, secret());
return ok(res, { websiteId, token }); return ok(res, { websiteId, token });
} }

View File

@ -26,7 +26,7 @@ export default async (req, res) => {
const events = await getEventMetrics(websiteId, startDate, endDate, tz, unit, { const events = await getEventMetrics(websiteId, startDate, endDate, tz, unit, {
url, url,
event_name, eventName: event_name,
}); });
return ok(res, events); return ok(res, events);

View File

@ -1,4 +1,4 @@
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized, getRandomChars } from 'next-basics';
import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries'; import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
@ -8,7 +8,7 @@ export default async (req, res) => {
const { id } = req.query; const { id } = req.query;
const websiteId = +id; const websiteId = +id;
const where = validate(id) ? { website_uuid: id } : { website_id: +id }; const where = validate(id) ? { websiteUuid: id } : { id: +id };
if (req.method === 'GET') { if (req.method === 'GET') {
await useCors(req, res); await useCors(req, res);
@ -25,17 +25,19 @@ export default async (req, res) => {
if (req.method === 'POST') { if (req.method === 'POST') {
await useAuth(req, res); await useAuth(req, res);
const { is_admin: currentUserIsAdmin, user_id: currentUserId, account_uuid } = req.auth; const { isAdmin: currentUserIsAdmin, userId: currentUserId, accountUuid } = req.auth;
const { name, domain, owner, share_id } = req.body; const { name, domain, owner, enable_share_url } = req.body;
let account; let account;
if (account_uuid) { if (accountUuid) {
account = await getAccount({ account_uuid }); account = await getAccount({ accountUuid });
} }
const website = await getWebsite(where); const website = await getWebsite(where);
if (website.user_id !== currentUserId && !currentUserIsAdmin) { const shareId = enable_share_url ? website.shareId || getRandomChars(8) : null;
if (website.userId !== currentUserId && !currentUserIsAdmin) {
return unauthorized(res); return unauthorized(res);
} }
@ -43,8 +45,8 @@ export default async (req, res) => {
{ {
name, name,
domain, domain,
share_id: share_id || null, shareId: shareId,
user_id: account ? account.id : +owner, userId: account ? account.id : +owner,
}, },
where, where,
); );

View File

@ -11,9 +11,9 @@ export default async (req, res) => {
return unauthorized(res); return unauthorized(res);
} }
const { id, start_at, end_at, url, referrer, os, browser, device, country } = req.query; const { website_id, start_at, end_at, url, referrer, os, browser, device, country } = req.query;
const websiteId = +id; const websiteId = +website_id;
const startDate = new Date(+start_at); const startDate = new Date(+start_at);
const endDate = new Date(+end_at); const endDate = new Date(+end_at);

View File

@ -6,44 +6,41 @@ import { uuid } from 'lib/crypto';
export default async (req, res) => { export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
const { user_id: current_user_id, is_admin, account_uuid } = req.auth; const { userId: currentUserId, isAdmin, accountUuid } = req.auth;
const { user_id, include_all } = req.query; const { user_id, include_all } = req.query;
let account; let account;
if (account_uuid) { if (accountUuid) {
account = await getAccount({ account_uuid }); account = await getAccount({ accountUuid: accountUuid });
} }
const userId = account ? account.user_id : +user_id; const userId = account ? account.id : +user_id;
if (req.method === 'GET') { if (req.method === 'GET') {
if (userId && userId !== current_user_id && !is_admin) { if (userId && userId !== currentUserId && !isAdmin) {
return unauthorized(res); return unauthorized(res);
} }
const websites = const websites =
is_admin && include_all isAdmin && include_all
? await getAllWebsites() ? await getAllWebsites()
: await getUserWebsites(userId || current_user_id); : await getUserWebsites(userId || currentUserId);
return ok(res, websites); return ok(res, websites);
} }
if (req.method === 'POST') { if (req.method === 'POST') {
await useAuth(req, res);
const { is_admin: currentUserIsAdmin, user_id: currentUserId } = req.auth;
const { name, domain, owner, enable_share_url } = req.body; const { name, domain, owner, enable_share_url } = req.body;
const website_owner = account ? account.user_id : +owner; const website_owner = account ? account.id : +owner;
if (website_owner !== currentUserId && !currentUserIsAdmin) { if (website_owner !== currentUserId && !isAdmin) {
return unauthorized(res); return unauthorized(res);
} }
const website_uuid = uuid(); const websiteUuid = uuid();
const share_id = enable_share_url ? getRandomChars(8) : null; const shareId = enable_share_url ? getRandomChars(8) : null;
const website = await createWebsite(website_owner, { website_uuid, name, domain, share_id }); const website = await createWebsite(website_owner, { websiteUuid, name, domain, shareId });
return ok(res, website); return ok(res, website);
} }

View File

@ -8,7 +8,7 @@ export default function ConsolePage({ enabled }) {
const { loading } = useRequireLogin(); const { loading } = useRequireLogin();
const { user } = useUser(); const { user } = useUser();
if (loading || !enabled || !user?.is_admin) { if (loading || !enabled || !user?.isAdmin) {
return null; return null;
} }

View File

@ -1,40 +1,40 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
import redis, { DELETED } from 'lib/redis'; import redis, { DELETED } from 'lib/redis';
export async function deleteAccount(user_id) { export async function deleteAccount(userId) {
const { client } = prisma; const { client } = prisma;
const websites = await client.website.findMany({ const websites = await client.website.findMany({
where: { user_id }, where: { userId },
select: { website_uuid: true }, select: { websiteUuid: true },
}); });
let websiteUuids = []; let websiteUuids = [];
if (websites.length > 0) { if (websites.length > 0) {
websiteUuids = websites.map(a => a.website_uuid); websiteUuids = websites.map(a => a.websiteUuid);
} }
return client return client
.$transaction([ .$transaction([
client.pageview.deleteMany({ client.pageview.deleteMany({
where: { session: { website: { user_id } } }, where: { session: { website: { userId } } },
}), }),
client.event_data.deleteMany({ client.eventData.deleteMany({
where: { event: { session: { website: { user_id } } } }, where: { event: { session: { website: { userId } } } },
}), }),
client.event.deleteMany({ client.event.deleteMany({
where: { session: { website: { user_id } } }, where: { session: { website: { userId } } },
}), }),
client.session.deleteMany({ client.session.deleteMany({
where: { website: { user_id } }, where: { website: { userId } },
}), }),
client.website.deleteMany({ client.website.deleteMany({
where: { user_id }, where: { userId },
}), }),
client.account.delete({ client.account.delete({
where: { where: {
user_id, id: userId,
}, },
}), }),
]) ])

View File

@ -1,9 +1,9 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function getAccountById(user_id) { export async function getAccountById(userId) {
return prisma.client.account.findUnique({ return prisma.client.account.findUnique({
where: { where: {
user_id, id: userId,
}, },
}); });
} }

View File

@ -3,17 +3,17 @@ import prisma from 'lib/prisma';
export async function getAccounts() { export async function getAccounts() {
return prisma.client.account.findMany({ return prisma.client.account.findMany({
orderBy: [ orderBy: [
{ is_admin: 'desc' }, { isAdmin: 'desc' },
{ {
username: 'asc', username: 'asc',
}, },
], ],
select: { select: {
user_id: true, id: true,
username: true, username: true,
is_admin: true, isAdmin: true,
created_at: true, createdAt: true,
updated_at: true, updatedAt: true,
}, },
}); });
} }

View File

@ -1,9 +1,9 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function updateAccount(user_id, data) { export async function updateAccount(userId, data) {
return prisma.client.account.update({ return prisma.client.account.update({
where: { where: {
user_id, id: userId,
}, },
data, data,
}); });

View File

@ -1,13 +1,13 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
import redis from 'lib/redis'; import redis from 'lib/redis';
export async function createWebsite(user_id, data) { export async function createWebsite(userId, data) {
return prisma.client.website return prisma.client.website
.create({ .create({
data: { data: {
account: { account: {
connect: { connect: {
user_id, id: userId,
}, },
}, },
...data, ...data,
@ -15,7 +15,7 @@ export async function createWebsite(user_id, data) {
}) })
.then(async res => { .then(async res => {
if (redis.client && res) { if (redis.client && res) {
await redis.client.set(`website:${res.website_uuid}`, res.website_id); await redis.client.set(`website:${res.websiteUuid}`, res.id);
} }
return res; return res;

View File

@ -2,30 +2,30 @@ import prisma from 'lib/prisma';
import redis, { DELETED } from 'lib/redis'; import redis, { DELETED } from 'lib/redis';
import { getWebsiteById } from 'queries'; import { getWebsiteById } from 'queries';
export async function deleteWebsite(website_id) { export async function deleteWebsite(websiteId) {
const { client, transaction } = prisma; const { client, transaction } = prisma;
const { website_uuid } = await getWebsiteById(website_id); const { websiteUuid } = await getWebsiteById(websiteId);
return transaction([ return transaction([
client.pageview.deleteMany({ client.pageview.deleteMany({
where: { session: { website: { website_id } } }, where: { session: { website: { id: websiteId } } },
}), }),
client.event_data.deleteMany({ client.eventData.deleteMany({
where: { event: { session: { website: { website_id } } } }, where: { event: { session: { website: { id: websiteId } } } },
}), }),
client.event.deleteMany({ client.event.deleteMany({
where: { session: { website: { website_id } } }, where: { session: { website: { id: websiteId } } },
}), }),
client.session.deleteMany({ client.session.deleteMany({
where: { website: { website_id } }, where: { website: { id: websiteId } },
}), }),
client.website.delete({ client.website.delete({
where: { website_id }, where: { id: websiteId },
}), }),
]).then(async res => { ]).then(async res => {
if (redis.client) { if (redis.client) {
await redis.client.set(`website:${website_uuid}`, DELETED); await redis.client.set(`website:${websiteUuid}`, DELETED);
} }
return res; return res;

View File

@ -4,7 +4,7 @@ export async function getAllWebsites() {
let data = await prisma.client.website.findMany({ let data = await prisma.client.website.findMany({
orderBy: [ orderBy: [
{ {
user_id: 'asc', userId: 'asc',
}, },
{ {
name: 'asc', name: 'asc',

View File

@ -1,9 +1,9 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function getUserWebsites(user_id) { export async function getUserWebsites(userId) {
return prisma.client.website.findMany({ return prisma.client.website.findMany({
where: { where: {
user_id, userId,
}, },
orderBy: { orderBy: {
name: 'asc', name: 'asc',

View File

@ -1,9 +1,9 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function getWebsiteById(website_id) { export async function getWebsiteById(websiteId) {
return prisma.client.website.findUnique({ return prisma.client.website.findUnique({
where: { where: {
website_id, id: websiteId,
}, },
}); });
} }

View File

@ -1,9 +1,9 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function getWebsiteByShareId(share_id) { export async function getWebsiteByShareId(shareId) {
return prisma.client.website.findUnique({ return prisma.client.website.findUnique({
where: { where: {
share_id, shareId,
}, },
}); });
} }

View File

@ -1,16 +1,16 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
import redis from 'lib/redis'; import redis from 'lib/redis';
export async function getWebsiteByUuid(website_uuid) { export async function getWebsiteByUuid(websiteUuid) {
return prisma.client.website return prisma.client.website
.findUnique({ .findUnique({
where: { where: {
website_uuid, websiteUuid,
}, },
}) })
.then(async res => { .then(async res => {
if (redis.client && res) { if (redis.client && res) {
await redis.client.set(`website:${res.website_uuid}`, res.website_id); await redis.client.set(`website:${res.websiteUuid}`, res.id);
} }
return res; return res;

View File

@ -1,20 +1,20 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function resetWebsite(website_id) { export async function resetWebsite(websiteId) {
const { client, transaction } = prisma; const { client, transaction } = prisma;
return transaction([ return transaction([
client.pageview.deleteMany({ client.pageview.deleteMany({
where: { session: { website: { website_id } } }, where: { session: { website: { id: websiteId } } },
}), }),
client.event_data.deleteMany({ client.eventData.deleteMany({
where: { event: { session: { website: { website_id } } } }, where: { event: { session: { website: { id: websiteId } } } },
}), }),
client.event.deleteMany({ client.event.deleteMany({
where: { session: { website: { website_id } } }, where: { session: { website: { id: websiteId } } },
}), }),
client.session.deleteMany({ client.session.deleteMany({
where: { website: { website_id } }, where: { website: { id: websiteId } },
}), }),
]); ]);
} }

View File

@ -10,7 +10,7 @@ export async function getEventMetrics(...args) {
} }
async function relationalQuery( async function relationalQuery(
website_id, websiteId,
start_at, start_at,
end_at, end_at,
timezone = 'utc', timezone = 'utc',
@ -18,7 +18,7 @@ async function relationalQuery(
filters = {}, filters = {},
) { ) {
const { rawQuery, getDateQuery, getFilterQuery } = prisma; const { rawQuery, getDateQuery, getFilterQuery } = prisma;
const params = [website_id, start_at, end_at]; const params = [websiteId, start_at, end_at];
return rawQuery( return rawQuery(
`select `select
@ -36,7 +36,7 @@ async function relationalQuery(
} }
async function clickhouseQuery( async function clickhouseQuery(
website_id, websiteId,
start_at, start_at,
end_at, end_at,
timezone = 'UTC', timezone = 'UTC',
@ -44,7 +44,7 @@ async function clickhouseQuery(
filters = {}, filters = {},
) { ) {
const { rawQuery, getDateQuery, getBetweenDates, getFilterQuery } = clickhouse; const { rawQuery, getDateQuery, getBetweenDates, getFilterQuery } = clickhouse;
const params = [website_id]; const params = [websiteId];
return rawQuery( return rawQuery(
`select `select

View File

@ -13,11 +13,11 @@ function relationalQuery(websites, start_at) {
return prisma.client.event.findMany({ return prisma.client.event.findMany({
where: { where: {
website: { website: {
website_id: { id: {
in: websites, in: websites,
}, },
}, },
created_at: { createdAt: {
gte: start_at, gte: start_at,
}, },
}, },

View File

@ -10,18 +10,18 @@ export async function saveEvent(...args) {
}); });
} }
async function relationalQuery(website_id, { session_id, url, event_name, event_data }) { async function relationalQuery(websiteId, { sessionId, url, eventName, eventData }) {
const data = { const data = {
website_id, websiteId,
session_id, sessionId,
url: url?.substring(0, URL_LENGTH), url: url?.substring(0, URL_LENGTH),
event_name: event_name?.substring(0, EVENT_NAME_LENGTH), eventName: eventName?.substring(0, EVENT_NAME_LENGTH),
}; };
if (event_data) { if (eventData) {
data.event_data = { data.eventData = {
create: { create: {
event_data: event_data, eventData: eventData,
}, },
}; };
} }
@ -32,18 +32,19 @@ async function relationalQuery(website_id, { session_id, url, event_name, event_
} }
async function clickhouseQuery( async function clickhouseQuery(
website_id, websiteId,
{ session: { country, ...sessionArgs }, event_uuid, url, event_name, event_data }, { session: { country, sessionUuid, ...sessionArgs }, eventUuid, url, eventName, eventData },
) { ) {
const { getDateFormat, sendMessage } = kafka; const { getDateFormat, sendMessage } = kafka;
const params = { const params = {
event_uuid, session_uuid: sessionUuid,
website_id, event_uuid: eventUuid,
website_id: websiteId,
created_at: getDateFormat(new Date()), created_at: getDateFormat(new Date()),
url: url?.substring(0, URL_LENGTH), url: url?.substring(0, URL_LENGTH),
event_name: event_name?.substring(0, EVENT_NAME_LENGTH), event_name: eventName?.substring(0, EVENT_NAME_LENGTH),
event_data: JSON.stringify(event_data), event_data: JSON.stringify(eventData),
...sessionArgs, ...sessionArgs,
country: country ? country : null, country: country ? country : null,
}; };

View File

@ -9,9 +9,9 @@ export async function getPageviewMetrics(...args) {
}); });
} }
async function relationalQuery(website_id, { startDate, endDate, column, table, filters = {} }) { async function relationalQuery(websiteId, { startDate, endDate, column, table, filters = {} }) {
const { rawQuery, parseFilters } = prisma; const { rawQuery, parseFilters } = prisma;
const params = [website_id, startDate, endDate]; const params = [websiteId, startDate, endDate];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table, table,
column, column,
@ -34,9 +34,9 @@ async function relationalQuery(website_id, { startDate, endDate, column, table,
); );
} }
async function clickhouseQuery(website_id, { startDate, endDate, column, filters = {} }) { async function clickhouseQuery(websiteId, { startDate, endDate, column, filters = {} }) {
const { rawQuery, parseFilters, getBetweenDates } = clickhouse; const { rawQuery, parseFilters, getBetweenDates } = clickhouse;
const params = [website_id]; const params = [websiteId];
const { pageviewQuery, sessionQuery, eventQuery } = parseFilters(column, filters, params); const { pageviewQuery, sessionQuery, eventQuery } = parseFilters(column, filters, params);
return rawQuery( return rawQuery(

View File

@ -8,9 +8,9 @@ export async function getPageviewParams(...args) {
}); });
} }
async function relationalQuery(website_id, start_at, end_at, column, table, filters = {}) { async function relationalQuery(websiteId, start_at, end_at, column, table, filters = {}) {
const { parseFilters, rawQuery } = prisma; const { parseFilters, rawQuery } = prisma;
const params = [website_id, start_at, end_at]; const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table, table,
column, column,

View File

@ -10,7 +10,7 @@ export async function getPageviewStats(...args) {
} }
async function relationalQuery( async function relationalQuery(
website_id, websiteId,
{ {
start_at, start_at,
end_at, end_at,
@ -22,7 +22,7 @@ async function relationalQuery(
}, },
) { ) {
const { getDateQuery, parseFilters, rawQuery } = prisma; const { getDateQuery, parseFilters, rawQuery } = prisma;
const params = [website_id, start_at, end_at]; const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview', 'pageview',
null, null,
@ -45,11 +45,11 @@ async function relationalQuery(
} }
async function clickhouseQuery( async function clickhouseQuery(
website_id, websiteId,
{ start_at, end_at, timezone = 'UTC', unit = 'day', count = '*', filters = {} }, { start_at, end_at, timezone = 'UTC', unit = 'day', count = '*', filters = {} },
) { ) {
const { parseFilters, rawQuery, getDateStringQuery, getDateQuery, getBetweenDates } = clickhouse; const { parseFilters, rawQuery, getDateStringQuery, getDateQuery, getBetweenDates } = clickhouse;
const params = [website_id]; const params = [websiteId];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params); const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
return rawQuery( return rawQuery(

View File

@ -13,11 +13,11 @@ async function relationalQuery(websites, start_at) {
return prisma.client.pageview.findMany({ return prisma.client.pageview.findMany({
where: { where: {
website: { website: {
website_id: { id: {
in: websites, in: websites,
}, },
}, },
created_at: { createdAt: {
gte: start_at, gte: start_at,
}, },
}, },

View File

@ -10,11 +10,11 @@ export async function savePageView(...args) {
}); });
} }
async function relationalQuery(website_id, { session: { session_id }, url, referrer }) { async function relationalQuery(websiteId, { session: { sessionId }, url, referrer }) {
return prisma.client.pageview.create({ return prisma.client.pageview.create({
data: { data: {
website_id, websiteId,
session_id, sessionId,
url: url?.substring(0, URL_LENGTH), url: url?.substring(0, URL_LENGTH),
referrer: referrer?.substring(0, URL_LENGTH), referrer: referrer?.substring(0, URL_LENGTH),
}, },
@ -22,12 +22,13 @@ async function relationalQuery(website_id, { session: { session_id }, url, refer
} }
async function clickhouseQuery( async function clickhouseQuery(
website_id, websiteId,
{ session: { country, ...sessionArgs }, url, referrer }, { session: { country, sessionUuid, ...sessionArgs }, url, referrer },
) { ) {
const { getDateFormat, sendMessage } = kafka; const { getDateFormat, sendMessage } = kafka;
const params = { const params = {
website_id: website_id, session_uuid: sessionUuid,
website_id: websiteId,
created_at: getDateFormat(new Date()), created_at: getDateFormat(new Date()),
url: url?.substring(0, URL_LENGTH), url: url?.substring(0, URL_LENGTH),
referrer: referrer?.substring(0, URL_LENGTH), referrer: referrer?.substring(0, URL_LENGTH),

View File

@ -10,16 +10,16 @@ export async function createSession(...args) {
}); });
} }
async function relationalQuery(website_id, data) { async function relationalQuery(websiteId, data) {
return prisma.client.session return prisma.client.session
.create({ .create({
data: { data: {
website_id, websiteId,
...data, ...data,
}, },
select: { select: {
session_id: true, sessionId: true,
session_uuid: true, sessionUuid: true,
hostname: true, hostname: true,
browser: true, browser: true,
os: true, os: true,
@ -31,7 +31,7 @@ async function relationalQuery(website_id, data) {
}) })
.then(async res => { .then(async res => {
if (redis.client && res) { if (redis.client && res) {
await redis.client.set(`session:${res.session_uuid}`, res.session_id); await redis.client.set(`session:${res.sessionUuid}`, res.id);
} }
return res; return res;
@ -39,14 +39,14 @@ async function relationalQuery(website_id, data) {
} }
async function clickhouseQuery( async function clickhouseQuery(
website_id, websiteId,
{ session_uuid, hostname, browser, os, screen, language, country, device }, { sessionUuid, hostname, browser, os, screen, language, country, device },
) { ) {
const { getDateFormat, sendMessage } = kafka; const { getDateFormat, sendMessage } = kafka;
const params = { const params = {
session_uuid, session_uuid: sessionUuid,
website_id, website_id: websiteId,
created_at: getDateFormat(new Date()), created_at: getDateFormat(new Date()),
hostname, hostname,
browser, browser,
@ -60,6 +60,6 @@ async function clickhouseQuery(
await sendMessage(params, 'event'); await sendMessage(params, 'event');
if (redis.client) { if (redis.client) {
await redis.client.set(`session:${session_uuid}`, 1); await redis.client.set(`session:${sessionUuid}`, 1);
} }
} }

View File

@ -10,25 +10,25 @@ export async function getSessionByUuid(...args) {
}); });
} }
async function relationalQuery(session_uuid) { async function relationalQuery(sessionUuid) {
return prisma.client.session return prisma.client.session
.findUnique({ .findUnique({
where: { where: {
session_uuid, sessionUuid,
}, },
}) })
.then(async res => { .then(async res => {
if (redis.client && res) { if (redis.client && res) {
await redis.client.set(`session:${res.session_uuid}`, res.session_id); await redis.client.set(`session:${res.sessionUuid}`, res.sessionId);
} }
return res; return res;
}); });
} }
async function clickhouseQuery(session_uuid) { async function clickhouseQuery(sessionUuid) {
const { rawQuery, findFirst } = clickhouse; const { rawQuery, findFirst } = clickhouse;
const params = [session_uuid]; const params = [sessionUuid];
return rawQuery( return rawQuery(
`select distinct `select distinct

View File

@ -9,9 +9,9 @@ export async function getSessionMetrics(...args) {
}); });
} }
async function relationalQuery(website_id, { startDate, endDate, field, filters = {} }) { async function relationalQuery(websiteId, { startDate, endDate, field, filters = {} }) {
const { parseFilters, rawQuery } = prisma; const { parseFilters, rawQuery } = prisma;
const params = [website_id, startDate, endDate]; const params = [websiteId, startDate, endDate];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(null, filters, params); const { pageviewQuery, sessionQuery, joinSession } = parseFilters(null, filters, params);
return rawQuery( return rawQuery(
@ -32,9 +32,9 @@ async function relationalQuery(website_id, { startDate, endDate, field, filters
); );
} }
async function clickhouseQuery(website_id, { startDate, endDate, field, filters = {} }) { async function clickhouseQuery(websiteId, { startDate, endDate, field, filters = {} }) {
const { parseFilters, getBetweenDates, rawQuery } = clickhouse; const { parseFilters, getBetweenDates, rawQuery } = clickhouse;
const params = [website_id]; const params = [websiteId];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params); const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
return rawQuery( return rawQuery(

View File

@ -15,13 +15,13 @@ async function relationalQuery(websites, start_at) {
...(websites && websites.length > 0 ...(websites && websites.length > 0
? { ? {
website: { website: {
website_id: { id: {
in: websites, in: websites,
}, },
}, },
} }
: {}), : {}),
created_at: { createdAt: {
gte: start_at, gte: start_at,
}, },
}, },

View File

@ -10,9 +10,9 @@ export async function getActiveVisitors(...args) {
}); });
} }
async function relationalQuery(website_id) { async function relationalQuery(websiteId) {
const date = subMinutes(new Date(), 5); const date = subMinutes(new Date(), 5);
const params = [website_id, date]; const params = [websiteId, date];
return prisma.rawQuery( return prisma.rawQuery(
`select count(distinct session_id) x `select count(distinct session_id) x
@ -23,9 +23,9 @@ async function relationalQuery(website_id) {
); );
} }
async function clickhouseQuery(website_id) { async function clickhouseQuery(websiteId) {
const { rawQuery, getDateFormat } = clickhouse; const { rawQuery, getDateFormat } = clickhouse;
const params = [website_id]; const params = [websiteId];
return rawQuery( return rawQuery(
`select count(distinct session_uuid) x `select count(distinct session_uuid) x

View File

@ -10,19 +10,19 @@ export async function getRealtimeData(websites, time) {
]); ]);
return { return {
pageviews: pageviews.map(({ view_id, ...props }) => ({ pageviews: pageviews.map(({ pageviewId, ...props }) => ({
__id: `p${view_id}`, __id: `p${pageviewId}`,
view_id, pageviewId,
...props, ...props,
})), })),
sessions: sessions.map(({ session_id, ...props }) => ({ sessions: sessions.map(({ sessionId, ...props }) => ({
__id: `s${session_id}`, __id: `s${sessionId}`,
session_id, sessionId,
...props, ...props,
})), })),
events: events.map(({ event_id, ...props }) => ({ events: events.map(({ eventId, ...props }) => ({
__id: `e${event_id}`, __id: `e${eventId}`,
event_id, eventId,
...props, ...props,
})), })),
timestamp: Date.now(), timestamp: Date.now(),

View File

@ -9,9 +9,9 @@ export async function getWebsiteStats(...args) {
}); });
} }
async function relationalQuery(website_id, { start_at, end_at, filters = {} }) { async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) {
const { getDateQuery, getTimestampInterval, parseFilters, rawQuery } = prisma; const { getDateQuery, getTimestampInterval, parseFilters, rawQuery } = prisma;
const params = [website_id, start_at, end_at]; const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters( const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview', 'pageview',
null, null,
@ -41,9 +41,9 @@ async function relationalQuery(website_id, { start_at, end_at, filters = {} }) {
); );
} }
async function clickhouseQuery(website_id, { start_at, end_at, filters = {} }) { async function clickhouseQuery(websiteId, { start_at, end_at, filters = {} }) {
const { rawQuery, getDateQuery, getBetweenDates, parseFilters } = clickhouse; const { rawQuery, getDateQuery, getBetweenDates, parseFilters } = clickhouse;
const params = [website_id]; const params = [websiteId];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params); const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
return rawQuery( return rawQuery(

View File

@ -92,24 +92,24 @@
.then(text => (cache = text)); .then(text => (cache = text));
}; };
const trackView = (url = currentUrl, referrer = currentRef, uuid = website) => const trackView = (url = currentUrl, referrer = currentRef, websiteUuid = website) =>
collect( collect(
'pageview', 'pageview',
assign(getPayload(), { assign(getPayload(), {
website: uuid, website: websiteUuid,
url, url,
referrer, referrer,
}), }),
); );
const trackEvent = (event_name, event_data, url = currentUrl, uuid = website) => const trackEvent = (eventName, eventData, url = currentUrl, websiteUuid = website) =>
collect( collect(
'event', 'event',
assign(getPayload(), { assign(getPayload(), {
website: uuid, website: websiteUuid,
url, url,
event_name, event_name: eventName,
event_data, event_data: eventData,
}), }),
); );