1+ import { Injectable , NotFoundException } from '@nestjs/common' ;
2+ import { InjectRepository } from '@nestjs/typeorm' ;
3+ import { Repository } from 'typeorm' ;
4+
5+ import { Payment } from './entities/payment.entity' ;
6+ import { CreatePaymentDto } from './dto/create-payment.dto' ;
7+ import { RefundPaymentDto } from './dto/refund-payment.dto' ;
8+ import { PaymentStatus } from './enums/payment-status.enum' ;
9+
10+ @Injectable ( )
11+ export class PaymentsService {
12+ constructor (
13+ @InjectRepository ( Payment )
14+ private paymentRepo : Repository < Payment > ,
15+ ) { }
16+
17+ async createPayment ( dto : CreatePaymentDto ) : Promise < Payment > {
18+ const payment = this . paymentRepo . create ( dto ) ;
19+ return this . paymentRepo . save ( payment ) ;
20+ }
21+
22+ async getPayments ( page = 1 , limit = 10 ) {
23+ const [ data , total ] = await this . paymentRepo . findAndCount ( {
24+ skip : ( page - 1 ) * limit ,
25+ take : limit ,
26+ order : { createdAt : 'DESC' } ,
27+ } ) ;
28+
29+ return {
30+ data,
31+ total,
32+ page,
33+ limit,
34+ } ;
35+ }
36+
37+ async getPaymentById ( id : string ) : Promise < Payment > {
38+ const payment = await this . paymentRepo . findOne ( { where : { id } } ) ;
39+
40+ if ( ! payment ) {
41+ throw new NotFoundException ( 'Payment not found' ) ;
42+ }
43+
44+ return payment ;
45+ }
46+
47+ async getPaymentsByOrder ( orderId : string ) : Promise < Payment [ ] > {
48+ return this . paymentRepo . find ( {
49+ where : { orderId } ,
50+ order : { createdAt : 'DESC' } ,
51+ } ) ;
52+ }
53+
54+ async refundPayment ( id : string , dto : RefundPaymentDto ) : Promise < Payment > {
55+ const payment = await this . getPaymentById ( id ) ;
56+
57+ payment . status = PaymentStatus . REFUNDED ;
58+
59+ payment . metadata = {
60+ ...( payment . metadata || { } ) ,
61+ refundReason : dto . reason ,
62+ refundedAt : new Date ( ) ,
63+ } ;
64+
65+ return this . paymentRepo . save ( payment ) ;
66+ }
67+
68+ async handleWebhook ( payload : any ) {
69+ // provider-agnostic webhook handling
70+ // store event metadata for tracking
71+
72+ return {
73+ received : true ,
74+ payload,
75+ } ;
76+ }
77+ }
0 commit comments