diff --git a/README.md b/README.md index 78ced88..542c816 100644 --- a/README.md +++ b/README.md @@ -28,3 +28,12 @@ Перед отправкой issue или pull request ознакомьтесь с [руководством по участию](https://github.com/PilotOpenTools/.github/blob/main/CONTRIBUTING.md) и [Кодексом поведения](https://github.com/PilotOpenTools/.github/blob/main/CODE_OF_CONDUCT.md). Сборка и отладка: [docs/development.md](docs/development.md). Выпуск релиза: [docs/releasing.md](docs/releasing.md). + + +### Сервер и права пользователя + +Имя сервера указано в верхнем меню PilotLookUp. + +В режиме просмотра объекта выберите объект слева и нажмите значок пользователя со щитом в левой панели («Права пользователя на объект»). Откроется окно PilotLookUp. Введите часть ФИО или логина и выберите сотрудника из списка. Pilot рассчитает его действующие права на выбранный объект с учётом наследования и групп. Команда также доступна из контекстного меню объекта. + +Под итоговыми правами видны действующие разрешения и запреты для должностей, подразделений и групп пользователя. У каждой записи указано, назначена ли она на выбранном объекте или откуда унаследована. У администратора базы окно показывает его роль как основание доступа. diff --git a/docs/development.md b/docs/development.md index de4c6ec..e5d9a8c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -4,7 +4,7 @@ - Windows: проект собирается под `net48` с WPF (`UseWPF`). - .NET SDK 10.0.x: такая версия стоит в [CI](../.github/workflows/ci.yml) и в [release.yml](../.github/workflows/release.yml). Язык C# 10 (`LangVersion`). -- NuGet-пакеты подтягиваются при сборке: `Ascon.Pilot.SDK` и `Ascon.Pilot.Bim.SDK` 26.15.0, `SimpleInjector`, `Svg`, `Microsoft.Xaml.Behaviors.Wpf`, `System.Composition`, `Microsoft.CSharp`. +- NuGet-пакеты подтягиваются при сборке: `Ascon.Pilot.SDK` и `Ascon.Pilot.Bim.SDK` 26.13.0, `SimpleInjector`, `Svg`, `Microsoft.Xaml.Behaviors.Wpf`, `System.Composition`, `Microsoft.CSharp`. - Для отладки: установленный клиент Pilot-BIM или Pilot-ICE Enterprise. ## Структура diff --git a/src/App.cs b/src/App.cs index 9c8d27d..790db8f 100644 --- a/src/App.cs +++ b/src/App.cs @@ -55,6 +55,8 @@ public class App : IMenu, private readonly IMenuCommandHandler _menuHandler; private readonly ISelectedService _selectedService; + private readonly IViewFactory _viewFactory; + private readonly IClientInfo _clientInfo; [ImportingConstructor] public App(IObjectsRepository objectsRepository, @@ -64,9 +66,11 @@ public App(IObjectsRepository objectsRepository, IFileProvider fileProvider, // Поисковый сервис клиент экспортирует через MEF (не через IPilotServiceProvider); // AllowDefault: без него плагин загрузится, расширенный поиск скроется - [Import(AllowDefault = true)] ISearchService searchService) + [Import(AllowDefault = true)] ISearchService searchService, + [Import(AllowDefault = true)] IClientInfo clientInfo) { AppDomain.CurrentDomain.AssemblyResolve += Resolver.ResolveAssembly; + _clientInfo = clientInfo; // BIM-сервисы есть только в Pilot-BIM; в Pilot-ICE вернется пусто - // BIM-функции мягко отключаются (IBimModelService.IsAvailable == false) @@ -80,9 +84,11 @@ public App(IObjectsRepository objectsRepository, fileProvider, searchService, modelManager, - modelStorageProvider); + modelStorageProvider, + clientInfo); _menuHandler = container.GetInstance(); + _viewFactory = container.GetInstance(); _selectedService = container.GetInstance(); serviceProvider.Register>( @@ -109,8 +115,19 @@ private void BuildModelContextMenu(IMenuBuilder builder, ModelContext context) } // ===== Меню ===== - public void Build(IMenuBuilder builder, MainViewContext context) => _menuHandler.BuildMainMenu(builder); - public void Build(IMenuBuilder builder, ObjectsViewContext context) => BuildContextMenu(builder, context); + public void Build(IMenuBuilder builder, MainViewContext context) => _menuHandler.BuildMainMenu(builder, GetServerName()); + public void Build(IMenuBuilder builder, ObjectsViewContext context) + { + BuildContextMenu(builder, context); + if (context.SelectedObjects?.Count() == 1) + builder.AddItem("PilotUserAccess", 1).WithHeader("Права пользователя на объект"); + } + + private string GetServerName() + { + var uri = _clientInfo?.ConnectionString; + return uri != null && uri.IsAbsoluteUri ? uri.Host : null; + } public void Build(IMenuBuilder builder, StorageContext context) => BuildContextMenu(builder, context); public void Build(IMenuBuilder builder, TasksViewContext2 context) => BuildContextMenu(builder, context); public void Build(IMenuBuilder builder, DocumentFilesContext context) => BuildContextMenu(builder, context); @@ -120,7 +137,17 @@ private void BuildModelContextMenu(IMenuBuilder builder, ModelContext context) public void Build(IMenuBuilder builder, SignatureRequestsContext context) => BuildContextMenu(builder, context); public void OnMenuItemClick(string name, MainViewContext context) => _menuHandler.ItemClick(name); - public void OnMenuItemClick(string name, ObjectsViewContext context) => _menuHandler.ItemClick(name); + public void OnMenuItemClick(string name, ObjectsViewContext context) + { + if (name == "PilotUserAccess") + { + var objects = context.SelectedObjects?.ToList(); + if (objects?.Count == 1) + _viewFactory.ShowUserAccess(objects[0]); + return; + } + _menuHandler.ItemClick(name); + } public void OnMenuItemClick(string name, StorageContext context) => _menuHandler.ItemClick(name); public void OnMenuItemClick(string name, TasksViewContext2 context) => _menuHandler.ItemClick(name); public void OnMenuItemClick(string name, DocumentFilesContext context) => _menuHandler.ItemClick(name); diff --git a/src/Interfaces/IMenuCommandHandler.cs b/src/Interfaces/IMenuCommandHandler.cs index 16f1c3a..262a658 100644 --- a/src/Interfaces/IMenuCommandHandler.cs +++ b/src/Interfaces/IMenuCommandHandler.cs @@ -6,7 +6,7 @@ namespace PilotLookUp.Interfaces // App только делегирует сюда вызовы из MEF-интерфейсов public interface IMenuCommandHandler { - void BuildMainMenu(IMenuBuilder builder); + void BuildMainMenu(IMenuBuilder builder, string serverName); void BuildLookSelectedItem(IMenuBuilder builder); void ItemClick(string name); } diff --git a/src/Interfaces/IViewFactory.cs b/src/Interfaces/IViewFactory.cs index 9eda114..5bb2739 100644 --- a/src/Interfaces/IViewFactory.cs +++ b/src/Interfaces/IViewFactory.cs @@ -1,10 +1,11 @@ -using PilotLookUp.Objects; +using PilotLookUp.Objects; namespace PilotLookUp.Interfaces { public interface IViewFactory { void LookSelection(ObjectSet selected); + void ShowUserAccess(Ascon.Pilot.SDK.IDataObject selected); void LookDB(); void SearchPage(); void EventMonitor(); diff --git a/src/Model/Factories/ViewFactory.cs b/src/Model/Factories/ViewFactory.cs index e591564..982a6b9 100644 --- a/src/Model/Factories/ViewFactory.cs +++ b/src/Model/Factories/ViewFactory.cs @@ -1,4 +1,8 @@ -using PilotLookUp.Contracts; +using Ascon.Pilot.SDK; +using PilotLookUp.Contracts; +using PilotLookUp.Model.Services; +using System.Linq; +using System.Windows; using PilotLookUp.Enums; using PilotLookUp.Interfaces; using PilotLookUp.Objects; @@ -10,9 +14,12 @@ public class ViewFactory : IViewFactory { private readonly IViewModelFactory _viewModelFactory; - public ViewFactory( IViewModelFactory viewModelFactory) + private readonly IObjectsRepository _repository; + + public ViewFactory(IViewModelFactory viewModelFactory, IObjectsRepository repository) { _viewModelFactory = viewModelFactory; + _repository = repository; } public void LookSelection(ObjectSet selected) @@ -22,6 +29,17 @@ public void LookSelection(ObjectSet selected) Show(startInfo); } + public void ShowUserAccess(Ascon.Pilot.SDK.IDataObject selected) + { + var id = selected.Id; + var window = new UserAccessWindow(selected.DisplayName, id, + () => _repository.GetPeople().Where(p => !p.IsDeleted) + .Select(p => new AccessPerson(p.Id, p.DisplayName, p.Login)).ToArray(), + personId => AccessExplanation.DescribeAsync(_repository, selected, personId)); + window.Owner = Application.Current?.Windows.OfType().FirstOrDefault(w => w.IsActive); + window.ShowDialog(); + } + public void LookDB() { var startInfo = new StartViewInfo { PageName = PagesName.DBPage }; diff --git a/src/Model/Factories/ViewModelFactory.cs b/src/Model/Factories/ViewModelFactory.cs index 11744a4..89b1280 100644 --- a/src/Model/Factories/ViewModelFactory.cs +++ b/src/Model/Factories/ViewModelFactory.cs @@ -18,6 +18,7 @@ public class ViewModelFactory : IViewModelFactory private readonly IObjectsRepository _objectsRepository; private readonly IClientEventService _clientEventService; private readonly IAdvancedSearchService _advancedSearchService; + private readonly ServerIdentity _serverIdentity; // Lazy разрывает циклы: ViewFactory/TreeItemService/PageServiceFactory // сами зависят от IViewModelFactory @@ -34,6 +35,7 @@ public ViewModelFactory( IObjectsRepository objectsRepository, IClientEventService clientEventService, IAdvancedSearchService advancedSearchService, + ServerIdentity serverIdentity, Lazy viewFactory, Lazy treeItemService, Lazy pageServiceFactory) @@ -46,6 +48,7 @@ public ViewModelFactory( _objectsRepository = objectsRepository; _clientEventService = clientEventService; _advancedSearchService = advancedSearchService; + _serverIdentity = serverIdentity; _viewFactory = viewFactory; _treeItemService = treeItemService; _pageServiceFactory = pageServiceFactory; @@ -54,7 +57,7 @@ public ViewModelFactory( public MainVM CreateMainVM(StartViewInfo startInfo) { var pageService = _pageServiceFactory.Value.CreatePageService(startInfo); - return new MainVM(pageService); + return new MainVM(pageService, _serverIdentity); } public LookUpVM CreateLookUpVM() diff --git a/src/Model/ServerIdentity.cs b/src/Model/ServerIdentity.cs new file mode 100644 index 0000000..84de7d4 --- /dev/null +++ b/src/Model/ServerIdentity.cs @@ -0,0 +1,20 @@ +using Ascon.Pilot.SDK; + +namespace PilotLookUp.Model +{ + public sealed class ServerIdentity + { + private readonly IClientInfo _clientInfo; + public ServerIdentity(IClientInfo clientInfo) => _clientInfo = clientInfo; + + public string Name + { + get + { + var uri = _clientInfo?.ConnectionString; + return uri != null && uri.IsAbsoluteUri && !string.IsNullOrWhiteSpace(uri.Host) + ? uri.Host : "не определён"; + } + } + } +} diff --git a/src/Model/ServiceContainer.cs b/src/Model/ServiceContainer.cs index c8790e1..d4f319f 100644 --- a/src/Model/ServiceContainer.cs +++ b/src/Model/ServiceContainer.cs @@ -20,7 +20,8 @@ public Container CreateContainer(IObjectsRepository objectsRepository, IFileProvider fileProvider, ISearchService searchService = null, IModelManager modelManager = null, - IModelStorageProvider modelStorageProvider = null) + IModelStorageProvider modelStorageProvider = null, + IClientInfo clientInfo = null) { _container = new Container(); @@ -29,6 +30,8 @@ public Container CreateContainer(IObjectsRepository objectsRepository, _container.RegisterInstance(pilotDialogService); _container.RegisterInstance(fileProvider); + _container.RegisterInstance(new ServerIdentity(clientInfo)); + RegisterServices(_container); RegisterFactories(_container); diff --git a/src/Model/Services/AccessExplanation.cs b/src/Model/Services/AccessExplanation.cs new file mode 100644 index 0000000..df74ab1 --- /dev/null +++ b/src/Model/Services/AccessExplanation.cs @@ -0,0 +1,142 @@ +using Ascon.Pilot.SDK; +using PilotLookUp.Extensions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace PilotLookUp.Model.Services +{ + internal static class AccessExplanation + { + public static async Task DescribeAsync(IObjectsRepository repository, IDataObject selected, int personId) + { + var id = selected.Id; + var effective = repository.GetCurrentAccess(id, personId); + var result = FormatAccess(effective, Environment.NewLine); + try + { + var person = repository.GetPerson(personId); + if (person.IsAdmin) + return result + "\n\nОснование — администратор базы Pilot."; + + var current = selected; + var state = current.ObjectStateInfo?.State; + if (state == ObjectState.InRecycleBin || state == ObjectState.DeletedPermanently) + return result + "\n\nДоступ определён правилами Pilot для удалённого объекта."; + if (state == ObjectState.Frozen) + result += "\n\nОбъект заморожен. Pilot ограничивает действующие права."; + + var units = new HashSet(person.AllOrgUnits()); + var now = DateTime.UtcNow; + var typeId = current.Type.Id; + var records = new List<(IAccessRecord Record, Guid ObjectId, string ObjectName, bool Inherited)>(); + var visited = new HashSet(); + var cursor = current; + var blockedBySecret = false; + string missing = null; + while (cursor != null && visited.Add(cursor.Id)) + { + bool inherited = cursor.Id != id; + foreach (var record in cursor.Access2 ?? Enumerable.Empty()) + { + var access = record.Access; + if (!units.Contains(record.OrgUnitId) || access.ValidThrough < now || + (access.TypeIds != null && access.TypeIds.Length > 0 && !access.TypeIds.Contains(typeId))) + continue; + if (inherited && (!access.IsInheritable || + (blockedBySecret && access.Inheritance != AccessInheritance.InheritWholeSubtree))) + continue; + // Некоторые реализации возвращают уже унаследованные записи в Access2. + // Источник у них хранится в InheritanceSource. + var sourceId = record.Access.IsInherited && record.InheritanceSource != Guid.Empty + ? record.InheritanceSource : cursor.Id; + var sourceName = sourceId == cursor.Id ? cursor.DisplayName : null; + records.Add((record, sourceId, sourceName, sourceId != id)); + } + + blockedBySecret |= cursor.IsSecret; + var parentId = cursor.ParentId; + if (parentId == Guid.Empty || parentId == cursor.Id) break; + if (visited.Contains(parentId)) + { + missing = "Обнаружен цикл в цепочке родителей."; + break; + } + IDataObject parent; + try + { + parent = await repository.GetObjectWithTimeout(parentId); + } + catch (Exception) + { + parent = null; + } + if (parent == null || parent.State != DataState.Loaded) + { + missing = $"Не удалось загрузить родительский объект {parentId}. Список оснований может быть неполным."; + break; + } + cursor = parent; + } + + if (records.Count == 0) + return result + "\n\nВ доступных записях объекта нет действующих назначений для пользователя." + + (missing == null ? "" : "\n" + missing); + + records = records.GroupBy(entry => new + { + entry.ObjectId, entry.Record.OrgUnitId, entry.Record.Access.Type, + entry.Record.Access.AccessLevel, entry.Record.Access.ValidThrough, + entry.Record.Access.Inheritance, + Types = string.Join(",", (entry.Record.Access.TypeIds ?? Array.Empty()).OrderBy(x => x)) + }).Select(group => group.OrderByDescending(entry => entry.ObjectName != null).First()).ToList(); + + var recipients = records.Select(r => r.Record.OrgUnitId).Distinct() + .ToDictionary(unitId => unitId, unitId => UnitName(repository, unitId)); + var rows = records.Select(entry => + { + var r = entry.Record; + var location = entry.Inherited + ? $"Унаследовано от «{entry.ObjectName ?? "имя недоступно"}» ({entry.ObjectId})" + : "На этом объекте"; + var kind = r.Access.Type == AccessType.Deny ? "Запрет" : "Разрешение"; + return $"{location}\n{recipients[r.OrgUnitId]} · {kind}: {FormatAccess(r.Access.AccessLevel, ", ")}"; + }); + if (missing != null) result += "\n\n" + missing; + return result + "\n\nНазначения прав\n\n" + string.Join("\n\n", rows); + } + catch (Exception ex) + { + return result + "\n\nНе удалось прочитать основания доступа. " + ex.Message; + } + } + + private static string UnitName(IObjectsRepository repository, int id) + { + var unit = repository.GetOrganisationUnit(id); + if (unit == null) return $"Оргединица #{id}"; + var kind = unit.Kind() switch + { + OrganizationUnitKind.Group => "Группа", + OrganizationUnitKind.Position => "Должность", + _ => "Подразделение" + }; + return $"{kind} «{unit.Title}» (#{id})"; + } + + private static string FormatAccess(AccessLevel access, string separator) + { + if (access == AccessLevel.None) return "Нет прав на объект."; + var actions = new (AccessLevel Flag, string Title)[] + { + (AccessLevel.View, "Просмотр"), (AccessLevel.Create, "Создание"), + (AccessLevel.EditAttributes, "Изменение атрибутов"), (AccessLevel.EditFiles, "Изменение файлов"), + (AccessLevel.Delete, "Удаление"), (AccessLevel.Agreement, "Согласование"), + (AccessLevel.Freeze, "Замораживание"), (AccessLevel.Share, "Делегирование прав") + }; + var labels = actions.Where(a => access.HasFlag(a.Flag)).Select(a => a.Title); + return string.Join(separator, labels); + } + } +} diff --git a/src/Model/Services/DisplaySettings.cs b/src/Model/Services/DisplaySettings.cs new file mode 100644 index 0000000..8d9dcd9 --- /dev/null +++ b/src/Model/Services/DisplaySettings.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using System.Xml.Linq; + +namespace PilotLookUp.Model.Services +{ + internal static class DisplaySettings + { + private static readonly string SettingsPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "PilotLookUp", "settings.xml"); + + public static bool ShowServerName + { + get + { + try + { + if (!File.Exists(SettingsPath)) return true; + return (bool?)XDocument.Load(SettingsPath).Root?.Element("ShowServerName") ?? true; + } + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || + ex is System.Xml.XmlException || ex is FormatException) + { + return true; + } + } + } + + public static void Save(bool showServerName) + { + Directory.CreateDirectory(Path.GetDirectoryName(SettingsPath)); + var document = new XDocument(new XElement("PilotLookUp", + new XElement("ShowServerName", showServerName))); + document.Save(SettingsPath); + } + } +} diff --git a/src/Model/Services/MenuCommandHandler.cs b/src/Model/Services/MenuCommandHandler.cs index 77982ee..a2d7433 100644 --- a/src/Model/Services/MenuCommandHandler.cs +++ b/src/Model/Services/MenuCommandHandler.cs @@ -2,6 +2,7 @@ using PilotLookUp.Interfaces; using PilotLookUp.Objects; using System.Linq; +using PilotLookUp.View; namespace PilotLookUp.Model.Services { @@ -21,13 +22,15 @@ public MenuCommandHandler( _clientEventService = clientEventService; } - public void BuildMainMenu(IMenuBuilder builder) + public void BuildMainMenu(IMenuBuilder builder, string serverName) { - var item = builder.AddItem("PilotLookUp", 1).WithHeader("PilotLookUp"); + var header = !DisplaySettings.ShowServerName || string.IsNullOrWhiteSpace(serverName) ? "PilotLookUp" : $"PilotLookUp · {serverName}"; + var item = builder.AddItem("PilotLookUp", 1).WithHeader(header); item.WithSubmenu().AddItem("LookSelected", 0).WithHeader("LookSelected"); item.WithSubmenu().AddItem("LookDB", 1).WithHeader("LookDB"); item.WithSubmenu().AddItem("Search", 2).WithHeader("Search"); item.WithSubmenu().AddItem("EventMonitor", 3).WithHeader("EventMonitor"); + item.WithSubmenu().AddItem("PilotSettings", 4).WithHeader("Настройки…"); } public void BuildLookSelectedItem(IMenuBuilder builder) @@ -41,6 +44,9 @@ public void ItemClick(string name) switch (name) { + case "PilotSettings": + new SettingsWindow().ShowDialog(); + return; case "LookDB": _viewFactory.LookDB(); return; diff --git a/src/PilotLookUp.csproj b/src/PilotLookUp.csproj index 6694659..0ff25f8 100644 --- a/src/PilotLookUp.csproj +++ b/src/PilotLookUp.csproj @@ -1,4 +1,4 @@ - + Library @@ -8,7 +8,7 @@ PilotLookUp PilotLookUp PilotLookUp - 2.8.1.0 + 2.8.1.6 PilotLookUp Library @@ -105,8 +105,8 @@ - - + + diff --git a/src/View/MainView.xaml b/src/View/MainView.xaml index d7d8ede..61481b4 100644 --- a/src/View/MainView.xaml +++ b/src/View/MainView.xaml @@ -1,4 +1,4 @@ - + + + + + + + + + + + + + @@ -38,7 +51,7 @@