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
131 changes: 131 additions & 0 deletions backend/src/migrations/1800410000000-CreateGoalTransferTables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import {
MigrationInterface,
QueryRunner,
Table,
TableForeignKey,
TableIndex,
} from 'typeorm';

export class CreateGoalTransferTables1800410000000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'goal_transfer_schedules',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
generationStrategy: 'uuid',
default: 'uuid_generate_v4()',
},
{ name: 'userId', type: 'uuid', isNullable: false },
{ name: 'goalId', type: 'uuid', isNullable: false },
{ name: 'productId', type: 'uuid', isNullable: true },
{
name: 'amount',
type: 'decimal',
precision: 14,
scale: 7,
isNullable: false,
},
{
name: 'frequency',
type: 'enum',
enum: ['DAILY', 'WEEKLY', 'BI_WEEKLY', 'MONTHLY'],
isNullable: false,
},
{
name: 'status',
type: 'enum',
enum: ['ACTIVE', 'PAUSED', 'CANCELLED'],
default: "'ACTIVE'",
isNullable: false,
},
{ name: 'nextRunAt', type: 'timestamptz', isNullable: false },
{ name: 'retryCount', type: 'int', default: 0 },
{ name: 'createdAt', type: 'timestamp', default: 'now()' },
{ name: 'updatedAt', type: 'timestamp', default: 'now()' },
],
}),
true,
);

await queryRunner.createForeignKey(
'goal_transfer_schedules',
new TableForeignKey({
columnNames: ['userId'],
referencedTableName: 'users',
referencedColumnNames: ['id'],
onDelete: 'CASCADE',
}),
);

await queryRunner.createForeignKey(
'goal_transfer_schedules',
new TableForeignKey({
columnNames: ['goalId'],
referencedTableName: 'savings_goals',
referencedColumnNames: ['id'],
onDelete: 'CASCADE',
}),
);

await queryRunner.createIndex(
'goal_transfer_schedules',
new TableIndex({
name: 'IDX_GOAL_TRANSFER_USER_ID',
columnNames: ['userId'],
}),
);

await queryRunner.createTable(
new Table({
name: 'goal_transfer_executions',
columns: [
{
name: 'id',
type: 'uuid',
isPrimary: true,
generationStrategy: 'uuid',
default: 'uuid_generate_v4()',
},
{ name: 'scheduleId', type: 'uuid', isNullable: false },
{ name: 'userId', type: 'uuid', isNullable: false },
{ name: 'goalId', type: 'uuid', isNullable: false },
{
name: 'amount',
type: 'decimal',
precision: 14,
scale: 7,
isNullable: false,
},
{
name: 'status',
type: 'enum',
enum: ['SUCCESS', 'FAILED'],
isNullable: false,
},
{ name: 'errorMessage', type: 'text', isNullable: true },
{ name: 'executedAt', type: 'timestamp', default: 'now()' },
],
}),
true,
);

await queryRunner.createForeignKey(
'goal_transfer_executions',
new TableForeignKey({
columnNames: ['scheduleId'],
referencedTableName: 'goal_transfer_schedules',
referencedColumnNames: ['id'],
onDelete: 'CASCADE',
}),
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('goal_transfer_executions');
await queryRunner.dropTable('goal_transfer_schedules');
}
}
42 changes: 42 additions & 0 deletions backend/src/modules/savings/dto/goal-transfer.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsNumber, IsOptional, IsUUID, Min } from 'class-validator';
import {
GoalTransferFrequency,
GoalTransferStatus,
} from '../entities/goal-transfer-schedule.entity';
import { IsPositiveAmount } from '../../../common/validators/is-positive-amount.validator';

export class CreateGoalTransferScheduleDto {
@ApiProperty({ example: 'uuid-goal-id' })
@IsUUID()
goalId: string;

@ApiPropertyOptional({ example: 'uuid-product-id' })
@IsOptional()
@IsUUID()
productId?: string;

@ApiProperty({ example: 50, minimum: 0.01 })
@IsNumber()
@IsPositiveAmount()
@Min(0.01)
amount: number;

@ApiProperty({ enum: GoalTransferFrequency })
@IsEnum(GoalTransferFrequency)
frequency: GoalTransferFrequency;
}

export class GoalTransferScheduleResponseDto {
@ApiProperty() id: string;
@ApiProperty() userId: string;
@ApiProperty() goalId: string;
@ApiPropertyOptional() productId: string | null;
@ApiProperty() amount: number;
@ApiProperty({ enum: GoalTransferFrequency })
frequency: GoalTransferFrequency;
@ApiProperty({ enum: GoalTransferStatus }) status: GoalTransferStatus;
@ApiProperty() nextRunAt: Date;
@ApiProperty() createdAt: Date;
@ApiProperty() updatedAt: Date;
}
113 changes: 113 additions & 0 deletions backend/src/modules/savings/entities/goal-transfer-schedule.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
import { SavingsGoal } from './savings-goal.entity';
import { SavingsProduct } from './savings-product.entity';

export enum GoalTransferFrequency {
DAILY = 'DAILY',
WEEKLY = 'WEEKLY',
BI_WEEKLY = 'BI_WEEKLY',
MONTHLY = 'MONTHLY',
}

export enum GoalTransferStatus {
ACTIVE = 'ACTIVE',
PAUSED = 'PAUSED',
CANCELLED = 'CANCELLED',
}

