Skip to content

Use the actual billing cycle dates in all usage-based Billing pages #14485

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 35 additions & 25 deletions components/dashboard/src/components/UsageBasedBillingConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,30 +45,34 @@ export default function UsageBasedBillingConfig({ attributionId }: Props) {

const localStorageKey = `pendingStripeSubscriptionFor${attributionId}`;
const now = dayjs().utc(true);
const billingPeriodFrom = now.startOf("month");
const billingPeriodTo = now.endOf("month");
const [billingCycleFrom, setBillingCycleFrom] = useState<dayjs.Dayjs>(now.startOf("month"));
const [billingCycleTo, setBillingCycleTo] = useState<dayjs.Dayjs>(now.endOf("month"));

const refreshSubscriptionDetails = async (attributionId: string) => {
setStripeSubscriptionId(undefined);
setIsLoadingStripeSubscription(true);
try {
const [subscriptionId, costCenter] = await Promise.all([
getGitpodService().server.findStripeSubscriptionId(attributionId),
getGitpodService().server.getCostCenter(attributionId),
]);
setStripeSubscriptionId(subscriptionId);
setUsageLimit(costCenter?.spendingLimit);
setBillingCycleFrom(dayjs(costCenter?.billingCycleStart || now.startOf("month")).utc(true));
setBillingCycleTo(dayjs(costCenter?.nextBillingTime || now.endOf("month")).utc(true));
} catch (error) {
console.error("Could not get Stripe subscription details.", error);
setErrorMessage(`Could not get Stripe subscription details. ${error?.message || String(error)}`);
} finally {
setIsLoadingStripeSubscription(false);
}
};

useEffect(() => {
if (!attributionId) {
return;
}
(async () => {
setStripeSubscriptionId(undefined);
setIsLoadingStripeSubscription(true);
try {
const [subscriptionId, limit] = await Promise.all([
getGitpodService().server.findStripeSubscriptionId(attributionId),
getGitpodService().server.getUsageLimit(attributionId),
]);
setStripeSubscriptionId(subscriptionId);
setUsageLimit(limit);
} catch (error) {
console.error("Could not get Stripe subscription details.", error);
setErrorMessage(`Could not get Stripe subscription details. ${error?.message || String(error)}`);
} finally {
setIsLoadingStripeSubscription(false);
}
})();
refreshSubscriptionDetails(attributionId);
}, [attributionId]);

useEffect(() => {
Expand Down Expand Up @@ -156,8 +160,7 @@ export default function UsageBasedBillingConfig({ attributionId }: Props) {
if (!pollStripeSubscriptionTimeout) {
// Refresh Stripe subscription in 5 seconds in order to poll for upgrade confirmation
const timeout = setTimeout(async () => {
const subscriptionId = await getGitpodService().server.findStripeSubscriptionId(attributionId);
setStripeSubscriptionId(subscriptionId);
await refreshSubscriptionDetails(attributionId);
setPollStripeSubscriptionTimeout(undefined);
}, 5000);
setPollStripeSubscriptionTimeout(timeout);
Expand All @@ -178,12 +181,12 @@ export default function UsageBasedBillingConfig({ attributionId }: Props) {
const response = await getGitpodService().server.listUsage({
attributionId,
order: Ordering.ORDERING_DESCENDING,
from: billingPeriodFrom.toDate().getTime(),
from: billingCycleFrom.toDate().getTime(),
to: Date.now(),
});
setCurrentUsage(response.creditsUsed);
})();
}, [attributionId]);
}, [attributionId, billingCycleFrom]);

