write tests /** * @description получить вложенный одноуровневый объект из DOMNode */…
- User
write tests /**
-
@description получить вложенный одноуровневый объект из DOMNode */ export const getObjectFromDOMNode = (node: Node) => { const result: Record<string, string | null> = {};
node.childNodes.forEach((key) => { result[key.nodeName] = key.textContent; });
return result; };
-
- Assistant
- User
import type { ConditionScroll } from '$conditions-core';
import { getXPathExpressionNodes } from '../getXPathExpressionNodes';
interface GetScrollsFromXmlTreeProps { xmlTree: string; }
/**
-
@param xmlTree Дерево продукта
-
@description получить список перечней групп из Приложения 4 продукта
-
Дублирование полей обусловлено разным применением результата */ export const getScrollsFromXmlTree = ({ xmlTree, }: GetScrollsFromXmlTreeProps): ConditionScroll[] => { const SCROLLS_XML_TREE_PATH = '//properties/product';
const items = getXPathExpressionNodes({ expression: SCROLLS_XML_TREE_PATH, xmlTree, });
const scrolls = items?.nodes?.[0]?.getElementsByTagName('group') ?? [];
if (scrolls.length > 0) { return Array.from(scrolls).map((scroll) => { const id = scroll.getElementsByTagName('id')[0].textContent ?? ''; const name = scroll.getElementsByTagName('name')[0]?.textContent ?? ''; const scrollName = scroll.getElementsByTagName('name')[0]?.textContent; const number = scroll.getElementsByTagName('number')[0]?.textContent; const scrollNumber = scroll.getElementsByTagName('number')[0]?.textContent; const members = scroll.getElementsByTagName('members')[0]?.textContent; const consolidationCompany = scroll.getElementsByTagName('consolidationCompany')[0]?.textContent; const hasIndividualEntrepreneur = scroll.getElementsByTagName('hasIndividualEntrepreneur')[0] ?.textContent;
-
- Assistant
- User
const xmlTree =
<data> <properties> <product> <group> <id>1</id> <name>Group A</name> <number>1001</number> <members>10</members> <consolidationCompany>Company A</consolidationCompany> <hasIndividualEntrepreneur>true</hasIndividualEntrepreneur> </group> <group> <id>2</id> <name>Group B</name> <number>1002</number> <members>20</members> <consolidationCompany>Company B</consolidationCompany> <hasIndividualEntrepreneur>false</hasIndividualEntrepreneur> </group> </product> </properties> </data>;как сделать эту строку преобразованной к строке в один ряд - Assistant
- User
import { evaluate, XPathResult } from 'xpath';
import { XmlTreeCache } from '$conditions-core';
import { modifyXPathExpression } from '../modifyXPathExpression';
interface GetXPathExpressionNodesProps { expression: string; xmlTree: XMLDocument | string; propagationIndex?: number; }
/**
-
@description выполнение XPath Expression
-
@returns Список элементов */ export const getXPathExpressionNodes = ({ expression, xmlTree, propagationIndex, }: GetXPathExpressionNodesProps) => { try { // на случай, если где-то не заменено использование документа вместо строки // убрать после тестов let doc = xmlTree;
if (typeof xmlTree === 'string') { doc = XmlTreeCache.getXmlTreeFromString(xmlTree) as XMLDocument; } else { doc = xmlTree; } const modifiedExpression = modifyXPathExpression({ expression, propagationIndex }); return evaluate(modifiedExpression, doc, null, XPathResult.ANY_TYPE, null);} catch (err) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.log('Ошибка вычисления условия', err, expression); }
return null;} };
-
- Assistant
- User
import { evaluate, XPathResult } from 'xpath';
import { XmlTreeCache } from '$conditions-core';
import { modifyXPathExpression } from '../modifyXPathExpression';
interface GetXPathExpressionValueProps { expression: string; xmlTree: XMLDocument | string; propagationIndex: number; }
/**
-
@description выполнение XPath Expression
-
@returns Значение в дереве */ export const getXPathExpressionValue = ({ expression, xmlTree, propagationIndex, }: GetXPathExpressionValueProps) => { try { // на случай, если где-то не заменено использование документа вместо строки // убрать после тестов let doc = xmlTree;
if (typeof xmlTree === 'string') { doc = XmlTreeCache.getXmlTreeFromString(xmlTree) as XMLDocument; } else { doc = xmlTree; } const modifiedExpression = modifyXPathExpression({ expression, propagationIndex }); const expressionResult = evaluate(modifiedExpression, doc, null, XPathResult.STRING_TYPE, null); return expressionResult.stringValue;} catch (err) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.log('Ошибка вычисления условия', err, expression); }
return null;} };
-
- Assistant
- User
interface InjectParentIndexInAvailabilityExpressionProps { expression: string | null; parentIndex: number; }
/**
- @description Добавляет для вложенных элементов индекс родительского элемента в выражение
- Используется для дочерних атрибутов partyList
- @param expression Выражение XPath
- @param parentIndex Индекс родительского элемента
- @returns Выражение XPath
- */
export const injectParentIndexInAvailabilityExpression = ({
parentIndex,
expression,
}: InjectParentIndexInAvailabilityExpressionProps) =>
expression?.replace(/item/g,
item[@index="${parentIndex}"]) ?? '';
- Assistant
- User
interface ModifyXPathExpressionProps { expression: string; propagationIndex?: number; }
export const modifyXPathExpression = ({ expression, propagationIndex, }: ModifyXPathExpressionProps) => { if (propagationIndex != null && expression.includes('/codes/')) { return expression.replace(//codes/g,
/codes[propagationIndex=${propagationIndex}]); }return expression;};
- Assistant
- User
export const removeHeaderFromXmlTreeStr = (xmlTreeStr: string) => xmlTreeStr.replace('', '');
- Assistant
- User
import { checkXPathExpression } from '../../../xml';
type CheckIsCorrectResponsibilityProps = { defaultExpr: string | null; xmlTreeString: string; };
export const checkIsCorrectResponsibility = ({ defaultExpr, xmlTreeString, }: CheckIsCorrectResponsibilityProps) => { return checkXPathExpression({ expression: defaultExpr, xmlTree: xmlTreeString, }); };
- Assistant
- User
import type { ResponsibilityKindId } from '$conditions-core';
import type { DefaultResponsibilities } from '$conditions-constructor-v2/entities/condition';
import { checkIsCorrectResponsibility } from './checkIsCorrectResponsibility';
type CheckDisabledResponsibilityWithExceptionProps = { defaultResponsibility: Labeled; defaultResponsibilities: DefaultResponsibilities[]; xmlTreeString: string; };
export const checkDisabledResponsibilityWithException = ({ defaultResponsibility, defaultResponsibilities, xmlTreeString, }: CheckDisabledResponsibilityWithExceptionProps) => { let calculatedDefaultResponsibility = { ...defaultResponsibility };
if (defaultResponsibilities.length > 0) { defaultResponsibilities.forEach((responsibility) => { if ( checkIsCorrectResponsibility({ defaultExpr: responsibility.defaultExpr, xmlTreeString }) ) { calculatedDefaultResponsibility = { ...responsibility.responsibilityKind }; } }); } return calculatedDefaultResponsibility.id === 'DEFAULT';};
- Assistant
- User
import type { ConditionGroupId, ResponsibilityKindId } from '$conditions-core';
import type { DefaultResponsibilities } from '$conditions-constructor-v2/entities/condition';
import { checkDisabledResponsibilityWithException } from './checkDisabledResponsibilityWithException';
type GetDisabledResponsibilityProps = { defaultResponsibility: Labeled; defaultResponsibilities: DefaultResponsibilities[]; conditionGroupId: ConditionGroupId; xmlTreeString: string; };
export const getDisabledResponsibility = ({ defaultResponsibility, defaultResponsibilities, conditionGroupId, xmlTreeString, }: GetDisabledResponsibilityProps) => { switch (conditionGroupId) { case 'ATYPICAL': case 'OTHER_TYPICAL': return false; default: return checkDisabledResponsibilityWithException({ defaultResponsibility, defaultResponsibilities, xmlTreeString, }); } };
- Assistant
- User
import type { FieldPath } from 'react-hook-form';
import type { Propagation } from '$conditions-core';
import type { ConditionDto, ConditionMessage } from '$conditions-constructor-v2/entities/condition';
interface GetErrorsWithIndexesProps { errors: ConditionMessage[]; propagations: Propagation[]; }
export const getErrorsWithIndexes = ({ errors, propagations }: GetErrorsWithIndexesProps) => { return errors.map((err) => { if (err.propagationId !== null) { const propagationIndex = propagations?.find( (el) => el.id === err.propagationId, )?.propagationIndex;
- Assistant
- User
import type { Propagation, PropagationKind } from '$conditions-core';
import type { ConditionSettingsMenuItem } from '../../..'; import { getPropagationsByKind } from './getPropagationsByKind';
interface GetSettingsItemsFromPropagationsProps { propagations: Propagation[]; kinds: PropagationKind[]; }
export const getSettingsItemsFromPropagations = ( props: GetSettingsItemsFromPropagationsProps, ): Array => { const filteredPropagations = getPropagationsByKind(props);
return filteredPropagations.map((it) => ({ id: it.propagationIndex, name: it.name, disabled: it.mandatory, }));}; /**
- Тип распространений
- GROUP - Группа
- BORROWER - Заемщик
- SURETY - Поручитель
- DEAL - Сделка
- PLEDGER - Залогодатель
- GUARANTOR - Гарант */ export type PropagationKind = 'GROUP' | 'BORROWER' | 'SURETY' | 'DEAL' | 'PLEDGER' | 'GUARANTOR'; import type { Propagation, PropagationKind } from '$conditions-core';
interface GetPropagationsByKindProps { propagations: Propagation[]; kinds: PropagationKind[]; }
export const getPropagationsByKind = ({ kinds, propagations }: GetPropagationsByKindProps) => propagations.filter((it) => kinds.includes(it.propagationKind.id));
- Assistant
- User
- Assistant
- User
import type { Propagation } from '$conditions-core';
export const getIsBorrowerPropagation = (propagation: Propagation) => propagation.propagationKind.id === 'BORROWER';
export const getIsSuretyPropagation = (propagation: Propagation) => propagation.propagationKind.id === 'SURETY';
export const getIsGroupPropagation = (propagation: Propagation) => propagation.propagationKind.id === 'GROUP';
export const getIsDealPropagation = (propagation: Propagation) => propagation.propagationKind.id === 'DEAL';
export const getIsPledgerPropagation = (propagation: Propagation) => propagation.propagationKind.id === 'PLEDGER';
export const getIsGuarantorPropagation = (propagation: Propagation) => propagation.propagationKind.id === 'GUARANTOR';
- Assistant
- User
export const parseStringToNullableNumber = (str: string | null): number | null => typeof str === 'string' ? Number(str) : null;
- Assistant
- User
import type { ConditionGroupId, Propagation } from '$conditions-core';
import type { OtherTypicalCondition } from '$conditions-constructor-v2/entities/condition';
import { OTHER_TYPICAL_CONDITIONS_OPTIONS_MAP } from '../../../consts';
interface GetUpdateOtherTypicalConditionDataProps { propagations: Propagation[]; otherTypicalConditionData: OtherTypicalCondition | null; conditionGroupId: ConditionGroupId; }
export const getUpdatedOtherTypicalConditionData = ({ propagations, otherTypicalConditionData, conditionGroupId, }: GetUpdateOtherTypicalConditionDataProps): OtherTypicalCondition | null => { if (conditionGroupId === 'OTHER_TYPICAL') { const nullableInAppendix3 = !propagations.some( (it) => it.selected && (it.propagationKind.id === 'BORROWER' || it.propagationKind.id === 'SURETY'), );
const displayInAppendix3 = nullableInAppendix3 ? null : (otherTypicalConditionData?.displayInAppendix3 ?? OTHER_TYPICAL_CONDITIONS_OPTIONS_MAP.displayInAppendix3[0]); return { ...otherTypicalConditionData, displayInAppendix3, } as OtherTypicalCondition; } return null;};
- Assistant
- User
import type { OtherTypicalCondition } from '$conditions-constructor-v2/entities/condition';
export const OTHER_TYPICAL_CONDITIONS_OPTIONS_MAP: { [Property in keyof OtherTypicalCondition]: Array<NonNullable<OtherTypicalCondition[Property]>>; } = { conditionGroup: [ { id: 'FINANCE', name: 'Финансовый' }, { id: 'PRODUCT', name: 'Продуктовый' }, ], displayInAppendix3: [ { id: 'ALL_MANDATORY_EXPANDED', name: 'отдельной строкой в разделе "Все обязательные условия, в т.ч."', }, { id: 'ADDITIONAL', name: 'отдельной строкой в разделе "Дополнительные условия"', }, ], typicalTextExistence: [ { id: 'SET_TYPICAL_TEXT', name: 'Задать типовую формулировку', }, { id: 'TYPICAL_TEXT_ABSENT', name: 'Типовая формулировка отсутствует', }, ], };
/** Код другого типового ковенанта */ export const OTHER_TYPICAL_COVENANT_CODE = '10.';
- Assistant
- User
import cloneDeep from 'lodash.clonedeep';
import type { Attribute } from '$conditions-core';
import { checkIsPartyList, checkIsSelect } from '../../../attributeTypeGuards';
/** Удалить все атрибуты с типом STATIC, т.к. они не содержат значений и сервер их не сохраняет */ export const clearStaticAttributes = (attributes: Attribute[]): Attribute[] => (attributes || []) .filter((it) => it.attributeType?.id !== 'STATIC') .map((attr) => { const attribute = cloneDeep(attr);
if (attribute?.childAttributes?.length > 0) { attribute.childAttributes = clearStaticAttributes(attribute.childAttributes); } if (checkIsSelect(attribute) && attribute?.selectedOption?.childAttributes?.length > 0) { attribute.selectedOption.childAttributes = clearStaticAttributes( attribute.selectedOption.childAttributes, ); } if (checkIsPartyList(attribute) && attribute?.partyList?.length > 0) { attribute.partyList = attribute.partyList.map((it) => ({ ...it, childAttributes: clearStaticAttributes(it.childAttributes), })); } return attribute; }); - Assistant
- User
import type { Attribute } from '$conditions-core';
import { checkIsPartyList } from '../../../attributeTypeGuards';
export const deleteUnavailableAttributes = (attributes: Attribute[]): Attribute[] => attributes // Проверка на it?.attributeType костыль, из-за появляния фантомного атрибута // TODO: исправить в 54.0 релизе .filter((it) => it?.attributeType && it.available) .map((it) => { if (!checkIsPartyList(it) && (!it.childAttributes || it.childAttributes?.length === 0)) { return it; }
if (checkIsPartyList(it)) { return { ...it, partyList: it.partyList.map((party) => ({ ...party, childAttributes: deleteUnavailableAttributes(party.childAttributes), })), }; } return { ...it, childAttributes: deleteUnavailableAttributes(it.childAttributes), }; }); - Assistant
- User
import type { ConditionGroupId } from '$conditions-core';
import type { ConditionDto } from '$conditions-constructor-v2/entities/condition';
import { getNotTypicalConditionDefaultName } from '../getNotTypicalConditionDefaultName'; import { clearStaticAttributes } from './clearStaticAttributes'; import { deleteUnavailableAttributes } from './deleteUnavailableAttributes';
interface FormatCovenantStateBeforeSaveProps { formState: ConditionDto; conditionGroupId: ConditionGroupId; }
export const formatConditionStateBeforeSave = ({ conditionGroupId, formState, }: FormatCovenantStateBeforeSaveProps) => { const conditionDto = { ...formState, };
if ( (conditionGroupId === 'OTHER_TYPICAL' || conditionGroupId === 'ATYPICAL') && !formState.name.trim().length ) { conditionDto.name = getNotTypicalConditionDefaultName(conditionGroupId); } conditionDto.propagations = conditionDto.propagations .filter((it) => it.selected) .map((it) => ({ ...it, attributes: deleteUnavailableAttributes(clearStaticAttributes(it.attributes)), })); return conditionDto;};
- Assistant
- User
import type { ConditionGroupId } from '$conditions-core';
interface ConditionHasTextInfoProps { conditionGroupId: ConditionGroupId; }
/* Имеет ли условие текстовки на сервере */ export const conditionHasTextInfo = ({ conditionGroupId }: ConditionHasTextInfoProps) => conditionGroupId !== 'ATYPICAL';
- Assistant
The
conditionHasTextInfofunction is a simple utility function that checks whether a condition has text information based on itsconditionGroupId. Specifically, it returnstruefor all group IDs except for . - User
import type { ConditionGroupId } from '$conditions-core';
export const getNotTypicalConditionDefaultName = (conditionGroupId: ConditionGroupId) => { switch (conditionGroupId) { case 'OTHER_TYPICAL': return 'Другой типовой ковенант';
case 'ATYPICAL': return 'Нетиповой ковенант'; default: return ''; }};
- Assistant