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
2 changes: 2 additions & 0 deletions backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { RefreshToken } from './entities/refreshToken.entity';
import { SetupTotpProvider } from './providers/setup-totp.provider';
import { VerifyTotpProvider } from './providers/verify-totp.provider';
import { ManageTotpProvider } from './providers/manage-totp.provider';
import { ReferralsModule } from '../referrals/referrals.module';

@Module({
imports: [
Expand All @@ -33,6 +34,7 @@ import { ManageTotpProvider } from './providers/manage-totp.provider';
}),
}),
PassportModule,
ReferralsModule,
],
controllers: [AuthController],
providers: [
Expand Down
17 changes: 17 additions & 0 deletions backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ConflictException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
Expand All @@ -28,9 +29,12 @@ import { Setup2faDto } from './dto/setup-2fa.dto';
import { VerifyTotpDto } from './dto/verify-totp.dto';
import { UseBackupCodeDto } from './dto/use-backup-code.dto';
import { Disable2faDto } from './dto/disable-2fa.dto';
import { ReferralsService } from '../referrals/referrals.service';

@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);

constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
Expand All @@ -40,6 +44,7 @@ export class AuthService {
private readonly setupTotpProvider: SetupTotpProvider,
private readonly verifyTotpProvider: VerifyTotpProvider,
private readonly manageTotpProvider: ManageTotpProvider,
private readonly referralsService: ReferralsService,
) {}

async createUser(createUserDto: CreateUserDto) {
Expand Down Expand Up @@ -74,6 +79,18 @@ export class AuthService {
});
await this.userRepository.save(newUser);

// Track referral relationship if a referral code was provided at signup.
// Failures here must not break registration — log and continue.
if (createUserDto.referralCode) {
this.referralsService
.createReferral(createUserDto.referralCode, newUser.id)
.catch((err: Error) => {
this.logger.warn(
`Failed to record referral ${createUserDto.referralCode}: ${err.message}`,
);
});
}

await this.emailService.sendVerificationEmail(
newUser.email,
verificationCode,
Expand Down
11 changes: 11 additions & 0 deletions backend/src/auth/dto/create-user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
MinLength,
IsNotEmpty,
IsEmail,
IsOptional,
MaxLength,
} from 'class-validator';

Expand All @@ -23,4 +24,14 @@ export class CreateUserDto {
@IsNotEmpty({ message: 'password can not be empty' })
@MinLength(6, { message: 'password must be at least 6 character long' })
password: string;

/**
* Optional referral code captured from the shareable URL
* (e.g. /register?ref=MH-AAAA...) so the new user can be linked
* to the referrer for downstream rewards tracking.
*/
@IsOptional()
@IsString()
@MaxLength(64)
referralCode?: string;
}
2 changes: 2 additions & 0 deletions backend/src/payments/payments.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { BookingsModule } from '../bookings/bookings.module';
import { InvoicesModule } from '../invoices/invoices.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { PromoCodesModule } from '../promo-codes/promo-codes.module';
import { ReferralsModule } from '../referrals/referrals.module';