@Entity('goal_transfer_schedules')
export class GoalTransferSchedule {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column('uuid')
userId: string;

@Column('uuid')
goalId: string;

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

@Column('decimal', { precision: 14, scale: 7 })
amount: number;

@Column({ type: 'enum', enum: GoalTransferFrequency })
frequency: GoalTransferFrequency;

@Column({
type: 'enum',
enum: GoalTransferStatus,
default: GoalTransferStatus.ACTIVE,
})
status: GoalTransferStatus;

@Column({ type: 'timestamptz' })
nextRunAt: Date;

@Column({ type: 'int', default: 0 })
retryCount: number;

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;

@ManyToOne(() => User, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'userId' })
user: User;

@ManyToOne(() => SavingsGoal, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'goalId' })
goal: SavingsGoal;

@ManyToOne(() => SavingsProduct, { onDelete: 'SET NULL', nullable: true })
@JoinColumn({ name: 'productId' })
product: SavingsProduct | null;
}

export enum GoalTransferExecutionStatus {
SUCCESS = 'SUCCESS',
FAILED = 'FAILED',
}

@Entity('goal_transfer_executions')
export class GoalTransferExecution {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column('uuid')
scheduleId: string;

@Column('uuid')
userId: string;

@Column('uuid')
goalId: string;

@Column('decimal', { precision: 14, scale: 7 })
amount: number;

@Column({ type: 'enum', enum: GoalTransferExecutionStatus })
status: GoalTransferExecutionStatus;

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

@CreateDateColumn()
executedAt: Date;

@ManyToOne(() => GoalTransferSchedule, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'scheduleId' })
schedule: GoalTransferSchedule;
}
88 changes: 88 additions & 0 deletions backend/src/modules/savings/savings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ import {
AutoDepositResponseDto,
} from './dto/auto-deposit.dto';
import { AutoDepositSchedule } from './entities/auto-deposit-schedule.entity';
import { GoalTransferService } from './services/goal-transfer.service';
import {
CreateGoalTransferScheduleDto,
GoalTransferScheduleResponseDto,
} from './dto/goal-transfer.dto';
import {
GoalTransferSchedule,
GoalTransferExecution,
} from './entities/goal-transfer-schedule.entity';
import {
SavingsGoalProgress,
UserSubscriptionWithLiveBalance,
Expand All @@ -73,6 +82,7 @@ export class SavingsController {
private readonly milestoneService: MilestoneService,
private readonly recommendationService: RecommendationService,
private readonly autoDepositService: AutoDepositService,
private readonly goalTransferService: GoalTransferService,
) {}

@Get('products')
Expand Down Expand Up @@ -530,4 +540,82 @@ export class SavingsController {
): Promise<void> {
return this.autoDepositService.cancel(id, user.id);
}

// ── Goal Auto-Transfer (#930) ──────────────────────────────────────────────

@Post('goal-transfer/create')
@UseGuards(JwtAuthGuard)
@UseInterceptors(IdempotencyInterceptor)
@HttpCode(HttpStatus.CREATED)
@ApiBearerAuth()
@ApiOperation({ summary: 'Create a recurring goal auto-transfer schedule' })
@ApiBody({ type: CreateGoalTransferScheduleDto })
@ApiResponse({ status: 201, type: GoalTransferScheduleResponseDto })
async createGoalTransfer(
@Body() dto: CreateGoalTransferScheduleDto,
@CurrentUser() user: { id: string },
): Promise<GoalTransferSchedule> {
return this.goalTransferService.create(user.id, dto);
}

@Get('goal-transfer')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
summary: 'List goal auto-transfer schedules for current user',
})
@ApiResponse({ status: 200, type: [GoalTransferScheduleResponseDto] })
async getGoalTransfers(
@CurrentUser() user: { id: string },
): Promise<GoalTransferSchedule[]> {
return this.goalTransferService.findAllForUser(user.id);
}

@Patch('goal-transfer/:id/pause')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Pause a goal auto-transfer schedule' })
async pauseGoalTransfer(
@Param('id') id: string,
@CurrentUser() user: { id: string },
): Promise<GoalTransferSchedule> {
return this.goalTransferService.pause(id, user.id);
}

@Patch('goal-transfer/:id/resume')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Resume a paused goal auto-transfer schedule' })
async resumeGoalTransfer(
@Param('id') id: string,
@CurrentUser() user: { id: string },
): Promise<GoalTransferSchedule> {
return this.goalTransferService.resume(id, user.id);
}

@Delete('goal-transfer/:id')
@UseGuards(JwtAuthGuard)
@HttpCode(HttpStatus.NO_CONTENT)
@ApiBearerAuth()
@ApiOperation({ summary: 'Cancel a goal auto-transfer schedule' })
async cancelGoalTransfer(
@Param('id') id: string,
@CurrentUser() user: { id: string },
): Promise<void> {
return this.goalTransferService.cancel(id, user.id);
}

@Get('goal-transfer/:id/executions')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({
summary: 'Get execution history for a goal transfer schedule',
})
@ApiResponse({ status: 200, type: [GoalTransferExecution] })
async getGoalTransferExecutions(
@Param('id') id: string,
@CurrentUser() user: { id: string },
): Promise<GoalTransferExecution[]> {
return this.goalTransferService.getExecutions(id, user.id);
}
}
Loading
Loading