All files / src/Batch APohodaListBatch.ts

65.33% Statements 49/75
32% Branches 8/25
84.21% Functions 16/19
65.33% Lines 49/75

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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 25918x   18x 18x   18x 18x 18x   18x   18x   252x 252x               14x       14x               14x 14x 14x   14x   14x       14x         14x     14x             14x     14x       14x 14x   14x                                                                         9x 9x   9x 9x   9x 9x   9x 9x   9x       14x                     14x         28x         14x         14x         14x         7x         13x                   28x                                     14x 14x                               14x         14x       14x 14x                                                                              
import CoreFormsEnum from '@orchesty/nodejs-sdk/dist/lib/Application/Base/CoreFormsEnum';
import { ApplicationInstall } from '@orchesty/nodejs-sdk/dist/lib/Application/Database/ApplicationInstall';
import ABatchNode from '@orchesty/nodejs-sdk/dist/lib/Batch/ABatchNode';
import { HttpMethods } from '@orchesty/nodejs-sdk/dist/lib/Transport/HttpMethods';
import BatchProcessDto from '@orchesty/nodejs-sdk/dist/lib/Utils/BatchProcessDto';
import { StatusCodes } from 'http-status-codes';
import { DateTime } from 'luxon';
import { checkErrorInResponse, ICO, jsonToXml, ResponseState, xmlToJson } from '../PohodaApplication';
 
export const LAST_RUN = 'lastRun';
 
export default abstract class APohodaListBatch<IInput, IOutput, Filter extends string> extends ABatchNode {
 
    public constructor(private readonly timeout = 120_000) {
        super();
    }
 
    protected abstract getKey(): string;
 
    protected abstract getSchema(): string;
 
    public async processAction(dto: BatchProcessDto<IInput>): Promise<BatchProcessDto<IOutput>> {
        const applicationInstall = await this.getApplicationInstallFromProcess(
            dto,
            await this.useInForm(dto) ? null : true,
        );
        const requestDto = (await this.getApplication().getRequestDto(
            dto,
            applicationInstall,
            HttpMethods.POST,
            'xml',
            jsonToXml(await this.createData(dto, applicationInstall)),
        )).setTimeout(this.timeout);
 
        const responseDto = await this.getSender().send(requestDto, [StatusCodes.OK]);
        const response = xmlToJson<IResponse<IOutput>>(responseDto.getBuffer());
        let items = this.getItems(response);
 
        items ??= [];
 
        Iif (!Array.isArray(items)) {
            items = [items];
        }
 
        Iif (await this.useAsBatch(dto)) {
            if (items.length) {
                dto.addItem(items);
            }
        } else {
            dto.setItemList(items);
        }
 
        Iif (items.length === await this.getLimit(dto)) {
            const item = items.pop() as Record<string, { id: string; }> | undefined;
 
            if (item) {
                dto.setBatchCursor(String(Number(item[`${this.getKey()}Header`].id) + 1));
            }
        } else {
            await this.setLastRun(dto);
        }
 
        return dto as unknown as Promise<BatchProcessDto<IOutput>>;
    }
 
    protected async createData(dto: BatchProcessDto<IInput>, applicationInstall: ApplicationInstall): Promise<object> {
        const itemKey = this.getKey();
        const listKey = `${itemKey.charAt(0).toUpperCase()}${itemKey.slice(1)}`;
 
        return {
            /* eslint-disable @typescript-eslint/naming-convention */
            'data:dataPack': {
                '@_xmlns:data': 'http://www.stormware.cz/schema/version_2/data.xsd',
                '@_xmlns:filter': 'http://www.stormware.cz/schema/version_2/filter.xsd',
                '@_xmlns:filterType': 'http://www.stormware.cz/schema/version_2/type.xsd',
                '@_xmlns:itemData': this.getSchema(),
                '@_id': 'Orchesty',
                '@_ico': applicationInstall.getSettings()[CoreFormsEnum.AUTHORIZATION_FORM][ICO],
                '@_application': 'Orchesty',
                '@_note': `${listKey}List`,
                '@_version': '2.0',
                ...await this.getCustomDataPackAttributes(dto),
                'data:dataPackItem': {
                    '@_id': 'Orchesty',
                    '@_version': '2.0',
                    ...await this.getCustomDataPackItemAttributes(dto),
                    [`itemData:list${listKey}Request`]: {
                        '@_version': '2.0',
                        [`@_${itemKey}Version`]: '2.0',
                        'itemData:limit': {
                            'filter:count': await this.getLimit(dto),
                            'filter:idFrom': await this.getOffset(dto),
                        },
                        [`itemData:request${listKey}`]: {
                            ...await this.getCustomRequestAttributes(dto),
                            ...this.processFilters(await this.getFilters(dto)),
                        },
                        ...await this.getCustomListRequestAttributes(dto),
                    },
                },
            },
            /* eslint-enable @typescript-eslint/naming-convention */
        };
    }
 
