mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-08-25 05:42:27 +00:00
77 lines
2.6 KiB
TypeScript
77 lines
2.6 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { Roles } from '~/auth/enums';
|
|
import { IJwtPayload } from '~/auth/interfaces';
|
|
import { CreateGiftRequestDto, GiftFiltersRequestDto, GiftReplyRequestDto } from '../dtos/request';
|
|
import { Gift, GiftRedemption, GiftReply } from '../entities';
|
|
import { GiftStatus } from '../enums';
|
|
const ONE = 1;
|
|
|
|
@Injectable()
|
|
export class GiftsRepository {
|
|
constructor(@InjectRepository(Gift) private readonly giftsRepository: Repository<Gift>) {}
|
|
|
|
create(guardianId: string, gift: CreateGiftRequestDto): Promise<Gift> {
|
|
return this.giftsRepository.save(
|
|
this.giftsRepository.create({
|
|
name: gift.name,
|
|
description: gift.description,
|
|
amount: gift.amount,
|
|
recipientId: gift.recipientId,
|
|
imageId: gift.imageId,
|
|
color: gift.color,
|
|
giverId: guardianId,
|
|
}),
|
|
);
|
|
}
|
|
|
|
findJuniorGiftById(juniorId: string, giftId: string): Promise<Gift | null> {
|
|
return this.giftsRepository.findOne({
|
|
where: { recipientId: juniorId, id: giftId },
|
|
relations: ['recipient', 'recipient.customer', 'image', 'giver', 'giver.customer', 'reply'],
|
|
});
|
|
}
|
|
|
|
findGuardianGiftById(guardianId: string, giftId: string): Promise<Gift | null> {
|
|
return this.giftsRepository.findOne({
|
|
where: { giverId: guardianId, id: giftId },
|
|
relations: ['recipient', 'recipient.customer', 'image', 'giver', 'giver.customer', 'reply'],
|
|
});
|
|
}
|
|
|
|
findGifts(user: IJwtPayload, filters: GiftFiltersRequestDto) {
|
|
const query = this.giftsRepository.createQueryBuilder('gift');
|
|
if (user.roles.includes(Roles.GUARDIAN)) {
|
|
query.where('gift.giverId = :giverId', { giverId: user.sub });
|
|
} else {
|
|
query.where('gift.recipientId = :recipientId', { recipientId: user.sub });
|
|
}
|
|
query.andWhere('gift.status = :status', { status: filters.status });
|
|
query.skip((filters.page - ONE) * filters.size);
|
|
query.take(filters.size);
|
|
query.orderBy('gift.createdAt', 'DESC');
|
|
return query.getManyAndCount();
|
|
}
|
|
|
|
redeemGift(gift: Gift) {
|
|
const redemptions = gift.redemptions || [];
|
|
gift.status = GiftStatus.REDEEMED;
|
|
gift.redeemedAt = new Date();
|
|
gift.redemptions = [...redemptions, new GiftRedemption()];
|
|
return this.giftsRepository.save(gift);
|
|
}
|
|
|
|
UndoGiftRedemption(gift: Gift) {
|
|
gift.status = GiftStatus.AVAILABLE;
|
|
gift.redeemedAt = null;
|
|
return this.giftsRepository.save(gift);
|
|
}
|
|
|
|
replyToGift(gift: Gift, reply: GiftReplyRequestDto) {
|
|
gift.reply = GiftReply.create({ ...reply });
|
|
|
|
return this.giftsRepository.save(gift);
|
|
}
|
|
}
|