All files / src/features/donation donation.service.ts

98.59% Statements 70/71
79.66% Branches 47/59
100% Functions 7/7
98.48% Lines 65/66

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270                          24x 24x 24x 24x 24x                                       1x                               1x                   1x 1x 1x 1x 1x                       1x       6x     6x 4x 4x 1x     1x       6x 3x     3x 1x   2x       4x 4x                               1x 1x                         1x             7x 7x   6x 1x     5x   5x   4x 2x 1x   1x   2x 2x 2x   1x   1x 1x         3x                         1x   1x 1x   1x 1x           1x                             1x             1x 1x 1x 1x 1x           1x         1x                       1x   1x 1x                       1x     1x      
import { Injectable } from '@nestjs/common'
import { PrismaService } from '../../database/prisma.service'
import { CreateDonationParams } from './interfaces/donation-service.interface'
import { BadRequestException, NotFoundException } from '@nestjs/common'
 
import { PaymentService } from './services/payment.service'
import { GatewayGateway } from '../gateway/gateway.gateway'
import { EmailProducer } from '../queue/producers/email.producer'
import { EventsService } from '../events/events.service'
 
@Injectable()
export class DonationService {
    constructor(
        private readonly prisma: PrismaService,
        private readonly paymentService: PaymentService,
        private readonly donationGateway: GatewayGateway,
        private readonly emailProducer: EmailProducer,
        private readonly eventsService: EventsService,
    ) {}
 
    /**
     * Unified processor for successful donations from any source (Stripe, PayPal, Offline)
     */
    async processSuccessfulDonation(data: {
        amount: number
        currency: string
        transactionId: string
        paymentMethod: string
        donorName?: string
        donorEmail?: string
        isAnonymous?: boolean
        message?: string
        metadata?: any
        eventId: string
        staffMemberId?: string
    }) {
        // 1. Persist to DB
        const donation = await this.create({
            amount: data.amount,
            currency: data.currency,
            transactionId: data.transactionId,
            status: 'COMPLETED',
            paymentMethod: data.paymentMethod,
            donorName: data.donorName,
            donorEmail: data.donorEmail,
            isAnonymous: data.isAnonymous,
            message: data.message,
            metadata: data.metadata,
            eventId: data.eventId,
            staffMemberId: data.staffMemberId,
        })
 
        // 2. Emit to Live Screen
        this.donationGateway.emitDonation({
            amount: data.amount,
            currency: data.currency,
            donorName: data.donorName || 'Anonymous',
            message: data.message,
            isAnonymous: data.isAnonymous,
            eventId: data.eventId,
        })
 
        // 3. Send Email Receipt
        Eif (data.donorEmail) {
            try {
                const event = await this.eventsService.findOne(data.eventId)
                Eif (event) {
                    await this.emailProducer.sendReceipt(
                        data.donorEmail,
                        data.amount / 100,
                        data.transactionId,
                        event.slug,
                    )
                }
            } catch (e) {
                console.error('Failed to send receipt email', e)
            }
        }
 
        return donation
    }
 
    async create(data: CreateDonationParams) {
        let eventId = data.eventId
 
        // Validate if provided event exists
        if (eventId) {
            const exists = await this.prisma.event.count({ where: { id: eventId } })
            if (exists === 0) {
                console.warn(
                    `Donation attempt with invalid eventId: ${eventId}. Falling back to default.`,
                )
                eventId = undefined
            }
        }
 
        if (!eventId) {
            const defaultEvent = await this.prisma.event.findFirst({
                select: { id: true },
            })
            if (defaultEvent) {
                eventId = defaultEvent.id
            } else {
                throw new Error('No event found to link donation to.')
            }
        }
 
        try {
            return await this.prisma.donation.create({
                data: {
                    amount: data.amount,
                    currency: data.currency || 'EUR',
                    donorName: data.donorName,
                    donorEmail: data.donorEmail,
                    message: data.message,
                    isAnonymous: data.isAnonymous ?? false,
                    status: data.status,
                    paymentMethod: data.paymentMethod,
                    transactionId: data.transactionId,
                    eventId: eventId,
                    staffMemberId: data.staffMemberId,
                },
            })
        } catch (error) {
            console.error('Error creating donation:', error)
            throw error
        }
    }
 
