36 Commits

Author SHA1 Message Date
Emily
96c39dbba1 fix docker-compose 2024-09-28 14:24:47 +02:00
Emily
9403aebbb9 update dockercompose 2024-09-28 14:21:53 +02:00
Emily
69bb6fb03c fix cors on api 2024-09-28 13:42:40 +02:00
Emily
33b730e66b add cors + adjusting dockerfile 2024-09-28 13:37:10 +02:00
Emily
0ba44a406d removed old dirs + start dockerfile unification 2024-09-27 21:14:23 +02:00
Emily
3c77a727cd update 2024-09-27 20:33:49 +02:00
Emily
8e3ad2920f fix script url 2024-09-26 15:54:51 +02:00
Emily
f4401d74a2 fix ecosystem 2024-09-26 15:53:00 +02:00
Emily
375330bac4 add ecosystem 2024-09-26 15:51:59 +02:00
Emily
3b1ee0fd13 add security loop 2024-09-26 15:48:59 +02:00
Emily
f5edf187fd update security + chart events è anomaly service 2024-09-24 16:48:23 +02:00
Emily
5b7e93bcbb add cap to dates on slices 2024-09-23 15:01:14 +02:00
Emily
3b6a202538 better logging 2024-09-23 14:03:37 +02:00
Emily
cf1aa103e4 fix security page 2024-09-21 15:19:41 +02:00
Emily
4eeebaa0c3 better first interactions + bug fix 2024-09-21 15:14:46 +02:00
Emily
f285e92132 add secutiry 2024-09-19 15:44:27 +02:00
Emily
ac7ba7abd3 fix 2024-09-19 14:00:12 +02:00
Emily
3c59551f88 new consumer 2024-09-18 23:05:07 +02:00
Emily
628e471cec update consumers 2024-09-18 17:57:25 +02:00
Emily
0be3dbecbf Services rewrite 2024-09-18 17:43:04 +02:00
Emily
fa5a37ece2 . 2024-09-17 13:41:52 +02:00
Emily
db32afe741 better processed logs 2024-09-17 13:39:56 +02:00
Emily
e813b3246d remove console.log 2024-09-17 13:38:47 +02:00
Emily
86011c38ce add logger 2024-09-17 13:38:02 +02:00
Emily
fd5eca29cc remove test error 2024-09-16 20:39:07 +02:00
Emily
a591b43600 fixes 2024-09-16 20:09:32 +02:00
Emily
cebb45484c add logger 2024-09-16 20:09:15 +02:00
Emily
e4e2c2a42a fix anomaly 2024-09-16 20:09:07 +02:00
Emily
dfa1407102 fix anomaly service 2024-09-16 20:08:58 +02:00
Emily
e6adbf9c7b enchance ai 2024-09-16 15:37:18 +02:00
Emily
c3904ebd55 Add advanced ai 2024-09-16 01:03:49 +02:00
Emily
4c46a36c75 add anomaly + fix billing + add emails templates 2024-09-14 17:07:46 +02:00
Emily
c253846b86 fix email 2024-09-13 19:02:15 +02:00
Emily
e7c2dbf237 fix dates 2024-09-13 15:25:26 +02:00
Emily
525a371a6e . 2024-09-12 16:16:19 +02:00
Emily
6a9a698b7a add colors + fix billing page 2024-09-11 15:13:03 +02:00
298 changed files with 8137 additions and 78128 deletions

View File

@@ -1,51 +1,26 @@
shared/node_modules
shared/.output
# Broker
broker/node_modules
broker/scripts/start_dev.js
broker/ecosystem.config.cjs
broker/ecosystem.config.example.cjs
broker/Dockerfile
broker/.gitignore
broker/dist
scripts/node_modules
lyx-ui/node_modules
lyx-ui/.nuxt
lyx-ui/.output
# Producer
producer/node_modules
producer/scripts/start_dev.js
producer/ecosystem.config.cjs
producer/ecosystem.config.example.cjs
producer/Dockerfile
producer/.gitignore
producer/dist
# Dashboard
consumer/node_modules
consumer/scripts/start_dev.js
consumer/ecosystem.config.cjs
dashboard/node_modules
dashboard/.nuxt
dashboard/.output
dashboard/explains
dashboard/tests
dashboard/.env.example
dashboard/.env
dashboard/.gitignore
dashboard/winston-*.ndjson
dashboard/ecosystem.config.cjs
dashboard/out.pdf
dashboard/timeline.report.txt
dashboard/Dockerfile
dashboard/vitest.config.ts
dashboard/vitest.setup.ts
# Shared
shared/node_modules
shared/.gitignore
# Others
docs/*
landing/*
docker/*
dev/*
assets/*
CODE_OF_CONDUCT.md
LICENSE
readme.md
SECURITY.md
steps
docker-compose.yml
docker-compose.admin.yml

3
.gitignore vendored
View File

@@ -2,4 +2,5 @@ steps
PROCESS_EVENT
docker
dev
docker-compose.admin.yml
docker-compose.admin.yml
full_reload.sh

30
Dockerfile Normal file
View File

@@ -0,0 +1,30 @@
FROM node:21-alpine as base
FROM base as build
RUN npm i -g pnpm
RUN npm i -g pm2
# COPY --link dashboard/package.json dashboard/pnpm-lock.yaml ./
# RUN npm install --production=false
WORKDIR /home/app
COPY --link dashboard ./dashboard
COPY --link lyx-ui ./lyx-ui
COPY --link consumer ./consumer
COPY --link producer ./producer
COPY --link shared ./shared
WORKDIR /home/app/producer
RUN pnpm install
WORKDIR /home/app/consumer
RUN pnpm install
WORKDIR /home/app/dashboard
RUN pnpm install
RUN pnpm run dev
# CMD [ "node", "/home/app/.output/server/index.mjs" ]

View File

@@ -1,43 +0,0 @@
ARG NODE_VERSION=21
FROM node:${NODE_VERSION}-alpine as base
ENV NODE_ENV=development
# Build stage
FROM base as build
RUN npm install -g pnpm
COPY --link broker/package.json broker/pnpm-lock.yaml home/app/
COPY --link shared/package.json shared/pnpm-lock.yaml /home/shared/
WORKDIR /home/app
RUN pnpm install --frozen-lockfile
WORKDIR /home/shared
RUN pnpm install --frozen-lockfile
COPY --link ../broker /home/app
COPY --link ../shared /home/shared
WORKDIR /home/app
RUN pnpm run build_all
RUN pnpm prune
# Final stage
FROM base
COPY --from=build /home/app /home/app
WORKDIR /home/app
EXPOSE ${PORT}
CMD ["node", "dist/app/src/index.js"]

View File

@@ -1,13 +0,0 @@
/** @type {import('ts-jest').JestConfigWithTsJest} **/
module.exports = {
testEnvironment: "node",
transform: {
"^.+.tsx?$": ["ts-jest",{}],
},
moduleNameMapper: {
'@services/(.*)': '<rootDir>/../shared/services/$1',
'@data/(.*)': '<rootDir>/../shared/data/$1',
'@functions/(.*)': '<rootDir>/../shared/functions/$1',
'@schema/(.*)': '<rootDir>/../shared/schema/$1',
}
};

View File

@@ -1,43 +0,0 @@
{
"dependencies": {
"@getbrevo/brevo": "^2.2.0",
"cors": "^2.8.5",
"express": "^4.19.2",
"mongoose": "^8.3.2",
"nodemailer": "^6.9.13",
"redis": "^4.6.14",
"ua-parser-js": "^1.0.37"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.13",
"@types/nodemailer": "^6.4.15",
"@types/ua-parser-js": "^0.7.39",
"glob": "^10.4.1",
"jest": "^29.7.0",
"node-ssh": "^13.2.0",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
},
"name": "litlyx-queue-broker",
"version": "1.0.0",
"main": "dist/index.js",
"scripts": {
"dev": "node scripts/start_dev.js",
"compile": "tsc",
"build": "ts-node scripts/build.ts",
"create_db": "cd scripts && ts-node create_database.ts",
"build_all": "npm run compile && npm run build && npm run create_db",
"docker-build": "docker build -t litlyx-broker -f Dockerfile ../",
"docker-inspect": "docker run -it litlyx-broker sh",
"test": "jest"
},
"keywords": [],
"author": "Emily",
"license": "MIT",
"description": "Queue broker for Litlyx - Saves events to database."
}

