Skip to content

Commit

Permalink
chore: cleanup useless code
Browse files Browse the repository at this point in the history
  • Loading branch information
letehaha committed Sep 27, 2024
1 parent 9d097e1 commit f20e0e6
Show file tree
Hide file tree
Showing 7 changed files with 6 additions and 208 deletions.
5 changes: 0 additions & 5 deletions shared-types/routes/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ import { QueryPayload } from './index';

export interface GetTransactionsQuery extends QueryPayload {
sort?: SORT_DIRECTIONS;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
limit?: number;
from?: number;
type?: TRANSACTION_TYPES;
Expand Down
12 changes: 0 additions & 12 deletions src/controllers/transactions.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,12 @@ export const getTransactionById = async (req, res: CustomResponse) => {
try {
const { id } = req.params;
const { id: userId } = req.user;
const { includeUser, includeAccount, includeCategory, includeAll, nestedInclude } = req.query;

if (id === undefined) throw new ValidationError({ message: 'id should exist.' });

const data = await transactionsService.getTransactionById({
id,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

return res.status(200).json({
Expand All @@ -35,19 +29,13 @@ export const getTransactionsByTransferId = async (req, res: CustomResponse) => {
try {
const { transferId } = req.params;
const { id: userId } = req.user;
const { includeUser, includeAccount, includeCategory, includeAll, nestedInclude } = req.query;

if (transferId === undefined)
throw new ValidationError({ message: '"transferId" is required.' });

const data = await transactionsService.getTransactionsByTransferId({
transferId,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

return res.status(200).json({
Expand Down
5 changes: 0 additions & 5 deletions src/controllers/transactions.controller/get-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,6 @@ export const getTransactionsSchema = z.object({
z.array(z.number().int().positive()),
)
.optional(),
includeUser: z.preprocess((val) => val === 'true', z.boolean()).optional(),
includeAccount: z.preprocess((val) => val === 'true', z.boolean()).optional(),
includeCategory: z.preprocess((val) => val === 'true', z.boolean()).optional(),
includeAll: z.preprocess((val) => val === 'true', z.boolean()).optional(),
nestedInclude: z.preprocess((val) => val === 'true', z.boolean()).optional(),
excludeTransfer: z.preprocess((val) => val === 'true', z.boolean()).optional(),
excludeRefunds: z.preprocess((val) => val === 'true', z.boolean()).optional(),
startDate: z
Expand Down
37 changes: 1 addition & 36 deletions src/models/Balances.model.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import { Op } from 'sequelize';
import { Model, Column, DataType, ForeignKey, BelongsTo, Table } from 'sequelize-typescript';
import { TRANSACTION_TYPES, BalanceModel, ACCOUNT_TYPES } from 'shared-types';
import { TRANSACTION_TYPES, ACCOUNT_TYPES } from 'shared-types';
import { subDays } from 'date-fns';
import Accounts from './Accounts.model';
import Transactions, { TransactionsAttributes } from './Transactions.model';

interface GetTotalBalanceHistoryPayload {
startDate: Date;
endDate: Date;
accountIds: number[];
}

@Table({ timestamps: true })
export default class Balances extends Model {
@Column({
Expand Down Expand Up @@ -39,35 +33,6 @@ export default class Balances extends Model {
@BelongsTo(() => Accounts)
account: Accounts;

// Method to calculate the total balance across all accounts
static async getTotalBalance({ userId }: { userId: number }): Promise<number> {
const userAccounts = await Accounts.findAll({ where: { userId: userId } });
const accountIds = userAccounts.map((account) => account.id);

const result = await Balances.sum('amount', {
where: { accountId: accountIds },
});

return result || 0;
}

// Method to retrieve total balance history for specified dates and accounts
static async getTotalBalanceHistory(
payload: GetTotalBalanceHistoryPayload,
): Promise<BalanceModel[]> {
const { startDate, endDate, accountIds } = payload;
return Balances.findAll({
where: {
date: {
[Op.between]: [startDate, endDate],
},
accountId: accountIds,
},
order: [['date', 'ASC']],
include: [Accounts],
});
}

// Transactions might have positive and negative amount
// ### Transaction creation
// 1. ✅ If just a new tx is created. Create a new record with date and (amount + refAmount) of tx
Expand Down
112 changes: 3 additions & 109 deletions src/models/Transactions.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
SORT_DIRECTIONS,
TransactionModel,
} from 'shared-types';
import { Op, Includeable, WhereOptions } from 'sequelize';
import { Op, WhereOptions } from 'sequelize';
import {
Table,
BeforeCreate,
Expand All @@ -20,7 +20,7 @@ import {
DataType,
BelongsTo,
} from 'sequelize-typescript';
import { isExist, removeUndefinedKeys } from '@js/helpers';
import { removeUndefinedKeys } from '@js/helpers';
import { ValidationError } from '@js/errors';
import { updateAccountBalanceForChangedTx } from '@services/accounts';
import Users from '@models/Users.model';
Expand All @@ -29,35 +29,6 @@ import Categories from '@models/Categories.model';
import Currencies from '@models/Currencies.model';
import Balances from '@models/Balances.model';

// TODO: replace with scopes
const prepareTXInclude = ({
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
}: {
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
}) => {
let include: Includeable | Includeable[] | null = null;

if (isExist(includeAll)) {
include = { all: true, nested: isExist(nestedInclude) || undefined };
} else {
include = [];

if (isExist(includeUser)) include.push({ model: Users });
if (isExist(includeAccount)) include.push({ model: Accounts });
if (isExist(includeCategory)) include.push({ model: Categories });
}

return include;
};

export interface TransactionsAttributes {
id: number;
amount: number;
Expand Down Expand Up @@ -254,8 +225,7 @@ export default class Transactions extends Model {

@AfterUpdate
static async updateAccountBalanceAfterUpdate(instance: Transactions) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const newData: Transactions = (instance as any).dataValues;
const newData: Transactions = instance.dataValues;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const prevData: Transactions = (instance as any)._previousDataValues;
const isAccountChanged = newData.accountId !== prevData.accountId;
Expand Down Expand Up @@ -316,12 +286,7 @@ export const findWithFilters = async ({
accountIds,
userId,
order = SORT_DIRECTIONS.desc,
includeUser,
includeAccount,
transactionType,
includeCategory,
includeAll,
nestedInclude,
isRaw = false,
excludeTransfer,
excludeRefunds,
Expand All @@ -337,11 +302,6 @@ export const findWithFilters = async ({
accountIds?: number[];
userId: number;
order?: SORT_DIRECTIONS;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
isRaw: boolean;
excludeTransfer?: boolean;
excludeRefunds?: boolean;
Expand All @@ -350,14 +310,6 @@ export const findWithFilters = async ({
amountGte?: number;
amountLte?: number;
}) => {
const include = prepareTXInclude({
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

const whereClause: WhereOptions<Transactions> = {
userId,
...removeUndefinedKeys({
Expand Down Expand Up @@ -401,7 +353,6 @@ export const findWithFilters = async ({
}

const transactions = await Transactions.findAll({
include,
where: whereClause,
offset: from,
limit: limit,
Expand Down Expand Up @@ -435,100 +386,43 @@ export const getTransactionBySomeId = ({
export const getTransactionById = ({
id,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
}: {
id: number;
userId: number;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
}): Promise<Transactions | null> => {
const include = prepareTXInclude({
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

return Transactions.findOne({
where: { id, userId },
include,
});
};

export const getTransactionsByTransferId = ({
transferId,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
}: {
transferId: number;
userId: number;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
}) => {
const include = prepareTXInclude({
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

return Transactions.findAll({
where: { transferId, userId },
include,
});
};

export const getTransactionsByArrayOfField = async <T extends keyof TransactionModel>({
fieldValues,
fieldName,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
}: {
fieldValues: TransactionModel[T][];
fieldName: T;
userId: number;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
}) => {
const include = prepareTXInclude({
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

const transactions = await Transactions.findAll({
where: {
[fieldName]: {
[Op.in]: fieldValues,
},
userId,
},
include,
});

return transactions;
Expand Down
23 changes: 1 addition & 22 deletions src/services/transactions/get-by-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,10 @@ import * as Transactions from '@models/Transactions.model';
import { withTransaction } from '../common';

export const getTransactionById = withTransaction(
async ({
id,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
}: {
id: number;
userId: number;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
}) => {
async ({ id, userId }: Parameters<typeof Transactions.getTransactionById>[0]) => {
const data = await Transactions.getTransactionById({
id,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

return data;
Expand Down
20 changes: 1 addition & 19 deletions src/services/transactions/get-by-transfer-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,10 @@ export const getTransactionsByTransferId = withTransaction(
async ({
transferId,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
}: {
transferId: number;
userId: number;
includeUser?: boolean;
includeAccount?: boolean;
includeCategory?: boolean;
includeAll?: boolean;
nestedInclude?: boolean;
}) => {
}: Parameters<typeof Transactions.getTransactionsByTransferId>[0]) => {
const data = await Transactions.getTransactionsByTransferId({
transferId,
userId,
includeUser,
includeAccount,
includeCategory,
includeAll,
nestedInclude,
});

return data;
Expand Down

0 comments on commit f20e0e6

Please sign in to comment.