Skip to content

Commit

Permalink
Update User Statistics
Browse files Browse the repository at this point in the history
  • Loading branch information
koechkevin committed Sep 6, 2024
1 parent 308bddc commit c949a2a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 59 deletions.
66 changes: 26 additions & 40 deletions apps/vpnmanager/src/lib/data/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import path from "path";
const dbPath = path.resolve(process.cwd(), "data", "database.sqlite");
const db = betterSqlite3(dbPath);

class Record {
export interface Record {
ID?: number;
userId: string;
usage: number;
Expand All @@ -13,32 +13,11 @@ class Record {
email: string;
accessUrl?: string;
createdAt: string;

constructor(
userId: string,
usage: number,
date: string,
cumulativeData: number,
email: string,
accessUrl?: string,
createdAt?: string,
ID?: number,
) {
this.ID = ID;
this.userId = userId;
this.usage = usage;
this.date = date;
this.cumulativeData = cumulativeData;
this.email = email;
this.accessUrl = accessUrl;
this.createdAt = createdAt || new Date().toISOString();
}
}

export interface Filters {
email?: string;
date?: string;
dateBetween?: { start: string; end: string };
date?: string | { start: string; end: string };
userId?: string;
ID?: number;
groupBy?: "email" | "date";
Expand All @@ -56,16 +35,24 @@ class Model {
cumulativeData INTEGER NOT NULL,
email TEXT NOT NULL,
accessUrl TEXT,
createdAt TEXT NOT NULL
createdAt TEXT NOT NULL,
UNIQUE (date, userId)
)
`;
db.exec(createTable);
}

static create(record: Record) {
static createOrUpdate(record: Record) {
const insertData = db.prepare(`
INSERT INTO records (userId, usage, date, cumulativeData, email, accessUrl, createdAt)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(date, userId)
DO UPDATE SET
usage = excluded.usage,
cumulativeData = excluded.cumulativeData,
email = excluded.email,
accessUrl = excluded.accessUrl,
createdAt = excluded.createdAt;
`);
const info = insertData.run(
record.userId,
Expand Down Expand Up @@ -97,27 +84,26 @@ class Model {
let query = "SELECT";
const params: any[] = [];
if (filters.groupBy === "email" || filters.groupBy === "date") {
if (filters.groupBy === "email") {
query +=
" email, userId, accessUrl, SUM(usage) as totalUsage FROM records WHERE 1=1";
}
if (filters.groupBy === "date") {
query += " date, SUM(usage) as totalUsage FROM records WHERE 1=1";
}
query +=
filters.groupBy === "email"
? " email, userId, accessUrl, SUM(usage) as totalUsage FROM records"
: " date, SUM(usage) as totalUsage FROM records";
} else {
query += " * FROM records WHERE 1=1";
query += " * FROM records";
}
query += " WHERE 1=1";
if (filters.email) {
query += " AND email = ?";
params.push(filters.email);
}
if (filters.date) {
query += " AND date = ?";
params.push(filters.date);
}
if (filters.dateBetween && !filters.date) {
query += " AND date BETWEEN ? AND ?";
params.push(filters.dateBetween.start, filters.dateBetween.end);
if (typeof filters.date === "string") {
query += " AND date = ?";
params.push(filters.date);
} else {
query += " AND date BETWEEN ? AND ?";
params.push(filters.date.start, filters.date.end);
}
}
if (filters.userId) {
query += " AND userId = ?";
Expand Down Expand Up @@ -146,4 +132,4 @@ class Model {
// Initialize the database
Model.initialize();

export { Model, Record };
export { Model };
30 changes: 11 additions & 19 deletions apps/vpnmanager/src/lib/userStatistics.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { OutlineVPN } from "./outline";
import { Model, Record } from "@/vpnmanager/lib/data/database";
import { Filters, Model, Record } from "@/vpnmanager/lib/data/database";

interface UserDataUsage {
outlineId: string | number;
Expand All @@ -24,17 +24,7 @@ function calculateDailyDataUsage(userData: UserDataUsage) {
}

function addUserStatsToDb(record: Omit<Record, "ID">) {
// Find in DB if userId and date exists then update else create
const date = new Date();
const [res] = Model.getAll({
date: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`,
userId: record?.userId?.toString(),
}) as Record[];
if (res) {
Model.update(res.ID as number, record);
return;
}
Model.create(record);
Model.createOrUpdate(record);
}
// Process Daily user stats. Doesn't matter the time of the day, it just updates.
export async function processUserStats() {
Expand Down Expand Up @@ -62,20 +52,22 @@ export async function processUserStats() {
return unprocessedUsers;
}

export async function getStats(filters: { [key: string]: string }) {
export async function getStats(
filters: Partial<Filters> & { "date.start"?: string; "date.end"?: string },
) {
const validFilters = {
email: filters.email,
ID: parseInt(filters.ID),
ID: filters.ID,
userId: filters.userId,
groupBy: filters.groupBy as "email" | "date",
orderBy: filters.orderBy,
dateBetween:
filters["dateBetween.start"] && filters["dateBetween.end"]
date:
filters["date.start"] && filters["date.end"]
? {
start: filters["dateBetween.start"],
end: filters["dateBetween.end"],
start: filters["date.start"],
end: filters["date.end"],
}
: undefined,
: filters.date,
};

return Model.getAll(validFilters);
Expand Down

0 comments on commit c949a2a

Please sign in to comment.