4685
broker/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,17 +0,0 @@
import fs from 'fs';
import { globSync } from 'glob';
const tsconfigContent = fs.readFileSync('tsconfig.json', 'utf8');
const tsconfigObject = JSON.parse(tsconfigContent);
const paths = tsconfigObject.compilerOptions.paths;
const filesList = globSync('dist/**/*.js');
filesList.forEach(file => {
let raw = fs.readFileSync(file, 'utf8');
for (const path in paths) {
const deep = (file.match(/\\|\//g) || []).length;
const pathText = path.replace('*', '');
const toReplaceText = new RegExp(`"${pathText}(.*?)"`, 'g');
raw = raw.replace(toReplaceText, `"${new Array(deep - 2).fill('../').join('')}${paths[path][0].replace('*', '')}${'$1'}"`);
}
fs.writeFileSync(file, raw);
});

View File

@@ -1,16 +0,0 @@
export function getDeviceFromScreenSize(width: number, height: number) {
const totalArea = width * height;
const mobileArea = 375 * 667;
const tabletMinArea = 768 * 1366
const tabletMaxArea = 1024 * 1366
const isMobile = totalArea <= mobileArea;
const isTablet = totalArea >= tabletMinArea && totalArea <= tabletMaxArea;
if (isMobile) return 'mobile';
if (isTablet) return 'tablet'
return 'desktop';
}

View File

@@ -1,150 +0,0 @@
import { RedisStreamService } from '@services/RedisStreamService';
import { requireEnv } from '../../shared/utilts/requireEnv';
import { EventModel } from '@schema/metrics/EventSchema';
import { SessionModel } from '@schema/metrics/SessionSchema';
import { ProjectModel } from '@schema/ProjectSchema';
import { ProjectLimitModel } from '@schema/ProjectsLimits';
import { ProjectCountModel } from '@schema/ProjectsCounts';
import { EVENT_LOG_LIMIT_PERCENT } from '@data/broker/Limits';
import { checkLimitsForEmail } from './Controller';
import { lookup } from './lookup';
import { UAParser } from 'ua-parser-js';
import { VisitModel } from '@schema/metrics/VisitSchema';
export async function startStreamLoop() {
await RedisStreamService.connect();
await RedisStreamService.startReadingLoop({
streamName: requireEnv('STREAM_NAME'),
delay: { base: 10, empty: 5000 },
readBlock: 2000
}, processStreamEvent);
}
export async function processStreamEvent(data: Record<string, string>) {
try {
const eventType = data._type;
if (!eventType) return;
const { pid, sessionHash } = data;
const project = await ProjectModel.exists({ _id: pid });
if (!project) return;
if (eventType === 'event') return await process_event(data, sessionHash);
if (eventType === 'keep_alive') return await process_keep_alive(data, sessionHash);
if (eventType === 'visit') return await process_visit(data, sessionHash);
} catch (ex: any) {
console.error('ERROR PROCESSING STREAM EVENT', ex.message);
}
}
async function checkLimits(project_id: string) {
const projectLimits = await ProjectLimitModel.findOne({ project_id });
if (!projectLimits) return false;
const TOTAL_COUNT = projectLimits.events + projectLimits.visits;
const COUNT_LIMIT = projectLimits.limit;
if ((TOTAL_COUNT) > COUNT_LIMIT * EVENT_LOG_LIMIT_PERCENT) return false;
await checkLimitsForEmail(projectLimits);
return true;
}
async function process_visit(data: Record<string, string>, sessionHash: string) {
const { pid, ip, website, page, referrer, userAgent, flowHash } = data;
const canLog = await checkLimits(pid);
if (!canLog) return;
let referrerParsed;
try {
referrerParsed = new URL(referrer);
} catch (ex) {
referrerParsed = { hostname: referrer };
}
const geoLocation = lookup(ip);
const userAgentParsed = UAParser(userAgent);
const device = userAgentParsed.device.type;
const visit = new VisitModel({
project_id: pid, website, page, referrer: referrerParsed.hostname,
browser: userAgentParsed.browser.name || 'NO_BROWSER',
os: userAgentParsed.os.name || 'NO_OS',
device: device ? device : (userAgentParsed.browser.name ? 'desktop' : undefined),
session: sessionHash,
flowHash,
continent: geoLocation[0],
country: geoLocation[1],
});
await visit.save();
await ProjectCountModel.updateOne({ project_id: pid }, { $inc: { 'visits': 1 } }, { upsert: true });
await ProjectLimitModel.updateOne({ project_id: pid }, { $inc: { 'visits': 1 } });
}
async function process_keep_alive(data: Record<string, string>, sessionHash: string) {
const { pid, instant, flowHash } = data;
const canLog = await checkLimits(pid);
if (!canLog) return;
const existingSession = await SessionModel.findOne({ project_id: pid, session: sessionHash }, { _id: 1 });
if (!existingSession) {
await ProjectCountModel.updateOne({ project_id: pid }, { $inc: { 'sessions': 1 } }, { upsert: true });
}
if (instant == "true") {
await SessionModel.updateOne({ project_id: pid, session: sessionHash, }, {
$inc: { duration: 0 },
flowHash,
updated_at: Date.now()
}, { upsert: true });
} else {
await SessionModel.updateOne({ project_id: pid, session: sessionHash, }, {
$inc: { duration: 1 },
flowHash,
updated_at: Date.now()
}, { upsert: true });
}
}
async function process_event(data: Record<string, string>, sessionHash: string) {
const { name, metadata, pid, flowHash } = data;
const canLog = await checkLimits(pid);
if (!canLog) return;
let metadataObject;
try {
if (metadata) metadataObject = JSON.parse(metadata);
} catch (ex) {
metadataObject = { error: 'Error parsing metadata' }
}
const event = new EventModel({ project_id: pid, name, flowHash, metadata: metadataObject, session: sessionHash });
await event.save();
await ProjectCountModel.updateOne({ project_id: pid }, { $inc: { 'events': 1 } }, { upsert: true });
await ProjectLimitModel.updateOne({ project_id: pid }, { $inc: { 'events': 1 } });
}

View File

@@ -1,18 +0,0 @@
import express from 'express';
import cors from 'cors';
import { requireEnv } from '../../shared/utilts/requireEnv';
import { connectDatabase } from '@services/DatabaseService';
import { startStreamLoop } from './StreamLoopController';
const app = express();
app.use(cors());
connectDatabase(requireEnv('MONGO_CONNECTION_STRING'));
import HealthRouter from './routes/HealthRouter';
app.use('/health', HealthRouter);
app.listen(requireEnv('PORT'), () => console.log(`Listening on port ${requireEnv('PORT')}`));
startStreamLoop();

View File

@@ -1,15 +0,0 @@
import { Router } from "express";
const router = Router();
router.get('/', async (req, res) => {
try {
return res.json({ alive: true });
} catch (ex) {
console.error(ex);
return res.status(500).json({ error: 'ERROR' });
}
});
export default router;

View File

@@ -1,15 +0,0 @@
import { Request } from "express";
import crypto from 'crypto';
export function getIPFromRequest(req: Request) {
const ip = req.header('X-Real-IP') || req.header('X-Forwarded-For') || '0.0.0.0';
return ip;
}
export function createSessionHash(website: string, ip: string, userAgent: string) {
const dailySalt = new Date().toLocaleDateString('it-IT');
const sessionClean = dailySalt + website + ip + userAgent;
const sessionHash = crypto.createHash('md5').update(sessionClean).digest("hex");
return sessionHash;
}

38
consumer/Dockerfile Normal file
View File

@@ -0,0 +1,38 @@
# Start with a minimal Node.js base image
FROM node:21-alpine as base
# Install pnpm globally with caching to avoid reinstalling if nothing has changed
RUN npm i -g pnpm
# Set the working directory
WORKDIR /home/app
# Copy only package-related files to leverage caching
COPY --link ./scripts/package.json ./scripts/pnpm-lock.yaml ./scripts/
COPY --link ./shared/package.json ./shared/pnpm-lock.yaml ./shared/
COPY --link ./consumer/package.json ./consumer/pnpm-lock.yaml ./consumer/
# Install dependencies for each package
WORKDIR /home/app/scripts
RUN pnpm install --frozen-lockfile
WORKDIR /home/app/shared
RUN pnpm install --frozen-lockfile
WORKDIR /home/app/consumer
RUN pnpm install --frozen-lockfile
# Now copy the rest of the source files
WORKDIR /home/app
COPY --link ../scripts ./scripts
COPY --link ../shared ./shared
COPY --link ../consumer ./consumer
# Build the consumer
WORKDIR /home/app/consumer
RUN pnpm run build_all
# Start the application
CMD ["node", "/home/app/consumer/dist/consumer/src/index.js"]

View File

@@ -1,19 +1,16 @@
module.exports = {
apps: [
{
name: 'QueueBroker',
port: '3999',
name: 'consumer',
exec_mode: 'fork',
script: './dist/producer/src/index.js',
script: './dist/consumer/src/index.js',
env: {
EMAIL_SERVICE: "",
BREVO_API_KEY: "",
PORT: "",
MONGO_CONNECTION_STRING: "",
REDIS_URL: "",
REDIS_USERNAME: "",
REDIS_PASSWORD: "",
STREAM_NAME: ""
STREAM_NAME: "",
GROUP_NAME: ""
}
}
]

30
consumer/package.json Normal file
View File

@@ -0,0 +1,30 @@
{
"dependencies": {
"@getbrevo/brevo": "^2.2.0",
"mongoose": "^8.3.2",
"redis": "^4.6.14",
"ua-parser-js": "^1.0.37"
},
"devDependencies": {
"@types/node": "^20.12.13",
"@types/ua-parser-js": "^0.7.39",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
},
"name": "consumer-database",
"version": "1.0.0",
"main": "dist/index.js",
"scripts": {
"dev": "node scripts/start_dev.js",
"compile": "tsc",
"build": "node ../scripts/build.js",
"create_db": "cd scripts && ts-node create_database.ts",
"build_all": "npm run compile && npm run build && npm run create_db",
"docker-build": "docker build -t litlyx-consumer -f Dockerfile ../",
"docker-inspect": "docker run -it litlyx-consumer sh"
},
"keywords": [],
"author": "Emily",
"license": "MIT",
"description": "Database Consumer - Saves events to database."
}

1498
consumer/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@ import { ProjectModel } from "@schema/ProjectSchema";
import { UserModel } from "@schema/UserSchema";
import { LimitNotifyModel } from "@schema/broker/LimitNotifySchema";
import EmailService from '@services/EmailService';
import { requireEnv } from "../../shared/utilts/requireEnv";
import { requireEnv } from "@utils/requireEnv";
import { TProjectLimit } from "@schema/ProjectsLimits";
if (process.env.EMAIL_SERVICE) {
@@ -11,8 +11,6 @@ if (process.env.EMAIL_SERVICE) {
export async function checkLimitsForEmail(projectCounts: TProjectLimit) {
console.log('CHECK LIMIT EMAIL');
const project_id = projectCounts.project_id;
const hasNotifyEntry = await LimitNotifyModel.findOne({ project_id });
if (!hasNotifyEntry) {
@@ -20,10 +18,8 @@ export async function checkLimitsForEmail(projectCounts: TProjectLimit) {
}
if ((projectCounts.visits + projectCounts.events) >= (projectCounts.limit)) {
console.log('LIMIT 3');
const notify = await LimitNotifyModel.findOne({ project_id });
if (notify && notify.limit3 === true) return;
if (hasNotifyEntry.limit3 === true) return;
const project = await ProjectModel.findById(project_id);
if (!project) return;
@@ -35,10 +31,8 @@ export async function checkLimitsForEmail(projectCounts: TProjectLimit) {
await LimitNotifyModel.updateOne({ project_id: projectCounts.project_id }, { limit1: true, limit2: true, limit3: true });
} else if ((projectCounts.visits + projectCounts.events) >= (projectCounts.limit * 0.9)) {
console.log('LIMIT 2');
const notify = await LimitNotifyModel.findOne({ project_id });
if (notify && notify.limit2 === true) return;
if (hasNotifyEntry.limit2 === true) return;
const project = await ProjectModel.findById(project_id);
if (!project) return;
@@ -51,10 +45,7 @@ export async function checkLimitsForEmail(projectCounts: TProjectLimit) {
} else if ((projectCounts.visits + projectCounts.events) >= (projectCounts.limit * 0.5)) {
console.log('LIMIT 1');
const notify = await LimitNotifyModel.findOne({ project_id });
if (notify && notify.limit1 === true) return;
if (hasNotifyEntry.limit1 === true) return;
const project = await ProjectModel.findById(project_id);
if (!project) return;

View File

@@ -0,0 +1,15 @@
import { ProjectLimitModel } from '@schema/ProjectsLimits';
import { MAX_LOG_LIMIT_PERCENT } from '@data/broker/Limits';
import { checkLimitsForEmail } from './EmailController';
export async function checkLimits(project_id: string) {
const projectLimits = await ProjectLimitModel.findOne({ project_id });
if (!projectLimits) return false;
const TOTAL_COUNT = projectLimits.events + projectLimits.visits;
const COUNT_LIMIT = projectLimits.limit;
if ((TOTAL_COUNT) > COUNT_LIMIT * MAX_LOG_LIMIT_PERCENT) return false;
await checkLimitsForEmail(projectLimits);
return true;
}

142
consumer/src/index.ts Normal file
View File

@@ -0,0 +1,142 @@
import { requireEnv } from '@utils/requireEnv';
import { connectDatabase } from '@services/DatabaseService';
import { RedisStreamService } from '@services/RedisStreamService';
import { ProjectModel } from "@schema/ProjectSchema";
import { VisitModel } from "@schema/metrics/VisitSchema";
import { SessionModel } from "@schema/metrics/SessionSchema";
import { EventModel } from "@schema/metrics/EventSchema";
import { lookup } from './lookup';
import { UAParser } from 'ua-parser-js';
import { checkLimits } from './LimitChecker';
import { ProjectLimitModel } from '@schema/ProjectsLimits';
import { ProjectCountModel } from '@schema/ProjectsCounts';
connectDatabase(requireEnv('MONGO_CONNECTION_STRING'));
main();
async function main() {
await RedisStreamService.connect();
const stream_name = requireEnv('STREAM_NAME');
const group_name = requireEnv('GROUP_NAME') as any; // Checks are inside "startReadingLoop"
await RedisStreamService.startReadingLoop({
stream_name, group_name, consumer_name: `CONSUMER_${process.env.NODE_APP_INSTANCE || 'DEFAULT'}`
}, processStreamEntry);
}
async function processStreamEntry(data: Record<string, string>) {
try {
const start = Date.now();
const eventType = data._type;
if (!eventType) return;
const { pid, sessionHash } = data;
const project = await ProjectModel.exists({ _id: pid });
if (!project) return;
const canLog = await checkLimits(pid);
if (!canLog) return;
if (eventType === 'event') {
await process_event(data, sessionHash);
} else if (eventType === 'keep_alive') {
await process_keep_alive(data, sessionHash);
} else if (eventType === 'visit') {
await process_visit(data, sessionHash);
}
const duration = Date.now() - start;
// console.log('Entry processed in', duration, 'ms');
} catch (ex: any) {
console.error('ERROR PROCESSING STREAM EVENT', ex.message);
}
}
async function process_visit(data: Record<string, string>, sessionHash: string) {
const { pid, ip, website, page, referrer, userAgent, flowHash } = data;
let referrerParsed;
try {
referrerParsed = new URL(referrer);
} catch (ex) {
referrerParsed = { hostname: referrer };
}
const geoLocation = lookup(ip);
const userAgentParsed = UAParser(userAgent);
const device = userAgentParsed.device.type;
await Promise.all([
VisitModel.create({
project_id: pid, website, page, referrer: referrerParsed.hostname,
browser: userAgentParsed.browser.name || 'NO_BROWSER',
os: userAgentParsed.os.name || 'NO_OS',
device: device ? device : (userAgentParsed.browser.name ? 'desktop' : undefined),
session: sessionHash,
flowHash,
continent: geoLocation[0],
country: geoLocation[1],
}),
ProjectCountModel.updateOne({ project_id: pid }, { $inc: { 'visits': 1 } }, { upsert: true }),
ProjectLimitModel.updateOne({ project_id: pid }, { $inc: { 'visits': 1 } })
]);
}
async function process_keep_alive(data: Record<string, string>, sessionHash: string) {
const { pid, instant, flowHash } = data;
const existingSession = await SessionModel.findOne({ project_id: pid, session: sessionHash }, { _id: 1 });
if (!existingSession) {
await ProjectCountModel.updateOne({ project_id: pid }, { $inc: { 'sessions': 1 } }, { upsert: true });
}
if (instant == "true") {
await SessionModel.updateOne({ project_id: pid, session: sessionHash, }, {
$inc: { duration: 0 },
flowHash,
updated_at: Date.now()
}, { upsert: true });
} else {
await SessionModel.updateOne({ project_id: pid, session: sessionHash, }, {
$inc: { duration: 1 },
flowHash,
updated_at: Date.now()
}, { upsert: true });
}
}
async function process_event(data: Record<string, string>, sessionHash: string) {
const { name, metadata, pid, flowHash } = data;
let metadataObject;
try {
if (metadata) metadataObject = JSON.parse(metadata);
} catch (ex) {
metadataObject = { error: 'Error parsing metadata' }
}
await Promise.all([
EventModel.create({ project_id: pid, name, flowHash, metadata: metadataObject, session: sessionHash }),
ProjectCountModel.updateOne({ project_id: pid }, { $inc: { 'events': 1 } }, { upsert: true }),
ProjectLimitModel.updateOne({ project_id: pid }, { $inc: { 'events': 1 } })
]);
}

View File

@@ -5,10 +5,6 @@
"target": "ESNext",
"esModuleInterop": true,
"outDir": "dist",
"types": [
"node",
"jest"
],
"paths": {
"@schema/*": [
"../shared/schema/*"
@@ -21,14 +17,14 @@
],
"@functions/*": [
"../shared/functions/*"
],
"@utils/*": [
"../shared/utils/*"
]
}
},
"include": [
"src/**/*.ts",
"scripts/**/*.ts",
"tests/**/*.test.ts",
"tests/utils.ts"
"src/**/*.ts"
],
"exclude": [
"node_modules"

View File

@@ -12,6 +12,7 @@ node_modules
# Logs
logs
*.log
winston-*.ndjson
# Misc
.DS_Store

View File

@@ -1,34 +1,50 @@
ARG NODE_VERSION=21
# Start with a minimal Node.js base image
FROM node:21-alpine AS base
FROM node:${NODE_VERSION}-alpine as base
# Create a distinct build environment
FROM base AS build
ENV NODE_ENV=production
# Build stage
# Install pnpm globally with caching to avoid reinstalling if nothing has changed
RUN npm i -g pnpm
# Set the working directory
WORKDIR /home/app
FROM base as build
# Copy only package-related files to leverage caching
COPY --link ./dashboard/package.json ./dashboard/pnpm-lock.yaml ./dashboard/
COPY --link ./lyx-ui/package.json ./lyx-ui/pnpm-lock.yaml ./lyx-ui/
COPY --link ./shared/package.json ./shared/pnpm-lock.yaml ./shared/
COPY --link dashboard/package.json dashboard/pnpm-lock.yaml ./
RUN npm install --production=false
# Install dependencies for each package
WORKDIR /home/app/lyx-ui
RUN pnpm install --frozen-lockfile
COPY --link dashboard/ ./
# WORKDIR /home/app/shared
# RUN pnpm install --frozen-lockfile
COPY --link shared/ /home/shared
WORKDIR /home/app/dashboard
RUN pnpm install --frozen-lockfile
ARG GOOGLE_AUTH_CLIENT_ID
ENV GOOGLE_AUTH_CLIENT_ID=$GOOGLE_AUTH_CLIENT_ID
# Now copy the rest of the source files
WORKDIR /home/app
RUN npm run build
RUN npm prune
COPY --link ./dashboard ./dashboard
COPY --link ./lyx-ui ./lyx-ui
COPY --link ./shared ./shared
# Final stage
# Build the dashboard
WORKDIR /home/app/dashboard
FROM base
RUN pnpm run build
COPY --from=build /home/app /home/app
# Use a smaller base image for the final production build
FROM node:21-alpine AS production
EXPOSE ${PORT}
# Set the working directory for the production container
WORKDIR /home/app
CMD [ "node", "/home/app/.output/server/index.mjs" ]
# Copy the built application from the build stage
COPY --from=build /home/app/dashboard/.output /home/app/.output
# Start the application
CMD ["node", "/home/app/.output/server/index.mjs"]

View File

@@ -12,12 +12,6 @@ const { showDialog, closeDialog, dialogComponent, dialogParams, dialogStyle, dia
const { visible } = usePricingDrawer();
const { data: planData } = useFetch('/api/project/plan', {
...signHeaders(),
lazy: true
});
</script>
<template>
@@ -25,10 +19,10 @@ const { data: planData } = useFetch('/api/project/plan', {
<div class="w-dvw h-dvh bg-lyx-background-light relative">
<Transition name="pdrawer">
<LazyPricingDrawer @onCloseClick="visible = false" :currentSub="planData?.premium_type || 0"
class="bg-black fixed right-0 top-0 w-full xl:w-[60vw] xl:min-w-[65rem] h-full z-[20]" v-if=visible>
<LazyPricingDrawer @onCloseClick="visible = false"
class="bg-black fixed right-0 top-0 w-full xl:w-[60vw] xl:min-w-[65rem] h-full z-[20]" v-if="visible">
</LazyPricingDrawer>
</Transition>
</Transition>
<div class="fixed top-4 right-8 z-[999] flex flex-col gap-2" v-if="alerts.length > 0">

View File

@@ -67,7 +67,7 @@ const chartData = ref<ChartData<'bar'>>({
label: e.label || '?',
backgroundColor: [e.color],
borderWidth: 0,
borderRadius: 8
borderRadius: 0
}
})
});

View File

@@ -10,7 +10,7 @@ export type Entry = {
icon?: string,
action?: () => any,
adminOnly?: boolean,
premiumOnly?:boolean,
premiumOnly?: boolean,
external?: boolean,
grow?: boolean
}
@@ -28,6 +28,7 @@ const route = useRoute();
const props = defineProps<Props>();
const { isAdmin } = useUserRoles();
const loggedUser = useLoggedUser()
const debugMode = process.dev;
@@ -101,8 +102,15 @@ function onLogout() {
}
const { projects } = useProjectsList();
const { data: guestProjects } = useGuestProjectsList()
const activeProject = useActiveProject();
const selectorProjects = computed(() => {
const result: TProject[] = [];
if (projects.value) result.push(...projects.value);
if (guestProjects.value) result.push(...guestProjects.value);
return result;
});
const { data: maxProjects } = useFetch("/api/user/max_projects", {
headers: computed(() => {
@@ -117,10 +125,18 @@ watch(selected, () => {
setActiveProject(selected.value._id.toString())
})
const isPremium = computed(()=>{
const isPremium = computed(() => {
return activeProject.value?.premium;
})
function isProjectMine(owner?: string) {
if (!owner) return false;
if (!loggedUser.value?.logged) return;
return loggedUser.value.id == owner;
}
const pricingDrawer = usePricingDrawer();
</script>
<template>
@@ -131,6 +147,13 @@ const isPremium = computed(()=>{
}">
<div class="py-4 px-2 gap-6 flex flex-col w-full">
<!-- <div class="flex px-2" v-if="!isPremium">
<LyxUiButton type="primary" class="w-full text-center text-[.8rem] font-medium" @click="pricingDrawer.visible.value = true;">
Upgrade plan
</LyxUiButton>
</div> -->
<div class="flex px-2 flex-col">
<div class="flex items-center gap-2 w-full">
@@ -142,14 +165,14 @@ const isPremium = computed(()=>{
base: 'hover:!bg-lyx-widget-lighter cursor-pointer',
active: '!bg-lyx-widget-lighter'
}
}" class="w-full" v-if="projects" v-model="selected" :options="projects">
}" class="w-full" v-if="selectorProjects" v-model="selected" :options="selectorProjects">
<template #option="{ option, active, selected }">
<div class="flex items-center gap-2">
<div>
<img class="h-5 bg-black rounded-full" :src="'/logo_32.png'" alt="Litlyx logo">
</div>
<div> {{ option.name }} </div>
<div> {{ option.name }} {{ !isProjectMine(option.owner) ? '(Guest)' : '' }}</div>
</div>
</template>
@@ -158,7 +181,10 @@ const isPremium = computed(()=>{
<div>
<img class="h-5 bg-black rounded-full" :src="'/logo_32.png'" alt="Litlyx logo">
</div>
<div> {{ activeProject?.name || '???' }} </div>
<div>
{{ activeProject?.name || '-' }}
{{ !isProjectMine(activeProject?.owner?.toString()) ? '(Guest)' : '' }}
</div>
</div>
</template>
</USelectMenu>
@@ -169,6 +195,7 @@ const isPremium = computed(()=>{
</div>
<NuxtLink to="/project_creation" v-if="projects && (projects.length < (maxProjects || 1))"
class="flex items-center text-[.8rem] gap-1 justify-end pt-2 pr-2 text-lyx-text-dark hover:text-lyx-text cursor-pointer">
<div><i class="fas fa-plus"></i></div>

View File

@@ -6,20 +6,19 @@ const props = defineProps<{ title: string, sub?: string }>();
<template>
<LyxUiCard>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-4 h-full">
<div class="flex items-center">
<div class="flex flex-col grow">
<div class="poppins font-semibold text-[1.1rem] md:text-[1.4rem] text-text">
<div class="poppins font-semibold text-[1rem] md:text-[1.3rem] text-text">
{{ props.title }}
</div>
<div v-if="props.sub" class="poppins text-[.8rem] md:text-[1.1rem] text-text-sub">
<div v-if="props.sub" class="poppins text-[.7rem] md:text-[1rem] text-text-sub">
{{ props.sub }}
</div>
</div>
<slot name="header"></slot>
</div>
<div>
<div class="h-full">
<slot></slot>
</div>
</div>

View File

@@ -0,0 +1,292 @@
<script lang="ts" setup>
const activeProject = useActiveProject();
const { createAlert } = useAlert();
import 'highlight.js/styles/stackoverflow-dark.css';
import hljs from 'highlight.js';
import CardTitled from './CardTitled.vue';
const props = defineProps<{
firstInteraction: boolean,
refreshInteraction: () => any
}>()
onMounted(() => {
hljs.highlightAll();
})
function copyProjectId() {
if (!navigator.clipboard) alert('You can\'t copy in HTTP');
navigator.clipboard.writeText(activeProject.value?._id?.toString() || '');
createAlert('Success', 'Project id copied successfully.', 'far fa-circle-check', 5000);
}
function copyScript() {
if (!navigator.clipboard) alert('You can\'t copy in HTTP');
const createScriptText = () => {
return [
'<script defer ',
`data-project="${activeProject.value?._id}" `,
'src="https://cdn.jsdelivr.net/gh/litlyx/litlyx-js/browser/litlyx.js"></',
'script>'
].join('')
}
navigator.clipboard.writeText(createScriptText());
createAlert('Success', 'Script copied successfully.', 'far fa-circle-check', 5000);
}
const scriptText = computed(() => {
return [
`<script defer data-project="${activeProject.value?._id.toString()}"`,
`\nsrc="https://cdn.jsdelivr.net/gh/litlyx/litlyx-js/browser/litlyx.js">\n<`,
`/script>`
].join('');
})
function reloadPage() {
location.reload();
}
</script>
<template>
<div v-if="!firstInteraction && activeProject" class="mt-[5vh] flex flex-col">
<div class="flex gap-4 items-center justify-center">
<div class="animate-pulse w-[1.5rem] h-[1.5rem] bg-accent rounded-full"> </div>
<div class="text-text/90 poppins text-[1.3rem] font-semibold">
Waiting for your first Visit or Event
</div>
</div>
<div class="flex justify-center mt-4">
<LyxUiButton type="primary" @click="reloadPage()">
<div class="flex items-center gap-2">
<i class="far fa-refresh"></i>
<div> Reload </div>
</div>
</LyxUiButton>
</div>
<div class="flex items-center justify-center mt-10">
<div class="flex flex-col gap-6">
<div class="flex gap-6">
<div>
<CardTitled class="h-full" title="Tutorial" sub="Coming soon. For now enjoy our launch video.">
<div class="flex items-center justify-center h-full">
<iframe width="560" height="315"
src="https://www.youtube.com/embed/GntyWMR7jsY?si=YGGkQwrk6-Iqmn8w" title="Litlyx"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>
</CardTitled>
</div>
<div class="flex flex-col gap-6">
<div>
<CardTitled title="Quick Integration"
sub="Start tracking web analytics in one line. (works everywhere js is supported)">
<div class="flex flex-col items-end gap-4">
<div class="w-full">
<pre><code class="language-html">{{ scriptText }}</code></pre>
</div>
<LyxUiButton type="secondary" @click="copyScript()">
Copy
</LyxUiButton>
</div>
</CardTitled>
</div>
<div class="h-full w-full">
<CardTitled class="h-full w-full" title="Project id"
sub="This is the identifier for this project, used to forward data">
<div class="flex flex-col items-end">
<div class="w-full text-[.9rem] text-[#acacac]"> {{ activeProject?._id }} </div>
<LyxUiButton type="secondary" @click="copyProjectId()"> Copy </LyxUiButton>
</div>
</CardTitled>
</div>
</div>
</div>
<div>
<div>
<CardTitled class="w-full h-full" title="Documentation"
sub="Learn how to use Litlyx in every tech stack">
<div class="flex flex-col items-end">
<div class="flex justify-center w-full">
<svg width="680" height="100" viewBox="0 0 680 100" fill="none"
xmlns="http://www.w3.org/2000/svg">
<mask id="path-1-inside-1_473_1361" fill="white">
<path
d="M0 12C0 5.37258 5.37258 0 12 0H88C94.6274 0 100 5.37258 100 12V88C100 94.6274 94.6274 100 88 100H12C5.37258 100 0 94.6274 0 88V12Z" />
</mask>
<path
d="M0 12C0 5.37258 5.37258 0 12 0H88C94.6274 0 100 5.37258 100 12V88C100 94.6274 94.6274 100 88 100H12C5.37258 100 0 94.6274 0 88V12Z"
fill="#0A0A0A" />
<path
d="M0 12C0 4.8203 5.8203 -1 13 -1H87C94.1797 -1 100 4.8203 100 12C100 5.92487 94.6274 1 88 1H12C5.37258 1 0 5.92487 0 12ZM100 100H0H100ZM0 100V0V100ZM100 0V100V0Z"
fill="#303246" mask="url(#path-1-inside-1_473_1361)" />
<mask id="path-3-inside-2_473_1361" fill="white">
<path
d="M348 12C348 5.37258 353.373 0 360 0H436C442.627 0 448 5.37258 448 12V88C448 94.6274 442.627 100 436 100H360C353.373 100 348 94.6274 348 88V12Z" />
</mask>
<path
d="M348 12C348 5.37258 353.373 0 360 0H436C442.627 0 448 5.37258 448 12V88C448 94.6274 442.627 100 436 100H360C353.373 100 348 94.6274 348 88V12Z"
fill="#0A0A0A" />
<path
d="M348 12C348 4.8203 353.82 -1 361 -1H435C442.18 -1 448 4.8203 448 12C448 5.92487 442.627 1 436 1H360C353.373 1 348 5.92487 348 12ZM448 100H348H448ZM348 100V0V100ZM448 0V100V0Z"
fill="#303246" mask="url(#path-3-inside-2_473_1361)" />
<path
d="M398 80C414.569 80 428 66.5685 428 50C428 33.4315 414.569 20 398 20C381.431 20 368 33.4315 368 50C368 66.5685 381.431 80 398 80Z"
fill="white" />
<path
d="M417.836 72.5068L391.047 38H386V61.99H390.038V43.1278L414.666 74.9484C415.778 74.2045 416.836 73.3884 417.836 72.5068Z"
fill="url(#paint0_linear_473_1361)" />
<path d="M410.333 38H406.333V62H410.333V38Z"
fill="url(#paint1_linear_473_1361)" />
<mask id="path-8-inside-3_473_1361" fill="white">
<path
d="M116 12C116 5.37258 121.373 0 128 0H204C210.627 0 216 5.37258 216 12V88C216 94.6274 210.627 100 204 100H128C121.373 100 116 94.6274 116 88V12Z" />
</mask>
<path
d="M116 12C116 5.37258 121.373 0 128 0H204C210.627 0 216 5.37258 216 12V88C216 94.6274 210.627 100 204 100H128C121.373 100 116 94.6274 116 88V12Z"
fill="#0A0A0A" />
<path
d="M116 12C116 4.8203 121.82 -1 129 -1H203C210.18 -1 216 4.8203 216 12C216 5.92487 210.627 1 204 1H128C121.373 1 116 5.92487 116 12ZM216 100H116H216ZM116 100V0V100ZM216 0V100V0Z"
fill="#303246" mask="url(#path-8-inside-3_473_1361)" />
<path d="M182.2 27H193L166 73.575L139 27H159.655L166 37.8L172.21 27H182.2Z"
fill="#41B883" />
<path d="M139 27L166 73.575L193 27H182.2L166 54.945L149.665 27H139Z"
fill="#41B883" />
<path d="M149.665 27L166 55.08L182.2 27H172.21L166 37.8L159.655 27H149.665Z"
fill="#35495E" />
<path
d="M53.6605 70H75.9651C76.6735 70.0001 77.3695 69.8153 77.983 69.4642C78.5965 69.1131 79.1059 68.6081 79.46 67.9999C79.8141 67.3918 80.0003 66.7019 80 65.9998C79.9997 65.2977 79.8128 64.608 79.4582 64.0002L64.4791 38.2859C64.1251 37.6779 63.6158 37.173 63.0024 36.8219C62.389 36.4709 61.6932 36.2861 60.9849 36.2861C60.2766 36.2861 59.5808 36.4709 58.9674 36.8219C58.354 37.173 57.8447 37.6779 57.4906 38.2859L53.6605 44.8653L46.1721 31.9995C45.8177 31.3916 45.3082 30.8867 44.6946 30.5358C44.0811 30.1848 43.3852 30 42.6767 30C41.9683 30 41.2724 30.1848 40.6588 30.5358C40.0453 30.8867 39.5357 31.3916 39.1814 31.9995L20.5418 64.0002C20.1872 64.608 20.0003 65.2977 20 65.9998C19.9997 66.7019 20.1859 67.3918 20.54 67.9999C20.8941 68.6081 21.4035 69.1131 22.017 69.4642C22.6305 69.8153 23.3265 70.0001 24.0349 70H38.0359C43.5832 70 47.6741 67.585 50.4891 62.8734L57.3233 51.143L60.9838 44.8653L71.9698 63.7222H57.3233L53.6605 70ZM37.8076 63.7158L28.0367 63.7136L42.6833 38.5724L49.9913 51.143L45.0983 59.545C43.2289 62.602 41.1051 63.7158 37.8076 63.7158Z"
fill="#00DC82" />
<mask id="path-14-inside-4_473_1361" fill="white">
<path
d="M464 12C464 5.37258 469.373 0 476 0H552C558.627 0 564 5.37258 564 12V88C564 94.6274 558.627 100 552 100H476C469.373 100 464 94.6274 464 88V12Z" />
</mask>
<path
d="M464 12C464 5.37258 469.373 0 476 0H552C558.627 0 564 5.37258 564 12V88C564 94.6274 558.627 100 552 100H476C469.373 100 464 94.6274 464 88V12Z"
fill="#0A0A0A" />
<path
d="M464 12C464 4.8203 469.82 -1 477 -1H551C558.18 -1 564 4.8203 564 12C564 5.92487 558.627 1 552 1H476C469.373 1 464 5.92487 464 12ZM564 100H464H564ZM464 100V0V100ZM564 0V100V0Z"
fill="#303246" mask="url(#path-14-inside-4_473_1361)" />
<path
d="M514 55.299C517.088 55.299 519.591 52.7959 519.591 49.7081C519.591 46.6203 517.088 44.1172 514 44.1172C510.912 44.1172 508.409 46.6203 508.409 49.7081C508.409 52.7959 510.912 55.299 514 55.299Z"
fill="#61DAFB" />
<path
d="M514 61.1625C530.569 61.1625 544 56.0341 544 49.708C544 43.3818 530.569 38.2534 514 38.2534C497.431 38.2534 484 43.3818 484 49.708C484 56.0341 497.431 61.1625 514 61.1625Z"
stroke="#61DAFB" stroke-width="5" />
<path
d="M504.08 55.4353C512.364 69.7841 523.521 78.8519 529 75.6888C534.479 72.5257 532.204 58.3295 523.92 43.9808C515.636 29.632 504.479 20.5642 499 23.7273C493.521 26.8904 495.796 41.0865 504.08 55.4353Z"
stroke="#61DAFB" stroke-width="5" />
<path
d="M504.08 43.9808C495.796 58.3296 493.521 72.5258 499 75.6888C504.479 78.8519 515.636 69.7841 523.92 55.4354C532.204 41.0866 534.479 26.8904 529 23.7273C523.521 20.5642 512.364 29.632 504.08 43.9808Z"
stroke="#61DAFB" stroke-width="5" />
<mask id="path-20-inside-5_473_1361" fill="white">
<path
d="M232 12C232 5.37258 237.373 0 244 0H320C326.627 0 332 5.37258 332 12V88C332 94.6274 326.627 100 320 100H244C237.373 100 232 94.6274 232 88V12Z" />
</mask>
<path
d="M232 12C232 5.37258 237.373 0 244 0H320C326.627 0 332 5.37258 332 12V88C332 94.6274 326.627 100 320 100H244C237.373 100 232 94.6274 232 88V12Z"
fill="#0A0A0A" />
<path
d="M232 12C232 4.8203 237.82 -1 245 -1H319C326.18 -1 332 4.8203 332 12C332 5.92487 326.627 1 320 1H244C237.373 1 232 5.92487 232 12ZM332 100H232H332ZM232 100V0V100ZM332 0V100V0Z"
fill="#303246" mask="url(#path-20-inside-5_473_1361)" />
<path
d="M282 20C298.569 20 312 33.4314 312 50C312 66.5686 298.569 80 282 80C265.431 80 252 66.5686 252 50C252 33.4314 265.431 20 282 20Z"
fill="black" />
<path
d="M281.327 64.6787C280.558 64.4713 279.766 64.9167 279.541 65.6761L279.531 65.7115L277.539 73.0943L277.53 73.1299C277.342 73.8995 277.802 74.6827 278.572 74.8901C279.341 75.0979 280.132 74.6525 280.357 73.8929L280.367 73.8577L282.359 66.4749L282.369 66.4391C282.382 66.3837 282.392 66.3279 282.399 66.2723L282.405 66.2167L282.358 65.9775L282.289 65.6331L282.245 65.4181C282.152 65.2379 282.022 65.0791 281.864 64.9517C281.706 64.8245 281.523 64.7315 281.327 64.6787ZM267.445 57.0757C267.408 57.1481 267.378 57.2245 267.353 57.3043L267.339 57.3525L265.347 64.7353L265.338 64.7711C265.15 65.5407 265.61 66.3237 266.38 66.5313C267.149 66.7389 267.941 66.2937 268.166 65.5341L268.176 65.4987L269.982 58.8045C269.036 58.3035 268.187 57.7255 267.445 57.0757ZM262.694 48.5857C261.925 48.3781 261.133 48.8233 260.908 49.5829L260.898 49.6183L258.906 57.0011L258.897 57.0367C258.709 57.8063 259.169 58.5893 259.939 58.7969C260.708 59.0045 261.499 58.5593 261.725 57.7997L261.734 57.7643L263.727 50.3815L263.736 50.3459C263.923 49.5763 263.463 48.7933 262.694 48.5857ZM307.364 46.9091C306.595 46.7015 305.803 47.1467 305.578 47.9063L305.568 47.9417L303.576 55.3245L303.567 55.3601C303.379 56.1297 303.839 56.9127 304.608 57.1203C305.378 57.3279 306.169 56.8827 306.394 56.1231L306.404 56.0877L308.396 48.7049L308.406 48.6693C308.593 47.8997 308.133 47.1167 307.364 46.9091ZM258.356 37.0504C256.687 40.0887 255.625 43.4223 255.228 46.8657C255.418 47.0823 255.668 47.2379 255.946 47.3125C256.715 47.5203 257.507 47.0749 257.732 46.3153L257.742 46.2801L259.734 38.8972L259.743 38.8616C259.931 38.0919 259.471 37.3088 258.701 37.1013C258.589 37.0708 258.472 37.0538 258.356 37.0504ZM302.318 37.1013C301.549 36.8936 300.757 37.3389 300.532 38.0985L300.522 38.1338L298.53 45.5167L298.521 45.5523C298.333 46.3219 298.793 47.1051 299.563 47.3125C300.332 47.5203 301.123 47.0749 301.349 46.3153L301.358 46.2801L303.351 38.8972L303.36 38.8616C303.547 38.0919 303.087 37.3088 302.318 37.1013Z"
fill="white" />
<path
d="M267.026 30.0813C266.256 29.8736 265.465 30.319 265.24 31.0786L265.23 31.1138L263.238 38.4967L263.229 38.5323C263.041 39.302 263.501 40.085 264.27 40.2926C265.04 40.5002 265.831 40.0548 266.056 39.2953L266.066 39.26L268.058 31.8772L268.067 31.8416C268.255 31.0719 267.795 30.2888 267.026 30.0813ZM292.623 31.4769C291.854 31.2692 291.062 31.7145 290.837 32.4742L290.827 32.5094L289.489 37.47C290.356 37.8983 291.183 38.4025 291.962 38.9768L292.091 39.0729L293.656 33.2728L293.665 33.2372C293.852 32.4675 293.393 31.6844 292.623 31.4769ZM279.594 23.1528C278.659 23.2354 277.729 23.3668 276.809 23.5463L276.613 23.5853L274.756 30.4684L274.747 30.504C274.56 31.2737 275.02 32.0567 275.789 32.2643C276.558 32.4719 277.35 32.0266 277.575 31.267L277.585 31.2317L279.577 23.8489L279.586 23.8133C279.639 23.5966 279.642 23.3707 279.594 23.1528ZM297.925 28.2526L297.534 29.7034L297.525 29.7389C297.337 30.5086 297.797 31.2916 298.566 31.4992C299.336 31.7068 300.127 31.2615 300.352 30.5019L300.362 30.4666L300.405 30.3092C299.672 29.6241 298.902 28.9802 298.098 28.3804L297.925 28.2526ZM286.334 23.3935L285.628 26.0119L285.619 26.0475C285.431 26.8172 285.891 27.6002 286.661 27.8078C287.43 28.0154 288.221 27.5701 288.447 26.8105L288.456 26.7752L289.2 24.0193C288.325 23.7773 287.438 23.58 286.543 23.4281L286.334 23.3935Z"
fill="white" />
<path
d="M271.382 69.2504C271.607 68.4908 272.398 68.0456 273.168 68.253C273.937 68.4604 274.397 69.2436 274.209 70.0134L274.2 70.049L272.774 75.3326L272.575 75.2592C271.717 74.9386 270.875 74.5744 270.054 74.1676L271.372 69.2856L271.382 69.2504Z"
fill="white" />
<path
d="M280.828 36.9814C272.104 36.9814 265.318 42.4734 265.318 49.3032C265.318 55.7536 271.562 59.8722 281.242 59.666C282.065 59.6484 282.303 60.2014 282.571 60.9466C282.839 61.6918 283.559 65.6192 284.133 68.6232C284.647 71.3118 285.168 74.0102 285.567 76.719C291.888 75.8834 297.733 72.7612 302.015 68.052L297.447 51.0174C296.309 46.9034 294.978 43.1126 291.457 40.3586C288.624 38.1431 285.024 36.9814 280.828 36.9814Z"
fill="white" />
<path
d="M282.703 41.9141C283.739 41.9141 284.578 42.7535 284.578 43.7891C284.578 44.8247 283.739 45.6641 282.703 45.6641C281.668 45.6641 280.828 44.8247 280.828 43.7891C280.828 42.7535 281.668 41.9141 282.703 41.9141Z"
fill="black" />
<mask id="path-28-inside-6_473_1361" fill="white">
<path
d="M580 12C580 5.37258 585.373 0 592 0H668C674.627 0 680 5.37258 680 12V88C680 94.6274 674.627 100 668 100H592C585.373 100 580 94.6274 580 88V12Z" />
</mask>
<path
d="M580 12C580 5.37258 585.373 0 592 0H668C674.627 0 680 5.37258 680 12V88C680 94.6274 674.627 100 668 100H592C585.373 100 580 94.6274 580 88V12Z"
fill="#0A0A0A" />
<path
d="M580 12C580 4.8203 585.82 -1 593 -1H667C674.18 -1 680 4.8203 680 12C680 5.92487 674.627 1 668 1H592C585.373 1 580 5.92487 580 12ZM680 100H580H680ZM580 100V0V100ZM680 0V100V0Z"
fill="#303246" mask="url(#path-28-inside-6_473_1361)" />
<path d="M655 25H605V75H655V25Z" fill="#F7DF1E" />
<path
d="M638.587 64.0625C639.594 65.7069 640.905 66.9156 643.222 66.9156C645.169 66.9156 646.413 65.9426 646.413 64.5982C646.413 62.9871 645.135 62.4164 642.992 61.4791L641.817 60.9752C638.427 59.5307 636.175 57.7212 636.175 53.8958C636.175 50.372 638.859 47.6895 643.056 47.6895C646.043 47.6895 648.19 48.7291 649.738 51.4514L646.079 53.8006C645.274 52.3561 644.405 51.7871 643.056 51.7871C641.679 51.7871 640.807 52.6601 640.807 53.8006C640.807 55.2101 641.68 55.7807 643.696 56.6537L644.871 57.1569C648.863 58.8688 651.117 60.6141 651.117 64.5379C651.117 68.768 647.794 71.0855 643.331 71.0855C638.967 71.0855 636.148 69.0061 634.769 66.2807L638.587 64.0625ZM621.99 64.4696C622.728 65.7791 623.399 66.8863 625.013 66.8863C626.557 66.8863 627.531 66.2823 627.531 63.9339V47.9577H632.229V63.9974C632.229 68.8625 629.377 71.0768 625.213 71.0768C621.452 71.0768 619.273 69.1299 618.165 66.7851L621.99 64.4696Z"
fill="black" />
<defs>
<linearGradient id="paint0_linear_473_1361" x1="404.333" y1="58.8334"
x2="416.167" y2="73.5" gradientUnits="userSpaceOnUse">
<stop />
<stop offset="1" stop-color="white" stop-opacity="0" />
</linearGradient>
<linearGradient id="paint1_linear_473_1361" x1="408.334" y1="38"
x2="408.267" y2="55.6251" gradientUnits="userSpaceOnUse">
<stop />
<stop offset="1" stop-color="white" stop-opacity="0" />
</linearGradient>
</defs>
</svg>
</div>
<LyxUiButton type="secondary" to="https://docs.litlyx.com"> Visit documentation
</LyxUiButton>
</div>
</CardTitled>
</div>
</div>
</div>
</div>
<!-- <div class="flex justify-center gap-10 flex-col lg:flex-row items-center lg:items-stretch px-10">
<div class="bg-menu p-6 rounded-xl flex flex-col gap-2 w-full">
<div class="poppins font-semibold"> Copy your project_id: </div>
<div class="flex items-center gap-2">
<div> <i @click="copyProjectId()" class="cursor-pointer hover:text-text far fa-copy"></i> </div>
<div class="text-[.9rem] text-[#acacac]"> {{ activeProject?._id }} </div>
</div>
</div>
<div class="bg-menu p-6 rounded-xl flex flex-col gap-2 w-full lg:max-w-[40vw]">
<div class="poppins font-semibold">
Start logging visits in 1 click | Plug anywhere !
</div>
<div class="flex items-center gap-4">
<div> <i @click="copyScript()" class="cursor-pointer hover:text-text far fa-copy"></i> </div>
<pre><code class="language-html">{{ scriptText }}</code></pre>
</div>
</div>
</div> -->
</div>
</template>

View File

@@ -16,10 +16,10 @@ const emits = defineEmits<{
<template>
<div class="flex gap-2 border-[1px] border-gray-400 p-1 md:p-2 rounded-xl">
<div class="flex gap-2 border-[1px] border-lyx-widget-lighter p-1 md:p-2 rounded-xl bg-lyx-widget">
<div @click="$emit('changeIndex', index)" v-for="(opt, index) of options"
class="hover:bg-white/10 select-btn-animated cursor-pointer rounded-lg poppins font-semibold px-2 md:px-3 py-1 text-[.8rem] md:text-[1rem]"
:class="{ 'bg-accent hover:!bg-accent': currentIndex == index }">
class="hover:bg-lyx-widget-lighter/60 select-btn-animated cursor-pointer rounded-lg poppins font-regular px-2 md:px-3 py-1 text-[.8rem] md:text-[1rem]"
:class="{ 'bg-lyx-widget-lighter hover:!bg-lyx-widget-lighter': currentIndex == index }">
{{ opt.label }}
</div>
</div>

View File

@@ -0,0 +1,138 @@
<script setup lang="ts">
import type { ChartData, ChartOptions } from 'chart.js';
import { useLineChart, LineChart } from 'vue-chart-3';
import * as datefns from 'date-fns';
registerChartComponents();
const errored = ref<boolean>(false);
const props = defineProps<{
labels: string[],
title: string,
datasets: {
points: number[],
color: string,
chartType: string,
name: string
}[]
}>();
const chartOptions = ref<ChartOptions<'line'>>({
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
mode: 'nearest',
axis: 'x',
includeInvisible: true
},
scales: {
y: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
// borderDash: [5, 10]
},
},
x: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
}
}
},
plugins: {
legend: { display: true },
title: {
display: true,
text: props.title
},
tooltip: {
enabled: true,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleFont: { size: 16, weight: 'bold' },
bodyFont: { size: 14 },
padding: 10,
cornerRadius: 4,
boxPadding: 10,
caretPadding: 20,
yAlign: 'bottom',
xAlign: 'center',
}
},
});
const chartData = ref<ChartData<'line'>>({
labels: props.labels.map(e => {
try {
return datefns.format(new Date(e), 'dd/MM');
} catch (ex) {
return e;
}
}),
datasets: props.datasets.map(e => ({
data: e.points,
label: e.name,
backgroundColor: [e.color + '77'],
borderColor: e.color,
borderWidth: 4,
fill: true,
tension: 0.45,
pointRadius: 0,
pointHoverRadius: 10,
hoverBackgroundColor: e.color,
hoverBorderColor: 'white',
hoverBorderWidth: 2,
type: e.chartType
} as any))
});
const { lineChartProps, lineChartRef } = useLineChart({ chartData: chartData, options: chartOptions });
function createGradient(startColor: string) {
const c = document.createElement('canvas');
const ctx = c.getContext("2d");
let gradient: any = `${startColor}22`;
if (ctx) {
gradient = ctx.createLinearGradient(0, 25, 0, 300);
gradient.addColorStop(0, `${startColor}99`);
gradient.addColorStop(0.35, `${startColor}66`);
gradient.addColorStop(1, `${startColor}22`);
} else {
console.warn('Cannot get context for gradient');
}
return gradient;
}
onMounted(async () => {
try {
chartData.value.datasets.forEach(dataset => {
if (dataset.borderColor && dataset.borderColor.toString().startsWith('#')) {
dataset.backgroundColor = [createGradient(dataset.borderColor as string)]
} else {
dataset.backgroundColor = [createGradient('#3d59a4')]
}
});
} catch (ex) {
errored.value = true;
console.error(ex);
}
});
</script>
<template>
<div>
<div v-if="errored"> ERROR CREATING CHART </div>
<LineChart v-if="!errored" ref="lineChartRef" v-bind="lineChartProps"> </LineChart>
</div>
</template>

View File

@@ -0,0 +1,110 @@
<script setup lang="ts">
import type { ChartData, ChartOptions } from 'chart.js';
import { useLineChart, LineChart } from 'vue-chart-3';
registerChartComponents();
const props = defineProps<{
data: any[],
labels: string[]
color: string,
}>();
const chartOptions = ref<ChartOptions<'line'>>({
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
mode: 'nearest',
axis: 'x',
includeInvisible: true
},
scales: {
y: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
// borderDash: [5, 10]
},
},
x: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
}
}
},
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
enabled: true,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleFont: { size: 16, weight: 'bold' },
bodyFont: { size: 14 },
padding: 10,
cornerRadius: 4,
boxPadding: 10,
caretPadding: 20,
yAlign: 'bottom',
xAlign: 'center',
}
},
});
const chartData = ref<ChartData<'line'>>({
labels: props.labels,
datasets: [
{
data: props.data,
backgroundColor: [props.color + '77'],
borderColor: props.color,
borderWidth: 4,
fill: true,
tension: 0.45,
pointRadius: 0,
pointHoverRadius: 10,
hoverBackgroundColor: props.color,
hoverBorderColor: 'white',
hoverBorderWidth: 2,
},
],
});
const { lineChartProps, lineChartRef } = useLineChart({ chartData: chartData, options: chartOptions });
onMounted(async () => {
const c = document.createElement('canvas');
const ctx = c.getContext("2d");
let gradient: any = `${props.color}22`;
if (ctx) {
gradient = ctx.createLinearGradient(0, 25, 0, 300);
gradient.addColorStop(0, `${props.color}99`);
gradient.addColorStop(0.35, `${props.color}66`);
gradient.addColorStop(1, `${props.color}22`);
} else {
console.warn('Cannot get context for gradient');
}
chartData.value.datasets[0].backgroundColor = [gradient];
watch(props, () => {
chartData.value.labels = props.labels;
chartData.value.datasets[0].data = props.data;
});
});
</script>
<template>
<LineChart ref="lineChartRef" v-bind="lineChartProps"> </LineChart>
</template>

View File

@@ -0,0 +1,355 @@
<script lang="ts" setup>
import { onMounted } from 'vue';
import DateService, { type Slice } from '@services/DateService';
import type { ChartData, ChartOptions, TooltipModel } from 'chart.js';
import { useLineChart, LineChart } from 'vue-chart-3';
registerChartComponents();
const errorData = ref<{ errored: boolean, text: string }>({
errored: false,
text: ''
})
const chartOptions = ref<ChartOptions<'line'>>({
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
mode: 'nearest',
axis: 'x',
includeInvisible: true
},
scales: {
y: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
// borderDash: [5, 10]
},
},
x: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
}
}
},
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
// enabled: true,
// backgroundColor: 'rgba(0, 0, 0, 0.8)',
// titleFont: { size: 16, weight: 'bold' },
// bodyFont: { size: 14 },
// padding: 10,
// cornerRadius: 4,
// boxPadding: 10,
// caretPadding: 20,
// yAlign: 'bottom',
// xAlign: 'center',
enabled: false,
position: 'nearest',
external: externalTooltipHandler
}
},
});
const chartData = ref<ChartData<'line' | 'bar' | 'bubble'>>({
labels: [],
datasets: [
{
label: 'Visits',
data: [],
backgroundColor: ['#5655d7'],
borderColor: '#5655d7',
borderWidth: 4,
fill: true,
tension: 0.45,
pointRadius: 0,
pointHoverRadius: 10,
hoverBackgroundColor: '#5655d7',
hoverBorderColor: 'white',
hoverBorderWidth: 2,
},
{
label: 'Unique sessions',
data: [],
backgroundColor: ['#4abde8'],
borderColor: '#4abde8',
borderWidth: 2,
hoverBackgroundColor: '#4abde8',
hoverBorderColor: '#4abde8',
hoverBorderWidth: 2,
type: 'bar'
},
{
label: 'Events',
data: [],
backgroundColor: ['#fbbf24'],
borderColor: '#fbbf24',
borderWidth: 2,
hoverBackgroundColor: '#fbbf24',
hoverBorderColor: '#fbbf24',
hoverBorderWidth: 2,
type: 'bubble',
stack: 'combined'
},
],
});
const { lineChartProps, lineChartRef, update: updateChart } = useLineChart({ chartData: (chartData as any), options: chartOptions });
const externalTooltipElement = ref<null | HTMLDivElement>(null);
function externalTooltipHandler(context: { chart: any, tooltip: TooltipModel<'line' | 'bar'> }) {
const { chart, tooltip } = context;
const tooltipEl = externalTooltipElement.value;
currentTooltipData.value.visits = (tooltip.dataPoints.find(e => e.datasetIndex == 0)?.raw) as number;
currentTooltipData.value.sessions = (tooltip.dataPoints.find(e => e.datasetIndex == 1)?.raw) as number;
currentTooltipData.value.events = ((tooltip.dataPoints.find(e => e.datasetIndex == 2)?.raw) as any)?.r2 as number;
currentTooltipData.value.date = new Date(allDatesFull.value[tooltip.dataPoints[0].dataIndex]).toLocaleDateString();
if (!tooltipEl) return;
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = '0';
return;
}
const { left: positionX, top: positionY } = chart.canvas.getBoundingClientRect();
tooltipEl.style.opacity = '1';
tooltipEl.style.left = positionX + tooltip.caretX + 'px';
tooltipEl.style.top = positionY + tooltip.caretY + 'px';
tooltipEl.style.padding = tooltip.options.padding + 'px ' + tooltip.options.padding + 'px';
}
const selectLabels: { label: string, value: Slice }[] = [
{ label: 'Hour', value: 'hour' },
{ label: 'Day', value: 'day' },
{ label: 'Month', value: 'month' },
];
const selectedLabelIndex = ref<number>(1);
const activeProject = useActiveProject();
const { safeSnapshotDates } = useSnapshot()
const allDatesFull = ref<string[]>([]);
function transformResponse(input: { _id: string, count: number }[]) {
const data = input.map(e => e.count);
const labels = input.map(e => DateService.getChartLabelFromISO(e._id, navigator.language, selectLabels[selectedLabelIndex.value].value));
allDatesFull.value = input.map(e => e._id.toString());
return { data, labels }
}
const body = computed(() => {
return {
from: safeSnapshotDates.value.from,
to: safeSnapshotDates.value.to,
slice: selectLabels[selectedLabelIndex.value].value
}
});
function onResponseError(e: any) {
console.log('ON RESPONSE ERROR')
errorData.value = { errored: true, text: e.response._data.message ?? 'Generic error' }
}
function onResponse(e: any) {
console.log('ON RESPONSE')
if (e.response.status != 500) errorData.value = { errored: false, text: '' }
}
const visitsData = useFetch(`/api/metrics/${activeProject.value?._id}/timeline/visits`, {
method: 'POST', ...signHeaders({ v2: 'true' }), body, transform: transformResponse,
lazy: true, immediate: false,
onResponseError,
onResponse
});
const eventsData = useFetch(`/api/metrics/${activeProject.value?._id}/timeline/events`, {
method: 'POST', ...signHeaders({ v2: 'true' }), body, transform: transformResponse,
lazy: true, immediate: false,
onResponseError,
onResponse
});
const sessionsData = useFetch(`/api/metrics/${activeProject.value?._id}/timeline/sessions`, {
method: 'POST', ...signHeaders({ v2: 'true' }), body, transform: transformResponse,
lazy: true, immediate: false,
onResponseError,
onResponse
});
const readyToDisplay = computed(() => {
return !visitsData.pending.value && !eventsData.pending.value && !sessionsData.pending.value;
});
watch(readyToDisplay, () => {
if (readyToDisplay.value === true) onDataReady();
})
function createGradient(startColor: string) {
const c = document.createElement('canvas');
const ctx = c.getContext("2d");
let gradient: any = `${startColor}22`;
if (ctx) {
gradient = ctx.createLinearGradient(0, 25, 0, 300);
gradient.addColorStop(0, `${startColor}99`);
gradient.addColorStop(0.35, `${startColor}66`);
gradient.addColorStop(1, `${startColor}22`);
} else {
console.warn('Cannot get context for gradient');
}
return gradient;
}
function onDataReady() {
console.log('DATA READY');
if (!visitsData.data.value) return;
if (!eventsData.data.value) return;
if (!sessionsData.data.value) return;
console.log('DATA READY 2');
chartData.value.labels = visitsData.data.value.labels;
const maxChartY = Math.max(...visitsData.data.value.data, ...sessionsData.data.value.data);
const maxEventSize = Math.max(...eventsData.data.value.data)
chartData.value.datasets[0].data = visitsData.data.value.data;
chartData.value.datasets[1].data = sessionsData.data.value.data;
chartData.value.datasets[2].data = eventsData.data.value.data.map(e => {
const rValue = 25 / maxEventSize * e;
return { x: 0, y: maxChartY + 70, r: isNaN(rValue) ? 0 : rValue, r2: e }
});
chartData.value.datasets[0].backgroundColor = [createGradient('#5655d7')];
chartData.value.datasets[1].backgroundColor = [createGradient('#4abde8')];
chartData.value.datasets[2].backgroundColor = [createGradient('#fbbf24')];
console.log('UPDATE CHART');
updateChart();
}
const currentTooltipData = ref<{ visits: number, events: number, sessions: number, date: string }>({
visits: 0,
events: 0,
sessions: 0,
date: ''
});
const tooltipNameIndex = ['visits', 'sessions', 'events'];
function onLegendChange(dataset: any, index: number, checked: any) {
dataset.hidden = !checked;
}
const legendColors = [
'#5655d7',
'#4abde8',
'#fbbf24'
]
onMounted(async () => {
visitsData.execute();
eventsData.execute();
sessionsData.execute();
});
const inLiveDemo = isLiveDemo();
</script>
<template>
<CardTitled title="Trend chart" sub="Easily match Visits, Unique sessions and Events trends." class="w-full">
<template #header>
<SelectButton class="w-fit" @changeIndex="selectedLabelIndex = $event" :currentIndex="selectedLabelIndex"
:options="selectLabels">
</SelectButton>
</template>
<div class="flex gap-6 w-full justify-between">
<LyxUiButton type="secondary" :to="inLiveDemo ? '#' : '/analyst'" :disabled="inLiveDemo">
<div class="flex items-center gap-2 px-10">
<i class="far fa-sparkles text-yellow-400"></i>
<div class="poppins text-lyx-text"> Ask AI </div>
</div>
</LyxUiButton>
<div class="flex gap-6">
<div v-for="(dataset, index) of chartData.datasets" class="flex gap-2 items-center text-[.9rem]">
<UCheckbox :ui="{
color: `text-[${legendColors[index]}]`
}" :model-value="true" @change="onLegendChange(dataset, index, $event)"></UCheckbox>
<label class="mt-[2px]"> {{ dataset.label }} </label>
</div>
</div>
</div>
<div id='external-tooltip' ref="externalTooltipElement" class="z-[400]">
<LyxUiCard>
<div class="flex gap-2 items-center">
<div> Date: </div>
<div v-if="currentTooltipData"> {{ currentTooltipData.date }}</div>
</div>
<div v-for="(dataset, index) of chartData.datasets" class="flex gap-2 items-center">
<div :style="`background-color: ${legendColors[index]}`" class="h-4 w-4 rounded-full">
</div>
<div> {{ dataset.label }}</div>
<div v-if="currentTooltipData" class="grow text-right px-4">
{{ (currentTooltipData as any)[tooltipNameIndex[index]] }}
</div>
</div>
<!-- <div class="bg-lyx-background-lighter h-[2px] w-full my-2"> </div> -->
</LyxUiCard>
</div>
<div v-if="!readyToDisplay" class="flex justify-center py-40">
<i class="fas fa-spinner text-[2rem] text-accent animate-[spin_1s_linear_infinite] duration-500"></i>
</div>
<div class="flex flex-col items-end" v-if="readyToDisplay && !errorData.errored">
<LineChart ref="lineChartRef" class="w-full h-full" v-bind="lineChartProps"> </LineChart>
</div>
<div v-if="errorData.errored" class="flex items-center justify-center py-8">
{{ errorData.text }}
</div>
</CardTitled>
</template>
<style lang="scss" scoped>
#external-tooltip {
border-radius: 3px;
color: white;
opacity: 0;
pointer-events: none;
position: absolute;
transform: translate(-50%, 0);
transition: all .1s ease;
}
</style>

