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 | 80x 44x 44x 44x 40x 40x 44x 28x 28x 16x 40x 40x 40x 16x 5x 5x 1x 11x 16x 16x 44x 44x 44x 44x 44x 2x 2x 42x 3x 3x 3x 3x 3x 2x 2x 1x 39x 44x 26x 26x 1x 28x 28x 28x 28x 28x 26x 26x 5x 2x 2x 26x 26x | /*
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
limitations under the License.
*/
import consts from '@front/consts.js';
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import userRightStore from '@front/store/userRightStore.js';
import {readLast, readRecent, pickEntryAlias} from '@front/helpers/recentArchitectures';
const logger = getLoggerWithTag('f/h/orgCtxOnStartPageHelper');
/**
* Обработка параметра orgctx
* 1. Ищем контекст в URL, referrer, доступных сохранённых организациях, затем берём первый из прав
* 2. Сохраняем orgCtx в userRightStore и устанавливаем на страницу если еще нету
*/
export async function processingOrgCtx() {
let orgCtx = findOrgCtxInUrl();
logger.debug(() => `found OrgCtx in url with value '${orgCtx}'`);
if (!orgCtx) {
orgCtx = pickEntryAlias({
last: readLast(),
recent: readRecent(),
rights: userRightStore.getAll()
}) || userRightStore.getFirstUserCtxAlias();
logger.debug(() => `OrgCtx in url was null or undefined, selected from accessible history or first user right, receive '${orgCtx}'`);
}
if (orgCtx) {
await addOrgCtxInUrl(orgCtx);
userRightStore.setCurrentCtx(orgCtx);
} else {
logger.info(() => 'not found ctx in url or user right store');
}
}
/**
* сохраняем контекст в url (_sfa-orgctx) при переходах по роутам если он есть
* @param to - целевая страница для перехода
* @param from - исходная страница, с которой произошел переход
*/
export function orgCtxRoutHandler(to, from) {
const fromContext = from.query[consts.roleModelV2.urlAliasParamName];
const toContext = to.query[consts.roleModelV2.urlAliasParamName];
if (fromContext !== toContext) { // если _sfa-orgctx на целевой странице отличается от исходной страницы
if (fromContext) { // и на исходной странице есть _sfa-orgctx
to.query[consts.roleModelV2.urlAliasParamName] = fromContext; // тогда переносим его на целевую страницу
if (toContext) { // при этом если на целевой странице тоже указан _sfa-orgctx
to.query[consts.roleModelV2.urlOriginAliasParamName] = toContext; // то сохраняем его в другом атрибуте (в планах возможно показать уведомление о разных контекстах)
}
} else { // если на исходной странице контекста нет, но он есть на целевой (потому что они не равны)
from.query[consts.roleModelV2.urlAliasParamName] = toContext; // то исходной проставим целевой (чтобы не попасть в вечный цикл)
}
Eif (fromContext !== toContext) {
return {
path: to.path,
query: to.query,
params: to.params,
hash: to.hash // якорь целевой страницы не теряется при перенаправлении
};
}
}
}
/**
* Ищем _sfa-orgctx
* Сначала проверяем может он есть в url который открыт.
* Если нет, тогда смотрим document.referrer - страницу с которой перешли, контекст в этом случае пробрасываем на текущую вкладку
* Если и в document.referrer нет, тогда ничего не делаем
*
* @returns {string,null} - вернем строку со значением найденного контекста или null
*/
function findOrgCtxInUrl() {
let resultCtx = null;
const currentLocation = new URL(window.location.href);
const currentLocationParams = new URLSearchParams(currentLocation.search);
const currentLocationCtx = currentLocationParams.get(consts.roleModelV2.urlAliasParamName);
if (currentLocationCtx) {
resultCtx = currentLocationCtx;
logger.debug(() => `seaf ctx '${currentLocationCtx}' found in page url`);
} else if(document.referrer) {
logger.debug(() => `seaf ctx not found in page url, try search in referrer: ${document.referrer}`);
const referrerUrl = new URL(document.referrer);
const referrerParams = new URLSearchParams(referrerUrl.search);
const referrerCtx = referrerParams.get(consts.roleModelV2.urlAliasParamName);
if (referrerCtx) {
resultCtx = referrerCtx;
logger.debug(() => `seaf ctx '${referrerCtx}' found in referrer`);
} else {
logger.debug(() => [
'seaf ctx not found in referrer',
{title: 'document.referrer', obj: document.referrer}
]);
}
} else {
logger.debug(() => [
'seaf ctx not found in page url and document.referrer is null or empty',
{title: 'document.referrer', obj: document.referrer}
]);
}
return resultCtx;
}
/**
* Декодирует якорь из window.location.hash: он процент-кодирован, а роутер при разборе объектной локации кодирует
* hash сам, иначе символ % закодируется повторно (кириллический якорь перестанет находить заголовок)
* @param hash якорь вида '#...'
* @returns {string} декодированный якорь; при некорректной последовательности — как есть
*/
function decodeHash(hash) {
try {
return decodeURIComponent(hash);
} catch (e) {
return hash;
}
}
/**
* Добавляем orgCtx в url через роутер: перенаправление на тот же адрес с контекстом в query, без новой записи в
* истории (replace) и с сохранением якоря страницы
* @param orgCtx
*/
async function addOrgCtxInUrl(orgCtx) {
Iif (!orgCtx) {
logger.warn(() => [
'addOrgCtxInUrl receive null or undefined "orgCtx" param, cannot set in url',
{title: 'document.referrer', obj: document.referrer}
]);
return;
}
const currentLocation = window.location;
const searchParams = new URLSearchParams(currentLocation.search);
const currentLocationCtx = searchParams.get(consts.roleModelV2.urlAliasParamName);
if (currentLocationCtx !== orgCtx) { // устанавливаем orgctx в url если его нет или он отличается
const query = Object.create(null);
for (const [key, value] of searchParams) {
if (!Object.hasOwn(query, key)) query[key] = value;
else Iif (Array.isArray(query[key])) query[key].push(value);
else query[key] = [query[key], value];
}
query[consts.roleModelV2.urlAliasParamName] = orgCtx;
await window.Router.push({
path: currentLocation.pathname,
query,
hash: decodeHash(currentLocation.hash), // якорь страницы остаётся в адресе
// На уже открытой странице orgCtxRoutHandler кладёт контекст в текущий маршрут и перенаправляет на тот же
// адрес; без force роутер отбросит перенаправление как повтор текущего маршрута и адрес не изменится
force: true,
// Адрес та же страница, только с контекстом: replace не добавляет запись в историю, иначе «Назад» вернёт
// на адрес без контекста, и хук снова перенаправит на страницу с контекстом
replace: true
});
}
}
|