Feature/routes export (#29)
Tests / backend-test (push) Successful in 6m7s
Tests / frontend-test (push) Successful in 1m29s

Co-authored-by: gorbenko.pavel <gorbenko.pavel@tansu.kz>
Reviewed-on: http://git.tnsu.kz/gorbenko.pavel/tnsu-approval-route/pulls/29
This commit was merged in pull request #29.
This commit is contained in:
2026-10-14 05:06:58 +00:00
parent 05f73d356a
commit 0e6a7064d2
21 changed files with 832 additions and 28 deletions
@@ -20,6 +20,7 @@ import { RouteStepsScreen } from '../screens/RouteStepsScreen';
import { ResolveScreen } from '../screens/ResolveScreen';
import { ManageRequestsScreen } from '../screens/ManageRequestsScreen';
import { ManageByUserScreen } from '../screens/ManageByUserScreen';
import { RoutesExportScreen } from '../screens/RoutesExportScreen';
// Тот же боковой рейл (@tnsu/ui-kit Sidebar), что и в request-portal — единый
// стиль навигации во всех веб-частях Tnsu. 'routeSteps' сюда не входит: это не
@@ -28,11 +29,12 @@ import { ManageByUserScreen } from '../screens/ManageByUserScreen';
const NAV_ITEMS: ISidebarItem[] = [
{ id: 'dashboard', title: texts.nav.dashboard, icon: 'chart' },
{ id: 'requestTypes', title: texts.nav.requestTypes, icon: 'document' },
{ id: 'requestTypeAccess', title: texts.nav.requestTypeAccess, icon: 'people' },
{ id: 'routes', title: texts.nav.routes, icon: 'send' },
{ id: 'resolve', title: texts.nav.resolve, icon: 'search' },
{ id: 'routesExport', title: texts.nav.routesExport, icon: 'document' },
{ id: 'manageRequests', title: texts.nav.manageRequests, icon: 'clipboard' },
{ id: 'manageByUser', title: texts.nav.manageByUser, icon: 'user-check' }
{ id: 'manageByUser', title: texts.nav.manageByUser, icon: 'user-check' },
{ id: 'requestTypeAccess', title: texts.nav.requestTypeAccess, icon: 'people' }
];
function sidebarActiveId(tab: ScreenKey): string {
@@ -184,6 +186,7 @@ export const AdminApp: React.FC<IAdminAppProps> = ({ api, dictionary, sharePoint
route={route.resolve}
/>
)}
{route.tab === 'routesExport' && <RoutesExportScreen api={api} />}
{route.tab === 'manageRequests' && (
<ManageRequestsScreen api={api} dictionary={dictionary} requestManage={requestManage} route={route.manage} />
)}
@@ -5,5 +5,6 @@ export type ScreenKey =
| 'routes'
| 'routeSteps'
| 'resolve'
| 'routesExport'
| 'manageRequests'
| 'manageByUser';
@@ -10,3 +10,24 @@
max-width: 320px;
flex: 1;
}
.chosen {
display: flex;
flex-direction: column;
gap: 6px;
margin-top: 10px;
}
.chosenItem {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 4px 8px 4px 12px;
border: 1px solid #e1e4ea;
border-radius: 6px;
}
.chosenEmpty {
opacity: 0.6;
}
@@ -53,7 +53,7 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
const [showForm, setShowForm] = React.useState(false);
const [requestTypeId, setRequestTypeId] = React.useState('');
const [email, setEmail] = React.useState('');
const [emails, setEmails] = React.useState<string[]>([]);
const submit = useAsyncSubmit();
const [filterRequestTypeId, setFilterRequestTypeId] = useLocalStorageState(ACCESS_FILTER_TYPE_STORAGE_KEY, '');
@@ -97,7 +97,7 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
const openCreate = (): void => {
setRequestTypeId('');
setEmail('');
setEmails([]);
setShowForm(true);
};
@@ -106,17 +106,56 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
submit.fail(texts.requestTypeAccess.validationRequestType);
return;
}
if (!email.trim()) {
if (emails.length === 0) {
submit.fail(texts.requestTypeAccess.validationEmail);
return;
}
submit.run(() =>
api.requestTypeAccess.create({ requestTypeId: Number(requestTypeId), email: email.trim() }).then(() => {
// По одному запросу на сотрудника (бэкенд выдаёт доступ по одному). Падение на
// одном не отменяет остальных: неудавшиеся остаются в списке с причиной, чтобы
// можно было поправить и нажать ещё раз.
submit.run(async () => {
const failures: string[] = [];
const failedEmails: string[] = [];
for (const email of emails) {
try {
await api.requestTypeAccess.create({ requestTypeId: Number(requestTypeId), email });
} catch (e) {
failedEmails.push(email);
failures.push(`${email}: ${(e as Error).message}`);
}
}
if (failedEmails.length < emails.length) access.reload();
if (failures.length === 0) {
setShowForm(false);
access.reload();
})
);
return;
}
setEmails(failedEmails);
throw new Error(texts.requestTypeAccess.createFailed(failures));
});
};
// Тех, у кого доступ к этому типу уже есть (и кого уже добавили в список), показываем
// в поиске с пометкой, но выбрать нельзя — так видно, что человек не потерялся.
const grantedEmails = new Set(
access.items.filter(a => String(a.requestTypeId) === requestTypeId).map(a => a.email.toLowerCase())
);
const chosenEmails = new Set(emails.map(e => e.toLowerCase()));
const employeeOptions = employees.items.map(employee => {
const option = toEmployeeOption(employee);
const key = employee.email.toLowerCase();
if (grantedEmails.has(key)) {
return { ...option, disabled: true, sublabel: `${option.sublabel ?? ''} · ${texts.requestTypeAccess.alreadyGranted}` };
}
if (chosenEmails.has(key)) {
return { ...option, disabled: true, sublabel: `${option.sublabel ?? ''} · ${texts.requestTypeAccess.alreadyChosen}` };
}
return option;
});
const employeeLabel = (email: string): string => {
const employee = employees.items.find(e => e.email.toLowerCase() === email.toLowerCase());
return employee ? `${employee.fio} · ${employee.email}` : email;
};
return (
@@ -207,15 +246,30 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
/>
</Field>
<Field label={texts.requestTypeAccess.emailLabel} required full>
<SearchableSelect
options={employees.items.map(toEmployeeOption)}
value={email}
loading={employees.isLoading}
placeholder={texts.requestTypeAccess.emailPlaceholder}
searchPlaceholder={texts.select.employeeSearchPlaceholder}
emptyMessage={texts.select.employeesEmpty}
onChange={setEmail}
/>
<div>
<SearchableSelect
options={employeeOptions}
value=""
loading={employees.isLoading}
placeholder={texts.requestTypeAccess.emailPlaceholder}
searchPlaceholder={texts.select.employeeSearchPlaceholder}
emptyMessage={texts.select.employeesEmpty}
onChange={value => value && setEmails(current => [...current, value])}
/>
<div className={styles.chosen}>
{emails.length === 0 && <span className={styles.chosenEmpty}>{texts.requestTypeAccess.noEmailsSelected}</span>}
{emails.map(email => (
<div key={email} className={styles.chosenItem}>
<span>{employeeLabel(email)}</span>
<IconButton
icon="close"
label={texts.requestTypeAccess.removeEmail}
onClick={() => setEmails(current => current.filter(x => x !== email))}
/>
</div>
))}
</div>
</div>
</Field>
</FormGrid>
</FormModal>
@@ -0,0 +1,99 @@
import * as React from 'react';
import { ApprovalRouteApi } from '../../services/api';
import { texts } from '../../texts';
import { useRequestTypes } from '../../hooks/useRequestTypes';
import { useLocalStorageState } from '../../hooks/useLocalStorageState';
import { reportError } from '../../utils/errors';
import { Alert, Breadcrumbs, Button, Checkbox, PageHeader, Panel } from '../ui';
export interface IRoutesExportScreenProps {
api: ApprovalRouteApi;
}
// Выбранные типы заявок переживают перезагрузку страницы — выгрузку обычно
// делают по одному и тому же набору типов.
const SELECTED_STORAGE_KEY = 'approvalAdmin.routesExport.selected';
function download(blob: Blob, fileName: string): void {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
export const RoutesExportScreen: React.FC<IRoutesExportScreenProps> = ({ api }) => {
const requestTypes = useRequestTypes(api);
const [storedSelected, setSelected] = useLocalStorageState<number[]>(SELECTED_STORAGE_KEY, []);
const [isBusy, setIsBusy] = React.useState(false);
const [error, setError] = React.useState<string | undefined>();
const allIds = requestTypes.items.map(rt => rt.id);
// Удалённые с тех пор типы из сохранённого выбора не считаем.
const selected = storedSelected.filter(id => allIds.indexOf(id) !== -1);
const allSelected = allIds.length > 0 && allIds.every(id => selected.indexOf(id) !== -1);
const toggle = (id: number, checked: boolean): void =>
setSelected(current => (checked ? [...current.filter(x => x !== id), id] : current.filter(x => x !== id)));
const runExport = (): void => {
setError(undefined);
setIsBusy(true);
api.reports.routes(selected)
.then(file => download(file.blob, file.fileName ?? texts.routesExport.fileName))
.catch((e: Error) => setError(texts.routesExport.failed(reportError(e, 'RoutesExportScreen: export'))))
.then(() => setIsBusy(false), () => setIsBusy(false));
};
return (
<div>
<Breadcrumbs items={[{ label: texts.common.home }, { label: texts.routesExport.breadcrumb }]} />
<PageHeader
icon="clipboard"
subtitle={texts.routesExport.subtitle}
title={texts.routesExport.title}
actions={
<Button
variant="accent"
icon="check"
disabled={selected.length === 0 || isBusy}
onClick={runExport}
>
{isBusy ? texts.routesExport.exporting : texts.routesExport.export}
</Button>
}
/>
{requestTypes.error && <Alert kind="err">{requestTypes.error}</Alert>}
{error && <Alert kind="err">{error}</Alert>}
<Panel>
<p>{texts.routesExport.hint}</p>
{requestTypes.isLoading && <p>{texts.common.loading}</p>}
{!requestTypes.isLoading && requestTypes.items.length === 0 && <p>{texts.routesExport.emptyTypes}</p>}
{requestTypes.items.length > 0 && (
<div>
<Checkbox
label={texts.routesExport.selectAll}
checked={allSelected}
onChange={checked => setSelected(checked ? allIds : [])}
/>
{requestTypes.items.map(rt => (
<Checkbox
key={rt.id}
label={rt.name}
checked={selected.indexOf(rt.id) !== -1}
onChange={checked => toggle(rt.id, checked)}
/>
))}
<p>{texts.routesExport.selected(selected.length)}</p>
</div>
)}
</Panel>
</div>
);
};
@@ -116,6 +116,7 @@
&:hover, &.active { background: $gold-50; color: $navy-900; }
&.selected { font-weight: 600; color: $navy-900; }
&:disabled { cursor: not-allowed; opacity: 0.55; background: transparent; color: $gray-700; }
}
.itemSub {
@@ -9,6 +9,8 @@ export interface ISearchableOption {
label: string;
/** Второстепенная строка под названием — например, компания у отдела. */
sublabel?: string;
/** Показывается в списке (и находится поиском), но выбрать нельзя. */
disabled?: boolean;
}
export interface ISearchableSelectProps {
@@ -135,6 +137,7 @@ export const SearchableSelect: React.FC<ISearchableSelectProps> = ({
type="button"
key={opt.value}
className={`${styles.item} ${opt.value === value ? styles.selected : ''}`}
disabled={opt.disabled}
onClick={() => pick(opt.value)}
>
{opt.label}
@@ -89,7 +89,7 @@ const ROUTE_CHANGE_EVENT = 'aa-route-change';
// 'routeSteps' сюда намеренно не входит — это не отдельная вкладка URL, а
// состояние вкладки 'routes' при наличии aaroute (см. parseRoute).
const TABS: ScreenKey[] = ['dashboard', 'requestTypes', 'requestTypeAccess', 'routes', 'resolve', 'manageRequests', 'manageByUser'];
const TABS: ScreenKey[] = ['dashboard', 'requestTypes', 'routes', 'resolve', 'routesExport', 'manageRequests', 'manageByUser', 'requestTypeAccess'];
const PARAM_KEYS = [
'aatab', 'aaroute', 'aarfilter',
@@ -1,4 +1,4 @@
import { IHttpClient } from './httpClient';
import { IDownloadedFile, IHttpClient } from './httpClient';
import {
CreateRequestTypeAccessInput,
CreateRequestTypeInput,
@@ -172,4 +172,10 @@ export class ApprovalRouteApi {
})
.then(rows => rows.map(toUserApprovalRow))
};
// Выгрузки файлами (ReportsController) — в ответ приходит xlsx, не JSON.
public readonly reports = {
routes: (requestTypeIds: number[]): Promise<IDownloadedFile> =>
this.http.postForBlob('/api/reports/routes', { requestTypeIds })
};
}
@@ -18,6 +18,28 @@ export class ApiClientError extends Error {
}
}
/** Скачанный файл; fileName пуст, если сервер не прислал Content-Disposition. */
export interface IDownloadedFile {
blob: Blob;
fileName?: string;
}
// filename*=UTF-8''... (RFC 5987, так отдаёт ASP.NET для кириллицы) или обычный filename=...
// eslint-disable-next-line @rushstack/no-new-null -- header — результат Headers.get() (DOM API)
function fileNameFromDisposition(header: string | null | undefined): string | undefined {
if (!header) return undefined;
const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header);
if (encoded) {
try {
return decodeURIComponent(encoded[1]);
} catch {
// Битая кодировка — падаем на обычный filename ниже.
}
}
const plain = /filename="?([^";]+)"?/i.exec(header);
return plain ? plain[1] : undefined;
}
export type QueryParams = Record<string, string | number | boolean | undefined>;
export interface IHttpClient {
@@ -26,6 +48,8 @@ export interface IHttpClient {
put<T>(path: string, body?: unknown): Promise<T>;
patch<T>(path: string, body?: unknown): Promise<T>;
delete(path: string): Promise<void>;
/** POST, на который сервер отвечает файлом (xlsx), а не JSON-конвертом. */
postForBlob(path: string, body: unknown): Promise<IDownloadedFile>;
}
function buildUrl(baseUrl: string, path: string, query?: QueryParams): string {
@@ -105,6 +129,21 @@ export class AadApiHttpClient implements IHttpClient {
await this.send<void>('DELETE', path);
}
public async postForBlob(path: string, body: unknown): Promise<IDownloadedFile> {
const url = buildUrl(this.baseUrl, path);
const response = await this.client.fetch(url, AadHttpClient.configurations.v1, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!response.ok) {
// Ошибка приходит обычным JSON-конвертом ({ messages } или { errors }) — разбираем тем же парсером.
await parseResponse<void>(response);
throw new ApiClientError(response.status, [`HTTP ${response.status}`]);
}
return { blob: await response.blob(), fileName: fileNameFromDisposition(response.headers.get('Content-Disposition')) };
}
private send<T>(method: string, path: string, body?: unknown): Promise<T> {
const url = buildUrl(this.baseUrl, path);
return this.client
+24 -3
View File
@@ -96,6 +96,7 @@ export const texts = {
requestTypeAccess: 'Доступ к заявкам',
routes: 'Маршруты',
resolve: 'Проверка маршрута',
routesExport: 'Выгрузка маршрутов',
manageRequests: 'Редактирование заявок',
manageByUser: 'Заявки по участнику'
},
@@ -197,15 +198,35 @@ export const texts = {
createTitle: 'Выдать доступ',
requestTypeLabel: 'Тип заявки',
requestTypePlaceholder: 'Выберите тип заявки',
emailLabel: 'Сотрудник',
emailPlaceholder: 'Найдите по ФИО или email',
emailLabel: 'Сотрудники',
emailPlaceholder: 'Добавьте сотрудника — найдите по ФИО или email',
removeEmail: 'Убрать из списка',
alreadyGranted: 'доступ уже есть',
alreadyChosen: 'уже в списке',
noEmailsSelected: 'Пока никого не выбрано.',
createFailed: (failures: string[]): string =>
`Не удалось выдать доступ (остались в списке): ${failures.join('; ')}`,
validationRequestType: 'Выберите тип заявки.',
validationEmail: 'Выберите сотрудника.',
validationEmail: 'Выберите хотя бы одного сотрудника.',
deleteTitle: 'Отозвать доступ?',
deleteText: (email: string, requestTypeName: string): string =>
`${email} больше не будет видеть все заявки типа «${requestTypeName}».`
},
routesExport: {
breadcrumb: 'Выгрузка маршрутов',
subtitle: 'Маршруты согласования в Excel',
title: 'Выгрузка маршрутов',
hint: 'Отметьте типы заявок — каждый попадёт на отдельный лист файла (согласующие и исполнители отдельными таблицами).',
selectAll: 'Выбрать все',
export: 'Выгрузить',
exporting: 'Формирование файла...',
emptyTypes: 'Типов заявок пока нет.',
selected: (count: number): string => `Выбрано: ${count}`,
fileName: 'Маршруты согласования.xlsx',
failed: (reason: string): string => `Не удалось выгрузить маршруты: ${reason}`
},
routes: {
breadcrumb: 'Маршруты согласования',
subtitle: 'Настройка согласований',