const showSpinner = !attributionId || isLoadingStripeSubscription || !!pendingStripeSubscription;
const showBalance = !showSpinner && !(AttributionId.parse(attributionId)?.kind === "team" && !stripeSubscriptionId);
Expand Down Expand Up @@ -255,8 +258,15 @@ export default function UsageBasedBillingConfig({ attributionId }: Props) {
<div className="flex-grow">
<div className="uppercase text-sm text-gray-400 dark:text-gray-500">Current Period</div>
<div className="text-sm font-medium text-gray-500 dark:text-gray-400">
<span className="font-semibold">{`${billingPeriodFrom.format("MMMM YYYY")}`}</span>{" "}
{`(${billingPeriodFrom.format("MMM D")}` + ` - ${billingPeriodTo.format("MMM D")})`}
<span className="font-semibold">{`${billingCycleFrom.format("MMMM YYYY")}`}</span> (
<span title={billingCycleFrom.toDate().toUTCString().replace("GMT", "UTC")}>
{billingCycleFrom.format("MMM D")}
</span>{" "}
-{" "}
<span title={billingCycleTo.toDate().toUTCString().replace("GMT", "UTC")}>
{billingCycleTo.format("MMM D")}
</span>
)
</div>
</div>
<div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Copyright (c) 2022 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License-AGPL.txt in the project root for license information.
*/

import { MigrationInterface, QueryRunner } from "typeorm";
import { columnExists } from "./helper/helper";

const D_B_COST_CENTER = "d_b_cost_center";
const COL_BILLING_CYCLE_START = "billingCycleStart";

export class CostCenterBillingCycleStart1667919924081 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
if (!(await columnExists(queryRunner, D_B_COST_CENTER, COL_BILLING_CYCLE_START))) {
await queryRunner.query(
`ALTER TABLE ${D_B_COST_CENTER} ADD COLUMN ${COL_BILLING_CYCLE_START} varchar(30) NOT NULL, ALGORITHM=INPLACE, LOCK=NONE `,
);
await queryRunner.query(
`ALTER TABLE ${D_B_COST_CENTER} ADD INDEX(${COL_BILLING_CYCLE_START}), ALGORITHM=INPLACE, LOCK=NONE `,
);
}
}

