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,98 @@
import { MigrationInterface, QueryRunner, Table, TableIndex } from 'typeorm';

export class CreateSavingsExperimentTables1791200000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'savings_experiments',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
isGenerated: true,
generationStrategy: 'uuid',
},
{ name: 'key', type: 'varchar', isUnique: true },
{ name: 'name', type: 'varchar' },
{ name: 'description', type: 'text', isNullable: true },
{ name: 'productId', type: 'uuid', isNullable: true },
{ name: 'variants', type: 'jsonb' },
{ name: 'configuration', type: 'jsonb', isNullable: true },
{ name: 'status', type: 'varchar', default: "'DRAFT'" },
{ name: 'minSampleSize', type: 'int', default: 100 },
{
name: 'confidenceLevel',
type: 'decimal',
precision: 4,
scale: 2,
default: 0.95,
},
{ name: 'startedAt', type: 'timestamp', isNullable: true },
{ name: 'endedAt', type: 'timestamp', isNullable: true },
{ name: 'createdAt', type: 'timestamp', default: 'now()' },
{ name: 'updatedAt', type: 'timestamp', default: 'now()' },
],
}),
);

await queryRunner.createTable(
new Table({
name: 'savings_experiment_assignments',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
isGenerated: true,
generationStrategy: 'uuid',
},
{ name: 'experimentId', type: 'uuid' },
{ name: 'userId', type: 'uuid' },
{ name: 'variantKey', type: 'varchar' },
{ name: 'convertedAt', type: 'timestamp', isNullable: true },
{
name: 'conversionValue',
type: 'decimal',
precision: 14,
scale: 2,
default: 0,
},
{ name: 'metadata', type: 'jsonb', isNullable: true },
{ name: 'createdAt', type: 'timestamp', default: 'now()' },
{ name: 'updatedAt', type: 'timestamp', default: 'now()' },
],
}),
);

await queryRunner.createIndex(
'savings_experiment_assignments',
new TableIndex({
name: 'IDX_savings_experiment_user_unique',
columnNames: ['experimentId', 'userId'],
isUnique: true,
}),
);

await queryRunner.createIndex(
'savings_experiment_assignments',
new TableIndex({
name: 'IDX_savings_experiment_variant',
columnNames: ['experimentId', 'variantKey'],
}),
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropIndex(
'savings_experiment_assignments',
'IDX_savings_experiment_variant',
);
await queryRunner.dropIndex(
'savings_experiment_assignments',
'IDX_savings_experiment_user_unique',
);
await queryRunner.dropTable('savings_experiment_assignments');
await queryRunner.dropTable('savings_experiments');
}
}
66 changes: 66 additions & 0 deletions backend/src/modules/admin/admin-savings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { Role } from '../../common/enums/role.enum';
import { ExperimentsService } from '../savings/experiments.service';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { ProductCapacitySnapshot } from '../savings/savings.service';
import { PageOptionsDto } from '../../common/dto/page-options.dto';
Expand All @@ -39,6 +40,10 @@ import { AdminSavingsService } from './admin-savings.service';
@Roles(Role.ADMIN)
@Controller({ path: 'admin/savings/products', version: '1' })
export class AdminSavingsController {
constructor(
private readonly savingsService: SavingsService,
private readonly experimentsService: ExperimentsService,
) {}
constructor(private readonly adminSavingsService: AdminSavingsService) {}

@Post()
Expand Down Expand Up @@ -83,6 +88,67 @@ export class AdminSavingsController {
return this.adminSavingsService.getSubscribers(id, opts);
}

@Post('experiments')
@ApiOperation({ summary: 'Create a savings product experiment (admin)' })
@ApiResponse({ status: 201, description: 'Experiment created' })
async createExperiment(
@Body()
body: {
key: string;
name: string;
description?: string;
productId?: string;
variants: Array<{
key: string;
weight: number;
config: Record<string, any>;
}>;
configuration?: Record<string, any>;
minSampleSize?: number;
confidenceLevel?: number;
status?: 'DRAFT' | 'ACTIVE' | 'PAUSED' | 'COMPLETED';
},
) {
return await this.experimentsService.createExperiment(body);
}

@Post('experiments/:id/assignments')
@ApiOperation({ summary: 'Assign a user to an experiment variant (admin)' })
@ApiResponse({ status: 200, description: 'User assigned to a variant' })
async assignExperimentUser(
@Param('id') id: string,
@Body() body: { userId: string },
) {
return await this.experimentsService.assignUser(id, body.userId);
}

@Post('experiments/:id/conversions')
@ApiOperation({ summary: 'Track an experiment conversion event (admin)' })
@ApiResponse({ status: 200, description: 'Conversion tracked' })
async trackExperimentConversion(
@Param('id') id: string,
@Body()
body: {
userId: string;
value?: number;
metadata?: Record<string, any>;
},
) {
return await this.experimentsService.trackConversion(
id,
body.userId,
body.value ?? 1,
body.metadata,
);
}

@Post('experiments/:id/dashboard')
@ApiOperation({ summary: 'Get experiment dashboard statistics (admin)' })
@ApiResponse({ status: 200, description: 'Experiment dashboard' })
async getExperimentDashboard(
@Param('id') id: string,
): Promise<Record<string, unknown>> {
return await this.experimentsService.getDashboard(id);
@Post('products/:id/migrations')
@ApiOperation({
summary: 'Migrate active subscriptions to another product version (admin)',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Index,
} from 'typeorm';

@Entity('savings_experiment_assignments')
@Index(['experimentId', 'userId'], { unique: true })
@Index(['experimentId', 'variantKey'])
export class SavingsExperimentAssignment {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column('uuid')
experimentId: string;

@Column('uuid')
userId: string;

@Column()
variantKey: string;

@Column({ type: 'timestamp', nullable: true })
convertedAt: Date | null;

@Column('decimal', { precision: 14, scale: 2, default: 0 })
conversionValue: number;

@Column({ type: 'jsonb', nullable: true })
metadata: Record<string, any> | null;

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;
}
62 changes: 62 additions & 0 deletions backend/src/modules/savings/entities/savings-experiment.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Index,
} from 'typeorm';

export type ExperimentStatus = 'DRAFT' | 'ACTIVE' | 'PAUSED' | 'COMPLETED';

export interface ExperimentVariant {
key: string;
weight: number;
config: Record<string, any>;
}

@Entity('savings_experiments')
@Index(['status', 'createdAt'])
export class SavingsExperiment {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ unique: true })
key: string;

@Column()
name: string;

@Column({ type: 'text', nullable: true })
description: string | null;

@Column({ type: 'uuid', nullable: true })
productId: string | null;

@Column({ type: 'jsonb' })
variants: ExperimentVariant[];

@Column({ type: 'jsonb', nullable: true })
configuration: Record<string, any> | null;

@Column({ type: 'varchar', default: 'DRAFT' })
status: ExperimentStatus;

@Column({ type: 'int', default: 100 })
minSampleSize: number;

@Column({ type: 'decimal', precision: 4, scale: 2, default: 0.95 })
confidenceLevel: number;

@Column({ type: 'timestamp', nullable: true })
startedAt: Date | null;

@Column({ type: 'timestamp', nullable: true })
endedAt: Date | null;

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;
}
Loading
Loading