From 0dc4b422b296c62f2b01016cd4441b33fd2637e0 Mon Sep 17 00:00:00 2001 From: Anand Chowdhary Date: Sat, 31 Oct 2020 15:50:19 +0530 Subject: [PATCH] :sparkles: Add Stripe invoices endpoints --- .../stripe/stripe-invoices.controller.ts | 30 ++++++++++++++++++ src/modules/stripe/stripe.service.ts | 31 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 src/modules/stripe/stripe-invoices.controller.ts diff --git a/src/modules/stripe/stripe-invoices.controller.ts b/src/modules/stripe/stripe-invoices.controller.ts new file mode 100644 index 000000000..804a58414 --- /dev/null +++ b/src/modules/stripe/stripe-invoices.controller.ts @@ -0,0 +1,30 @@ +import { Controller, Get, Param, ParseIntPipe, Query } from '@nestjs/common'; +import Stripe from 'stripe'; +import { CursorPipe } from '../../pipes/cursor.pipe'; +import { OptionalIntPipe } from '../../pipes/optional-int.pipe'; +import { Scopes } from '../auth/scope.decorator'; +import { StripeService } from './stripe.service'; + +@Controller('groups/:groupId/invoices') +export class StripeBillingController { + constructor(private stripeService: StripeService) {} + + @Get() + @Scopes('group-{groupId}:read-invoice') + async getAll( + @Param('groupId', ParseIntPipe) groupId: number, + @Query('take', OptionalIntPipe) take?: number, + @Query('cursor', CursorPipe) cursor?: { id: string }, + ): Promise { + return this.stripeService.getInvoices(groupId, { take, cursor }); + } + + @Get(':id') + @Scopes('group-{groupId}:read-invoice-{id}') + async get( + @Param('groupId', ParseIntPipe) groupId: number, + @Param('id') id: string, + ): Promise { + return this.stripeService.getInvoice(groupId, id); + } +} diff --git a/src/modules/stripe/stripe.service.ts b/src/modules/stripe/stripe.service.ts index 09a0f279d..52c83fe69 100644 --- a/src/modules/stripe/stripe.service.ts +++ b/src/modules/stripe/stripe.service.ts @@ -67,6 +67,37 @@ export class StripeService { return result; } + async getInvoices( + groupId: number, + params: { + take?: number; + cursor?: { id: string }; + }, + ): Promise { + const stripeId = await this.stripeId(groupId); + const result = await this.stripe.invoices.list({ + customer: stripeId, + limit: params.take, + starting_after: params.cursor?.id, + }); + return this.list(result); + } + + async getInvoice( + groupId: number, + invoiceId: string, + ): Promise { + const stripeId = await this.stripeId(groupId); + const result = await this.stripe.invoices.retrieve(invoiceId); + if (result.customer !== stripeId) + throw new NotFoundException('Invoice not found'); + return result; + } + + private list(result: Stripe.Response>) { + return result.data; + } + /** Get the Stripe customer ID from a group or throw an error */ private async stripeId(groupId: number): Promise { const group = await this.prisma.groups.findOne({