@Module({
imports: [
Expand All @@ -26,6 +27,7 @@ import { PromoCodesModule } from '../promo-codes/promo-codes.module';
InvoicesModule,
NotificationsModule,
PromoCodesModule,
ReferralsModule,
],
controllers: [PaymentsController],
providers: [
Expand Down
14 changes: 14 additions & 0 deletions backend/src/payments/providers/handle-webhook.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { NotificationType } from '../../notifications/enums/notification-type.en
import { User } from '../../users/entities/user.entity';
import { EmailService } from '../../email/email.service';
import { PromoCodesService } from '../../promo-codes/promo-codes.service';
import { ReferralsService } from '../../referrals/referrals.service';
import { UserCredit } from '../../credits/entities/user-credit.entity';
import { UserCreditTransaction } from '../../credits/entities/credit-transaction.entity';
import { CreditTransactionType } from '../../credits/enums/credit-transaction-type.enum';
Expand Down Expand Up @@ -53,6 +54,7 @@ export class HandleWebhookProvider {
private readonly emailService: EmailService,
private readonly configService: ConfigService,
private readonly promoCodesService: PromoCodesService,
private readonly referralsService: ReferralsService,
) {}

async handle(rawBody: Buffer, signature: string): Promise<void> {
Expand Down Expand Up @@ -148,6 +150,18 @@ export class HandleWebhookProvider {
});
}

// Referral "conversion" — completing a paid booking by a referred user
// marks that referral as COMPLETED and awards the default reward.
if (payment.userId) {
this.referralsService
.completeReferral(payment.userId)
.catch((err: Error) => {
this.logger.error(
`Failed to complete referral for user ${payment.userId}: ${err.message}`,
);
});
}

// Generate invoice asynchronously — do not block payment confirmation
this.invoicesService.generateForPayment(payment.id).catch((err: Error) => {
this.logger.error(
Expand Down
60 changes: 60 additions & 0 deletions backend/src/referrals/entities/referral.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
ManyToOne,
JoinColumn,
CreateDateColumn,
} from 'typeorm';
import { User } from '../../users/entities/user.entity';

export enum ReferralStatus {
PENDING = 'pending',
COMPLETED = 'completed',
}
export enum RewardType {
DISCOUNT = 'discount',
CREDIT = 'credit',
}

@Entity('referrals')
export class Referral {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column('uuid')
referrerId: string;

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

@Column({ type: 'uuid', nullable: true })
referredUserId: string;

@ManyToOne(() => User, { nullable: true, onDelete: 'SET NULL' })
@JoinColumn({ name: 'referredUserId' })
referredUser: User;

@Column()
code: string;

@Column({
type: 'enum',
enum: ReferralStatus,
default: ReferralStatus.PENDING,
})
status: ReferralStatus;

@Column({ type: 'enum', enum: RewardType, nullable: true })
rewardType: RewardType;

@Column({ type: 'int', nullable: true })
rewardValue: number;

@Column({ type: 'timestamptz', nullable: true })
awardedAt: Date;

@CreateDateColumn()
createdAt: Date;
}
25 changes: 16 additions & 9 deletions backend/src/referrals/referrals.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { ReferralsService } from './referrals.service';
import { JwtAuthGuard } from '../auth/guard/jwt.auth.guard';
import { CurrentUser } from '../auth/decorators/current.user.decorators';
import { User } from '../users/entities/user.entity';
import { RolesGuard } from '../auth/guard/roles.guard';
import { Roles } from '../auth/decorators/roles.decorators';
import { GetCurrentUser } from '../auth/decorators/getCurrentUser.decorator';
import { UserRole } from '../users/enums/userRoles.enum';

@ApiTags('Referrals')
@ApiBearerAuth()
Expand All @@ -13,14 +15,19 @@ export class ReferralsController {
constructor(private readonly service: ReferralsService) {}

@Get('my-code')
async getMyCode(@CurrentUser() user: User) {
const data = await this.service.getMyCode(user.id);
return { data };
async getMyCode(@GetCurrentUser('id') userId: string) {
return { data: await this.service.getMyCode(userId) };
}

@Get('history')
async getHistory(@CurrentUser() user: User) {
const data = await this.service.getHistory(user.id);
return { data };
@Get('stats')
async getStats(@GetCurrentUser('id') userId: string) {
return { data: await this.service.getStats(userId) };
}

@Get()
@UseGuards(RolesGuard)
@Roles(UserRole.ADMIN, UserRole.SUPER_ADMIN)
async getAll() {
return { data: await this.service.getAll() };
}
}
4 changes: 3 additions & 1 deletion backend/src/referrals/referrals.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from '../users/entities/user.entity';
import { Referral } from './entities/referral.entity';
import { ReferralsService } from './referrals.service';
import { ReferralsController } from './referrals.controller';

@Module({
imports: [TypeOrmModule.forFeature([User])],
imports: [TypeOrmModule.forFeature([User, Referral])],
controllers: [ReferralsController],
providers: [ReferralsService],
exports: [ReferralsService],
})
export class ReferralsModule {}
Loading
Loading