All files / src/web/controllers transactionsController.ts

90.09% Statements 100/111
79.77% Branches 71/89
100% Functions 7/7
89.71% Lines 96/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240  7x 7x     7x 7x 7x 7x 7x 7x 7x   7x 39x 39x   39x 78x 74x     4x 3x     1x     39x                       39x   39x 39x 39x 39x 39x 39x 39x 39x 39x 39x   39x 1x   1x     38x 1x   1x     37x 1x   1x     36x 1x   1x     35x 1x   1x     34x 1x   1x     33x           33x 2x 1x   1x       32x 16x 1x   1x       31x 2x 1x   1x       30x                       30x   30x   30x                                                         30x   30x                   7x 2x 2x   2x 2x 2x   2x 57x   2x 2x   2x   2x                   7x 1x 1x   1x 1x 1x   1x 1x   1x   1x                   7x 444x   57x 24x   24x     33x     7x  
import { Request, Response } from "express";
import { injectables } from "../../core/types/injectables";
import { DependencyInjector } from "../../dependencyInjector";
import ILogger from "../../core/contracts/ILogger";
import TransactionRepository from "../../core/repositories/transactionRepository";
import { ResponseExtensions } from "../../core/extensions/responseExtensions";
import { TransactionExtensions } from "../../core/extensions/transactionExtensions";
import { TransactionTypeExtensions } from "../../core/extensions/transactionTypeExtensions";
import { EntryTypeExtensions } from "../../core/extensions/entryTypeExtensions";
import TransactionType from "../../core/enums/transactionType";
import EntryType from "../../core/enums/entryType";
import Constants from "../../constants";
 
const get = async (req: Request, res: Response) => {
    const logger = DependencyInjector.Singleton.resolve<ILogger>(injectables.ILogger);
    const transactionRepository = DependencyInjector.Singleton.resolve<TransactionRepository>(injectables.TransactionRepository);
 
    const parseEnumQuery = (query: unknown) => {
        if (query === undefined || query == '') {
            return [] as string[];
        }
 
        if (!Array.isArray(query)) {
            return [query].map(String);
        }
        
        return query.map(String);
    }
 
    try {
        const {
            fromDate,
            toDate,
            since,
            count,
            fromSum,
            toSum,
            types,
            entryTypes,
            recipient,
            description
        } = req.query;
 
        const fromDateParsed = fromDate === undefined ? null : new Date(String(fromDate).concat(' 00:00:00Z'));
        const toDateParsed = toDate === undefined ? null : new Date(String(toDate).concat(' 12:00:00Z'));
        const sinceParsed = since === undefined ? new Date() : new Date(String(since));
        const countParsed = count === undefined ? Constants.defaultTransactionCount : Number(count);
        const fromSumParsed = fromSum === undefined ? null : Number(fromSum);
        const toSumParsed = toSum === undefined ? null : Number(toSum);
        const typesParsed = parseEnumQuery(types).map(TransactionTypeExtensions.toEnum);
        const entryTypesParsed = parseEnumQuery(entryTypes).map(EntryTypeExtensions.toEnum);
        const recipientParsed = recipient ? String(recipient) : null;
        const descriptionParsed = description ? String(description) : null;
 
        if (fromDateParsed !== null && isNaN(fromDateParsed.getTime())) {
            ResponseExtensions.badRequest(res, `Invalid fromDate value: ${fromDate}`);
        
            return;
        }
 
        if (toDateParsed !== null && isNaN(toDateParsed.getTime())) {
            ResponseExtensions.badRequest(res, `Invalid toDate value: ${toDate}`);
        
            return;
        }
 
        if (fromDateParsed !== null && toDateParsed !== null && fromDateParsed.getTime() > toDateParsed.getTime()) {
            ResponseExtensions.badRequest(res, `Invalid date range: ${fromDateParsed.toResponse()} - ${toDateParsed.toResponse()}`);
        
            return;
        }
 
        if (isNaN(sinceParsed.getTime())) {
            ResponseExtensions.badRequest(res, `Invalid since value: ${since}`);
        
            return;
        }
 
        if (isNaN(Number(countParsed))) {
            ResponseExtensions.badRequest(res, `Invalid count value: ${count}`);
        
            return;
        }
 
        if (fromSumParsed !== null && (Number.isNaN(fromSumParsed) || fromSumParsed < 0)) {
            ResponseExtensions.badRequest(res, `Invalid sum value: ${fromSum}`);
        
            return;
        }
 
        Iif (toSumParsed !== null && (Number.isNaN(toSumParsed) || toSumParsed < 0)) {
            ResponseExtensions.badRequest(res, `Invalid sum value: ${toSum}`);
        
            return;
        }
        
        if (toSumParsed !== null && fromSumParsed !== null) {
            if (fromSumParsed > toSumParsed) {
                ResponseExtensions.badRequest(res, `Invalid sum range: ${fromSumParsed} - ${toSumParsed}`);
        
                return;
            }
        }
 
        for(const type of typesParsed) {
            if (!Object.values(TransactionType).includes(type)) {
                ResponseExtensions.badRequest(res, `Invalid types value: ${type}`);
        
                return;
            }
        }
 
        for(const entryType of entryTypesParsed) {
            if (!Object.values(EntryType).includes(entryType)) {
                ResponseExtensions.badRequest(res, `Invalid entryTypes value: ${entryType}`);
        
                return;
            }
        }
 
        const transactions = await transactionRepository.filterAsync(
            fromDateParsed,
            toDateParsed,
            sinceParsed,
            countParsed,
            typesParsed,
            entryTypesParsed,
            fromSumParsed,
            toSumParsed,
            recipientParsed,
            descriptionParsed);
        
        const resolvedCount = transactions.length;
 
        const message = `Resolved ${resolvedCount} transaction${resolvedCount == 1 ? '' : 's'}`;
        
        logger.log(message, {
            since: sinceParsed.toISOString(),
            count: countParsed,
            ...(fromDateParsed !== null) && {
                from_date: fromDate
            },
            ...(toDateParsed !== null) && {
                to_date: toDate
            },
            ...(fromSum !== undefined) && {
                from_sum: fromSum
            },
            ...(toSum !== undefined) && {
                to_sum: toSum
            },
            ...(typesParsed.length > 0) && {
                types: typesParsed.join()
            },
            ...(entryTypesParsed.length > 0) && {
                entry_types: entryTypesParsed.join()
            },
            ...(recipientParsed !== null) && {
                recipient: recipientParsed
            },
            ...(descriptionParsed !== null) && {
                description: description
            }
        });
 
        const result = transactions.map(TransactionExtensions.toResponse);
 
        ResponseExtensions.ok(res, result);
    } catch(ex) {
        const error = ex as Error;
 
        logger.error(error);
 
        ResponseExtensions.internalError(res, error.message ?? ex);
    }
}
 
