-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathbilling-service.ts
78 lines (72 loc) · 2.84 KB
/
billing-service.ts
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
/**
* Copyright (c) 2022 Gitpod GmbH. All rights reserved.
* Licensed under the Gitpod Enterprise Source Code License,
* See License.enterprise.txt in the project root folder.
*/
import { User } from "@gitpod/gitpod-protocol";
import { AttributionId } from "@gitpod/gitpod-protocol/lib/attribution";
import { log } from "@gitpod/gitpod-protocol/lib/util/logging";
import { UsageServiceClient, UsageServiceDefinition } from "@gitpod/usage-api/lib/usage/v1/usage.pb";
import { inject, injectable } from "inversify";
import { UserService } from "../../../src/user/user-service";
export interface UsageLimitReachedResult {
reached: boolean;
almostReached?: boolean;
attributionId: AttributionId;
}
@injectable()
export class BillingService {
@inject(UserService) protected readonly userService: UserService;
@inject(UsageServiceDefinition.name)
protected readonly usageService: UsageServiceClient;
async checkUsageLimitReached(user: User): Promise<UsageLimitReachedResult> {
const attributionId = await this.userService.getWorkspaceUsageAttributionId(user);
const costCenter = (
await this.usageService.getCostCenter({
attributionId: AttributionId.render(attributionId),
})
).costCenter;
if (!costCenter) {
const err = new Error("No CostCenter found");
log.error({ userId: user.id }, err.message, err, { attributionId });
// Technically we do not have any spending limit set, yet. But sending users down the "reached" path will fix this issues as well.
return {
reached: true,
attributionId,
};
}
const now = new Date();
const currentBalance = await this.usageService.listUsage({
attributionId: AttributionId.render(attributionId),
from: now,
to: now,
});
const currentInvoiceCredits = currentBalance.creditBalanceAtEnd | 0;
if (currentInvoiceCredits >= (costCenter.spendingLimit || 0)) {
log.info({ userId: user.id }, "Usage limit reached", {
attributionId,
currentInvoiceCredits,
usageLimit: costCenter.spendingLimit,
});
return {
reached: true,
attributionId,
};
} else if (currentInvoiceCredits > costCenter.spendingLimit * 0.8) {
log.info({ userId: user.id }, "Usage limit almost reached", {
attributionId,
currentInvoiceCredits,
usageLimit: costCenter.spendingLimit,
});
return {
reached: false,
almostReached: true,
attributionId,
};
}
return {
reached: false,
attributionId,
};
}
}