Merge pull request #1023 from automatisch/refactor-billing-and-usage

refactor: getBillingAndUsage graphQL query
This commit is contained in:
Ali BARIN
2023-03-26 16:06:16 +02:00
committed by GitHub

View File

@@ -2,9 +2,10 @@ import Context from '../../types/express/context';
import Billing from '../../helpers/billing/index.ee';
import Execution from '../../models/execution';
import ExecutionStep from '../../models/execution-step';
import Subscription from '../../models/subscription.ee';
import { DateTime } from 'luxon';
type Subscription = {
type ComputedSubscription = {
monthlyQuota: string;
status: string;
nextBillDate: string;
@@ -22,23 +23,35 @@ const getBillingAndUsage = async (
'subscription'
);
let subscription: Subscription;
const subscription: ComputedSubscription = persistedSubscription
? paidSubscription(persistedSubscription)
: freeTrialSubscription();
if (persistedSubscription) {
return {
subscription,
usage: {
task: executionStepCount(context),
},
};
};
const paidSubscription = (subscription: Subscription): ComputedSubscription => {
const currentPlan = Billing.paddlePlans.find(
(plan) => plan.productId === persistedSubscription.paddlePlanId
(plan) => plan.productId === subscription.paddlePlanId
);
subscription = {
return {
monthlyQuota: currentPlan.limit,
status: persistedSubscription.status,
nextBillDate: persistedSubscription.nextBillDate,
nextBillAmount: '€' + persistedSubscription.nextBillAmount,
updateUrl: persistedSubscription.updateUrl,
cancelUrl: persistedSubscription.cancelUrl,
status: subscription.status,
nextBillDate: subscription.nextBillDate,
nextBillAmount: '€' + subscription.nextBillAmount,
updateUrl: subscription.updateUrl,
cancelUrl: subscription.cancelUrl,
};
} else {
subscription = {
};
const freeTrialSubscription = (): ComputedSubscription => {
return {
monthlyQuota: 'Free trial',
status: null,
nextBillDate: '---',
@@ -46,16 +59,19 @@ const getBillingAndUsage = async (
updateUrl: null,
cancelUrl: null,
};
}
};
const executionIds = (
const executionIds = async (context: Context) => {
return (
await context.currentUser
.$relatedQuery('executions')
.select('executions.id')
).map((execution: Execution) => execution.id);
};
const executionStepCount = async (context: Context) => {
const executionStepCount = await ExecutionStep.query()
.whereIn('execution_id', executionIds)
.whereIn('execution_id', await executionIds(context))
.andWhere(
'created_at',
'>=',
@@ -64,12 +80,7 @@ const getBillingAndUsage = async (
.count()
.first();
return {
subscription,
usage: {
task: executionStepCount.count,
},
};
return executionStepCount.count;
};
export default getBillingAndUsage;