    async update(
        id: string,
        data: {
            donorName?: string
            donorEmail?: string
            isAnonymous?: boolean
            message?: string
        },
    ) {
        return this.prisma.donation.update({
            where: { id },
            data,
        })
    }
 
    async cancel(id: string, shouldRefund: boolean = false) {
        const donation = await this.prisma.donation.findUnique({ where: { id } })
        if (!donation) throw new NotFoundException('Donation not found')
 
        if (donation.status === 'CANCELLED' || donation.status === 'REFUNDED') {
            throw new BadRequestException('Donation is already cancelled or refunded')
        }
 
        let newStatus = 'CANCELLED'
 
        if (shouldRefund) {
            // Verify refund capability
            if (!donation.transactionId) {
                if (donation.paymentMethod === 'stripe' || donation.paymentMethod === 'paypal') {
                    throw new BadRequestException('Cannot refund: Missing Transaction ID')
                }
                newStatus = 'REFUNDED' // Cash/Other just mark refunded
            } else {
                try {
                    Eif (donation.transactionId) {
                        await this.paymentService.refundDonation(donation.transactionId)
                    }
                    newStatus = 'REFUNDED'
                } catch (error) {
                    console.error('Refund failed:', error)
                    throw new BadRequestException('Failed to process refund')
                }
            }
        }
 
        return this.prisma.donation.update({
            where: { id },
            data: { status: newStatus },
        })
    }
 
    async findAll(
        eventId?: string,
        limit: number = 50,
        offset: number = 0,
        search?: string,
        status?: string,
    ) {
        const where: any = {}
 
        Eif (eventId) where.eventId = eventId
        Eif (status && status !== 'all') where.status = status
 
        Eif (search) {
            where.OR = [
                { donorName: { contains: search, mode: 'insensitive' } },
                { donorEmail: { contains: search, mode: 'insensitive' } },
            ]
        }
 
        const [data, total] = await Promise.all([
            this.prisma.donation.findMany({
                where,
                orderBy: { createdAt: 'desc' },
                take: Number(limit),
                skip: Number(offset),
                include: {
                    staffMember: {
                        select: { id: true, name: true, code: true },
                    },
                },
            }),
            this.prisma.donation.count({ where }),
        ])
 
        return { data, total }
    }
 
    /**
     * Generates a CSV string for all donations matching the criteria.
     */
    async getExportData(eventId?: string, search?: string, status?: string): Promise<string> {
        const where: any = {}
        Eif (eventId) where.eventId = eventId
        Eif (status && status !== 'all') where.status = status
        Eif (search) {
            where.OR = [
                { donorName: { contains: search, mode: 'insensitive' } },
                { donorEmail: { contains: search, mode: 'insensitive' } },
            ]
        }
 
        const donations = await this.prisma.donation.findMany({
            where,
            orderBy: { createdAt: 'desc' },
        })
 
        const headers = [
            'ID',
            'Date',
            'Donor Name',
            'Donor Email',
            'Amount',
            'Currency',
            'Status',
            'Payment Method',
            'Message',
            'Anonymous',
        ]
        const csvRows = [headers.join(',')]
 
        for (const donation of donations) {
            const row = [
                donation.id,
                donation.createdAt.toISOString(),
                `"${(donation.donorName || '').replace(/"/g, '""')}"`,
                donation.donorEmail || '',
                donation.amount.toString(),
                donation.currency,
                donation.status,
                donation.paymentMethod,
                `"${(donation.message || '').replace(/"/g, '""')}"`,
                donation.isAnonymous,
            ]
            csvRows.push(row.join(','))
        }
 
        return csvRows.join('\n')
    }
}