@@ -0,0 +1,373 @@ |
| | 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| | 2 | + |
| | 3 | +// Package billing owns local paid-organization state. It stores Stripe |
| | 4 | +// identifiers and derived subscription state, but it does not call |
| | 5 | +// Stripe directly; webhook/API integration lands in SP03. |
| | 6 | +package billing |
| | 7 | + |
| | 8 | +import ( |
| | 9 | + "context" |
| | 10 | + "encoding/json" |
| | 11 | + "errors" |
| | 12 | + "fmt" |
| | 13 | + "strings" |
| | 14 | + "time" |
| | 15 | + |
| | 16 | + "github.com/jackc/pgx/v5" |
| | 17 | + "github.com/jackc/pgx/v5/pgtype" |
| | 18 | + "github.com/jackc/pgx/v5/pgxpool" |
| | 19 | + |
| | 20 | + billingdb "github.com/tenseleyFlow/shithub/internal/billing/sqlc" |
| | 21 | +) |
| | 22 | + |
| | 23 | +type Deps struct { |
| | 24 | + Pool *pgxpool.Pool |
| | 25 | +} |
| | 26 | + |
| | 27 | +type Plan = billingdb.OrgPlan |
| | 28 | +type SubscriptionStatus = billingdb.BillingSubscriptionStatus |
| | 29 | +type State = billingdb.OrgBillingState |
| | 30 | + |
| | 31 | +const ( |
| | 32 | + PlanFree = billingdb.OrgPlanFree |
| | 33 | + PlanTeam = billingdb.OrgPlanTeam |
| | 34 | + PlanEnterprise = billingdb.OrgPlanEnterprise |
| | 35 | + |
| | 36 | + SubscriptionStatusNone = billingdb.BillingSubscriptionStatusNone |
| | 37 | + SubscriptionStatusIncomplete = billingdb.BillingSubscriptionStatusIncomplete |
| | 38 | + SubscriptionStatusTrialing = billingdb.BillingSubscriptionStatusTrialing |
| | 39 | + SubscriptionStatusActive = billingdb.BillingSubscriptionStatusActive |
| | 40 | + SubscriptionStatusPastDue = billingdb.BillingSubscriptionStatusPastDue |
| | 41 | + SubscriptionStatusCanceled = billingdb.BillingSubscriptionStatusCanceled |
| | 42 | + SubscriptionStatusUnpaid = billingdb.BillingSubscriptionStatusUnpaid |
| | 43 | + SubscriptionStatusPaused = billingdb.BillingSubscriptionStatusPaused |
| | 44 | +) |
| | 45 | + |
| | 46 | +var ( |
| | 47 | + ErrPoolRequired = errors.New("billing: pool is required") |
| | 48 | + ErrOrgIDRequired = errors.New("billing: org id is required") |
| | 49 | + ErrStripeCustomerID = errors.New("billing: stripe customer id is required") |
| | 50 | + ErrInvalidPlan = errors.New("billing: invalid plan") |
| | 51 | + ErrInvalidStatus = errors.New("billing: invalid subscription status") |
| | 52 | + ErrInvalidSeatCount = errors.New("billing: seat counts cannot be negative") |
| | 53 | + ErrWebhookEventID = errors.New("billing: webhook event id is required") |
| | 54 | + ErrWebhookEventType = errors.New("billing: webhook event type is required") |
| | 55 | + ErrWebhookPayload = errors.New("billing: webhook payload must be a JSON object") |
| | 56 | +) |
| | 57 | + |
| | 58 | +// SubscriptionSnapshot is the local projection of a provider |
| | 59 | +// subscription event. Provider-specific conversion belongs in SP03. |
| | 60 | +type SubscriptionSnapshot struct { |
| | 61 | + OrgID int64 |
| | 62 | + Plan Plan |
| | 63 | + Status SubscriptionStatus |
| | 64 | + StripeSubscriptionID string |
| | 65 | + StripeSubscriptionItemID string |
| | 66 | + CurrentPeriodStart time.Time |
| | 67 | + CurrentPeriodEnd time.Time |
| | 68 | + CancelAtPeriodEnd bool |
| | 69 | + TrialEnd time.Time |
| | 70 | + CanceledAt time.Time |
| | 71 | + LastWebhookEventID string |
| | 72 | +} |
| | 73 | + |
| | 74 | +type SeatSnapshot struct { |
| | 75 | + OrgID int64 |
| | 76 | + StripeSubscriptionID string |
| | 77 | + ActiveMembers int |
| | 78 | + BillableSeats int |
| | 79 | + Source string |
| | 80 | +} |
| | 81 | + |
| | 82 | +type WebhookEvent struct { |
| | 83 | + ProviderEventID string |
| | 84 | + EventType string |
| | 85 | + APIVersion string |
| | 86 | + Payload []byte |
| | 87 | +} |
| | 88 | + |
| | 89 | +func GetOrgBillingState(ctx context.Context, deps Deps, orgID int64) (State, error) { |
| | 90 | + if err := validateDeps(deps); err != nil { |
| | 91 | + return State{}, err |
| | 92 | + } |
| | 93 | + if orgID == 0 { |
| | 94 | + return State{}, ErrOrgIDRequired |
| | 95 | + } |
| | 96 | + return billingdb.New().GetOrgBillingState(ctx, deps.Pool, orgID) |
| | 97 | +} |
| | 98 | + |
| | 99 | +func SetStripeCustomer(ctx context.Context, deps Deps, orgID int64, customerID string) (State, error) { |
| | 100 | + if err := validateDeps(deps); err != nil { |
| | 101 | + return State{}, err |
| | 102 | + } |
| | 103 | + if orgID == 0 { |
| | 104 | + return State{}, ErrOrgIDRequired |
| | 105 | + } |
| | 106 | + customerID = strings.TrimSpace(customerID) |
| | 107 | + if customerID == "" { |
| | 108 | + return State{}, ErrStripeCustomerID |
| | 109 | + } |
| | 110 | + return billingdb.New().SetStripeCustomer(ctx, deps.Pool, billingdb.SetStripeCustomerParams{ |
| | 111 | + OrgID: orgID, |
| | 112 | + StripeCustomerID: pgText(customerID), |
| | 113 | + }) |
| | 114 | +} |
| | 115 | + |
| | 116 | +func ApplySubscriptionSnapshot(ctx context.Context, deps Deps, snap SubscriptionSnapshot) (State, error) { |
| | 117 | + if err := validateDeps(deps); err != nil { |
| | 118 | + return State{}, err |
| | 119 | + } |
| | 120 | + if snap.OrgID == 0 { |
| | 121 | + return State{}, ErrOrgIDRequired |
| | 122 | + } |
| | 123 | + if !validPlan(snap.Plan) { |
| | 124 | + return State{}, fmt.Errorf("%w: %q", ErrInvalidPlan, snap.Plan) |
| | 125 | + } |
| | 126 | + if !validStatus(snap.Status) { |
| | 127 | + return State{}, fmt.Errorf("%w: %q", ErrInvalidStatus, snap.Status) |
| | 128 | + } |
| | 129 | + row, err := billingdb.New().ApplySubscriptionSnapshot(ctx, deps.Pool, billingdb.ApplySubscriptionSnapshotParams{ |
| | 130 | + OrgID: snap.OrgID, |
| | 131 | + Plan: snap.Plan, |
| | 132 | + SubscriptionStatus: snap.Status, |
| | 133 | + StripeSubscriptionID: pgText(snap.StripeSubscriptionID), |
| | 134 | + StripeSubscriptionItemID: pgText(snap.StripeSubscriptionItemID), |
| | 135 | + CurrentPeriodStart: pgTime(snap.CurrentPeriodStart), |
| | 136 | + CurrentPeriodEnd: pgTime(snap.CurrentPeriodEnd), |
| | 137 | + CancelAtPeriodEnd: snap.CancelAtPeriodEnd, |
| | 138 | + TrialEnd: pgTime(snap.TrialEnd), |
| | 139 | + CanceledAt: pgTime(snap.CanceledAt), |
| | 140 | + LastWebhookEventID: strings.TrimSpace(snap.LastWebhookEventID), |
| | 141 | + }) |
| | 142 | + if err != nil { |
| | 143 | + return State{}, err |
| | 144 | + } |
| | 145 | + return stateFromApply(row), nil |
| | 146 | +} |
| | 147 | + |
| | 148 | +func RecordWebhookEvent(ctx context.Context, deps Deps, event WebhookEvent) (billingdb.BillingWebhookEvent, bool, error) { |
| | 149 | + if err := validateDeps(deps); err != nil { |
| | 150 | + return billingdb.BillingWebhookEvent{}, false, err |
| | 151 | + } |
| | 152 | + event.ProviderEventID = strings.TrimSpace(event.ProviderEventID) |
| | 153 | + event.EventType = strings.TrimSpace(event.EventType) |
| | 154 | + event.APIVersion = strings.TrimSpace(event.APIVersion) |
| | 155 | + if event.ProviderEventID == "" { |
| | 156 | + return billingdb.BillingWebhookEvent{}, false, ErrWebhookEventID |
| | 157 | + } |
| | 158 | + if event.EventType == "" { |
| | 159 | + return billingdb.BillingWebhookEvent{}, false, ErrWebhookEventType |
| | 160 | + } |
| | 161 | + if !jsonObject(event.Payload) { |
| | 162 | + return billingdb.BillingWebhookEvent{}, false, ErrWebhookPayload |
| | 163 | + } |
| | 164 | + row, err := billingdb.New().CreateWebhookEventReceipt(ctx, deps.Pool, billingdb.CreateWebhookEventReceiptParams{ |
| | 165 | + ProviderEventID: event.ProviderEventID, |
| | 166 | + EventType: event.EventType, |
| | 167 | + ApiVersion: event.APIVersion, |
| | 168 | + Payload: event.Payload, |
| | 169 | + }) |
| | 170 | + if err != nil { |
| | 171 | + if errors.Is(err, pgx.ErrNoRows) { |
| | 172 | + return billingdb.BillingWebhookEvent{}, false, nil |
| | 173 | + } |
| | 174 | + return billingdb.BillingWebhookEvent{}, false, err |
| | 175 | + } |
| | 176 | + return row, true, nil |
| | 177 | +} |
| | 178 | + |
| | 179 | +func SyncSeatSnapshot(ctx context.Context, deps Deps, snap SeatSnapshot) (billingdb.BillingSeatSnapshot, error) { |
| | 180 | + if err := validateDeps(deps); err != nil { |
| | 181 | + return billingdb.BillingSeatSnapshot{}, err |
| | 182 | + } |
| | 183 | + if snap.OrgID == 0 { |
| | 184 | + return billingdb.BillingSeatSnapshot{}, ErrOrgIDRequired |
| | 185 | + } |
| | 186 | + if snap.ActiveMembers < 0 || snap.BillableSeats < 0 { |
| | 187 | + return billingdb.BillingSeatSnapshot{}, ErrInvalidSeatCount |
| | 188 | + } |
| | 189 | + source := strings.TrimSpace(snap.Source) |
| | 190 | + if source == "" { |
| | 191 | + source = "local" |
| | 192 | + } |
| | 193 | + row, err := billingdb.New().CreateSeatSnapshot(ctx, deps.Pool, billingdb.CreateSeatSnapshotParams{ |
| | 194 | + OrgID: snap.OrgID, |
| | 195 | + StripeSubscriptionID: pgText(snap.StripeSubscriptionID), |
| | 196 | + ActiveMembers: int32(snap.ActiveMembers), |
| | 197 | + BillableSeats: int32(snap.BillableSeats), |
| | 198 | + Source: source, |
| | 199 | + }) |
| | 200 | + if err != nil { |
| | 201 | + return billingdb.BillingSeatSnapshot{}, err |
| | 202 | + } |
| | 203 | + return billingdb.BillingSeatSnapshot(row), nil |
| | 204 | +} |
| | 205 | + |
| | 206 | +func MarkPastDue(ctx context.Context, deps Deps, orgID int64, graceUntil time.Time, lastWebhookEventID string) (State, error) { |
| | 207 | + if err := validateDeps(deps); err != nil { |
| | 208 | + return State{}, err |
| | 209 | + } |
| | 210 | + if orgID == 0 { |
| | 211 | + return State{}, ErrOrgIDRequired |
| | 212 | + } |
| | 213 | + return billingdb.New().MarkPastDue(ctx, deps.Pool, billingdb.MarkPastDueParams{ |
| | 214 | + OrgID: orgID, |
| | 215 | + GraceUntil: pgTime(graceUntil), |
| | 216 | + LastWebhookEventID: strings.TrimSpace(lastWebhookEventID), |
| | 217 | + }) |
| | 218 | +} |
| | 219 | + |
| | 220 | +func MarkCanceled(ctx context.Context, deps Deps, orgID int64, lastWebhookEventID string) (State, error) { |
| | 221 | + if err := validateDeps(deps); err != nil { |
| | 222 | + return State{}, err |
| | 223 | + } |
| | 224 | + if orgID == 0 { |
| | 225 | + return State{}, ErrOrgIDRequired |
| | 226 | + } |
| | 227 | + row, err := billingdb.New().MarkCanceled(ctx, deps.Pool, billingdb.MarkCanceledParams{ |
| | 228 | + OrgID: orgID, |
| | 229 | + LastWebhookEventID: strings.TrimSpace(lastWebhookEventID), |
| | 230 | + }) |
| | 231 | + if err != nil { |
| | 232 | + return State{}, err |
| | 233 | + } |
| | 234 | + return stateFromCanceled(row), nil |
| | 235 | +} |
| | 236 | + |
| | 237 | +func ClearBillingLock(ctx context.Context, deps Deps, orgID int64) (State, error) { |
| | 238 | + if err := validateDeps(deps); err != nil { |
| | 239 | + return State{}, err |
| | 240 | + } |
| | 241 | + if orgID == 0 { |
| | 242 | + return State{}, ErrOrgIDRequired |
| | 243 | + } |
| | 244 | + row, err := billingdb.New().ClearBillingLock(ctx, deps.Pool, orgID) |
| | 245 | + if err != nil { |
| | 246 | + return State{}, err |
| | 247 | + } |
| | 248 | + return stateFromClear(row), nil |
| | 249 | +} |
| | 250 | + |
| | 251 | +func validateDeps(deps Deps) error { |
| | 252 | + if deps.Pool == nil { |
| | 253 | + return ErrPoolRequired |
| | 254 | + } |
| | 255 | + return nil |
| | 256 | +} |
| | 257 | + |
| | 258 | +func validPlan(plan Plan) bool { |
| | 259 | + switch plan { |
| | 260 | + case PlanFree, PlanTeam, PlanEnterprise: |
| | 261 | + return true |
| | 262 | + default: |
| | 263 | + return false |
| | 264 | + } |
| | 265 | +} |
| | 266 | + |
| | 267 | +func validStatus(status SubscriptionStatus) bool { |
| | 268 | + switch status { |
| | 269 | + case SubscriptionStatusNone, |
| | 270 | + SubscriptionStatusIncomplete, |
| | 271 | + SubscriptionStatusTrialing, |
| | 272 | + SubscriptionStatusActive, |
| | 273 | + SubscriptionStatusPastDue, |
| | 274 | + SubscriptionStatusCanceled, |
| | 275 | + SubscriptionStatusUnpaid, |
| | 276 | + SubscriptionStatusPaused: |
| | 277 | + return true |
| | 278 | + default: |
| | 279 | + return false |
| | 280 | + } |
| | 281 | +} |
| | 282 | + |
| | 283 | +func pgText(s string) pgtype.Text { |
| | 284 | + s = strings.TrimSpace(s) |
| | 285 | + return pgtype.Text{String: s, Valid: s != ""} |
| | 286 | +} |
| | 287 | + |
| | 288 | +func pgTime(t time.Time) pgtype.Timestamptz { |
| | 289 | + return pgtype.Timestamptz{Time: t, Valid: !t.IsZero()} |
| | 290 | +} |
| | 291 | + |
| | 292 | +func jsonObject(payload []byte) bool { |
| | 293 | + var v map[string]any |
| | 294 | + return json.Unmarshal(payload, &v) == nil && v != nil |
| | 295 | +} |
| | 296 | + |
| | 297 | +func stateFromApply(row billingdb.ApplySubscriptionSnapshotRow) State { |
| | 298 | + return State{ |
| | 299 | + OrgID: row.OrgID, |
| | 300 | + Provider: row.Provider, |
| | 301 | + StripeCustomerID: row.StripeCustomerID, |
| | 302 | + StripeSubscriptionID: row.StripeSubscriptionID, |
| | 303 | + StripeSubscriptionItemID: row.StripeSubscriptionItemID, |
| | 304 | + Plan: row.Plan, |
| | 305 | + SubscriptionStatus: row.SubscriptionStatus, |
| | 306 | + BillableSeats: row.BillableSeats, |
| | 307 | + SeatSnapshotAt: row.SeatSnapshotAt, |
| | 308 | + CurrentPeriodStart: row.CurrentPeriodStart, |
| | 309 | + CurrentPeriodEnd: row.CurrentPeriodEnd, |
| | 310 | + CancelAtPeriodEnd: row.CancelAtPeriodEnd, |
| | 311 | + TrialEnd: row.TrialEnd, |
| | 312 | + PastDueAt: row.PastDueAt, |
| | 313 | + CanceledAt: row.CanceledAt, |
| | 314 | + LockedAt: row.LockedAt, |
| | 315 | + LockReason: row.LockReason, |
| | 316 | + GraceUntil: row.GraceUntil, |
| | 317 | + LastWebhookEventID: row.LastWebhookEventID, |
| | 318 | + CreatedAt: row.CreatedAt, |
| | 319 | + UpdatedAt: row.UpdatedAt, |
| | 320 | + } |
| | 321 | +} |
| | 322 | + |
| | 323 | +func stateFromCanceled(row billingdb.MarkCanceledRow) State { |
| | 324 | + return State{ |
| | 325 | + OrgID: row.OrgID, |
| | 326 | + Provider: row.Provider, |
| | 327 | + StripeCustomerID: row.StripeCustomerID, |
| | 328 | + StripeSubscriptionID: row.StripeSubscriptionID, |
| | 329 | + StripeSubscriptionItemID: row.StripeSubscriptionItemID, |
| | 330 | + Plan: row.Plan, |
| | 331 | + SubscriptionStatus: row.SubscriptionStatus, |
| | 332 | + BillableSeats: row.BillableSeats, |
| | 333 | + SeatSnapshotAt: row.SeatSnapshotAt, |
| | 334 | + CurrentPeriodStart: row.CurrentPeriodStart, |
| | 335 | + CurrentPeriodEnd: row.CurrentPeriodEnd, |
| | 336 | + CancelAtPeriodEnd: row.CancelAtPeriodEnd, |
| | 337 | + TrialEnd: row.TrialEnd, |
| | 338 | + PastDueAt: row.PastDueAt, |
| | 339 | + CanceledAt: row.CanceledAt, |
| | 340 | + LockedAt: row.LockedAt, |
| | 341 | + LockReason: row.LockReason, |
| | 342 | + GraceUntil: row.GraceUntil, |
| | 343 | + LastWebhookEventID: row.LastWebhookEventID, |
| | 344 | + CreatedAt: row.CreatedAt, |
| | 345 | + UpdatedAt: row.UpdatedAt, |
| | 346 | + } |
| | 347 | +} |
| | 348 | + |
| | 349 | +func stateFromClear(row billingdb.ClearBillingLockRow) State { |
| | 350 | + return State{ |
| | 351 | + OrgID: row.OrgID, |
| | 352 | + Provider: row.Provider, |
| | 353 | + StripeCustomerID: row.StripeCustomerID, |
| | 354 | + StripeSubscriptionID: row.StripeSubscriptionID, |
| | 355 | + StripeSubscriptionItemID: row.StripeSubscriptionItemID, |
| | 356 | + Plan: row.Plan, |
| | 357 | + SubscriptionStatus: row.SubscriptionStatus, |
| | 358 | + BillableSeats: row.BillableSeats, |
| | 359 | + SeatSnapshotAt: row.SeatSnapshotAt, |
| | 360 | + CurrentPeriodStart: row.CurrentPeriodStart, |
| | 361 | + CurrentPeriodEnd: row.CurrentPeriodEnd, |
| | 362 | + CancelAtPeriodEnd: row.CancelAtPeriodEnd, |
| | 363 | + TrialEnd: row.TrialEnd, |
| | 364 | + PastDueAt: row.PastDueAt, |
| | 365 | + CanceledAt: row.CanceledAt, |
| | 366 | + LockedAt: row.LockedAt, |
| | 367 | + LockReason: row.LockReason, |
| | 368 | + GraceUntil: row.GraceUntil, |
| | 369 | + LastWebhookEventID: row.LastWebhookEventID, |
| | 370 | + CreatedAt: row.CreatedAt, |
| | 371 | + UpdatedAt: row.UpdatedAt, |
| | 372 | + } |
| | 373 | +} |