/
billing.go
278 lines (230 loc) · 6.43 KB
/
billing.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"context"
"fmt"
"strings"
"github.com/manifoldco/go-manifold"
"github.com/urfave/cli"
"github.com/manifoldco/manifold-cli/api"
"github.com/manifoldco/manifold-cli/config"
"github.com/manifoldco/manifold-cli/errs"
"github.com/manifoldco/manifold-cli/middleware"
"github.com/manifoldco/manifold-cli/prompts"
"github.com/manifoldco/manifold-cli/session"
"github.com/manifoldco/manifold-cli/generated/billing/client/discount"
"github.com/manifoldco/manifold-cli/generated/billing/client/profile"
bModels "github.com/manifoldco/manifold-cli/generated/billing/models"
)
func init() {
billingCmd := cli.Command{
Name: "billing",
Usage: "Manage your billing information",
Category: "ADMINISTRATIVE",
Subcommands: []cli.Command{
{
Name: "add",
Usage: "Add a credit card",
Flags: teamFlags,
Action: middleware.Chain(middleware.EnsureSession,
middleware.LoadTeamPrefs, addBillingProfileCmd),
},
{
Name: "update",
Usage: "Change the credit card on file",
Flags: teamFlags,
Action: middleware.Chain(middleware.EnsureSession,
middleware.LoadTeamPrefs, updateBillingProfileCmd),
},
{
Name: "redeem",
Usage: "Redeem a coupon code",
Flags: teamFlags,
ArgsUsage: "[code]",
Action: middleware.Chain(middleware.EnsureSession,
middleware.LoadTeamPrefs, redeemCouponCmd),
},
},
}
cmds = append(cmds, billingCmd)
}
// Error returned when attempting to use a team token to perform user actions
var errUserActionAsTeam = cli.NewExitError("Cannot perform user action as team", -1)
func addBillingProfileCmd(cliCtx *cli.Context) error {
ctx := context.Background()
userID, userIDErr := loadUserID(ctx)
if userIDErr != nil && userIDErr != errUserActionAsTeam {
return userIDErr
}
teamID, teamIDErr := validateTeamID(cliCtx)
if teamIDErr != nil {
return teamIDErr
}
if teamID == nil && userIDErr == errUserActionAsTeam {
return errUserActionAsTeam
}
err := createNewBillingProfile(ctx, userID, teamID)
if err != nil {
return err
}
fmt.Println("Your billing info has been saved.")
return nil
}
func createNewBillingProfile(ctx context.Context, userID, teamID *manifold.ID) error {
token, err := creditCardInput(ctx)
if err != nil {
return err
}
client, err := api.New(api.Billing)
if err != nil {
return err
}
params := profile.NewPostProfilesParamsWithContext(ctx)
if teamID == nil {
params.SetBody(&bModels.ProfileCreateRequest{
Token: &token,
UserID: userID,
})
} else {
params.SetBody(&bModels.ProfileCreateRequest{
Token: &token,
TeamID: teamID,
})
}
spin := prompts.NewSpinner("Creating billing profile")
spin.Start()
defer spin.Stop()
_, err = client.Billing.Profile.PostProfiles(params, nil)
if err != nil {
return cli.NewExitError("Failed to add billing profile: "+err.Error(), -1)
}
return nil
}
func updateBillingProfileCmd(cliCtx *cli.Context) error {
ctx := context.Background()
userID, err := loadUserID(ctx)
if err != nil {
return err
}
teamID, err := validateTeamID(cliCtx)
if err != nil {
return err
}
token, err := creditCardInput(ctx)
if err != nil {
return err
}
client, err := api.New(api.Billing)
if err != nil {
return err
}
params := profile.NewPatchProfilesIDParamsWithContext(ctx)
if teamID == nil {
params.SetID(userID.String())
} else {
params.SetID(teamID.String())
}
params.SetBody(&bModels.ProfileUpdateRequest{
Token: &token,
})
spin := prompts.NewSpinner("Updating billing profile")
spin.Start()
defer spin.Stop()
_, err = client.Billing.Profile.PatchProfilesID(params, nil)
if err != nil {
return cli.NewExitError("Failed to update billing profile: "+err.Error(), -1)
}
fmt.Println("Your billing info has been saved.")
return nil
}
func redeemCouponCmd(cliCtx *cli.Context) error {
ctx := context.Background()
if err := maxOptionalArgsLength(cliCtx, 1); err != nil {
return err
}
var err error
code := cliCtx.Args().First()
if code == "" {
code, err = prompts.CouponCode()
if err != nil {
return err
}
}
teamID, err := validateTeamID(cliCtx)
if err != nil {
return err
}
client, err := api.New(api.Billing)
if err != nil {
return err
}
body := &bModels.DiscountCreateRequest{
Code: bModels.CouponCode(code),
}
me := cliCtx.Bool("me")
if !me && teamID != nil {
body.TeamID = teamID
}
spin := prompts.NewSpinner("Applying coupon")
spin.Start()
defer spin.Stop()
params := discount.NewPostDiscountsParamsWithContext(ctx)
params.SetBody(body)
_, err = client.Billing.Discount.PostDiscounts(params, nil)
if err != nil {
switch e := err.(type) {
case *discount.PostDiscountsBadRequest:
msg := strings.Join(e.Payload.Message, "\n")
return cli.NewExitError("Failed to redeem coupon code: "+msg, -1)
case *discount.PostDiscountsConflict:
return cli.NewExitError("This coupon code has been used before.", -1)
case *discount.PostDiscountsInternalServerError:
return errs.ErrSomethingWentHorriblyWrong
default:
return cli.NewExitError("Failed to redeem coupon code: "+err.Error(), -1)
}
}
fmt.Println("Coupon credit has been applied to your account.")
return nil
}
// loadUserID retrieves the user id based on the session.
func loadUserID(ctx context.Context) (*manifold.ID, error) {
cfg, err := config.Load()
if err != nil {
return nil, cli.NewExitError("Could not load config: "+err.Error(), -1)
}
s, err := session.Retrieve(ctx, cfg)
if err != nil {
return nil, cli.NewExitError("Could not retrieve session: "+err.Error(), -1)
}
if !s.IsUser() {
return nil, errUserActionAsTeam
}
return &s.User().ID, nil
}
// creditCardInput prompts for the user credit card information and returns
// the user id and the Stripe payment source token.
func creditCardInput(ctx context.Context) (string, error) {
token, err := prompts.CreditCard()
if err != nil {
return "", cli.NewExitError("Failed to tokenize credit card: "+err.Error(), -1)
}
return token.ID, nil
}
// retrieveBillingProfile returns the billing profile for the authenticated used
func retrieveBillingProfile(ctx context.Context) (*bModels.BillingProfile, error) {
userID, err := loadUserID(ctx)
if err != nil {
return nil, err
}
client, err := api.New(api.Billing)
if err != nil {
return nil, err
}
params := profile.NewGetProfilesIDParamsWithContext(ctx)
params.SetID(userID.String())
resp, err := client.Billing.Profile.GetProfilesID(params, nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}