usage.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. package billing
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/getlago/lago-go-client"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/telemetry"
  13. )
  14. const (
  15. lagoBaseURL = "https://api.getlago.com"
  16. defaultStarterCreditsCents = 500
  17. defaultRewardAmountCents = 1000
  18. maxReferralRewards = 10
  19. defaultMaxRetries = 10
  20. maxIngestEventLimit = 100
  21. // porterStandardTrialDays is the number of days for the trial
  22. porterStandardTrialDays = 15
  23. // These prefixes are used to build the customer and subscription IDs
  24. // in Lago. This way we can reuse the project IDs instead of storing
  25. // the Lago IDs in the database.
  26. // TrialIDPrefix is the prefix for the trial ID
  27. TrialIDPrefix = "trial"
  28. // SubscriptionIDPrefix is the prefix for the subscription ID
  29. SubscriptionIDPrefix = "sub"
  30. // CustomerIDPrefix is the prefix for the customer ID
  31. CustomerIDPrefix = "cus"
  32. )
  33. // LagoClient is the client used to call the Lago API
  34. type LagoClient struct {
  35. client lago.Client
  36. lagoApiKey string
  37. PorterCloudPlanCode string
  38. PorterStandardPlanCode string
  39. PorterTrialCode string
  40. // DefaultRewardAmountCents is the default amount in USD cents rewarded to users
  41. // who successfully refer a new user
  42. DefaultRewardAmountCents int64
  43. // MaxReferralRewards is the maximum number of referral rewards a user can receive
  44. MaxReferralRewards int64
  45. }
  46. // NewLagoClient returns a new Lago client
  47. func NewLagoClient(lagoApiKey string, porterCloudPlanCode string, porterStandardPlanCode string, porterTrialCode string) (client LagoClient, err error) {
  48. lagoClient := lago.New().SetApiKey(lagoApiKey)
  49. if lagoClient == nil {
  50. return client, fmt.Errorf("failed to create lago client")
  51. }
  52. return LagoClient{
  53. lagoApiKey: lagoApiKey,
  54. client: *lagoClient,
  55. PorterCloudPlanCode: porterCloudPlanCode,
  56. PorterStandardPlanCode: porterStandardPlanCode,
  57. PorterTrialCode: porterTrialCode,
  58. DefaultRewardAmountCents: defaultRewardAmountCents,
  59. MaxReferralRewards: maxReferralRewards,
  60. }, nil
  61. }
  62. // CreateCustomerWithPlan will create the customer in Lago and immediately add it to the plan
  63. func (m LagoClient) CreateCustomerWithPlan(ctx context.Context, userEmail string, projectName string, projectID uint, billingID string, sandboxEnabled bool) (err error) {
  64. ctx, span := telemetry.NewSpan(ctx, "add-lago-customer-plan")
  65. defer span.End()
  66. if projectID == 0 {
  67. return telemetry.Error(ctx, span, err, "project id empty")
  68. }
  69. customerID, err := m.createCustomer(ctx, userEmail, projectName, projectID, billingID, sandboxEnabled)
  70. if err != nil {
  71. return telemetry.Error(ctx, span, err, "error while creating customer")
  72. }
  73. trialID := m.generateLagoID(TrialIDPrefix, projectID, sandboxEnabled)
  74. subscriptionID := m.generateLagoID(SubscriptionIDPrefix, projectID, sandboxEnabled)
  75. // The dates need to be at midnight UTC
  76. now := time.Now().UTC()
  77. now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  78. trialEndTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).Add(time.Hour * 24 * porterStandardTrialDays).UTC()
  79. if sandboxEnabled {
  80. err = m.addCustomerPlan(ctx, customerID, m.PorterCloudPlanCode, subscriptionID, &now, nil)
  81. if err != nil {
  82. return telemetry.Error(ctx, span, err, fmt.Sprintf("error while adding customer to plan %s", m.PorterCloudPlanCode))
  83. }
  84. walletName := "Porter Credits"
  85. err = m.CreateCreditsGrant(ctx, projectID, walletName, defaultStarterCreditsCents, sandboxEnabled)
  86. if err != nil {
  87. return telemetry.Error(ctx, span, err, "error while creating starter credits grant")
  88. }
  89. return nil
  90. }
  91. // First, start the new customer on the trial
  92. err = m.addCustomerPlan(ctx, customerID, m.PorterTrialCode, trialID, &now, &trialEndTime)
  93. if err != nil {
  94. return telemetry.Error(ctx, span, err, fmt.Sprintf("error while starting customer trial %s", m.PorterTrialCode))
  95. }
  96. // Then, add the customer to the actual plan. The date of the subscription will be the end of the trial
  97. err = m.addCustomerPlan(ctx, customerID, m.PorterStandardPlanCode, subscriptionID, &trialEndTime, nil)
  98. if err != nil {
  99. return telemetry.Error(ctx, span, err, fmt.Sprintf("error while adding customer to plan %s", m.PorterStandardPlanCode))
  100. }
  101. return err
  102. }
  103. // CheckIfCustomerExists will check if the customer exists in Lago
  104. func (m LagoClient) CheckIfCustomerExists(ctx context.Context, projectID uint, enableSandbox bool) (exists bool, err error) {
  105. ctx, span := telemetry.NewSpan(ctx, "check-lago-customer-exists")
  106. defer span.End()
  107. if projectID == 0 {
  108. return exists, telemetry.Error(ctx, span, err, "project id empty")
  109. }
  110. customerID := m.generateLagoID(CustomerIDPrefix, projectID, enableSandbox)
  111. _, lagoErr := m.client.Customer().Get(ctx, customerID)
  112. if lagoErr != nil {
  113. if lagoErr.ErrorCode == "customer_not_found" {
  114. return false, nil
  115. }
  116. return exists, telemetry.Error(ctx, span, lagoErr.Err, "failed to get customer")
  117. }
  118. return true, nil
  119. }
  120. // GetCustomerActivePlan will return the active plan for the customer
  121. func (m LagoClient) GetCustomerActivePlan(ctx context.Context, projectID uint, sandboxEnabled bool) (plan types.Plan, err error) {
  122. ctx, span := telemetry.NewSpan(ctx, "get-active-subscription")
  123. defer span.End()
  124. if projectID == 0 {
  125. return plan, telemetry.Error(ctx, span, err, "project id empty")
  126. }
  127. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  128. telemetry.WithAttributes(span,
  129. telemetry.AttributeKV{Key: "customer_id", Value: customerID},
  130. )
  131. activeSubscriptions, err := m.getCustomerActiveSubscription(ctx, customerID)
  132. if err != nil {
  133. return plan, telemetry.Error(ctx, span, err, "failed to get active subscriptions")
  134. }
  135. if activeSubscriptions == nil {
  136. return plan, telemetry.Error(ctx, span, err, "no active subscriptions found")
  137. }
  138. for _, subscription := range activeSubscriptions {
  139. if subscription.Status != string(lago.SubscriptionStatusActive) {
  140. continue
  141. }
  142. plan.ID = subscription.ExternalID
  143. plan.CustomerID = subscription.ExternalCustomerID
  144. plan.StartingOn = subscription.SubscriptionAt
  145. if subscription.EndingAt != "" {
  146. plan.EndingBefore = subscription.EndingAt
  147. }
  148. if strings.Contains(subscription.ExternalID, TrialIDPrefix) {
  149. plan.TrialInfo.EndingBefore = subscription.EndingAt
  150. }
  151. break
  152. }
  153. return plan, nil
  154. }
  155. // DeleteCustomer will delete the customer and terminate all subscriptions
  156. func (m LagoClient) DeleteCustomer(ctx context.Context, projectID uint, sandboxEnabled bool) (err error) {
  157. ctx, span := telemetry.NewSpan(ctx, "delete-lago-customer")
  158. defer span.End()
  159. if projectID == 0 {
  160. return telemetry.Error(ctx, span, err, "subscription id empty")
  161. }
  162. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  163. _, lagoErr := m.client.Customer().Delete(ctx, customerID)
  164. if lagoErr != nil {
  165. return telemetry.Error(ctx, span, lagoErr.Err, "failed to terminate subscription")
  166. }
  167. return nil
  168. }
  169. // ListCustomerCredits will return the total number of credits for the customer
  170. func (m LagoClient) ListCustomerCredits(ctx context.Context, projectID uint, sandboxEnabled bool) (credits types.ListCreditGrantsResponse, err error) {
  171. ctx, span := telemetry.NewSpan(ctx, "list-customer-credits")
  172. defer span.End()
  173. if projectID == 0 {
  174. return credits, telemetry.Error(ctx, span, err, "project id empty")
  175. }
  176. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  177. walletList, err := m.listCustomerWallets(ctx, customerID)
  178. if err != nil {
  179. return credits, telemetry.Error(ctx, span, err, "failed to list customer wallets")
  180. }
  181. var response types.ListCreditGrantsResponse
  182. for _, wallet := range walletList {
  183. if wallet.Status != string(lago.Active) {
  184. continue
  185. }
  186. response.GrantedBalanceCents += wallet.BalanceCents
  187. response.RemainingBalanceCents += wallet.OngoingBalanceCents
  188. }
  189. return response, nil
  190. }
  191. // CheckCustomerCouponExpiration will return the expiration date of the customer's coupon
  192. func (m LagoClient) CheckCustomerCouponExpiration(ctx context.Context, projectID uint, sandboxEnabled bool) (trialEndDate string, err error) {
  193. ctx, span := telemetry.NewSpan(ctx, "list-customer-coupons")
  194. defer span.End()
  195. if projectID == 0 {
  196. return trialEndDate, telemetry.Error(ctx, span, err, "project id empty")
  197. }
  198. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  199. couponList, err := m.listCustomerAppliedCoupons(ctx, customerID)
  200. if err != nil {
  201. return trialEndDate, telemetry.Error(ctx, span, err, "failed to list customer coupons")
  202. }
  203. if len(couponList) == 0 {
  204. return trialEndDate, nil
  205. }
  206. appliedCoupon := couponList[0]
  207. trialEndDate = time.Now().UTC().AddDate(0, appliedCoupon.FrequencyDurationRemaining, 0).Format(time.RFC3339)
  208. return trialEndDate, nil
  209. }
  210. // CreateCreditsGrant will create a new credit grant for the customer with the specified amount
  211. func (m LagoClient) CreateCreditsGrant(ctx context.Context, projectID uint, name string, grantAmount int64, sandboxEnabled bool) (err error) {
  212. ctx, span := telemetry.NewSpan(ctx, "create-credits-grant")
  213. defer span.End()
  214. if projectID == 0 {
  215. return telemetry.Error(ctx, span, err, "project id empty")
  216. }
  217. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  218. walletList, err := m.listCustomerWallets(ctx, customerID)
  219. if err != nil {
  220. return telemetry.Error(ctx, span, err, "failed to list customer wallets")
  221. }
  222. if len(walletList) == 0 {
  223. walletInput := &lago.WalletInput{
  224. ExternalCustomerID: customerID,
  225. Name: name,
  226. Currency: lago.USD,
  227. GrantedCredits: strconv.FormatInt(grantAmount, 10),
  228. // Rate is 1 credit = 1 cent
  229. RateAmount: "0.01",
  230. }
  231. _, lagoErr := m.client.Wallet().Create(ctx, walletInput)
  232. if lagoErr != nil {
  233. return telemetry.Error(ctx, span, lagoErr.Err, "failed to create wallet")
  234. }
  235. return nil
  236. }
  237. // Currently only one wallet per customer is supported in Lago
  238. wallet := walletList[0]
  239. walletTransactionInput := &lago.WalletTransactionInput{
  240. WalletID: wallet.LagoID.String(),
  241. GrantedCredits: strconv.FormatInt(grantAmount, 10),
  242. }
  243. // If the wallet already exists, we need to update the balance
  244. _, lagoErr := m.client.WalletTransaction().Create(ctx, walletTransactionInput)
  245. if lagoErr != nil {
  246. return telemetry.Error(ctx, span, lagoErr.Err, "failed to update credits grant")
  247. }
  248. return nil
  249. }
  250. // ListCustomerUsage will return the aggregated usage for a customer
  251. func (m LagoClient) ListCustomerUsage(ctx context.Context, customerID string, subscriptionID string, currentPeriod bool, previousPeriods int) (usageList []types.Usage, err error) {
  252. ctx, span := telemetry.NewSpan(ctx, "list-customer-usage")
  253. defer span.End()
  254. if subscriptionID == "" {
  255. return usageList, telemetry.Error(ctx, span, err, "subscription id empty")
  256. }
  257. if currentPeriod {
  258. customerUsageInput := &lago.CustomerUsageInput{
  259. ExternalSubscriptionID: subscriptionID,
  260. }
  261. currentUsage, lagoErr := m.client.Customer().CurrentUsage(ctx, customerID, customerUsageInput)
  262. if lagoErr != nil {
  263. return usageList, telemetry.Error(ctx, span, lagoErr.Err, "failed to get customer usage")
  264. }
  265. if currentUsage == nil {
  266. return usageList, nil
  267. }
  268. usage := createUsageFromLagoUsage(*currentUsage)
  269. usageList = append(usageList, usage)
  270. } else {
  271. url := fmt.Sprintf("%s/api/v1/customers/%s/past_usage?external_subscription_id=%s&periods_count=%d", lagoBaseURL, customerID, subscriptionID, previousPeriods)
  272. req, err := http.NewRequest("GET", url, nil)
  273. if err != nil {
  274. return usageList, telemetry.Error(ctx, span, err, "failed to create wallets request")
  275. }
  276. req.Header.Set("Authorization", "Bearer "+m.lagoApiKey)
  277. client := &http.Client{}
  278. resp, err := client.Do(req)
  279. if err != nil {
  280. return usageList, telemetry.Error(ctx, span, err, "failed to get customer credits")
  281. }
  282. var previousUsage lago.CustomerPastUsageResult
  283. err = json.NewDecoder(resp.Body).Decode(&previousUsage)
  284. if err != nil {
  285. return usageList, telemetry.Error(ctx, span, err, "failed to decode usage list response")
  286. }
  287. for _, pastUsage := range previousUsage.UsagePeriods {
  288. usage := createUsageFromLagoUsage(pastUsage)
  289. usageList = append(usageList, usage)
  290. }
  291. }
  292. return usageList, nil
  293. }
  294. // IngestEvents sends a list of billing events to Lago's ingest endpoint
  295. func (m LagoClient) IngestEvents(ctx context.Context, subscriptionID string, events []types.BillingEvent, enableSandbox bool) (err error) {
  296. ctx, span := telemetry.NewSpan(ctx, "ingest-billing-events")
  297. defer span.End()
  298. if len(events) == 0 {
  299. return nil
  300. }
  301. for i := 0; i < len(events); i += maxIngestEventLimit {
  302. end := i + maxIngestEventLimit
  303. if end > len(events) {
  304. end = len(events)
  305. }
  306. batch := events[i:end]
  307. var batchInput []lago.EventInput
  308. for i := range batch {
  309. projectID, err := strconv.ParseUint(batch[i].CustomerID, 10, 64)
  310. if err != nil {
  311. return telemetry.Error(ctx, span, err, "failed to parse project id")
  312. }
  313. if enableSandbox {
  314. // For Porter Cloud, we can't infer the project ID from the request, so we
  315. // instead use the one in the billing event
  316. subscriptionID = m.generateLagoID(SubscriptionIDPrefix, uint(projectID), enableSandbox)
  317. }
  318. event := lago.EventInput{
  319. TransactionID: batch[i].TransactionID,
  320. ExternalSubscriptionID: subscriptionID,
  321. Code: batch[i].EventType,
  322. Properties: batch[i].Properties,
  323. }
  324. batchInput = append(batchInput, event)
  325. }
  326. // Retry each batch to make sure all events are ingested
  327. var currentAttempts int
  328. for currentAttempts := 0; currentAttempts < defaultMaxRetries; currentAttempts++ {
  329. _, lagoErr := m.client.Event().Batch(ctx, &batchInput)
  330. if lagoErr == nil {
  331. return nil
  332. }
  333. }
  334. if currentAttempts == defaultMaxRetries {
  335. return telemetry.Error(ctx, span, err, "max number of retry attempts reached with no success")
  336. }
  337. }
  338. return nil
  339. }
  340. // ListCustomerFinalizedInvoices will return all finalized invoices for the customer
  341. func (m LagoClient) ListCustomerFinalizedInvoices(ctx context.Context, projectID uint, enableSandbox bool) (invoiceList []types.Invoice, err error) {
  342. ctx, span := telemetry.NewSpan(ctx, "list-customer-invoices")
  343. defer span.End()
  344. if projectID == 0 {
  345. return invoiceList, telemetry.Error(ctx, span, err, "project id cannot be empty")
  346. }
  347. customerID := m.generateLagoID(CustomerIDPrefix, projectID, enableSandbox)
  348. invoiceListInput := &lago.InvoiceListInput{
  349. ExternalCustomerID: customerID,
  350. Status: lago.InvoiceStatusFinalized,
  351. }
  352. invoices, lagoErr := m.client.Invoice().GetList(ctx, invoiceListInput)
  353. if lagoErr != nil {
  354. return invoiceList, telemetry.Error(ctx, span, lagoErr.Err, "failed to list invoices")
  355. }
  356. for _, invoice := range invoices.Invoices {
  357. invoiceReq, lagoErr := m.client.Invoice().Download(ctx, invoice.LagoID.String())
  358. if lagoErr != nil {
  359. return invoiceList, telemetry.Error(ctx, span, lagoErr.Err, "failed to download invoice")
  360. }
  361. var fileURL string
  362. if invoiceReq == nil {
  363. fileURL = invoice.FileURL
  364. } else {
  365. fileURL = invoiceReq.FileURL
  366. }
  367. invoiceList = append(invoiceList, types.Invoice{
  368. HostedInvoiceURL: fileURL,
  369. Status: string(invoice.Status),
  370. Created: invoice.IssuingDate,
  371. })
  372. }
  373. return invoiceList, nil
  374. }
  375. // createCustomer will create the customer in Lago
  376. func (m LagoClient) createCustomer(ctx context.Context, userEmail string, projectName string, projectID uint, billingID string, sandboxEnabled bool) (customerID string, err error) {
  377. ctx, span := telemetry.NewSpan(ctx, "create-lago-customer")
  378. defer span.End()
  379. customerID = m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  380. customerInput := &lago.CustomerInput{
  381. ExternalID: customerID,
  382. Name: projectName,
  383. Email: userEmail,
  384. BillingConfiguration: lago.CustomerBillingConfigurationInput{
  385. PaymentProvider: lago.PaymentProviderStripe,
  386. ProviderCustomerID: billingID,
  387. Sync: false,
  388. SyncWithProvider: false,
  389. },
  390. }
  391. _, lagoErr := m.client.Customer().Create(ctx, customerInput)
  392. if lagoErr != nil {
  393. return customerID, telemetry.Error(ctx, span, lagoErr.Err, "failed to create lago customer")
  394. }
  395. return customerID, nil
  396. }
  397. // addCustomerPlan will create a plan subscription for the customer
  398. func (m LagoClient) addCustomerPlan(ctx context.Context, customerID string, planID string, subscriptionID string, startingAt *time.Time, endingAt *time.Time) (err error) {
  399. ctx, span := telemetry.NewSpan(ctx, "add-lago-customer-plan")
  400. defer span.End()
  401. if customerID == "" || planID == "" {
  402. return telemetry.Error(ctx, span, err, "project and plan id are required")
  403. }
  404. subscriptionInput := &lago.SubscriptionInput{
  405. ExternalCustomerID: customerID,
  406. ExternalID: subscriptionID,
  407. PlanCode: planID,
  408. SubscriptionAt: startingAt,
  409. EndingAt: endingAt,
  410. BillingTime: lago.Calendar,
  411. }
  412. _, lagoErr := m.client.Subscription().Create(ctx, subscriptionInput)
  413. if lagoErr != nil {
  414. return telemetry.Error(ctx, span, lagoErr.Err, "failed to create subscription")
  415. }
  416. return nil
  417. }
  418. func (m LagoClient) getCustomerActiveSubscription(ctx context.Context, customerID string) (subscriptions []types.Subscription, err error) {
  419. ctx, span := telemetry.NewSpan(ctx, "list-customer-active-subscriptions")
  420. defer span.End()
  421. url := fmt.Sprintf("%s/api/v1/subscriptions?external_customer_id=%s&status[]=%s", lagoBaseURL, customerID, lago.SubscriptionStatusActive)
  422. req, err := http.NewRequest("GET", url, nil)
  423. if err != nil {
  424. return subscriptions, telemetry.Error(ctx, span, err, "failed to create list subscriptions request")
  425. }
  426. req.Header.Set("Authorization", "Bearer "+m.lagoApiKey)
  427. client := &http.Client{}
  428. resp, err := client.Do(req)
  429. if err != nil {
  430. return subscriptions, telemetry.Error(ctx, span, err, "failed to get customer subscriptions")
  431. }
  432. var response struct {
  433. Subscriptions []types.Subscription `json:"subscriptions"`
  434. }
  435. err = json.NewDecoder(resp.Body).Decode(&response)
  436. if err != nil {
  437. return subscriptions, telemetry.Error(ctx, span, err, "failed to decode subscriptions list response")
  438. }
  439. err = resp.Body.Close()
  440. if err != nil {
  441. return subscriptions, telemetry.Error(ctx, span, err, "failed to close response body")
  442. }
  443. return response.Subscriptions, nil
  444. }
  445. func (m LagoClient) listCustomerWallets(ctx context.Context, customerID string) (walletList []types.Wallet, err error) {
  446. ctx, span := telemetry.NewSpan(ctx, "list-lago-customer-wallets")
  447. defer span.End()
  448. // We manually do the request in this function because the Lago client has an issue
  449. // with types for this specific request
  450. url := fmt.Sprintf("%s/api/v1/wallets?external_customer_id=%s", lagoBaseURL, customerID)
  451. req, err := http.NewRequest("GET", url, nil)
  452. if err != nil {
  453. return walletList, telemetry.Error(ctx, span, err, "failed to create wallets list request")
  454. }
  455. req.Header.Set("Authorization", "Bearer "+m.lagoApiKey)
  456. client := &http.Client{}
  457. resp, err := client.Do(req)
  458. if err != nil {
  459. return walletList, telemetry.Error(ctx, span, err, "failed to get customer wallets")
  460. }
  461. response := struct {
  462. Wallets []types.Wallet `json:"wallets"`
  463. }{}
  464. err = json.NewDecoder(resp.Body).Decode(&response)
  465. if err != nil {
  466. return walletList, telemetry.Error(ctx, span, err, "failed to decode wallet list response")
  467. }
  468. err = resp.Body.Close()
  469. if err != nil {
  470. return walletList, telemetry.Error(ctx, span, err, "failed to close response body")
  471. }
  472. return response.Wallets, nil
  473. }
  474. func (m LagoClient) listCustomerAppliedCoupons(ctx context.Context, customerID string) (couponList []types.AppliedCoupon, err error) {
  475. ctx, span := telemetry.NewSpan(ctx, "list-lago-customer-coupons")
  476. defer span.End()
  477. // We manually do the request in this function because the Lago client has an issue
  478. // with types for this specific request
  479. url := fmt.Sprintf("%s/api/v1/applied_coupons?external_customer_id=%s&status=%s", lagoBaseURL, customerID, lago.AppliedCouponStatusActive)
  480. req, err := http.NewRequest("GET", url, nil)
  481. if err != nil {
  482. return couponList, telemetry.Error(ctx, span, err, "failed to create coupons list request")
  483. }
  484. req.Header.Set("Authorization", "Bearer "+m.lagoApiKey)
  485. client := &http.Client{}
  486. resp, err := client.Do(req)
  487. if err != nil {
  488. return couponList, telemetry.Error(ctx, span, err, "failed to get customer coupons")
  489. }
  490. response := struct {
  491. AppliedCoupons []types.AppliedCoupon `json:"applied_coupons"`
  492. }{}
  493. err = json.NewDecoder(resp.Body).Decode(&response)
  494. if err != nil {
  495. return couponList, telemetry.Error(ctx, span, err, "failed to decode coupons list response")
  496. }
  497. err = resp.Body.Close()
  498. if err != nil {
  499. return couponList, telemetry.Error(ctx, span, err, "failed to close response body")
  500. }
  501. return response.AppliedCoupons, nil
  502. }
  503. func createUsageFromLagoUsage(lagoUsage lago.CustomerUsage) types.Usage {
  504. usage := types.Usage{}
  505. usage.FromDatetime = lagoUsage.FromDatetime.Format(time.RFC3339)
  506. usage.ToDatetime = lagoUsage.ToDatetime.Format(time.RFC3339)
  507. usage.TotalAmountCents = int64(lagoUsage.TotalAmountCents)
  508. usage.ChargesUsage = make([]types.ChargeUsage, len(lagoUsage.ChargesUsage))
  509. for i, charge := range lagoUsage.ChargesUsage {
  510. usage.ChargesUsage[i] = types.ChargeUsage{
  511. Units: charge.Units,
  512. AmountCents: int64(charge.AmountCents),
  513. AmountCurrency: string(charge.AmountCurrency),
  514. BillableMetric: types.BillableMetric{
  515. Name: charge.BillableMetric.Name,
  516. },
  517. }
  518. }
  519. return usage
  520. }
  521. func (m LagoClient) generateLagoID(prefix string, projectID uint, sandboxEnabled bool) string {
  522. if sandboxEnabled {
  523. return fmt.Sprintf("cloud_%s_%d", prefix, projectID)
  524. }
  525. return fmt.Sprintf("%s_%d", prefix, projectID)
  526. }