View File

@@ -12,6 +12,16 @@ const props = defineProps<{
ready?: boolean
}>();
const { snapshotDuration } = useSnapshot()
const uTooltipText = computed(() => {
const duration = snapshotDuration.value;
if (!duration) return '';
if (duration > 25) return 'Monthly trend';
if (duration > 7) return 'Weekly trend';
return 'Daily trend';
})
</script>
<template>
@@ -29,14 +39,17 @@ const props = defineProps<{
<div class="poppins text-text-sub text-[.9rem] 2xl:text-base"> {{ text }} </div>
</div>
<div v-if="trend" class="flex flex-col items-center gap-1">
<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]" :style="`color: ${props.color}`"></i>
<div :style="`color: ${props.color}`" class="font-semibold text-[.75rem] 2xl:text-[.875rem]">
{{ trend.toFixed(0) }} %
<UTooltip :text="uTooltipText">
<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]" :style="`color: ${props.color}`"></i>
<div :style="`color: ${props.color}`" class="font-semibold text-[.75rem] 2xl:text-[.875rem]">
{{ trend.toFixed(0) }} %
</div>
</div>
</div>
<div class="poppins text-text-sub text-[.7rem]"> Trend </div>
</UTooltip>
<!-- <div class="poppins text-text-sub text-[.7rem]"> Trend </div> -->
</div>
</div>

View File

