All files / src/web/controllers gmailTransactionsController.ts

92.75% Statements 64/69
69.76% Branches 30/43
100% Functions 3/3
92.53% Lines 62/67

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  7x 7x         7x 7x       7x 7x   7x   7x   7x 2x   2x     5x   5x   5x 2x   2x     3x   3x 3x 3x   3x 3x       3x 3x 3x   3x 62x 2x     60x 1x     94x   59x 11x 11x   11x     48x   48x     3x   3x             3x             3x                             7x 2x   2x   2x           2x   2x 2x   2x 2x   2x 23x   22x     1x   1x   1x   1x   1x   1x   1x   1x       7x
import { Request, Response } from "express";
import { injectables } from "../../core/types/injectables";
import { DependencyInjector } from "../../dependencyInjector";
import GoogleOAuth2Identifiers from "../../googleOAuth2/types/googleOAuth2Identifiers";
import ILogger from "../../core/contracts/ILogger";
import TransactionRepository from "../../core/repositories/transactionRepository";
import ITransactionProvider from "../../core/contracts/ITransactionProvider";
import { ResponseExtensions } from "../../core/extensions/responseExtensions";
import { TransactionExtensions } from "../../core/extensions/transactionExtensions";
import Transaction from "../../core/types/transaction";
import PaymentDetails from "../../core/types/paymentDetails";
 
const getLast = async (req: Request, res: Response) => {
    const logger = DependencyInjector.Singleton.resolve<ILogger>(injectables.ILogger);
 
    const lastParam = req.params.last;
    
    const last = Number(lastParam);
 
    if (Number.isNaN(last) || last < 1) {
        ResponseExtensions.badRequest(res, `Invalid last amount provided: ${lastParam}`);
        
        return;
    }
 
    const skipDepthQuery = req.query.skip_depth;
    
    const skipDepth = Number(skipDepthQuery);
 
    if (skipDepthQuery !== undefined && (Number.isNaN(skipDepth) || skipDepth < 1)) {
        ResponseExtensions.badRequest(res, `Invalid skip depth provided: ${skipDepthQuery}`);
        
        return;
    }
 
    const skipSaved = req.query.skip_saved === 'true';
 
    const identifiers = res.locals.googleOAuth2Identifiers as GoogleOAuth2Identifiers;
    const gmailTransactionProvider = await DependencyInjector.Singleton.generateGmailServiceAsync<ITransactionProvider>(injectables.GmailTransactionProviderGenerator, identifiers);
    const transactionRepository = DependencyInjector.Singleton.resolve<TransactionRepository>(injectables.TransactionRepository);
 
    try {
        const existingTransactionIds = skipSaved
            ? await transactionRepository.getAllIdsAsync()
            : []; // Only load existing IDs if needed
 
        const transactionIds: string[] = [];
        let skippedCount = 0;
        let consecutiveSkippedCount = 0;
 
        for await (const transactionId of gmailTransactionProvider.generateAsync()) {
            if (lastParam !== undefined && transactionIds.length + skippedCount >= last) {
                break;
            }
 
            if (skipDepthQuery !== undefined && consecutiveSkippedCount >= skipDepth) {
                break;
            }
 
            const transactionExists = existingTransactionIds.find((id) => id === transactionId) !== undefined;
 
            if (skipSaved && transactionExists) {
                skippedCount++;
                consecutiveSkippedCount++;
 
                continue;
            }
            
            transactionIds.push(transactionId);
 
            consecutiveSkippedCount = 0;
        }
 
        const resolvedCount = transactionIds.length;
        
        const message = `Resolved ${resolvedCount} out of the last ${last} transaction ids${
            skippedCount > 0
                ? `, skipped ${skippedCount}${skipDepthQuery !== undefined
                    ? ` with a skip depth of ${skipDepth}`
                    : ''}`
                : ``}`
 
        logger.log(message, {
            last: last,
            ...(skipDepthQuery !== undefined && !Number.isNaN(skipDepth)) && { skip_depth: skipDepth },
            ...(skipSaved !== undefined) && { skip_saved: skipSaved },
            access_token: identifiers.accessToken
        });
 
        ResponseExtensions.ok(res, transactionIds);
    } catch (ex) {
        const error = ex as Error;
 
        logger.error(error, {
            last: last,
            ...(skipDepthQuery !== undefined && !Number.isNaN(skipDepth)) && { skip_depth: skipDepth },
            ...(skipSaved !== undefined) && { skip_saved: skipSaved },
            access_token: identifiers.accessToken
        })
 
        ResponseExtensions.internalError(res, error.message ?? ex);
    }
};
 
const resolve = async (req: Request, res: Response) => {
    const logger = DependencyInjector.Singleton.resolve<ILogger>(injectables.ILogger);
 
    const ids: string[] = req.body;
    
    Iif (!Array.isArray(ids)) {
        ResponseExtensions.badRequest(res, `Bad ids parameter: ${ids}`);
        
        return;
    }
 
    const aggregatedIds = ids.join(',');
 
    const identifiers = res.locals.googleOAuth2Identifiers as GoogleOAuth2Identifiers;
    const gmailTransactionProvider = await DependencyInjector.Singleton.generateGmailServiceAsync<ITransactionProvider>(injectables.GmailTransactionProviderGenerator, identifiers);
 
    try {
        let transactions: Transaction<PaymentDetails>[] = [];
 
        for (const id of ids) {
            const transaction = await gmailTransactionProvider.resolveTransactionAsync(id);
 
            transactions.push(transaction);
        }
 
        const resolvedCount = transactions.length;
 
        const message = `Resolved ${resolvedCount} transaction${resolvedCount == 1 ? '' : 's'}`;
 
        logger.log(message, { transaction_ids: aggregatedIds, access_token: identifiers.accessToken });
 
        const result = transactions.map(TransactionExtensions.toResponse);
        
        ResponseExtensions.ok(res, result);
    } catch (ex) {
        const error = ex as Error;
 
        logger.error(error, { transactionIds: aggregatedIds, access_token: identifiers.accessToken });
 
        ResponseExtensions.internalError(res, error.message ?? ex);
    }
};
 
export { getLast, resolve }