2022-10-11 01:20:07 +02:00
|
|
|
import { getWebsiteStats, getWebsiteById } from 'queries';
|
2022-08-29 05:20:54 +02:00
|
|
|
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
|
2020-10-09 00:02:48 +02:00
|
|
|
import { allowQuery } from 'lib/auth';
|
2022-04-04 09:33:20 +02:00
|
|
|
import { useCors } from 'lib/middleware';
|
2020-10-09 00:02:48 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
if (req.method === 'GET') {
|
2022-04-04 09:33:20 +02:00
|
|
|
await useCors(req, res);
|
|
|
|
|
2020-10-09 00:02:48 +02:00
|
|
|
if (!(await allowQuery(req))) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2022-10-10 22:42:18 +02:00
|
|
|
const { website_id, start_at, end_at, url, referrer, os, browser, device, country } = req.query;
|
2020-10-09 00:02:48 +02:00
|
|
|
|
2022-10-10 22:42:18 +02:00
|
|
|
const websiteId = +website_id;
|
2022-10-11 01:20:07 +02:00
|
|
|
let websiteUuid = (await getWebsiteById(websiteId)).websiteUuid;
|
2020-10-09 00:02:48 +02:00
|
|
|
const startDate = new Date(+start_at);
|
|
|
|
const endDate = new Date(+end_at);
|
|
|
|
|
2021-08-13 01:01:51 +02:00
|
|
|
const distance = end_at - start_at;
|
|
|
|
const prevStartDate = new Date(+start_at - distance);
|
|
|
|
const prevEndDate = new Date(+end_at - distance);
|
|
|
|
|
2022-10-11 01:20:07 +02:00
|
|
|
const metrics = await getWebsiteStats(websiteUuid, {
|
2022-09-24 07:43:51 +02:00
|
|
|
start_at: startDate,
|
|
|
|
end_at: endDate,
|
|
|
|
filters: {
|
|
|
|
url,
|
|
|
|
referrer,
|
|
|
|
os,
|
|
|
|
browser,
|
|
|
|
device,
|
|
|
|
country,
|
|
|
|
},
|
2022-04-10 12:51:43 +02:00
|
|
|
});
|
2022-10-11 01:20:07 +02:00
|
|
|
const prevPeriod = await getWebsiteStats(websiteUuid, {
|
2022-09-24 07:43:51 +02:00
|
|
|
start_at: prevStartDate,
|
|
|
|
end_at: prevEndDate,
|
|
|
|
filters: {
|
|
|
|
url,
|
|
|
|
referrer,
|
|
|
|
os,
|
|
|
|
browser,
|
|
|
|
device,
|
|
|
|
country,
|
|
|
|
},
|
2022-03-20 22:10:41 +01:00
|
|
|
});
|
2020-10-09 00:02:48 +02:00
|
|
|
|
|
|
|
const stats = Object.keys(metrics[0]).reduce((obj, key) => {
|
2021-08-13 01:01:51 +02:00
|
|
|
obj[key] = {
|
|
|
|
value: Number(metrics[0][key]) || 0,
|
2022-07-21 10:35:14 +02:00
|
|
|
change: Number(metrics[0][key]) - Number(prevPeriod[0][key]) || 0,
|
2021-08-13 01:01:51 +02:00
|
|
|
};
|
2020-10-09 00:02:48 +02:00
|
|
|
return obj;
|
|
|
|
}, {});
|
|
|
|
|
|
|
|
return ok(res, stats);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|