    protected getItems(response: IResponse<IOutput>): IOutput[] {
        const itemKey = this.getKey();
        const listKey = `list${itemKey.charAt(0).toUpperCase()}${itemKey.slice(1)}`;
 
        const { responsePack } = response;
        checkErrorInResponse(responsePack);
 
        const { responsePackItem } = responsePack;
        checkErrorInResponse(responsePackItem);
 
        const itemsList = responsePackItem[listKey];
        checkErrorInResponse(itemsList.importDetails?.detail);
 
        return itemsList[itemKey];
    }
 
    protected async getFilters(dto: BatchProcessDto<IInput>): Promise<IFilter<Filter>> {
        Iif (await this.useLastRun(dto)) {
            const lastRun = await this.getLastRun(dto);
 
            if (lastRun) {
                return {
                    // @ts-expect-error Intentionally
                    lastChanges: lastRun,
                };
            }
        }
 
        return {};
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async getLimit(dto: BatchProcessDto<IInput>): Promise<number> {
        return 1_000;
    }
 
    // eslint-disable-next-line @typescript-eslint/require-await
    protected async getOffset(dto: BatchProcessDto<IInput>): Promise<string> {
        return dto.getBatchCursor('0');
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async getCustomDataPackAttributes(dto: BatchProcessDto<IInput>): Promise<object> {
        return {};
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async getCustomDataPackItemAttributes(dto: BatchProcessDto<IInput>): Promise<object> {
        return {};
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async getCustomListRequestAttributes(dto: BatchProcessDto<IInput>): Promise<object> {
        return {};
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async getCustomRequestAttributes(dto: BatchProcessDto<IInput>): Promise<object> {
        return {};
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async getLastRunKey(dto: BatchProcessDto<IInput>): Promise<string> {
        return this.getKey();
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async useLastRun(dto: BatchProcessDto<IInput>): Promise<boolean> {
        return false;
    }
 
    protected async getLastRun(dto: BatchProcessDto<IInput>): Promise<string | undefined> {
        if (!await this.useLastRun(dto)) {
            return undefined;
        }
 
        const applicationInstall = await this.getApplicationInstallFromProcess(dto);
        const lastRun = applicationInstall.getNonEncryptedSettings()[LAST_RUN]?.[await this.getLastRunKey(dto)];
 
        if (!lastRun) {
            return undefined;
        }
 
        return `${DateTime.fromISO(lastRun, { zone: 'Europe/Prague' }).toISO({ includeOffset: false })}Z`;
    }
 
    protected async setLastRun(dto: BatchProcessDto<IInput>): Promise<void> {
        Eif (!await this.useLastRun(dto)) {
            return;
        }
 
        const applicationInstall = await this.getApplicationInstallFromProcess(dto);
 
        applicationInstall.addNonEncryptedSettings({
            [LAST_RUN]: {
                [await this.getLastRunKey(dto)]: new Date().toISOString(),
            },
        });
 
        await this.getDbClient().getApplicationRepository().update(applicationInstall);
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async useAsBatch(dto: BatchProcessDto<IInput>): Promise<boolean> {
        return false;
    }
 
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/require-await
    protected async useInForm(dto: BatchProcessDto<IInput>): Promise<boolean> {
        return false;
    }
 
    private processFilters(filters: IFilter<Filter>): object {
        Eif (!Object.keys(filters).length) {
            return {};
        }
 
        const rawFilter = 'filter:filter';
        const rawFilters: Record<string, Record<string, unknown>> = {
            [rawFilter]: {},
        };
 
        Object
            .entries(filters)
            .map(([key, value]) => {
                rawFilters[rawFilter][`filter:${key}`] = value;
 
                return undefined;
            });
 
        return rawFilters;
    }
 
}
 
export type IFilter<Filter extends string> = Partial<Record<Filter, string | { 'filterType:id': string }>>;
 
interface IResponse<IOutput> {
    responsePack: {
        responsePackItem: Record<string, Record<string, IOutput[]> & IResponsePackItemError>;
        state: ResponseState;
        note: string;
    };
}
 
interface IResponsePackItemError {
    importDetails: {
        detail: {
            state: ResponseState;
            note: string;
        };
    };
}