All files / src/modules/promotions promotions.service.ts

80.76% Statements 21/26
90% Branches 9/10
80% Functions 4/5
72.22% Lines 13/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 4313x 13x     13x 3x                     2x 2x 1x             2x 2x 1x         2x 2x 1x                
import { ForbiddenException, Injectable } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
 
@Injectable()
export class PromotionsService {
  constructor(private readonly prisma: PrismaService) {}
 
  options() {
    return [
      { sku: 'HIGHLIGHT', priceCents: 500_00 },
      { sku: 'URGENT', priceCents: 700_00 },
      { sku: 'TOP_OF_LIST', priceCents: 1200_00 },
    ];
  }
 
  async purchase(listingId: number, userId: number, dto: { sku: string; startAt: Date; endAt: Date }) {
    const listing = await this.prisma.client.listing.findUnique({ where: { id: listingId } });
    if (!listing) throw new Error('Listing not found');
    if (listing.userId !== userId) throw new ForbiddenException('Not owner');
    return this.prisma.client.promotion.create({
      data: { listingId, sku: dto.sku, startAt: dto.startAt, endAt: dto.endAt },
    });
  }
 
  async listForOwner(listingId: number, userId: number) {
    const listing = await this.prisma.client.listing.findUnique({ where: { id: listingId } });
    if (!listing) throw new Error('Listing not found');
    if (listing.userId !== userId) throw new ForbiddenException('Not owner');
    return this.prisma.client.promotion.findMany({ where: { listingId }, orderBy: { endAt: 'desc' } });
  }
 
  async cancel(promoId: number, userId: number) {
    const promo = await this.prisma.client.promotion.findUnique({ where: { id: promoId }, include: { listing: true } } as any);
    if (!promo) return { ok: true };
    if (promo.listing.userId !== userId) throw new ForbiddenException('Not owner');
    // Soft cancel via inactive flag
    await this.prisma.client.promotion.update({ where: { id: promoId }, data: { active: false } });
    return { ok: true };
  }
}