Проблема: Иногда не работает сортировка и иногда не работает поиск по фильтрам,…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Проблема: Иногда не работает сортировка и иногда не работает поиск по фильтрам, (замечено только в неактивных сделках, в активных проблем не замечено)
По одному ИНН в фильтре находится два ИНН или не находится по ИНН который точно есть в списке По одному контрагенту в фильтре находятся совсем другие контрагенты или не находится , но он точно есть в списке не находится по валютной паре, которая точно есть в списке сделок, или выводит валютнуб пару а с ней ещё записи с пустой валютной парой или другой парой
Эндпоинт на бэке: GET /tin/list
page integer (query) Zero-based page index (0..N) Default value: 0
size integer (query) The size of the page to be returned Default value: 20
sort array[string] (query) Sorting criteria in the format: property,(asc|desc). Default sort order is ascending. Multiple sort criteria are supported.
search string (query) Filtering criteria in the format: key(==, !=, >, <, >=, <=, ~)value. Several filtering criteria are supported, where the delimiter is ',' - operator AND, '|' - operator OR. search
src/pages/TinSettings/TinSettings.tsx редактировано под хранение в стор
export const TinSettings = () => { const dispatch = useAppDispatch(); const isAdmin = useSelector(isAdminSelector); const isLoading = useSelector(getIsPending(getTinSettings)); const error = useSelector(getError(getTinSettings)); const currencyPairs = useSelector(CurrencyPairsSelector); const content = useSelector(TinSettingDataSelector); const searchString = useSelector(tinSearchStringSelector); const pageInfo = useSelector(PageInfoSelector); const sort = useSelector(tinSortStringSelector); const { tin, counterpartyName, currencyPair, active } = searchString;
const setSort = (key: string) => { let newSort: typeof sort = null; if (!sort || sort.key !== key) { newSort = { key, value: 'asc' }; } else if (sort?.value === 'asc' && sort.key === key) { newSort = { key, value: 'desc' }; } dispatch(setSortString(newSort)); };
const { isEditing }= useSelector (selectActiveForm)
const onMoreClick = useCallback(() => { dispatch(changePageNumber({})); }, []);
const getData = useDebounced(() => dispatch(getTinSettings()), 500);
useEffect(() => { getData(); }, [sort, searchString, pageInfo.size, pageInfo.number]);
useEffect(() => { dispatch(getCurrencyPairs()); dispatch(getTinSettings()); }, []);
const onDelete = useCallback(async (id: string) => { await dispatch(deleteTinSetting([id])); }, []); };
const renderSortIcon = (key: string) => { if (!sort) { return null; } if (key == sort.key) { return sort.value === 'asc'? <Icon.ArrowUpSmall /> : <Icon.ArrowDownSmall />; } return null; };
const currencyOptions = useMemo (() => currencyPairs.map((pair) => ({ label: pair, value: pair })), [currencyPairs]);
const handleFilter = (key: string, value?: string) => { dispatch(setSearchString({...searchString, [key]: value})); };
const resetFilter = () => { dispatch(setSearchString({})); };
if (!content.length && isLoading) { return ; }
return ( <Flex pt="24px" gridGap={'24px'} flexDirection="column"> <Input value={tin || ''} width="258px" size={SIZE_VARIANT.XSMALL} inlineLabel labelText="ИНН" type="number" allowLeadingZeroes maxLength={12} onChange={(value) => handleFilter('tin', value)} /> <Input value={counterpartyName || ''} width="258px" size={SIZE_VARIANT.XSMALL] inlineLabel labelText="Контрагент" onChange={(value) => handleFilter('counterpartyName', value)} /> <SelectNew inlineLabel width="258px" labelText-"Валютная пара" type="search-single" size-{SIZE_VARIANT.XSMALL} selected={currencyPair || ''} options={currencyOptions} onSelect={(value) => { handleFilter('currencyPair', value as string); }} /> <Switch label="Только активные" isActive-{active === 'true'} onChange={(value) => handleFilter('active', value ? 'true' : undefined)} isText={false} /> <Button iconRight={Icon.Refresh} disabled={isEditing} type="button" marginLeft="auto" variation-{BUTTON_VARIATION.GHOST} onClick={resetFilter}
Очистить фильтры {isAdmin && ( <Button iconRight={Icon.Plus} disabled={isEditing} type="button" marginLeft="auto" variation-{BUTTON_VARIATION.GHOST} onClick={() => { dispatch(resetFormData ())b dispatch(startEditing ()); }
Добавить запись )}
<Flex flexDirection="column" borderRadius="md" height="100%" border="1px solid" borderColor="table-cell-border--default"
{isEditing && <Editing key="new" toggleEditing={() => dispatch (startEditing())} isNew />} {content.map((data, index) => ( <TinRow key={data.id} rowData={data} index={index} onDelete={() => onDelete (data.id)} /> ))} {content.length === 0 && !isEditing && ( )} <ErrorNotification isPositive={lerror} details={error || 'Данные не найдены'} /> handleClickMore={onMoreClick} currentPage={pageInfo.number} isLoading={isLoading} isLast={pageInfo.last} totalElements={pageInfo.totalElements} ); };
//src/typings/Platform.ts export type TEMPORARY_ANY = any; // eslint-disable-line
export interface PlatformState { [key: string]: TEMPORARY_ANY; }
export interface MicrofrontendProps { name: string; context: () => { [key: string]: unknown }; publish: (state: S) => void; navigateTo: (appName: string) => void; subscribe: ( listener: (value: PlatformState [T], oldValue?: PlatformState [T]) => void, path?: T ) => VoidFunction | void; setToast: (arg: { title: string; content: string }) => void; callModal: (modal: TModalData) => void; closeModal: () => void; setError: (modal: TModalData) => void; handleFinishApp: (callback: () => void) => void; finishApp: () => void; onFinishClientSession: () => void; registerApp: (callback: () => void) => void; domElementGetter: () => HTMLElement; };
export type TButton = { label: string; callback: () => void; type: 'primary' | 'secondary'; isInFocus?: boolean; };
export type TModalData = { erroriar: string; title?: string; content?: string; onok?: TButton; onCancel?: TButton; };
export interface LegalClient { inn: string; kpp?: string; ogrn?: string; shortName: string; unifiedId: string; }
src/pages/TinSettings/Editing.tsx
type Props = | { data: TinSettingData; toggleEditing: () => void; isNew?: false } | { isNew: true; data?: TinSettingData; toggleEditing: () => void };
export const Editing: FC = ({ data, toggleEditing, isNew }) => { const dispatch = useAppDispatch(); const currencyPairs = useSelector (CurrencyPairsSelector); const isLoading = useSelector(getIsPending (changeTinSetting));
const onSubmit = async (values: TinSettingData) => { const req = await dispatch( changeTinSetting({ ...values, counterpartyName: values.counterpartyName | undefined, validUntil: values.validUntil || undefined, currencyPair: values.currencyPair || undefined, description: values.description || undefined, minAmount: values.minAmount?.replace(/\D/g, '') || undefined, maxAmount: values.maxAmount?.replace(/\D/g, '') || undefined, globalId: values.globalId || '', }) );
(req.meta.requestStatus === 'fulfilled') { dispatch(resetFormData ()); toggleEditing(); };
const formik = useFormik({ initialValues: isNew ? ({ active: true } as TinSettingData): data, onSubmit, validate: (values) => { const errorobj = {} as Record<keyof TinSettingData, string | undefined>;
if (!values.tin || (values.tin.length !== 10 && values.tin.length !== 12)) { errorobj.tin = 'Укажите корректный ИНН'; }
if (values.validUntil && Number(values?.validUntil?.length) !== 10) { errorobj.validUntil = 'Укажите корректную дату'; }
if (values.validUntil && !isBeforeDate(new Date(), parseDateString(values.validUntil))) { } errorObj.validUntil = 'Дата не должна быть из прошлого';
if (values.minAmount && values.maxAmount) { if (Number(values.minAmount.replace(/\D/g, '')) > Number(values.maxAmount.replace(/\D/g,''))) { errorObj.minAmount = 'Сумма мин. не может быть больше суммы макс.'; } } return errorObj; }, validateOnBlur: true, enableReinitialize: true, });
const { values, errors, dirty, touched, isValid, setFieldValue, handleSubmit } = formik;
useEffect( () => () => { dispatch(resetActionsStatuses()); }, [] );
useEffect(() => { document.onkeydown = (e: KeyboardEvent) => { const { ctrlKey, code } = e;
if (ctrlKey && code === 'Enter') {
e.preventDefault(); handleSubmit(); return; } }; return () => { document.onkeydown = () => { // }; document.onkeyup = () => { // }; }; }, []);
const currencyOptions = useMemo ( () => { label: '', value: ''}].concat(currencyPairs.map((pair) => ({ label: pair, value: pair }))), [currencyPairs] );
useEffect (()=>{ const subscriber = subscribe((client: LegalClient) => { if (client) { formik.setValues({ ... formik.values, tin.: client.inn, counterpartyName: client.shortName, globalId: client.unifiedId, }) } }, 'crmLegalClient.crmLegalClient'); return subscriber }, []);
const handleClientSearch = () =>{ navigateTo(PLATFORM_APPS.LEGAL_CLIENT_SEARCH) }
return (
<Switch
isText={false}
isActive={values?.active}
onChange={(value: boolean) setFieldValue(active. value)
isActive={values?.active}
onChange={(value: boolean) => setFieldValue(active, value)}
/>
<DateInput
size={SIZE_VARIANT.XSMALL}
captionText={errors.validUntil}
hasError={touched.validUntil && !! errors.validUntil}
placeholder="Ввести дату до"
value={values.validUntil}
onChange={(value: string) => setFieldValue(validUntil, value)}
/>
<Input
size={SIZE_VARIANT.XSMALL}
value={formik.values.tin}
captionText={errors.tin}
hasError={touched.tin && !! errors.tin}
type="number"
allowLeadingZeroes
maxLength={12}
onChange={(value: string) => setFieldValue(tin, value)}
readOnly
disabled={!!values.globalId}
/>
<Icon.Magnifier />
Based on the provided code and problem description, here are the likely causes and solutions for the issues with sorting and filtering in inactive TIN settings:
1. Sorting Issues:
Problem: Sorting might not be working consistently, especially for inactive records.
Likely Cause:
/tin/list). It's possible that the sorting logic doesn't handle inactive records correctly or has a bug when applying sorting criteria to them.sortString state in the Redux store might not be correctly updating or being passed to the API request when dealing with inactive records.Solutions:
/tin/list endpoint with different sorting criteria and filter combinations, especially focusing on inactive records. Check the database queries generated by the backend to ensure they correctly apply sorting.sortString state changes in the TinSettings.tsx component, particularly when dealing with inactive records. Ensure it's being correctly included in the API request.2. Filtering Issues:
Problem: Filtering by INN, counterparty, or currency pair sometimes returns incorrect or missing results, especially for inactive records.
Likely Cause:
getTinSettings might be incorrect or incomplete. The searchString construction logic might need adjustments to handle specific filter scenarios, especially for inactive records.Solutions:
searchString construction logic in getTinSettings. Ensure it correctly handles all filter types (INN, counterparty, currency pair, active status) and their combinations. Consider using a more robust filtering library or framework if the current implementation is complex./tin/list endpoint with various filter combinations, focusing on inactive records. Verify that the database queries generated by the backend correctly apply the filters.3. Specific Filter Issues:
Multiple INN Matches: This could be due to:
Missing INN Matches:
Incorrect Counterparty Matches:
Currency Pair Issues:
Debugging Steps:
Console Logging: Add extensive console logs to track the values of searchString, sortString, and the API request parameters in getTinSettings.
Network Inspection: Use browser developer tools to inspect the network requests sent to /tin/list. Verify the parameters and the responses received.
Backend Debugging: If possible, debug the backend code to see how it processes the sorting and filtering criteria and generates the database queries.
Database Query Analysis: Examine the SQL queries generated by the backend to ensure they correctly apply the sorting and filtering logic.
Additional Considerations:
Pagination: Ensure pagination is handled correctly, especially when dealing with large datasets.
Data Consistency: Address any data inconsistencies (duplicates, formatting issues) in the database.
Error Handling: Implement robust error handling to catch and display any errors returned by the backend API.
Unit Tests: Write unit tests for the filtering and sorting logic in both the frontend and backend to ensure correctness.
By systematically debugging the frontend, backend, and database interactions, you should be able to identify and resolve the issues with sorting and filtering in inactive TIN settings.