Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-- CreateTable
CREATE TABLE "analytics_events" (
"id" TEXT NOT NULL,
"eventType" TEXT NOT NULL,
"userId" TEXT,
"sessionId" TEXT,
"path" TEXT,
"properties" JSONB,
"userAgent" TEXT,
"ipAddress" TEXT,
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "analytics_events_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "analytics_events_eventType_idx" ON "analytics_events"("eventType");

-- CreateIndex
CREATE INDEX "analytics_events_userId_idx" ON "analytics_events"("userId");

-- CreateIndex
CREATE INDEX "analytics_events_occurredAt_idx" ON "analytics_events"("occurredAt");

-- CreateIndex
CREATE INDEX "analytics_events_eventType_occurredAt_idx" ON "analytics_events"("eventType", "occurredAt");
20 changes: 20 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,26 @@ model AdminAuditLog {
}

// ============================================================
// ANALYTICS EVENTS
// ============================================================

model AnalyticsEvent {
id String @id @default(uuid())
eventType String
userId String?
sessionId String?
path String?
properties Json?
userAgent String?
ipAddress String?
occurredAt DateTime @default(now())
createdAt DateTime @default(now())

@@index([eventType])
@@index([userId])
@@index([occurredAt])
@@index([eventType, occurredAt])
@@map("analytics_events")
// COURSE DATA RESTORE
// ============================================================

Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { ModerationModule } from './modules/moderation/moderation.module';
import { GamificationModule } from './modules/gamification/gamification.module';
import { ReferralsModule } from './modules/referrals/referrals.module';
import { AuditLogModule } from './modules/audit-log/audit-log.module';
import { AnalyticsModule } from './modules/analytics/analytics.module';
import { BackupsModule } from './modules/backups/backups.module';
import { UploadsModule } from './modules/uploads/uploads.module';

Expand Down Expand Up @@ -74,6 +75,7 @@ import { UploadsModule } from './modules/uploads/uploads.module';
GamificationModule,
ReferralsModule,
AuditLogModule,
AnalyticsModule,
BackupsModule,
UploadsModule,
],
Expand Down
93 changes: 93 additions & 0 deletions src/modules/analytics/analytics.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {
Body,
Controller,
Get,
Headers,
HttpCode,
HttpStatus,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { UserRole } from '@prisma/client';
import { Request } from 'express';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { Roles, RolesGuard } from '../../common/guards/roles.guard';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { AnalyticsService } from './analytics.service';
import {
BatchTrackAnalyticsEventsDto,
QueryAnalyticsEventsDto,
TrackAnalyticsEventDto,
} from './dto/track-analytics-event.dto';

@ApiTags('analytics')
@Controller('analytics')
export class AnalyticsController {
constructor(private readonly analyticsService: AnalyticsService) {}

@Post('events')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Ingest a single analytics event' })
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
trackEvent(
@Body() dto: TrackAnalyticsEventDto,
@CurrentUser('id') userId: string,
@Req() req: Request,
@Headers('user-agent') userAgent?: string,
) {
return this.analyticsService.trackEvent(dto, {
userId: dto.userId ?? userId,
ipAddress: req.ip,
userAgent: dto.userAgent ?? userAgent,
});
}

@Post('events/batch')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({
summary: 'Batch-ingest analytics events for high-frequency tracking',
})
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
trackEventsBatch(
@Body() dto: BatchTrackAnalyticsEventsDto,
@CurrentUser('id') userId: string,
@Req() req: Request,
@Headers('user-agent') userAgent?: string,
) {
return this.analyticsService.trackEventsBatch(dto, {
userId,
ipAddress: req.ip,
userAgent,
});
}

@Get('volume')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Get event volume aggregated by event type (admin)' })
@ApiQuery({ name: 'from', required: false })
@ApiQuery({ name: 'to', required: false })
getVolume(@Query('from') from?: string, @Query('to') to?: string) {
return this.analyticsService.getVolumeByEventType(from, to);
}

@Get('events')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiOperation({ summary: 'Query raw analytics events (admin only)' })
queryRawEvents(@Query() query: QueryAnalyticsEventsDto) {
return this.analyticsService.queryRawEvents(query);
}
}
10 changes: 10 additions & 0 deletions src/modules/analytics/analytics.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { AnalyticsController } from './analytics.controller';
import { AnalyticsService } from './analytics.service';

@Module({
controllers: [AnalyticsController],
providers: [AnalyticsService],
exports: [AnalyticsService],
})
export class AnalyticsModule {}
153 changes: 153 additions & 0 deletions src/modules/analytics/analytics.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { BadRequestException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../common/prisma/prisma.service';
import { AnalyticsService } from './analytics.service';

describe('AnalyticsService', () => {
let service: AnalyticsService;

const mockPrisma = {
analyticsEvent: {
create: jest.fn(),
createMany: jest.fn(),
groupBy: jest.fn(),
findMany: jest.fn(),
count: jest.fn(),
},
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AnalyticsService,
{ provide: PrismaService, useValue: mockPrisma },
],
}).compile();

service = module.get(AnalyticsService);
jest.clearAllMocks();
});

describe('trackEvent()', () => {
it('ingests a valid analytics event', async () => {
mockPrisma.analyticsEvent.create.mockResolvedValue({
id: 'evt-1',
eventType: 'page_view',
path: '/courses',
});

const result = await service.trackEvent(
{ eventType: 'page_view', path: '/courses' },
{ userId: 'user-1', ipAddress: '127.0.0.1' },
);

expect(result.id).toBe('evt-1');
expect(mockPrisma.analyticsEvent.create).toHaveBeenCalledWith({
data: expect.objectContaining({
eventType: 'page_view',
path: '/courses',
userId: 'user-1',
ipAddress: '127.0.0.1',
}),
});
});

it('rejects empty eventType', async () => {
await expect(
service.trackEvent({ eventType: ' ' } as any),
).rejects.toThrow(BadRequestException);
});

it('rejects non-object properties', async () => {
await expect(
service.trackEvent({
eventType: 'click',
properties: ['bad'] as any,
}),
).rejects.toThrow(BadRequestException);
});
});

describe('trackEventsBatch()', () => {
it('batch-ingests high-frequency events', async () => {
mockPrisma.analyticsEvent.createMany.mockResolvedValue({ count: 3 });

const result = await service.trackEventsBatch({
events: [
{ eventType: 'click', path: '/a' },
{ eventType: 'click', path: '/b' },
{ eventType: 'page_view', path: '/c' },
],
});

expect(result).toEqual({ ingested: 3, requested: 3 });
expect(mockPrisma.analyticsEvent.createMany).toHaveBeenCalledTimes(1);
});

it('rejects empty batches', async () => {
await expect(
service.trackEventsBatch({ events: [] }),
).rejects.toThrow(BadRequestException);
});
});

describe('getVolumeByEventType()', () => {
it('returns volume metrics per event type', async () => {
mockPrisma.analyticsEvent.groupBy.mockResolvedValue([
{ eventType: 'page_view', _count: { _all: 10 } },
{ eventType: 'click', _count: { _all: 4 } },
]);

const result = await service.getVolumeByEventType();
expect(result.total).toBe(14);
expect(result.byEventType).toEqual([
{ eventType: 'page_view', count: 10 },
{ eventType: 'click', count: 4 },
]);
});
});

describe('queryRawEvents()', () => {
it('returns paginated raw events for admins', async () => {
mockPrisma.analyticsEvent.findMany.mockResolvedValue([
{ id: 'evt-1', eventType: 'page_view' },
]);
mockPrisma.analyticsEvent.count.mockResolvedValue(1);

const result = await service.queryRawEvents({
eventType: 'page_view',
page: 1,
limit: 10,
});

expect(result.data).toHaveLength(1);
expect(result.meta).toEqual({
total: 1,
page: 1,
limit: 10,
totalPages: 1,
});
});
});

describe('validateEventPayload()', () => {
it('allows known and custom event types', () => {
expect(() =>
service.validateEventPayload({ eventType: 'page_view' }),
).not.toThrow();
expect(() =>
service.validateEventPayload({ eventType: 'custom.widget_open' }),
).not.toThrow();
});

it('rejects oversized properties payloads', () => {
const huge = { blob: 'x'.repeat(20_000) };
expect(() =>
service.validateEventPayload({
eventType: 'click',
properties: huge,
}),
).toThrow(BadRequestException);
});
});
});
Loading