@@ -2,6 +2,7 @@ package customerbalance
22
33import (
44 "context"
5+ "fmt"
56
67 "github.com/openmeterio/openmeter/openmeter/billing/charges/creditpurchase"
78 "github.com/openmeterio/openmeter/openmeter/billing/charges/meta"
@@ -33,20 +34,26 @@ func (l *fundedCreditTransactionLoader) Load(ctx context.Context, input creditTr
3334
3435 items := make ([]CreditTransaction , 0 , len (result .Items ))
3536 for _ , activity := range result .Items {
37+ balanceCursor , err := l .balanceCursorForFundedActivity (ctx , input .CustomerID .Namespace , activity )
38+ if err != nil {
39+ return creditTransactionLoaderResult {}, err
40+ }
41+
3642 annotations := models.Annotations {
3743 ledger .AnnotationChargeID : activity .ChargeID .ID ,
3844 }
3945
4046 items = append (items , CreditTransaction {
41- ID : models .NamespacedID (activity .ChargeID ),
42- CreatedAt : activity .ChargeCreatedAt ,
43- BookedAt : activity .FundedAt ,
44- Type : CreditTransactionTypeFunded ,
45- Currency : activity .Currency ,
46- Amount : activity .Amount ,
47- Name : activity .Name ,
48- Description : activity .Description ,
49- Annotations : annotations ,
47+ ID : models .NamespacedID (activity .ChargeID ),
48+ CreatedAt : activity .ChargeCreatedAt ,
49+ BookedAt : activity .FundedAt ,
50+ Type : CreditTransactionTypeFunded ,
51+ Currency : activity .Currency ,
52+ Amount : activity .Amount ,
53+ Name : activity .Name ,
54+ Description : activity .Description ,
55+ Annotations : annotations ,
56+ balanceCursor : balanceCursor ,
5057 })
5158 }
5259
@@ -56,6 +63,38 @@ func (l *fundedCreditTransactionLoader) Load(ctx context.Context, input creditTr
5663 }, nil
5764}
5865
66+ func (l * fundedCreditTransactionLoader ) balanceCursorForFundedActivity (
67+ ctx context.Context ,
68+ namespace string ,
69+ activity creditpurchase.FundedCreditActivity ,
70+ ) (* ledger.TransactionCursor , error ) {
71+ if activity .TransactionGroupID == "" {
72+ return nil , nil
73+ }
74+
75+ group , err := l .service .Ledger .GetTransactionGroup (ctx , models.NamespacedID {
76+ Namespace : namespace ,
77+ ID : activity .TransactionGroupID ,
78+ })
79+ if err != nil {
80+ return nil , fmt .Errorf ("get funded credit transaction group %s: %w" , activity .TransactionGroupID , err )
81+ }
82+
83+ for _ , tx := range group .Transactions () {
84+ impact , currency , err := creditTransactionFBOImpact (tx )
85+ if err != nil {
86+ continue
87+ }
88+
89+ if currency == activity .Currency && impact .Equal (activity .Amount ) {
90+ cursor := tx .Cursor ()
91+ return & cursor , nil
92+ }
93+ }
94+
95+ return nil , fmt .Errorf ("funded credit transaction group %s has no matching customer FBO transaction" , activity .TransactionGroupID )
96+ }
97+
5998func toFundedCreditActivityCursor (cursor * ledger.TransactionCursor ) * creditpurchase.FundedCreditActivityCursor {
6099 if cursor == nil {
61100 return nil
0 commit comments