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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | 57x 57x 57x 6x 51x 51x 170x 169x 36x 36x 31x 31x 29x 31x 5x 4x 4x 3x 3x 3x 3x 3x 3x 134x 51x 106x 134x 2x 134x 2x 134x 1x 134x 4x 134x 1x 1x 51x 51x 90x 85x 85x 82x 74x 74x 74x 74x 77x 77x 3x 74x 74x 72x 74x 106x 33x 33x 3x 1x 3x 1x 2x 74x 10148x 20204x 20172x 20126x 20157x 10148x 20280x 148x 58x 58x 57x 57x 57x 54x 54x 54x 54x 54x 54x 66x 63x 63x 60x 60x 60x 60x 18x 54x 43x 10071x 10070x 10070x 10070x 10070x 20138x 20103x 65x 65x 65x 10071x 10071x 50x 106x 106x 62x 62x 62x 62x 59x 59x 59x 59x 57x 57x 57x 57x 57x 28x 48x 28x 10071x 10071x 10071x 10071x 10071x 10071x 10071x 10067x 10067x 10067x 10067x 10067x 65x 10067x | /*
Copyright (C) 2026 Sber
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
restrictions under the License.
*/
import { DEFS_REF_PREFIX, PRESENTATION_PRIORITY, RELS_REF_PREFIX, SEARCH_RECORD_LINK_HASH } from './constants.mjs';
import { getRecordParam, resolvePresentationParams, validatePresentationParams } from './presentation-params.ts';
import { getSearchableEntityIds } from './search-config.mjs';
/**
* Рекурсивно собирает поля со ссылками на $rels из схемы сущности.
* @param {object} fullSchema - Полная схема (req.storage.schema или manifest)
* @param {string} choice - Идентификатор сущности (entityId)
* @param {object} manifest - Манифест для fallback (manifest.entities[choice]?.schema)
* @returns {Array<{key: string, relTarget: string, isArray: boolean, title?: string}>}
*/
export function collectRelFields(fullSchema, choice, manifest) {
const entitySchema = fullSchema?.properties?.[choice] ?? manifest?.entities?.[choice]?.schema;
const defs = { ...(entitySchema?.$defs ?? {}), ...(fullSchema?.$defs ?? {}) };
if (!entitySchema || typeof entitySchema !== 'object') {
return [];
}
const result = new Map();
const processedDefs = new Set();
function visit(node, fieldName, isArray, title) {
if (!node || typeof node !== 'object') return;
if (node.$ref) {
const ref = String(node.$ref);
if (ref.startsWith(RELS_REF_PREFIX)) {
const relTarget = ref.slice(RELS_REF_PREFIX.length);
if (fieldName && !result.has(fieldName)) {
result.set(fieldName, {
key: fieldName,
relTarget,
isArray: !!isArray,
title: node.title ?? title
});
}
return;
}
if (ref.startsWith(DEFS_REF_PREFIX)) {
const defKey = ref.slice(DEFS_REF_PREFIX.length);
if (processedDefs.has(defKey)) return;
processedDefs.add(defKey);
const defNode = defs[defKey];
Eif (defNode) {
visit(defNode, fieldName, isArray, title);
}
processedDefs.delete(defKey);
return;
}
}
if (node.properties) {
for (const [k, v] of Object.entries(node.properties)) {
visit(v, k, isArray, v?.title);
}
}
if (node.items) {
visit(node.items, fieldName, true, node.title ?? title);
}
if (Array.isArray(node.allOf)) {
for (const s of node.allOf) visit(s, fieldName, isArray, title);
}
if (Array.isArray(node.oneOf)) {
for (const s of node.oneOf) visit(s, fieldName, isArray, title);
}
if (Array.isArray(node.anyOf)) {
for (const s of node.anyOf) visit(s, fieldName, isArray, title);
}
if (node.patternProperties && typeof node.patternProperties === 'object') {
for (const v of Object.values(node.patternProperties)) {
visit(v, fieldName, isArray, title);
}
}
}
visit(entitySchema, null, false, undefined);
return Array.from(result.values());
}
/**
* Парсит relTarget в entityId и subjectId.
* @param {string} relTarget - формат: "entityId.subjectId" (напр. "kadzo.v2023.groups.groups")
*/
export function parseRelTarget(relTarget) {
if (!relTarget || typeof relTarget !== 'string') return null;
const lastDot = relTarget.lastIndexOf('.');
if (lastDot < 0) return { entityId: relTarget, subjectId: null };
return {
entityId: relTarget.slice(0, lastDot),
subjectId: relTarget.slice(lastDot + 1)
};
}
export function collectTopLevelProperties(obj) {
const result = {};
const stack = [obj];
const processed = new Set();
while (stack.length > 0) {
const current = stack.pop();
if (!current || typeof current !== 'object' || processed.has(current)) {
continue;
}
processed.add(current);
// Если у текущего объекта есть properties, добавляем их
if (current.properties && typeof current.properties === 'object') {
Object.assign(result, current.properties);
}
// Добавляем все поля в стек, КРОМЕ properties
for (const key in current) {
// Пропускаем поле properties
if (key === 'properties') continue;
const value = current[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
// Для массивов добавляем каждый элемент
for (let i = 0; i < value.length; i++) {
if (value[i] && typeof value[i] === 'object') {
stack.push(value[i]);
}
}
} else {
stack.push(value);
}
}
}
}
return result;
}
export function getTitleDescriptionFields(allProperties) {
const stringFields = Object.entries(allProperties)
.filter(([, v]) => v?.type === 'string' || v?.enum)
.map(([k]) => k);
const titleKey = stringFields.find(k => /^title$|^name$|^label$/i.test(k)) || stringFields[0];
const descKey = stringFields.find(k => /^description$|^desc$/i.test(k));
return { titleKey, descKey, stringFields };
}
export function getObjectTitle(obj, { titleKey }) {
if (titleKey && obj[titleKey] != null) return String(obj[titleKey]);
return obj.title ?? obj.name ?? obj.label ?? obj._sfa_key ?? '—';
}
/**
* Преобразует ID ссылок в строку названий (title + aliases) для поиска.
* @param {object} manifest
* @param {string} relTarget - entityId.subjectId
* @param {string|string[]} ids - один ID или массив ID
* @param {Record<string, Record<string, object>>} [entityDataMap]
* @returns {string}
*/
export function resolveRefTitles(manifest, relTarget, ids, entityDataMap = {}) {
const parsed = parseRelTarget(relTarget);
if (!parsed) return '';
const { entityId } = parsed;
const entityData = entityDataMap[entityId] ?? manifest?.[entityId];
if (!entityData || typeof entityData !== 'object') return '';
const idList = Array.isArray(ids) ? ids : (ids != null && ids !== '' ? [ids] : []);
const entityDef = manifest?.entities?.[entityId];
const allProperties = entityDef?.schema ? collectTopLevelProperties(entityDef.schema) : null;
const { titleKey } = getTitleDescriptionFields(allProperties || {});
const parts = [];
for (const id of idList) {
if (id == null || typeof id !== 'string') continue;
const obj = entityData[id];
if (!obj) continue;
const objWithKey = { ...obj, _sfa_key: id };
const title = getObjectTitle(objWithKey, { titleKey });
parts.push(title);
if (Array.isArray(obj.aliases)) {
parts.push(...obj.aliases.map(a => String(a)));
}
}
return parts.join('; ');
}
export function getSearchableEntities(manifest) {
return getSearchableEntityIds(manifest);
}
function getCompanyFromKey(key, companies = {}) {
if (!key || typeof key !== 'string') return '—';
const parts = key.split('.');
const companyId = parts[0];
const company = companies[companyId];
return company?.title || companyId || '—';
}
function getObjectDescription(obj, { descKey }) {
if (descKey && obj[descKey] != null) return String(obj[descKey]);
return obj.description ?? obj.desc ?? '';
}
function matchWordsInText(text, words, ignoreCase = true) {
Iif (!text || typeof text !== 'string') return false;
const s = ignoreCase ? text.toLowerCase() : text;
return words.every(w => s.includes(ignoreCase ? w.toLowerCase() : w));
}
async function getLinkToPresForEntity(entityDef, entityId, key, orgCtx) {
const presentations = entityDef?.presentations;
if (!presentations || typeof presentations !== 'object') return null;
for (const pid of PRESENTATION_PRIORITY) {
const presentation = presentations[pid];
if (!presentation) continue;
const declared = getRecordParam(presentation);
const keys = Object.keys(presentation.params?.properties ?? {});
const parameter = declared ?? (keys.length === 1 ? keys[0] : undefined);
if (!parameter) continue;
const marker = declared && presentation.recordMarkerRequired === true;
const hash = !declared && ['tab', 'page'].includes(parameter) ? SEARCH_RECORD_LINK_HASH : '';
const query = {[parameter]: String(key)};
// Один параметр URL не может одновременно передавать разные ID записи и организации.
if (orgCtx && parameter === '_sfa-orgctx' && query[parameter] !== orgCtx) continue;
if (marker) query['_sfa-record'] = '1';
if (orgCtx) query['_sfa-orgctx'] = orgCtx;
const {params, invalidMarker} = resolvePresentationParams(presentation, query, entityId);
try {
if (invalidMarker || await validatePresentationParams(presentation.params, params)) continue;
} catch {
// Отказ валидатора или некорректная схема кандидата не блокируют поиск.
continue;
}
const search = Object.entries(query).map(([name, value]) =>
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`
).join('&');
return `/entities/${entityId}/${pid}?${search}${hash}`;
}
}
export async function buildSearchResultItem(key, value, entityId, entityTitle, companies, allProperties, entityDef, orgCtx) {
const card = await getLinkToPresForEntity(entityDef, entityId, key, orgCtx);
const company = getCompanyFromKey(key, companies);
const obj = { ...value, _sfa_key: key };
const { titleKey, descKey } = allProperties
? getTitleDescriptionFields(allProperties)
: { titleKey: 'title', descKey: 'description' };
const title = getObjectTitle(obj, { titleKey });
const description = getObjectDescription(obj, { descKey }, []);
return {
_sfa_key: key,
_sfa_entity: entityId,
company,
entityTitle,
title,
description,
card: card || undefined,
...value
};
}
export function checkSearchQueryMatch(queryWords, key, value, titleKey, descKey) {
const obj = { ...value, _sfa_key: key };
const title = getObjectTitle(obj, { titleKey });
const description = getObjectDescription(obj, { descKey }, []);
const searchText = `${title} ${description}`.trim();
const match = queryWords.length === 0
? true
: queryWords.some(w => matchWordsInText(searchText, [w]));
return match;
}
|