generate code
This commit is contained in:
@@ -95,5 +95,10 @@ export class CouponController {
|
||||
validateCouponDto.userId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Get('public/coupons/generate-code')
|
||||
@ApiOperation({ summary: 'generate a coupon code' })
|
||||
generateCouponCode(@RestId() restId: string) {
|
||||
return this.couponService.generateCouponCode(restId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Entity, ManyToOne, Property, Enum } from '@mikro-orm/core';
|
||||
import { Entity, ManyToOne, Property, Enum, Unique } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
|
||||
@@ -8,11 +8,12 @@ export enum CouponType {
|
||||
}
|
||||
|
||||
@Entity({ tableName: 'coupons' })
|
||||
@Unique({ properties: ['code', 'restaurant'] })
|
||||
export class Coupon extends BaseEntity {
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@Property({ unique: true })
|
||||
@Property()
|
||||
code!: string;
|
||||
|
||||
@Property()
|
||||
|
||||
@@ -8,6 +8,7 @@ import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { RequiredEntityData } from '@mikro-orm/core';
|
||||
import { Coupon, CouponType } from '../entities/coupon.entity';
|
||||
import { CouponMessage, RestMessage } from 'src/common/enums/message.enum';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
@Injectable()
|
||||
export class CouponService {
|
||||
@@ -250,4 +251,13 @@ export class CouponService {
|
||||
await this.em.persistAndFlush(coupon);
|
||||
}
|
||||
}
|
||||
|
||||
async generateCouponCode(restId: string): Promise<string> {
|
||||
const code = randomBytes(8).toString('hex');
|
||||
const existingCoupon = await this.couponRepository.findOne({ code, restaurant: { id: restId } });
|
||||
if (existingCoupon) {
|
||||
return this.generateCouponCode(restId);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user