- Added `checkIsBanned` method calls in the `createOrder`, `getOrder`, `getOrders`, and `updateOrder` methods of the `OrdersService` to prevent actions from banned users. - Updated the calculation of `remainingOrdersCount` in the `SubscriptionsService` to ensure it does not go below zero, enhancing subscription management accuracy.
236 lines
7.0 KiB
TypeScript
236 lines
7.0 KiB
TypeScript
import { getClientWithToken } from '../apollo/client';
|
|
import * as GQL from '../types';
|
|
import { BaseService } from './base';
|
|
import { OrdersService } from './orders';
|
|
import { type VariablesOf } from '@graphql-typed-document-node/core';
|
|
import dayjs from 'dayjs';
|
|
|
|
export class SubscriptionsService extends BaseService {
|
|
async createSubscription(variables: VariablesOf<typeof GQL.CreateSubscriptionDocument>) {
|
|
await this.checkIsBanned();
|
|
|
|
const { mutate } = await getClientWithToken();
|
|
|
|
const mutationResult = await mutate({
|
|
mutation: GQL.CreateSubscriptionDocument,
|
|
variables,
|
|
});
|
|
|
|
const error = mutationResult.errors?.at(0);
|
|
if (error) throw new Error(error.message);
|
|
|
|
return mutationResult.data;
|
|
}
|
|
|
|
async createSubscriptionHistory(
|
|
variables: VariablesOf<typeof GQL.CreateSubscriptionHistoryDocument>,
|
|
) {
|
|
await this.checkIsBanned();
|
|
|
|
const { mutate } = await getClientWithToken();
|
|
|
|
const mutationResult = await mutate({
|
|
mutation: GQL.CreateSubscriptionHistoryDocument,
|
|
variables,
|
|
});
|
|
|
|
const error = mutationResult.errors?.at(0);
|
|
if (error) throw new Error(error.message);
|
|
|
|
return mutationResult.data;
|
|
}
|
|
|
|
async createTrialSubscription() {
|
|
// Получаем пользователя и проверяем бан
|
|
const { customer } = await this.checkIsBanned();
|
|
|
|
// Проверяем, не использовал ли пользователь уже пробный период
|
|
const { subscription: existingSubscription } = await this.getSubscription({
|
|
telegramId: customer.telegramId,
|
|
});
|
|
if (existingSubscription) {
|
|
// Проверяем, есть ли в истории успешная пробная подписка
|
|
const hasUsedTrial = existingSubscription.subscriptionHistories?.some(
|
|
(item) =>
|
|
item?.period === GQL.Enum_Subscriptionhistory_Period.Trial &&
|
|
item?.state === GQL.Enum_Subscriptionhistory_State.Success,
|
|
);
|
|
if (hasUsedTrial) {
|
|
throw new Error('Пробный период уже был использован');
|
|
}
|
|
}
|
|
|
|
// Получаем цены подписки для определения длительности пробного периода
|
|
const { subscriptionPrices } = await this.getSubscriptionPrices({ isActive: true });
|
|
if (!subscriptionPrices) throw new Error('Subscription prices not found');
|
|
|
|
// Ищем пробный период
|
|
const trialPrice = subscriptionPrices.find(
|
|
(price) => price?.period === GQL.Enum_Subscriptionprice_Period.Trial,
|
|
);
|
|
if (!trialPrice) throw new Error('Trial period not found');
|
|
if (!trialPrice.isActive) throw new Error('Trial period is not active');
|
|
|
|
const trialPeriodDays = trialPrice?.days;
|
|
const now = dayjs();
|
|
const expiresAt = now.add(trialPeriodDays, 'day');
|
|
|
|
// Создаем пробную подписку
|
|
const subscriptionData = await this.createSubscription({
|
|
input: {
|
|
autoRenew: false,
|
|
customer: customer.documentId,
|
|
expiresAt: expiresAt.toISOString(),
|
|
isActive: true,
|
|
},
|
|
});
|
|
|
|
if (!subscriptionData?.createSubscription) {
|
|
throw new Error('Failed to create trial subscription');
|
|
}
|
|
|
|
const subscription = subscriptionData.createSubscription;
|
|
|
|
// Создаем запись в истории подписки
|
|
await this.createSubscriptionHistory({
|
|
input: {
|
|
amount: 0,
|
|
currency: 'RUB',
|
|
description: `Пробный период на ${trialPeriodDays} дней`,
|
|
endDate: expiresAt.toISOString(),
|
|
period: GQL.Enum_Subscriptionhistory_Period.Trial,
|
|
source: GQL.Enum_Subscriptionhistory_Source.Promo,
|
|
startDate: now.toISOString(),
|
|
state: GQL.Enum_Subscriptionhistory_State.Success,
|
|
subscription: subscription.documentId,
|
|
},
|
|
});
|
|
|
|
return subscriptionData;
|
|
}
|
|
|
|
async getSubscription(variables: VariablesOf<typeof GQL.GetSubscriptionDocument>) {
|
|
await this.checkIsBanned();
|
|
|
|
const { query } = await getClientWithToken();
|
|
|
|
const result = await query({
|
|
query: GQL.GetSubscriptionDocument,
|
|
variables,
|
|
});
|
|
|
|
const subscription = result.data.subscriptions.at(0);
|
|
|
|
const { maxOrdersPerMonth, remainingOrdersCount } = await this.getRemainingOrdersCount();
|
|
|
|
return { maxOrdersPerMonth, remainingOrdersCount, subscription };
|
|
}
|
|
|
|
async getSubscriptionHistory(variables: VariablesOf<typeof GQL.GetSubscriptionHistoryDocument>) {
|
|
await this.checkIsBanned();
|
|
|
|
const { query } = await getClientWithToken();
|
|
|
|
const result = await query({
|
|
query: GQL.GetSubscriptionHistoryDocument,
|
|
variables,
|
|
});
|
|
|
|
const subscriptionHistories = result.data.subscriptionHistories;
|
|
|
|
return { subscriptionHistories };
|
|
}
|
|
|
|
async getSubscriptionPrices(variables?: VariablesOf<typeof GQL.GetSubscriptionPricesDocument>) {
|
|
await this.checkIsBanned();
|
|
|
|
const { query } = await getClientWithToken();
|
|
|
|
const result = await query({
|
|
query: GQL.GetSubscriptionPricesDocument,
|
|
variables,
|
|
});
|
|
|
|
return result.data;
|
|
}
|
|
|
|
async getSubscriptionSettings() {
|
|
await this.checkIsBanned();
|
|
|
|
const { query } = await getClientWithToken();
|
|
|
|
const result = await query({
|
|
query: GQL.GetSubscriptionSettingsDocument,
|
|
});
|
|
|
|
return result.data;
|
|
}
|
|
|
|
async updateSubscription(variables: VariablesOf<typeof GQL.UpdateSubscriptionDocument>) {
|
|
await this.checkIsBanned();
|
|
|
|
const { mutate } = await getClientWithToken();
|
|
|
|
const mutationResult = await mutate({
|
|
mutation: GQL.UpdateSubscriptionDocument,
|
|
variables,
|
|
});
|
|
|
|
const error = mutationResult.errors?.at(0);
|
|
if (error) throw new Error(error.message);
|
|
|
|
return mutationResult.data;
|
|
}
|
|
|
|
async updateSubscriptionHistory(
|
|
variables: VariablesOf<typeof GQL.UpdateSubscriptionHistoryDocument>,
|
|
) {
|
|
await this.checkIsBanned();
|
|
|
|
const { mutate } = await getClientWithToken();
|
|
|
|
const mutationResult = await mutate({
|
|
mutation: GQL.UpdateSubscriptionHistoryDocument,
|
|
variables,
|
|
});
|
|
|
|
const error = mutationResult.errors?.at(0);
|
|
if (error) throw new Error(error.message);
|
|
|
|
return mutationResult.data;
|
|
}
|
|
|
|
private async getRemainingOrdersCount() {
|
|
const ordersService = new OrdersService(this._user);
|
|
|
|
const now = dayjs();
|
|
|
|
const { orders } = await ordersService.getOrders({
|
|
filters: {
|
|
datetime_end: {
|
|
lte: now.endOf('month').toISOString(),
|
|
},
|
|
datetime_start: {
|
|
gte: now.startOf('month').toISOString(),
|
|
},
|
|
|
|
state: {
|
|
eq: GQL.Enum_Order_State.Completed,
|
|
},
|
|
},
|
|
});
|
|
|
|
const { subscriptionSetting } = await this.getSubscriptionSettings();
|
|
|
|
if (!subscriptionSetting) throw new Error('Subscription setting not found');
|
|
|
|
const { maxOrdersPerMonth } = subscriptionSetting;
|
|
|
|
let remainingOrdersCount = maxOrdersPerMonth - (orders?.length ?? 0);
|
|
|
|
if (remainingOrdersCount < 0) remainingOrdersCount = 0;
|
|
|
|
return { maxOrdersPerMonth, remainingOrdersCount };
|
|
}
|
|
}
|