Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create and void invoice #19

Merged
merged 3 commits into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions libs/stripe/src/lib/controllers/invoice.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import { ApiBearerAuth, ApiTags, ApiResponse } from '@nestjs/swagger';
import {
BaseDataResponse,
BaseResponse,
BaseSearchInvoiceDto,
InvoiceDto,
InvoiceFinalizeInvoiceDto,
Expand All @@ -22,6 +23,7 @@ import {
} from '../dto';
import { StripeAuthGuard } from '../stripe-auth.guard';
import { StripeService } from '../stripe.service';
import { CreateInvoiceDto } from '../dto/create-invoice.dto';

@ApiBearerAuth()
@ApiTags('Stripe: Invoice')
Expand Down Expand Up @@ -51,6 +53,12 @@ export class InvoiceController {
return this.stripeService.upcomingInvoicePreview(dto);
}

@ApiResponse({ type: BaseDataResponse<InvoiceDto> })
@Post('')
createInvoice(@Body() dto: CreateInvoiceDto): Promise<BaseDataResponse<InvoiceDto>> {
return this.stripeService.createInvoice(dto);
}

@ApiResponse({ type: BaseDataResponse<InvoiceDto> })
@Patch(':invoiceId/void')
voidInvoice(
Expand Down
114 changes: 114 additions & 0 deletions libs/stripe/src/lib/dto/create-invoice.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { CustomFieldDto, DiscountDto, MetadataDto } from './shared.dto';

export class CreateInvoiceDto {
@ApiPropertyOptional({
description: 'The account tax IDs associated with the invoice. Only editable when the invoice is a draft.',
isArray: true,
type: String
})
accountTaxIds?: Array<string>;

@ApiPropertyOptional({
description: 'A fee in cents (or local equivalent) that will be applied to the invoice and transferred to the application owner\'s Stripe account. The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. For more information, see the application fees [documentation](https://stripe.com/docs/billing/invoices/connect#collecting-fees).'
})
applicationFeeAmount?: number;

@ApiPropertyOptional({
description: 'Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) of the invoice. When `false`, the invoice\'s state will not automatically advance without an explicit action.'
})
autoAdvance?: boolean;

@ApiPropertyOptional({
description: 'Settings for automatic tax lookup for this invoice.\nWhether Stripe automatically computes tax on this invoice. Note that incompatible invoice items (invoice items with manually specified [tax rates](https://stripe.com/docs/api/tax_rates), negative amounts, or `tax_behavior=unspecified`) cannot be added to automatic tax invoices.'
})
automaticTax?: boolean;

@ApiPropertyOptional({
description: 'Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions. Defaults to `charge_automatically`.',
enum: ['charge_automatically', 'send_invoice']
})
collectionMethod?: 'charge_automatically' | 'send_invoice';

@ApiPropertyOptional({ description: 'The currency to create this invoice in. Defaults to that of `customer` if not specified.'})
currency?: string;

@ApiPropertyOptional({
description: 'A list of up to 4 custom fields to be displayed on the invoice.',
isArray: true,
type: CustomFieldDto
})
customFields?: Array<CustomFieldDto>;

@ApiPropertyOptional()
customer?: string;

@ApiPropertyOptional({
description: 'The number of days from when the invoice is created until it is due. Valid only for invoices where `collection_method=send_invoice`.'
})
daysUntilDue?: number;

@ApiPropertyOptional({
description: 'ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription\'s default payment method, if any, or to the default payment method in the customer\'s invoice settings.'
})
defaultPaymentMethodId?: string;

@ApiPropertyOptional({
description: 'ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription\'s default source, if any, or to the customer\'s default source.'
})
defaultSource?: string;

@ApiPropertyOptional({
description: 'The tax rates that will apply to any line item that does not have `tax_rates` set.',
isArray: true,
type: String,
})
defaultTaxRates?: Array<string>;

@ApiPropertyOptional()
description?: string;

@ApiPropertyOptional({
description: 'The coupons to redeem into discounts for the invoice. If not specified, inherits the discount from the invoice\'s customer. Pass an empty string to avoid inheriting any discounts.',
isArray: true,
type: DiscountDto
})
discounts?: Array<DiscountDto>;

@ApiPropertyOptional({
description: ' The date on which payment for this invoice is due. Valid only for invoices where `collection_method=send_invoice`.'
})
dueDate?: number;

@ApiPropertyOptional({ isArray: true, type: String})
expand?: Array<string>;

@ApiPropertyOptional()
footer?: string;

@ApiPropertyOptional({
description: 'Revise an existing invoice. The new invoice will be created in `status=draft`. See the [revision documentation](https://stripe.com/docs/invoicing/invoice-revisions) for more details.'
})
fromInvoice?: string;

@ApiPropertyOptional({
description: 'Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.'
})
metadata?: MetadataDto;

@ApiPropertyOptional({
description: 'The account (if any) for which the funds of the invoice payment are intended. If set, the invoice will be presented with the branding and support information of the specified account. See the [Invoices with Connect](https://stripe.com/docs/billing/invoices/connect) documentation for details.'
})
onBehalfOf?: string;

@ApiPropertyOptional({
description: 'How to handle pending invoice items on invoice creation. One of `include` or `exclude`. `include` will include any pending invoice items, and will create an empty draft invoice if no pending invoice items exist. `exclude` will always create an empty invoice draft regardless if there are pending invoice items or not. Defaults to `exclude` if the parameter is omitted.',
enum: ['exclude', 'include', 'include_and_require']
})
pendingInvoiceItemsBehavior?: 'exclude' | 'include' | 'include_and_require';

@ApiPropertyOptional({
description: 'The ID of the subscription to invoice, if any. If set, the created invoice will only include pending invoice items for that subscription. The subscription\'s billing cycle and regular subscription events won\'t be affected.'
})
subscription?: string;
}
16 changes: 16 additions & 0 deletions libs/stripe/src/lib/dto/shared.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,19 @@ export class DobDto {
@ApiProperty()
year: number | null;
}

export class DiscountDto {
@ApiPropertyOptional({
description: 'ID of the coupon to create a new discount for.'
})
coupon?: string;

@ApiProperty({
description: 'ID of an existing discount on the object (or one of its ancestors) to reuse.'
})
discount?: string;
}

export class MetadataDto {
[name: string]: string | number | null;
}
31 changes: 31 additions & 0 deletions libs/stripe/src/lib/stripe.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import {
} from './dto';
import { StripeConfig, STRIPE_CONFIG } from './stripe.config';
import { StripeLogger } from './stripe.logger';
import { CreateInvoiceDto } from './dto/create-invoice.dto';

@Injectable()
export class StripeService {
Expand Down Expand Up @@ -996,6 +997,36 @@ export class StripeService {
}
}

async createInvoice(dto: CreateInvoiceDto): Promise<BaseDataResponse<InvoiceDto>> {
try {
const invoice = await this.stripe.invoices.create({
account_tax_ids: dto.accountTaxIds,
application_fee_amount: dto.applicationFeeAmount,
auto_advance: dto.autoAdvance,
automatic_tax: dto.automaticTax != null ? { enabled: dto.automaticTax } : undefined,
collection_method: dto.collectionMethod,
currency: dto.currency,
custom_fields: dto.customFields,
customer: dto.customer,
days_until_due: dto.daysUntilDue,
default_payment_method: dto.defaultPaymentMethodId,
default_source: dto.defaultSource,
default_tax_rates: dto.defaultTaxRates,
description: dto.description,
discounts: dto.discounts,
due_date: dto.dueDate,
pending_invoice_items_behavior: dto.pendingInvoiceItemsBehavior,
subscription: dto.subscription,
});
return {
success: true,
data: this.invoiceToDto(invoice)
}
} catch (exception) {
return this.handleError(exception, 'Invoice Create');
}
}

async getInvoiceById(id: string): Promise<BaseDataResponse<InvoiceDto>> {
try {
const invoice = await this.stripe.invoices.retrieve(id);
Expand Down
Loading