const save = async (req: Request, res: Response) => {
    const logger = DependencyInjector.Singleton.resolve<ILogger>(injectables.ILogger);
    const transactionRepository = DependencyInjector.Singleton.resolve<TransactionRepository>(injectables.TransactionRepository);
 
    try {
        const transactionsRaw: Record<string, string | number | object>[] = Array.isArray(req.body) ? req.body : [];
        const transactions = transactionsRaw.map(TransactionExtensions.toModel);
 
        const existingTransactionIds = await transactionRepository.getAllIdsAsync();
        const newTransactions = transactions.filter(t => !transactionExists(t.id, existingTransactionIds, logger));
 
        const created = await transactionRepository.bulkCreateAsync(newTransactions);
        const skipped = transactionsRaw.length - created;
 
        logger.log(`Saved ${created} transaction${created === 1 ? '' : 's'} to database${skipped > 0 ? `, skipped ${skipped}` : ''}`);
        
        ResponseExtensions.added(res, created, 'transaction');
    } catch (ex) {
        const error = ex as Error;
 
        logger.error(error);
 
        ResponseExtensions.internalError(res, error.message ?? ex);
    }
};
 
const update = async (req: Request, res: Response) => {
    const logger = DependencyInjector.Singleton.resolve<ILogger>(injectables.ILogger);
    const transactionRepository = DependencyInjector.Singleton.resolve<TransactionRepository>(injectables.TransactionRepository);
 
    try {
        const transactionsRaw: Record<string, string | number | object>[] = Array.isArray(req.body) ? req.body : [];
        const transactions = transactionsRaw.map(TransactionExtensions.toModel);
 
        const updated = await transactionRepository.bulkUpdateAsync(transactions);
        const skipped = transactions.length - updated;
 
        logger.log(`Updated ${updated} transaction${updated === 1 ? '' : 's'}${skipped > 0 ? `, skipped ${skipped}` : ''}`);
        
        ResponseExtensions.noContent(res);
    } catch (ex) {
        const error = ex as Error;
 
        logger.error(error);
 
        ResponseExtensions.internalError(res, error.message ?? ex);
    }
}
 
const transactionExists = (transactionId: string, existingTransactionIds: string[], logger: ILogger) => {
    const exists = existingTransactionIds.find((id) => id === transactionId) !== undefined;
 
    if (exists) {
        logger.warn("Transaction already exists", { transactionId: transactionId });
 
        return true;
    }
 
    return false;
};
 
export { save, get, update }