-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathcreditNotes.ts
64 lines (54 loc) · 2.03 KB
/
creditNotes.ts
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
import Stripe from 'stripe'
import { getConfig } from '../utils/config'
import { constructUpsertSql } from '../utils/helpers'
import { backfillInvoices } from './invoices'
import { backfillCustomers } from './customers'
import { findMissingEntries, getUniqueIds, upsertMany } from './database_utils'
import { stripe } from '../utils/StripeClientManager'
import { creditNoteSchema } from '../schemas/credit_note'
const config = getConfig()
export const upsertCreditNotes = async (
creditNotes: Stripe.CreditNote[],
backfillRelatedEntities: boolean = true
): Promise<Stripe.CreditNote[]> => {
if (backfillRelatedEntities) {
await Promise.all([
backfillCustomers(getUniqueIds(creditNotes, 'customer')),
backfillInvoices(getUniqueIds(creditNotes, 'invoice')),
])
}
// Stripe only sends the first 10 refunds by default, the option will actively fetch all refunds
if (getConfig().AUTO_EXPAND_LISTS) {
for (const creditNote of creditNotes) {
if (creditNote.lines?.has_more) {
const allLines: Stripe.CreditNoteLineItem[] = []
for await (const lineItem of stripe.creditNotes.listLineItems(creditNote.id, {
limit: 100,
})) {
allLines.push(lineItem)
}
creditNote.lines = {
...creditNote.lines,
data: allLines,
has_more: false,
}
}
}
}
return upsertMany(creditNotes, () =>
constructUpsertSql(config.SCHEMA, 'credit_notes', creditNoteSchema)
)
}
export const backfillCreditNotes = async (creditNoteIds: string[]) => {
const missingCreditNoteIds = await findMissingEntries('credit_notes', creditNoteIds)
await fetchAndInsertCreditNotes(missingCreditNoteIds)
}
const fetchAndInsertCreditNotes = async (creditNoteIds: string[]) => {
if (!creditNoteIds.length) return
const creditNotes: Stripe.CreditNote[] = []
for (const creditNoteId of creditNoteIds) {
const creditNote = await stripe.creditNotes.retrieve(creditNoteId)
creditNotes.push(creditNote)
}
await upsertCreditNotes(creditNotes, true)
}