public async down(queryRunner: QueryRunner): Promise<void> {}
}
1 change: 1 addition & 0 deletions components/gitpod-protocol/BUILD.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ packages:
- :lib
- components/gitpod-protocol/go:lib
- components/gitpod-protocol/java:lib
- components/usage-api/typescript:lib
- name: lib
type: yarn
srcs:
Expand Down
1 change: 1 addition & 0 deletions components/gitpod-protocol/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"watch": "leeway exec --package .:lib --transitive-dependencies --filter-type yarn --components --parallel -- tsc -w --preserveWatchOutput"
},
"dependencies": {
"@gitpod/usage-api": "0.1.5",
"@types/react": "17.0.32",
"abort-controller-x": "^0.4.0",
"ajv": "^6.5.4",
Expand Down
3 changes: 2 additions & 1 deletion components/gitpod-protocol/src/gitpod-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import { InstallationAdminSettings, TelemetryData } from "./installation-admin-p
import { ListUsageRequest, ListUsageResponse } from "./usage";
import { SupportedWorkspaceClass } from "./workspace-class";
import { BillingMode } from "./billing-mode";
import { CostCenter } from "@gitpod/usage-api/lib/usage/v1/usage.pb";

export interface GitpodClient {
onInstanceUpdate(instance: WorkspaceInstance): void;
Expand Down Expand Up @@ -280,7 +281,7 @@ export interface GitpodServer extends JsonRpcServer<GitpodClient>, AdminServer,
createStripeCustomerIfNeeded(attributionId: string, currency: string): Promise<void>;
subscribeToStripe(attributionId: string, setupIntentId: string, usageLimit: number): Promise<number | undefined>;
getStripePortalUrl(attributionId: string): Promise<string>;
getUsageLimit(attributionId: string): Promise<number | undefined>;
getCostCenter(attributionId: string): Promise<CostCenter | undefined>;
setUsageLimit(attributionId: string, usageLimit: number): Promise<void>;

listUsage(req: ListUsageRequest): Promise<ListUsageResponse>;
Expand Down
11 changes: 0 additions & 11 deletions components/gitpod-protocol/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { WorkspaceInstance, PortVisibility } from "./workspace-instance";
import { RoleOrPermission } from "./permission";
import { Project } from "./teams-projects-protocol";
import { createHash } from "crypto";
import { AttributionId } from "./attribution";

export interface UserInfo {
name?: string;
Expand Down Expand Up @@ -1518,13 +1517,3 @@ export interface StripeConfig {
individualUsagePriceIds: { [currency: string]: string };
teamUsagePriceIds: { [currency: string]: string };
}

export type BillingStrategy = "other" | "stripe";
export interface CostCenter {
readonly id: AttributionId;
/**
* Unit: credits
*/
spendingLimit: number;
billingStrategy: BillingStrategy;
}
12 changes: 5 additions & 7 deletions components/server/ee/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import { AccountStatementProvider } from "../user/account-statement-provider";
import { GithubUpgradeURL, PlanCoupon } from "@gitpod/gitpod-protocol/lib/payment-protocol";
import { ListUsageRequest, ListUsageResponse } from "@gitpod/gitpod-protocol/lib/usage";
import {
CostCenter,
CostCenter_BillingStrategy,
ListUsageRequest_Ordering,
UsageServiceClient,
Expand Down Expand Up @@ -2261,21 +2262,18 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
return url;
}

async getUsageLimit(ctx: TraceContext, attributionId: string): Promise<number | undefined> {
async getCostCenter(ctx: TraceContext, attributionId: string): Promise<CostCenter | undefined> {
const attrId = AttributionId.parse(attributionId);
if (attrId === undefined) {
log.error(`Invalid attribution id: ${attributionId}`);
throw new ResponseError(ErrorCodes.BAD_REQUEST, `Invalid attibution id: ${attributionId}`);
}

const user = this.checkAndBlockUser("getUsageLimit");
const user = this.checkAndBlockUser("getCostCenter");
await this.guardCostCenterAccess(ctx, user.id, attrId, "get");

const costCenter = await this.usageService.getCostCenter({ attributionId });
if (costCenter?.costCenter) {
return costCenter.costCenter.spendingLimit;
}
return undefined;
const { costCenter } = await this.usageService.getCostCenter({ attributionId });
return costCenter;
}

async setUsageLimit(ctx: TraceContext, attributionId: string, usageLimit: number): Promise<void> {
Expand Down
2 changes: 1 addition & 1 deletion components/server/src/auth/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ const defaultFunctions: FunctionsConfig = {
getPrebuildEvents: { group: "default", points: 1 },
setUsageAttribution: { group: "default", points: 1 },
listAvailableUsageAttributionIds: { group: "default", points: 1 },
getUsageLimit: { group: "default", points: 1 },
getCostCenter: { group: "default", points: 1 },
setUsageLimit: { group: "default", points: 1 },
getNotifications: { group: "default", points: 1 },
getSupportedWorkspaceClasses: { group: "default", points: 1 },
Expand Down
3 changes: 2 additions & 1 deletion components/server/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ import { MessageBusIntegration } from "./messagebus-integration";
import { AttributionId } from "@gitpod/gitpod-protocol/lib/attribution";
import * as grpc from "@grpc/grpc-js";
import { CachingBlobServiceClientProvider } from "../util/content-service-sugar";
import { CostCenter } from "@gitpod/usage-api/lib/usage/v1/usage.pb";

// shortcut
export const traceWI = (ctx: TraceContext, wi: Omit<LogContext, "userId">) => TraceContext.setOWI(ctx, wi); // userId is already taken care of in WebsocketConnectionManager
Expand Down Expand Up @@ -3157,7 +3158,7 @@ export class GitpodServerImpl implements GitpodServerWithTracing, Disposable {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}

async getUsageLimit(ctx: TraceContext, attributionId: string): Promise<number | undefined> {
async getCostCenter(ctx: TraceContext, attributionId: string): Promise<CostCenter | undefined> {
throw new ResponseError(ErrorCodes.SAAS_FEATURE, `Not implemented in this version`);
}

Expand Down
Loading