Browse Source

fix(api): improve type safety in account, subscription, and user services

pull/8361/head
KenTandrian 4 weeks ago
parent
commit
9ca109f673
  1. 41
      apps/api/src/services/account/account.service.ts
  2. 27
      apps/api/src/services/subscription/subscription.service.ts
  3. 42
      apps/api/src/services/user/user.service.ts

41
apps/api/src/services/account/account.service.ts

@ -73,9 +73,10 @@ export class AccountService {
accountWhereUniqueInput: Prisma.AccountWhereUniqueInput,
accountInclude: Prisma.AccountInclude
): Promise<
Account & {
activities?: Order[];
}
| (Account & {
activities?: Order[];
})
| null
> {
return this.prismaService.account.findUnique({
include: accountInclude,
@ -97,7 +98,7 @@ export class AccountService {
tags?: Pick<Tag, 'id'>[];
})[];
balances?: AccountBalance[];
platform?: Platform;
platform?: Platform | null;
tags?: Tag[];
})[]
> {
@ -140,7 +141,15 @@ export class AccountService {
const startOfUtcDateOfTomorrow = getStartOfUtcDateOfTomorrow();
return accounts.map((account) => {
const result = {
const result: AccountWithBalance & {
activities?: (Order & {
SymbolProfile?: SymbolProfile;
tags?: Pick<Tag, 'id'>[];
})[];
balances?: AccountBalance[];
platform?: Platform | null;
tags?: Tag[];
} = {
...account,
balance:
// The balances are ordered by date descending, hence the first account
@ -181,7 +190,9 @@ export class AccountService {
tagIds?: string[];
userId: string;
}): Promise<Account> {
await this.tagService.validateTagIdsWithoutDraftTag({ tagIds, userId });
if (tagIds?.length) {
await this.tagService.validateTagIdsWithoutDraftTag({ tagIds, userId });
}
const account = await this.prismaService.account.create({
data: {
@ -248,7 +259,7 @@ export class AccountService {
return accounts.map((account) => {
const result = {
...account,
activitiesCount: account.activities.length
activitiesCount: account.activities?.length ?? 0
};
delete result.activities;
@ -296,7 +307,7 @@ export class AccountService {
totalCashBalanceInBaseCurrency = totalCashBalanceInBaseCurrency.plus(
this.exchangeRateDataService.toCurrency(
account.balance,
account.currency,
account.currency ?? currency,
currency
)
);
@ -321,7 +332,9 @@ export class AccountService {
userId: string;
where: Prisma.AccountWhereUniqueInput;
}): Promise<Account> {
await this.tagService.validateTagIdsWithoutDraftTag({ tagIds, userId });
if (tagIds?.length) {
await this.tagService.validateTagIdsWithoutDraftTag({ tagIds, userId });
}
const account = await this.prismaService.account.update({
data: {
@ -372,18 +385,24 @@ export class AccountService {
date?: Date;
userId: string;
}) {
const { balance, currency: currencyOfAccount } = await this.account({
const account = await this.account({
id_userId: {
userId,
id: accountId
}
});
if (!account) {
return;
}
const { balance, currency: currencyOfAccount } = account;
const amountInCurrencyOfAccount =
await this.exchangeRateDataService.toCurrencyAtDate(
amount,
currency,
currencyOfAccount,
currencyOfAccount ?? currency,
date
);

27
apps/api/src/services/subscription/subscription.service.ts

@ -82,7 +82,7 @@ export class SubscriptionService {
{
allowed_payment_method_types: ['card'],
cancel_url: `${this.configurationService.get('ROOT_URL')}/${
user.settings.settings.language
user.settings?.settings?.language ?? DEFAULT_LANGUAGE_CODE
}/account`,
client_reference_id: user.id,
line_items: [
@ -112,7 +112,7 @@ export class SubscriptionService {
);
return {
sessionUrl: session.url
sessionUrl: session.url ?? ''
};
}
@ -166,10 +166,16 @@ export class SubscriptionService {
const durationExtension = subscriptionOffer?.durationExtension;
if (!session.client_reference_id) {
throw new Error(
`Stripe Checkout Session '${aCheckoutSessionId}' is missing client_reference_id`
);
}
try {
await this.createSubscription({
durationExtension,
price: session.amount_total / 100,
price: (session.amount_total ?? 0) / 100,
stripeCheckoutSessionId: session.id,
userId: session.client_reference_id
});
@ -210,11 +216,11 @@ export class SubscriptionService {
let offerKey: SubscriptionOfferKey = price ? 'renewal' : 'default';
if (isBefore(createdAt, parseDate('2023-01-01'))) {
if (createdAt && isBefore(createdAt, parseDate('2023-01-01')!)) {
offerKey = 'renewal-early-bird-2023';
} else if (isBefore(createdAt, parseDate('2024-01-01'))) {
} else if (createdAt && isBefore(createdAt, parseDate('2024-01-01')!)) {
offerKey = 'renewal-early-bird-2024';
} else if (isBefore(createdAt, parseDate('2025-12-01'))) {
} else if (createdAt && isBefore(createdAt, parseDate('2025-12-01')!)) {
offerKey = 'renewal-early-bird-2025';
}
@ -223,7 +229,7 @@ export class SubscriptionService {
});
return {
offer,
offer: offer as SubscriptionOffer,
subscribedAt,
expiresAt: isBefore(new Date(), expiresAt) ? expiresAt : undefined,
type: isBefore(new Date(), expiresAt)
@ -236,7 +242,7 @@ export class SubscriptionService {
});
return {
offer,
offer: offer as SubscriptionOffer,
type: SubscriptionType.Basic
};
}
@ -246,7 +252,7 @@ export class SubscriptionService {
key
}: {
key: SubscriptionOfferKey;
}): Promise<SubscriptionOffer> {
}): Promise<SubscriptionOffer | undefined> {
if (!this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) {
return undefined;
}
@ -263,7 +269,7 @@ export class SubscriptionService {
}
private getStripeLocale(
languageCode: string
languageCode?: string
): Stripe.Checkout.SessionCreateParams.Locale {
const unsupportedLanguageCodes: Record<
Exclude<
@ -282,6 +288,7 @@ export class SubscriptionService {
};
if (
languageCode &&
(SUPPORTED_LANGUAGE_CODES as readonly string[]).includes(languageCode) &&
!(languageCode in unsupportedLanguageCodes)
) {

42
apps/api/src/services/user/user.service.ts

@ -142,7 +142,7 @@ export class UserService {
}),
impersonationUserId
? this.user({ id: impersonationUserId })
: Promise.resolve<UserWithSettings>(null),
: Promise.resolve<UserWithSettings | null>(null),
this.tagService.getTagsForUser(impersonationUserId || user.id)
]);
@ -206,10 +206,10 @@ export class UserService {
activityTypes,
dateOfFirstActivity,
id,
permissions,
permissions: permissions ?? [],
referralPartners,
scopes,
subscription,
subscription: subscription as IUser['subscription'],
systemMessage,
tags,
access: access.map((accessItem) => {
@ -221,9 +221,18 @@ export class UserService {
scopes: getScopesOfAccess(accessItem)
};
}),
accounts: accounts.sort((a, b) => {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
}),
accounts: accounts
.map((account) => {
return {
...account,
platform: account.platform ?? undefined
};
})
.sort((a, b) => {
return (a.name ?? '')
.toLowerCase()
.localeCompare((b.name ?? '').toLowerCase());
}),
settings: {
...resolvedUserSettings,
baseCurrency: resolvedUserSettings.baseCurrency ?? DEFAULT_CURRENCY,
@ -435,7 +444,10 @@ export class UserService {
frequency = 6;
}
if (frequency === 1 || analytics?.activityCount % frequency === 1) {
if (
frequency === 1 ||
(analytics?.activityCount ?? 0) % frequency === 1
) {
currentPermissions.push(permissions.enableSubscriptionInterstitial);
}
@ -550,7 +562,9 @@ export class UserService {
}
user.accounts = user.accounts.sort((a, b) => {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
return (a.name ?? '')
.toLowerCase()
.localeCompare((b.name ?? '').toLowerCase());
});
user.permissions = currentPermissions.sort();
@ -659,11 +673,13 @@ export class UserService {
});
} catch {}
try {
await this.activitiesService.deleteActivities({
userId: where.id
});
} catch {}
if (where.id) {
try {
await this.activitiesService.deleteActivities({
userId: where.id
});
} catch {}
}
try {
await this.prismaService.settings.delete({

Loading…
Cancel
Save