Merge branch 'dev' into feat/um-66-update-clickhouse-schema-uuid

This commit is contained in:
Brian Cao 2022-10-10 16:20:07 -07:00
commit ec6454aead
65 changed files with 436 additions and 441 deletions

View File

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

View File

@ -43,7 +43,7 @@ export default function ChangePasswordForm({ values, onSave, onClose }) {
const { user } = useUser();
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) {
onSave();

View File

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

View File

@ -26,7 +26,7 @@ export default function TrackingCodeForm({ values, onClose }) {
rows={3}
cols={60}
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
}${basePath}/${trackerScriptName ? `${trackerScriptName}.js` : 'umami.js'}"></script>`}
readOnly

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -21,11 +21,11 @@ function mergeData(state, data, time) {
const ids = state.map(({ __id }) => __id);
return state
.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) {
return data.filter(({ website_id }) => website_id === id);
return data.filter(({ websiteId }) => websiteId === id);
}
export default function RealtimeDashboard() {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -40,19 +40,19 @@ export async function allowQuery(req, skipToken) {
const { id } = req.query;
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 (token && token !== 'undefined' && !skipToken) {
return isValidToken(token, { website_id: website.website_id });
return isValidToken(token, { websiteId: website.id });
}
const authToken = await getAuthToken(req);
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 sessionUuids = sessions.map(a => {
return { key: `session:${a.session_uuid}`, value: 1 };
return { key: `session:${a.sessionUuid}`, value: 1 };
});
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);

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;
}
@ -33,21 +33,21 @@ export async function getSession(req) {
// Check if website exists
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
if (!websiteId) {
const website = await getWebsiteByUuid(website_uuid);
websiteId = website ? website.website_id : null;
const website = await getWebsiteByUuid(websiteUuid);
websiteId = website ? website.websiteId : null;
}
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 session_uuid = uuid(websiteId, hostname, ip, userAgent);
const sessionUuid = uuid(websiteId, hostname, ip, userAgent);
let sessionId = null;
let session = null;
@ -55,19 +55,19 @@ export async function getSession(req) {
if (!clickhouse.enabled) {
// Check if session exists
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
if (!sessionId) {
session = await getSessionByUuid(session_uuid);
sessionId = session ? session.session_id : null;
session = await getSessionByUuid(sessionUuid);
sessionId = session ? session.sessionId : null;
}
if (!sessionId) {
try {
session = await createSession(websiteId, website_uuid, {
session_uuid,
session = await createSession(websiteId, {
sessionUuid,
hostname,
browser,
os,
@ -84,8 +84,8 @@ export async function getSession(req) {
}
} else {
session = {
session_id: sessionId,
session_uuid,
sessionId,
sessionUuid,
hostname,
browser,
os,
@ -97,8 +97,7 @@ export async function getSession(req) {
}
return {
website_id: websiteId,
website_uuid: website_uuid,
websiteId: websiteId,
session,
};
}

View File

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

View File

@ -12,7 +12,7 @@ import {
export default async (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 { id } = req.query;
const userId = +id;

View File

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

View File

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

View File

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

View File

@ -8,10 +8,10 @@ export default async (req, res) => {
await useAuth(req, res);
if (req.method === 'GET') {
const { user_id } = req.auth;
const { userId } = req.auth;
const websites = await getUserWebsites(user_id);
const ids = websites.map(({ website_id }) => website_id);
const websites = await getUserWebsites(userId);
const ids = websites.map(({ id }) => id);
const token = createToken({ websites: ids }, secret());
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);
if (website) {
const websiteId = website.website_id;
const token = createToken({ website_id: websiteId }, secret());
const websiteId = website.websiteId;
const token = createToken({ websiteId: websiteId }, secret());
return ok(res, { websiteId, token });
}

View File

@ -27,7 +27,7 @@ export default async (req, res) => {
const events = await getEventMetrics(websiteId, website_uuid, startDate, endDate, tz, unit, {
url,
event_name,
eventName: event_name,
});
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 { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
@ -8,7 +8,7 @@ export default async (req, res) => {
const { id } = req.query;
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') {
await useCors(req, res);
@ -25,17 +25,19 @@ export default async (req, res) => {
if (req.method === 'POST') {
await useAuth(req, res);
const { is_admin: currentUserIsAdmin, user_id: currentUserId, account_uuid } = req.auth;
const { name, domain, owner, share_id } = req.body;
const { isAdmin: currentUserIsAdmin, userId: currentUserId, accountUuid } = req.auth;
const { name, domain, owner, enable_share_url } = req.body;
let account;
if (account_uuid) {
account = await getAccount({ account_uuid });
if (accountUuid) {
account = await getAccount({ accountUuid });
}
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);
}
@ -43,8 +45,8 @@ export default async (req, res) => {
{
name,
domain,
share_id: share_id || null,
user_id: account ? account.id : +owner,
shareId: shareId,
userId: account ? account.id : +owner,
},
where,
);

View File

@ -1,4 +1,4 @@
import { getWebsiteStats } from 'queries';
import { getWebsiteStats, getWebsiteById } from 'queries';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { useCors } from 'lib/middleware';
@ -11,10 +11,10 @@ export default async (req, 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 website_uuid = id;
const websiteId = +website_id;
let websiteUuid = (await getWebsiteById(websiteId)).websiteUuid;
const startDate = new Date(+start_at);
const endDate = new Date(+end_at);
@ -22,7 +22,7 @@ export default async (req, res) => {
const prevStartDate = new Date(+start_at - distance);
const prevEndDate = new Date(+end_at - distance);
const metrics = await getWebsiteStats(websiteId, website_uuid, {
const metrics = await getWebsiteStats(websiteUuid, {
start_at: startDate,
end_at: endDate,
filters: {
@ -34,7 +34,7 @@ export default async (req, res) => {
country,
},
});
const prevPeriod = await getWebsiteStats(websiteId, website_uuid, {
const prevPeriod = await getWebsiteStats(websiteUuid, {
start_at: prevStartDate,
end_at: prevEndDate,
filters: {

View File

@ -6,44 +6,41 @@ import { uuid } from 'lib/crypto';
export default async (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;
let account;
if (account_uuid) {
account = await getAccount({ account_uuid });
if (accountUuid) {
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 (userId && userId !== current_user_id && !is_admin) {
if (userId && userId !== currentUserId && !isAdmin) {
return unauthorized(res);
}
const websites =
is_admin && include_all
isAdmin && include_all
? await getAllWebsites()
: await getUserWebsites(userId || current_user_id);
: await getUserWebsites(userId || currentUserId);
return ok(res, websites);
}
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 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);
}
const website_uuid = uuid();
const share_id = enable_share_url ? getRandomChars(8) : null;
const website = await createWebsite(website_owner, { website_uuid, name, domain, share_id });
const websiteUuid = uuid();
const shareId = enable_share_url ? getRandomChars(8) : null;
const website = await createWebsite(website_owner, { websiteUuid, name, domain, shareId });
return ok(res, website);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,13 +1,13 @@
import prisma from 'lib/prisma';
import redis from 'lib/redis';
export async function createWebsite(user_id, data) {
export async function createWebsite(userId, data) {
return prisma.client.website
.create({
data: {
account: {
connect: {
user_id,
id: userId,
},
},
...data,
@ -15,7 +15,7 @@ export async function createWebsite(user_id, data) {
})
.then(async 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;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,16 +1,16 @@
import prisma from 'lib/prisma';
import redis from 'lib/redis';
export async function getWebsiteByUuid(website_uuid) {
export async function getWebsiteByUuid(websiteUuid) {
return prisma.client.website
.findUnique({
where: {
website_uuid,
websiteUuid,
},
})
.then(async 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;

View File

@ -1,20 +1,20 @@
import prisma from 'lib/prisma';
export async function resetWebsite(website_id) {
export async function resetWebsite(websiteId) {
const { client, transaction } = prisma;
return transaction([
client.pageview.deleteMany({
where: { session: { website: { website_id } } },
where: { session: { website: { id: websiteId } } },
}),
client.event_data.deleteMany({
where: { event: { session: { website: { website_id } } } },
client.eventData.deleteMany({
where: { event: { session: { website: { id: websiteId } } } },
}),
client.event.deleteMany({
where: { session: { website: { website_id } } },
where: { session: { website: { id: websiteId } } },
}),
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(
website_id,
websiteId,
start_at,
end_at,
timezone = 'utc',
@ -18,7 +18,7 @@ async function relationalQuery(
filters = {},
) {
const { rawQuery, getDateQuery, getFilterQuery } = prisma;
const params = [website_id, start_at, end_at];
const params = [websiteId, start_at, end_at];
return rawQuery(
`select
@ -36,6 +36,7 @@ async function relationalQuery(
}
async function clickhouseQuery(
websiteId,
website_uuid,
start_at,
end_at,
@ -44,7 +45,7 @@ async function clickhouseQuery(
filters = {},
) {
const { rawQuery, getDateQuery, getBetweenDates, getFilterQuery } = clickhouse;
const params = [website_uuid];
const params = [websiteId];
return rawQuery(
`select

View File

@ -13,11 +13,11 @@ function relationalQuery(websites, start_at) {
return prisma.client.event.findMany({
where: {
website: {
website_id: {
id: {
in: websites,
},
},
created_at: {
createdAt: {
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 = {
website_id,
session_id,
websiteId,
sessionId,
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) {
data.event_data = {
if (eventData) {
data.eventData = {
create: {
event_data: event_data,
eventData: eventData,
},
};
}
@ -32,18 +32,21 @@ async function relationalQuery(website_id, { session_id, url, event_name, event_
}
async function clickhouseQuery(
websiteId,
{ session: { country, sessionUuid, ...sessionArgs }, eventUuid, url, eventName, eventData },
website_uuid,
{ session: { country, ...sessionArgs }, event_uuid, url, event_name, event_data },
) {
const { getDateFormat, sendMessage } = kafka;
const params = {
event_uuid,
session_uuid: sessionUuid,
event_uuid: eventUuid,
website_id: websiteId,
website_uuid,
created_at: getDateFormat(new Date()),
url: url?.substring(0, URL_LENGTH),
event_name: event_name?.substring(0, EVENT_NAME_LENGTH),
event_data: JSON.stringify(event_data),
event_name: eventName?.substring(0, EVENT_NAME_LENGTH),
event_data: JSON.stringify(eventData),
...sessionArgs,
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 params = [website_id, startDate, endDate];
const params = [websiteId, startDate, endDate];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table,
column,
@ -34,9 +34,9 @@ async function relationalQuery(website_id, { startDate, endDate, column, table,
);
}
async function clickhouseQuery(website_uuid, { startDate, endDate, column, filters = {} }) {
async function clickhouseQuery(websiteId, { startDate, endDate, column, filters = {} }) {
const { rawQuery, parseFilters, getBetweenDates } = clickhouse;
const params = [website_uuid];
const params = [websiteId];
const { pageviewQuery, sessionQuery, eventQuery } = parseFilters(column, filters, params);
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 params = [website_id, start_at, end_at];
const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, eventQuery, joinSession } = parseFilters(
table,
column,

View File

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

View File

@ -13,11 +13,11 @@ async function relationalQuery(websites, start_at) {
return prisma.client.pageview.findMany({
where: {
website: {
website_id: {
id: {
in: websites,
},
},
created_at: {
createdAt: {
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({
data: {
website_id,
session_id,
websiteId,
sessionId,
url: url?.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(
website_uuid,
{ session: { country, ...sessionArgs }, url, referrer },
websiteId,
{ session: { country, sessionUuid, ...sessionArgs }, url, referrer },
) {
const { getDateFormat, sendMessage } = kafka;
const params = {
website_id: website_uuid,
session_uuid: sessionUuid,
website_id: websiteId,
created_at: getDateFormat(new Date()),
url: url?.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
.create({
data: {
website_id,
websiteId,
...data,
},
select: {
session_id: true,
session_uuid: true,
sessionId: true,
sessionUuid: true,
hostname: true,
browser: true,
os: true,
@ -31,7 +31,7 @@ async function relationalQuery(website_id, data) {
})
.then(async 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;
@ -39,14 +39,14 @@ async function relationalQuery(website_id, data) {
}
async function clickhouseQuery(
website_uuid,
{ session_uuid, hostname, browser, os, screen, language, country, device },
websiteId,
{ sessionUuid, hostname, browser, os, screen, language, country, device },
) {
const { getDateFormat, sendMessage } = kafka;
const params = {
session_uuid,
website_uuid,
session_uuid: sessionUuid,
website_id: websiteId,
created_at: getDateFormat(new Date()),
hostname,
browser,
@ -60,6 +60,6 @@ async function clickhouseQuery(
await sendMessage(params, 'event');
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
.findUnique({
where: {
session_uuid,
sessionUuid,
},
})
.then(async 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;
});
}
async function clickhouseQuery(session_uuid) {
async function clickhouseQuery(sessionUuid) {
const { rawQuery, findFirst } = clickhouse;
const params = [session_uuid];
const params = [sessionUuid];
return rawQuery(
`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 params = [website_id, startDate, endDate];
const params = [websiteId, startDate, endDate];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(null, filters, params);
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 params = [website_id];
const params = [websiteId];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
return rawQuery(

View File

@ -15,13 +15,13 @@ async function relationalQuery(websites, start_at) {
...(websites && websites.length > 0
? {
website: {
website_id: {
id: {
in: websites,
},
},
}
: {}),
created_at: {
createdAt: {
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 params = [website_id, date];
const params = [websiteId, date];
return prisma.rawQuery(
`select count(distinct session_id) x
@ -23,9 +23,9 @@ async function relationalQuery(website_id) {
);
}
async function clickhouseQuery(website_uuid) {
async function clickhouseQuery(websiteId) {
const { rawQuery, getDateFormat } = clickhouse;
const params = [website_uuid];
const params = [websiteId];
return rawQuery(
`select count(distinct session_id) x

View File

@ -10,19 +10,19 @@ export async function getRealtimeData(websites, time) {
]);
return {
pageviews: pageviews.map(({ view_id, ...props }) => ({
__id: `p${view_id}`,
view_id,
pageviews: pageviews.map(({ pageviewId, ...props }) => ({
__id: `p${pageviewId}`,
pageviewId,
...props,
})),
sessions: sessions.map(({ session_id, ...props }) => ({
__id: `s${session_id}`,
session_id,
sessions: sessions.map(({ sessionId, ...props }) => ({
__id: `s${sessionId}`,
sessionId,
...props,
})),
events: events.map(({ event_id, ...props }) => ({
__id: `e${event_id}`,
event_id,
events: events.map(({ eventId, ...props }) => ({
__id: `e${eventId}`,
eventId,
...props,
})),
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 params = [website_id, start_at, end_at];
const params = [websiteId, start_at, end_at];
const { pageviewQuery, sessionQuery, joinSession } = parseFilters(
'pageview',
null,
@ -41,9 +41,9 @@ async function relationalQuery(website_id, { start_at, end_at, filters = {} }) {
);
}
async function clickhouseQuery(website_uuid, { start_at, end_at, filters = {} }) {
async function clickhouseQuery(websiteId, { start_at, end_at, filters = {} }) {
const { rawQuery, getDateQuery, getBetweenDates, parseFilters } = clickhouse;
const params = [website_uuid];
const params = [websiteId];
const { pageviewQuery, sessionQuery } = parseFilters(null, filters, params);
return rawQuery(

View File

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