Skip to content
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 рассчитает его действующие права на выбранный объект с учётом наследования и групп. Команда также доступна из контекстного меню объекта.

Под итоговыми правами видны действующие разрешения и запреты для должностей, подразделений и групп пользователя. У каждой записи указано, назначена ли она на выбранном объекте или откуда унаследована. У администратора базы окно показывает его роль как основание доступа.
2 changes: 1 addition & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

## Структура
Expand Down
37 changes: 32 additions & 5 deletions src/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public class App : IMenu<MainViewContext>,

private readonly IMenuCommandHandler _menuHandler;
private readonly ISelectedService _selectedService;
private readonly IViewFactory _viewFactory;
private readonly IClientInfo _clientInfo;

[ImportingConstructor]
public App(IObjectsRepository objectsRepository,
Expand All @@ -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)
Expand All @@ -80,9 +84,11 @@ public App(IObjectsRepository objectsRepository,
fileProvider,
searchService,
modelManager,
modelStorageProvider);
modelStorageProvider,
clientInfo);

_menuHandler = container.GetInstance<IMenuCommandHandler>();
_viewFactory = container.GetInstance<IViewFactory>();
_selectedService = container.GetInstance<ISelectedService>();

serviceProvider.Register<IMenu<ModelContext>>(
Expand All @@ -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);
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/Interfaces/IMenuCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
3 changes: 2 additions & 1 deletion src/Interfaces/IViewFactory.cs
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
22 changes: 20 additions & 2 deletions src/Model/Factories/ViewFactory.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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)
Expand All @@ -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<Window>().FirstOrDefault(w => w.IsActive);
window.ShowDialog();
}

public void LookDB()
{
var startInfo = new StartViewInfo { PageName = PagesName.DBPage };
Expand Down
5 changes: 4 additions & 1 deletion src/Model/Factories/ViewModelFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -34,6 +35,7 @@ public ViewModelFactory(
IObjectsRepository objectsRepository,
IClientEventService clientEventService,
IAdvancedSearchService advancedSearchService,
ServerIdentity serverIdentity,
Lazy<IViewFactory> viewFactory,
Lazy<ITreeItemService> treeItemService,
Lazy<IPageServiceFactory> pageServiceFactory)
Expand All @@ -46,6 +48,7 @@ public ViewModelFactory(
_objectsRepository = objectsRepository;
_clientEventService = clientEventService;
_advancedSearchService = advancedSearchService;
_serverIdentity = serverIdentity;
_viewFactory = viewFactory;
_treeItemService = treeItemService;
_pageServiceFactory = pageServiceFactory;
Expand All @@ -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()
Expand Down
20 changes: 20 additions & 0 deletions src/Model/ServerIdentity.cs
Original file line number Diff line number Diff line change
@@ -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 : "не определён";
}
}
}
}
5 changes: 4 additions & 1 deletion src/Model/ServiceContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -29,6 +30,8 @@ public Container CreateContainer(IObjectsRepository objectsRepository,
_container.RegisterInstance(pilotDialogService);
_container.RegisterInstance(fileProvider);

_container.RegisterInstance(new ServerIdentity(clientInfo));

RegisterServices(_container);
RegisterFactories(_container);

Expand Down
142 changes: 142 additions & 0 deletions src/Model/Services/AccessExplanation.cs
Original file line number Diff line number Diff line change
@@ -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<string> 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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Обновляйте объект перед чтением локальных назначений. Итоговые права запрашиваются при выборе сотрудника, а локальные назначения берутся из объекта, переданного при открытии окна. Если администратор отзовёт разрешение, пока окно открыто, итог может уже учитывать отзыв, а список всё ещё покажет старое разрешение. Загружайте актуальный объект перед построением списка оснований.

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<int>(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<Guid>();
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<IAccessRecord>())
{
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<int>()).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, "Согласование"),

Check warning on line 135 in src/Model/Services/AccessExplanation.cs

View workflow job for this annotation

GitHub Actions / build

'AccessLevel.Agreement' is obsolete: 'Use the Approve flag instead'
Comment on lines +134 to +135

@mahach666 mahach666 Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проверьте расширение на актуальном Pilot SDK. PR меняет Ascon.Pilot.SDK и Ascon.Pilot.Bim.SDK с 26.15.0 в master на 26.13.0. Я собрал этот коммит с последней стабильной версией обоих пакетов, 26.23.0. Release-сборка прошла. Форматтер корректно показывает EditAttributes, EditFiles и Delete отдельно и все три права для составного Edit. Предлагаю использовать 26.23.0 и проверить загрузку расширения и расчёт прав в клиенте Pilot этой версии.

Если требуется поддержка клиентов с SDK 26.15, это отдельная проверка совместимости. В 26.15 единый Edit отображается в текущем форматтере как «Изменение атрибутов».

(AccessLevel.Freeze, "Замораживание"), (AccessLevel.Share, "Делегирование прав")
};
var labels = actions.Where(a => access.HasFlag(a.Flag)).Select(a => a.Title);
return string.Join(separator, labels);
}
}
}
Loading
Loading