11 Commits

Author SHA1 Message Date
gorbenko.pavel 32fe3904e3 Выгрузка маршрутов: загрузка шагов и условий раздельными запросами (AsSplitQuery)
Tests / frontend-test (pull_request) Successful in 1m31s
Tests / backend-test (pull_request) Successful in 1m55s
Убирает предупреждение EF про MultipleCollectionIncludeWarning.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:48:28 +05:00
gorbenko.pavel bacf18c608 Выгрузка маршрутов: в имени файла сокращённые типы заявок (до 7) и дата
Имя формирует бэкенд и отдаёт в Content-Disposition (он добавлен в
экспонируемые заголовки CORS), фронт сохраняет файл под этим именем.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:40:19 +05:00
gorbenko.pavel dce71ab672 Выгрузка маршрутов: комментарий «может назначить согласующего/исполнителя»
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:38:25 +05:00
gorbenko.pavel 4d3453da34 Выгрузка маршрутов: исполнители идут сразу под согласующими без шапки и пустой строки
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:35:20 +05:00
gorbenko.pavel f68c69163f RouteExportRequest: RequestTypeIds необязателен на уровне привязки, ошибку отдаёт сервис
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:28:49 +05:00
gorbenko.pavel 7c64f3ccf4 Выгрузка маршрутов: колонка «Организация» — компания сотрудника, а не маршрута
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:26:09 +05:00
gorbenko.pavel 6433299c62 Выгрузка маршрутов: сборка таблицы перенесена на бэкенд, добавлены организация, комментарий и деление на согласующих/исполнителей
Бэкенд сам читает маршруты, шаги и справочники портала (сотрудники с должностями,
компании, отделы), фронт шлёт только id типов заявок и скачивает файл.
Колонки: №, Роль, Исполнитель, Организация, Условие, Комментарий.
Согласующие и исполнители — отдельными таблицами. Условие по CompaniesJson
показывается как «организация». Директор Tansu и Управляющий директор Tansu
выводятся с ФИО. Комментарий «назначает согласующего/исполнителя» — при галочке
переназначения.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 10:24:18 +05:00
gorbenko.pavel 43b3c77ac1 Сохранять выбранные галочки на вкладке «Выгрузка маршрутов» в localStorage
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 09:50:04 +05:00
gorbenko.pavel 75214f5797 переделал на нечеткий поиск 2026-10-13 09:38:13 +05:00
gorbenko.pavel 0b06e2b958 Свернуть appsettings.*.json под appsettings.json в Solution Explorer
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 09:29:07 +05:00
gorbenko.pavel 6a01101054 Добавить вкладку «Выгрузка маршрутов» и перенести «Доступ к заявкам» вниз меню
Выбранные типы заявок выгружаются в xlsx (лист на тип: №, роль, исполнитель,
условие) через POST /api/reports/routes. Пункт меню стоит после «Проверки
маршрута», «Доступ к заявкам» — последним.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 16:18:51 +05:00
31 changed files with 132 additions and 582 deletions
@@ -1,44 +0,0 @@
using Tnsu.ApprovalRoute.Domain.Enums;
namespace Tnsu.ApprovalRoute.Application.Common;
/// <summary>
/// Русские названия типов руководителя и ролей в проекте — для всего, что видит
/// человек: предупреждения резолва, ошибки валидации, выгрузка маршрутов. Имя
/// enum'а («DirectionHead») в тексте для пользователя недопустимо.
/// </summary>
public static class StepLabels
{
public static string Of(HeadType headType) => headType switch
{
HeadType.Chief => "Непосредственный руководитель",
HeadType.DirectionHead => "Руководитель направления",
HeadType.DirectorTansu => "Директор Tansu",
HeadType.ManagingDirectorTansu => "Управляющий директор Tansu",
HeadType.DepartmentHead => "Руководитель указанного отдела",
HeadType.CompanyDirectors => "Директора компаний инициатора",
_ => headType.ToString()
};
/// <summary>Название с маленькой буквы — для середины фразы («Не найден руководитель направления»).</summary>
public static string InSentence(HeadType headType) => Lower(Of(headType));
/// <summary>
/// Все названия мужского рода («найден руководитель проекта»), кроме «Безопасность» —
/// для неё нужна отдельная формулировка, иначе выйдет «найден безопасность».
/// </summary>
public static string InSentence(ProjectRole projectRole) =>
projectRole == ProjectRole.Security ? "сотрудник службы безопасности" : Lower(Of(projectRole));
private static string Lower(string label) => char.ToLowerInvariant(label[0]) + label[1..];
public static string Of(ProjectRole projectRole) => projectRole switch
{
ProjectRole.ProjectManager => "Руководитель проекта",
ProjectRole.Planner => "Планировщик",
ProjectRole.ManagerHSE => "Менеджер HSE",
ProjectRole.Security => "Безопасность",
ProjectRole.Keeper => "Заведующий склада",
_ => projectRole.ToString()
};
}
@@ -1,7 +1,6 @@
using FluentResults;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Tnsu.ApprovalRoute.Application.Common;
using Tnsu.ApprovalRoute.Domain.Entities;
using Tnsu.ApprovalRoute.Domain.Enums;
using Tnsu.ApprovalRoute.Infrastructure.Persistence;
@@ -45,6 +44,25 @@ public sealed class RouteExportService(
["CompaniesJson"] = "организация"
};
private static readonly Dictionary<ProjectRole, string> ProjectRoleLabels = new()
{
[ProjectRole.ProjectManager] = "Руководитель проекта",
[ProjectRole.Planner] = "Планировщик",
[ProjectRole.ManagerHSE] = "Менеджер HSE",
[ProjectRole.Security] = "Безопасность",
[ProjectRole.Keeper] = "Заведующий склада"
};
private static readonly Dictionary<HeadType, string> HeadTypeLabels = new()
{
[HeadType.Chief] = "Непосредственный руководитель",
[HeadType.DirectionHead] = "Руководитель направления",
[HeadType.DirectorTansu] = "Директор Tansu",
[HeadType.ManagingDirectorTansu] = "Управляющий директор Tansu",
[HeadType.DepartmentHead] = "Руководитель указанного отдела",
[HeadType.CompanyDirectors] = "Директора компаний инициатора"
};
private static readonly Dictionary<ComparisonOperator, string> OperatorSymbols = new()
{
[ComparisonOperator.GreaterThan] = ">",
@@ -210,7 +228,7 @@ public sealed class RouteExportService(
}
if (step.ProjectRole is { } projectRole && projectRole != ProjectRole.None)
return (StepLabels.Of(projectRole), ByRequest, Empty);
return (ProjectRoleLabels[projectRole], ByRequest, Empty);
if (step.HeadType is { } headType && headType != HeadType.None)
{
@@ -222,9 +240,9 @@ public sealed class RouteExportService(
};
if (fixedEmail is not null)
// Нет в справочнике — лучше показать email, чем пустую ячейку.
return (StepLabels.Of(headType), directory.FindByEmail(fixedEmail)?.Fio ?? fixedEmail, directory.CompaniesOf(fixedEmail));
return (HeadTypeLabels[headType], directory.FindByEmail(fixedEmail)?.Fio ?? fixedEmail, directory.CompaniesOf(fixedEmail));
return (StepLabels.Of(headType), ByRequest, Empty);
return (HeadTypeLabels[headType], ByRequest, Empty);
}
return (Empty, Empty, Empty);
@@ -1,7 +1,6 @@
using FluentResults;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Tnsu.ApprovalRoute.Application.Common;
using Tnsu.ApprovalRoute.Application.Common.Errors;
using Tnsu.ApprovalRoute.Application.Common.Interfaces;
using Tnsu.ApprovalRoute.Domain.Entities;
@@ -83,7 +82,7 @@ public sealed class TemplateRouteStepService(
if (await HasDuplicateHeadTypeAsync(route.Id, r.HeadType, r.Conditions, r.ConditionsLogic, excludeId: null, cancellationToken))
return Result.Fail<TemplateRouteStepDto>(new ConflictError(
$"В маршруте уже есть шаг с типом руководителя «{StepLabels.Of(r.HeadType!.Value)}» и таким же условием появления — второй такой шаг недопустим."));
$"В маршруте уже есть шаг с типом руководителя «{r.HeadType}» и таким же условием появления — второй такой шаг недопустим."));
var entity = new TemplateRouteStep
{
@@ -142,7 +141,7 @@ public sealed class TemplateRouteStepService(
if (await HasDuplicateHeadTypeAsync(route.Id, r.HeadType, r.Conditions, r.ConditionsLogic, excludeId: entity.Id, cancellationToken))
return Result.Fail<TemplateRouteStepDto>(new ConflictError(
$"В маршруте уже есть шаг с типом руководителя «{StepLabels.Of(r.HeadType!.Value)}» и таким же условием появления — второй такой шаг недопустим."));
$"В маршруте уже есть шаг с типом руководителя «{r.HeadType}» и таким же условием появления — второй такой шаг недопустим."));
entity.OrderNo = r.OrderNo;
entity.ExecutorEmail = r.ExecutorEmail;
@@ -211,7 +210,7 @@ public sealed class TemplateRouteStepService(
if (await HasDuplicateHeadTypeAsync(route.Id, headType, conditions, conditionsLogic, excludeId: entity.Id, cancellationToken))
return Result.Fail<TemplateRouteStepDto>(new ConflictError(
$"В маршруте уже есть шаг с типом руководителя «{StepLabels.Of(headType!.Value)}» и таким же условием появления — второй такой шаг недопустим."));
$"В маршруте уже есть шаг с типом руководителя «{headType}» и таким же условием появления — второй такой шаг недопустим."));
entity.OrderNo = r.OrderNo ?? entity.OrderNo;
entity.ExecutorEmail = executorEmail;
@@ -3,7 +3,6 @@ using FluentResults;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Tnsu.ApprovalRoute.Application.Common;
using Tnsu.ApprovalRoute.Application.Common.Errors;
using Tnsu.ApprovalRoute.Application.Common.Interfaces;
using Tnsu.ApprovalRoute.Domain.Entities;
@@ -438,7 +437,7 @@ public sealed class TemplateRouteService(
{
resolvedEmail = projectExecutors.FirstOrDefault(e => e.ProjectRole == step.ProjectRole)?.Email;
if (string.IsNullOrWhiteSpace(resolvedEmail))
warning = $"В проекте не найден {StepLabels.InSentence(step.ProjectRole.Value)}.";
warning = $"Не найден исполнитель с ролью в проекте «{step.ProjectRole}».";
}
// DepartmentHead — единственный HeadType, который резолвится НЕ по цепочке
// подчинённости инициатора, а по отделу, переданному явно в запросе (см.
@@ -470,14 +469,7 @@ public sealed class TemplateRouteService(
_ => null
};
if (string.IsNullOrWhiteSpace(resolvedEmail))
{
var headLabel = StepLabels.InSentence(step.HeadType.Value);
// Директор Tansu и управляющий директор берутся из настроек сервиса, а не из
// справочника сотрудников — там email не «не найден», а «не проставлен».
warning = step.HeadType is HeadType.DirectorTansu or HeadType.ManagingDirectorTansu
? $"Не проставлен {headLabel}."
: $"Не найден {headLabel}.";
}
warning = $"Не найден руководитель типа «{step.HeadType}».";
}
else
{
@@ -620,7 +612,7 @@ public sealed class TemplateRouteService(
else if (existing.PositionCode is not null && step.PositionCode is not null && existing.PositionCode != step.PositionCode)
{
var conflictWarning =
$"Исполнитель «{step.ExecutorEmail}» получен через разные роли шага ({StepLabels.Of(existing.PositionCode.Value)} и {StepLabels.Of(step.PositionCode.Value)}) — оставлен «{StepLabels.Of(existing.PositionCode.Value)}».";
$"Исполнитель «{step.ExecutorEmail}» получен через разные роли шага ({existing.PositionCode} и {step.PositionCode}) — оставлен {existing.PositionCode}.";
var combinedWarning = string.Join(" ", new[] { existing.Warning, conflictWarning }
.Where(w => !string.IsNullOrWhiteSpace(w)));
result[index] = existing with { Warning = combinedWarning };
@@ -361,9 +361,8 @@ public sealed class TemplateRouteServiceTests : IClassFixture<PostgresDatabaseFi
resolved.Value.Steps[0].PositionCode.ShouldBe(HeadType.Chief);
var warning = resolved.Value.Steps[0].Warning;
warning.ShouldNotBeNull();
warning.ShouldContain("Непосредственный руководитель");
warning.ShouldContain("Руководитель направления");
warning.ShouldNotContain("DirectionHead");
warning.ShouldContain("Chief");
warning.ShouldContain("DirectionHead");
}
[Fact(DisplayName = "Резолв маршрута с шагом «Руководитель указанного отдела» без departmentId в запросе — маршрут формируется, шаг с предупреждением")]
@@ -1051,7 +1050,7 @@ public sealed class TemplateRouteServiceTests : IClassFixture<PostgresDatabaseFi
resolved.Value.Steps[0].ExecutorEmail.ShouldBeNull();
var warning = resolved.Value.Steps[0].Warning;
warning.ShouldNotBeNull();
warning.ShouldBe("Не найден непосредственный руководитель.");
warning.ShouldContain("руководитель");
}
[Fact(DisplayName = "Резолв шага с должностью возвращает warning, если сотрудник по должности не найден")]
@@ -1109,7 +1108,7 @@ public sealed class TemplateRouteServiceTests : IClassFixture<PostgresDatabaseFi
resolved.Value.Steps[0].ExecutorEmail.ShouldBeNull();
var warning = resolved.Value.Steps[0].Warning;
warning.ShouldNotBeNull();
warning.ShouldBe("В проекте не найден сотрудник службы безопасности.");
warning.ShouldContain("роль");
}
[Fact(DisplayName = "Резолв маршрута откатывается на маршрут без отдела, если точного совпадения по отделу нет")]
+1 -1
View File
@@ -1 +1 @@
@tnsu:registry=https://git.tnsu.kz/api/packages/tansu/npm/
@tnsu:registry=http://git.tnsu.kz/api/packages/timur.gorodetskiy/npm/
+4 -4
View File
@@ -17,7 +17,7 @@
"@microsoft/sp-property-pane": "1.22.1",
"@microsoft/sp-webpart-base": "1.22.1",
"@pnp/sp": "^4.20.0",
"@tnsu/ui-kit": "^0.14.0",
"@tnsu/ui-kit": "^0.4.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
@@ -6283,9 +6283,9 @@
"license": "0BSD"
},
"node_modules/@tnsu/ui-kit": {
"version": "0.14.0",
"resolved": "https://git.tnsu.kz/api/packages/tansu/npm/%40tnsu%2Fui-kit/-/0.14.0/ui-kit-0.14.0.tgz",
"integrity": "sha512-Vun9AUM9jL8rttbsbKo5Yh6TUz1srkNqxiO6mmzebrSo1JOASNJqNjJPMTS+8Jt3MTrJPklvh0TbeqGQzw7qxQ==",
"version": "0.4.0",
"resolved": "http://git.tnsu.kz/api/packages/timur.gorodetskiy/npm/%40tnsu%2Fui-kit/-/0.4.0/ui-kit-0.4.0.tgz",
"integrity": "sha512-J3cBvoR2vV0SC5GihOagLAqvC0txQE342qIh6viabMt+Um6Jg4mhTff+ZkVahG0g+bF6sqSCUl3x813aO82KuQ==",
"license": "ISC",
"peerDependencies": {
"@fluentui/react": "^8.106.4",
+1 -1
View File
@@ -21,7 +21,7 @@
"@microsoft/sp-property-pane": "1.22.1",
"@microsoft/sp-webpart-base": "1.22.1",
"@pnp/sp": "^4.20.0",
"@tnsu/ui-kit": "^0.14.0",
"@tnsu/ui-kit": "^0.4.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
@@ -74,11 +74,6 @@ export const ManageRequestsApproverModal: React.FC<IManageRequestsApproverModalP
const excludedSet = new Set(excludedEmails.map(e => e.toLowerCase()));
const selectableEmployees = employees.filter(e => !excludedSet.has(e.email.toLowerCase()));
const isDirty =
email !== initialEmail ||
slaHours !== slaHoursToInput(initialSlaHours) ||
askOverdueReason !== boolToTriState(initialAskOverdueReason);
const handleSubmit = (): void => {
const trimmedEmail = email.trim();
if (!trimmedEmail) {
@@ -100,7 +95,7 @@ export const ManageRequestsApproverModal: React.FC<IManageRequestsApproverModalP
};
return (
<FormModal title={title} error={submit.error} isSaving={submit.isBusy} onSubmit={handleSubmit} onClose={onClose} isDirty={isDirty}>
<FormModal title={title} error={submit.error} isSaving={submit.isBusy} onSubmit={handleSubmit} onClose={onClose}>
<FormGrid>
<Field label={texts.manageRequests.approverLabel} required full>
<SearchableSelect
@@ -10,24 +10,3 @@
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;
}
@@ -9,8 +9,6 @@ import { usePortalEmployees } from '../../hooks/usePortalEmployees';
import { useAsyncSubmit } from '../../hooks/useAsyncSubmit';
import { useDeleteTarget } from '../../hooks/useDeleteTarget';
import { useLocalStorageState } from '../../hooks/useLocalStorageState';
import { useFormDraft } from '../../hooks/useFormDraft';
import { usePersistedOpen } from '../../hooks/usePersistedOpen';
import { toEmployeeOption } from '../../utils/employee';
import { replaceRoute } from '../../routing';
import { RequestTypeAccess } from '../../models';
@@ -43,17 +41,6 @@ export interface IRequestTypeAccessScreenProps {
const ACCESS_FILTER_TYPE_STORAGE_KEY = 'approvalAdmin.accessFilterRequestTypeId';
const ACCESS_FILTER_EMAIL_STORAGE_KEY = 'approvalAdmin.accessFilterEmail';
/** Черновик формы выдачи доступа — переживает закрытие модалки, см. useFormDraft. */
const CREATE_DRAFT_STORAGE_KEY = 'approvalAdmin.draft.requestTypeAccess';
const CREATE_OPEN_STORAGE_KEY = 'approvalAdmin.draftOpen.requestTypeAccess';
interface IFormState {
requestTypeId: string;
emails: string[];
}
const EMPTY_FORM: IFormState = { requestTypeId: '', emails: [] };
export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> = ({
api,
dictionary,
@@ -64,11 +51,9 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
const access = useRequestTypeAccess(api);
const employees = usePortalEmployees(dictionary);
const createOpen = usePersistedOpen(CREATE_OPEN_STORAGE_KEY);
const draft = useFormDraft<IFormState>(CREATE_DRAFT_STORAGE_KEY, EMPTY_FORM);
const { requestTypeId, emails } = draft.value;
const setEmails = (update: (current: string[]) => string[]): void =>
draft.setValue(f => ({ ...f, emails: update(f.emails) }));
const [showForm, setShowForm] = React.useState(false);
const [requestTypeId, setRequestTypeId] = React.useState('');
const [email, setEmail] = React.useState('');
const submit = useAsyncSubmit();
const [filterRequestTypeId, setFilterRequestTypeId] = useLocalStorageState(ACCESS_FILTER_TYPE_STORAGE_KEY, '');
@@ -111,7 +96,9 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
: item.sharePointLists.map(l => l.title ?? l.listId).join(', ');
const openCreate = (): void => {
createOpen.open();
setRequestTypeId('');
setEmail('');
setShowForm(true);
};
const submitForm = (): void => {
@@ -119,57 +106,17 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
submit.fail(texts.requestTypeAccess.validationRequestType);
return;
}
if (emails.length === 0) {
if (!email.trim()) {
submit.fail(texts.requestTypeAccess.validationEmail);
return;
}
// По одному запросу на сотрудника (бэкенд выдаёт доступ по одному). Падение на
// одном не отменяет остальных: неудавшиеся остаются в списке с причиной, чтобы
// можно было поправить и нажать ещё раз.
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) {
draft.reset();
createOpen.close();
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;
submit.run(() =>
api.requestTypeAccess.create({ requestTypeId: Number(requestTypeId), email: email.trim() }).then(() => {
setShowForm(false);
access.reload();
})
);
};
return (
@@ -242,15 +189,13 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
}
/>
{createOpen.isOpen && (
{showForm && (
<FormModal
title={texts.requestTypeAccess.createTitle}
error={submit.error}
isSaving={submit.isBusy}
onSubmit={submitForm}
onClose={createOpen.close}
onReset={draft.reset}
canReset={draft.isDirty}
onClose={() => setShowForm(false)}
>
<FormGrid>
<Field label={texts.requestTypeAccess.requestTypeLabel} required full>
@@ -258,34 +203,19 @@ export const RequestTypeAccessScreen: React.FC<IRequestTypeAccessScreenProps> =
options={requestTypes.items.map(rt => ({ value: String(rt.id), label: rt.name }))}
placeholder={texts.requestTypeAccess.requestTypePlaceholder}
value={requestTypeId}
onChange={e => draft.setValue(f => ({ ...f, requestTypeId: e.target.value }))}
onChange={e => setRequestTypeId(e.target.value)}
/>
</Field>
<Field label={texts.requestTypeAccess.emailLabel} required full>
<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>
<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}
/>
</Field>
</FormGrid>
</FormModal>
@@ -19,8 +19,6 @@ import { useSharePointSiteTitle } from '../../hooks/useSharePointSiteTitle';
import { useSharePointListTitle } from '../../hooks/useSharePointListTitle';
import { useAsyncSubmit } from '../../hooks/useAsyncSubmit';
import { useDeleteTarget } from '../../hooks/useDeleteTarget';
import { useFormDraft } from '../../hooks/useFormDraft';
import { usePersistedOpen } from '../../hooks/usePersistedOpen';
import {
ActionsCell,
Alert,
@@ -59,22 +57,6 @@ const EMPTY_FORM: IFormState = {
name: '', pageUrl: '', section: '', siteUrl: '', listId: '', slaHours: '', askOverdueReason: ''
};
/** Черновик формы создания — переживает закрытие модалки, см. useFormDraft. */
const CREATE_DRAFT_STORAGE_KEY = 'approvalAdmin.draft.requestType';
const CREATE_OPEN_STORAGE_KEY = 'approvalAdmin.draftOpen.requestType';
function toFormState(item: RequestType): IFormState {
return {
name: item.name,
pageUrl: item.pageUrl,
section: item.section,
siteUrl: item.siteUrl ?? '',
listId: item.listId ?? '',
slaHours: slaHoursToInput(item.slaHours),
askOverdueReason: boolToTriState(item.askOverdueReason)
};
}
// siteUrl/listId — поля RequestType, зеркалящие nullable JSON-контракт бэкенда
// (см. models/requestTypes.ts) — здесь сразу приводим null к undefined,
// внутренний код (хуки/кэш SharePointListsClient) с null не работает нигде.
@@ -96,18 +78,8 @@ export const RequestTypesScreen: React.FC<IRequestTypesScreenProps> = ({ api, sh
const list = useRequestTypes(api);
const [editing, setEditing] = React.useState<RequestType | undefined>();
// showForm — только редактирование; окно создания восстанавливается после F5 (usePersistedOpen).
const [showForm, setShowForm] = React.useState(false);
const createOpen = usePersistedOpen(CREATE_OPEN_STORAGE_KEY);
const closeForm = (): void => {
setShowForm(false);
createOpen.close();
};
const draft = useFormDraft<IFormState>(CREATE_DRAFT_STORAGE_KEY, EMPTY_FORM);
const [editForm, setEditForm] = React.useState<IFormState>(EMPTY_FORM);
const form = editing ? editForm : draft.value;
const isEditDirty = Boolean(editing) && JSON.stringify(editForm) !== JSON.stringify(toFormState(editing as RequestType));
const setForm = editing ? setEditForm : draft.setValue;
const [form, setForm] = React.useState<IFormState>(EMPTY_FORM);
const submit = useAsyncSubmit();
const sharePointLists = useSharePointLists(sharePoint, form.siteUrl);
const siteTitle = useSharePointSiteTitle(sharePoint, form.siteUrl);
@@ -120,14 +92,21 @@ export const RequestTypesScreen: React.FC<IRequestTypesScreenProps> = ({ api, sh
const openCreate = (): void => {
setEditing(undefined);
setShowForm(false);
createOpen.open();
setForm(EMPTY_FORM);
setShowForm(true);
};
const openEdit = (item: RequestType): void => {
setEditing(item);
setEditForm(toFormState(item));
createOpen.close();
setForm({
name: item.name,
pageUrl: item.pageUrl,
section: item.section,
siteUrl: item.siteUrl ?? '',
listId: item.listId ?? '',
slaHours: slaHoursToInput(item.slaHours),
askOverdueReason: boolToTriState(item.askOverdueReason)
});
setShowForm(true);
};
@@ -164,8 +143,7 @@ export const RequestTypesScreen: React.FC<IRequestTypesScreenProps> = ({ api, sh
submit.run(() =>
request.then(() => {
if (!editing) draft.reset();
closeForm();
setShowForm(false);
list.reload();
})
);
@@ -214,16 +192,13 @@ export const RequestTypesScreen: React.FC<IRequestTypesScreenProps> = ({ api, sh
emptyMessage={list.isLoading ? texts.common.loading : texts.requestTypes.emptyList}
/>
{(showForm || createOpen.isOpen) && (
{showForm && (
<FormModal
title={editing ? texts.requestTypes.editTitle : texts.requestTypes.createTitle}
error={submit.error}
isSaving={submit.isBusy}
onSubmit={submitForm}
onClose={closeForm}
onReset={editing ? undefined : draft.reset}
canReset={draft.isDirty}
isDirty={isEditDirty}
onClose={() => setShowForm(false)}
>
<FormGrid>
<Field label={texts.requestTypes.nameLabel} required full>
@@ -2,7 +2,6 @@ import * as React from 'react';
import { Company, Department, RequestType, TemplateRoute } from '../../models';
import { texts } from '../../texts';
import { useAsyncSubmit } from '../../hooks/useAsyncSubmit';
import { useFormDraft } from '../../hooks/useFormDraft';
import { ApprovalRouteApi } from '../../services/api';
import { Checkbox, Field, FormGrid, FormModal, SearchableSelect, Select } from '../ui';
@@ -28,9 +27,6 @@ interface IFormState {
requiresControl: boolean;
}
/** Черновик формы создания — переживает закрытие модалки, см. useFormDraft. */
const CREATE_DRAFT_STORAGE_KEY = 'approvalAdmin.draft.route';
function toFormState(editing: TemplateRoute | undefined, initialRequestTypeId: string): IFormState {
if (!editing) {
return {
@@ -62,10 +58,7 @@ export const RouteFormModal: React.FC<IRouteFormModalProps> = ({
onSaved,
onClose
}) => {
// Редактирование не персистим — форма всегда открывается с данными маршрута с сервера.
const draft = useFormDraft<IFormState>(editing ? undefined : CREATE_DRAFT_STORAGE_KEY, toFormState(editing, initialRequestTypeId));
const form = draft.value;
const setForm = draft.setValue;
const [form, setForm] = React.useState<IFormState>(() => toFormState(editing, initialRequestTypeId));
const submit = useAsyncSubmit();
// Отдел принадлежит компании, поэтому список сужаем под выбранную:
@@ -100,7 +93,6 @@ export const RouteFormModal: React.FC<IRouteFormModalProps> = ({
submit.run(() =>
request.then(() => {
draft.reset();
onSaved();
onClose();
})
@@ -114,9 +106,6 @@ export const RouteFormModal: React.FC<IRouteFormModalProps> = ({
isSaving={submit.isBusy}
onSubmit={submitForm}
onClose={onClose}
onReset={editing ? undefined : draft.reset}
canReset={draft.isDirty}
isDirty={Boolean(editing) && draft.isDirty}
>
<FormGrid>
<Field label={texts.routes.requestTypeLabel} required full>
@@ -24,7 +24,6 @@ import {
import { detectExecutorKind } from '../../utils/stepExecutor';
import { matchEmployeesByPosition, toEmployeeOption } from '../../utils/employee';
import { useAsyncSubmit } from '../../hooks/useAsyncSubmit';
import { useFormDraft } from '../../hooks/useFormDraft';
import { useSharePointFields } from '../../hooks/useSharePointFields';
import { ApprovalRouteApi } from '../../services/api';
import { isNumericFieldType, SharePointListsClient } from '../../services/sharePointLists';
@@ -120,9 +119,6 @@ const IS_MANAGER_VALUE_OPTIONS = [
{ value: 'false', label: texts.common.no }
];
/** Черновик формы создания шага — свой у каждого маршрута, переживает закрытие модалки (см. useFormDraft). */
const createDraftStorageKey = (routeId: number): string => `approvalAdmin.draft.routeStep.${routeId}`;
function toFormState(editing: TemplateRouteStep | undefined, nextOrderNo: number): IFormState {
if (!editing) {
return {
@@ -174,10 +170,7 @@ export const RouteStepFormModal: React.FC<IRouteStepFormModalProps> = ({
onSaved,
onClose
}) => {
// Редактирование не персистим — форма всегда открывается с данными шага с сервера.
const draft = useFormDraft<IFormState>(editing ? undefined : createDraftStorageKey(route.id), toFormState(editing, nextOrderNo));
const form = draft.value;
const setForm = draft.setValue;
const [form, setForm] = React.useState<IFormState>(() => toFormState(editing, nextOrderNo));
const submit = useAsyncSubmit();
const hasListId = Boolean(requestType?.listId);
const sharePointFields = useSharePointFields(sharePoint, requestType?.siteUrl ?? undefined, requestType?.listId ?? undefined);
@@ -407,7 +400,6 @@ export const RouteStepFormModal: React.FC<IRouteStepFormModalProps> = ({
submit.run(() =>
request.then(step => {
draft.reset();
onSaved(step);
onClose();
})
@@ -421,9 +413,6 @@ export const RouteStepFormModal: React.FC<IRouteStepFormModalProps> = ({
isSaving={submit.isBusy}
onSubmit={submitForm}
onClose={onClose}
onReset={editing ? undefined : draft.reset}
canReset={draft.isDirty}
isDirty={Boolean(editing) && draft.isDirty}
>
<FormGrid>
<Field label={texts.routeSteps.orderNoLabel} required>
@@ -13,7 +13,6 @@ import { blockIndexOf, blockRanges, markParallel, withOrdersFrom } from '../../u
import { reportError } from '../../utils/errors';
import { useRouteSteps } from '../../hooks/useRouteSteps';
import { useDeleteTarget } from '../../hooks/useDeleteTarget';
import { usePersistedOpen } from '../../hooks/usePersistedOpen';
import { usePortalEmployees } from '../../hooks/usePortalEmployees';
import { usePortalDictionaries } from '../../hooks/usePortalDictionaries';
import {
@@ -54,14 +53,7 @@ export const RouteStepsScreen: React.FC<IRouteStepsScreenProps> = ({ api, route,
const requestTypeName = requestType?.name ?? `#${route.requestTypeId}`;
const [editing, setEditing] = React.useState<TemplateRouteStep | undefined>();
// showForm — только редактирование; окно создания восстанавливается после F5 (usePersistedOpen),
// ключ свой у каждого маршрута — как и у черновика (см. RouteStepFormModal).
const [showForm, setShowForm] = React.useState(false);
const createOpen = usePersistedOpen(`approvalAdmin.draftOpen.routeStep.${route.id}`);
const closeForm = (): void => {
setShowForm(false);
createOpen.close();
};
const deleteTarget = useDeleteTarget<TemplateRouteStep>(
item => api.templateRouteSteps.remove(route.id, item.id),
@@ -79,13 +71,11 @@ export const RouteStepsScreen: React.FC<IRouteStepsScreenProps> = ({ api, route,
const openCreate = (): void => {
setEditing(undefined);
setShowForm(false);
createOpen.open();
setShowForm(true);
};
const openEdit = (item: TemplateRouteStep): void => {
setEditing(item);
createOpen.close();
setShowForm(true);
};
@@ -288,7 +278,7 @@ export const RouteStepsScreen: React.FC<IRouteStepsScreenProps> = ({ api, route,
</div>
)}
{(showForm || createOpen.isOpen) && (
{showForm && (
<RouteStepFormModal
// Undefined, если у маршрута компания не задана (запасной маршрут,
// применяется к любой компании инициатора) — тогда подсказка
@@ -303,7 +293,7 @@ export const RouteStepsScreen: React.FC<IRouteStepsScreenProps> = ({ api, route,
employees={employees.items}
employeesLoading={employees.isLoading}
onSaved={handleSaved}
onClose={closeForm}
onClose={() => setShowForm(false)}
/>
)}
@@ -11,7 +11,6 @@ import { useRequestTypes } from '../../hooks/useRequestTypes';
import { useTemplateRoutes } from '../../hooks/useTemplateRoutes';
import { usePortalDictionaries } from '../../hooks/usePortalDictionaries';
import { useDeleteTarget } from '../../hooks/useDeleteTarget';
import { usePersistedOpen } from '../../hooks/usePersistedOpen';
import { useLocalStorageState } from '../../hooks/useLocalStorageState';
import { replaceRoute } from '../../routing';
import {
@@ -40,8 +39,6 @@ export interface IRoutesScreenProps {
// Фильтр по типу заявки переживает перезагрузку: администратор обычно работает
// с одним типом заявок подряд, и сбрасывать выбор на каждый заход неудобно.
const ROUTES_FILTER_STORAGE_KEY = 'approvalAdmin.routesFilter';
/** Окно создания маршрута переживает F5 — поля подставляются из черновика (см. RouteFormModal). */
const CREATE_OPEN_STORAGE_KEY = 'approvalAdmin.draftOpen.route';
export const RoutesScreen: React.FC<IRoutesScreenProps> = ({
api,
@@ -72,13 +69,7 @@ export const RoutesScreen: React.FC<IRoutesScreenProps> = ({
const routes = useTemplateRoutes(api, filterRequestTypeId ? Number(filterRequestTypeId) : undefined);
const [editing, setEditing] = React.useState<TemplateRoute | undefined>();
// showForm — только редактирование; окно создания восстанавливается после F5 (usePersistedOpen).
const [showForm, setShowForm] = React.useState(false);
const createOpen = usePersistedOpen(CREATE_OPEN_STORAGE_KEY);
const closeForm = (): void => {
setShowForm(false);
createOpen.close();
};
const [copying, setCopying] = React.useState<TemplateRoute | undefined>();
const deleteTarget = useDeleteTarget<TemplateRoute>(item => api.templateRoutes.remove(item.id), routes.reload);
@@ -92,13 +83,11 @@ export const RoutesScreen: React.FC<IRoutesScreenProps> = ({
const openCreate = (): void => {
setEditing(undefined);
setShowForm(false);
createOpen.open();
setShowForm(true);
};
const openEdit = (item: TemplateRoute): void => {
setEditing(item);
createOpen.close();
setShowForm(true);
};
@@ -170,7 +159,7 @@ export const RoutesScreen: React.FC<IRoutesScreenProps> = ({
emptyMessage={routes.isLoading ? texts.common.loading : texts.routes.emptyList}
/>
{(showForm || createOpen.isOpen) && (
{showForm && (
<RouteFormModal
api={api}
editing={editing}
@@ -180,7 +169,7 @@ export const RoutesScreen: React.FC<IRoutesScreenProps> = ({
departments={portalDictionaries.departments}
dictionaryLoading={portalDictionaries.isLoading}
onSaved={routes.reload}
onClose={closeForm}
onClose={() => setShowForm(false)}
/>
)}
@@ -16,13 +16,12 @@
gap: 16px;
box-shadow: $sh-1;
cursor: pointer;
@include card-hover-gold;
border: 1px solid $gray-200;
text-decoration: none;
color: inherit;
position: relative;
overflow: hidden;
// Миксин с вложенным &:hover — после всех объявлений, иначе Sass ругается mixed-decls.
@include card-hover-gold;
&::before {
content: '';
@@ -1,15 +1,12 @@
import * as React from 'react';
import styles from './Modal.module.scss';
import { Button } from './Button';
import { ModalOverlay } from './ModalOverlay';
import { texts } from '../../texts';
export interface IConfirmDialogProps {
title: string;
text: string;
confirmLabel: string;
/** Подпись кнопки отказа — по умолчанию «Отмена». */
cancelLabel?: string;
onConfirm: () => void;
onCancel: () => void;
busy?: boolean;
@@ -19,19 +16,18 @@ export const ConfirmDialog: React.FC<IConfirmDialogProps> = ({
title,
text,
confirmLabel,
cancelLabel = texts.common.cancel,
onConfirm,
onCancel,
busy
}) => (
<ModalOverlay onBackdropClick={onCancel}>
<div className={styles.overlay} onClick={e => { if (e.target === e.currentTarget) onCancel(); }}>
<div className={`${styles.box} ${styles.narrow}`}>
<div className={styles.title}>{title}</div>
<p className={styles.text}>{text}</p>
<div className={styles.narrowFooter}>
<Button variant="secondary" onClick={onCancel} disabled={busy}>{cancelLabel}</Button>
<Button variant="secondary" onClick={onCancel} disabled={busy}>{texts.common.cancel}</Button>
<Button variant="danger" icon="trash" onClick={onConfirm} disabled={busy}>{confirmLabel}</Button>
</div>
</div>
</ModalOverlay>
</div>
);
@@ -1,9 +1,7 @@
import * as React from 'react';
import { Alert } from './Alert';
import { Button } from './Button';
import { ConfirmDialog } from './ConfirmDialog';
import { Modal } from './Modal';
import styles from './Modal.module.scss';
import { texts } from '../../texts';
export interface IFormModalProps {
@@ -17,18 +15,6 @@ export interface IFormModalProps {
savingLabel?: string;
onSubmit: () => void;
onClose: () => void;
/**
* Сбросить черновик формы (см. useFormDraft). Кнопка «Очистить» показывается,
* только если передан и canReset — «Отмена» и клик мимо окна черновик не трогают.
*/
onReset?: () => void;
canReset?: boolean;
/**
* В форме есть несохранённые правки существующей записи: выход (крестик,
* «Отмена», клик мимо окна) сначала спрашивает подтверждение. Для форм создания
* не нужен — их черновик сохраняется сам (см. useFormDraft).
*/
isDirty?: boolean;
children: React.ReactNode;
}
@@ -44,51 +30,21 @@ export const FormModal: React.FC<IFormModalProps> = ({
savingLabel = texts.common.saving,
onSubmit,
onClose,
onReset,
canReset,
isDirty,
children
}) => {
const [confirmingClose, setConfirmingClose] = React.useState(false);
// Во время сохранения не закрываем и не спрашиваем: запрос уже ушёл.
const requestClose = (): void => {
if (isSaving) return;
if (isDirty) setConfirmingClose(true);
else onClose();
};
return (
<>
<Modal
title={title}
onClose={requestClose}
footer={
<>
{onReset && canReset && (
<span className={styles.footerStart}>
<Button variant="ghost" icon="refresh" onClick={onReset} disabled={isSaving}>{texts.common.resetDraft}</Button>
</span>
)}
<Button variant="secondary" onClick={requestClose} disabled={isSaving}>{texts.common.cancel}</Button>
<Button variant="accent" icon="check" onClick={onSubmit} disabled={isSaving}>
{isSaving ? savingLabel : submitLabel}
</Button>
</>
}
>
{error && <Alert kind="err">{error}</Alert>}
{children}
</Modal>
{confirmingClose && (
<ConfirmDialog
title={texts.common.discardTitle}
text={texts.common.discardText}
confirmLabel={texts.common.discardConfirm}
cancelLabel={texts.common.discardKeepEditing}
onConfirm={onClose}
onCancel={() => setConfirmingClose(false)}
/>
)}
</>
);
};
}) => (
<Modal
title={title}
onClose={onClose}
footer={
<>
<Button variant="secondary" onClick={onClose} disabled={isSaving}>{texts.common.cancel}</Button>
<Button variant="accent" icon="check" onClick={onSubmit} disabled={isSaving}>
{isSaving ? savingLabel : submitLabel}
</Button>
</>
}
>
{error && <Alert kind="err">{error}</Alert>}
{children}
</Modal>
);
@@ -7,17 +7,9 @@
display: flex;
align-items: center;
justify-content: center;
// Выше шапки SharePoint, но ниже слоёв Fluent UI (1000000). Оверлей рендерится
// порталом в body (см. ModalOverlay), поэтому сравнивается с шапкой напрямую.
z-index: 100000;
z-index: 300;
backdrop-filter: blur(6px);
padding: 20px;
// Портал вне корня веб-части — шрифт и метрики .shell (AdminApp.module.scss)
// сюда не наследуются, задаём заново.
font-family: $font-sans;
font-size: $fs-body;
line-height: 1.55;
box-sizing: border-box;
}
.box {
@@ -71,7 +63,4 @@
padding: 16px 26px 22px;
}
/** Кнопка в подвале, прижатая влево, подальше от «Отмена/Сохранить» (см. «Очистить» в FormModal). */
.footerStart { margin-right: auto; }
.narrowFooter { justify-content: center; padding: 0; margin-top: 24px; }
@@ -1,7 +1,6 @@
import * as React from 'react';
import styles from './Modal.module.scss';
import { IconButton } from './IconButton';
import { ModalOverlay } from './ModalOverlay';
import { texts } from '../../texts';
export interface IModalProps {
@@ -12,7 +11,8 @@ export interface IModalProps {
}
export const Modal: React.FC<IModalProps> = ({ title, onClose, footer, children }) => (
<ModalOverlay onBackdropClick={onClose}>
// Клик по подложке закрывает окно, клик внутри — нет (проверяем сам currentTarget).
<div className={styles.overlay} onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
<div className={styles.box}>
<div className={styles.header}>
<div className={styles.title}>{title}</div>
@@ -21,5 +21,5 @@ export const Modal: React.FC<IModalProps> = ({ title, onClose, footer, children
<div className={styles.body}>{children}</div>
{footer && <div className={styles.footer}>{footer}</div>}
</div>
</ModalOverlay>
</div>
);
@@ -1,25 +0,0 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import styles from './Modal.module.scss';
export interface IModalOverlayProps {
/** Клик по подложке (не по содержимому окна). */
onBackdropClick: () => void;
children: React.ReactNode;
}
/**
* Затемнение под модалкой — порталом в document.body, а не внутри веб-части.
* На живой странице SharePoint канва веб-части лежит в своём контексте наложения
* ниже шапки (suite bar), и position: fixed-оверлей изнутри неё оказывался ПОД
* шапкой: верх окна, центрированного по высоте экрана, уезжал за неё. В workbench
* шапки нет — там было незаметно.
*/
export const ModalOverlay: React.FC<IModalOverlayProps> = ({ onBackdropClick, children }) =>
ReactDOM.createPortal(
// Клик по подложке закрывает окно, клик внутри — нет (проверяем сам currentTarget).
<div className={styles.overlay} onClick={e => { if (e.target === e.currentTarget) onBackdropClick(); }}>
{children}
</div>,
document.body
);
@@ -1,6 +1,6 @@
@import '../../../../styles/design-tokens';
// Ниже Modal.module.scss/.overlay (z-index 100000) — диалоги, которые может
// Ниже Modal.module.scss/.overlay (z-index 300) — диалоги, которые может
// открыть сама длительная операция (например, разрешение конфликта), должны
// быть ПОВЕРХ этой подложки, а не под ней.
.overlay {
@@ -73,7 +73,7 @@
box-shadow: $sh-modal;
border: 1px solid $gray-200;
padding: 6px;
z-index: 100001; // над оверлеем модалки (Modal.module.scss)
z-index: 400;
max-height: 320px;
display: flex;
flex-direction: column;
@@ -116,7 +116,6 @@
&: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,8 +9,6 @@ export interface ISearchableOption {
label: string;
/** Второстепенная строка под названием — например, компания у отдела. */
sublabel?: string;
/** Показывается в списке (и находится поиском), но выбрать нельзя. */
disabled?: boolean;
}
export interface ISearchableSelectProps {
@@ -137,7 +135,6 @@ 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}
@@ -17,7 +17,6 @@ export * from './PrimaryCell';
export * from './ActionsCell';
export * from './CellNote';
export * from './Modal';
export * from './ModalOverlay';
export * from './ConfirmDialog';
export * from './FormModal';
export * from './FormGrid';
@@ -1,58 +0,0 @@
import * as React from 'react';
import { readLocalStorage } from './useLocalStorageState';
export interface IFormDraft<T> {
value: T;
setValue: React.Dispatch<React.SetStateAction<T>>;
/** Форма отличается от initial — есть что сбрасывать. */
isDirty: boolean;
/** Вернуть initial и забыть черновик (кнопка «Очистить», успешное сохранение). */
reset: () => void;
}
function removeDraft(key: string): void {
try {
window.localStorage.removeItem(key);
} catch {
// приватный режим — черновика и не было
}
}
/**
* Состояние формы создания, которое переживает закрытие модалки (случайный клик
* по подложке, «Отмена», F5): черновик лежит в localStorage под key, пока его
* не сбросят явно — reset() после успешного сохранения или по кнопке «Очистить».
*
* key === undefined — обычный useState без персиста: так форма редактирования
* существующей записи всегда открывается с актуальными данными с сервера, а не
* с устаревшей правкой.
*/
export function useFormDraft<T>(key: string | undefined, initial: T): IFormDraft<T> {
const [value, setValue] = React.useState<T>(() => (key ? readLocalStorage(key, initial) : initial));
// initial у вызывающих — литерал, пересоздаётся каждый рендер; сравниваем по содержимому.
const initialJson = JSON.stringify(initial);
const isDirty = JSON.stringify(value) !== initialJson;
React.useEffect(() => {
if (!key) return;
if (!isDirty) {
removeDraft(key);
return;
}
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch {
// приватный режим / переполненная квота — не критично, просто не персистим
}
}, [key, value, isDirty]);
// Ключ удаляем синхронно, а не через эффект: после успешного сохранения модалка
// тут же размонтируется, и эффект на новое значение уже не отработает.
const reset = (): void => {
if (key) removeDraft(key);
setValue(JSON.parse(initialJson) as T);
};
return { value, setValue, isDirty, reset };
}
@@ -1,44 +0,0 @@
import { coerceStored } from './useLocalStorageState';
describe('coerceStored', () => {
const initial = { name: '', count: 0, flag: false, tags: [] as string[], nested: { a: '' } };
it('подставляет дефолт для полей, добавленных после сохранения', () => {
expect(coerceStored(initial, { name: 'x' })).toEqual({ ...initial, name: 'x' });
});
it('отбрасывает ключи, которых в форме больше нет', () => {
expect(coerceStored(initial, { name: 'x', removed: 1 })).not.toHaveProperty('removed');
});
it('заменяет значение другого типа дефолтом', () => {
expect(coerceStored(initial, { name: 5, tags: { a: 1 }, flag: 'yes', nested: 'oops' }))
.toEqual(initial);
});
it('принимает массив нужного типа и мёржит вложенный объект', () => {
expect(coerceStored(initial, { tags: ['a'], nested: {} }))
.toEqual({ ...initial, tags: ['a'] });
});
it('не падает на null и примитиве вместо объекта', () => {
expect(coerceStored(initial, null)).toEqual(initial);
expect(coerceStored(initial, 'x')).toEqual(initial);
});
it('для примитивного initial проверяет тип', () => {
expect(coerceStored('', 5)).toBe('');
expect(coerceStored('', 'abc')).toBe('abc');
expect(coerceStored<number[]>([], [1, 2])).toEqual([1, 2]);
});
it('для boolean-флага отбрасывает значение другого типа', () => {
expect(coerceStored(false, true)).toBe(true);
expect(coerceStored(false, 'true')).toBe(false);
});
it('при initial === undefined принимает сохранённое как есть', () => {
expect(coerceStored<string | undefined>(undefined, 'a')).toBe('a');
expect(coerceStored({ x: undefined as string | undefined }, { x: 'a' })).toEqual({ x: 'a' });
});
});
@@ -4,56 +4,28 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/**
* Сохранённое значение, приведённое к форме initial. Запись могла быть сделана
* старой версией формы, поэтому ей нельзя доверять слепо:
* - объект мёржится с initial — добавленные с тех пор поля получают дефолт;
* - ключи, которых в initial нет (поле удалили), отбрасываются;
* - значение, чей тип не совпал с initial (было число — стала строка, было
* [] — стал объект), заменяется дефолтом: иначе .map/.trim по нему уронил бы рендер;
* - null/undefined в initial типа не задают — там принимаем любое сохранённое.
*/
export function coerceStored<T>(initial: T, stored: unknown): T {
if (initial === null || initial === undefined) return stored as T;
if (Array.isArray(initial)) return (Array.isArray(stored) ? stored : initial) as unknown as T;
if (isPlainObject(initial)) {
if (!isPlainObject(stored)) return initial;
const result: Record<string, unknown> = { ...initial };
Object.keys(initial).forEach(k => {
if (k in stored) result[k] = coerceStored(initial[k], stored[k]);
});
return result as T;
}
return (typeof stored === typeof initial ? stored : initial) as T;
}
/**
* Значение из localStorage под key, приведённое к форме initial (см. coerceStored),
* или initial, если записи нет / она битая / localStorage недоступен.
*/
export function readLocalStorage<T>(key: string, initial: T): T {
try {
const raw = window.localStorage.getItem(key);
if (!raw) return initial;
return coerceStored(initial, JSON.parse(raw));
} catch {
return initial;
}
}
/**
* Как React.useState, но значение переживает перезагрузку страницы — хранится
* в localStorage под key. Падение доступа к localStorage (приватный режим,
* квота) не ломает форму — просто не персистит.
*
* Сохранённое значение приводится к форме initial (см. coerceStored): новое поле
* получает дефолт, удалённое отбрасывается, значение не того типа заменяется
* дефолтом — иначе старая запись в localStorage уронила бы рендер на первом же
* .map/.trim по этому полю.
* Сохранённое значение мелко мёржится с initial (для объектных T): если после
* обновления в форму добавили новое поле, у пользователей со старой записью в
* localStorage оно не потеряется как undefined (что уронило бы рендер на
* первом же .map/.trim по этому полю), а подставится дефолт из initial.
*/
export function useLocalStorageState<T>(key: string, initial: T): [T, React.Dispatch<React.SetStateAction<T>>] {
const [value, setValue] = React.useState<T>(() => readLocalStorage(key, initial));
const [value, setValue] = React.useState<T>(() => {
try {
const raw = window.localStorage.getItem(key);
if (!raw) return initial;
const parsed = JSON.parse(raw) as T;
return isPlainObject(initial) && isPlainObject(parsed) ? { ...initial, ...parsed } as T : parsed;
} catch {
return initial;
}
});
React.useEffect(() => {
try {
@@ -1,17 +0,0 @@
import { useLocalStorageState } from './useLocalStorageState';
export interface IPersistedOpen {
isOpen: boolean;
open: () => void;
close: () => void;
}
/**
* Признак «модалка создания открыта», переживающий F5: после перезагрузки окно
* открывается снова, а поля подставляются из черновика (см. useFormDraft).
* close() сбрасывает только признак — черновик остаётся до сохранения или «Очистить».
*/
export function usePersistedOpen(key: string): IPersistedOpen {
const [isOpen, setIsOpen] = useLocalStorageState<boolean>(key, false);
return { isOpen, open: () => setIsOpen(true), close: () => setIsOpen(false) };
}
+3 -16
View File
@@ -76,13 +76,6 @@ export const texts = {
remove: 'Удалить',
edit: 'Редактировать',
close: 'Закрыть',
/** Сброс черновика формы создания — сам черновик переживает закрытие окна. */
resetDraft: 'Очистить',
/** Предупреждение при выходе из формы редактирования с несохранёнными правками. */
discardTitle: 'Закрыть без сохранения?',
discardText: 'Внесённые изменения не сохранятся.',
discardConfirm: 'Закрыть без сохранения',
discardKeepEditing: 'Продолжить редактирование',
loading: 'Загрузка...',
yes: 'Да',
no: 'Нет',
@@ -205,16 +198,10 @@ export const texts = {
createTitle: 'Выдать доступ',
requestTypeLabel: 'Тип заявки',
requestTypePlaceholder: 'Выберите тип заявки',
emailLabel: 'Сотрудники',
emailPlaceholder: 'Добавьте сотрудника — найдите по ФИО или email',
removeEmail: 'Убрать из списка',
alreadyGranted: 'доступ уже есть',
alreadyChosen: 'уже в списке',
noEmailsSelected: 'Пока никого не выбрано.',
createFailed: (failures: string[]): string =>
`Не удалось выдать доступ (остались в списке): ${failures.join('; ')}`,
emailLabel: 'Сотрудник',
emailPlaceholder: 'Найдите по ФИО или email',
validationRequestType: 'Выберите тип заявки.',
validationEmail: 'Выберите хотя бы одного сотрудника.',
validationEmail: 'Выберите сотрудника.',
deleteTitle: 'Отозвать доступ?',
deleteText: (email: string, requestTypeName: string): string =>
`${email} больше не будет видеть все заявки типа «${requestTypeName}».`