@@ -17,46 +17,54 @@ func (c *stripeAppClient) AddInvoiceLines(ctx context.Context, input AddInvoiceL
1717 return nil , fmt .Errorf ("stripe add invoice lines: invalid input: %w" , err )
1818 }
1919
20- items , err := slicesx .MapWithErr (input .Lines , func (i * stripe.InvoiceItemParams ) (* stripe.InvoiceItem , error ) {
20+ // Add the invoice lines to the Stripe invoice, one by one.
21+ createdInvoiceItems , err := slicesx .MapWithErr (input .Lines , func (i * stripe.InvoiceItemParams ) (* stripe.InvoiceItem , error ) {
2122 i .Invoice = stripe .String (input .StripeInvoiceID )
2223 return c .client .InvoiceItems .New (i )
2324 })
2425 if err != nil {
2526 return nil , fmt .Errorf ("stripe add invoice lines: %w" , err )
2627 }
2728
28- if len (items ) == 0 {
29+ if len (createdInvoiceItems ) == 0 {
2930 return nil , nil
3031 }
3132
33+ // Get the invoice to map the line IDs to the invoice item IDs
3234 invoice , err := c .client .Invoices .Get (input .StripeInvoiceID , nil )
3335 if err != nil {
3436 return nil , fmt .Errorf ("stripe add invoice lines: get invoice: %w" , err )
3537 }
3638
37- itemIDToLineID := make (map [string ]string , len (items ))
39+ // Map the invoice item IDs to the line IDs
40+ capacity := 0
3841 if invoice .Lines != nil {
39- for _ , item := range invoice .Lines .Data {
40- if item != nil && item .InvoiceItem != nil {
41- itemIDToLineID [item .InvoiceItem .ID ] = item .ID
42+ capacity = len (invoice .Lines .Data )
43+ }
44+ itemIDToLineID := make (map [string ]string , capacity )
45+ if invoice .Lines != nil {
46+ for _ , invoiceLineItem := range invoice .Lines .Data {
47+ if invoiceLineItem != nil && invoiceLineItem .InvoiceItem != nil {
48+ itemIDToLineID [invoiceLineItem .InvoiceItem .ID ] = invoiceLineItem .ID
4249 }
4350 }
4451 }
4552
46- lines := make ([]StripeInvoiceItemWithLineID , 0 , len (items ))
47- for _ , item := range items {
48- lineID , found := itemIDToLineID [item .ID ]
53+ // Lookup the line IDs for the invoice items
54+ createdLines := make ([]StripeInvoiceItemWithLineID , 0 , len (createdInvoiceItems ))
55+ for _ , createdInvoiceItem := range createdInvoiceItems {
56+ lineID , found := itemIDToLineID [createdInvoiceItem .ID ]
4957 if ! found {
50- return nil , fmt .Errorf ("stripe add invoice lines: line not found: %s" , item .ID )
58+ return nil , fmt .Errorf ("stripe add invoice lines: line not found: %s" , createdInvoiceItem .ID )
5159 }
5260
53- lines = append (lines , StripeInvoiceItemWithLineID {
54- InvoiceItem : item ,
61+ createdLines = append (createdLines , StripeInvoiceItemWithLineID {
62+ InvoiceItem : createdInvoiceItem ,
5563 LineID : lineID ,
5664 })
5765 }
5866
59- return lines , nil
67+ return createdLines , nil
6068}
6169
6270// UpdateInvoiceLines is the input for updating invoice lines on a Stripe invoice.
0 commit comments