Skip to content

Commit

Permalink
show username and instance name in data table
Browse files Browse the repository at this point in the history
  • Loading branch information
moeakwak committed Apr 29, 2024
1 parent 187aba4 commit 92a8891
Show file tree
Hide file tree
Showing 11 changed files with 83 additions and 32 deletions.
9 changes: 7 additions & 2 deletions src/app/(panel)/admin/logs/events/event-logs-table.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
"use client";

import { DataTable } from "@/components/data-table";
import { EventLogSchema } from "@/schema/eventLog.schema";
import { EventLogSchemaWithUser } from "@/schema/eventLog.schema";
import { type PaginationInput } from "@/schema/pagination.schema";

export function EventLogsTable({ fetchData }: { fetchData: (input: PaginationInput) => Promise<any> }) {
return (
<div className="w-full">
<DataTable
className="h-[800px]"
schema={EventLogSchema}
schema={EventLogSchemaWithUser}
enableColumnSelector={true}
lazyPagination={true}
fetchData={fetchData}
defaultPageSize={20}
defaultColumnVisibility={{
userId: false,
user: false,
}}
/>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ export function ResourceLogsTable({ fetchData }: { fetchData: (input: Pagination
enableColumnSelector={true}
defaultColumnVisibility={{
type: false,
"details": false,
"details_type": false,
"details_inputTokens": false
userId: false,
instanceId: false,
user: false,
details: false,
details_type: false,
details_inputTokens: false,
}}
/>
</div>
Expand Down
4 changes: 2 additions & 2 deletions src/app/(panel)/dashboard/logs/user-resource-logs-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import { DataTable } from "@/components/data-table";
import { type PaginationInput } from "@/schema/pagination.schema";
import { ChatGPTSharedResourceUsageLogSchema, ResourceUsageLogSchema } from "@/schema/resourceLog.schema";
import { ChatGPTSharedResourceUsageLogSchema } from "@/schema/resourceLog.schema";

const UserResourceUsageLogDisplaySchema = ChatGPTSharedResourceUsageLogSchema.pick({
createdAt: true,
instanceId: true,
instanceName: true,
details: true,
});

Expand Down
1 change: 0 additions & 1 deletion src/app/auth/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Card } from "@/components/ui/card";
import { redirect } from "next/navigation";
import { getSessionData } from "@/server/auth";

Expand Down
8 changes: 3 additions & 5 deletions src/components/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ import { Badge } from "@/components/ui/badge";
import { formatValueToNode } from "@/lib/format";

export function formatUserDataTableCellValue(key: string, value: any): React.ReactNode {
if (key === "id") {
return <Badge variant="secondary">{(value as string).slice(0, 4)}...</Badge>;
if (value && (key === "id" || key.endsWith("Id"))) {
return <Badge variant="secondary">{(value as string).slice(0, 8)}...</Badge>;
}
if (key === "role") {
// return <Badge variant="default">{(value as string).toLowerCase()}</Badge>;
Expand Down Expand Up @@ -146,8 +146,6 @@ export function createColumns<T>(
): ColumnDef<T>[] {
const columnHelper = createColumnHelper<T>();

console.log(schema.shape, extractKeysFromSchema(schema));

const columns = [
getDataTableCheckboxColumn(columnHelper),
...extractKeysFromSchema(schema).map((key) =>
Expand Down Expand Up @@ -302,7 +300,7 @@ export function DataTable<T>({
setTableData(response.data);
setLastPage(response.pagination.totalPages);
setTotalPages(response.pagination.totalPages);
console.log("Fetched data", response);
// console.log("Fetched data", response);
})
.catch((error) => {
console.error("Error fetching data", error);
Expand Down
4 changes: 2 additions & 2 deletions src/lib/format.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { ScrollArea } from "@/components/ui/scroll-area";

export function formatValueToNode(key: string, value: unknown): React.ReactNode {
if (value === null) {
return <span className="text-gray-400"> null </span>;
return <span className="text-muted-foreground"> null </span>;
}
if (value instanceof Date) {
return <span className="text-sm">{value.toLocaleString()}</span>;
return <span className="text-muted-foreground">{value.toLocaleString()}</span>;
}
if (key === "text") {
const text = value as string;
Expand Down
10 changes: 10 additions & 0 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ export function extractKeysFromSchema(
);
keys = keys.concat(nestedKeys);
}
if (value instanceof z.ZodOptional && value._def.innerType instanceof z.ZodObject) {
const nestedKeys = extractKeysFromSchema(
value._def.innerType as z.ZodObject<z.ZodRawShape>,
maxDepth,
currentDepth + 1,
newPrefix,
);
keys = keys.concat(nestedKeys);
}

}

return keys;
Expand Down
9 changes: 9 additions & 0 deletions src/schema/eventLog.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,12 @@ export const EventLogWhereInputSchema = z.object({
timeStart: z.date().optional(),
timeEnd: z.date().optional(),
});

export const EventLogSchemaWithUser = EventLogSchema.merge(
z.object({
user: z.object({
username: z.string(),
name: z.string(),
}).optional(),
}),
);
30 changes: 21 additions & 9 deletions src/schema/resourceLog.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { resourceUsageLogs } from "@/server/db/schema";
import { DurationWindowSchema } from "@/server/db/enum";
import { ChatGPTSharedResourceUsageLogDetailsSchema } from "./service/chatgpt-shared.schema";



export const ResourceLogSumResultSchema = z.object({
durationWindow: DurationWindowSchema,
stats: z.object({
Expand Down Expand Up @@ -39,10 +37,24 @@ export const ResourceUsageLogWhereInputSchema = z.object({
export const ResourceUsageLogDetailsSchema = z.discriminatedUnion("type", [ChatGPTSharedResourceUsageLogDetailsSchema]);
export type ResourceUsageLogDetails = z.infer<typeof ResourceUsageLogDetailsSchema>;

export const ResourceUsageLogSchema = createSelectSchema(resourceUsageLogs).merge(z.object({
details: ResourceUsageLogDetailsSchema
}))

export const ChatGPTSharedResourceUsageLogSchema = createSelectSchema(resourceUsageLogs).merge(z.object({
details: ChatGPTSharedResourceUsageLogDetailsSchema
}));
export const ResourceUsageLogSchema = createSelectSchema(resourceUsageLogs).merge(
z.object({
details: ResourceUsageLogDetailsSchema,
user: z.object({
username: z.string(),
name: z.string(),
}).optional(),
instanceName: z.string().optional()
}),
);

export const ChatGPTSharedResourceUsageLogSchema = createSelectSchema(resourceUsageLogs).merge(
z.object({
details: ChatGPTSharedResourceUsageLogDetailsSchema,
user: z.object({
username: z.string(),
name: z.string(),
}).optional(),
instanceName: z.string().optional()
}),
);
12 changes: 9 additions & 3 deletions src/server/api/routers/eventLog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { PaginationInputSchema } from "@/schema/pagination.schema";
import { z } from "zod";
import { paginateQuery } from "../pagination";
import { EventLogSchema, EventLogWhereInputSchema } from "@/schema/eventLog.schema";
import { type SQL, and, count, eq, gte, lte, desc } from "drizzle-orm";
import { eventLogs } from "@/server/db/schema";
import { type SQL, and, count, eq, gte, lte, desc, getTableColumns } from "drizzle-orm";
import { eventLogs, users } from "@/server/db/schema";

const PaginationEventLogsInputSchema = z.object({
where: EventLogWhereInputSchema,
Expand Down Expand Up @@ -46,7 +46,13 @@ const getPaginatedResourceLogs = async ({
.from(eventLogs)
.where(and(...andParams));
const result = await tx
.select()
.select({
...getTableColumns(eventLogs),
user: {
username: users.username,
name: users.name,
}
})
.from(eventLogs)
.where(filter)
.orderBy(desc(eventLogs.createdAt))
Expand Down
19 changes: 14 additions & 5 deletions src/server/api/routers/resourceLog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {
ResourceUsageLogSchema,
} from "@/schema/resourceLog.schema";
import { paginateQuery } from "../pagination";
import { type SQL, and, count, eq, gte, lte, sql, countDistinct, desc } from "drizzle-orm";
import { resourceUsageLogs } from "@/server/db/schema";
import { type SQL, and, count, eq, gte, lte, sql, countDistinct, desc, getTableColumns } from "drizzle-orm";
import { resourceUsageLogs, serviceInstances, users } from "@/server/db/schema";
import { UserRoles } from "@/schema/user.schema";
import { DURATION_WINDOWS, type DurationWindow, DurationWindowSchema, ServiceTypeSchema } from "@/server/db/enum";
import { alignTimeToGranularity } from "@/lib/utils";
Expand Down Expand Up @@ -98,7 +98,6 @@ const _groupGPT4LogsInDurationWindow = async ({
),
)
.groupBy(sql`${resourceUsageLogs.details}->>'chatgptAccountId'`);
// console.log("groupByResult", groupByResult);
const result = {
durationWindow,
counts: groupByResult.map((item) => ({
Expand Down Expand Up @@ -156,11 +155,21 @@ const getPaginatedResourceLogs = async ({
value: count(),
})
.from(resourceUsageLogs)
.where(and(...andParams));
.where(and(...andParams))
.leftJoin(users, eq(resourceUsageLogs.userId, users.id));
const result = await tx
.select()
.select({
...getTableColumns(resourceUsageLogs),
user: {
username: users.username,
name: users.name,
},
instanceName: serviceInstances.name,
})
.from(resourceUsageLogs)
.where(filter)
.leftJoin(users, eq(resourceUsageLogs.userId, users.id))
.leftJoin(serviceInstances, eq(resourceUsageLogs.instanceId, serviceInstances.id))
.orderBy(desc(resourceUsageLogs.createdAt))
.limit(take)
.offset(skip);
Expand Down

0 comments on commit 92a8891

Please sign in to comment.