Merge remote-tracking branch 'origin/dev' into dev

# Conflicts:
#	src/components/common/Pager.module.css
#	src/lib/constants.ts
#	src/lib/yup.ts
#	src/pages/api/teams/[id]/users/index.ts
#	src/pages/api/websites/[id]/reports.ts
This commit is contained in:
Mike Cao 2023-09-26 23:27:55 -07:00
commit 40cfcd41e9
19 changed files with 135 additions and 92 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "umami", "name": "umami",
"version": "2.6.2", "version": "2.7.0",
"description": "A simple, fast, privacy-focused alternative to Google Analytics.", "description": "A simple, fast, privacy-focused alternative to Google Analytics.",
"author": "Mike Cao <mike@mikecao.com>", "author": "Mike Cao <mike@mikecao.com>",
"license": "MIT", "license": "MIT",

View File

@ -12,11 +12,10 @@ import { startOfMonth, endOfMonth } from 'date-fns';
import Icons from 'components/icons'; import Icons from 'components/icons';
import { useLocale } from 'components/hooks'; import { useLocale } from 'components/hooks';
import { formatDate } from 'lib/date'; import { formatDate } from 'lib/date';
import { getDateLocale } from 'lib/lang';
import styles from './MonthSelect.module.css'; import styles from './MonthSelect.module.css';
export function MonthSelect({ date = new Date(), onChange }) { export function MonthSelect({ date = new Date(), onChange }) {
const { locale } = useLocale(); const { locale, dateLocale } = useLocale();
const month = formatDate(date, 'MMMM', locale); const month = formatDate(date, 'MMMM', locale);
const year = date.getFullYear(); const year = date.getFullYear();
const ref = useRef(); const ref = useRef();
@ -40,7 +39,7 @@ export function MonthSelect({ date = new Date(), onChange }) {
{close => ( {close => (
<CalendarMonthSelect <CalendarMonthSelect
date={date} date={date}
locale={getDateLocale(locale)} locale={dateLocale}
onSelect={handleChange.bind(null, close)} onSelect={handleChange.bind(null, close)}
/> />
)} )}
@ -57,7 +56,7 @@ export function MonthSelect({ date = new Date(), onChange }) {
{close => ( {close => (
<CalendarYearSelect <CalendarYearSelect
date={date} date={date}
locale={getDateLocale(locale)} locale={dateLocale}
onSelect={handleChange.bind(null, close)} onSelect={handleChange.bind(null, close)}
/> />
)} )}

View File

@ -4,4 +4,5 @@
flex-direction: column; flex-direction: column;
background: var(--base50); background: var(--base50);
position: relative; position: relative;
height: 100%;
} }

View File

@ -1,8 +1,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { Button, ButtonGroup, Calendar } from 'react-basics'; import { Button, ButtonGroup, Calendar } from 'react-basics';
import { isAfter, isBefore, isSameDay } from 'date-fns'; import { isAfter, isBefore, isSameDay, startOfDay, endOfDay } from 'date-fns';
import useLocale from 'components/hooks/useLocale'; import useLocale from 'components/hooks/useLocale';
import { getDateLocale } from 'lib/lang';
import { FILTER_DAY, FILTER_RANGE } from 'lib/constants'; import { FILTER_DAY, FILTER_RANGE } from 'lib/constants';
import useMessages from 'components/hooks/useMessages'; import useMessages from 'components/hooks/useMessages';
import styles from './DatePickerForm.module.css'; import styles from './DatePickerForm.module.css';
@ -21,7 +20,7 @@ export function DatePickerForm({
const [singleDate, setSingleDate] = useState(defaultStartDate); const [singleDate, setSingleDate] = useState(defaultStartDate);
const [startDate, setStartDate] = useState(defaultStartDate); const [startDate, setStartDate] = useState(defaultStartDate);
const [endDate, setEndDate] = useState(defaultEndDate); const [endDate, setEndDate] = useState(defaultEndDate);
const { locale } = useLocale(); const { dateLocale } = useLocale();
const { formatMessage, labels } = useMessages(); const { formatMessage, labels } = useMessages();
const disabled = const disabled =
@ -31,9 +30,9 @@ export function DatePickerForm({
const handleSave = () => { const handleSave = () => {
if (selected === FILTER_DAY) { if (selected === FILTER_DAY) {
onChange(`range:${singleDate.getTime()}:${singleDate.getTime()}`); onChange(`range:${startOfDay(singleDate).getTime()}:${endOfDay(singleDate).getTime()}`);
} else { } else {
onChange(`range:${startDate.getTime()}:${endDate.getTime()}`); onChange(`range:${startOfDay(startDate).getTime()}:${endOfDay(endDate).getTime()}`);
} }
}; };
@ -51,6 +50,7 @@ export function DatePickerForm({
date={singleDate} date={singleDate}
minDate={minDate} minDate={minDate}
maxDate={maxDate} maxDate={maxDate}
locale={dateLocale}
onChange={setSingleDate} onChange={setSingleDate}
/> />
)} )}
@ -60,14 +60,14 @@ export function DatePickerForm({
date={startDate} date={startDate}
minDate={minDate} minDate={minDate}
maxDate={endDate} maxDate={endDate}
locale={getDateLocale(locale)} locale={dateLocale}
onChange={setStartDate} onChange={setStartDate}
/> />
<Calendar <Calendar
date={endDate} date={endDate}
minDate={startDate} minDate={startDate}
maxDate={maxDate} maxDate={maxDate}
locale={getDateLocale(locale)} locale={dateLocale}
onChange={setEndDate} onChange={setEndDate}
/> />
</> </>

View File

@ -30,7 +30,7 @@ export const FILTER_DAY = 'filter-day';
export const FILTER_RANGE = 'filter-range'; export const FILTER_RANGE = 'filter-range';
export const FILTER_REFERRERS = 'filter-referrers'; export const FILTER_REFERRERS = 'filter-referrers';
export const FILTER_PAGES = 'filter-pages'; export const FILTER_PAGES = 'filter-pages';
export const UNIT_TYPES = ['year', 'month', 'hour', 'day'];
export const EVENT_COLUMNS = ['url', 'referrer', 'title', 'query', 'event']; export const EVENT_COLUMNS = ['url', 'referrer', 'title', 'query', 'event'];
export const SESSION_COLUMNS = [ export const SESSION_COLUMNS = [

View File

@ -78,7 +78,9 @@ export function parseDateRange(value, locale = 'en-US') {
const endDate = new Date(+endTime); const endDate = new Date(+endTime);
return { return {
...getDateRangeValues(startDate, endDate), startDate,
endDate,
unit: getMinimumUnit(startDate, endDate),
value, value,
}; };
} }
@ -255,14 +257,6 @@ export function getMinimumUnit(startDate, endDate) {
return 'year'; return 'year';
} }
export function getDateRangeValues(startDate, endDate) {
return {
startDate: startOfDay(startDate),
endDate: endOfDay(endDate),
unit: getMinimumUnit(startDate, endDate),
};
}
export function getDateFromString(str) { export function getDateFromString(str) {
const [ymd, hms] = str.split(' '); const [ymd, hms] = str.split(' ');
const [year, month, day] = ymd.split('-'); const [year, month, day] = ymd.split('-');

15
src/lib/yup.ts Normal file
View File

@ -0,0 +1,15 @@
import moment from 'moment';
import * as yup from 'yup';
import { UNIT_TYPES } from './constants';
export const TimezoneTest = yup.string().test(
'timezone',
() => `Invalid timezone`,
value => moment.tz.zone(value) !== null,
);
export const UnitTypeTest = yup.string().test(
'unit',
() => `Invalid unit`,
value => UNIT_TYPES.includes(value),
);

View File

@ -1,6 +1,7 @@
import { canViewWebsite } from 'lib/auth'; import { canViewWebsite } from 'lib/auth';
import { useAuth, useCors, useValidate } from 'lib/middleware'; import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types'; import { NextApiRequestQueryBody } from 'lib/types';
import { TimezoneTest } from 'lib/yup';
import { NextApiResponse } from 'next'; import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getRetention } from 'queries'; import { getRetention } from 'queries';
@ -8,7 +9,7 @@ import * as yup from 'yup';
export interface RetentionRequestBody { export interface RetentionRequestBody {
websiteId: string; websiteId: string;
dateRange: { startDate: string; endDate: string }; dateRange: { startDate: string; endDate: string; timezone: string };
} }
const schema = { const schema = {
@ -19,6 +20,7 @@ const schema = {
.shape({ .shape({
startDate: yup.date().required(), startDate: yup.date().required(),
endDate: yup.date().required(), endDate: yup.date().required(),
timezone: TimezoneTest,
}) })
.required(), .required(),
}), }),
@ -37,7 +39,7 @@ export default async (
if (req.method === 'POST') { if (req.method === 'POST') {
const { const {
websiteId, websiteId,
dateRange: { startDate, endDate }, dateRange: { startDate, endDate, timezone },
} = req.body; } = req.body;
if (!(await canViewWebsite(req.auth, websiteId))) { if (!(await canViewWebsite(req.auth, websiteId))) {
@ -47,6 +49,7 @@ export default async (
const data = await getRetention(websiteId, { const data = await getRetention(websiteId, {
startDate: new Date(startDate), startDate: new Date(startDate),
endDate: new Date(endDate), endDate: new Date(endDate),
timezone,
}); });
return ok(res, data); return ok(res, data);

View File

@ -5,6 +5,7 @@ import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { deleteTeamUser } from 'queries'; import { deleteTeamUser } from 'queries';
import * as yup from 'yup'; import * as yup from 'yup';
export interface TeamUserRequestQuery { export interface TeamUserRequestQuery {
id: string; id: string;
userId: string; userId: string;

View File

@ -1,5 +1,6 @@
import * as yup from 'yup';
import { canViewTeam } from 'lib/auth'; import { canViewTeam } from 'lib/auth';
import { useAuth } from 'lib/middleware'; import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter } from 'lib/types'; import { NextApiRequestQueryBody, SearchFilter } from 'lib/types';
import { NextApiResponse } from 'next'; import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized } from 'next-basics';
@ -9,16 +10,19 @@ export interface TeamUserRequestQuery extends SearchFilter {
id: string; id: string;
} }
export interface TeamUserRequestBody { const schema = {
email: string; GET: yup.object().shape({
roleId: string; id: yup.string().uuid().required(),
} }),
};
export default async ( export default async (
req: NextApiRequestQueryBody<TeamUserRequestQuery, TeamUserRequestBody>, req: NextApiRequestQueryBody<TeamUserRequestQuery, any>,
res: NextApiResponse, res: NextApiResponse,
) => { ) => {
await useAuth(req, res); await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
const { id: teamId } = req.query; const { id: teamId } = req.query;

View File

@ -1,32 +1,29 @@
import { WebsiteMetric, NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite } from 'lib/auth'; import { canViewWebsite } from 'lib/auth';
import { useAuth, useCors, useValidate } from 'lib/middleware'; import { useAuth, useCors, useValidate } from 'lib/middleware';
import moment from 'moment-timezone';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventMetrics } from 'queries';
import { parseDateRangeQuery } from 'lib/query'; import { parseDateRangeQuery } from 'lib/query';
import { NextApiRequestQueryBody, WebsiteMetric } from 'lib/types';
const unitTypes = ['year', 'month', 'hour', 'day']; import { TimezoneTest, UnitTypeTest } from 'lib/yup';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventMetrics } from 'queries';
import * as yup from 'yup';
export interface WebsiteEventsRequestQuery { export interface WebsiteEventsRequestQuery {
id: string; id: string;
startAt: string; startAt: string;
endAt: string; endAt: string;
unit: string; unit?: string;
timezone: string; timezone?: string;
url: string; url: string;
} }
import * as yup from 'yup';
const schema = { const schema = {
GET: yup.object().shape({ GET: yup.object().shape({
id: yup.string().uuid().required(), id: yup.string().uuid().required(),
startAt: yup.number().integer().required(), startAt: yup.number().integer().required(),
endAt: yup.number().integer().moreThan(yup.ref('startAt')).required(), endAt: yup.number().integer().moreThan(yup.ref('startAt')).required(),
unit: yup.string().required(), unit: UnitTypeTest,
timezone: yup.string().required(), timezone: TimezoneTest,
url: yup.string(), url: yup.string(),
}), }),
}; };
@ -49,10 +46,6 @@ export default async (
return unauthorized(res); return unauthorized(res);
} }
if (!moment.tz.zone(timezone) || !unitTypes.includes(unit)) {
return badRequest(res);
}
const events = await getEventMetrics(websiteId, { const events = await getEventMetrics(websiteId, {
startDate, startDate,
endDate, endDate,

View File

@ -22,6 +22,12 @@ const schema = {
GET: yup.object().shape({ GET: yup.object().shape({
id: yup.string().uuid().required(), id: yup.string().uuid().required(),
}), }),
POST: yup.object().shape({
id: yup.string().uuid().required(),
name: yup.string().required(),
domain: yup.string().required(),
shareId: yup.string().matches(SHARE_ID_REGEX, { excludeEmptyString: true }),
}),
}; };
export default async ( export default async (
@ -55,10 +61,6 @@ export default async (
let website; let website;
if (shareId && !shareId.match(SHARE_ID_REGEX)) {
return serverError(res, 'Invalid share ID.');
}
try { try {
website = await updateWebsite(websiteId, { name, domain, shareId }); website = await updateWebsite(websiteId, { name, domain, shareId });
} catch (e: any) { } catch (e: any) {

View File

@ -33,6 +33,18 @@ const schema = {
type: yup.string().required(), type: yup.string().required(),
startAt: yup.number().required(), startAt: yup.number().required(),
endAt: yup.number().required(), endAt: yup.number().required(),
url: yup.string(),
referrer: yup.string(),
title: yup.string(),
query: yup.string(),
os: yup.string(),
browser: yup.string(),
device: yup.string(),
country: yup.string(),
region: yup.string(),
city: yup.string(),
language: yup.string(),
event: yup.string(),
}), }),
}; };

View File

@ -1,18 +1,17 @@
import moment from 'moment-timezone';
import { NextApiResponse } from 'next';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { NextApiRequestQueryBody, WebsitePageviews } from 'lib/types';
import { canViewWebsite } from 'lib/auth'; import { canViewWebsite } from 'lib/auth';
import { useAuth, useCors, useValidate } from 'lib/middleware'; import { useAuth, useCors, useValidate } from 'lib/middleware';
import { getPageviewStats, getSessionStats } from 'queries';
import { parseDateRangeQuery } from 'lib/query'; import { parseDateRangeQuery } from 'lib/query';
import { NextApiRequestQueryBody, WebsitePageviews } from 'lib/types';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getPageviewStats, getSessionStats } from 'queries';
export interface WebsitePageviewRequestQuery { export interface WebsitePageviewRequestQuery {
id: string; id: string;
startAt: number; startAt: number;
endAt: number; endAt: number;
unit: string; unit?: string;
timezone: string; timezone?: string;
url?: string; url?: string;
referrer?: string; referrer?: string;
title?: string; title?: string;
@ -24,10 +23,24 @@ export interface WebsitePageviewRequestQuery {
city?: string; city?: string;
} }
import { TimezoneTest, UnitTypeTest } from 'lib/yup';
import * as yup from 'yup'; import * as yup from 'yup';
const schema = { const schema = {
GET: yup.object().shape({ GET: yup.object().shape({
id: yup.string().uuid().required(), id: yup.string().uuid().required(),
startAt: yup.number().required(),
endAt: yup.number().required(),
unit: UnitTypeTest,
timezone: TimezoneTest,
url: yup.string(),
referrer: yup.string(),
title: yup.string(),
os: yup.string(),
browser: yup.string(),
device: yup.string(),
country: yup.string(),
region: yup.string(),
city: yup.string(),
}), }),
}; };
@ -62,10 +75,6 @@ export default async (
const { startDate, endDate, unit } = await parseDateRangeQuery(req); const { startDate, endDate, unit } = await parseDateRangeQuery(req);
if (!moment.tz.zone(timezone)) {
return badRequest(res);
}
const filters = { const filters = {
startDate, startDate,
endDate, endDate,

View File

@ -4,14 +4,14 @@ import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiResponse } from 'next'; import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { resetWebsite } from 'queries'; import { resetWebsite } from 'queries';
import * as yup from 'yup';
export interface WebsiteResetRequestQuery { export interface WebsiteResetRequestQuery {
id: string; id: string;
} }
import * as yup from 'yup';
const schema = { const schema = {
GET: yup.object().shape({ POST: yup.object().shape({
id: yup.string().uuid().required(), id: yup.string().uuid().required(),
}), }),
}; };
@ -22,7 +22,6 @@ export default async (
) => { ) => {
await useCors(req, res); await useCors(req, res);
await useAuth(req, res); await useAuth(req, res);
req.yup = schema; req.yup = schema;
await useValidate(req, res); await useValidate(req, res);

View File

@ -11,23 +11,36 @@ export interface WebsiteStatsRequestQuery {
id: string; id: string;
startAt: number; startAt: number;
endAt: number; endAt: number;
url: string; url?: string;
referrer: string; referrer?: string;
title: string; title?: string;
query: string; query?: string;
event: string; event?: string;
os: string; os?: string;
browser: string; browser?: string;
device: string; device?: string;
country: string; country?: string;
region: string; region?: string;
city: string; city?: string;
} }
import * as yup from 'yup'; import * as yup from 'yup';
const schema = { const schema = {
GET: yup.object().shape({ GET: yup.object().shape({
id: yup.string().uuid().required(), id: yup.string().uuid().required(),
startAt: yup.number().required(),
endAt: yup.number().required(),
url: yup.string(),
referrer: yup.string(),
title: yup.string(),
query: yup.string(),
event: yup.string(),
os: yup.string(),
browser: yup.string(),
device: yup.string(),
country: yup.string(),
region: yup.string(),
city: yup.string(),
}), }),
}; };

View File

@ -1,6 +1,6 @@
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import cache from 'lib/cache'; import cache from 'lib/cache';
import { ROLES, USER_FILTER_TYPES } from 'lib/constants'; import { ROLES } from 'lib/constants';
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
import { FilterResult, Role, User, UserSearchFilter } from 'lib/types'; import { FilterResult, Role, User, UserSearchFilter } from 'lib/types';
import { getRandomChars } from 'next-basics'; import { getRandomChars } from 'next-basics';
@ -37,10 +37,10 @@ export async function getUserByUsername(username: string, options: GetUserOption
} }
export async function getUsers( export async function getUsers(
searchFilter: UserSearchFilter, params: UserSearchFilter,
options?: { include?: Prisma.UserInclude }, options?: { include?: Prisma.UserInclude },
): Promise<FilterResult<User[]>> { ): Promise<FilterResult<User[]>> {
const { teamId, filter, filterType = USER_FILTER_TYPES.all } = searchFilter; const { teamId, query } = params;
const mode = prisma.getSearchMode(); const mode = prisma.getSearchMode();
const where: Prisma.UserWhereInput = { const where: Prisma.UserWhereInput = {
@ -51,17 +51,14 @@ export async function getUsers(
}, },
}, },
}), }),
...(filter && { ...(query && {
AND: { AND: {
OR: [ OR: [
{ {
...((filterType === USER_FILTER_TYPES.all ||
filterType === USER_FILTER_TYPES.username) && {
username: { username: {
startsWith: filter, contains: query,
...mode, ...mode,
}, },
}),
}, },
], ],
}, },
@ -70,7 +67,7 @@ export async function getUsers(
const [pageFilters, getParameters] = prisma.getPageFilters({ const [pageFilters, getParameters] = prisma.getPageFilters({
orderBy: 'username', orderBy: 'username',
...searchFilter, ...params,
}); });
const users = await prisma.client.user const users = await prisma.client.user

View File

@ -8,7 +8,7 @@ export async function getRetention(
filters: { filters: {
startDate: Date; startDate: Date;
endDate: Date; endDate: Date;
timezone: string; timezone?: string;
}, },
] ]
) { ) {
@ -23,7 +23,7 @@ async function relationalQuery(
filters: { filters: {
startDate: Date; startDate: Date;
endDate: Date; endDate: Date;
timezone: string; timezone?: string;
}, },
): Promise< ): Promise<
{ {
@ -103,7 +103,7 @@ async function clickhouseQuery(
filters: { filters: {
startDate: Date; startDate: Date;
endDate: Date; endDate: Date;
timezone: string; timezone?: string;
}, },
): Promise< ): Promise<
{ {

View File

@ -187,7 +187,8 @@
headers, headers,
}) })
.then(res => res.text()) .then(res => res.text())
.then(text => (cache = text)); .then(text => (cache = text))
.catch(() => {}); // no-op, gulp error
}; };
const track = (obj, data) => { const track = (obj, data) => {