Merge branch 'dev'

This commit is contained in:
Emily
2024-06-24 14:51:49 +02:00
5 changed files with 90 additions and 27 deletions

View File

@@ -28,18 +28,21 @@ const props = defineProps<{
</div> </div>
<div class="poppins text-text-sub text-[.9rem] 2xl:text-base"> {{ text }} </div> <div class="poppins text-text-sub text-[.9rem] 2xl:text-base"> {{ text }} </div>
</div> </div>
<div v-if="trend" class="flex items-center gap-3 rounded-xl px-2 py-1" <div v-if="trend" class="flex flex-col items-center gap-1">
:style="`background-color: ${props.color}33`"> <div class="flex items-center gap-3 rounded-xl px-2 py-1" :style="`background-color: ${props.color}33`">
<i :class="trend > 0 ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down'" class="far text-[.9rem] 2xl:text-[1rem]" <i :class="trend > 0 ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down'"
:style="`color: ${props.color}`"></i> class="far text-[.9rem] 2xl:text-[1rem]" :style="`color: ${props.color}`"></i>
<div :style="`color: ${props.color}`" class="font-semibold text-[.75rem] 2xl:text-[.875rem]"> <div :style="`color: ${props.color}`" class="font-semibold text-[.75rem] 2xl:text-[.875rem]">
{{ trend.toFixed(0) }} % {{ trend.toFixed(0) }} %
</div> </div>
</div> </div>
<div class="poppins text-text-sub text-[.7rem]"> Daily variation </div>
</div>
</div> </div>
<div class="absolute bottom-0 left-0 w-full h-[50%] flex items-end" v-if="(props.data?.length || 0) > 0"> <div class="absolute bottom-0 left-0 w-full h-[50%] flex items-end" v-if="(props.data?.length || 0) > 0">
<DashboardEmbedChartCard v-if="ready" :data="props.data || []" :labels="props.labels || []" :color="props.color"> <DashboardEmbedChartCard v-if="ready" :data="props.data || []" :labels="props.labels || []"
:color="props.color">
</DashboardEmbedChartCard> </DashboardEmbedChartCard>
</div> </div>
</Card> </Card>

View File

@@ -1,6 +1,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { MetricsTimeline } from '~/server/api/metrics/[project_id]/timeline/generic'; import type { MetricsTimeline } from '~/server/api/metrics/[project_id]/timeline/generic';
import DateService from '@services/DateService';
const { data: metricsInfo } = useMetricsData(); const { data: metricsInfo } = useMetricsData();
@@ -63,11 +63,18 @@ const sessionsData = reactive<Data>({ data: [], labels: [], trend: 0, ready: fal
const sessionsDurationData = reactive<Data>({ data: [], labels: [], trend: 0, ready: false }); const sessionsDurationData = reactive<Data>({ data: [], labels: [], trend: 0, ready: false });
async function loadData(timelineEndpointName: string, target: Data) { async function loadData(timelineEndpointName: string, target: Data) {
const response = await useTimelineData(timelineEndpointName, 'day');
const response = await useTimeline(timelineEndpointName as any, 'day');
if (!response) return; if (!response) return;
target.data = response.data; target.data = response.map(e => e.count);
target.labels = response.labels; target.labels = response.map(e => DateService.getChartLabelFromISO(e._id, navigator.language, 'day'));
target.trend = response.trend;
const pool = [...response.map(e => e.count)];
pool.pop();
const avg = pool.reduce((a, e) => a + e, 0) / pool.length;
const diffPercent = (100 / avg * (response.at(-1)?.count || 0)) - 100;
target.trend = diffPercent;
target.ready = true; target.ready = true;
} }

View File

@@ -2,6 +2,7 @@ import { EventModel } from "@schema/metrics/EventSchema";
import { getTimeline } from "./generic"; import { getTimeline } from "./generic";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService"; import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA"; import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { executeTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
export default defineEventHandler(async event => { export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event); const project_id = getRequestProjectId(event);
@@ -11,11 +12,25 @@ export default defineEventHandler(async event => {
const project = await getUserProjectFromId(project_id, user); const project = await getUserProjectFromId(project_id, user);
if (!project) return; if (!project) return;
const { slice, duration } = await readBody(event); const { slice, from, to } = await readBody(event);
return await Redis.useCache({ key: `timeline:events:${project_id}:${slice}`, exp: TIMELINE_EXPIRE_TIME }, async () => { if (!from) return setResponseStatus(event, 400, 'from is required');
const timelineEvents = await getTimeline(EventModel, project_id, slice, duration); if (!from) return setResponseStatus(event, 400, 'to is required');
return timelineEvents; if (!from) return setResponseStatus(event, 400, 'slice is required');
return await Redis.useCache({
key: `timeline:events:${project_id}:${slice}:${from || 'none'}:${to || 'none'}`,
exp: TIMELINE_EXPIRE_TIME
}, async () => {
const timelineData = await executeTimelineAggregation({
projectId: project._id,
model: EventModel,
from, to, slice
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
return timelineFilledMerged;
}); });
}); });

View File

@@ -2,6 +2,7 @@ import { getTimeline } from "./generic";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService"; import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA"; import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { SessionModel } from "@schema/metrics/SessionSchema"; import { SessionModel } from "@schema/metrics/SessionSchema";
import { executeAdvancedTimelineAggregation, executeTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
export default defineEventHandler(async event => { export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event); const project_id = getRequestProjectId(event);
@@ -11,16 +12,44 @@ export default defineEventHandler(async event => {
const project = await getUserProjectFromId(project_id, user); const project = await getUserProjectFromId(project_id, user);
if (!project) return; if (!project) return;
const { slice, duration } = await readBody(event); // const { slice, duration } = await readBody(event);
return await Redis.useCache({ key: `timeline:sessions_duration:${project_id}:${slice}`, exp: TIMELINE_EXPIRE_TIME }, async () => { // return await Redis.useCache({ key: `timeline:sessions_duration:${project_id}:${slice}`, exp: TIMELINE_EXPIRE_TIME }, async () => {
const timelineSessionsDuration = await getTimeline(SessionModel, project_id, slice, duration, {}, // const timelineSessionsDuration = await getTimeline(SessionModel, project_id, slice, duration,
{ duration: { $sum: '$duration' } }, // {},
{ count: { $divide: ["$duration", "$count"] } } // { duration: { $sum: '$duration' } },
); // { count: { $divide: ["$duration", "$count"] } }
return timelineSessionsDuration; // );
// return timelineSessionsDuration;
// });
const { slice, from, to } = await readBody(event);
if (!from) return setResponseStatus(event, 400, 'from is required');
if (!from) return setResponseStatus(event, 400, 'to is required');
if (!from) return setResponseStatus(event, 400, 'slice is required');
return await Redis.useCache({
key: `timeline:sessions_duration:${project_id}:${slice}:${from || 'none'}:${to || 'none'}`,
exp: TIMELINE_EXPIRE_TIME
}, async () => {
const timelineData = await executeAdvancedTimelineAggregation({
projectId: project._id,
model: SessionModel,
from, to, slice,
customGroup: {
duration: { $sum: '$duration' }
},
customProjection: {
count: { $divide: ["$duration", "$count"] }
},
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
return timelineFilledMerged;
}); });
}); });

View File

@@ -9,16 +9,21 @@ export type TimelineAggregationOptions = {
model: mongoose.Model<any>, model: mongoose.Model<any>,
from: string | number, from: string | number,
to: string | number, to: string | number,
slice: Slice slice: Slice,
debug?: boolean
} }
export type AdvancedTimelineAggregationOptions = TimelineAggregationOptions & { export type AdvancedTimelineAggregationOptions = TimelineAggregationOptions & {
customMatch?: Record<string, any> customMatch?: Record<string, any>,
customGroup?: Record<string, any>,
customProjection?: Record<string, any>
} }
export async function executeAdvancedTimelineAggregation(options: AdvancedTimelineAggregationOptions) { export async function executeAdvancedTimelineAggregation(options: AdvancedTimelineAggregationOptions) {
options.customMatch = options.customMatch || {}; options.customMatch = options.customMatch || {};
options.customGroup = options.customGroup || {};
options.customProjection = options.customProjection || {};
const { group, sort, fromParts } = DateService.getQueryDateRange(options.slice); const { group, sort, fromParts } = DateService.getQueryDateRange(options.slice);
@@ -30,11 +35,15 @@ export async function executeAdvancedTimelineAggregation(options: AdvancedTimeli
...options.customMatch ...options.customMatch
} }
}, },
{ $group: { _id: group, count: { $sum: 1 } } }, { $group: { _id: group, count: { $sum: 1 }, ...options.customGroup } },
{ $sort: sort }, { $sort: sort },
{ $project: { _id: { $dateFromParts: fromParts }, count: "$count" } } { $project: { _id: { $dateFromParts: fromParts }, count: "$count", ...options.customProjection } }
] ]
if (options.debug === true) {
console.log(JSON.stringify(aggregation, null, 2));
}
const timeline: { _id: string, count: number }[] = await options.model.aggregate(aggregation); const timeline: { _id: string, count: number }[] = await options.model.aggregate(aggregation);
return timeline; return timeline;