@@ -46,7 +46,28 @@ const chartData = ref<ChartData<'doughnut'>>({
{
rotation: 1,
data: [],
backgroundColor: ['#6bbbe3', '#5655d0', '#a6d5cb', '#fae0b9'],
backgroundColor: [
"#5655d0",
"#6bbbe3",
"#a6d5cb",
"#fae0b9",
"#f28e8e",
"#e3a7e4",
"#c4a8e1",
"#8cc1d8",
"#f9c2cd",
"#b4e3b2",
"#ffdfba",
"#e9c3b5",
"#d5b8d6",
"#add7f6",
"#ffd1dc",
"#ffe7a1",
"#a8e6cf",
"#d4a5a5",
"#f3d6e4",
"#c3aed6"
],
borderColor: ['#1d1d1f'],
borderWidth: 2
},
@@ -56,7 +77,7 @@ const chartData = ref<ChartData<'doughnut'>>({
const { doughnutChartProps, doughnutChartRef } = useDoughnutChart({ chartData: chartData, options: chartOptions });
const activeProject = useActiveProject();
const activeProjectId = useActiveProjectId();
const { safeSnapshotDates } = useSnapshot();
@@ -81,13 +102,15 @@ const headers = computed(() => {
return {
'x-from': safeSnapshotDates.value.from,
'x-to': safeSnapshotDates.value.to,
Authorization: authorizationHeaderComputed.value,
limit: "10"
'Authorization': authorizationHeaderComputed.value,
'x-schema': 'events',
'x-limit': "6",
'x-pid': activeProjectId.data.value || ''
}
});
const eventsData = useFetch(`/api/metrics/${activeProject.value?._id}/data/events`, {
method: 'POST', headers, lazy: true, immediate: false,transform:transformResponse
const eventsData = useFetch(`/api/data/query`, {
method: 'POST', headers, lazy: true, immediate: false, transform: transformResponse
});
onMounted(() => {

View File

@@ -13,12 +13,25 @@ function copyProjectId() {
navigator.clipboard.writeText((activeProject.value?._id || 0).toString());
createAlert('Success', 'Project id copied successfully.', 'far fa-circle-check', 5000);
}
function showAnomalyInfoAlert() {
createAlert('AI Anomaly Detector info',
`Anomaly detector is running. It helps you detect a spike in visits or events, it could mean an
attack or simply higher traffic due to good performance. Additionally, it can detect if someone is
stealing parts of your website and hosting a duplicate version—an unfortunately common practice.
Litlyx will notify you via email with actionable advices`,
'far fa-shield',
10000
)
}
</script>
<template>
<div
class="w-full px-6 py-2 lg:py-6 font-bold text-text-sub/40 flex flex-col xl:flex-row text-lg lg:text-2xl gap-2 xl:gap-12">
class="w-full px-6 py-2 lg:py-6 font-bold text-text-sub/40 flex flex-col xl:flex-row text-lg gap-2 xl:gap-12 lg:text-2xl">
<div class="flex gap-2 items-center text-text/90 justify-center md:justify-start">
<div class="animate-pulse w-[1rem] h-[1rem] bg-green-400 rounded-full"> </div>
@@ -29,8 +42,10 @@ function copyProjectId() {
<div class="flex md:gap-2 items-center md:justify-start flex-col md:flex-row">
<div class="poppins font-medium text-lyx-text-darker text-[1.2rem]">Project:</div>
<div class="text-lyx-text poppins font-medium text-[1.2rem]"> {{ activeProject?.name || 'Loading...' }} </div>
<div class="text-lyx-text poppins font-medium text-[1.2rem]"> {{ activeProject?.name || 'Loading...' }}
</div>
</div>
<div class="flex flex-col md:flex-row md:gap-2 items-center md:justify-start">
<div class="poppins font-medium text-lyx-text-darker text-[1.2rem]">Project id:</div>
<div class="flex gap-2">
@@ -38,9 +53,20 @@ function copyProjectId() {
{{ activeProject?._id || 'Loading...' }}
</div>
<div class="flex items-center ml-3">
<i @click="copyProjectId()" class="far fa-copy text-lyx-text hover:text-lyx-primary cursor-pointer text-[1.2rem]"></i>
<i @click="copyProjectId()"
class="far fa-copy text-lyx-text hover:text-lyx-primary cursor-pointer text-[1.2rem]"></i>
</div>
</div>
</div>
<div class="flex gap-2 items-center text-text/90 justify-center md:justify-start">
<div class="animate-pulse w-[1rem] h-[1rem] bg-green-400 rounded-full"> </div>
<div class="poppins font-regular text-[1rem]"> AI Anomaly Detector </div>
<div class="flex items-center">
<i class="far fa-info-circle text-[.9rem] hover:text-lyx-primary cursor-pointer"
@click="showAnomalyInfoAlert"></i>
</div>
</div>
</div>
</template>

View File

@@ -76,7 +76,6 @@ async function confirmSnapshot() {
</div>
<div class="mt-4 justify-center flex w-full">
<UPopover class="w-full" :popper="{ placement: 'bottom' }">
<UButton class="w-full" color="primary" variant="solid">
<div class="flex items-center justify-center w-full gap-2">
@@ -97,8 +96,6 @@ async function confirmSnapshot() {
</div>
</template>
</UPopover>
</div>
<div class="grow"></div>

View File

@@ -0,0 +1,148 @@
<script setup lang="ts">
import type { ChartData, ChartOptions } from 'chart.js';
import { defineChartComponent } from 'vue-chart-3';
registerChartComponents();
const FunnelChart = defineChartComponent('funnel', 'funnel');
const chartOptions = ref<ChartOptions<'funnel'>>({
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
mode: 'nearest',
axis: 'x',
includeInvisible: true
},
scales: {
y: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
// borderDash: [5, 10]
},
},
x: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
}
}
},
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
enabled: true,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleFont: { size: 16, weight: 'bold' },
bodyFont: { size: 14 },
padding: 10,
cornerRadius: 4,
boxPadding: 10,
caretPadding: 20,
yAlign: 'bottom',
xAlign: 'center',
}
},
});
const chartData = ref<ChartData<'funnel'>>({
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#5680F8' + '77'],
// borderColor: '#0000CC',
// borderWidth: 4,
fill: true,
tension: 0.45,
pointRadius: 0,
pointHoverRadius: 10,
hoverBackgroundColor: '#5680F8',
// hoverBorderColor: 'white',
// hoverBorderWidth: 2,
},
],
});
onMounted(async () => {
// const c = document.createElement('canvas');
// const ctx = c.getContext("2d");
// let gradient: any = `${'#0000CC'}22`;
// if (ctx) {
// gradient = ctx.createLinearGradient(0, 25, 0, 300);
// gradient.addColorStop(0, `${'#0000CC'}99`);
// gradient.addColorStop(0.35, `${'#0000CC'}66`);
// gradient.addColorStop(1, `${'#0000CC'}22`);
// } else {
// console.warn('Cannot get context for gradient');
// }
// chartData.value.datasets[0].backgroundColor = [gradient];
});
const activeProjectId = useActiveProjectId();
const { safeSnapshotDates } = useSnapshot();
const eventsCount = await useFetch<{ _id: string, count: number }[]>(`/api/data/query`, {
...signHeaders({
'x-pid': activeProjectId.data.value || '',
'x-schema': 'events',
'x-from': safeSnapshotDates.value.from,
'x-to': safeSnapshotDates.value.to,
'x-query-limit': '1000'
}), lazy: true
});
const enabledEvents = ref<string[]>([]);
async function onEventCheck(eventName: string) {
const index = enabledEvents.value.indexOf(eventName);
if (index == -1) {
enabledEvents.value.push(eventName);
} else {
enabledEvents.value.splice(index, 1);
}
chartData.value.labels = enabledEvents.value;
chartData.value.datasets[0].data = [];
for (const enabledEvent of enabledEvents.value) {
const target = (eventsCount.data.value ?? []).find(e => e._id == enabledEvent);
chartData.value.datasets[0].data.push(target?.count || 0);
}
}
</script>
<template>
<CardTitled title="Funnel" sub="Funnel events">
<div class="flex gap-2 justify-between">
<div>
<div class="min-w-[20rem]">
Select two or more events
</div>
<div v-for="event of eventsCount.data.value">
<UCheckbox @change="onEventCheck(event._id)" :value="enabledEvents.includes(event._id)"
:label="event._id">
</UCheckbox>
</div>
</div>
<div class="grow">
<FunnelChart :chart-data="chartData" :options="chartOptions"> </FunnelChart>
</div>
</div>
</CardTitled>
</template>

View File

@@ -30,7 +30,29 @@ function transformResponse(input: { _id: string, name: string, count: number }[]
});
const parsedDatasets: any[] = [];
const colors = ['#5655d0', '#6bbbe3', '#a6d5cb', '#fae0b9'];
const colors = [
"#5655d0",
"#6bbbe3",
"#a6d5cb",
"#fae0b9",
"#f28e8e",
"#e3a7e4",
"#c4a8e1",
"#8cc1d8",
"#f9c2cd",
"#b4e3b2",
"#ffdfba",
"#e9c3b5",
"#d5b8d6",
"#add7f6",
"#ffd1dc",
"#ffe7a1",
"#a8e6cf",
"#d4a5a5",
"#f3d6e4",
"#c3aed6"
];
for (let i = 0; i < fixed.allKeys.length; i++) {
const line: any = {
@@ -52,8 +74,26 @@ function transformResponse(input: { _id: string, name: string, count: number }[]
}
}
const errorData = ref<{ errored: boolean, text: string }>({
errored: false,
text: ''
})
function onResponseError(e: any) {
console.log('ON RESPONSE ERROR')
errorData.value = { errored: true, text: e.response._data.message ?? 'Generic error' }
}
function onResponse(e: any) {
console.log('ON RESPONSE')
if (e.response.status != 500) errorData.value = { errored: false, text: '' }
}
const eventsStackedData = useFetch(`/api/metrics/${activeProject.value?._id}/timeline/events_stacked`, {
method: 'POST', body, lazy: true, immediate: false, transform: transformResponse, ...signHeaders()
method: 'POST', body, lazy: true, immediate: false, transform: transformResponse, ...signHeaders(),
onResponseError,
onResponse
});
@@ -64,13 +104,17 @@ onMounted(async () => {
</script>
<template>
<div>
<div class="h-full">
<div v-if="eventsStackedData.pending.value" class="flex justify-center py-40">
<i class="fas fa-spinner text-[2rem] text-accent animate-[spin_1s_linear_infinite] duration-500"></i>
</div>
<AdvancedStackedBarChart v-if="!eventsStackedData.pending.value"
<AdvancedStackedBarChart v-if="!eventsStackedData.pending.value && !errorData.errored"
:datasets="eventsStackedData.data.value?.datasets || []"
:labels="eventsStackedData.data.value?.labels || []">
</AdvancedStackedBarChart>
<div v-if="errorData.errored" class="flex items-center justify-center py-8 h-full">
{{ errorData.text }}
</div>
</div>
</template>

View File

@@ -38,7 +38,7 @@ async function analyzeEvent() {
<template>
<CardTitled title="Event User Flow"
sub="Track your user's journey from external links to custom events within your platform." class="w-full p-4">
sub="Track your user's journey from external links to in-app events, maintaining a complete view of their path from entry to engagement." class="w-full p-4">
<div class="p-2 flex flex-col gap-3">
<USelectMenu searchable searchable-placeholder="Search an event..." class="w-full"

View File

@@ -0,0 +1,157 @@
<script lang="ts" setup>
import { sub, isSameDay, type Duration } from 'date-fns'
type ChartType = 'bar' | 'line';
const chartTypeOptions: { value: ChartType, label: string }[] = [
{ value: 'bar', label: 'Bar chart' },
{ value: 'line', label: 'Line chart' },
]
type yAxisMode = 'count';
const yAxisModeOptions: { value: yAxisMode, label: string }[] = [
{ value: 'count', label: 'Count fields' },
]
type Slice = 'day' | 'month';
const sliceOptions: Slice[] = ['day', 'month'];
const chartType = ref<ChartType>('line');
const tableName = ref<string>('');
const xAxis = ref<string>('');
const yAxisMode = ref<yAxisMode>('count');
const slice = ref<Slice>('day');
const visualizationName = ref<string>('');
const ranges = [
{ label: 'Last 7 days', duration: { days: 7 } },
{ label: 'Last 14 days', duration: { days: 14 } },
{ label: 'Last 30 days', duration: { days: 30 } },
{ label: 'Last 3 months', duration: { months: 3 } },
{ label: 'Last 6 months', duration: { months: 6 } },
{ label: 'Last year', duration: { years: 1 } }
]
const timeframe = ref<{ start: Date, end: Date }>({ start: sub(new Date(), { days: 14 }), end: new Date() })
function isRangeSelected(duration: Duration) {
return isSameDay(timeframe.value.start, sub(new Date(), duration)) && isSameDay(timeframe.value.end, new Date())
}
function selectRange(duration: Duration) {
timeframe.value = { start: sub(new Date(), duration), end: new Date() }
}
const { createAlert } = useAlert();
const { closeDialog } = useCustomDialog();
const activeProjectId = useActiveProjectId();
const { integrationsCredentials,testConnection } = useSupabase();
async function generate() {
const credentials = integrationsCredentials.data.value;
if (!credentials?.supabase) return createAlert('Credentials not found', 'Please add supabase credentials on the integration page', 'far fa-error', 5000);
const connectionStatus = await testConnection();
if (!connectionStatus) return createAlert('Invalid supabase credentials', 'Please check your supabase credentials on the integration page', 'far fa-error', 5000);
try {
const creation = await $fetch('/api/integrations/supabase/add', {
...signHeaders({
'x-pid': activeProjectId.data.value || '',
'Content-Type': 'application/json'
}),
method: 'POST',
body: JSON.stringify({
name: visualizationName.value,
chart_type: chartType.value,
table_name: tableName.value,
xField: xAxis.value,
yMode: yAxisMode.value,
from: timeframe.value.start,
to: timeframe.value.end,
slice: slice.value
})
})
createAlert('Integration generated', 'Integration generated successfully', 'far fa-check-circle', 5000);
closeDialog();
} catch (ex: any) {
createAlert('Error generating integrations', ex.response._data.message.toString(), 'far fa-error', 5000);
}
}
</script>
<template>
<div class="flex flex-col gap-4">
<div>
<div> Visualization name </div>
<div>
<LyxUiInput class="w-full px-2 py-1" v-model="visualizationName"></LyxUiInput>
</div>
</div>
<div>
<div> Chart type </div>
<USelect v-model="chartType" :options="chartTypeOptions" />
</div>
<div>
<div> Table name </div>
<div>
<LyxUiInput class="w-full px-2 py-1" v-model="tableName"></LyxUiInput>
</div>
</div>
<div>
<div> X axis field </div>
<div>
<LyxUiInput class="w-full px-2 py-1" v-model="xAxis"></LyxUiInput>
</div>
</div>
<div>
<div> Y axis mode </div>
<div>
<USelect v-model="yAxisMode" :options="yAxisModeOptions" />
</div>
</div>
<div>
<div> Timeframe </div>
<div>
<UPopover class="w-full" :popper="{ placement: 'bottom' }">
<UButton class="w-full" color="primary" variant="solid">
<div class="flex items-center justify-center w-full gap-2">
<i class="i-heroicons-calendar-days-20-solid"></i>
{{ timeframe.start.toLocaleDateString() }} - {{ timeframe.end.toLocaleDateString() }}
</div>
</UButton>
<template #panel="{ close }">
<div class="flex items-center sm:divide-x divide-gray-200 dark:divide-gray-800">
<div class="hidden sm:flex flex-col py-4">
<UButton v-for="(range, index) in ranges" :key="index" :label="range.label" color="gray"
variant="ghost" class="rounded-none px-6"
:class="[isRangeSelected(range.duration) ? 'bg-gray-100 dark:bg-gray-800' : 'hover:bg-gray-50 dark:hover:bg-gray-800/50']"
truncate @click="selectRange(range.duration)" />
</div>
<DatePicker v-model="timeframe" @close="close" />
</div>
</template>
</UPopover>
</div>
</div>
<div>
<div> View mode </div>
<div>
<USelect v-model="slice" :options="sliceOptions" />
</div>
</div>
<LyxUiButton type="primary" @click="generate()">
Generate
</LyxUiButton>
</div>
</template>

View File

@@ -0,0 +1,170 @@
<script setup lang="ts">
import type { TSupabaseIntegration } from '@schema/integrations/SupabaseIntegrationSchema';
import type { ChartData, ChartOptions } from 'chart.js';
import { useLineChart, LineChart } from 'vue-chart-3';
const props = defineProps<{ integration_id: string }>();
const activeProjectId = useActiveProjectId();
const supabaseData = ref<{ labels: string[], data: number[] }>();
const supabaseError = ref<string | undefined>(undefined);
const supabaseFetching = ref<boolean>(false);
const { getRemoteData } = useSupabase();
function createGradient() {
const c = document.createElement('canvas');
const ctx = c.getContext("2d");
let gradient: any = `#34B67C22`;
if (ctx) {
gradient = ctx.createLinearGradient(0, 25, 0, 300);
gradient.addColorStop(0, `#34B67C99`);
gradient.addColorStop(0.35, `#34B67C66`);
gradient.addColorStop(1, `#34B67C22`);
} else {
console.warn('Cannot get context for gradient');
}
chartData.value.datasets[0].backgroundColor = [gradient];
}
const chartOptions = ref<ChartOptions<'line'>>({
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
mode: 'nearest',
axis: 'x',
includeInvisible: true
},
scales: {
y: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
// borderDash: [5, 10]
},
},
x: {
ticks: { display: true },
grid: {
display: true,
drawBorder: false,
color: '#CCCCCC22',
}
}
},
plugins: {
legend: { display: false },
title: { display: false },
tooltip: {
enabled: true,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleFont: { size: 16, weight: 'bold' },
bodyFont: { size: 14 },
padding: 10,
cornerRadius: 4,
boxPadding: 10,
caretPadding: 20,
yAlign: 'bottom',
xAlign: 'center',
}
},
});
const chartData = ref<ChartData<'line'>>({
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#34B67C' + '77'],
borderColor: '#34B67C',
borderWidth: 4,
fill: true,
tension: 0.45,
pointRadius: 0,
pointHoverRadius: 10,
hoverBackgroundColor: '#34B67C',
hoverBorderColor: 'white',
hoverBorderWidth: 2,
},
],
});
onMounted(async () => {
supabaseFetching.value = true;
supabaseError.value = undefined;
const integrationData = await $fetch<TSupabaseIntegration>('/api/integrations/supabase/get', {
...signHeaders({
'x-pid': activeProjectId.data.value || '',
'x-integration': props.integration_id
})
});
if (!integrationData) {
supabaseError.value = 'Cannot get integration data';
supabaseFetching.value = false;
return;
}
try {
const data = await getRemoteData(
integrationData.table_name,
integrationData.xField,
integrationData.yMode,
integrationData.from.toString(),
integrationData.to.toString(),
integrationData.slice,
);
if (data.error) {
supabaseError.value = data.error;
supabaseFetching.value = false;
return;
}
supabaseFetching.value = false;
supabaseData.value = data.result;
chartData.value.labels = data.result?.labels || [];
chartData.value.datasets[0].data = data.result?.data || [];
console.log(data.result);
createGradient();
} catch (ex: any) {
if (!ex.response._data) {
supabaseError.value = ex.message.toString();
supabaseFetching.value = false;
} else {
supabaseError.value = ex.response._data.message.toString();
supabaseFetching.value = false;
}
}
});
const { lineChartProps, lineChartRef } = useLineChart({ chartData: chartData, options: chartOptions });
</script>
<template>
<div v-if="!supabaseFetching">
<div v-if="!supabaseError">
<LineChart ref="lineChartRef" v-bind="lineChartProps"> </LineChart>
</div>
<div v-if="supabaseError"> {{ supabaseError }} </div>
</div>
<div v-if="supabaseFetching">
Getting remote data...
</div>
</template>

View File

@@ -1,185 +1,201 @@
<script lang="ts" setup>
import type { PricingCardProp } from './PricingCardGeneric.vue';
const props = defineProps<{ currentSub: number }>();
const freePricing: PricingCardProp[] = [
{
title: 'Free',
price: '€0 / mo',
subs: [
'Up to 5000 visits/events per month',
'CPM 0€ per visit/event'
],
features: [
'Email support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 10',
'Server type: SHARED',
'Data retention: 2 Months'
],
cta: 'Start For Free now!',
active: props.currentSub == 0,
isDowngrade: props.currentSub > 0,
planId: 0
},
]
const customPricing: PricingCardProp[] = [
{
title: 'Enterprise',
price: 'Custom',
subs: [
'Unlimited visits/events per month',
'Service Tailor-made on needs'
],
features: [
'Priority support',
'Server type: DEDICATED',
'DB instance: DEDICATED',
'Dedicated operator',
'White label',
'Custom Data Aggregation'
],
cta: 'Let\'s Talk!',
link: 'mailto:help@litlyx.com',
active: false,
isDowngrade: false,
planId: -1
}
]
const { data: planData, refresh: refreshPlanData } = useFetch('/api/project/plan', {
...signHeaders(),
lazy: true
});
const activeProject = useActiveProject();
watch(activeProject, () => {
refreshPlanData();
});
function getPricingsData() {
const freePricing: PricingCardProp[] = [
{
title: 'Free',
price: '€0 / mo',
subs: [
'Up to 5000 visits/events per month',
'CPM 0€ per visit/event'
],
features: [
'Email support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 10',
'Server type: SHARED',
'Data retention: 2 Months'
],
cta: 'Start For Free now!',
active: (planData.value?.premium_type || 0) == 0,
isDowngrade: (planData.value?.premium_type || 0) > 0,
planId: 0
},
]
const customPricing: PricingCardProp[] = [
{
title: 'Enterprise',
price: 'Custom',
subs: [
'Unlimited visits/events per month',
'Service Tailor-made on needs'
],
features: [
'Priority support',
'Server type: DEDICATED',
'DB instance: DEDICATED',
'Dedicated operator',
'White label',
'Custom Data Aggregation'
],
cta: 'Let\'s Talk!',
link: 'mailto:help@litlyx.com',
active: false,
isDowngrade: false,
planId: -1
}
]
const slidePricings: PricingCardProp[] = [
{
title: 'Incubation',
price: '€4,99 / mo',
subs: [
'Up to 50.000 visits/events per month',
'CPM 0,10€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 30',
'Server type: SHARED',
'Data retention: 6 Months'
],
cta: 'Go to Cloud Dashboard',
active: (planData.value?.premium_type || 0) == 101,
isDowngrade: (planData.value?.premium_type || 0) > 101,
planId: 101
},
{
title: 'Acceleration',
price: '€9,99 / mo',
subs: [
'Up to 150.000 visits/events per month',
'CPM 0,06€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 100',
'Server type: SHARED',
'Data retention: 9 Months'
],
cta: 'Go to Cloud Dashboard',
active: (planData.value?.premium_type || 0) == 102,
isDowngrade: (planData.value?.premium_type || 0) > 102,
planId: 102
},
{
title: 'Growth',
price: '€29,99 / mo',
subs: [
'Up to 500.000 visits/events per month',
'CPM 0,059€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 3.000',
'Server type: SHARED',
'Data retention: 1 Year'
],
cta: 'Go to Cloud Dashboard',
active: (planData.value?.premium_type || 0) == 103,
isDowngrade: (planData.value?.premium_type || 0) > 103,
planId: 103
},
{
title: 'Expansion',
price: '€59,99 / mo',
subs: [
'Up to 1.000.000 visits/events per month',
'CPM 0,059€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 5.000',
'Server type: SHARED',
'Data retention: 1 Year'
],
cta: 'Go to Cloud Dashboard',
active: (planData.value?.premium_type || 0) == 104,
isDowngrade: (planData.value?.premium_type || 0) > 104,
planId: 104
},
{
title: 'Scaling',
price: '€99,99 / mo',
subs: [
'Up to 2.500.000 visits/events per month',
'CPM 0,039€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 10.000',
'Server type: DEDICATED',
'Data retention: 2 Years'
],
cta: 'Go to Cloud Dashboard',
active: (planData.value?.premium_type || 0) == 105,
isDowngrade: (planData.value?.premium_type || 0) > 105,
planId: 105
},
{
title: 'Unicorn',
price: '€149,99 / mo',
subs: [
'Up to 5.000.000 visits/events per month',
'CPM 0,029€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 20.000',
'Server type: DEDICATED',
'Data retention: 3 Years'
],
cta: 'Go to Cloud Dashboard',
active: (planData.value?.premium_type || 0) == 106,
isDowngrade: (planData.value?.premium_type || 0) > 106,
planId: 106
}
]
return { freePricing, customPricing, slidePricings }
}
const slidePricings: PricingCardProp[] = [
{
title: 'Incubation',
price: '€4,99 / mo',
subs: [
'Up to 50.000 visits/events per month',
'CPM 0,10€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 30',
'Server type: SHARED',
'Data retention: 6 Months'
],
cta: 'Go to Cloud Dashboard',
active: props.currentSub == 101,
isDowngrade: props.currentSub > 101,
planId: 101
},
{
title: 'Acceleration',
price: '€9,99 / mo',
subs: [
'Up to 150.000 visits/events per month',
'CPM 0,06€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 100',
'Server type: SHARED',
'Data retention: 9 Months'
],
cta: 'Go to Cloud Dashboard',
active: props.currentSub == 102,
isDowngrade: props.currentSub > 102,
planId: 102
},
{
title: 'Growth',
price: '€29,99 / mo',
subs: [
'Up to 500.000 visits/events per month',
'CPM 0,059€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 3.000',
'Server type: SHARED',
'Data retention: 1 Year'
],
cta: 'Go to Cloud Dashboard',
active: props.currentSub == 103,
isDowngrade: props.currentSub > 103,
planId: 103
},
{
title: 'Expansion',
price: '€59,99 / mo',
subs: [
'Up to 1.000.000 visits/events per month',
'CPM 0,059€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 5.000',
'Server type: SHARED',
'Data retention: 1 Year'
],
cta: 'Go to Cloud Dashboard',
active: props.currentSub == 104,
isDowngrade: props.currentSub > 104,
planId: 104
},
{
title: 'Scaling',
price: '€99,99 / mo',
subs: [
'Up to 2.500.000 visits/events per month',
'CPM 0,039€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 10.000',
'Server type: DEDICATED',
'Data retention: 2 Years'
],
cta: 'Go to Cloud Dashboard',
active: props.currentSub == 105,
isDowngrade: props.currentSub > 105,
planId: 105
},
{
title: 'Unicorn',
price: '€149,99 / mo',
subs: [
'Up to 5.000.000 visits/events per month',
'CPM 0,029€ per visit/event'
],
features: [
'Slack support',
'Unlimited domains',
'Unlimited reports',
'AI Tokens: 20.000',
'Server type: DEDICATED',
'Data retention: 3 Years'
],
cta: 'Go to Cloud Dashboard',
active: props.currentSub == 106,
isDowngrade: props.currentSub > 106,
planId: 106
}
]
const emits = defineEmits<{
(evt: 'onCloseClick'): void
}>();
const activeProject = useActiveProject()
async function onLifetimeUpgradeClick() {
const res = await $fetch<string>(`/api/pay/${activeProject.value?._id.toString()}/create-onetime`, {
...signHeaders({ 'content-type': 'application/json' }),
@@ -201,9 +217,9 @@ async function onLifetimeUpgradeClick() {
</div>
<div class="flex gap-8 mt-10 h-max xl:flex-row flex-col">
<PricingCardGeneric class="flex-1" :datas="freePricing"></PricingCardGeneric>
<PricingCardGeneric class="flex-1" :datas="slidePricings" :default-index="2"></PricingCardGeneric>
<PricingCardGeneric class="flex-1" :datas="customPricing"></PricingCardGeneric>
<PricingCardGeneric class="flex-1" :datas="getPricingsData().freePricing"></PricingCardGeneric>
<PricingCardGeneric class="flex-1" :datas="getPricingsData().slidePricings" :default-index="2"></PricingCardGeneric>
<PricingCardGeneric class="flex-1" :datas="getPricingsData().customPricing"></PricingCardGeneric>
</div>
<LyxUiCard class="w-full mt-6">

View File

@@ -14,7 +14,6 @@ const entries: SettingsTemplateEntry[] = [
const activeProject = useActiveProject();
const projectNameInputVal = ref<string>(activeProject.value?.name || '');
const apiKeys = ref<TApiSettings[]>([]);
const newApiKeyName = ref<string>('');
@@ -111,6 +110,8 @@ async function deleteProject() {
const { createAlert } = useAlert()
const activeProjectId = useActiveProjectId()
function copyScript() {
if (!navigator.clipboard) alert('You can\'t copy in HTTP');
@@ -118,7 +119,7 @@ function copyScript() {
const createScriptText = () => {
return [
'<script defer ',
`data-project="${activeProject.value?._id}" `,
`data-project="${activeProjectId.data.value}" `,
'src="https://cdn.jsdelivr.net/gh/litlyx/litlyx-js/browser/litlyx.js"></',
'script>'
].join('')
@@ -131,7 +132,7 @@ function copyScript() {
function copyProjectId() {
if (!navigator.clipboard) alert('You can\'t copy in HTTP');
navigator.clipboard.writeText(activeProject.value?._id?.toString() || '');
navigator.clipboard.writeText(activeProjectId.data.value || '');
createAlert('Success', 'Project id copied successfully.', 'far fa-circle-check', 5000);
}
@@ -145,13 +146,15 @@ function copyProjectId() {
<template #pname>
<div class="flex items-center gap-4">
<LyxUiInput class="w-full px-4 py-2" v-model="projectNameInputVal"></LyxUiInput>
<LyxUiButton @click="changeProjectName()" :disabled="!canChange" type="primary"> Change </LyxUiButton>
<LyxUiButton v-if="!isGuest" @click="changeProjectName()" :disabled="!canChange" type="primary"> Change
</LyxUiButton>
</div>
</template>
<template #api>
<div class="flex items-center gap-4" v-if="apiKeys && apiKeys.length < 5">
<LyxUiInput class="grow px-4 py-2" placeholder="ApiKeyName" v-model="newApiKeyName"></LyxUiInput>
<LyxUiButton @click="createApiKey()" :disabled="newApiKeyName.length < 3" type="primary">
<LyxUiButton v-if="!isGuest" @click="createApiKey()" :disabled="newApiKeyName.length < 3"
type="primary">
<i class="far fa-plus"></i>
</LyxUiButton>
</div>
@@ -186,7 +189,7 @@ function copyProjectId() {
</LyxUiCard>
</template>
<template #pdelete>
<div class="flex justify-end">
<div class="flex justify-end" v-if="!isGuest">
<LyxUiButton type="danger" @click="deleteProject()">
Delete project
</LyxUiButton>

View File

@@ -23,7 +23,7 @@ const props = defineProps<SettingsTemplateProp>();
<div class="poppins font-medium text-lyx-text">
{{ entry.title }}
</div>
<div class="poppins font-regular text-lyx-text-dark">
<div class="poppins font-regular text-lyx-text-dark whitespace-pre-wrap">
{{ entry.text }}
</div>
</div>

View File

@@ -1,14 +1,18 @@
<script lang="ts" setup>
import dayjs from 'dayjs';
import type { SettingsTemplateEntry } from './Template.vue';
import { getPlanFromId, PREMIUM_PLAN, type PREMIUM_TAG } from '@data/PREMIUM';
const activeProject = useActiveProject();
definePageMeta({ layout: 'dashboard' });
const { data: planData, refresh: planRefresh, pending: planPending } = useFetch('/api/project/plan', {
...signHeaders(),
lazy: true
...signHeaders(), lazy: true
});
const { data: customerAddress, refresh: refreshCustomerAddress } = useFetch(`/api/pay/${activeProject.value?._id.toString()}/customer_info`, {
...signHeaders(), lazy: true
});
const percent = computed(() => {
@@ -42,8 +46,7 @@ const prettyExpireDate = computed(() => {
const { data: invoices, refresh: invoicesRefresh, pending: invoicesPending } = useFetch(`/api/pay/${activeProject.value?._id.toString()}/invoices`, {
...signHeaders(),
lazy: true
...signHeaders(), lazy: true
})
function openInvoice(link: string) {
@@ -51,26 +54,62 @@ function openInvoice(link: string) {
}
function getPremiumName(type: number) {
if (type === 0) return 'FREE';
if (type === 1) return 'ACCELERATION';
if (type === 2) return 'EXPANSION';
return 'CUSTOM';
return Object.keys(PREMIUM_PLAN).map(e => ({
...PREMIUM_PLAN[e as PREMIUM_TAG], name: e
})).find(e => e.ID == type)?.name;
}
watch(activeProject, () => {
invoicesRefresh();
planRefresh();
})
function getPremiumPrice(type: number) {
const PLAN = getPlanFromId(type);
if (!PLAN) return '0,00';
return (PLAN.COST / 100).toFixed(2).replace('.', ',')
}
const entries: SettingsTemplateEntry[] = [
{ id: 'plan', title: 'Current plan', text: 'Manage current plat for this project' },
{ id: 'usage', title: 'Usage', text: 'Show usage of current project' },
{ id: 'info', title: 'Billing address', text: 'This will be reflected in every upcoming invoice,\npast invoices are not affected' },
{ id: 'invoices', title: 'Invoices', text: 'Manage invoices of current project' },
]
watch(customerAddress, () => {
console.log('UPDATE',customerAddress.value)
if (!customerAddress.value) return;
currentBillingInfo.value = customerAddress.value;
});
const currentBillingInfo = ref<any>({
line1: '',
line2: '',
city: '',
country: '',
postal_code: '',
state: ''
});
const { createAlert } = useAlert()
async function saveBillingInfo() {
try {
const res = await $fetch(`/api/pay/${activeProject.value?._id.toString()}/update_customer`, {
method: 'POST',
...signHeaders({
'Content-Type': 'application/json'
}),
body: JSON.stringify(currentBillingInfo.value)
});
createAlert('Customer updated','Customer updated successfully', 'far fa-check', 5000);
} catch(ex) {
createAlert('Error updating customer','An error occurred while updating the customer', 'far fa-error', 8000);
}
}
const { visible } = usePricingDrawer();
@@ -85,6 +124,35 @@ const { visible } = usePricingDrawer();
</div>
<SettingsTemplate v-if="!invoicesPending && !planPending" :entries="entries">
<template #info>
<div>
<div class="flex flex-col gap-2">
<LyxUiInput class="px-2 py-1" placeholder="Address line 1" v-model="currentBillingInfo.line1">
</LyxUiInput>
<LyxUiInput class="px-2 py-1" placeholder="Address line 2" v-model="currentBillingInfo.line2">
</LyxUiInput>
<div class="flex gap-2 w-full">
<LyxUiInput class="px-2 py-1 w-full" placeholder="Country"
v-model="currentBillingInfo.country">
</LyxUiInput>
<LyxUiInput class="px-2 py-1 w-full" placeholder="Postal code"
v-model="currentBillingInfo.postal_code">
</LyxUiInput>
</div>
<div class="flex gap-2 w-full">
<LyxUiInput class="px-2 py-1 w-full" placeholder="City" v-model="currentBillingInfo.city">
</LyxUiInput>
<LyxUiInput class="px-2 py-1 w-full" placeholder="State" v-model="currentBillingInfo.state">
</LyxUiInput>
</div>
</div>
<div class="mt-5 flex justify-end">
<LyxUiButton type="primary" @click="saveBillingInfo">
Save
</LyxUiButton>
</div>
</div>
</template>
<template #plan>
<LyxUiCard v-if="planData" class="flex flex-col w-full">
<div class="flex flex-col gap-6 px-8 grow">
@@ -104,8 +172,12 @@ const { visible } = usePricingDrawer();
</div>
</div>
<div class="flex items-center gap-1">
<div class="poppins font-semibold text-[2rem]"> $0 </div>
<div class="poppins font-semibold text-[2rem]">
{{ getPremiumPrice(planData.premium_type) }} </div>
<div class="poppins text-text-sub mt-2"> per month </div>
<div class="flex items-center ml-2">
<i class="far fa-info-circle text-[.8rem]"></i>
</div>
</div>
</div>
<div class="flex flex-col">

View File

@@ -1,11 +1,7 @@
import { Chart, registerables } from 'chart.js';
let registered = false;
export async function registerChartComponents() {
if (registered) return;
if (process.client) {
Chart.register(...registerables);
registered = true;
}
console.log('registerChartComponents is deprecated. Plugin is now used');
registered = true;
}

View File

@@ -4,6 +4,7 @@
const ACCESS_TOKEN_STATE_KEY = 'access_token';
const ACCESS_TOKEN_COOKIE_KEY = 'access_token';
export function signHeaders(headers?: Record<string, string>) {
const { token } = useAccessToken()
return { headers: { ...(headers || {}), 'Authorization': 'Bearer ' + token.value } }

View File

@@ -5,9 +5,9 @@ export function isLiveDemo() {
return route.path == '/live_demo';
}
const liveDemoData = useFetch('/api/live_demo');
export function useLiveDemo() {
return useFetch('/api/live_demo', {
key: 'live_demo_project'
});
return liveDemoData;
}

View File

@@ -15,7 +15,7 @@ function startWatching(instant: boolean = true) {
if (instant) getOnlineUsers();
watching = setInterval(async () => {
await getOnlineUsers();
}, 5000);
}, 20000);
}
function stopWatching() {

View File

@@ -68,9 +68,15 @@ async function updateSnapshots() {
await remoteSnapshots.refresh();
}
const snapshotDuration = computed(() => {
const from = new Date(snapshot.value?.from || 0).getTime();
const to = new Date(snapshot.value?.to || 0).getTime();
return (to - from) / (1000 * 60 * 60 * 24);
});
export function useSnapshot() {
if (remoteSnapshots.status.value === 'idle') {
remoteSnapshots.execute();
}
return { snapshot, snapshots, safeSnapshotDates, updateSnapshots }
return { snapshot, snapshots, safeSnapshotDates, updateSnapshots, snapshotDuration }
}

View File

@@ -0,0 +1,125 @@
import type { TSupabaseIntegration } from "@schema/integrations/SupabaseIntegrationSchema";
import { createClient, SupabaseClient } from "@supabase/supabase-js";
import { format } from 'date-fns';
const activeProjectId = useActiveProjectId();
const computedHeaders = computed<Record<string, string>>(() => {
const signedHeaders = signHeaders();
return {
'x-pid': activeProjectId.data.value || '',
'Authorization': signedHeaders.headers.Authorization
}
})
const integrationsCredentials = useFetch(`/api/integrations/credentials/get`, {
headers: computedHeaders,
onResponse: (e) => {
supabaseUrl.value = e.response._data.supabase.url || '';
supabaseAnonKey.value = e.response._data.supabase.anon_key || '';
supabaseServiceRoleKey.value = e.response._data.supabase.service_role_key || '';
}
});
const supabaseUrl = ref<string>('');
const supabaseAnonKey = ref<string>('');
const supabaseServiceRoleKey = ref<string>('');
const supabaseIntegrations = useFetch<TSupabaseIntegration[]>('/api/integrations/supabase/list', { headers: computedHeaders })
const subabaseClientData: { client: SupabaseClient | undefined } = {
client: undefined
}
async function updateIntegrationsCredentails(data: { supabase_url: string, supabase_anon_key: string, supabase_service_role_key: string }) {
try {
await $fetch(`/api/integrations/credentials/${activeProjectId.data.value}/update`, {
...signHeaders({ 'Content-Type': 'application/json' }),
method: 'POST',
body: JSON.stringify({
supabase_url: data.supabase_url,
supabase_anon_key: data.supabase_anon_key,
supabase_service_role_key: data.supabase_service_role_key
}),
});
integrationsCredentials.refresh();
return { ok: true, error: '' }
} catch (ex: any) {
return { ok: false, error: ex.message.toString() };
}
}
function createSupabaseUrl(supabaseUrl: string) {
let result = supabaseUrl;
if (!result.includes('https://')) result = `https://${result}`;
if (!result.endsWith('.supabase.co')) result = `${result}.supabase.co`;
return result;
}
async function testConnection() {
const url = createSupabaseUrl(supabaseUrl.value);
subabaseClientData.client = createClient(url, supabaseAnonKey.value);
const res = await subabaseClientData.client.from('_t_e_s_t_').select('*').limit(1);
if (res.error?.message.startsWith('TypeError')) return false;
return true;
}
type GroupBy = 'day' | 'month';
const groupByDate = (data: string[], groupBy: GroupBy) => {
return data.reduce((acc, item) => {
const date = new Date(item);
const dateKey = groupBy === 'day'
? format(date, 'yyyy-MM-dd') // Group by day
: format(date, 'yyyy-MM'); // Group by month
if (!acc[dateKey]) { acc[dateKey] = []; }
acc[dateKey].push(item);
return acc;
}, {} as Record<string, string[]>);
}
async function getRemoteData(table: string, xField: string, yMode: string, from: string, to: string, slice: string) {
const url = createSupabaseUrl(supabaseUrl.value);
subabaseClientData.client = createClient(url, supabaseAnonKey.value);
const res = await subabaseClientData.client.from(table).select(xField)
.filter(xField, 'gte', from)
.filter(xField, 'lte', to);
if (res.error) return { error: res.error.message };
const grouped = groupByDate(res.data.map((e: any) => e.created_at) || [], slice as any);
const result: { labels: string[], data: number[] } = { labels: [], data: [] }
for (const key in grouped) {
result.labels.push(key);
result.data.push(grouped[key].length);
}
return { result };
}
export function useSupabase() {
return {
getRemoteData,
testConnection,
supabaseIntegrations, integrationsCredentials,
supabaseUrl, supabaseAnonKey,
supabaseServiceRoleKey,
updateIntegrationsCredentails
}
}

View File

@@ -17,10 +17,11 @@ const sections: Section[] = [
entries: [
{ label: 'Dashboard', to: '/', icon: 'fal fa-table-layout' },
{ label: 'Events', to: '/events', icon: 'fal fa-square-bolt' },
{ label: 'Analyst', to: '/analyst', icon: 'fal fa-microchip-ai' },
{ label: 'AI Analyst', to: '/analyst', icon: 'fal fa-sparkles' },
{ label: 'Security', to: '/security', icon: 'fal fa-shield' },
{ label: 'Insights (soon)', to: '#', icon: 'fal fa-lightbulb', disabled: true },
{ label: 'Links (soon)', to: '#', icon: 'fal fa-globe-pointer', disabled: true },
{ label: 'Integrations (soon)', to: '#', icon: 'fal fa-cube', disabled: true },
{ label: 'Integrations (soon)', to: '/integrations', icon: 'fal fa-cube', disabled: true },
{ label: 'Settings', to: '/settings', icon: 'fal fa-gear' },
{
grow: true,
@@ -29,8 +30,10 @@ const sections: Section[] = [
},
{
label: 'Slack support', icon: 'fab fa-slack',
to: '#',
premiumOnly: true,
action() {
if (isGuest.value === true) return;
if (isPremium.value === true) {
window.open('https://join.slack.com/t/litlyx/shared_invite/zt-2q3oawn29-hZlu_fBUBlc4052Ooe3FZg', '_blank');
} else {

View File

@@ -12,7 +12,7 @@ export default defineNuxtConfig({
postcss: {
plugins: {
tailwindcss: {},
autoprefixer: {}
autoprefixer: {},
}
},
colorMode: {
@@ -43,6 +43,8 @@ export default defineNuxtConfig({
AUTH_JWT_SECRET: process.env.AUTH_JWT_SECRET,
GOOGLE_AUTH_CLIENT_ID: process.env.GOOGLE_AUTH_CLIENT_ID,
GOOGLE_AUTH_CLIENT_SECRET: process.env.GOOGLE_AUTH_CLIENT_SECRET,
GITHUB_AUTH_CLIENT_ID: process.env.GITHUB_AUTH_CLIENT_ID,
GITHUB_AUTH_CLIENT_SECRET: process.env.GITHUB_AUTH_CLIENT_SECRET,
STRIPE_SECRET: process.env.STRIPE_SECRET,
STRIPE_WH_SECRET: process.env.STRIPE_WH_SECRET,
STRIPE_SECRET_TEST: process.env.STRIPE_SECRET_TEST,
@@ -50,13 +52,17 @@ export default defineNuxtConfig({
NOAUTH_USER_EMAIL: process.env.NOAUTH_USER_EMAIL,
NOAUTH_USER_NAME: process.env.NOAUTH_USER_NAME,
public: {
AUTH_MODE: process.env.AUTH_MODE
AUTH_MODE: process.env.AUTH_MODE,
GITHUB_CLIENT_ID: process.env.GITHUB_AUTH_CLIENT_ID || 'NONE'
}
},
nitro: {
plugins: ['~/server/init.ts']
},
plugins: [
{ src: '~/plugins/chartjs.ts', mode: 'client' }
],
...gooleSignInConfig,
modules: ['@nuxt/ui', 'nuxt-vue3-google-signin'],
devServer: {

View File

@@ -10,22 +10,27 @@
"postinstall": "nuxt prepare",
"test": "vitest",
"docker-build": "docker build -t litlyx-dashboard -f Dockerfile ../",
"docker-inspect": "docker run -it litlyx-dashboard sh"
"docker-inspect": "docker run -it litlyx-dashboard sh",
"docker-run": "docker run -p 3000:3000 litlyx-dashboard"
},
"dependencies": {
"@getbrevo/brevo": "^2.2.0",
"@nuxtjs/tailwindcss": "^6.12.0",
"@supabase/supabase-js": "^2.45.4",
"chart.js": "^3.9.1",
"chartjs-chart-funnel": "^4.2.1",
"chartjs-plugin-annotation": "^2.2.1",
"date-fns": "^3.6.0",
"dayjs": "^1.11.11",
"google-auth-library": "^9.9.0",
"highlight.js": "^11.10.0",
"jsonwebtoken": "^9.0.2",
"litlyx-js": "^1.0.2",
"mongoose": "^8.3.2",
"nodemailer": "^6.9.13",
"nuxt": "^3.11.2",
"nuxt-vue3-google-signin": "^0.0.11",
"openai": "^4.47.1",
"openai": "^4.61.0",
"pdfkit": "^0.15.0",
"primevue": "^3.52.0",
"redis": "^4.6.13",
@@ -34,11 +39,14 @@
"v-calendar": "^3.1.2",
"vue": "^3.4.21",
"vue-chart-3": "^3.1.8",
"vue-router": "^4.3.0"
"vue-markdown-render": "^2.2.1",
"vue-router": "^4.3.0",
"winston": "^3.14.2"
},
"devDependencies": {
"@nuxt/ui": "^2.15.2",
"@types/jsonwebtoken": "^9.0.6",
"@types/markdown-it": "^14.1.2",
"@types/nodemailer": "^6.4.15",
"@types/pdfkit": "^0.13.4",
"autoprefixer": "^10.4.19",

View File

@@ -1,10 +1,18 @@
<script lang="ts" setup>
definePageMeta({ layout: 'dashboard' });
import VueMarkdown from 'vue-markdown-render';
definePageMeta({ layout: 'dashboard' });
const activeProject = useActiveProject();
const { data: chatsList, refresh: reloadChatsList } = useFetch(`/api/ai/${activeProject.value?._id}/chats_list`, signHeaders());
const { data: chatsList, refresh: reloadChatsList } = useFetch(`/api/ai/${activeProject.value?._id}/chats_list`, {
...signHeaders()
});
const viewChatsList = computed(() => (chatsList.value || []).toReversed());
const { data: chatsRemaining, refresh: reloadChatsRemaining } = useFetch(`/api/ai/${activeProject.value?._id}/chats_remaining`, signHeaders());
@@ -12,7 +20,7 @@ const currentText = ref<string>("");
const loading = ref<boolean>(false);
const currentChatId = ref<string>("");
const currentChatMessages = ref<any[]>([]);
const currentChatMessages = ref<{ role: string, content: string, charts?: any[] }[]>([]);
const scroller = ref<HTMLDivElement | null>(null);
@@ -39,7 +47,7 @@ async function sendMessage() {
body: JSON.stringify(body),
...signHeaders({ 'Content-Type': 'application/json' })
});
currentChatMessages.value.push({ role: 'assistant', content: res });
currentChatMessages.value.push({ role: 'assistant', content: res.content || 'nocontent', charts: res.charts.map(e => JSON.parse(e)) });
await reloadChatsRemaining();
await reloadChatsList();
@@ -67,15 +75,18 @@ async function sendMessage() {
async function openChat(chat_id?: string) {
menuOpen.value = false;
if (!activeProject.value) return;
currentChatMessages.value = [];
if (!chat_id) {
currentChatMessages.value = [];
currentChatId.value = '';
return;
}
currentChatId.value = chat_id;
const messages = await $fetch(`/api/ai/${activeProject.value._id}/${chat_id}/get_messages`, signHeaders());
if (!messages) return;
currentChatMessages.value = messages;
currentChatMessages.value = messages.map(e => ({ ...e, charts: e.charts.map(k => JSON.parse(k)) })) as any;
setTimeout(() => scrollToBottom(), 1);
}
@@ -99,10 +110,10 @@ function onKeyDown(e: KeyboardEvent) {
const menuOpen = ref<boolean>(false);
const defaultPrompts = [
'How many visits i got last week ?',
'How many visits i got last month ?',
'How many visits i got today ?',
'How many events i got last week ?',
"Create a line chart with this data: \n[100, 200, 30, 300, 500, 40]",
"Create a chart with Events (bar) and Visits (line) data from last week.",
"How many visits did I get last week?",
"Create a line chart of last week's visits."
]
async function deleteChat(chat_id: string) {
@@ -117,6 +128,8 @@ async function deleteChat(chat_id: string) {
await reloadChatsList();
}
const { visible: pricingDrawerVisible } = usePricingDrawer()
</script>
<template>
@@ -124,7 +137,7 @@ async function deleteChat(chat_id: string) {
<div class="flex flex-row h-full">
<div class="flex-[5] py-8 flex flex-col items-center relative">
<div class="flex-[5] py-8 flex flex-col items-center relative bg-lyx-background-light">
<div class="flex flex-col items-center mt-[20vh] px-28" v-if="currentChatMessages.length == 0">
<div class="w-[10rem]">
@@ -138,7 +151,7 @@ async function deleteChat(chat_id: string) {
</div>
<div class="grid grid-cols-2 gap-4 mt-6" v-if="!isGuest">
<div v-for="prompt of defaultPrompts" @click="currentText = prompt"
class="bg-[#2f2f2f] hover:bg-[#424242] cursor-pointer p-4 rounded-lg poppins text-center">
class="bg-lyx-widget-light hover:bg-lyx-widget-lighter cursor-pointer p-4 rounded-lg poppins text-center whitespace-pre-wrap flex items-center justify-center text-[.9rem]">
{{ prompt }}
</div>
</div>
@@ -146,21 +159,36 @@ async function deleteChat(chat_id: string) {
<div ref="scroller" class="flex flex-col w-full gap-6 px-6 xl:px-28 overflow-y-auto pb-20">
<div class="flex w-full" v-for="message of currentChatMessages">
<div class="flex w-full flex-col" v-for="message of currentChatMessages">
<div class="flex justify-end w-full poppins text-[1.1rem]" v-if="message.role === 'user'">
<div class="bg-[#303030] px-5 py-3 rounded-lg">
<div class="bg-lyx-widget-light px-5 py-3 rounded-lg">
{{ message.content }}
</div>
</div>
<div class="flex items-center gap-3 justify-start w-full poppins text-[1.1rem]"
v-if="message.role === 'assistant'">
v-if="message.role === 'assistant' && message.content">
<div class="flex items-center justify-center shrink-0">
<img class="h-[3.5rem] w-auto" :src="'analyst.png'">
</div>
<div v-html="parseMessageContent(message.content)"
class="max-w-[70%] text-text/90 whitespace-pre-wrap">
<div class="max-w-[70%] text-text/90 ai-message">
<vue-markdown :source="message.content" :options="{
html: true,
breaks: true,
}" />
</div>
</div>
<div v-if="message.charts && message.charts.length > 0"
class="flex items-center gap-3 justify-start w-full poppins text-[1.1rem] flex-col mt-4">
<div v-for="chart of message.charts" class="w-full">
<AnalystComposableChart :datasets="chart.datasets" :labels="chart.labels"
:title="chart.title">
</AnalystComposableChart>
</div>
</div>
</div>
<div v-if="loading"
@@ -177,13 +205,13 @@ async function deleteChat(chat_id: string) {
<div v-if="!isGuest" class="flex gap-2 items-center absolute bottom-8 left-0 w-full px-10 xl:px-28">
<input @keydown="onKeyDown" v-model="currentText"
class="bg-[#303030] w-full focus:outline-none px-4 py-2 rounded-lg" type="text">
class="bg-lyx-widget-light w-full focus:outline-none px-4 py-2 rounded-lg" type="text">
<div @click="sendMessage()"
class="bg-[#303030] hover:bg-[#464646] cursor-pointer px-4 py-2 rounded-full">
class="bg-lyx-widget-light hhover:bg-lyx-widget-lighter cursor-pointer px-4 py-2 rounded-full">
<i class="far fa-arrow-up"></i>
</div>
<div @click="menuOpen = !menuOpen"
class="bg-[#303030] lg:hidden hover:bg-[#464646] cursor-pointer px-4 py-2 rounded-full">
class="bg-lyx-widget-light lg:hidden hhover:bg-lyx-widget-lighter cursor-pointer px-4 py-2 rounded-full">
<i class="far fa-message"></i>
</div>
</div>
@@ -194,32 +222,37 @@ async function deleteChat(chat_id: string) {
<div :class="{
'absolute': menuOpen,
'hidden lg:flex': !menuOpen
}" class="flex-[2] bg-[#303030] p-6 flex flex-col gap-4 h-full overflow-hidden">
}" class="flex-[2] bg-lyx-widget-light p-6 flex flex-col gap-4 h-full overflow-hidden">
<div class="gap-2 flex flex-col">
<div class="lg:hidden absolute right-4 top-4 text-[1.5rem]">
<i @click="menuOpen = false" class="fas fa-close cursor-pointer"></i>
</div>
<div class="poppins font-semibold text-[1.5rem]">
Lit, your AI Analyst is here!
What Lit can do for you?
</div>
<div class="poppins text-text/75">
Ask anything you want on your analytics,
and understand more Trends and Key Points to take Strategic moves!
Ask anything from your data history, visualize and overlap charts, explore events or metadata,
and enjoy a highly personalized data analysis experience.
</div>
</div>
<div class="flex gap-2 items-center py-3">
<div class="flex gap-2 items-center pt-3">
<div class="bg-accent w-5 h-5 rounded-full animate-pulse">
</div>
<div class="manrope font-semibold"> {{ chatsRemaining }} remaining messages </div>
<div class="manrope font-semibold"> {{ chatsRemaining }} remaining AI requests </div>
</div>
<div class="poppins font-semibold text-[1.1rem]"> History: </div>
<LyxUiButton type="primary" class="text-[.9rem] text-center w-full"
@click="pricingDrawerVisible = true">
Upgrade plan for more requests
</LyxUiButton>
<div class="poppins font-semibold text-[1.1rem]"> History </div>
<div class="px-2">
<div @click="openChat()"
class="bg-menu cursor-pointer hover:bg-menu/80 rounded-lg px-4 py-3 poppins flex gap-2 items-center">
class="bg-lyx-widget-lighter cursor-pointer hover:bg-lyx-widget rounded-lg px-4 py-3 poppins flex gap-4 items-center">
<div> <i class="fas fa-plus"></i> </div>
<div> New chat </div>
</div>
@@ -228,12 +261,13 @@ async function deleteChat(chat_id: string) {
<div class="overflow-y-auto">
<div class="flex flex-col gap-2 px-2">
<div class="flex items-center gap-4 w-full" v-for="chat of chatsList?.toReversed()">
<div :class="{ '!bg-accent/60': chat._id.toString() === currentChatId }"
class="flex rounded-lg items-center gap-4 w-full px-4 bg-lyx-widget-lighter hover:bg-lyx-widget"
v-for="chat of viewChatsList">
<i @click="deleteChat(chat._id.toString())"
class="fas fa-trash hover:text-gray-300 cursor-pointer"></i>
class="far fa-trash hover:text-gray-300 cursor-pointer"></i>
<div @click="openChat(chat._id.toString())"
class="bg-menu px-4 py-3 w-full cursor-pointer hover:bg-menu/80 poppins rounded-lg"
:class="{ '!bg-accent/60': chat._id.toString() === currentChatId }">
class="py-3 w-full cursor-pointer poppins rounded-lg">
{{ chat.title }}
</div>
</div>
@@ -248,4 +282,76 @@ async function deleteChat(chat_id: string) {
</div>
</div>
</template>
</template>
<style lang="scss">
.ai-message {
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: bold;
margin-top: 1.5em;
margin-bottom: 0.5em;
color: white;
}
p {
line-height: 1.8;
margin-bottom: 1em;
max-width: 750px;
}
blockquote {
margin: 1.5em 10px;
padding: 10px 20px;
color: #555;
border-left: 5px solid #ccc;
background-color: #f5f5f5;
}
pre {
background-color: #f4f4f4;
padding: 15px;
border-radius: 5px;
font-size: 14px;
overflow-x: auto;
}
code {
background-color: #f1f1f1;
padding: 2px 5px;
border-radius: 3px;
font-size: 90%;
}
ul,
ol {
margin-left: 30px;
margin-bottom: 1.5em;
}
li {
margin-bottom: 0.5em;
}
a {
color: #007acc;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
hr {
border: 1px solid #ddd;
margin: 2em 0;
}
}
</style>

View File

@@ -1,4 +1,6 @@
<script lang="ts" setup>
import EventsFunnelChart from '~/components/events/EventsFunnelChart.vue';
definePageMeta({ layout: 'dashboard' });
@@ -20,15 +22,16 @@ const refreshKey = computed(() => `${snapshot.value._id.toString() + activeProje
<template>
<div class="w-full h-full overflow-y-auto pb-20 p-6 gap-6 flex flex-col">
<div class="flex gap-6 flex-col xl:flex-row">
<div class="flex gap-6 flex-col xl:flex-row h-full">
<CardTitled :key="refreshKey" class="p-4 flex-[4] w-full" title="Events" sub="Events stacked bar chart.">
<CardTitled :key="refreshKey" class="p-4 flex-[4] w-full h-full" title="Events"
sub="Events stacked bar chart.">
<template #header>
<SelectButton @changeIndex="eventsStackedSelectIndex = $event"
:currentIndex="eventsStackedSelectIndex" :options="selectLabelsEvents">
</SelectButton>
</template>
<div>
<div class="h-full">
<EventsStackedBarChart :slice="(selectLabelsEvents[eventsStackedSelectIndex].value as any)">
</EventsStackedBarChart>
</div>
@@ -41,6 +44,10 @@ const refreshKey = computed(() => `${snapshot.value._id.toString() + activeProje
</div>
<div class="flex">
<EventsFunnelChart :key="refreshKey" class="w-full"></EventsFunnelChart>
</div>
<div class="flex">
<EventsUserFlow :key="refreshKey"></EventsUserFlow>
</div>

View File

@@ -20,6 +20,10 @@ const limitsInfo = ref<{
percent: number
}>();
const justLogged = computed(() => {
return route.query.just_logged;
})
onMounted(async () => {
if (route.query.just_logged) return location.href = '/';
@@ -30,33 +34,6 @@ onMounted(async () => {
});
const { createAlert } = useAlert();
function copyProjectId() {
if (!navigator.clipboard) alert('You can\'t copy in HTTP');
navigator.clipboard.writeText(activeProject.value?._id?.toString() || '');
createAlert('Success', 'Project id copied successfully.', 'far fa-circle-check', 5000);
}
function copyScript() {
if (!navigator.clipboard) alert('You can\'t copy in HTTP');
const createScriptText = () => {
return [
'<script defer ',
`data-project="${activeProject.value?._id}" `,
'src="https://cdn.jsdelivr.net/gh/litlyx/litlyx-js/browser/litlyx.js"></',
'script>'
].join('')
}
navigator.clipboard.writeText(createScriptText());
createAlert('Success', 'Script copied successfully.', 'far fa-circle-check', 5000);
}
const firstInteractionUrl = computed(() => {
return `/api/metrics/${activeProject.value?._id}/first_interaction`
});
@@ -78,6 +55,10 @@ const { snapshot } = useSnapshot();
const refreshKey = computed(() => `${snapshot.value._id.toString() + activeProject.value?._id.toString()}`);
const isPremium = computed(() => {
return activeProject.value?.premium;
})
const pricingDrawer = usePricingDrawer();
function goToUpgrade() {
@@ -91,11 +72,10 @@ function goToUpgrade() {
<div class="dashboard w-full h-full overflow-y-auto pb-20 md:pt-4 lg:pt-0">
<div :key="'home-' + isLiveDemo()" v-if="projects && activeProject && firstInteraction.data.value">
<div class="w-full px-4 py-2">
<div :key="'home-' + isLiveDemo()"
v-if="projects && activeProject && (firstInteraction.data.value === true) && !justLogged">
<div class="w-full px-4 py-2 gap-2 flex flex-col">
<div v-if="limitsInfo && limitsInfo.limited"
class="w-full bg-[#fbbf2422] p-4 rounded-lg text-[.9rem] flex items-center">
<div class="flex flex-col grow">
@@ -110,15 +90,35 @@ function goToUpgrade() {
<div>
<LyxUiButton type="outline" @click="goToUpgrade()"> Upgrade </LyxUiButton>
</div>
</div>
<div v-if="!isPremium" class="w-full bg-[#5680f822] p-4 rounded-lg text-[.9rem] flex items-center">
<div class="flex flex-col grow">
<div class="poppins font-semibold text-lyx-primary">
Launch offer: 25% off
</div>
<div class="poppins text-lyx-primary">
We're offering an exclusive 25% discount forever on all plans starting from the Acceleration
Plan for our first 100 users who believe in our project.
<br>
Redeem Code: <span class="text-white font-bold text-[1rem]">LIT25</span> at checkout to
claim your discount.
</div>
</div>
<div>
<LyxUiButton type="outline" @click="goToUpgrade()"> Upgrade </LyxUiButton>
</div>
</div>
</div>
<DashboardTopSection></DashboardTopSection>
<DashboardTopCards :key="refreshKey"></DashboardTopCards>
<div class="mt-6 px-6 flex gap-6 flex-col 2xl:flex-row w-full">
<DashboardActionableChart :key="refreshKey"></DashboardActionableChart>
</div>
<!--
<div class="mt-6 px-6 flex gap-6 flex-col 2xl:flex-row">
<CardTitled :key="refreshKey" class="p-4 flex-1 w-full" title="Visits trends"
@@ -128,26 +128,25 @@ function goToUpgrade() {
:options="selectLabels">
</SelectButton>
</template>
<div>
<DashboardVisitsLineChart :slice="(selectLabels[mainChartSelectIndex].value as any)">
</DashboardVisitsLineChart>
</div>
</CardTitled>
<div>
<DashboardVisitsLineChart :slice="(selectLabels[mainChartSelectIndex].value as any)">
</DashboardVisitsLineChart>
</div>
</CardTitled>
<!-- <CardTitled :key="refreshKey" class="p-4 flex-1 w-full" title="Sessions"
sub="Shows trends in sessions.">
<template #header>
<CardTitled :key="refreshKey" class="p-4 flex-1 w-full" title="Sessions" sub="Shows trends in sessions.">
<template #header>
<SelectButton @changeIndex="sessionsChartSelectIndex = $event"
:currentIndex="sessionsChartSelectIndex" :options="selectLabels">
</SelectButton>
</template>
<div>
<DashboardSessionsLineChart :slice="(selectLabels[sessionsChartSelectIndex].value as any)">
</DashboardSessionsLineChart>
</div>
</CardTitled> -->
<div>
<DashboardSessionsLineChart :slice="(selectLabels[sessionsChartSelectIndex].value as any)">
</DashboardSessionsLineChart>
</div>
</CardTitled>
</div>
</div> -->
<div class="flex w-full justify-center mt-6 px-6">
<div class="flex w-full gap-6 flex-col xl:flex-row">
@@ -160,7 +159,6 @@ function goToUpgrade() {
</div>
</div>
<div class="flex w-full justify-center mt-6 px-6">
<div class="flex w-full gap-6 flex-col xl:flex-row">
<div class="flex-1">
@@ -195,50 +193,15 @@ function goToUpgrade() {
</div>
<div v-if="!firstInteraction.data.value && activeProject" class="mt-[20vh] lg:mt-[36vh] flex flex-col gap-6">
<div class="flex gap-4 items-center justify-center">
<div class="animate-pulse w-[1.5rem] h-[1.5rem] bg-accent rounded-full"> </div>
<div class="text-text/90 poppins text-[1.3rem] font-semibold">
Waiting for your first Visit or Event
</div>
</div>
<FirstInteraction v-if="!justLogged" :refresh-interaction="firstInteraction.refresh"
:first-interaction="(firstInteraction.data.value || false)"></FirstInteraction>
<div class="flex justify-center gap-10 flex-col lg:flex-row items-center lg:items-stretch px-10">
<div class="bg-menu p-6 rounded-xl flex flex-col gap-2 w-full">
<div class="poppins font-semibold"> Copy your project_id: </div>
<div class="flex items-center gap-2">
<div> <i @click="copyProjectId()" class="cursor-pointer hover:text-text far fa-copy"></i> </div>
<div class="text-[.9rem] text-[#acacac]"> {{ activeProject?._id }} </div>
</div>
</div>
<div class="bg-menu p-6 rounded-xl flex flex-col gap-2 w-full lg:max-w-[40vw]">
<div class="poppins font-semibold">
Start logging visits in 1 click | Plug anywhere !
</div>
<div class="flex items-center gap-4">
<div> <i @click="copyScript()" class="cursor-pointer hover:text-text far fa-copy"></i> </div>
<div class="text-[.9rem] text-[#acacac] lg:w-min">
{{ `
<script defer data-project="${activeProject?._id}"
src="https://cdn.jsdelivr.net/gh/litlyx/litlyx-js/browser/litlyx.js"></script>` }}
</div>
</div>
</div>
</div>
<NuxtLink to="https://docs.litlyx.com" target="_blank"
class="flex justify-center poppins text-[1.2rem] text-accent gap-2 items-center">
<div> <i class="far fa-book"></i> </div>
<div class="poppins"> Go to docs </div>
</NuxtLink>
<div class="text-text/85 mt-8 ml-8 poppis text-[1.2rem]" v-if="projects && projects.length == 0 && !justLogged">
Create your first project...
</div>
<div class="text-text/85 mt-8 ml-8 poppis text-[1.2rem]" v-if="projects && projects.length == 0">
Create your first project...
<div v-if="justLogged" class="text-[2rem]">
The page will refresh soon
</div>
</div>

View File

@@ -0,0 +1,105 @@
<script setup lang="ts">
import SupabaseChartDialog from '~/components/integrations/SupabaseChartDialog.vue';
definePageMeta({ layout: 'dashboard' });
const activeProjectId = useActiveProjectId();
const { createAlert } = useAlert();
const {
supabaseUrl, supabaseAnonKey, supabaseServiceRoleKey, integrationsCredentials,
supabaseIntegrations, updateIntegrationsCredentails
} = useSupabase()
async function updateCredentials() {
const res = await updateIntegrationsCredentails({
supabase_url: supabaseUrl.value,
supabase_anon_key: supabaseAnonKey.value,
supabase_service_role_key: supabaseServiceRoleKey.value
});
if (res.ok === true) {
integrationsCredentials.refresh();
createAlert('Credentials updated', 'Credentials updated successfully', 'far fa-error', 4000);
} else {
createAlert('Error updating credentials', res.error, 'far fa-error', 4000);
}
}
const { openDialogEx } = useCustomDialog()
function showChartDialog() {
openDialogEx(SupabaseChartDialog, {
closable: true,
width: '55vw',
height: '65vh'
})
}
</script>
<template>
<div class="home w-full h-full px-10 pt-6 overflow-y-auto">
<CardTitled title="Supabase integration" class="w-full">
<template #header>
<img class="h-10 w-10" :src="'supabase.svg'" alt="Supabase logo">
</template>
<div class="flex gap-6 flex-col w-full">
<div class="flex flex-col">
<div class="text-lyx-text"> Supabase url </div>
<div class="text-lyx-text-dark"> Required to fetch data from supabase </div>
<LyxUiInput v-if="!integrationsCredentials.pending.value" class="w-full mt-2 px-4 py-1"
v-model="supabaseUrl" type="text"></LyxUiInput>
<div v-if="integrationsCredentials.pending.value"> Loading... </div>
</div>
<div class="flex flex-col">
<div class="text-lyx-text"> Supabase anon key </div>
<div class="text-lyx-text-dark"> Required to fetch data from supabase </div>
<LyxUiInput v-if="!integrationsCredentials.pending.value" class="w-full mt-2 px-4 py-1"
v-model="supabaseAnonKey" type="password"></LyxUiInput>
<div v-if="integrationsCredentials.pending.value"> Loading... </div>
</div>
<div class="flex flex-col">
<div class="text-lyx-text"> Supabase service role key </div>
<div class="text-lyx-text-dark"> Only used if you need to bypass RLS </div>
<LyxUiInput v-if="!integrationsCredentials.pending.value" class="w-full mt-2 px-4 py-1"
v-model="supabaseServiceRoleKey" type="password"></LyxUiInput>
<div v-if="integrationsCredentials.pending.value"> Loading... </div>
</div>
<div class="flex gap-3">
<LyxUiButton v-if="!integrationsCredentials.pending.value" @click="updateCredentials()"
type="primary"> Save
</LyxUiButton>
</div>
</div>
</CardTitled>
<LyxUiCard class="mt-6 w-full">
<div class="flex flex-col gap-8">
<div class="flex gap-2 items-center" v-for="supabaseIntegration of supabaseIntegrations.data.value">
<div> {{ supabaseIntegration.name }} </div>
<div> <i class="far fa-edit"></i> </div>
<div> <i class="far fa-trash"></i> </div>
</div>
<div>
<LyxUiButton type="primary" @click="showChartDialog()"> Add supabase chart </LyxUiButton>
</div>
</div>
</LyxUiCard>
<div class="mt-10">
<IntegrationsSupabaseLineChart integration_id="66f6c558d97e4abd408feee0"></IntegrationsSupabaseLineChart>
</div>
</div>
</template>

View File

@@ -6,6 +6,8 @@ const { snapshot, snapshots } = useSnapshot();
const { data: project } = useLiveDemo();
const ready = ref<boolean>(false);
let interval: any;
onMounted(async () => {
@@ -13,8 +15,11 @@ onMounted(async () => {
snapshot.value = snapshots.value[0];
interval = setInterval(async () => {
await getOnlineUsers();
}, 5000);
}, 20000);
setTimeout(() => {
ready.value = true;
}, 2000);
})
onUnmounted(() => {
@@ -54,8 +59,7 @@ const selectLabelsEvents = [
<template>
<div class="dashboard w-full h-full overflow-y-auto pb-20">
<div v-if="project">
<div v-if="project && ready">
<div
class="bg-bg w-full px-6 py-6 text-text/90 flex flex-collg:flex-row text-lg lg:text-2xl gap-2 lg:gap-12">
@@ -85,35 +89,10 @@ const selectLabelsEvents = [
<DashboardTopCards></DashboardTopCards>
</div>
<div class="mt-6 px-6 flex gap-6 flex-col 2xl:flex-row">
<CardTitled class="p-4 flex-1 w-full" title="Visits trends" sub="Shows trends in page visits.">
<template #header>
<SelectButton @changeIndex="mainChartSelectIndex = $event" :currentIndex="mainChartSelectIndex"
:options="selectLabels">
</SelectButton>
</template>
<div>
<DashboardVisitsLineChart :slice="(selectLabels[mainChartSelectIndex].value as any)">
</DashboardVisitsLineChart>
</div>
</CardTitled>
<!-- <CardTitled class="p-4 flex-1" title="Sessions" sub="Shows trends in sessions.">
<template #header>
<SelectButton @changeIndex="sessionsChartSelectIndex = $event"
:currentIndex="sessionsChartSelectIndex" :options="selectLabels">
</SelectButton>
</template>
<div>
<DashboardSessionsLineChart :slice="(selectLabels[sessionsChartSelectIndex].value as any)">
</DashboardSessionsLineChart>
</div>
</CardTitled> -->
<div class="mt-6 px-6 flex gap-6 flex-col 2xl:flex-row w-full">
<DashboardActionableChart></DashboardActionableChart>
</div>
<div class="flex gap-6 flex-col xl:flex-row p-6">
<CardTitled class="p-4 flex-[4] w-full h-full" title="Events" sub="Events stacked bar chart.">
@@ -213,6 +192,9 @@ const selectLabelsEvents = [
</div>
<div v-if="!ready || !project" class="flex justify-center py-40">
<i class="fas fa-spinner text-[2rem] text-accent animate-[spin_1s_linear_infinite] duration-500"></i>
</div>
</div>
</template>

View File

@@ -81,6 +81,33 @@ function handleOnError(errorResponse: any) {
alert('Error' + errorResponse);
};
function getRandomHex(size: number) {
const bytes = new Uint8Array(size);
window.crypto.getRandomValues(bytes);
return Array.from(bytes)
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
}
function githubLogin() {
const client_id = config.public.GITHUB_CLIENT_ID;
const redirect_uri = window.location.origin + '/api';
console.log({ redirect_uri })
const state = getRandomHex(16);
localStorage.setItem("latestCSRFToken", state);
const link = `https://github.com/login/oauth/authorize?client_id=${client_id}&response_type=code&scope=repo&redirect_uri=${redirect_uri}/integrations/github/oauth2/callback&state=${state}`;
window.location.assign(link);
}
const route = useRoute();
onMounted(() => {
if (route.query.github_access_token) {
//TODO: Something
}
})
</script>
@@ -103,23 +130,34 @@ function handleOnError(errorResponse: any) {
</div>
<div class="text-text/80 text-[1.2rem] text-center w-[70%] poppins mt-2">
Real-time analytics for 15+ JS/TS frameworks
Track web analytics and custom events
<br>
with one-line code setup.
with extreme simplicity in under 30 sec.
<br>
<div class="font-bold poppins mt-4">
<!-- <div class="font-bold poppins mt-4">
Start for Free now! Up to 3k visits/events monthly.
</div>
</div> -->
</div>
<div class="mt-12">
<div v-if="!isNoAuth" @click="login"
class="hover:bg-accent cursor-pointer flex text-[1.3rem] gap-4 items-center border-[1px] border-gray-400 rounded-lg px-8 py-3 relative z-[2]">
<div class="flex items-center">
<i class="fab fa-google"></i>
<div v-if="!isNoAuth" class="flex flex-col gap-2">
<div @click="login"
class="hover:bg-accent cursor-pointer flex text-[1.3rem] gap-4 items-center border-[1px] border-gray-400 rounded-lg px-8 py-3 relative z-[2]">
<div class="flex items-center">
<i class="fab fa-google"></i>
</div>
Continue with Google
</div>
<div
class=" opacity-35 cursor-not-allowed flex text-[1.3rem] gap-4 items-center border-[1px] border-gray-400 rounded-lg px-8 py-3 relative z-[2]">
<div class="flex items-center">
<i class="fab fa-github"></i>
</div>
Continue with GitHub
</div>
Continue with Google
</div>
<div v-if="isNoAuth" @click="loginWithoutAuth"
@@ -133,7 +171,7 @@ function handleOnError(errorResponse: any) {
</div>
<div class="text-[.9rem] poppins mt-12 text-text-sub text-center relative z-[2]">
By continuing you are indicating that you accept
By continuing you are accepting
<br>
our
<a class="underline" href="https://litlyx.com/terms" target="_blank">Terms of Service</a> and

View File

@@ -0,0 +1,122 @@
<script setup lang="ts">
definePageMeta({ layout: 'dashboard' });
const activeProjectId = useActiveProjectId();
const headers = computed(() => {
return {
'Authorization': authorizationHeaderComputed.value,
'x-pid': activeProjectId.data.value || ''
}
});
const reportList = useFetch(`/api/security/list`, { headers });
const { createAlert } = useAlert();
function showAnomalyInfoAlert() {
createAlert('AI Anomaly Detector info',
`Anomaly detector is running. It helps you detect a spike in visits or events, it could mean an
attack or simply higher traffic due to good performance. Additionally, it can detect if someone is
stealing parts of your website and hosting a duplicate version—an unfortunately common practice.
Litlyx will notify you via email with actionable advices`,
'far fa-shield',
10000
)
}
const rows = computed(() => reportList.data.value || [])
const columns = [
{ key: 'scan', label: 'Scan date' },
{ key: 'type', label: 'Type' },
{ key: 'data', label: 'Data' },
];
</script>
<template>
<div class="home w-full h-full px-10 pt-6 overflow-y-auto">
<div class="flex gap-2 items-center text-text/90 justify-end">
<div class="animate-pulse w-[1rem] h-[1rem] bg-green-400 rounded-full"> </div>
<div class="poppins font-regular text-[1rem]"> AI Anomaly Detector </div>
<div class="flex items-center">
<i class="far fa-info-circle text-[.9rem] hover:text-lyx-primary cursor-pointer"
@click="showAnomalyInfoAlert"></i>
</div>
</div>
<div class="pb-[10rem]">
<UTable :rows="rows" :columns="columns">
<template #scan-data="{ row }">
<div class="text-lyx-text-dark">
{{ new Date(row.data.created_at).toLocaleString() }}
</div>
</template>
<template #type-data="{ row }">
<UBadge color="white" class="w-[4rem] flex justify-center">
{{ row.type }}
</UBadge>
</template>
<template #data-data="{ row }">
<div class="text-lyx-text-dark">
<div v-if="row.type === 'domain'">
{{ row.data.domain }}
</div>
<div v-if="row.type === 'visit'">
{{ row.data.visit }}
</div>
<div v-if="row.type === 'event'">
{{ row.data.event }}
</div>
</div>
</template>
<!-- <template #actions-data="{ row }">
<UDropdown :items="items(row)">
<UButton color="gray" variant="ghost" icon="i-heroicons-ellipsis-horizontal-20-solid" />
</UDropdown>
</template> -->
</UTable>
</div>
<!-- <div class="w-full py-8 px-12 pb-[10rem]">
<div v-if="reportList.data.value" class="flex flex-col gap-2">
<div v-for="entry of reportList.data.value" class="flex flex-col gap-4">
<div v-if="entry.type === 'event'" class="flex gap-2 flex-col lg:flex-row items-center lg:items-start">
<div class="text-lyx-text-darker">{{ new Date(entry.data.created_at).toLocaleString() }}</div>
<UBadge class="w-[4rem] flex justify-center"> {{ entry.type }} </UBadge>
<div class="text-lyx-text-dark">
Event date: {{ new Date(entry.data.eventDate).toLocaleString() }}
</div>
</div>
<div v-if="entry.type === 'visit'" class="flex gap-2 flex-col lg:flex-row items-center lg:items-start">
<div class="text-lyx-text-darker">{{ new Date(entry.data.created_at).toLocaleString() }}</div>
<UBadge class="w-[4rem] flex justify-center"> {{ entry.type }} </UBadge>
<div class="text-lyx-text-dark">
Visit date: {{ new Date(entry.data.visitDate).toLocaleString() }}
</div>
</div>
<div v-if="entry.type === 'domain'" class="flex gap-2 flex-col py-2 lg:flex-row items-center lg:items-start">
<div class="text-lyx-text-darker">{{ new Date(entry.data.created_at).toLocaleString() }}</div>
<UBadge class="w-[4rem] flex justify-center"> {{ entry.type }} </UBadge>
<div class="text-lyx-text-dark">
{{ entry.data.domain }}
</div>
</div>
</div>
</div>
</div> -->
</div>
</template>

View File

@@ -3,6 +3,8 @@
definePageMeta({ layout: 'dashboard' });
const activeProject = useActiveProject();
const items = [
{ label: 'General', slot: 'general' },
{ label: 'Members', slot: 'members' },
@@ -18,32 +20,18 @@ const items = [
<CustomTab :items="items" class="mt-8">
<template #general>
<SettingsGeneral></SettingsGeneral>
<SettingsGeneral :key="activeProject?._id.toString()"></SettingsGeneral>
</template>
<template #members>
<SettingsMembers></SettingsMembers>
<SettingsMembers :key="activeProject?._id.toString()"></SettingsMembers>
</template>
<template #billing>
<SettingsBilling></SettingsBilling>
<SettingsBilling :key="activeProject?._id.toString()"></SettingsBilling>
</template>
<template #account>
<SettingsAccount></SettingsAccount>
<SettingsAccount :key="activeProject?._id.toString()"></SettingsAccount>
</template>
</CustomTab>
<!-- <UTabs :items="items" class="mt-8">
<template #general>
<SettingsGeneral></SettingsGeneral>
</template>
<template #members>
<SettingsMembers></SettingsMembers>
</template>
<template #billing>
<SettingsBilling></SettingsBilling>
</template>
<template #account>
<SettingsAccount></SettingsAccount>
</template>
</UTabs> -->
</div>
</template>

View File

@@ -0,0 +1,10 @@
import { Chart, registerables } from 'chart.js';
import annotaionPlugin from 'chartjs-plugin-annotation';
import 'chartjs-chart-funnel';
import { FunnelController, FunnelChart, TrapezoidElement } from 'chartjs-chart-funnel';
export default defineNuxtPlugin(() => {
Chart.register(...registerables, annotaionPlugin, FunnelController, FunnelChart, TrapezoidElement);
})

420
dashboard/pnpm-lock.yaml generated
View File

@@ -14,9 +14,18 @@ importers:
'@nuxtjs/tailwindcss':
specifier: ^6.12.0
version: 6.12.0(rollup@4.18.0)
'@supabase/supabase-js':
specifier: ^2.45.4
version: 2.45.4
chart.js:
specifier: ^3.9.1
version: 3.9.1
chartjs-chart-funnel:
specifier: ^4.2.1
version: 4.2.1(chart.js@3.9.1)
chartjs-plugin-annotation:
specifier: ^2.2.1
version: 2.2.1(chart.js@3.9.1)
date-fns:
specifier: ^3.6.0
version: 3.6.0
@@ -26,6 +35,9 @@ importers:
google-auth-library:
specifier: ^9.9.0
version: 9.10.0(encoding@0.1.13)
highlight.js:
specifier: ^11.10.0
version: 11.10.0
jsonwebtoken:
specifier: ^9.0.2
version: 9.0.2
@@ -45,8 +57,8 @@ importers:
specifier: ^0.0.11
version: 0.0.11(@types/node@20.12.12)(rollup@4.18.0)(typescript@5.4.2)(vite@5.2.12(@types/node@20.12.12)(sass@1.77.2)(terser@5.31.0))(vue@3.4.27(typescript@5.4.2))
openai:
specifier: ^4.47.1
version: 4.47.2(encoding@0.1.13)
specifier: ^4.61.0
version: 4.61.0(encoding@0.1.13)
pdfkit:
specifier: ^0.15.0
version: 0.15.0
@@ -71,9 +83,15 @@ importers:
vue-chart-3:
specifier: ^3.1.8
version: 3.1.8(chart.js@3.9.1)(vue@3.4.27(typescript@5.4.2))
vue-markdown-render:
specifier: ^2.2.1
version: 2.2.1(vue@3.4.27(typescript@5.4.2))
vue-router:
specifier: ^4.3.0
version: 4.3.2(vue@3.4.27(typescript@5.4.2))
winston:
specifier: ^3.14.2
version: 3.14.2
devDependencies:
'@nuxt/ui':
specifier: ^2.15.2
@@ -81,6 +99,9 @@ importers:
'@types/jsonwebtoken':
specifier: ^9.0.6
version: 9.0.6
'@types/markdown-it':
specifier: ^14.1.2
version: 14.1.2
'@types/nodemailer':
specifier: ^6.4.15
version: 6.4.15
@@ -304,6 +325,10 @@ packages:
resolution: {integrity: sha512-EeEjMobfuJrwoctj7FA1y1KEbM0+Q1xSjobIEyie9k4haVEBB7vkDvsasw1pM3rO39mL2akxIAzLMUAtrMHZhA==}
engines: {node: '>=16.13'}
'@colors/colors@1.6.0':
resolution: {integrity: sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==}
engines: {node: '>=0.1.90'}
'@csstools/selector-resolve-nested@1.1.0':
resolution: {integrity: sha512-uWvSaeRcHyeNenKg8tp17EVDRkpflmdyvbE0DHo6D/GdBb6PDnCYYU6gRpXhtICMGMcahQmj2zGxwFM/WC8hCg==}
engines: {node: ^14 || ^16 || >=18}
@@ -316,6 +341,9 @@ packages:
peerDependencies:
postcss-selector-parser: ^6.0.13
'@dabh/diagnostics@2.0.3':
resolution: {integrity: sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==}
'@egoist/tailwindcss-icons@1.8.0':
resolution: {integrity: sha512-75LfllKL2lq0sGH+wcpsn/sLtJ0kMkDWmcZTLAB76QLDTmfsFu4QHwZVbtCD2woGyKl9c8KvtOUW9JSjRqOVtA==}
peerDependencies:
@@ -1113,6 +1141,28 @@ packages:
resolution: {integrity: sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg==}
engines: {node: '>=18'}
'@supabase/auth-js@2.65.0':
resolution: {integrity: sha512-+wboHfZufAE2Y612OsKeVP4rVOeGZzzMLD/Ac3HrTQkkY4qXNjI6Af9gtmxwccE5nFvTiF114FEbIQ1hRq5uUw==}
'@supabase/functions-js@2.4.1':
resolution: {integrity: sha512-8sZ2ibwHlf+WkHDUZJUXqqmPvWQ3UHN0W30behOJngVh/qHHekhJLCFbh0AjkE9/FqqXtf9eoVvmYgfCLk5tNA==}
'@supabase/node-fetch@2.6.15':
resolution: {integrity: sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==}
engines: {node: 4.x || >=6.0.0}
'@supabase/postgrest-js@1.16.1':
resolution: {integrity: sha512-EOSEZFm5pPuCPGCmLF1VOCS78DfkSz600PBuvBND/IZmMciJ1pmsS3ss6TkB6UkuvTybYiBh7gKOYyxoEO3USA==}
'@supabase/realtime-js@2.10.2':
resolution: {integrity: sha512-qyCQaNg90HmJstsvr2aJNxK2zgoKh9ZZA8oqb7UT2LCh3mj9zpa3Iwu167AuyNxsxrUE8eEJ2yH6wLCij4EApA==}
'@supabase/storage-js@2.7.0':
resolution: {integrity: sha512-iZenEdO6Mx9iTR6T7wC7sk6KKsoDPLq8rdu5VRy7+JiT1i8fnqfcOr6mfF2Eaqky9VQzhP8zZKQYjzozB65Rig==}
'@supabase/supabase-js@2.45.4':
resolution: {integrity: sha512-E5p8/zOLaQ3a462MZnmnz03CrduA5ySH9hZyL03Y+QZLIOO4/Gs8Rdy4ZCKDHsN7x0xdanVEWWFN3pJFQr9/hg==}
'@swc/helpers@0.3.17':
resolution: {integrity: sha512-tb7Iu+oZ+zWJZ3HJqwx8oNwSDIU440hmVMDPhpACWQWnrZHK99Bxs70gT1L2dnr5Hg50ZRWEFkQCAnOVVV0z1Q==}
@@ -1159,6 +1209,9 @@ packages:
'@types/argparse@1.0.38':
resolution: {integrity: sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA==}
'@types/chroma-js@2.4.4':
resolution: {integrity: sha512-/DTccpHTaKomqussrn+ciEvfW4k6NAHzNzs/sts1TCqg333qNxOhy8TNIoQCmbGG3Tl8KdEhkGAssb1n3mTXiQ==}
'@types/estree@1.0.5':
resolution: {integrity: sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==}
@@ -1168,9 +1221,18 @@ packages:
'@types/jsonwebtoken@9.0.6':
resolution: {integrity: sha512-/5hndP5dCjloafCXns6SZyESp3Ldq7YjH3zwzwczYnjxIT0Fqzk5ROSYVGfFyczIue7IUEj8hkvLbPoLQ18vQw==}
'@types/linkify-it@5.0.0':
resolution: {integrity: sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==}
'@types/lodash@4.17.7':
resolution: {integrity: sha512-8wTvZawATi/lsmNu10/j2hk1KEP0IvjubqPE3cu1Xz7xfXXt5oCq3SNUz4fMIP4XGF9Ky+Ue2tBA3hcS7LSBlA==}
'@types/markdown-it@14.1.2':
resolution: {integrity: sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==}
'@types/mdurl@2.0.0':
resolution: {integrity: sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==}
'@types/node-fetch@2.6.11':
resolution: {integrity: sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==}
@@ -1186,12 +1248,21 @@ packages:
'@types/pdfkit@0.13.4':
resolution: {integrity: sha512-ixGNDHYJCCKuamY305wbfYSphZ2WPe8FPkjn8oF4fHV+PgPV4V+hecPh2VOS2h4RNtpSB3zQcR4sCpNvvrEb1A==}
'@types/phoenix@1.6.5':
resolution: {integrity: sha512-xegpDuR+z0UqG9fwHqNoy3rI7JDlvaPh2TY47Fl80oq6g+hXT+c/LEuE43X48clZ6lOfANl5WrPur9fYO1RJ/w==}
'@types/qs@6.9.16':
resolution: {integrity: sha512-7i+zxXdPD0T4cKDuxCUXJ4wHcsJLwENa6Z3dCu8cfCK743OGy5Nu1RmAGqDPsoTDINVEcdXKRvR/zre+P2Ku1A==}
'@types/resize-observer-browser@0.1.11':
resolution: {integrity: sha512-cNw5iH8JkMkb3QkCoe7DaZiawbDQEUX8t7iuQaRTyLOyQCR2h+ibBD4GJt7p5yhUHrlOeL7ZtbxNHeipqNsBzQ==}
'@types/resolve@1.20.2':
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
'@types/triple-beam@1.3.5':
resolution: {integrity: sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==}
'@types/web-bluetooth@0.0.20':
resolution: {integrity: sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow==}
@@ -1201,6 +1272,9 @@ packages:
'@types/whatwg-url@11.0.5':
resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==}
'@types/ws@8.5.12':
resolution: {integrity: sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ==}
'@ungap/structured-clone@1.2.0':
resolution: {integrity: sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==}
@@ -1425,20 +1499,20 @@ packages:
'@vue/reactivity@3.4.27':
resolution: {integrity: sha512-kK0g4NknW6JX2yySLpsm2jlunZJl2/RJGZ0H9ddHdfBVHcNzxmQ0sS0b09ipmBoQpY8JM2KmUw+a6sO8Zo+zIA==}
'@vue/reactivity@3.4.38':
resolution: {integrity: sha512-4vl4wMMVniLsSYYeldAKzbk72+D3hUnkw9z8lDeJacTxAkXeDAP1uE9xr2+aKIN0ipOL8EG2GPouVTH6yF7Gnw==}
'@vue/reactivity@3.5.8':
resolution: {integrity: sha512-mlgUyFHLCUZcAYkqvzYnlBRCh0t5ZQfLYit7nukn1GR96gc48Bp4B7OIcSfVSvlG1k3BPfD+p22gi1t2n9tsXg==}
'@vue/runtime-core@3.4.27':
resolution: {integrity: sha512-7aYA9GEbOOdviqVvcuweTLe5Za4qBZkUY7SvET6vE8kyypxVgaT1ixHLg4urtOlrApdgcdgHoTZCUuTGap/5WA==}
'@vue/runtime-core@3.4.38':
resolution: {integrity: sha512-21z3wA99EABtuf+O3IhdxP0iHgkBs1vuoCAsCKLVJPEjpVqvblwBnTj42vzHRlWDCyxu9ptDm7sI2ZMcWrQqlA==}
'@vue/runtime-core@3.5.8':
resolution: {integrity: sha512-fJuPelh64agZ8vKkZgp5iCkPaEqFJsYzxLk9vSC0X3G8ppknclNDr61gDc45yBGTaN5Xqc1qZWU3/NoaBMHcjQ==}
'@vue/runtime-dom@3.4.27':
resolution: {integrity: sha512-ScOmP70/3NPM+TW9hvVAz6VWWtZJqkbdf7w6ySsws+EsqtHvkhxaWLecrTorFxsawelM5Ys9FnDEMt6BPBDS0Q==}
'@vue/runtime-dom@3.4.38':
resolution: {integrity: sha512-afZzmUreU7vKwKsV17H1NDThEEmdYI+GCAK/KY1U957Ig2NATPVjCROv61R19fjZNzMmiU03n79OMnXyJVN0UA==}
'@vue/runtime-dom@3.5.8':
resolution: {integrity: sha512-DpAUz+PKjTZPUOB6zJgkxVI3GuYc2iWZiNeeHQUw53kdrparSTG6HeXUrYDjaam8dVsCdvQxDz6ZWxnyjccUjQ==}
'@vue/server-renderer@3.4.27':
resolution: {integrity: sha512-dlAMEuvmeA3rJsOMJ2J1kXU7o7pOxgsNHVr9K8hB3ImIkSuBrIdy0vF66h8gf8Tuinf1TK3mPAz2+2sqyf3KzA==}
@@ -1448,11 +1522,8 @@ packages:
'@vue/shared@3.4.27':
resolution: {integrity: sha512-DL3NmY2OFlqmYYrzp39yi3LDkKxa5vZVwxWdQ3rG0ekuWscHraeIbnI8t+aZK7qhYqEqWKTUdijadunb9pnrgA==}
'@vue/shared@3.4.34':
resolution: {integrity: sha512-x5LmiRLpRsd9KTjAB8MPKf0CDPMcuItjP0gbNqFCIgL1I8iYp4zglhj9w9FPCdIbHG2M91RVeIbArFfFTz9I3A==}
'@vue/shared@3.4.38':
resolution: {integrity: sha512-q0xCiLkuWWQLzVrecPb0RMsNWyxICOjPrcrwxTUEHb1fsnvni4dcuyG7RT/Ie7VPTvnjzIaWzRMUBsrqNj/hhw==}
'@vue/shared@3.5.8':
resolution: {integrity: sha512-mJleSWbAGySd2RJdX1RBtcrUBX6snyOc0qHpgk3lGi4l9/P/3ny3ELqFWqYdkXIwwNN/kdm8nD9ky8o6l/Lx2A==}
'@vueuse/components@10.10.0':
resolution: {integrity: sha512-HiA10NQ9HJAGnju+8ZK4TyA8LIc0a6BnJmVWDa/k+TRhaYCVacSDU04k0BQ2otV+gghUDdwu98upf6TDRXpoeg==}
@@ -1826,6 +1897,16 @@ packages:
chart.js@3.9.1:
resolution: {integrity: sha512-Ro2JbLmvg83gXF5F4sniaQ+lTbSv18E+TIf2cOeiH1Iqd2PGFOtem+DUufMZsCJwFE7ywPOpfXFBwRTGq7dh6w==}
chartjs-chart-funnel@4.2.1:
resolution: {integrity: sha512-S1eqYMDXefl7k7uuQc5MA83ZS9zjclt4bbYXbmPJ5GEvB6HMBb7tt892R62AtzoKXbt/VfDNy9Sq3L785sWvdQ==}
peerDependencies:
chart.js: '>=3.7.0'
chartjs-plugin-annotation@2.2.1:
resolution: {integrity: sha512-RL9UtrFr2SXd7C47zD0MZqn6ZLgrcRt3ySC6cYal2amBdANcYB1QcwFXcpKWAYnO4SGJYRok7P5rKDDNgJMA/w==}
peerDependencies:
chart.js: '>=3.7.0'
check-error@1.0.3:
resolution: {integrity: sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==}
@@ -1837,6 +1918,9 @@ packages:
resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==}
engines: {node: '>=10'}
chroma-js@2.6.0:
resolution: {integrity: sha512-BLHvCB9s8Z1EV4ethr6xnkl/P2YRFOGqfgvuMG/MyCbZPrTA+NeiByY6XvgF0zP4/2deU2CXnWyMa3zu1LqQ3A==}
ci-info@4.0.0:
resolution: {integrity: sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg==}
engines: {node: '>=8'}
@@ -1884,16 +1968,25 @@ packages:
color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
color-string@1.9.1:
resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==}
color-support@1.1.3:
resolution: {integrity: sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==}
hasBin: true
color@3.2.1:
resolution: {integrity: sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==}
colord@2.9.3:
resolution: {integrity: sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==}
colorette@2.0.20:
resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}
colorspace@1.1.4:
resolution: {integrity: sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==}
combined-stream@1.0.8:
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
@@ -2264,6 +2357,9 @@ packages:
emoji-regex@9.2.2:
resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
enabled@2.0.0:
resolution: {integrity: sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==}
encodeurl@1.0.2:
resolution: {integrity: sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==}
engines: {node: '>= 0.8'}
@@ -2275,6 +2371,10 @@ packages:
resolution: {integrity: sha512-4U5pNsuDl0EhuZpq46M5xPslstkviJuhrdobaRDBk2Jy2KO37FDAJl4lb2KlNabxT0m4MTK2UHNrsAcphE8nyw==}
engines: {node: '>=10.13.0'}
entities@3.0.1:
resolution: {integrity: sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q==}
engines: {node: '>=0.12'}
entities@4.5.0:
resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
engines: {node: '>=0.12'}
@@ -2419,6 +2519,9 @@ packages:
fastq@1.17.1:
resolution: {integrity: sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==}
fecha@4.2.3:
resolution: {integrity: sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==}
file-entry-cache@6.0.1:
resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}
engines: {node: ^10.12.0 || >=12.0.0}
@@ -2450,6 +2553,9 @@ packages:
'@nuxt/kit':
optional: true
fn.name@1.1.0:
resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==}
focus-trap@7.5.4:
resolution: {integrity: sha512-N7kHdlgsO/v+iD/dMoJKtsSqs5Dz/dXZVebRgJw23LDk+jMi/974zyiOYDziY2JPp8xivq9BmUGwIJMiuSBi7w==}
@@ -2701,6 +2807,10 @@ packages:
resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}
hasBin: true
highlight.js@11.10.0:
resolution: {integrity: sha512-SYVnVFswQER+zu1laSya563s+F8VDGt7o35d4utbamowvUNLLMovFqwCLSocpZTz3MgaSRA1IbqRWZv97dtErQ==}
engines: {node: '>=12.0.0'}
hookable@5.5.3:
resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}
@@ -2846,6 +2956,9 @@ packages:
resolution: {integrity: sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==}
engines: {node: '>= 0.4'}
is-arrayish@0.3.2:
resolution: {integrity: sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==}
is-bigint@1.0.4:
resolution: {integrity: sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==}
@@ -3146,6 +3259,9 @@ packages:
kolorist@1.8.0:
resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}
kuler@2.0.0:
resolution: {integrity: sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==}
launch-editor@2.6.1:
resolution: {integrity: sha512-eB/uXmFVpY4zezmGp5XtU21kwo7GBbKB+EQ+UZeWtGb9yAM5xt/Evk+lYH3eRNAtId+ej4u7TYPFZ07w4s7rRw==}
@@ -3171,6 +3287,9 @@ packages:
lines-and-columns@1.2.4:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
linkify-it@4.0.1:
resolution: {integrity: sha512-C7bfi1UZmoj8+PQx22XyeXCuBlokoyWQL5pWSP+EI6nzRylyThouddufc2c1NDIcP9k5agmN9fLpA7VNJfIiqw==}
listhen@1.7.2:
resolution: {integrity: sha512-7/HamOm5YD9Wb7CFgAZkKgVPA96WwhcTQoqtm2VTZGVbVVn3IWKRBTgrU7cchA3Q8k9iCsG8Osoi9GX4JsGM9g==}
hasBin: true
@@ -3241,6 +3360,10 @@ packages:
lodash@4.17.21:
resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}
logform@2.6.1:
resolution: {integrity: sha512-CdaO738xRapbKIMVn2m4F6KTj4j7ooJ8POVnebSgKo3KBz5axNXRAL7ZdRjIV6NOr2Uf4vjtRkxrFETOioCqSA==}
engines: {node: '>= 12.0.0'}
loupe@2.3.7:
resolution: {integrity: sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==}
@@ -3273,12 +3396,19 @@ packages:
resolution: {integrity: sha512-cKTUFc/rbKUd/9meOvgrpJ2WrNzymt6jfRDdwg5UCnVzv9dTpEj9JS5m3wtziXVCjluIXyL8pcaukYqezIzZQA==}
engines: {node: ^16.14.0 || >=18.0.0}
markdown-it@13.0.2:
resolution: {integrity: sha512-FtwnEuuK+2yVU7goGn/MJ0WBZMM9ZPgU9spqlFs7/A/pDIUNSOQZhUgOqYCficIuR2QaFnrt8LHqBWsbTAoI5w==}
hasBin: true
mdn-data@2.0.28:
resolution: {integrity: sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==}
mdn-data@2.0.30:
resolution: {integrity: sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==}
mdurl@1.0.1:
resolution: {integrity: sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==}
media-typer@0.3.0:
resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==}
engines: {node: '>= 0.6'}
@@ -3676,6 +3806,9 @@ packages:
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
one-time@1.0.0:
resolution: {integrity: sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==}
onetime@5.1.2:
resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}
engines: {node: '>=6'}
@@ -3699,9 +3832,14 @@ packages:
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
engines: {node: '>=12'}
openai@4.47.2:
resolution: {integrity: sha512-E3Wq9mYdDSLajmcJm9RO/lCegTKrQ7ilAkMbhob4UgGhTjHwIHI+mXNDNPl5+sGIUp2iVUkpoi772FjYa7JlqA==}
openai@4.61.0:
resolution: {integrity: sha512-xkygRBRLIUumxzKGb1ug05pWmJROQsHkGuj/N6Jiw2dj0dI19JvbFpErSZKmJ/DA+0IvpcugZqCAyk8iLpyM6Q==}
hasBin: true
peerDependencies:
zod: ^3.23.8
peerDependenciesMeta:
zod:
optional: true
openapi-typescript@6.7.6:
resolution: {integrity: sha512-c/hfooPx+RBIOPM09GSxABOZhYPblDoyaGhqBkD/59vtpN21jEuWKDlM0KYTvqJVlSYjKs0tBcIdeXKChlSPtw==}
@@ -4253,6 +4391,10 @@ packages:
safe-buffer@5.2.1:
resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}
safe-stable-stringify@2.5.0:
resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==}
engines: {node: '>=10'}
safer-buffer@2.1.2:
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
@@ -4347,6 +4489,9 @@ packages:
simple-git@3.24.0:
resolution: {integrity: sha512-QqAKee9Twv+3k8IFOFfPB2hnk6as6Y6ACUpwCtQvRYBAes23Wv3SZlHVobAzqcE8gfsisCvPw3HGW3HYM+VYYw==}
simple-swizzle@0.2.2:
resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==}
sirv@2.0.4:
resolution: {integrity: sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ==}
engines: {node: '>= 10'}
@@ -4429,6 +4574,9 @@ packages:
resolution: {integrity: sha512-MGrFH9Z4NP9Iyhqn16sDtBpRRNJ0Y2hNa6D65h736fVSaPCHr4DM4sWUNvVaSuC+0OBGhwsrydQwmgfg5LncqQ==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
stack-trace@0.0.10:
resolution: {integrity: sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==}
stackback@0.0.2:
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
@@ -4575,6 +4723,9 @@ packages:
engines: {node: '>=10'}
hasBin: true
text-hex@1.0.0:
resolution: {integrity: sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==}
text-table@0.2.0:
resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==}
@@ -4629,6 +4780,10 @@ packages:
resolution: {integrity: sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==}
engines: {node: '>=14'}
triple-beam@1.4.1:
resolution: {integrity: sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==}
engines: {node: '>= 14.0.0'}
ts-interface-checker@0.1.13:
resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}
@@ -4678,6 +4833,9 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
uc.micro@1.0.6:
resolution: {integrity: sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==}
ufo@1.5.3:
resolution: {integrity: sha512-Y7HYmWaFwPUmkoQCUIAYpKqkOf+SbVj/2fJJZ4RJMCfZp0rTGwRbzQD+HghfnhKOjL9E01okqz+ncJskGYfBNw==}
@@ -5032,6 +5190,11 @@ packages:
vue-devtools-stub@0.1.0:
resolution: {integrity: sha512-RutnB7X8c5hjq39NceArgXg28WZtZpGc3+J16ljMiYnFhKvd8hITxSWQSQ5bvldxMDU6gG5mkxl1MTQLXckVSQ==}
vue-markdown-render@2.2.1:
resolution: {integrity: sha512-XkYnC0PMdbs6Vy6j/gZXSvCuOS0787Se5COwXlepRqiqPiunyCIeTPQAO2XnB4Yl04EOHXwLx5y6IuszMWSgyQ==}
peerDependencies:
vue: ^3.3.4
vue-observe-visibility@2.0.0-alpha.1:
resolution: {integrity: sha512-flFbp/gs9pZniXR6fans8smv1kDScJ8RS7rEpMjhVabiKeq7Qz3D9+eGsypncjfIyyU84saU88XZ0zjbD6Gq/g==}
peerDependencies:
@@ -5079,10 +5242,6 @@ packages:
typescript:
optional: true
web-streams-polyfill@3.3.3:
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
web-streams-polyfill@4.0.0-beta.3:
resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}
engines: {node: '>= 14'}
@@ -5142,6 +5301,14 @@ packages:
wide-align@1.1.5:
resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==}
winston-transport@4.7.1:
resolution: {integrity: sha512-wQCXXVgfv/wUPOfb2x0ruxzwkcZfxcktz6JIMUaPLmcNhO4bZTwA/WtDWK74xV3F2dKu8YadrFv0qhwYjVEwhA==}
engines: {node: '>= 12.0.0'}
winston@3.14.2:
resolution: {integrity: sha512-CO8cdpBB2yqzEf8v895L+GNKYJiEq8eKlHU38af3snQBQ+sdAIUepjMSguOIJC7ICbzm0ZI+Af2If4vIJrtmOg==}
engines: {node: '>= 12.0.0'}
word-wrap@1.2.5:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
@@ -5463,6 +5630,8 @@ snapshots:
dependencies:
mime: 3.0.0
'@colors/colors@1.6.0': {}
'@csstools/selector-resolve-nested@1.1.0(postcss-selector-parser@6.1.0)':
dependencies:
postcss-selector-parser: 6.1.0
@@ -5471,6 +5640,12 @@ snapshots:
dependencies:
postcss-selector-parser: 6.1.0
'@dabh/diagnostics@2.0.3':
dependencies:
colorspace: 1.1.4
enabled: 2.0.0
kuler: 2.0.0
'@egoist/tailwindcss-icons@1.8.0(tailwindcss@3.4.3)':
dependencies:
'@iconify/utils': 2.1.23
@@ -6485,6 +6660,48 @@ snapshots:
'@sindresorhus/merge-streams@2.3.0': {}
'@supabase/auth-js@2.65.0':
dependencies:
'@supabase/node-fetch': 2.6.15
'@supabase/functions-js@2.4.1':
dependencies:
'@supabase/node-fetch': 2.6.15
'@supabase/node-fetch@2.6.15':
dependencies:
whatwg-url: 5.0.0
'@supabase/postgrest-js@1.16.1':
dependencies:
'@supabase/node-fetch': 2.6.15
'@supabase/realtime-js@2.10.2':
dependencies:
'@supabase/node-fetch': 2.6.15
'@types/phoenix': 1.6.5
'@types/ws': 8.5.12
ws: 8.17.0
transitivePeerDependencies:
- bufferutil
- utf-8-validate
'@supabase/storage-js@2.7.0':
dependencies:
'@supabase/node-fetch': 2.6.15
'@supabase/supabase-js@2.45.4':
dependencies:
'@supabase/auth-js': 2.65.0
'@supabase/functions-js': 2.4.1
'@supabase/node-fetch': 2.6.15
'@supabase/postgrest-js': 1.16.1
'@supabase/realtime-js': 2.10.2
'@supabase/storage-js': 2.7.0
transitivePeerDependencies:
- bufferutil
- utf-8-validate
'@swc/helpers@0.3.17':
dependencies:
tslib: 2.6.2
@@ -6528,6 +6745,8 @@ snapshots:
'@types/argparse@1.0.38': {}
'@types/chroma-js@2.4.4': {}
'@types/estree@1.0.5': {}
'@types/http-proxy@1.17.14':
@@ -6538,11 +6757,20 @@ snapshots:
dependencies:
'@types/node': 20.12.12
'@types/linkify-it@5.0.0': {}
'@types/lodash@4.17.7': {}
'@types/markdown-it@14.1.2':
dependencies:
'@types/linkify-it': 5.0.0
'@types/mdurl': 2.0.0
'@types/mdurl@2.0.0': {}
'@types/node-fetch@2.6.11':
dependencies:
'@types/node': 18.19.33
'@types/node': 20.12.12
form-data: 4.0.0
'@types/node@18.19.33':
@@ -6561,10 +6789,16 @@ snapshots:
dependencies:
'@types/node': 20.12.12
'@types/phoenix@1.6.5': {}
'@types/qs@6.9.16': {}
'@types/resize-observer-browser@0.1.11': {}
'@types/resolve@1.20.2': {}
'@types/triple-beam@1.3.5': {}
'@types/web-bluetooth@0.0.20': {}
'@types/webidl-conversions@7.0.3': {}
@@ -6573,6 +6807,10 @@ snapshots:
dependencies:
'@types/webidl-conversions': 7.0.3
'@types/ws@8.5.12':
dependencies:
'@types/node': 20.12.12
'@ungap/structured-clone@1.2.0': {}
'@unhead/dom@1.9.11':
@@ -6990,7 +7228,7 @@ snapshots:
'@volar/language-core': 1.11.1
'@volar/source-map': 1.11.1
'@vue/compiler-dom': 3.4.27
'@vue/shared': 3.4.34
'@vue/shared': 3.5.8
computeds: 0.0.1
minimatch: 9.0.4
muggle-string: 0.3.1
@@ -7003,19 +7241,19 @@ snapshots:
dependencies:
'@vue/shared': 3.4.27
'@vue/reactivity@3.4.38':
'@vue/reactivity@3.5.8':
dependencies:
'@vue/shared': 3.4.38
'@vue/shared': 3.5.8
'@vue/runtime-core@3.4.27':
dependencies:
'@vue/reactivity': 3.4.27
'@vue/shared': 3.4.27
'@vue/runtime-core@3.4.38':
'@vue/runtime-core@3.5.8':
dependencies:
'@vue/reactivity': 3.4.38
'@vue/shared': 3.4.38
'@vue/reactivity': 3.5.8
'@vue/shared': 3.5.8
'@vue/runtime-dom@3.4.27':
dependencies:
@@ -7023,11 +7261,11 @@ snapshots:
'@vue/shared': 3.4.27
csstype: 3.1.3
'@vue/runtime-dom@3.4.38':
'@vue/runtime-dom@3.5.8':
dependencies:
'@vue/reactivity': 3.4.38
'@vue/runtime-core': 3.4.38
'@vue/shared': 3.4.38
'@vue/reactivity': 3.5.8
'@vue/runtime-core': 3.5.8
'@vue/shared': 3.5.8
csstype: 3.1.3
'@vue/server-renderer@3.4.27(vue@3.4.27(typescript@5.4.2))':
@@ -7038,9 +7276,7 @@ snapshots:
'@vue/shared@3.4.27': {}
'@vue/shared@3.4.34': {}
'@vue/shared@3.4.38': {}
'@vue/shared@3.5.8': {}
'@vueuse/components@10.10.0(vue@3.4.27(typescript@5.4.2))':
dependencies:
@@ -7429,6 +7665,16 @@ snapshots:
chart.js@3.9.1: {}
chartjs-chart-funnel@4.2.1(chart.js@3.9.1):
dependencies:
'@types/chroma-js': 2.4.4
chart.js: 3.9.1
chroma-js: 2.6.0
chartjs-plugin-annotation@2.2.1(chart.js@3.9.1):
dependencies:
chart.js: 3.9.1
check-error@1.0.3:
dependencies:
get-func-name: 2.0.2
@@ -7447,6 +7693,8 @@ snapshots:
chownr@2.0.0: {}
chroma-js@2.6.0: {}
ci-info@4.0.0: {}
citty@0.1.6:
@@ -7487,12 +7735,27 @@ snapshots:
color-name@1.1.4: {}
color-string@1.9.1:
dependencies:
color-name: 1.1.4
simple-swizzle: 0.2.2
color-support@1.1.3: {}
color@3.2.1:
dependencies:
color-convert: 1.9.3
color-string: 1.9.1
colord@2.9.3: {}
colorette@2.0.20: {}
colorspace@1.1.4:
dependencies:
color: 3.2.1
text-hex: 1.0.0
combined-stream@1.0.8:
dependencies:
delayed-stream: 1.0.0
@@ -7815,6 +8078,8 @@ snapshots:
emoji-regex@9.2.2: {}
enabled@2.0.0: {}
encodeurl@1.0.2: {}
encoding@0.1.13:
@@ -7827,6 +8092,8 @@ snapshots:
graceful-fs: 4.2.11
tapable: 2.2.1
entities@3.0.1: {}
entities@4.5.0: {}
env-paths@2.2.1: {}
@@ -8038,6 +8305,8 @@ snapshots:
dependencies:
reusify: 1.0.4
fecha@4.2.3: {}
file-entry-cache@6.0.1:
dependencies:
flat-cache: 3.2.0
@@ -8069,6 +8338,8 @@ snapshots:
optionalDependencies:
'@nuxt/kit': 3.11.2(rollup@4.18.0)
fn.name@1.1.0: {}
focus-trap@7.5.4:
dependencies:
tabbable: 6.2.0
@@ -8374,6 +8645,8 @@ snapshots:
he@1.2.0: {}
highlight.js@11.10.0: {}
hookable@5.5.3: {}
hosted-git-info@7.0.2:
@@ -8531,6 +8804,8 @@ snapshots:
call-bind: 1.0.7
get-intrinsic: 1.2.4
is-arrayish@0.3.2: {}
is-bigint@1.0.4:
dependencies:
has-bigints: 1.0.2
@@ -8829,6 +9104,8 @@ snapshots:
kolorist@1.8.0: {}
kuler@2.0.0: {}
launch-editor@2.6.1:
dependencies:
picocolors: 1.0.1
@@ -8854,6 +9131,10 @@ snapshots:
lines-and-columns@1.2.4: {}
linkify-it@4.0.1:
dependencies:
uc.micro: 1.0.6
listhen@1.7.2:
dependencies:
'@parcel/watcher': 2.4.1
@@ -8924,6 +9205,15 @@ snapshots:
lodash@4.17.21: {}
logform@2.6.1:
dependencies:
'@colors/colors': 1.6.0
'@types/triple-beam': 1.3.5
fecha: 4.2.3
ms: 2.1.3
safe-stable-stringify: 2.5.0
triple-beam: 1.4.1
loupe@2.3.7:
dependencies:
get-func-name: 2.0.2
@@ -8973,10 +9263,20 @@ snapshots:
transitivePeerDependencies:
- supports-color
markdown-it@13.0.2:
dependencies:
argparse: 2.0.1
entities: 3.0.1
linkify-it: 4.0.1
mdurl: 1.0.1
uc.micro: 1.0.6
mdn-data@2.0.28: {}
mdn-data@2.0.30: {}
mdurl@1.0.1: {}
media-typer@0.3.0: {}
memory-pager@1.5.0: {}
@@ -9550,6 +9850,10 @@ snapshots:
dependencies:
wrappy: 1.0.2
one-time@1.0.0:
dependencies:
fn.name: 1.1.0
onetime@5.1.2:
dependencies:
mimic-fn: 2.1.0
@@ -9578,16 +9882,17 @@ snapshots:
is-docker: 2.2.1
is-wsl: 2.2.0
openai@4.47.2(encoding@0.1.13):
openai@4.61.0(encoding@0.1.13):
dependencies:
'@types/node': 18.19.33
'@types/node-fetch': 2.6.11
'@types/qs': 6.9.16
abort-controller: 3.0.0
agentkeepalive: 4.5.0
form-data-encoder: 1.7.2
formdata-node: 4.4.1
node-fetch: 2.7.0(encoding@0.1.13)
web-streams-polyfill: 3.3.3
qs: 6.12.1
transitivePeerDependencies:
- encoding
@@ -10163,6 +10468,8 @@ snapshots:
safe-buffer@5.2.1: {}
safe-stable-stringify@2.5.0: {}
safer-buffer@2.1.2: {}
sass@1.77.2:
@@ -10284,6 +10591,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
simple-swizzle@0.2.2:
dependencies:
is-arrayish: 0.3.2
sirv@2.0.4:
dependencies:
'@polka/url': 1.0.0-next.25
@@ -10366,6 +10677,8 @@ snapshots:
dependencies:
minipass: 7.1.2
stack-trace@0.0.10: {}
stackback@0.0.2: {}
standard-as-callback@2.1.0: {}
@@ -10549,6 +10862,8 @@ snapshots:
commander: 2.20.3
source-map-support: 0.5.21
text-hex@1.0.0: {}
text-table@0.2.0: {}
thenify-all@1.6.0:
@@ -10590,6 +10905,8 @@ snapshots:
dependencies:
punycode: 2.3.1
triple-beam@1.4.1: {}
ts-interface-checker@0.1.13: {}
tslib@2.6.2: {}
@@ -10629,6 +10946,8 @@ snapshots:
typescript@5.4.2: {}
uc.micro@1.0.6: {}
ufo@1.5.3: {}
ultrahtml@1.5.3: {}
@@ -11028,8 +11347,8 @@ snapshots:
vue-chart-3@3.1.8(chart.js@3.9.1)(vue@3.4.27(typescript@5.4.2)):
dependencies:
'@vue/runtime-core': 3.4.38
'@vue/runtime-dom': 3.4.38
'@vue/runtime-core': 3.5.8
'@vue/runtime-dom': 3.5.8
chart.js: 3.9.1
csstype: 3.1.3
lodash-es: 4.17.21
@@ -11041,6 +11360,11 @@ snapshots:
vue-devtools-stub@0.1.0: {}
vue-markdown-render@2.2.1(vue@3.4.27(typescript@5.4.2)):
dependencies:
markdown-it: 13.0.2
vue: 3.4.27(typescript@5.4.2)
vue-observe-visibility@2.0.0-alpha.1(vue@3.4.27(typescript@5.4.2)):
dependencies:
vue: 3.4.27(typescript@5.4.2)
@@ -11098,8 +11422,6 @@ snapshots:
optionalDependencies:
typescript: 5.4.2
web-streams-polyfill@3.3.3: {}
web-streams-polyfill@4.0.0-beta.3: {}
webidl-conversions@3.0.1: {}
@@ -11164,6 +11486,26 @@ snapshots:
dependencies:
string-width: 4.2.3
winston-transport@4.7.1:
dependencies:
logform: 2.6.1
readable-stream: 3.6.2
triple-beam: 1.4.1
winston@3.14.2:
dependencies:
'@colors/colors': 1.6.0
'@dabh/diagnostics': 2.0.3
async: 3.2.5
is-stream: 2.0.1
logform: 2.6.1
one-time: 1.0.0
readable-stream: 3.6.2
safe-stable-stringify: 2.5.0
stack-trace: 0.0.10
triple-beam: 1.4.1
winston-transport: 4.7.1
word-wrap@1.2.5: {}
wrap-ansi@7.0.0:

View File

@@ -0,0 +1,15 @@
<svg width="98" height="100" viewBox="0 0 98 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M56.8944 98.338C54.3397 101.555 49.1599 99.7924 49.0983 95.6846L48.1982 35.6025H88.5973C95.9147 35.6025 99.9957 44.0542 95.4457 49.7849L56.8944 98.338Z" fill="url(#paint0_linear_99_24683)"/>
<path d="M56.8944 98.338C54.3397 101.555 49.1599 99.7924 49.0983 95.6846L48.1982 35.6025H88.5973C95.9147 35.6025 99.9957 44.0542 95.4457 49.7849L56.8944 98.338Z" fill="url(#paint1_linear_99_24683)" fill-opacity="0.2"/>
<path d="M40.464 1.66109C43.0187 -1.55638 48.1986 0.206562 48.2601 4.31445L48.6546 64.3964H8.76106C1.44348 64.3964 -2.63767 55.9448 1.91262 50.214L40.464 1.66109Z" fill="#3ECF8E"/>
<defs>
<linearGradient id="paint0_linear_99_24683" x1="48.1982" y1="48.9242" x2="84.1036" y2="63.9829" gradientUnits="userSpaceOnUse">
<stop stop-color="#249361"/>
<stop offset="1" stop-color="#3ECF8E"/>
</linearGradient>
<linearGradient id="paint1_linear_99_24683" x1="32.2797" y1="27.1289" x2="48.6544" y2="57.9534" gradientUnits="userSpaceOnUse">
<stop/>
<stop offset="1" stop-opacity="0"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -4,18 +4,22 @@ import { LITLYX_PROJECT_ID } from '@data/LITLYX'
import { hasAccessToProject } from "./utils/hasAccessToProject";
export async function getUserProjectFromId(project_id: string, user: AuthContext | undefined, allowGuest: boolean = true) {
if (project_id == LITLYX_PROJECT_ID) {
const project = await ProjectModel.findOne({ _id: project_id });
return project;
} else {
if (!user?.logged) return;
const project = await ProjectModel.findById(project_id);
if (!project) return;
const [hasAccess, role] = await hasAccessToProject(user.id, project_id, project);
if (!hasAccess) return;
if (role === 'GUEST' && !allowGuest) return false;
return project;
if (!project_id) return;
if (project_id === LITLYX_PROJECT_ID) {
return await ProjectModel.findOne({ _id: project_id });
}
if (!user || !user.logged) return;
const project = await ProjectModel.findById(project_id);
if (!project) return;
const [hasAccess, role] = await hasAccessToProject(user.id, project_id, project);
if (!hasAccess) return;
if (role === 'GUEST' && !allowGuest) return false;
return project;
}

View File

@@ -0,0 +1,47 @@
import winston from 'winston';
const { combine, timestamp, json, errors } = winston.format;
const timestampFormat = () => { return new Date().toLocaleString('it-IT', { timeZone: 'Europe/Rome' }); }
export const logger = winston.createLogger({
format: combine(
errors({ stack: true }),
timestamp({
format: timestampFormat
}),
json()
),
exceptionHandlers: [
new winston.transports.File({ filename: 'winston-logs.ndjson' }),
new winston.transports.File({ filename: 'winston-exceptions.ndjson' }),
],
rejectionHandlers: [
new winston.transports.File({ filename: 'winston-logs.ndjson' }),
new winston.transports.File({ filename: 'winston-rejections.ndjson' }),
],
transports: [
new winston.transports.Console({
level: 'debug',
format: combine(
winston.format.colorize({ all: true }),
errors({ stack: true }),
timestamp({ format: timestampFormat }),
winston.format.printf((info) => {
if (info instanceof Error) {
return `${info.timestamp} [${info.level}]: ${info.message}\n${info.stack}`;
} else {
return `${info.timestamp} [${info.level}]: ${info.message}`;
}
})
),
}),
new winston.transports.File({ filename: 'winston-logs.ndjson' }),
new winston.transports.File({
level: 'debug',
filename: 'winston-debug.ndjson'
})
]
});

View File

@@ -0,0 +1,30 @@
import type OpenAI from 'openai'
export type AIPlugin_TTool<T extends string> = (OpenAI.Chat.Completions.ChatCompletionTool & { function: { name: T } });
export type AIPlugin_TFunction<T extends string> = (...args: any[]) => any;
type AIPlugin_Constructor<Items extends string[]> = {
[Key in Items[number]]: {
tool: AIPlugin_TTool<Key>,
handler: AIPlugin_TFunction<Key>
}
}
export abstract class AIPlugin<Items extends string[] = []> {
constructor(public functions: AIPlugin_Constructor<Items>) { }
getTools() {
const keys = Object.keys(this.functions) as Items;
return keys.map((key: Items[number]) => { return this.functions[key].tool });
}
getHandlers() {
const keys = Object.keys(this.functions) as Items;
const result: Record<string, any> = {};
keys.forEach((key: Items[number]) => {
result[key] = this.functions[key].handler;
});
return result;
}
}

View File

@@ -0,0 +1,67 @@
import { AIPlugin } from "../Plugin";
export class AiComposableChart extends AIPlugin<['createComposableChart']> {
constructor() {
super({
'createComposableChart': {
handler: (data: { labels: string, points: number[] }) => {
return { ok: true };
},
tool: {
type: 'function',
function: {
name: 'createComposableChart',
description: 'Creates a chart based on the provided datasets',
parameters: {
type: 'object',
properties: {
labels: {
type: 'array',
items: { type: 'string' },
description: 'Labels for each data point in the chart'
},
title: {
type: 'string',
description: 'Title of the chart to let user understand what is displaying, not include dates'
},
datasets: {
type: 'array',
description: 'List of datasets',
items: {
type: 'object',
properties: {
chartType: {
type: 'string',
enum: ['line', 'bar'],
description: 'The type of chart to display the dataset, either "line" or "bar"'
},
points: {
type: 'array',
items: { type: 'number' },
description: 'Numerical values for each data point in the chart'
},
color: {
type: 'string',
description: 'Color used to represent the dataset in format "#RRGGBB"'
},
name: {
type: 'string',
description: 'Name of the dataset'
}
},
required: ['points', 'color', 'chartType', 'name'],
description: 'Data points and style information for the dataset'
}
}
},
required: ['labels', 'datasets', 'title']
}
}
}
}
})
}
}
export const AiComposableChartInstance = new AiComposableChart();

View File

@@ -0,0 +1,87 @@
import { EventModel } from "@schema/metrics/EventSchema";
import { AdvancedTimelineAggregationOptions, executeAdvancedTimelineAggregation, executeTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
import { Types } from "mongoose";
import { AIPlugin, AIPlugin_TTool } from "../Plugin";
const getEventsCountTool: AIPlugin_TTool<'getEventsCount'> = {
type: 'function',
function: {
name: 'getEventsCount',
description: 'Gets the number of events received on a date range, can also specify the event name and the metadata associated',
parameters: {
type: 'object',
properties: {
from: { type: 'string', description: 'ISO string of start date including hours' },
to: { type: 'string', description: 'ISO string of end date including hours' },
name: { type: 'string', description: 'Name of the events to get' },
metadata: { type: 'object', description: 'Metadata of events to get' },
},
required: ['from', 'to']
}
}
}
const getEventsTimelineTool: AIPlugin_TTool<'getEventsTimeline'> = {
type: 'function',
function: {
name: 'getEventsTimeline',
description: 'Gets an array of date and count for events received on a date range. Should be used to create charts.',
parameters: {
type: 'object',
properties: {
from: { type: 'string', description: 'ISO string of start date including hours' },
to: { type: 'string', description: 'ISO string of end date including hours' },
name: { type: 'string', description: 'Name of the events to get' },
metadata: { type: 'object', description: 'Metadata of events to get' },
},
required: ['from', 'to']
}
}
}
export class AiEvents extends AIPlugin<['getEventsCount', 'getEventsTimeline']> {
constructor() {
super({
'getEventsCount': {
handler: async (data: { project_id: string, from?: string, to?: string, name?: string, metadata?: string }) => {
const query: any = {
project_id: data.project_id,
created_at: {
$gt: data.from ? new Date(data.from).getTime() : new Date(2023).getTime(),
$lt: data.to ? new Date(data.to).getTime() : new Date().getTime(),
}
}
if (data.metadata) query.metadata = data.metadata;
if (data.name) query.name = data.name;
const result = await EventModel.countDocuments(query);
return { count: result };
},
tool: getEventsCountTool
},
'getEventsTimeline': {
handler: async (data: { project_id: string, from: string, to: string, name?: string, metadata?: string }) => {
const query: AdvancedTimelineAggregationOptions & { customMatch: Record<string, any> } = {
projectId: new Types.ObjectId(data.project_id) as any,
model: EventModel,
from: data.from, to: data.to, slice: 'day',
customMatch: {}
}
if (data.metadata) query.customMatch.metadata = data.metadata;
if (data.name) query.customMatch.name = data.name;
const timelineData = await executeAdvancedTimelineAggregation(query);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, 'day', data.from, data.to);
return { data: timelineFilledMerged };
},
tool: getEventsTimelineTool
}
})
}
}
export const AiEventsInstance = new AiEvents();

View File

@@ -0,0 +1,87 @@
import { VisitModel } from "@schema/metrics/VisitSchema";
import { AdvancedTimelineAggregationOptions, executeAdvancedTimelineAggregation, executeTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
import { Types } from "mongoose";
import { AIPlugin, AIPlugin_TTool } from "../Plugin";
const getVisitsCountsTool: AIPlugin_TTool<'getVisitsCount'> = {
type: 'function',
function: {
name: 'getVisitsCount',
description: 'Gets the number of visits received on a date range',
parameters: {
type: 'object',
properties: {
from: { type: 'string', description: 'ISO string of start date including hours' },
to: { type: 'string', description: 'ISO string of end date including hours' },
website: { type: 'string', description: 'The website of the visits' },
page: { type: 'string', description: 'The page of the visit' }
},
required: ['from', 'to']
}
}
}
const getVisitsTimelineTool: AIPlugin_TTool<'getVisitsTimeline'> = {
type: 'function',
function: {
name: 'getVisitsTimeline',
description: 'Gets an array of date and count for events received on a date range. Should be used to create charts.',
parameters: {
type: 'object',
properties: {
from: { type: 'string', description: 'ISO string of start date including hours' },
to: { type: 'string', description: 'ISO string of end date including hours' },
website: { type: 'string', description: 'The website of the visits' },
page: { type: 'string', description: 'The page of the visit' }
},
required: ['from', 'to']
}
}
}
export class AiVisits extends AIPlugin<['getVisitsCount', 'getVisitsTimeline']> {
constructor() {
super({
'getVisitsCount': {
handler: async (data: { project_id: string, from?: string, to?: string, website?: string, page?: string }) => {
const query: any = {
project_id: data.project_id,
created_at: {
$gt: data.from ? new Date(data.from).getTime() : new Date(2023).getTime(),
$lt: data.to ? new Date(data.to).getTime() : new Date().getTime(),
}
}
if (data.website) query.website = data.website;
if (data.page) query.page = data.page;
const result = await VisitModel.countDocuments(query);
return { count: result };
},
tool: getVisitsCountsTool
},
'getVisitsTimeline': {
handler: async (data: { project_id: string, from: string, to: string, website?: string, page?: string }) => {
const query: AdvancedTimelineAggregationOptions & { customMatch: Record<string, any> } = {
projectId: new Types.ObjectId(data.project_id) as any,
model: VisitModel,
from: data.from, to: data.to, slice: 'day',
customMatch: {}
}
if (data.website) query.customMatch.website = data.website;
if (data.page) query.customMatch.page = data.page;
const timelineData = await executeAdvancedTimelineAggregation(query);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, 'day', data.from, data.to);
return { data: timelineFilledMerged };
},
tool: getVisitsTimelineTool
}
})
}
}
export const AiVisitsInstance = new AiVisits();

View File

@@ -1,8 +1,5 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { AiChatModel } from "@schema/ai/AiChatSchema";
import { sendMessageOnChat } from "~/server/services/AiService";
export default defineEventHandler(async event => {

View File

@@ -1,8 +1,7 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { AiChatModel } from "@schema/ai/AiChatSchema";
import { sendMessageOnChat } from "~/server/services/AiService";
import type OpenAI from "openai";
import { getChartsInMessage } from "~/server/services/AiService";
export default defineEventHandler(async event => {
@@ -19,11 +18,14 @@ export default defineEventHandler(async event => {
const chat = await AiChatModel.findOne({ _id: chat_id, project_id });
if (!chat) return;
const messages = chat.messages.filter(e => {
return (e.role == 'user' || (e.role == 'assistant' && e.content != undefined))
}).map(e => {
return { role: e.role, content: e.content }
});
return messages;
return (chat.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[])
.filter(e => e.role === 'assistant' || e.role === 'user')
.map(e => {
const charts = getChartsInMessage(e);
const content = e.content;
return { role: e.role, content, charts }
})
.filter(e=>{
return e.charts.length > 0 || e.content
})
});

View File

@@ -23,5 +23,6 @@ export default defineEventHandler(async event => {
if (chatsRemaining <= 0) return setResponseStatus(event, 400, 'CHAT_LIMIT_REACHED');
const response = await sendMessageOnChat(text, project._id.toString(), chat_id);
return response || 'Error getting response';
return response;
});

View File

@@ -1,51 +0,0 @@
import OpenAI from "openai";
import { EventModel } from "@schema/metrics/EventSchema";
export const AI_EventsFunctions = {
getEventsCount: ({ pid, from, to, name, metadata }: any) => {
return getEventsCountForAI(pid, from, to, name, metadata);
}
}
export const getEventsCountForAIDeclaration: OpenAI.Chat.Completions.ChatCompletionTool = {
type: 'function',
function: {
name: 'getEventsCount',
description: 'Gets the number of events received on a date range, can also specify the event name and the metadata associated',
parameters: {
type: 'object',
properties: {
from: { type: 'string', description: 'ISO string of start date including hours' },
to: { type: 'string', description: 'ISO string of end date including hours' },
name: { type: 'string', description: 'Name of the events to get' },
metadata: { type: 'object', description: 'Metadata of events to get' },
},
required: ['from', 'to']
}
}
}
export const AI_EventsTools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
getEventsCountForAIDeclaration
]
export async function getEventsCountForAI(project_id: string, from?: string, to?: string, name?: string, metadata?: string) {
const query: any = {
project_id,
created_at: {
$gt: from ? new Date(from).getTime() : new Date(2023).getTime(),
$lt: to ? new Date(to).getTime() : new Date().getTime(),
}
}
if (metadata) query.metadata = metadata;
if (name) query.name = name;
const result = await EventModel.countDocuments(query);
return { count: result };
}

View File

@@ -1,14 +0,0 @@
import { VisitModel } from "@schema/metrics/VisitSchema";
export async function getVisitsCountFromDateRange(project_id: string, from?: string, to?: string) {
const result = await VisitModel.countDocuments({
project_id,
created_at: {
$gt: from ? new Date(from).getTime() : new Date(2023).getTime(),
$lt: to ? new Date(to).getTime() : new Date().getTime(),
}
});
return { count: result };
}

View File

@@ -0,0 +1,65 @@
import { EventModel } from "@schema/metrics/EventSchema";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { Redis } from "~/server/services/CacheService";
import type { Model } from "mongoose";
const allowedModels: Record<string, { model: Model<any>, field: string }> = {
'events': {
model: EventModel,
field: 'name'
}
}
type TModelName = keyof typeof allowedModels;
export default defineEventHandler(async event => {
const project_id = getHeader(event, 'x-pid');
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
const from = getRequestHeader(event, 'x-from');
const to = getRequestHeader(event, 'x-to');
if (!from || !to) return setResponseStatus(event, 400, 'x-from and x-to are required');
const schemaName = getRequestHeader(event, 'x-schema');
if (!schemaName) return setResponseStatus(event, 400, 'x-schema is required');
if (!Object.keys(allowedModels).includes(schemaName)) return setResponseStatus(event, 400, 'x-schema value is not valid');
const limitHeader = getRequestHeader(event, 'x-query-limit');
const limitNumber = parseInt(limitHeader || '10');
const limit = isNaN(limitNumber) ? 10 : limitNumber;
const cacheKey = `${schemaName}:${project_id}:${from}:${to}`;
const cacheExp = 60;
return await Redis.useCacheV2(cacheKey, cacheExp, async (noStore, updateExp) => {
const { model } = allowedModels[schemaName as TModelName];
const result = await model.aggregate([
{
$match: {
project_id: project._id,
created_at: {
$gte: new Date(from),
$lte: new Date(to)
}
}
},
{ $group: { _id: "$name", count: { $sum: 1, } } },
{ $sort: { count: -1 } },
{ $limit: limit }
]);
return result;
});
});

View File

@@ -0,0 +1,23 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { IntegrationsCredentialsModel } from '@schema/integrations/IntegrationsCredentialsSchema';
export default defineEventHandler(async event => {
const project_id = getHeader(event, 'x-pid');
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
const credentials = await IntegrationsCredentialsModel.findOne({ project_id });
return {
supabase: {
anon_key: credentials?.supabase_anon_key || '',
service_role_key: credentials?.supabase_service_role_key || '',
url: credentials?.supabase_url || ''
}
}
});

View File

@@ -0,0 +1,23 @@
import { IntegrationsCredentialsModel } from "@schema/integrations/IntegrationsCredentialsSchema";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
export default defineEventHandler(async event => {
const project_id = getHeader(event, 'x-pid');
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
const body = await readBody(event);
const res = await IntegrationsCredentialsModel.updateOne({ project_id }, {
supabase_anon_key: body.supabase_anon_key || '',
supabase_service_role_key: body.supabase_service_role_key || '',
supabase_url: body.supabase_url || '',
}, { upsert: true });
return { ok: res.acknowledged };
});

View File

@@ -0,0 +1,72 @@
import { createUserJwt } from '~/server/AuthManager';
import { UserModel } from '@schema/UserSchema';
import EmailService from '@services/EmailService';
const config = useRuntimeConfig();
export default defineEventHandler(async event => {
const { code } = getQuery(event);
console.log('CODE', code);
const redirect_uri = 'http://127.0.0.1:3000'
const res = await fetch(`https://github.com/login/oauth/access_token?client_id=${config.GITHUB_AUTH_CLIENT_ID}&client_secret=${config.GITHUB_AUTH_CLIENT_SECRET}&code=${code}&redirect_url=${redirect_uri}`, {
headers: {
"Accept": "application/json",
"Accept-Encoding": "application/json",
},
});
const data = await res.json();
const access_token = data.access_token;
console.log(data);
return sendRedirect(event,`http://127.0.0.1:3000/login?github_access_token=${access_token}`)
// const origin = event.headers.get('origin');
// const tokenResponse = await client.getToken({
// code: body.code,
// redirect_uri: origin || ''
// });
// const tokens = tokenResponse.tokens;
// const ticket = await client.verifyIdToken({
// idToken: tokens.id_token || '',
// audience: GOOGLE_AUTH_CLIENT_ID,
// });
// const payload = ticket.getPayload();
// if (!payload) return { error: true, access_token: '' };
// const user = await UserModel.findOne({ email: payload.email });
// if (user) return { error: false, access_token: createUserJwt({ email: user.email, name: user.name }) }
// const newUser = new UserModel({
// email: payload.email,
// given_name: payload.given_name,
// name: payload.name,
// locale: payload.locale,
// picture: payload.picture,
// created_at: Date.now()
// });
// const savedUser = await newUser.save();
// setImmediate(() => {
// console.log('SENDING WELCOME EMAIL TO', payload.email);
// if (payload.email) EmailService.sendWelcomeEmail(payload.email);
// });
// return { error: false, access_token: createUserJwt({ email: savedUser.email, name: savedUser.name }) }
});

View File

@@ -0,0 +1,29 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { SupabaseIntegrationModel } from "@schema/integrations/SupabaseIntegrationSchema";
export default defineEventHandler(async event => {
const project_id = getHeader(event, 'x-pid');
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
const { chart_type, table_name, xField, yMode, from, to, slice, name } = await readBody(event);
if (!project.premium) {
const supabaseIntegrationsCount = await SupabaseIntegrationModel.countDocuments({ project_id });
if (supabaseIntegrationsCount > 0) return setResponseStatus(event, 400, 'LIMIT_REACHED');
}
await SupabaseIntegrationModel.create({
name,
project_id, chart_type,
table_name, xField, yMode,
from, to, slice,
});
return { ok: true };
});

View File

@@ -0,0 +1,18 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { SupabaseIntegrationModel } from '@schema/integrations/SupabaseIntegrationSchema';
export default defineEventHandler(async event => {
const project_id = getHeader(event, 'x-pid');
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
const integration_id = getHeader(event, 'x-integration');
const integration = await SupabaseIntegrationModel.findOne({ _id: integration_id });
return integration;
});

View File

@@ -0,0 +1,16 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { SupabaseIntegrationModel } from '@schema/integrations/SupabaseIntegrationSchema';
export default defineEventHandler(async event => {
const project_id = getHeader(event, 'x-pid');
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
const integrations = await SupabaseIntegrationModel.find({ project_id });
return integrations;
});

View File

@@ -29,7 +29,7 @@ export default defineEventHandler(async event => {
const project = await ProjectModel.findById(project_id);
if (!project) return setResponseStatus(event, 400, 'Project not found');
if (project.owner.toString() != userData.id) {
return setResponseStatus(event, 400, 'You are not the owner');
}

View File

@@ -2,7 +2,7 @@ import { EventModel } from "@schema/metrics/EventSchema";
import { getTimeline } from "./generic";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { executeTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
import { executeTimelineAggregation, fillAndMergeTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
@@ -27,7 +27,7 @@ export default defineEventHandler(async event => {
model: EventModel,
from, to, slice
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, slice, from, to);
return timelineFilledMerged;
});

View File

@@ -2,7 +2,8 @@ import { EventModel } from "@schema/metrics/EventSchema";
import { getTimeline } from "./generic";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { executeAdvancedTimelineAggregation } from "~/server/services/TimelineService";
import { executeAdvancedTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
import DateService from '@services/DateService';
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
@@ -29,6 +30,9 @@ export default defineEventHandler(async event => {
customIdGroup: { name: '$name' },
})
// const filledDates = DateService.createBetweenDates(from, to, slice);
// const merged = DateService.mergeFilledDates(filledDates.dates, timelineStackedEvents, '_id', slice, { count: 0, name: '' });
return timelineStackedEvents;
});

View File

@@ -1,9 +1,7 @@
import { getTimeline } from "./generic";
import { VisitModel } from "@schema/metrics/VisitSchema";
import DateService from "@services/DateService";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { executeAdvancedTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
import { executeAdvancedTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
@@ -31,7 +29,7 @@ export default defineEventHandler(async event => {
referrer
}
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, slice, from, to);
return timelineFilledMerged;
});

View File

@@ -2,7 +2,7 @@ import { getTimeline } from "./generic";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { SessionModel } from "@schema/metrics/SessionSchema";
import { executeTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
import { executeTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
@@ -28,7 +28,7 @@ export default defineEventHandler(async event => {
model: SessionModel,
from, to, slice
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, slice, from, to);
return timelineFilledMerged;
});

View File

@@ -2,7 +2,7 @@ import { getTimeline } from "./generic";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import { SessionModel } from "@schema/metrics/SessionSchema";
import { executeAdvancedTimelineAggregation, executeTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
import { executeAdvancedTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
@@ -45,7 +45,7 @@ export default defineEventHandler(async event => {
count: { $divide: ["$duration", "$count"] }
},
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, slice, from ,to);
return timelineFilledMerged;
});

View File

@@ -2,7 +2,7 @@ import { VisitModel } from "@schema/metrics/VisitSchema";
import { Redis, TIMELINE_EXPIRE_TIME } from "~/server/services/CacheService";
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import DateService from "@services/DateService";
import { executeTimelineAggregation, fillAndMergeTimelineAggregation } from "~/server/services/TimelineService";
import { executeTimelineAggregation, fillAndMergeTimelineAggregationV2 } from "~/server/services/TimelineService";
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
@@ -28,11 +28,9 @@ export default defineEventHandler(async event => {
model: VisitModel,
from, to, slice,
});
const timelineFilledMerged = fillAndMergeTimelineAggregation(timelineData, slice);
const timelineFilledMerged = fillAndMergeTimelineAggregationV2(timelineData, slice, from, to);
return timelineFilledMerged;
});
});

View File

@@ -1,6 +0,0 @@
export default defineEventHandler(async event => {
console.log('TEST');
return;
});

View File

@@ -9,9 +9,13 @@ export default defineEventHandler(async event => {
if (!project_id) return;
const user = getRequestUser(event);
if (!user?.logged) return setResponseStatus(event, 400, 'User need to be logged');
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
if (project.owner.toString() != user.id) return setResponseStatus(event, 400, 'You cannot upgrade a project as guest');
const body = await readBody(event);
const { planId } = body;

View File

@@ -9,9 +9,13 @@ export default defineEventHandler(async event => {
if (!project_id) return;
const user = getRequestUser(event);
if (!user?.logged) return setResponseStatus(event, 400, 'User need to be logged');
const project = await getUserProjectFromId(project_id, user);
if (!project) return;
if (project.owner.toString() != user.id) return setResponseStatus(event, 400, 'You cannot upgrade a project as guest');
const body = await readBody(event);
const { planId } = body;
@@ -23,7 +27,7 @@ export default defineEventHandler(async event => {
return setResponseStatus(event, 400, 'Plan not exist');
}
const checkout = await StripeService.cretePayment(
const checkout = await StripeService.createPayment(
StripeService.testMode ? PLAN.PRICE_TEST : PLAN.PRICE,
'https://dashboard.litlyx.com/payment_ok',
project_id,

View File

@@ -0,0 +1,21 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import StripeService from '~/server/services/StripeService';
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
if (!project_id) return;
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user, false);
if (!project) return;
if (!project.customer_id) return;
const customer = await StripeService.getCustomer(project.customer_id);
if (customer?.deleted) return;
return customer?.address;
});

View File

@@ -0,0 +1,21 @@
import { getUserProjectFromId } from "~/server/LIVE_DEMO_DATA";
import StripeService from '~/server/services/StripeService';
export default defineEventHandler(async event => {
const project_id = getRequestProjectId(event);
if (!project_id) return setResponseStatus(event, 400, 'Cannot get project_id');
const user = getRequestUser(event);
const project = await getUserProjectFromId(project_id, user, false);
if (!project) return setResponseStatus(event, 400, 'Cannot get user from project_id');
if (!project.customer_id) return setResponseStatus(event, 400, 'Project has no customer_id');
const body = await readBody(event);
const res = await StripeService.setCustomerInfo(project.customer_id, body);
return { ok: true, data: res }
});

Some files were not shown because too many files have changed in this diff Show More