From 9b93097ae404bbf88f7ac968f9b446de628f4fde Mon Sep 17 00:00:00 2001 From: Hamza Alqurneh Date: Wed, 25 Nov 2026 15:56:58 +0300 Subject: [PATCH 1/2] feat: partner portal inside the app frame, with the real Exchanges page and retry --- .../Resources/Portal/ExchangeViews.cs | 135 ++++++ SW.Bitween.Api/Resources/Portal/Retry.cs | 69 +++ .../Resources/Portal/Subscriptions.cs | 63 ++- SW.Bitween.Api/Resources/Portal/Summary.cs | 49 --- SW.Bitween.Api/Resources/Portal/Xchanges.cs | 141 ------ .../Resources/Xchanges/RetryTree.cs | 10 +- SW.Bitween.Api/Resources/Xchanges/Search.cs | 56 ++- SW.Bitween.Api/Resources/Xchanges/Summary.cs | 20 +- .../Resources/Xchanges/XchangeFilters.cs | 8 +- .../Tests/PartnerPortalTests.cs | 25 +- .../Tests/PortalExchangeViewsTests.cs | 134 ++++++ .../Tests/PortalRetryTests.cs | 100 +++++ SW.Bitween.Sdk/Model/Permissions.cs | 4 +- SW.Bitween.Sdk/Model/Portal.cs | 69 +-- SW.Bitween.Web/ClientApp/src/api/client.ts | 20 +- .../ClientApp/src/api/http/exchanges.ts | 54 ++- .../ClientApp/src/api/http/portal.ts | 29 +- SW.Bitween.Web/ClientApp/src/api/queryKeys.ts | 1 + SW.Bitween.Web/ClientApp/src/api/types.ts | 45 -- SW.Bitween.Web/ClientApp/src/auth/guards.tsx | 5 +- .../src/components/layout/AppShell.tsx | 31 +- .../src/components/layout/CommandPalette.tsx | 9 +- SW.Bitween.Web/ClientApp/src/nav.ts | 17 +- SW.Bitween.Web/ClientApp/src/pages.ts | 54 ++- .../pages/exchanges/ExchangeDetailPanel.tsx | 14 +- .../src/pages/exchanges/ExchangeDrawer.tsx | 41 +- .../src/pages/exchanges/ExchangeList.tsx | 17 +- .../src/pages/exchanges/ExchangesPage.tsx | 75 +++- .../src/pages/exchanges/QueryBar.tsx | 14 +- .../src/pages/exchanges/RetryChain.tsx | 8 +- .../src/pages/exchanges/exchangeSource.tsx | 105 +++++ .../src/pages/exchanges/retryTree.ts | 9 +- .../ClientApp/src/pages/exchanges/shared.tsx | 5 +- .../src/pages/portal/PortalDetailsPage.tsx | 12 + .../src/pages/portal/PortalExchangesPage.tsx | 14 + .../src/pages/portal/PortalMappingPage.tsx | 22 +- .../src/pages/portal/PortalMappingsPage.tsx | 72 ++++ .../ClientApp/src/pages/portal/PortalPage.tsx | 401 ------------------ .../src/pages/portal/PortalPeoplePage.tsx | 22 +- .../pages/portal/PortalSubscriptionsPage.tsx | 45 ++ .../src/pages/portal/YourDetails.tsx | 8 +- .../portal/__tests__/PortalFrame.test.tsx | 129 ++++++ .../portal/__tests__/PortalPage.test.tsx | 105 ----- .../portal/__tests__/PortalPeople.test.tsx | 9 +- .../portal/__tests__/YourDetails.test.tsx | 6 +- .../ClientApp/src/pages/team/RoleEditor.tsx | 15 +- SW.Bitween.Web/ClientApp/src/routePages.tsx | 7 +- SW.Bitween.Web/ClientApp/src/router.tsx | 63 +-- docs/security.md | 5 +- 49 files changed, 1314 insertions(+), 1057 deletions(-) create mode 100644 SW.Bitween.Api/Resources/Portal/ExchangeViews.cs create mode 100644 SW.Bitween.Api/Resources/Portal/Retry.cs delete mode 100644 SW.Bitween.Api/Resources/Portal/Summary.cs delete mode 100644 SW.Bitween.Api/Resources/Portal/Xchanges.cs create mode 100644 SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs create mode 100644 SW.Bitween.IntegrationTests/Tests/PortalRetryTests.cs create mode 100644 SW.Bitween.Web/ClientApp/src/pages/exchanges/exchangeSource.tsx create mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/PortalDetailsPage.tsx create mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/PortalExchangesPage.tsx create mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingsPage.tsx delete mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/PortalPage.tsx create mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/PortalSubscriptionsPage.tsx create mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx delete mode 100644 SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPage.test.tsx diff --git a/SW.Bitween.Api/Resources/Portal/ExchangeViews.cs b/SW.Bitween.Api/Resources/Portal/ExchangeViews.cs new file mode 100644 index 00000000..5789e0ce --- /dev/null +++ b/SW.Bitween.Api/Resources/Portal/ExchangeViews.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using SW.Bitween.Domain; +using SW.Bitween.Model; +using SW.Bitween.Services; +using SW.PrimitiveTypes; + +namespace SW.Bitween.Resources.Portal; + +/// +/// What the partner portal's Exchanges page reads: our team's own search, counts and retry chain, +/// limited to the caller's partner and without what is ours to know. The same rows, so the same page +/// shows them. +/// +internal static class PortalExchangeViews +{ + /// + /// The filters and sorts the portal's page sends. Anything else is refused rather than ignored, so + /// a hand-made request can't sort or filter by a column they aren't shown, such as an error they may + /// not read, and learn it from the order or the count. + /// + private static readonly HashSet Filterable = new(StringComparer.Ordinal) + { + nameof(XchangeRow.StartedOn), nameof(XchangeRow.SubscriptionId), nameof(XchangeRow.DocumentId), + nameof(XchangeRow.CorrelationId), nameof(XchangeRow.PartnerId), "Id", "StatusFilter", "LatestOnly", + "IsRetry", "HasScheduledRetry", "PromotedPropertyKey", nameof(XchangeRow.PromotedPropertiesRaw), + "PromotedProperty" + }; + + private static readonly HashSet Sortable = new(StringComparer.Ordinal) + { + nameof(XchangeRow.StartedOn), nameof(XchangeRow.FinishedOn) + }; + + public static void EnsureAllowed(SearchyRequest request, PortalCaller caller) + { + var withErrors = caller.Can(Model.Permissions.Portal.ExchangeErrorsView); + foreach (var filter in request.Conditions.SelectMany(c => c.Filters)) + if (!Filterable.Contains(filter.Field) && !(withErrors && filter.Field == "ErrorContains")) + throw new SWValidationException("FILTER_NOT_ALLOWED", $"The exchanges can't be filtered by {filter.Field}."); + foreach (var sort in request.Sorts ?? []) + if (!Sortable.Contains(sort.Field)) + throw new SWValidationException("SORT_NOT_ALLOWED", $"The exchanges can't be sorted by {sort.Field}."); + } + + /// Takes out of a row what is ours to know, and what their role doesn't show. + public static XchangeRow Strip(XchangeRow row, PortalCaller caller) + { + // How their exchange was wired, on our side: which adapters ran, what fed it, where it was rolled up. + row.HandlerId = null; + // Whether one mapped it is theirs to see (the page shows a skipped stage); which adapter isn't. + row.MapperId = row.MapperId is null ? null : "mapper"; + row.References = null; + row.SourceXchangeId = null; + row.SourceValues = null; + row.AggregationXchangeId = null; + row.AggregatedOn = null; + row.RetryBlockedReason = null; + row.Warning = null; + // Where storage keeps the files; the links below are what they open them with. + row.InputKey = null; + row.OutputKey = null; + row.ResponseKey = null; + row.InputFileHash = null; + + if (!caller.Can(Model.Permissions.Portal.ExchangeErrorsView)) + row.Exception = null; + if (!caller.Can(Model.Permissions.Portal.ExchangeFilesView)) + { + row.InputUrl = row.OutputUrl = row.ResponseUrl = null; + row.InputFileName = row.OutputFileName = row.ResponseFileName = null; + row.InputFileSize = row.OutputFileSize = row.ResponseFileSize = 0; + } + return row; + } +} + +/// Their exchanges, as our team's list shows exchanges: the same filters, rows and paging. +[HandlerName("xchangesearch")] +public class SearchExchanges(BitweenDbContext dbContext, RequestContext requestContext, XchangeService xchangeService) + : ISearchyHandler +{ + public async Task Handle(SearchyRequest searchyRequest, bool lookup = false, string searchPhrase = null) + { + var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesView); + PortalExchangeViews.EnsureAllowed(searchyRequest, caller); + var found = await new SW.Bitween.Resources.Xchanges.Search(dbContext, xchangeService, requestContext) + .SearchAsync(searchyRequest, caller.PartnerId); + foreach (var row in found.Result) + PortalExchangeViews.Strip(row, caller); + return found; + } +} + +/// How many of their exchanges a filter matches, by status: the counts on their Exchanges page. +[HandlerName("xchangesummary")] +public class CountExchanges(BitweenDbContext dbContext, RequestContext requestContext, SlowCounts slowCounts) + : ISearchyHandler +{ + public async Task Handle(SearchyRequest searchyRequest, bool lookup = false, string searchPhrase = null) + { + var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesView); + PortalExchangeViews.EnsureAllowed(searchyRequest, caller); + return await new SW.Bitween.Resources.Xchanges.Summary(dbContext, requestContext, slowCounts).SummarizeAsync(searchyRequest, caller.PartnerId); + } +} + +/// The attempts of one of their exchanges, as our team's retry chain shows them. +[HandlerName("retrytree")] +public class ExchangeAttempts(BitweenDbContext dbContext, RequestContext requestContext) + : IQueryHandler +{ + public async Task Handle(XchangeRetryTreeRequest request) + { + var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesView); + // Someone else's exchange is simply not there for them. + if (!await dbContext.Set().AnyAsync(x => x.Id == request.Id && x.PartnerId == caller.PartnerId)) + throw new SWNotFoundException(request.Id); + + var tree = await new SW.Bitween.Resources.Xchanges.RetryTree(dbContext, requestContext).TreeAsync(request, caller.PartnerId); + var withErrors = caller.Can(Model.Permissions.Portal.ExchangeErrorsView); + foreach (var node in tree.Nodes) + { + node.RetryBlockedReason = null; + if (!withErrors) node.Exception = null; + } + // An original that wasn't theirs is left out, so the chain starts at their first attempt. + if (tree.Nodes.All(n => n.Id != tree.RootId) && tree.Nodes.Count > 0) + tree.RootId = tree.Nodes[0].Id; + return tree; + } +} diff --git a/SW.Bitween.Api/Resources/Portal/Retry.cs b/SW.Bitween.Api/Resources/Portal/Retry.cs new file mode 100644 index 00000000..d44bbd9a --- /dev/null +++ b/SW.Bitween.Api/Resources/Portal/Retry.cs @@ -0,0 +1,69 @@ +using System.Linq; +using System.Threading.Tasks; +using FluentValidation; +using Microsoft.EntityFrameworkCore; +using SW.Bitween.Domain; +using SW.Bitween.Model; +using SW.PrimitiveTypes; + +namespace SW.Bitween.Resources.Portal; + +/// +/// Retries one of their failed exchanges with the subscription's current settings, so a mapping or +/// detail they just fixed is used. Only the latest attempt, as our team's retry, and not while a +/// retry policy has one scheduled. +/// +[HandlerName("retry")] +public class Retry(BitweenDbContext dbContext, RequestContext requestContext, XchangeService xchangeService) + : ICommandHandler +{ + public async Task Handle(PortalRetry request) + { + var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesOperate); + // Someone else's exchange is simply not there for them. + var xchange = await dbContext.Set() + .SingleOrDefaultAsync(x => x.Id == request.XchangeId && x.PartnerId == caller.PartnerId) + ?? throw new SWNotFoundException(request.XchangeId); + + var result = await dbContext.Set().AsNoTracking().SingleOrDefaultAsync(r => r.Id == xchange.Id); + if (result is null || result.Success) + throw new SWValidationException("NOT_FAILED", "Only a failed exchange can be retried."); + if (await dbContext.Set().AnyAsync(d => d.Id == xchange.Id)) + throw new SWValidationException("AUTO_RETRY_SCHEDULED", + "This exchange is already scheduled to be tried again. It runs on its own shortly."); + if (await dbContext.Set().AnyAsync(c => c.Id == xchange.Id) || + await dbContext.Set().AnyAsync(x => x.RetryFor == xchange.Id)) + throw new SWValidationException("ALREADY_RETRIED", "This exchange was already retried. Retry its latest attempt instead."); + + var subscription = await dbContext.Subscriptions().FirstOrDefaultAsync(s => s.Id == xchange.SubscriptionId) + ?? throw new SWValidationException("SUBSCRIPTION_NOT_FOUND", + "This exchange can't be retried: what it ran for no longer exists."); + + var input = await xchangeService.GetFile(xchange, XchangeFileType.Input); + await xchangeService.CreateXchange(subscription, xchange, new XchangeFile(input, xchange.InputName), + manualRetry: true); + dbContext.Record(requestContext, OperatorAction.Retry, xchange.Id, "from the partner portal"); + try + { + await dbContext.SaveChangesAsync(); + } + catch (DbUpdateException) + { + // Another retry of the same exchange was saved a moment before this one. + if (await dbContext.Set().AsNoTracking().AnyAsync(c => c.Id == xchange.Id)) + throw new SWValidationException("ALREADY_RETRIED", + "This exchange was retried a moment ago. Retry its latest attempt instead."); + throw; + } + + // The claim the retry made names the exchange it made. + var retryId = await dbContext.Set().AsNoTracking() + .Where(c => c.Id == xchange.Id).Select(c => c.RetryXchangeId).SingleAsync(); + return new PortalRetried { XchangeId = retryId }; + } + + private class Validate : AbstractValidator + { + public Validate() => RuleFor(i => i.XchangeId).NotEmpty().MaximumLength(50); + } +} diff --git a/SW.Bitween.Api/Resources/Portal/Subscriptions.cs b/SW.Bitween.Api/Resources/Portal/Subscriptions.cs index da410802..bb9a9813 100644 --- a/SW.Bitween.Api/Resources/Portal/Subscriptions.cs +++ b/SW.Bitween.Api/Resources/Portal/Subscriptions.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -18,22 +19,7 @@ public class Subscriptions(BitweenDbContext dbContext, RequestContext requestCon public async Task Handle() { var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.SubscriptionsView); - var partnerId = caller.PartnerId; - - var owned = await dbContext.Set().AsNoTracking() - .Where(s => s.PartnerId == partnerId).Select(s => s.Id).ToListAsync(); - var viaGateways = await dbContext.Set().AsNoTracking() - .Where(g => g.PartnerId == partnerId).Select(g => g.SubscriptionId).ToListAsync(); - var viaRoutes = await dbContext.Set().AsNoTracking() - .Where(r => r.PartnerId == partnerId).Select(r => r.SubscriptionId).ToListAsync(); - - // A response subscription runs as the partner of the one that handed it the reply. - var reached = owned.Concat(viaGateways).Concat(viaRoutes).Distinct().ToList(); - var responses = await dbContext.Set().AsNoTracking() - .Where(s => reached.Contains(s.Id) && s.ResponseSubscriptionId != null) - .Select(s => s.ResponseSubscriptionId!.Value).ToListAsync(); - - var all = reached.Concat(responses).Distinct().ToList(); + var all = await IdsAsync(dbContext, caller.PartnerId); var rows = await (from s in dbContext.Set().AsNoTracking() join d in dbContext.Set() on s.DocumentId equals d.Id where all.Contains(s.Id) @@ -50,4 +36,49 @@ orderby s.Name return rows; } + + /// The ids of the subscriptions that run for a partner, as listed above. + internal static async Task> IdsAsync(BitweenDbContext dbContext, int partnerId) + { + var owned = await dbContext.Set().AsNoTracking() + .Where(s => s.PartnerId == partnerId).Select(s => s.Id).ToListAsync(); + var viaGateways = await dbContext.Set().AsNoTracking() + .Where(g => g.PartnerId == partnerId).Select(g => g.SubscriptionId).ToListAsync(); + var viaRoutes = await dbContext.Set().AsNoTracking() + .Where(r => r.PartnerId == partnerId).Select(r => r.SubscriptionId).ToListAsync(); + + // A response subscription runs as the partner of the one that handed it the reply. + var reached = owned.Concat(viaGateways).Concat(viaRoutes).Distinct().ToList(); + var responses = await dbContext.Set().AsNoTracking() + .Where(s => reached.Contains(s.Id) && s.ResponseSubscriptionId != null) + .Select(s => s.ResponseSubscriptionId!.Value).ToListAsync(); + + return reached.Concat(responses).Distinct().ToList(); + } +} + +/// +/// The information types of what runs for them, with the names of the values each promotes, for +/// their Exchanges page's filters. Not where in the document a value is read from: that is ours. +/// +[HandlerName("informationtypes")] +public class InformationTypes(BitweenDbContext dbContext, RequestContext requestContext) : IQueryHandler +{ + public async Task Handle() + { + var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesView); + var ids = await Subscriptions.IdsAsync(dbContext, caller.PartnerId); + // The ids first: told apart by id rather than by every column, some of which are JSON. + var documentIds = await dbContext.Set().AsNoTracking() + .Where(s => ids.Contains(s.Id)).Select(s => s.DocumentId).Distinct().ToListAsync(); + var documents = await dbContext.Set().AsNoTracking() + .Where(d => documentIds.Contains(d.Id)).ToListAsync(); + return documents.OrderBy(d => d.Name).Select(d => new PortalInformationType + { + Id = d.Id, + Name = d.Name, + Code = d.Code, + PromotedPropertyKeys = (d.PromotedProperties ?? new Dictionary()).Keys.ToList() + }).ToList(); + } } diff --git a/SW.Bitween.Api/Resources/Portal/Summary.cs b/SW.Bitween.Api/Resources/Portal/Summary.cs deleted file mode 100644 index d94cef5c..00000000 --- a/SW.Bitween.Api/Resources/Portal/Summary.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using SW.Bitween.Domain; -using SW.Bitween.Model; -using SW.PrimitiveTypes; - -namespace SW.Bitween.Resources.Portal; - -/// -/// The signed-in partner's name and their last 24 hours of exchanges by outcome. A day, not all -/// time, so it reads one day of the start-time index however long the history runs. -/// -[HandlerName("summary")] -public class Summary(BitweenDbContext dbContext, RequestContext requestContext) : IQueryHandler -{ - public async Task Handle() - { - var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesView); - var partnerId = caller.PartnerId; - var since = DateTime.UtcNow.AddDays(-1); - - var day = dbContext.Set().AsNoTracking().Where(x => x.PartnerId == partnerId && x.StartedOn >= since); - - // From the exchange's own status once it is filled in, with no join to the results: a busy - // partner's day took 100 ms that way on 2M exchanges, against 2 ms on the status. A bad - // response still delivered, so it counts as a success, as in the list. - var outcomes = await Services.XchangeStates.XchangeStateReadiness.IsReadyAsync(dbContext) - ? await day.GroupBy(x => x.Status == XchangeStatus.Processing ? 0 : x.Status == XchangeStatus.Failed ? 2 : 1) - .Select(g => new { Outcome = g.Key, Count = g.Count() }) - .ToListAsync() - : await (from x in day - join r in dbContext.Set() on x.Id equals r.Id into xr - from r in xr.DefaultIfEmpty() - group r by r == null ? 0 : r.Success ? 1 : 2 into g - select new { Outcome = g.Key, Count = g.Count() }) - .ToListAsync(); - - return new PortalSummary - { - PartnerName = await dbContext.Set().AsNoTracking() - .Where(p => p.Id == partnerId).Select(p => p.Name).SingleOrDefaultAsync() ?? "", - Running = outcomes.Where(o => o.Outcome == 0).Sum(o => o.Count), - Succeeded = outcomes.Where(o => o.Outcome == 1).Sum(o => o.Count), - Failed = outcomes.Where(o => o.Outcome == 2).Sum(o => o.Count) - }; - } -} diff --git a/SW.Bitween.Api/Resources/Portal/Xchanges.cs b/SW.Bitween.Api/Resources/Portal/Xchanges.cs deleted file mode 100644 index 3df6f7ce..00000000 --- a/SW.Bitween.Api/Resources/Portal/Xchanges.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using SW.Bitween.Domain; -using SW.Bitween.Model; -using SW.PrimitiveTypes; - -namespace SW.Bitween.Resources.Portal; - -/// The signed-in partner's exchanges, newest first, a page at a time. -/// -/// An exchange is the partner's when it carries their id. Exchanges from before that column existed -/// carry none and are not shown: the admin list works theirs out from the subscription, which no -/// index can answer, and a partner's list must stay quick on a table of millions. -/// -[HandlerName("xchanges")] -public class Xchanges(BitweenDbContext dbContext, RequestContext requestContext, XchangeService xchangeService) - : IQueryHandler -{ - public const int MaxPageSize = 100; - - public async Task Handle(PortalXchangeSearch request) - { - var caller = await PortalCaller.EnsureAsync(dbContext, requestContext, Model.Permissions.Portal.ExchangesView); - var partnerId = caller.PartnerId; - var size = Math.Clamp(request.Size, 1, MaxPageSize); - var page = Math.Max(request.Page, 0); - - var query = from x in dbContext.Set().AsNoTracking() - where x.PartnerId == partnerId - join r in dbContext.Set() on x.Id equals r.Id into xr - from r in xr.DefaultIfEmpty() - join d in dbContext.Set() on x.DocumentId equals d.Id - join s in dbContext.Set() on x.SubscriptionId equals s.Id into xs - from s in xs.DefaultIfEmpty() - select new { x, r, DocumentName = d.Name, SubscriptionName = s.Name }; - - // On the exchange's own status once it is filled in, which its index answers; before that, - // from the result, as the Exchanges page does. A bad response still delivered, so it counts - // as a success here. - var stateReady = await Services.XchangeStates.XchangeStateReadiness.IsReadyAsync(dbContext); - query = (request.Status?.ToLowerInvariant(), stateReady) switch - { - ("running", true) => query.Where(q => q.x.Status == XchangeStatus.Processing), - ("success", true) => query.Where(q => q.x.Status == null || q.x.Status == XchangeStatus.BadResponse), - ("failed", true) => query.Where(q => q.x.Status == XchangeStatus.Failed), - ("running", false) => query.Where(q => q.r == null), - ("success", false) => query.Where(q => q.r != null && q.r.Success), - ("failed", false) => query.Where(q => q.r != null && !q.r.Success), - _ => query - }; - if (request.SubscriptionId is { } subscriptionId) - query = query.Where(q => q.x.SubscriptionId == subscriptionId); - if (request.From is { } from) - { - var utc = Utc(from); - query = query.Where(q => q.x.StartedOn >= utc); - } - if (request.To is { } to) - { - var utc = Utc(to); - query = query.Where(q => q.x.StartedOn <= utc); - } - - // One more than the page, to tell whether there is a next one without counting them all. - var found = await query - .OrderByDescending(q => q.x.StartedOn) - // Two exchanges can start at the same instant; without a tie-break, one could show on two - // pages and the other on none. - .ThenByDescending(q => q.x.Id) - .Skip(page * size) - .Take(size + 1) - .Select(q => new - { - q.x.Id, - q.x.StartedOn, - q.x.FilesPrefix, - q.x.InputName, - q.x.InputSize, - q.x.SubscriptionId, - q.DocumentName, - q.SubscriptionName, - HasResult = q.r != null, - Success = q.r != null && q.r.Success, - FinishedOn = q.r != null ? q.r.FinishedOn : (DateTime?)null, - Exception = q.r != null ? q.r.Exception : null, - OutputName = q.r != null ? q.r.OutputName : null, - OutputSize = q.r != null ? q.r.OutputSize : 0, - ResponseName = q.r != null ? q.r.ResponseName : null, - ResponseSize = q.r != null ? q.r.ResponseSize : 0 - }) - .ToListAsync(); - - var withErrors = caller.Can(Model.Permissions.Portal.ExchangeErrorsView); - var withFiles = caller.Can(Model.Permissions.Portal.ExchangeFilesView); - - return new PortalXchangePage - { - HasMore = found.Count > size, - Result = found.Take(size).Select(f => new PortalXchangeRow - { - Id = f.Id, - StartedOn = f.StartedOn, - FinishedOn = f.FinishedOn, - Status = !f.HasResult ? "running" : f.Success ? "success" : "failed", - DocumentName = f.DocumentName, - SubscriptionId = f.SubscriptionId, - SubscriptionName = f.SubscriptionName, - Error = withErrors && f.HasResult && !f.Success ? f.Exception : null, - Files = withFiles - ? new[] - { - File(f.Id, f.FilesPrefix, XchangeFileType.Input, f.InputName, f.InputSize), - File(f.Id, f.FilesPrefix, XchangeFileType.Output, f.OutputName, f.OutputSize), - File(f.Id, f.FilesPrefix, XchangeFileType.Response, f.ResponseName, f.ResponseSize) - }.Where(file => file is not null).ToList() - : null - }).ToList() - }; - } - - /// A file the exchange has, or null: an empty size means it was never written. - private PortalXchangeFile File(string id, string prefix, XchangeFileType type, string name, int size) => - size <= 0 - ? null - : new PortalXchangeFile - { - Kind = type.ToString().ToLowerInvariant(), - Name = name, - Size = size, - Url = xchangeService.FileUrl(id, prefix, type) - }; - - private static DateTime Utc(DateTime value) => value.Kind switch - { - DateTimeKind.Local => value.ToUniversalTime(), - DateTimeKind.Unspecified => DateTime.SpecifyKind(value, DateTimeKind.Utc), - _ => value - }; -} diff --git a/SW.Bitween.Api/Resources/Xchanges/RetryTree.cs b/SW.Bitween.Api/Resources/Xchanges/RetryTree.cs index 36ca75c5..f6a7bf0b 100644 --- a/SW.Bitween.Api/Resources/Xchanges/RetryTree.cs +++ b/SW.Bitween.Api/Resources/Xchanges/RetryTree.cs @@ -57,7 +57,15 @@ public RetryTree(BitweenDbContext dbContext, RequestContext requestContext) public async Task Handle(XchangeRetryTreeRequest request) { await _requestContext.EnsurePermission(_dbContext, Model.Permissions.Exchanges.View); + return await TreeAsync(request, null); + } + /// + /// The chain the exchange belongs to. With , only that partner's + /// attempts: what the partner portal shows. The caller has checked who may see them. + /// + internal async Task TreeAsync(XchangeRetryTreeRequest request, int? partnerId) + { if (string.IsNullOrWhiteSpace(request?.Id)) throw new SWValidationException("ID_REQUIRED", "Which exchange's retries?"); @@ -124,7 +132,7 @@ from delayed in dr.DefaultIfEmpty() join promoted in _dbContext.Set() on xchange.Id equals promoted.Id into xp from promoted in xp.DefaultIfEmpty() join document in _dbContext.Set() on xchange.DocumentId equals document.Id - where ids.Contains(xchange.Id) + where ids.Contains(xchange.Id) && (partnerId == null || xchange.PartnerId == partnerId) orderby xchange.StartedOn select new XchangeRetryNode { diff --git a/SW.Bitween.Api/Resources/Xchanges/Search.cs b/SW.Bitween.Api/Resources/Xchanges/Search.cs index 0979d384..c061ec0d 100644 --- a/SW.Bitween.Api/Resources/Xchanges/Search.cs +++ b/SW.Bitween.Api/Resources/Xchanges/Search.cs @@ -36,14 +36,48 @@ public async Task Handle(SearchyRequest searchyRequest, bool lookup = fa if (!lookup) await requestContext.EnsurePermission(dbContext, Model.Permissions.Exchanges.View, Model.Permissions.Dashboard.View); + if (!lookup) + return await SearchAsync(searchyRequest, null); + + // Only id and information type, so the lookup has nothing to hide from a caller without + // the view permission. It returned whole rows before - errors, promoted values, source + // values - to anyone signed in. Capped, because exchanges run to millions and a lookup + // with no page size would otherwise list every one of them. + var query = await QueryAsync(searchyRequest, null); + await using var dr = await dbContext.Database.BeginTransactionAsync(IsolationLevel.ReadUncommitted); + return await Page(query, searchyRequest).Take(LookupLimit).ToDictionaryAsync(k => k.Id, v => v.DocumentName); + } + + /// + /// The page of exchanges a filter matches, with its total when asked for. With + /// , only that partner's: what the partner portal lists, the same + /// rows our team's list shows, filtered on the exchange's own partner so its index answers. + /// The caller has checked who may see them. + /// + internal async Task> SearchAsync(SearchyRequest searchyRequest, int? partnerId) + { + var query = await QueryAsync(searchyRequest, partnerId); + await using var dr = await dbContext.Database.BeginTransactionAsync(IsolationLevel.ReadUncommitted); + var r = await Page(query, searchyRequest).ToListAsync(); + return await FinishAsync(searchyRequest, query, r); + } + + private static IQueryable Page(IQueryable query, SearchyRequest searchyRequest) => + query.OrderByDescending(p => p.StartedOn).AsNoTracking().Search(searchyRequest.Conditions, + searchyRequest.Sorts, searchyRequest.PageSize, searchyRequest.PageIndex); + + private async Task> QueryAsync(SearchyRequest searchyRequest, int? partnerId) + { searchyRequest.DatesToUtc(); await XchangeFilters.ResolveReceiveAttemptFilterAsync(searchyRequest, dbContext); var stateReady = await Services.XchangeStates.XchangeStateReadiness.IsReadyAsync(dbContext); - await using var dr = await dbContext.Database.BeginTransactionAsync(IsolationLevel.ReadUncommitted); // The status and latest-only filters on the exchange's own columns once they are filled // in, which their index answers; before that, ApplySpecialFilters below works them out. - var query = from xchange in dbContext.Set().WhereState(searchyRequest, stateReady) + var exchanges = partnerId is { } partner + ? dbContext.Set().Where(x => x.PartnerId == partner) + : dbContext.Set(); + var query = from xchange in exchanges.WhereState(searchyRequest, stateReady) join result in dbContext.Set() on xchange.Id equals result.Id into xr from result in xr.DefaultIfEmpty() join agg in dbContext.Set() on xchange.Id equals agg.Id into xa @@ -111,20 +145,12 @@ from delayedRetry in drGroup.DefaultIfEmpty() Warning = result.Warning }; - query = query.ApplySpecialFilters(searchyRequest, dbContext); - - var s = query.OrderByDescending(p => p.StartedOn).AsNoTracking().Search(searchyRequest.Conditions, - searchyRequest.Sorts, searchyRequest.PageSize, searchyRequest.PageIndex); - - // Only id and information type, so the lookup has nothing to hide from a caller without - // the view permission. It returned whole rows before - errors, promoted values, source - // values - to anyone signed in. Capped, because exchanges run to millions and a lookup - // with no page size would otherwise list every one of them. - if (lookup) - return await s.Take(LookupLimit).ToDictionaryAsync(k => k.Id, v => v.DocumentName); - - var r = await s.ToListAsync(); + return query.ApplySpecialFilters(searchyRequest, dbContext); + } + private async Task> FinishAsync(SearchyRequest searchyRequest, + IQueryable query, List r) + { // Shown here, never used: a long source value is cut the way the editor's examples are, // so a page of rows stays small whatever a subscription reads. The exchange keeps it whole. foreach (var row in r.Where(row => row.SourceValues != null)) diff --git a/SW.Bitween.Api/Resources/Xchanges/Summary.cs b/SW.Bitween.Api/Resources/Xchanges/Summary.cs index cc407bf9..0942899d 100644 --- a/SW.Bitween.Api/Resources/Xchanges/Summary.cs +++ b/SW.Bitween.Api/Resources/Xchanges/Summary.cs @@ -46,7 +46,16 @@ public async Task Handle(SearchyRequest searchyRequest, bool lookup = fa // The same read the list itself is: whoever may see the exchanges, or the dashboard that // summarises them, may see how many there are. await requestContext.EnsurePermission(dbContext, Model.Permissions.Exchanges.View, Model.Permissions.Dashboard.View); + return await SummarizeAsync(searchyRequest, null); + } + /// + /// The counts by status, and the volume over time, of what a filter matches. With + /// , only that partner's: what the partner portal counts. The caller + /// has checked who may see them. + /// + internal async Task SummarizeAsync(SearchyRequest searchyRequest, int? partnerId) + { // Removed before anything else reads the request, from every condition rather than only // the first the special filters look at: a status filter left in a later condition would // reach Searchy as a column, and XchangeRow.StatusFilter is not one the database has. @@ -57,9 +66,10 @@ public async Task Handle(SearchyRequest searchyRequest, bool lookup = fa // Taken before FilteredRowsAsync takes the special filters out of the request: a count finished // in the background filters again from this, with a database of its own. var asked = (SearchyRequest)searchyRequest.Clone(); - var view = ViewKey(searchyRequest, DateTime.UtcNow); + // A partner's counts are kept apart from everyone else's: the same filter is another view. + var view = (partnerId is { } partner ? $"partner:{partner}|" : "") + ViewKey(searchyRequest, DateTime.UtcNow); - var rows = await XchangeFilters.FilteredRowsAsync(dbContext, searchyRequest); + var rows = await XchangeFilters.FilteredRowsAsync(dbContext, searchyRequest, partnerId: partnerId); // Read after FilteredRowsAsync, which is what moves the request's dates to UTC. The // StartedOn filters are plain columns, so Searchy has applied them and left them in place. @@ -99,7 +109,7 @@ public async Task Handle(SearchyRequest searchyRequest, bool lookup = fa using var histogramDeadline = new CancellationTokenSource(Budget); var started = await Answer($"histogram:{bucketMinutes}|{view}", histogramDeadline.Token, ct => StartedCounts(rows, bucketMinutes, ct), - async (db, ct) => await StartedCounts(await XchangeFilters.FilteredRowsAsync(db, Copy(asked)), bucketMinutes, ct)); + async (db, ct) => await StartedCounts(await XchangeFilters.FilteredRowsAsync(db, Copy(asked), partnerId: partnerId), bucketMinutes, ct)); if (started == null) { summary.Counting = true; @@ -114,8 +124,8 @@ public async Task Handle(SearchyRequest searchyRequest, bool lookup = fa // goes on the exchange table, where its index answers it. Task Count(string status, CancellationToken deadline) => Answer($"count:{status}|{view}", deadline, - async ct => await CountCapped(await XchangeFilters.FilteredRowsAsync(dbContext, Copy(asked), status), status, ct), - async (db, ct) => await CountCapped(await XchangeFilters.FilteredRowsAsync(db, Copy(asked), status), status, ct)); + async ct => await CountCapped(await XchangeFilters.FilteredRowsAsync(dbContext, Copy(asked), status, partnerId), status, ct), + async (db, ct) => await CountCapped(await XchangeFilters.FilteredRowsAsync(db, Copy(asked), status, partnerId), status, ct)); } /// diff --git a/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs b/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs index b9a9f612..4a6b3a7f 100644 --- a/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs +++ b/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs @@ -53,7 +53,7 @@ internal static class XchangeFilters /// /// internal static async Task> FilteredRowsAsync(BitweenDbContext dbContext, - SearchyRequest searchyRequest, string status = null) + SearchyRequest searchyRequest, string status = null, int? partnerId = null) { searchyRequest.DatesToUtc(); // Async, and inside here rather than in the callers, so a "select all matching" over a run @@ -61,7 +61,11 @@ internal static async Task> FilteredRowsAsync(BitweenDbCo await ResolveReceiveAttemptFilterAsync(searchyRequest, dbContext); var stateReady = await XchangeStateReadiness.IsReadyAsync(dbContext); - var query = from xchange in dbContext.Set().WhereState(searchyRequest, stateReady, status) + // A partner's own only, on the exchange's own column so its index answers: the portal's counts. + var exchanges = partnerId is { } partner + ? dbContext.Set().Where(x => x.PartnerId == partner) + : dbContext.Set(); + var query = from xchange in exchanges.WhereState(searchyRequest, stateReady, status) join result in dbContext.Set() on xchange.Id equals result.Id into xr from result in xr.DefaultIfEmpty() join agg in dbContext.Set() on xchange.Id equals agg.Id into xa diff --git a/SW.Bitween.IntegrationTests/Tests/PartnerPortalTests.cs b/SW.Bitween.IntegrationTests/Tests/PartnerPortalTests.cs index b1378b1d..86e6ca18 100644 --- a/SW.Bitween.IntegrationTests/Tests/PartnerPortalTests.cs +++ b/SW.Bitween.IntegrationTests/Tests/PartnerPortalTests.cs @@ -83,9 +83,9 @@ public async Task A_partner_sees_only_its_own_exchanges() var role = await PartnerRoleAsync(db, Permissions.Portal.ExchangesView); scope.As(await AccountAsync(db, world.Mine.Id, role)); - var handler = ActivatorUtilities.CreateInstance(scope.ServiceProvider); + var handler = ActivatorUtilities.CreateInstance(scope.ServiceProvider); - var page = (PortalXchangePage)await handler.Handle(new PortalXchangeSearch { Size = 100 }); + var page = (SearchyResponse)await handler.Handle(new SearchyRequest("") { PageSize = 100 }); var ids = page.Result.Select(r => r.Id).ToList(); Assert.Contains(mine, ids); @@ -101,25 +101,26 @@ public async Task Errors_and_files_need_their_own_permissions() var failed = await ExchangeAsync(db, world.MySubscription, world.Mine, exception: "Connection refused to 10.0.0.5"); // A scope each, as each request has its own: a request context is signed in once. - async Task RowAs(params string[] permissions) + async Task RowAs(params string[] permissions) { var account = await AccountAsync(db, world.Mine.Id, await PartnerRoleAsync(db, permissions)); await using var request = fixture.CreateScope(); request.As(account); - var handler = ActivatorUtilities.CreateInstance(request.ServiceProvider); - var page = (PortalXchangePage)await handler.Handle(new PortalXchangeSearch { Status = "failed", Size = 100 }); + var handler = ActivatorUtilities.CreateInstance(request.ServiceProvider); + var page = (SearchyResponse)await handler.Handle( + new SearchyRequest($"filter=Id:1:{failed}") { PageSize = 100 }); return page.Result.Single(r => r.Id == failed); } var bare = await RowAs(Permissions.Portal.ExchangesView); - Assert.Equal("failed", bare.Status); - Assert.Null(bare.Error); - Assert.Null(bare.Files); + Assert.False(bare.Status); + Assert.Null(bare.Exception); + Assert.Null(bare.InputUrl); var full = await RowAs(Permissions.Portal.ExchangesView, Permissions.Portal.ExchangeErrorsView, Permissions.Portal.ExchangeFilesView); - Assert.Equal("Connection refused to 10.0.0.5", full.Error); - Assert.Contains(full.Files!, f => f.Kind == "input"); + Assert.Equal("Connection refused to 10.0.0.5", full.Exception); + Assert.NotNull(full.InputUrl); } [Fact] @@ -131,9 +132,9 @@ public async Task Our_own_administrators_are_refused_by_the_portal() // An administrator holds the portal keys - that is what lets them hand out partner roles - // but has no partner, so there is nobody's data for the portal to show them. scope.As(await AccountAsync(db, null, Role.AdministratorId)); - var handler = ActivatorUtilities.CreateInstance(scope.ServiceProvider); + var handler = ActivatorUtilities.CreateInstance(scope.ServiceProvider); - var refused = await Assert.ThrowsAsync(() => handler.Handle(new PortalXchangeSearch())); + var refused = await Assert.ThrowsAsync(() => handler.Handle(new SearchyRequest(""))); Assert.Contains("NOT_A_PARTNER_ACCOUNT", refused.Message); } diff --git a/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs b/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs new file mode 100644 index 00000000..65e7fcb9 --- /dev/null +++ b/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs @@ -0,0 +1,134 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using SW.Bitween.Domain; +using SW.Bitween.Domain.Accounts; +using SW.Bitween.IntegrationTests.Fixtures; +using SW.Bitween.Model; +using SW.Bitween.Services; +using SW.PrimitiveTypes; +using Xunit; + +namespace SW.Bitween.IntegrationTests.Tests; + +/// +/// The portal's Exchanges page reads our team's own search, counts and retry chain, limited to the +/// caller's partner and without what is ours to know. +/// +[Collection("Bitween")] +public class PortalExchangeViewsTests(BitweenFixture fixture) +{ + private record World(int Mine, int SeesErrors, int SeesNothingMore, string MyFailed, string TheirFailed, int SubscriptionId); + + private async Task SetUpAsync() + { + await using var scope = fixture.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var xs = scope.ServiceProvider.GetRequiredService(); + var doc = new Document(null, $"Views {Guid.NewGuid():N}", DocumentFormat.Json); + var mine = new Partner($"Views mine {Guid.NewGuid():N}"); + var theirs = new Partner($"Views theirs {Guid.NewGuid():N}"); + db.AddRange(doc, mine, theirs); + await db.SaveChangesAsync(); + var sub = new Subscription($"Views {Guid.NewGuid():N}", doc.Id) { Inactive = false }; + db.Add(sub); + await db.SaveChangesAsync(); + + async Task Failed(Partner partner) + { + var x = await xs.CreateXchange(sub, new XchangeFile("{}"), gatewayPartner: partner); + await db.SaveChangesAsync(); + db.Add(new XchangeResult(x.Id, null, null, exception: "Connection refused by 10.0.0.7")); + await db.SaveChangesAsync(); + return x.Id; + } + + async Task Person(params string[] permissions) + { + var role = new Role($"Views role {Guid.NewGuid():N}", null, permissions, forPartners: true); + db.Add(role); + var account = new Account("Views", $"{Guid.NewGuid():N}@test.local", "hash", AccountRole.Viewer, mine.Id); + db.Add(account); + await db.SaveChangesAsync(); + db.Add(new AccountRoleLink(account.Id, role.Id)); + await db.SaveChangesAsync(); + return account.Id; + } + + return new World(mine.Id, + await Person(Permissions.Portal.ExchangesView, Permissions.Portal.ExchangeErrorsView), + await Person(Permissions.Portal.ExchangesView), + await Failed(mine), await Failed(theirs), sub.Id); + } + + private async Task As(int person, Func> act) where THandler : class + { + await using var scope = fixture.CreateScope(); + scope.As(person); + return (T)await act(ActivatorUtilities.CreateInstance(scope.ServiceProvider)); + } + + private static SearchyRequest Filter(params string[] filters) => + new(string.Join("&", filters.Select(f => $"filter={f}"))) { PageSize = 50 }; + + [Fact] + public async Task Lists_only_theirs_with_what_their_role_shows() + { + var w = await SetUpAsync(); + var bySubscription = $"SubscriptionId:1:{w.SubscriptionId}"; + + var withErrors = await As>(w.SeesErrors, + h => h.Handle(Filter(bySubscription))); + var row = Assert.Single(withErrors.Result); + Assert.Equal(w.MyFailed, row.Id); + Assert.Contains("Connection refused", row.Exception); + Assert.Null(row.HandlerId); + Assert.Null(row.InputKey); + + var plain = await As>(w.SeesNothingMore, + h => h.Handle(Filter(bySubscription))); + var plainRow = Assert.Single(plain.Result); + Assert.Null(plainRow.Exception); + Assert.Null(plainRow.InputUrl); + } + + [Fact] + public async Task Refuses_filters_on_what_they_may_not_read() + { + var w = await SetUpAsync(); + await Assert.ThrowsAsync(() => As(w.SeesNothingMore, + h => h.Handle(Filter("ErrorContains:1:refused")))); + await Assert.ThrowsAsync(() => As(w.SeesErrors, + h => h.Handle(Filter("Exception:1:refused")))); + await Assert.ThrowsAsync(() => As(w.SeesErrors, + h => h.Handle(Filter("HandlerId:1:x")))); + + // With the errors permission, the error filter works on their own. + var found = await As>(w.SeesErrors, + h => h.Handle(Filter($"SubscriptionId:1:{w.SubscriptionId}", "ErrorContains:1:refused"))); + Assert.Equal([w.MyFailed], found.Result.Select(r => r.Id).ToList()); + } + + [Fact] + public async Task Counts_only_theirs() + { + var w = await SetUpAsync(); + var summary = await As(w.SeesNothingMore, + h => h.Handle(Filter($"SubscriptionId:1:{w.SubscriptionId}"))); + Assert.Equal(1, summary.Counts.Failed); + } + + [Fact] + public async Task Shows_the_chain_of_theirs_only() + { + var w = await SetUpAsync(); + var tree = await As(w.SeesNothingMore, + h => h.Handle(new XchangeRetryTreeRequest { Id = w.MyFailed })); + Assert.Equal(w.MyFailed, Assert.Single(tree.Nodes).Id); + Assert.Null(tree.Nodes[0].Exception); + + await Assert.ThrowsAsync(() => As(w.SeesErrors, + h => h.Handle(new XchangeRetryTreeRequest { Id = w.TheirFailed }))); + } +} diff --git a/SW.Bitween.IntegrationTests/Tests/PortalRetryTests.cs b/SW.Bitween.IntegrationTests/Tests/PortalRetryTests.cs new file mode 100644 index 00000000..5dc4a03c --- /dev/null +++ b/SW.Bitween.IntegrationTests/Tests/PortalRetryTests.cs @@ -0,0 +1,100 @@ +using System; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using SW.Bitween.Domain; +using SW.Bitween.Domain.Accounts; +using SW.Bitween.IntegrationTests.Fixtures; +using SW.Bitween.Model; +using SW.Bitween.Services; +using SW.PrimitiveTypes; +using Xunit; + +namespace SW.Bitween.IntegrationTests.Tests; + +/// +/// A partner's person retries their own failed exchanges from the portal: only theirs, only failed, +/// only the latest attempt, and only with the permission to. +/// +[Collection("Bitween")] +public class PortalRetryTests(BitweenFixture fixture) +{ + private record World(int Mine, int Other, int Retrier, int Viewer, string MyFailed, string MyDelivered, string TheirFailed); + + private async Task SetUpAsync() + { + await using var scope = fixture.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var xs = scope.ServiceProvider.GetRequiredService(); + + var doc = new Document(null, $"Portal retry {Guid.NewGuid():N}", DocumentFormat.Json); + var mine = new Partner($"Retry mine {Guid.NewGuid():N}"); + var other = new Partner($"Retry other {Guid.NewGuid():N}"); + db.AddRange(doc, mine, other); + await db.SaveChangesAsync(); + var sub = new Subscription($"Portal retry {Guid.NewGuid():N}", doc.Id) { Inactive = false }; + db.Add(sub); + await db.SaveChangesAsync(); + + async Task Exchange(Partner partner, string exception) + { + var x = await xs.CreateXchange(sub, new XchangeFile("{}"), gatewayPartner: partner); + await db.SaveChangesAsync(); + db.Add(new XchangeResult(x.Id, null, null, exception: exception)); + await db.SaveChangesAsync(); + return x.Id; + } + + async Task Person(params string[] permissions) + { + var role = new Role($"Retry role {Guid.NewGuid():N}", null, permissions, forPartners: true); + db.Add(role); + var account = new Account("Retrier", $"{Guid.NewGuid():N}@test.local", "hash", AccountRole.Viewer, mine.Id); + db.Add(account); + await db.SaveChangesAsync(); + db.Add(new AccountRoleLink(account.Id, role.Id)); + await db.SaveChangesAsync(); + return account.Id; + } + + return new World(mine.Id, other.Id, + await Person(Permissions.Portal.ExchangesView, Permissions.Portal.ExchangesOperate), + await Person(Permissions.Portal.ExchangesView), + await Exchange(mine, "boom"), await Exchange(mine, null), await Exchange(other, "boom")); + } + + private async Task RetryAs(int person, string xchangeId) + { + await using var scope = fixture.CreateScope(); + scope.As(person); + return await ActivatorUtilities.CreateInstance(scope.ServiceProvider) + .Handle(new PortalRetry { XchangeId = xchangeId }); + } + + [Fact] + public async Task Retries_their_failed_exchange_once_with_their_partner_kept() + { + var w = await SetUpAsync(); + var retried = (PortalRetried)await RetryAs(w.Retrier, w.MyFailed); + + await using (var scope = fixture.CreateScope()) + { + var retry = await scope.ServiceProvider.GetRequiredService().Set().AsNoTracking() + .SingleAsync(x => x.Id == retried.XchangeId); + Assert.Equal(w.MyFailed, retry.RetryFor); + Assert.Equal(w.Mine, retry.PartnerId); + } + + // Only the latest attempt is retried again. + await Assert.ThrowsAsync(() => RetryAs(w.Retrier, w.MyFailed)); + } + + [Fact] + public async Task Refuses_one_delivered_someone_elses_or_without_the_permission() + { + var w = await SetUpAsync(); + await Assert.ThrowsAsync(() => RetryAs(w.Retrier, w.MyDelivered)); + await Assert.ThrowsAsync(() => RetryAs(w.Retrier, w.TheirFailed)); + await Assert.ThrowsAsync(() => RetryAs(w.Viewer, w.MyFailed)); + } +} diff --git a/SW.Bitween.Sdk/Model/Permissions.cs b/SW.Bitween.Sdk/Model/Permissions.cs index beb13a06..2c31f81e 100644 --- a/SW.Bitween.Sdk/Model/Permissions.cs +++ b/SW.Bitween.Sdk/Model/Permissions.cs @@ -211,6 +211,7 @@ public static class Portal { public const string SubscriptionsView = "portal-subscriptions.view"; public const string ExchangesView = "portal-exchanges.view"; + public const string ExchangesOperate = "portal-exchanges.operate"; public const string ExchangeFilesView = "portal-exchange-files.view"; public const string ExchangeErrorsView = "portal-exchange-errors.view"; public const string MappingsView = "portal-mappings.view"; @@ -409,7 +410,8 @@ private static PermissionAreaModel Area(string id, string label, string group, s Area("portal-exchanges", "Their exchanges", "Partner portal", "The exchanges that ran for the partner.", - (View, "Browse their exchanges: status, times and counts.")), + (View, "Browse their exchanges: status, times and counts."), + (Operate, "Retry their failed exchanges, with the current mapping and details.")), Area("portal-exchange-files", "Exchange files", "Partner portal", "What each of their exchanges received, sent and got back.", diff --git a/SW.Bitween.Sdk/Model/Portal.cs b/SW.Bitween.Sdk/Model/Portal.cs index 4dddb162..c62a6ff0 100644 --- a/SW.Bitween.Sdk/Model/Portal.cs +++ b/SW.Bitween.Sdk/Model/Portal.cs @@ -13,71 +13,21 @@ public class PortalSubscriptionRow public bool Paused { get; set; } } -public class PortalXchangeSearch -{ - /// running, success or failed; anything else, or nothing, is every exchange. - public string? Status { get; set; } - - public int? SubscriptionId { get; set; } - public DateTime? From { get; set; } - public DateTime? To { get; set; } - /// Zero-based. - public int Page { get; set; } - public int Size { get; set; } = 25; -} -/// -/// One page of exchanges, newest first. No total: counting every exchange a partner ever had costs -/// far more than the page does, so the page says only whether there is another. -/// -public class PortalXchangePage +public class PortalRetry { - public List Result { get; set; } = []; - public bool HasMore { get; set; } + public string XchangeId { get; set; } = null!; } -public class PortalXchangeRow +/// The exchange a retry made. +public class PortalRetried { - public string Id { get; set; } = null!; - public DateTime StartedOn { get; set; } - public DateTime? FinishedOn { get; set; } - - /// running, success or failed. - public string Status { get; set; } = null!; - - public string DocumentName { get; set; } = null!; - public int? SubscriptionId { get; set; } - public string? SubscriptionName { get; set; } - - /// Why it failed; only with the exchange errors permission. - public string? Error { get; set; } - - /// Its files; only with the exchange files permission, and only the ones it has. - public List? Files { get; set; } + public string XchangeId { get; set; } = null!; } -public class PortalXchangeFile -{ - /// input, output or response. - public string Kind { get; set; } = null!; - public string? Name { get; set; } - public int Size { get; set; } - - /// Opens the file without signing in; given only for the partner's own exchanges. - public string Url { get; set; } = null!; -} - -/// The last 24 hours of the partner's exchanges, by outcome. -public class PortalSummary -{ - public string PartnerName { get; set; } = null!; - public int Running { get; set; } - public int Succeeded { get; set; } - public int Failed { get; set; } -} /// A place a partner is connected, and whether they map it their own way there. public class PortalMappingPlace @@ -337,3 +287,12 @@ public class PortalSaveProperties public class PortalWithdrawProperties { } + +/// An information type of what runs for them, for their filters: the names of what it promotes, not where they're read from. +public class PortalInformationType +{ + public int Id { get; set; } + public string Name { get; set; } = null!; + public string? Code { get; set; } + public List PromotedPropertyKeys { get; set; } = []; +} diff --git a/SW.Bitween.Web/ClientApp/src/api/client.ts b/SW.Bitween.Web/ClientApp/src/api/client.ts index 0dbd4428..bb6cc664 100644 --- a/SW.Bitween.Web/ClientApp/src/api/client.ts +++ b/SW.Bitween.Web/ClientApp/src/api/client.ts @@ -1,7 +1,6 @@ import type { AddBusRouteInput, AttachPartnerInput } from "./http/gateways"; import type { SubscriptionPartnerMapping, - PortalExchangePage, PortalMapping, PortalMappingPlace, PortalMappingSample, @@ -15,9 +14,7 @@ import type { PartnerChangeDetail, PartnerChangeVersion, PartnerPropertyChangeDetail, - PortalExchangeQuery, PortalSubscription, - PortalSummary, MirrorBring, MirrorBringSection, MirrorListed, @@ -787,8 +784,11 @@ export interface ApiClient { ): Promise>; // - exchanges - - searchExchanges(query: ExchangeQuery, opts?: { count?: boolean }): Promise>; - getExchangeBreakdown(query: ExchangeQuery): Promise; + /** With `portal`, the signed-in partner's own, through the partner portal's API. */ + searchExchanges(query: ExchangeQuery, opts?: { count?: boolean; portal?: boolean }): Promise>; + getExchangeBreakdown(query: ExchangeQuery, opts?: { portal?: boolean }): Promise; + /** A file of a partner's exchange, by its signed link. */ + readExchangeFileLink(url: string): Promise; // - audit trail - /** Who changed what, and when. Filters narrow it; with none set it is the whole trail. */ @@ -823,7 +823,7 @@ export interface ApiClient { linkToBackgroundFile(id: string): Promise<{ url: string }>; /** How many of the selection's exchanges the export would come without files for. Changes nothing. */ checkExchangeFilesExport(selection: BulkRetrySelection): Promise; - getRetryTree(id: string): Promise; + getRetryTree(id: string, opts?: { portal?: boolean }): Promise; /** * Turns a plain-English question into the Exchanges page's filter, through the AI provider under * Settings, AI. Only the question, the time and names (partners, subscriptions, information @@ -939,13 +939,13 @@ export interface ApiClient { // --- Partner portal: the signed-in partner's own data only --- - /** Their name and the last 24 hours of their exchanges by outcome. */ - getPortalSummary(): Promise; /** The subscriptions that run for them, read-only. */ listPortalSubscriptions(): Promise; - /** Their exchanges newest first, a page at a time; errors and files only with those permissions. */ - searchPortalExchanges(query: PortalExchangeQuery): Promise; /** Every place they're connected, and whether they use their own mapping there. */ + /** The information types of what runs for them, shaped for the Exchanges page's filters. */ + listPortalInformationTypes(): Promise; + /** Retries one of their failed exchanges with the current settings; the new attempt's id. */ + retryPortalExchange(xchangeId: string): Promise; listPortalMappings(): Promise; getPortalMapping(subscriptionId: number): Promise; /** Saves their own mapping of a place: used from their next exchange, or waiting for approval. */ diff --git a/SW.Bitween.Web/ClientApp/src/api/http/exchanges.ts b/SW.Bitween.Web/ClientApp/src/api/http/exchanges.ts index 30199254..d9832676 100644 --- a/SW.Bitween.Web/ClientApp/src/api/http/exchanges.ts +++ b/SW.Bitween.Web/ClientApp/src/api/http/exchanges.ts @@ -55,6 +55,10 @@ interface RawXchangeRow { hasRetry: boolean; /** Absent from servers that predate it. */ warning?: string | null; + /** Signed links to the files; what a partner's people read them by, having no storage keys. */ + inputUrl?: string | null; + outputUrl?: string | null; + responseUrl?: string | null; } interface RawRetryNode { @@ -123,7 +127,11 @@ const STATUS_FILTER: Record = { failed: 3, }; -const toExchangeRow = (raw: RawXchangeRow, partnerNameById: Map): ExchangeRow => ({ +/** + * A row as the page reads it. For a partner's people (`portal`), a file is opened by its signed link, + * since storage keys are ours and never sent to them. + */ +const toExchangeRow = (raw: RawXchangeRow, partnerNameById: Map, portal = false): ExchangeRow => ({ id: raw.id, status: deriveStatus(raw), subscriptionId: raw.subscriptionId, @@ -149,18 +157,15 @@ const toExchangeRow = (raw: RawXchangeRow, partnerNameById: Map) // has bytes), not the file name, since gateway/manually created exchanges have // no name yet content still exists. files: { - input: raw.inputKey - ? { name: raw.inputFileName ?? "input", size: raw.inputFileSize ?? 0, key: raw.inputKey } - : null, - mapped: raw.outputKey - ? { name: raw.outputFileName ?? "mapped", size: raw.outputFileSize ?? 0, key: raw.outputKey } - : null, - handled: raw.responseKey - ? { name: raw.responseFileName ?? "handled", size: raw.responseFileSize ?? 0, key: raw.responseKey } - : null, + input: fileRef(portal ? raw.inputUrl : raw.inputKey, raw.inputFileName, raw.inputFileSize, "input"), + mapped: fileRef(portal ? raw.outputUrl : raw.outputKey, raw.outputFileName, raw.outputFileSize, "mapped"), + handled: fileRef(portal ? raw.responseUrl : raw.responseKey, raw.responseFileName, raw.responseFileSize, "handled"), }, }); +const fileRef = (key: string | null | undefined, name: string | null | undefined, size: number | null | undefined, fallback: string) => + key ? { name: name ?? fallback, size: size ?? 0, key } : null; + const toScheduledRetryRow = (raw: RawDelayedRetryRow): ScheduledRetryRow => ({ id: raw.id, on: raw.on, @@ -307,6 +312,13 @@ async function partnerNameMap(): Promise> { } export const exchangeMethods = { + /** A file of a partner's exchange, by the signed link their list carries. */ + async readExchangeFileLink(url: string): Promise { + const res = await fetch(url, { credentials: "include" }); + if (!res.ok) throw new ApiRequestError(res.status === 404 ? "NOT_FOUND" : "FILE_UNAVAILABLE", "This file couldn't be read."); + return res.text(); + }, + async getExchangeDocument(key: string): Promise { const res = await get<{ data: string; key: string }>(`/bitweendocs?documentKey=${encodeURIComponent(key)}`); return res.data; @@ -316,12 +328,17 @@ export const exchangeMethods = { * A page of exchanges and how many match. With `count: false` the total is left out, as 0, so the * rows come back without waiting for it: the Exchanges page has its total from the status counts. */ - async searchExchanges(query: ExchangeQuery, { count = true }: { count?: boolean } = {}): Promise> { + async searchExchanges( + query: ExchangeQuery, + { count = true, portal = false }: { count?: boolean; portal?: boolean } = {}, + ): Promise> { + const path = portal ? "/portal/xchangesearch" : "/xchanges"; const [res, partnerNameById] = await Promise.all([ - get>(`/xchanges?${buildExchangeQuery(query)}${count ? "" : "&count=false"}`), - partnerNameMap(), + get>(`${path}?${buildExchangeQuery(query)}${count ? "" : "&count=false"}`), + // A partner's people see only their own, and may not list partners. + portal ? Promise.resolve(new Map()) : partnerNameMap(), ]); - return { result: res.result.map((r) => toExchangeRow(r, partnerNameById)), total: res.totalCount }; + return { result: res.result.map((r) => toExchangeRow(r, partnerNameById, portal)), total: res.totalCount }; }, /** @@ -329,9 +346,10 @@ export const exchangeMethods = { * out of the filter on purpose: the tabs are the choice between statuses, so each needs its * count under every other filter. */ - async getExchangeBreakdown(query: ExchangeQuery): Promise { + async getExchangeBreakdown(query: ExchangeQuery, { portal = false }: { portal?: boolean } = {}): Promise { const params = buildExchangeFilters({ ...query, status: undefined }); - const res = await get(`/xchanges/summary${params.toString() ? `?${searchyQueryString(params)}` : ""}`); + const path = portal ? "/portal/xchangesummary" : "/xchanges/summary"; + const res = await get(`${path}${params.toString() ? `?${searchyQueryString(params)}` : ""}`); return { counts: { processing: res.counts?.processing ?? null, @@ -366,8 +384,8 @@ export const exchangeMethods = { * Every attempt related to one exchange. Worth asking for only when the row says there is * something to see - `retryFor` or `hasRetry` - since most exchanges have neither. */ - async getRetryTree(id: string): Promise { - const raw = await get(`/xchanges/retrytree?id=${encodeURIComponent(id)}`); + async getRetryTree(id: string, { portal = false }: { portal?: boolean } = {}): Promise { + const raw = await get(`${portal ? "/portal" : "/xchanges"}/retrytree?id=${encodeURIComponent(id)}`); return { rootId: raw.rootId, truncated: raw.truncated, diff --git a/SW.Bitween.Web/ClientApp/src/api/http/portal.ts b/SW.Bitween.Web/ClientApp/src/api/http/portal.ts index 9513b5a1..6ff4f2d8 100644 --- a/SW.Bitween.Web/ClientApp/src/api/http/portal.ts +++ b/SW.Bitween.Web/ClientApp/src/api/http/portal.ts @@ -1,11 +1,10 @@ import type { ApiClient } from "../client"; import type { + InformationType, PartnerChange, PartnerChangeDetail, PartnerChangeVersion, PartnerPropertyChangeDetail, - PortalExchangePage, - PortalExchangeQuery, PortalMapping, PortalMappingPlace, PortalMappingSample, @@ -14,7 +13,6 @@ import type { PortalPerson, PortalProperties, PortalRoleChoice, - PortalSummary, SubscriptionPartnerMapping, } from "../types"; import { get, post } from "./request"; @@ -22,9 +20,9 @@ import { get, post } from "./request"; /** The partner portal: always the signed-in partner's own data, scoped by the server. */ export const portalMethods: Pick< ApiClient, - | "getPortalSummary" | "listPortalSubscriptions" - | "searchPortalExchanges" + | "retryPortalExchange" + | "listPortalInformationTypes" | "listPortalMappings" | "getPortalMapping" | "savePortalMapping" @@ -58,20 +56,23 @@ export const portalMethods: Pick< | "setPortalPersonDisabled" | "removePortalPerson" > = { - getPortalSummary: () => get("/portal/summary"), - listPortalSubscriptions: () => get<{ id: number; name: string; type: string; documentName: string; paused: boolean }[]>("/portal/subscriptions").then( (rows) => rows.map((r) => ({ ...r, id: String(r.id) })), ), - searchPortalExchanges: (query: PortalExchangeQuery) => { - const params = new URLSearchParams({ page: String(query.page), size: String(query.size) }); - if (query.status) params.set("status", query.status); - if (query.subscriptionId) params.set("subscriptionId", query.subscriptionId); - return get(`/portal/xchanges?${params}`); - }, - + listPortalInformationTypes: async () => + (await get<{ id: number; name: string; code: string | null; promotedPropertyKeys: string[] }[]>("/portal/informationtypes")).map( + // Only what the filters read: the names it promotes, never where they're read from. + (t) => + ({ + id: t.id, + name: t.name, + code: t.code ?? undefined, + promotedProperties: t.promotedPropertyKeys.map((key) => ({ key, path: "" })), + }) as unknown as InformationType, + ), + retryPortalExchange: async (xchangeId) => (await post<{ xchangeId: string }>("/portal/retry", { xchangeId })).xchangeId, listPortalMappings: () => get("/portal/mappings"), getPortalMapping: (subscriptionId) => get(`/portal/mapping?subscriptionId=${subscriptionId}`), savePortalMapping: async (subscriptionId, mapperProperties) => diff --git a/SW.Bitween.Web/ClientApp/src/api/queryKeys.ts b/SW.Bitween.Web/ClientApp/src/api/queryKeys.ts index 4a79e660..ea823d13 100644 --- a/SW.Bitween.Web/ClientApp/src/api/queryKeys.ts +++ b/SW.Bitween.Web/ClientApp/src/api/queryKeys.ts @@ -180,6 +180,7 @@ export const keys = { /** A partner's admin's: their company's people, and the roles they may give. */ people: ["portal", "people"] as const, properties: ["portal", "properties"] as const, + informationTypes: ["portal", "informationTypes"] as const, peopleRoles: ["portal", "peopleRoles"] as const, change: (id: number) => ["portal", "change", id] as const, propertyChange: (id: number) => ["portal", "propertyChange", id] as const, diff --git a/SW.Bitween.Web/ClientApp/src/api/types.ts b/SW.Bitween.Web/ClientApp/src/api/types.ts index 364df98f..216dc47b 100644 --- a/SW.Bitween.Web/ClientApp/src/api/types.ts +++ b/SW.Bitween.Web/ClientApp/src/api/types.ts @@ -2723,13 +2723,6 @@ export interface RetrySuggestion { // --- Partner portal --- -export interface PortalSummary { - partnerName: string; - running: number; - succeeded: number; - failed: number; -} - export interface PortalSubscription { id: string; name: string; @@ -2738,44 +2731,6 @@ export interface PortalSubscription { paused: boolean; } -export type PortalExchangeStatus = "running" | "success" | "failed"; - -export interface PortalExchangeQuery { - status: PortalExchangeStatus | null; - subscriptionId: string | null; - /** Zero-based. */ - page: number; - size: number; -} - -export interface PortalExchangeFile { - kind: "input" | "output" | "response"; - name: string | null; - size: number; - /** Opens without signing in; handed out only for the partner's own exchanges. */ - url: string; -} - -export interface PortalExchange { - id: string; - startedOn: string; - finishedOn: string | null; - status: PortalExchangeStatus; - documentName: string; - subscriptionId: number | null; - subscriptionName: string | null; - /** Null without the exchange errors permission, and for anything but a failure. */ - error: string | null; - /** Null without the exchange files permission. */ - files: PortalExchangeFile[] | null; -} - -/** No total: the page says only whether there is another. */ -export interface PortalExchangePage { - result: PortalExchange[]; - hasMore: boolean; -} - /** A place a partner is connected, and whether they map it their own way there. */ export interface PortalMappingPlace { subscriptionId: number; diff --git a/SW.Bitween.Web/ClientApp/src/auth/guards.tsx b/SW.Bitween.Web/ClientApp/src/auth/guards.tsx index c11eb3cc..ee5fa1ce 100644 --- a/SW.Bitween.Web/ClientApp/src/auth/guards.tsx +++ b/SW.Bitween.Web/ClientApp/src/auth/guards.tsx @@ -58,10 +58,11 @@ export const PORTAL_PATH = "/portal"; const inPortal = (path: string) => path === PORTAL_PATH || path.startsWith(PORTAL_PATH + "/"); /** The partner portal is for a partner's people; our own are sent back to the app. */ -export function RequirePartner() { +/** A partner's people's page: anyone else goes back to the app. */ +export function RequirePartner({ children }: { children?: ReactNode }) { const { session } = useSession(); if (!session?.partner) return ; - return ; + return children ?? ; } /** Full-page stop for routes the session's roles don't unlock. */ diff --git a/SW.Bitween.Web/ClientApp/src/components/layout/AppShell.tsx b/SW.Bitween.Web/ClientApp/src/components/layout/AppShell.tsx index 35442873..5048acb8 100644 --- a/SW.Bitween.Web/ClientApp/src/components/layout/AppShell.tsx +++ b/SW.Bitween.Web/ClientApp/src/components/layout/AppShell.tsx @@ -9,6 +9,7 @@ import { Menu as MenuIcon, PanelLeftClose, PanelLeftOpen, + KeyRound, UserRound, X, Search as SearchIcon, @@ -227,7 +228,7 @@ function SidebarContent({ const scroll = useScrollEdges(`${collapsed.join()}|${railed}|${session?.permissions.length ?? 0}`); if (!session) return null; - const groups = visibleGroups(session.permissions); + const groups = visibleGroups(session.permissions, !!session.partner); const toggleGroup = (label: string) => setCollapsed((prev) => { @@ -308,6 +309,9 @@ function SidebarContent({
  • g.items.some((other) => other.path.startsWith(item.path + "/")))} onClick={onNavigate} aria-label={railed ? item.label : undefined} onMouseEnter={railed ? (e) => showTip(e.currentTarget, item.label) : undefined} @@ -390,16 +394,26 @@ function SidebarContent({ {session.user.displayName} - {session.roles.map((r) => r.name).join(", ") || "No roles"} + {/* A partner's people see whose portal this is: their company's. */} + {[session.partner?.name, session.roles.map((r) => r.name).join(", ") || "No roles"] + .filter(Boolean) + .join(" · ")} )} } > - navigate("/profile")}> - Your profile - + {/* The profile page is ours; a partner's people have their password to change and nothing else. */} + {session.partner ? ( + navigate("/change-password")}> + Change password + + ) : ( + navigate("/profile")}> + Your profile + + )} void signOut()}> Sign out @@ -412,6 +426,7 @@ function SidebarContent({ const RAILED_KEY = "bitween-nav-railed"; export function AppShell() { + const { session } = useSession(); const [mobileOpen, setMobileOpen] = useState(false); const [railed, setRailed] = useState(() => localStorage.getItem(RAILED_KEY) === "1"); const { pathname, search } = useLocation(); @@ -445,7 +460,11 @@ export function AppShell() { // a page asks for things in its own effects, which run after this but before a passive one. useLayoutEffect(() => setCurrentPage(pathname + search), [pathname, search]); // Work still running from before a reload, or finished while away, shows in the header again. - useEffect(() => void refreshBackground(), []); + // A partner's people start none, and may not list them. + const partner = !!session?.partner; + useEffect(() => { + if (!partner) void refreshBackground(); + }, [partner]); // ⌘K / Ctrl+K anywhere, as in most tools people already use; "/" too, when not typing. useEffect(() => { diff --git a/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx b/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx index 03b9b3c6..950d0851 100644 --- a/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx +++ b/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx @@ -55,7 +55,8 @@ function matches(items: Item[], query: string): Item[] { */ export function CommandPalette({ onClose }: { onClose: () => void }) { const navigate = useNavigate(); - const { can } = useSession(); + const { can, session } = useSession(); + const partner = !!session?.partner; const [query, setQuery] = useState(""); const panel = useRef(null); useModalFocus(panel); @@ -91,7 +92,9 @@ export function CommandPalette({ onClose }: { onClose: () => void }) { return (Object.keys(PAGES) as PageId[]) .filter((id) => !PAGES[id].path.includes(":")) .filter((id) => { - const { permission, alsoFor = [] } = PAGES[id]; + const { permission, alsoFor = [], audience } = PAGES[id]; + // A partner's people find their portal's pages, and everyone else none of them. + if ((audience === "partner") !== partner) return false; return !permission || can(permission) || alsoFor.some(can); }) .map((id) => { @@ -107,7 +110,7 @@ export function CommandPalette({ onClose }: { onClose: () => void }) { words: (page.keywords ?? []).join(" "), }; }); - }, [can]); + }, [can, partner]); const things = useMemo(() => { const of = ( diff --git a/SW.Bitween.Web/ClientApp/src/nav.ts b/SW.Bitween.Web/ClientApp/src/nav.ts index 7f21d7cf..cd638a1b 100644 --- a/SW.Bitween.Web/ClientApp/src/nav.ts +++ b/SW.Bitween.Web/ClientApp/src/nav.ts @@ -9,6 +9,8 @@ export interface NavItem { icon: LucideIcon; /** Visible when the session holds ANY of these. */ permissions: PermissionKey[]; + /** A partner's people's page: in their sidebar only, and theirs holds nothing else. */ + partner: boolean; } export interface NavGroup { @@ -21,6 +23,7 @@ const GROUP_LABELS: Record = { subscriptions: "Subscriptions", configuration: "Configuration", administration: "Administration", + portal: "Partner portal", }; /** @@ -40,6 +43,7 @@ export const NAV_GROUPS: NavGroup[] = (Object.keys(GROUP_LABELS) as NavGroupId[] path: `/${page.path}`, icon: page.nav.icon, permissions: page.permission ? [page.permission, ...(page.alsoFor ?? [])] : [], + partner: page.audience === "partner", }, ]; }), @@ -48,10 +52,12 @@ export const NAV_GROUPS: NavGroup[] = (Object.keys(GROUP_LABELS) as NavGroupId[] export const navItemVisible = (item: NavItem, permissions: PermissionKey[]) => item.permissions.some((p) => permissions.includes(p)); -export const visibleGroups = (permissions: PermissionKey[]): NavGroup[] => - NAV_GROUPS.map((g) => ({ ...g, items: g.items.filter((i) => navItemVisible(i, permissions)) })).filter( - (g) => g.items.length > 0, - ); +/** The sidebar for these permissions: a partner's people's own pages, or everyone else's. */ +export const visibleGroups = (permissions: PermissionKey[], partner = false): NavGroup[] => + NAV_GROUPS.map((g) => ({ + ...g, + items: g.items.filter((i) => i.partner === partner && navItemVisible(i, permissions)), + })).filter((g) => g.items.length > 0); /** * Where to land after signing in with nowhere particular to go: the dashboard when the session @@ -63,7 +69,8 @@ export const visibleGroups = (permissions: PermissionKey[]): NavGroup[] => * from a colleague both still end where they were headed. */ export const homePath = (session: Session): string => { - if (session.partner) return "/portal"; + // Their first page: Exchanges, unless their role doesn't show them. + if (session.partner) return visibleGroups(session.permissions, true)[0]?.items[0]?.path ?? "/portal"; if (session.permissions.includes("dashboard.view")) return "/dashboard"; const groups = visibleGroups(session.permissions); return groups[0]?.items[0]?.path ?? "/profile"; diff --git a/SW.Bitween.Web/ClientApp/src/pages.ts b/SW.Bitween.Web/ClientApp/src/pages.ts index 4d6ce4dd..772e14e7 100644 --- a/SW.Bitween.Web/ClientApp/src/pages.ts +++ b/SW.Bitween.Web/ClientApp/src/pages.ts @@ -1,5 +1,7 @@ import { Activity, + Building2, + FileCog, ArrowLeftRight, Cable, CalendarClock, @@ -48,7 +50,7 @@ import type { PermissionKey } from "./api"; * RetryPoliciesPage for the whole of one. */ -export type NavGroupId = "operate" | "subscriptions" | "configuration" | "administration"; +export type NavGroupId = "operate" | "subscriptions" | "configuration" | "administration" | "portal"; export interface PageDef { /** "subscriptions/:id" - relative to the app root, as the router takes it. */ @@ -67,6 +69,12 @@ export interface PageDef { layout?: "full"; /** Found by the command palette under these words too. */ keywords?: string[]; + /** + * A partner's people's page, in the partner portal: shown and opened only by them, and none of + * the others by them. Our administrators hold the portal's permissions too, so permissions alone + * can't keep the two apart. + */ + audience?: "partner"; } const definePages = (pages: Record>>) => pages; @@ -467,6 +475,50 @@ export const PAGES = definePages({ }, profile: { path: "profile", title: "Your profile", keywords: ["password", "account"] }, + // ── Partner portal: a partner's people's pages, and nothing else for them ── + portalExchanges: { + path: "portal", + title: "Exchanges", + permission: "portal-exchanges.view", + nav: { group: "portal", icon: ArrowLeftRight }, + audience: "partner", + }, + portalMappings: { + path: "portal/mappings", + title: "Mappings", + permission: "portal-mappings.view", + nav: { group: "portal", icon: FileCog }, + audience: "partner", + }, + portalMapping: { + path: "portal/mappings/:subscriptionId", + title: "Mapping", + permission: "portal-mappings.view", + parent: "portalMappings", + audience: "partner", + }, + portalSubscriptions: { + path: "portal/subscriptions", + title: "Subscriptions", + permission: "portal-subscriptions.view", + nav: { group: "portal", icon: Layers }, + audience: "partner", + }, + portalDetails: { + path: "portal/details", + title: "Your details", + permission: "portal-properties.view", + nav: { group: "portal", icon: Building2 }, + audience: "partner", + }, + portalPeople: { + path: "portal/people", + title: "People", + permission: "portal-people.view", + alsoFor: ["portal-people.edit"], + nav: { group: "portal", icon: Users }, + audience: "partner", + }, }); export type PageId = keyof typeof PAGES; diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDetailPanel.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDetailPanel.tsx index 89242542..ecd54a3b 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDetailPanel.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDetailPanel.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef } from "react"; -import { Link } from "react-router"; +import { OurPageLink } from "./exchangeSource"; import { ChevronDown, ChevronUp, X } from "lucide-react"; import type { ExchangeRow } from "../../api"; import { Badge } from "../../components/ui/basics"; @@ -54,27 +54,27 @@ export function ExchangeDetailPanel({ {x.aggregationXchangeId && Aggregated} {x.subscriptionName ? ( - + {x.subscriptionName} - + ) : ( No subscription )} {x.partnerName && ( <> {" · "} - + {x.partnerName} - + )} {" · "} - {x.informationTypeCode} - +
    diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDrawer.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDrawer.tsx index e322a773..3f482b16 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDrawer.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeDrawer.tsx @@ -3,7 +3,6 @@ import { Link } from "react-router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Download, FileText, Loader2, Play, RotateCcw } from "lucide-react"; import { api, ApiRequestError, type ExchangeDocStage, type ExchangeRow } from "../../api"; -import { useSessionCan } from "../../auth/useSessionCan"; import { Badge, Button, InlineNotice, ProblemText } from "../../components/ui/basics"; import { ConfirmDialog } from "../../components/ui/overlays"; import { HighlightedDocument } from "../../components/ui/HighlightedDocument"; @@ -17,6 +16,7 @@ import { journeyStages } from "./journey"; import { RetryChain } from "./RetryChain"; import { ExplainFailure } from "./ExplainFailure"; import { hasRetryChain, newestAttempt, retryTreeQuery } from "./retryTree"; +import { useExchangeSource } from "./exchangeSource"; import { keys } from "../../api/queryKeys"; const STAGE_TONES: Record = { @@ -178,12 +178,15 @@ const GONE_FOR_GOOD = new Set(["FILE_EXPIRED", "FILE_MISSING", "NOT_FOUND"]); */ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { const stages = journeyStages(x); - const canOperate = useSessionCan("exchanges.operate"); + const source = useExchangeSource(); + const { partner, listPath } = source; + const canOperate = source.canRetry; const queryClient = useQueryClient(); // An aggregation's exchange is the roll-up - its payload is the list of links to - // everything it collected, so it is the one exchange worth offering that drill from. + // everything it collected, so it is the one exchange worth offering that drill from. Our wiring: + // a partner's people neither see it nor may list the subscriptions it is read from. const isRollUp = - useSubscriptionsCache().data?.find((i) => i.id === x.subscriptionId)?.type === "Aggregation"; + useSubscriptionsCache(!partner).data?.find((i) => i.id === x.subscriptionId)?.type === "Aggregation"; const files: Record = { Input: x.files.input, @@ -203,7 +206,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { error: activeError, } = useQuery({ queryKey: keys.exchanges.document(activeKey), - queryFn: () => api.getExchangeDocument(activeKey!), + queryFn: () => source.readDocument(activeKey!), enabled: activeKey !== null, // A file the bucket deleted stays deleted; asking again only keeps "Loading…" up for the backoff. retry: (failures, error) => @@ -212,7 +215,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { // The same query the chain below reads, so asking here costs nothing extra - and only asked // for at all when the row says there is a chain to read. - const { data: chain } = useQuery({ ...retryTreeQuery(x.id), enabled: hasRetryChain(x) }); + const { data: chain } = useQuery({ ...retryTreeQuery(x.id, source), enabled: hasRetryChain(x) }); const newest = chain ? newestAttempt(chain, x.id) : null; const [confirming, setConfirming] = useState(false); @@ -222,7 +225,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { const invalidate = () => void queryClient.invalidateQueries({ queryKey: keys.exchanges.all }); const retry = useMutation({ - mutationFn: (reset: boolean) => api.retryExchange(x.id, { reset }), + mutationFn: (reset: boolean) => source.retryExchange(x.id, reset), onSuccess: ({ id }) => { setConfirming(false); setStartedId(id); @@ -310,7 +313,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { {x.exception && ( } + action={!partner && (x.status === "failed" || x.status === "badResponse") && } /> )} @@ -357,7 +360,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { {x.correlationId ? ( @@ -371,10 +374,10 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { - Retries & aggregation family + {partner ? "Its retries" : <>Retries & aggregation family} {isRollUp && ( @@ -452,10 +455,13 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { scheduled for {formatDateTime(x.scheduledRetryOn)} - + {/* Ours to hurry along, not a partner's. */} + {!partner && ( + + )} ) : ( (x.status === "failed" || x.status === "badResponse") && @@ -468,7 +474,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { {newest && newest.id !== x.id && ( Open the newest attempt to retry from there @@ -487,7 +493,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { )} {/* A bad response can come without error text: then Explain has no error box to sit on. */} - {!x.exception && (x.status === "failed" || x.status === "badResponse") && ( + {!partner && !x.exception && (x.status === "failed" || x.status === "badResponse") && (
    @@ -496,6 +502,7 @@ export function ExchangeDrawer({ x }: { x: ExchangeRow }) { {confirming && ( retry.mutate(reset)} onClose={() => setConfirming(false)} diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeList.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeList.tsx index 4bd7c007..e560cc91 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeList.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangeList.tsx @@ -1,5 +1,4 @@ import { useEffect, useState } from "react"; -import { Link } from "react-router"; import { useQueryClient } from "@tanstack/react-query"; import { Loader2 } from "lucide-react"; import type { ExchangeRow } from "../../api"; @@ -10,6 +9,7 @@ import { PromotedProps } from "../../components/config/shared"; import { clickableRow, clickableRowClass } from "../../components/ui/clickableRow"; import { duration, formatDateTime, timeAgo, timeUntil } from "../../lib/dates"; import { hasRetryChain, retryTreeQuery } from "./retryTree"; +import { OurPageLink, useExchangeSource } from "./exchangeSource"; import { journeyStages, journeySummary } from "./journey"; import { JourneyStrip, StatusBadge, WarningBadge } from "./shared"; @@ -68,12 +68,13 @@ export function ExchangeList({ }) { const queryClient = useQueryClient(); const narrow = useNarrow(); + const source = useExchangeSource(); /* Hovering a row is most of a second's head start on opening it, which is enough that its retry chain is already there when the panel renders. Only for rows that have one - most exchanges do not. */ const prefetch = (x: ExchangeRow) => { - if (hasRetryChain(x)) void queryClient.prefetchQuery(retryTreeQuery(x.id)); + if (hasRetryChain(x)) void queryClient.prefetchQuery(retryTreeQuery(x.id, source)); }; const markers = (x: ExchangeRow) => ( @@ -185,13 +186,13 @@ export function ExchangeList({ {/* Only the links swallow the click, never the cells: an opted-out cell would leave part of a clickable row doing nothing when clicked. */} - e.stopPropagation()} className="font-mono text-[11px] text-ink-600 hover:link" > {x.informationTypeCode} - + {/* Beside the open exchange there is no Route column, so the route rides along here instead of disappearing. */} {compact && ( @@ -229,24 +230,24 @@ export function ExchangeList({ {x.subscriptionName ? ( - e.stopPropagation()} className="font-medium text-ink-800 hover:link" > {x.subscriptionName} - + ) : ( - )} {x.partnerName && ( - e.stopPropagation()} className="text-xs text-ink-500 hover:link" > {x.partnerName} - + )} diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangesPage.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangesPage.tsx index 12aaf798..a37af55c 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangesPage.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/ExchangesPage.tsx @@ -10,6 +10,7 @@ import { type ExportFilesCheck, } from "../../api"; import { Can } from "../../auth/guards"; +import { useSessionCan } from "../../auth/useSessionCan"; import { PageHeader } from "../../components/layout/PageHeader"; import { useBackgroundProgress } from "../../lib/useBackground"; import { followDownload } from "../../lib/saveFile"; @@ -21,6 +22,7 @@ import { timeAgo } from "../../lib/dates"; import { keys } from "../../api/queryKeys"; import { NONE } from "../../lib/none"; import { RetryDialog } from "./shared"; +import { useExchangeSource } from "./exchangeSource"; import { ExchangeList } from "./ExchangeList"; import { ExchangeDetailPanel } from "./ExchangeDetailPanel"; import { AskedLine, type AskedQuestion } from "./AskExchanges"; @@ -82,6 +84,8 @@ const shortcutsBlocked = (e: KeyboardEvent) => { }; export function ExchangesPage() { + const source = useExchangeSource(); + const { partner } = source; const [searchParams, setSearchParams] = useSearchParams(); const query = useMemo(() => readQuery(searchParams), [searchParams]); const [refreshMs, setRefreshMs] = useState(15_000); @@ -113,7 +117,7 @@ export function ExchangesPage() { // counts below, which can take far longer to work out on a busy instance. const { data, isLoading, isFetching, isPlaceholderData, isError, error, dataUpdatedAt, refetch } = useQuery({ queryKey: keys.exchanges.search(viewSearch(searchParams) + `&offset=${query.offset}`), - queryFn: () => api.searchExchanges(readQuery(searchParams), { count: false }), + queryFn: () => source.searchExchanges(readQuery(searchParams), { count: false }), // A list that failed with nothing to show waits for Try again: asked every 15s, a timeout kept // the database busy with the same query for as long as the page stayed open. refetchInterval: (q) => (q.state.status === "error" && q.state.data === undefined ? false : refreshMs || false), @@ -140,23 +144,24 @@ export function ExchangesPage() { keepCounted(previous as ExchangeBreakdown | undefined, next as ExchangeBreakdown); const breakdown = useQuery({ queryKey: keys.exchanges.breakdown(breakdownKey), - queryFn: () => api.getExchangeBreakdown(readQuery(searchParams)), + queryFn: () => source.getExchangeBreakdown(readQuery(searchParams)), refetchInterval: askAgain, placeholderData: keepPreviousData, structuralSharing: keepNumbers, retry: false, }); - const chartParams = timed ? null : withParams(searchParams, { range: "24h", status: null }); + // No chart for a partner's people, yet: the list and its counts are what they came for. + const chartParams = timed || partner ? null : withParams(searchParams, { range: "24h", status: null }); const chartBreakdown = useQuery({ queryKey: keys.exchanges.breakdown(chartParams ? viewSearch(chartParams) : ""), - queryFn: () => api.getExchangeBreakdown(readQuery(chartParams!)), + queryFn: () => source.getExchangeBreakdown(readQuery(chartParams!)), enabled: !!chartParams, refetchInterval: askAgain, placeholderData: keepPreviousData, structuralSharing: keepNumbers, retry: false, }); - const volume = timed ? breakdown.data : chartBreakdown.data; + const volume = partner ? undefined : timed ? breakdown.data : chartBreakdown.data; // Now, rather than at the next tick - or at all, paused. The counts and the chart come along so // they never disagree with the rows. The chart's query is off when the list is timed, and a @@ -169,10 +174,31 @@ export function ExchangesPage() { }; const rangeEndsNow = !searchParams.get("to") && searchParams.get("range") !== "yesterday"; - const subscriptions = useSubscriptionsCache().data ?? []; - const partners = useQuery({ queryKey: keys.partners.list, queryFn: () => api.listPartners() }).data ?? []; - const infoTypes = - useQuery({ queryKey: keys.informationTypes.list, queryFn: () => api.listInformationTypes() }).data ?? NONE; + // What the filters pick from. A partner's people may list neither our subscriptions nor our + // information types, so theirs come from the portal: only what runs for them. + const canPortalSubscriptions = useSessionCan("portal-subscriptions.view"); + const staffSubscriptions = useSubscriptionsCache(!partner).data; + const portalSubscriptions = useQuery({ + queryKey: keys.portal.subscriptions, + queryFn: () => api.listPortalSubscriptions(), + enabled: partner && canPortalSubscriptions, + }).data; + const subscriptions = partner + ? (portalSubscriptions ?? []).map((s) => ({ id: Number(s.id), name: s.name })) + : (staffSubscriptions ?? []); + const partners = + useQuery({ queryKey: keys.partners.list, queryFn: () => api.listPartners(), enabled: !partner }).data ?? []; + const staffInfoTypes = useQuery({ + queryKey: keys.informationTypes.list, + queryFn: () => api.listInformationTypes(), + enabled: !partner, + }).data; + const portalInfoTypes = useQuery({ + queryKey: keys.portal.informationTypes, + queryFn: () => api.listPortalInformationTypes(), + enabled: partner, + }).data; + const infoTypes = (partner ? portalInfoTypes : staffInfoTypes) ?? NONE; /** * Every promoted key any information type declares, with the types that declare it. @@ -247,7 +273,7 @@ export function ExchangesPage() { // Opened from a link, or kept open while the page moved on: fetched on its own. const openElsewhere = useQuery({ queryKey: keys.exchanges.search(`open=${openId}`), - queryFn: () => api.searchExchanges({ ids: openId!, offset: 0, limit: 10 }), + queryFn: () => source.searchExchanges({ ids: openId!, offset: 0, limit: 10 }), enabled: !!openId && !openOnPage && !isLoading, }); const openRow = openOnPage ?? openElsewhere.data?.result.find((r) => r.id === openId) ?? null; @@ -305,7 +331,7 @@ export function ExchangesPage() { const next = rows[Math.max(0, Math.min(rows.length - 1, at))]; setOpen(next.id); document.querySelector(`[data-row-id="${next.id}"]`)?.scrollIntoView?.({ block: "nearest" }); - } else if (e.key === "x" && openId) { + } else if (e.key === "x" && openId && !partner) { e.preventDefault(); toggleSelected(openId); } @@ -322,7 +348,7 @@ export function ExchangesPage() { queryFn: () => { const after = new Date(new Date(newest!).getTime() + 1); const from = query.from && new Date(query.from) > after ? query.from : after.toISOString(); - return api.searchExchanges({ ...readQuery(searchParams), from, offset: 0, limit: 1 }); + return source.searchExchanges({ ...readQuery(searchParams), from, offset: 0, limit: 1 }); }, enabled: watchNew, refetchInterval: watchNew ? 15_000 : false, @@ -403,8 +429,12 @@ export function ExchangesPage() {
    @@ -757,6 +787,23 @@ export function ExchangesPage() { ); } +const PARTNER_HELP = { + title: "What's on this page?", + body: ( + <> +

    + Each row is one exchange: a message that ran for your company. Retrying one creates a new + exchange in the same chain, so one piece of work can show up as several rows.{" "} + Latest attempt only hides the attempts that have since been retried. +

    +

    + The status buttons count your exchanges under every other filter. Search by a value your documents carry, such + as an order number, to find one. +

    + + ), +}; + function Kbd({ children }: { children: string }) { return {children}; } diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/QueryBar.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/QueryBar.tsx index c2a1a37b..d134a596 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/QueryBar.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/QueryBar.tsx @@ -3,6 +3,7 @@ import { Bookmark, Check, ChevronDown, Clock, Link as LinkIcon, Plus, Search, Tr import { SearchSelect, type SearchSelectOption } from "../../components/ui/SearchSelect"; import { Button } from "../../components/ui/basics"; import { AskButton, type AskedQuestion } from "./AskExchanges"; +import { useExchangeSource } from "./exchangeSource"; import { Dropdown } from "./Dropdown"; import { BUILT_IN_VIEWS, @@ -54,6 +55,8 @@ export function QueryBar({ onAsked: (asked: AskedQuestion) => void; }) { const chips = filterChips(searchParams, lookups); + // A partner's people ask no AI about our traffic: Ask reads every exchange. + const { partner } = useExchangeSource(); return (
    @@ -67,7 +70,7 @@ export function QueryBar({
    - + {!partner && }
    ); } @@ -648,6 +651,7 @@ function AddFilterMenu({ const [open, setOpen] = useState(false); const needle = find.trim().toLowerCase(); const matches = (text: string) => !needle || text.toLowerCase().includes(needle); + const { hiddenFilters } = useExchangeSource(); const propertyKeys = options.propertyKeys.filter((o) => matches(o.label) || matches(o.sublabel ?? "")); const close = () => { @@ -706,7 +710,7 @@ function AddFilterMenu({
    {MENU.map((g, i) => { - const items = g.items.filter((it) => matches(it.label)); + const items = g.items.filter((it) => matches(it.label) && !hiddenFilters.has(it.kind)); const groupNode = items.length > 0 && (

    {g.group}

    @@ -783,7 +787,11 @@ function SearchField({ searchParams, apply }: { searchParams: URLSearchParams; a const [text, setText] = useState(""); const [active, setActive] = useState(0); const [focused, setFocused] = useState(false); - const suggestions = useMemo(() => searchSuggestions(text, searchParams), [text, searchParams]); + const { hiddenFilters } = useExchangeSource(); + const suggestions = useMemo( + () => searchSuggestions(text, searchParams).filter((s) => !(s.key === "error" && hiddenFilters.has("error"))), + [text, searchParams, hiddenFilters], + ); const inputRef = useRef(null); const listId = useId(); const open = focused && suggestions.length > 0; diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/RetryChain.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/RetryChain.tsx index 1107b5da..bc9227ee 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/RetryChain.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/RetryChain.tsx @@ -7,6 +7,7 @@ import { namesSomething } from "../../components/config/subscriptionLabels"; import { timeAgo, timeUntil } from "../../lib/dates"; import { StatusBadge } from "./shared"; import { retryTreeQuery } from "./retryTree"; +import { useExchangeSource } from "./exchangeSource"; const childrenOf = (tree: RetryTree, id: string | null) => tree.attempts @@ -27,6 +28,7 @@ function Attempt({ const isCurrent = node.id === currentId; const children = childrenOf(tree, node.id); const navigate = useNavigate(); + const { listPath } = useExchangeSource(); return ( <> @@ -34,7 +36,7 @@ function Attempt({ // The whole row opens the attempt, the way a row of the exchange list opens its own // drawer - the identity on the right can no longer be a link itself, since promoted // properties bring a panel of their own and a button cannot sit inside a link. - onClick={isCurrent ? undefined : () => navigate(`/exchanges?ids=${encodeURIComponent(node.id)}`)} + onClick={isCurrent ? undefined : () => navigate(`${listPath}?ids=${encodeURIComponent(node.id)}`)} className={`flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md px-2 py-1.5 ${ isCurrent ? "bg-ink-100/70" : "cursor-pointer hover:bg-ink-50" }`} @@ -51,7 +53,7 @@ function Attempt({ ) : ( @@ -124,7 +126,7 @@ const ordinal = (n: number) => { * rule was enforced can fork, and those show as branches rather than being hidden. */ export function RetryChain({ id }: { id: string }) { - const { data: tree, isLoading } = useQuery(retryTreeQuery(id)); + const { data: tree, isLoading } = useQuery(retryTreeQuery(id, useExchangeSource())); // A line rather than a spinner block: this sits inside an already-rendered drawer, and it is // usually filled in before anyone looks at it - the row is prefetched on hover. diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/exchangeSource.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/exchangeSource.tsx new file mode 100644 index 00000000..dde60f3a --- /dev/null +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/exchangeSource.tsx @@ -0,0 +1,105 @@ +import { createContext, useContext, useMemo, type MouseEvent, type ReactNode } from "react"; +import { Link } from "react-router"; +import { api, type ExchangeBreakdown, type ExchangeQuery, type ExchangeRow, type Paged, type RetryTree } from "../../api"; +import { useSessionCan } from "../../auth/useSessionCan"; +import type { FilterKind } from "./exchangeFilters"; + +/** + * Where the Exchanges page reads from, and what it offers. Our team's: every exchange, through the + * staff API, with every tool. A partner's people's (`partner`): their own, through the portal's API, + * which limits and strips them on the server; the page then leaves out our tools and the links into + * our pages. One page for both, so the portal shows exchanges exactly as Bitween does. + */ +export interface ExchangeSource { + partner: boolean; + /** Where the list lives, for a link to an exchange or a chain. */ + listPath: string; + searchExchanges(query: ExchangeQuery, opts?: { count?: boolean }): Promise>; + getExchangeBreakdown(query: ExchangeQuery): Promise; + /** A file's content, by the key its row carries: a storage key for us, a signed link for them. */ + readDocument(key: string): Promise; + getRetryTree(id: string): Promise; + /** May retry, and may choose to reset to the current settings; a partner's always does. */ + canRetry: boolean; + canChooseReset: boolean; + retryExchange(id: string, reset: boolean): Promise<{ id: string }>; + /** Filters not offered. */ + hiddenFilters: ReadonlySet; +} + +const Context = createContext(null); + +export function useExchangeSource(): ExchangeSource { + const partner = useContext(Context); + const canRetry = useSessionCan("exchanges.operate"); + const staff = useMemo( + () => ({ + partner: false, + listPath: "/exchanges", + searchExchanges: (query, opts) => api.searchExchanges(query, opts), + getExchangeBreakdown: (query) => api.getExchangeBreakdown(query), + readDocument: (key) => api.getExchangeDocument(key), + getRetryTree: (id) => api.getRetryTree(id), + canRetry, + canChooseReset: true, + retryExchange: (id, reset) => api.retryExchange(id, { reset }), + hiddenFilters: new Set(), + }), + [canRetry], + ); + return partner ?? staff; +} + +/** + * A link into one of our own pages, such as a subscription or a partner. A partner's people can't + * open those, so it is the same text without the link for them. + */ +export function OurPageLink({ + to, + className = "", + title, + onClick, + children, +}: { + to: string; + className?: string; + title?: string; + onClick?: (e: MouseEvent) => void; + children: ReactNode; +}) { + const { partner } = useExchangeSource(); + if (partner) + return ( + + {children} + + ); + return ( + + {children} + + ); +} + +/** The page, and everything it opens, as a partner's people see it. */ +export function PartnerExchangeSource({ children }: { children: ReactNode }) { + const canRetry = useSessionCan("portal-exchanges.operate"); + const canErrors = useSessionCan("portal-exchange-errors.view"); + const value = useMemo( + () => ({ + partner: true, + listPath: "/portal", + searchExchanges: (query, opts) => api.searchExchanges(query, { ...opts, portal: true }), + getExchangeBreakdown: (query) => api.getExchangeBreakdown(query, { portal: true }), + readDocument: (url) => api.readExchangeFileLink(url), + getRetryTree: (id) => api.getRetryTree(id, { portal: true }), + canRetry, + canChooseReset: false, + retryExchange: async (id) => ({ id: await api.retryPortalExchange(id) }), + // Always their own partner; runs and roll-ups are our wiring; errors only when their role shows them. + hiddenFilters: new Set(["partner", "receiveAttempt", "aggregated", ...(canErrors ? [] : ["error" as const])]), + }), + [canRetry, canErrors], + ); + return {children}; +} diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/retryTree.ts b/SW.Bitween.Web/ClientApp/src/pages/exchanges/retryTree.ts index 7203febc..5ec79b2d 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/retryTree.ts +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/retryTree.ts @@ -1,4 +1,4 @@ -import { api, type RetryTree, type RetryTreeNode } from "../../api"; +import { type RetryTree, type RetryTreeNode } from "../../api"; import { keys } from "../../api/queryKeys"; /** @@ -9,9 +9,10 @@ import { keys } from "../../api/queryKeys"; export const hasRetryChain = (x: { retryFor: string | null; hasRetry: boolean }) => x.retryFor !== null || x.hasRetry; -export const retryTreeQuery = (id: string) => ({ - queryKey: keys.exchanges.retryTree(id), - queryFn: () => api.getRetryTree(id), +/** From where the page reads (`ExchangeSource`): our team's chain, or a partner's own attempts. */ +export const retryTreeQuery = (id: string, source: { partner: boolean; getRetryTree: (id: string) => Promise }) => ({ + queryKey: [...keys.exchanges.retryTree(id), source.partner ? "partner" : "staff"], + queryFn: () => source.getRetryTree(id), /** * A chain is settled history above the exchange asked about and only ever grows below it, so * a held copy cannot be wrong about what it shows - at worst it is missing an attempt someone diff --git a/SW.Bitween.Web/ClientApp/src/pages/exchanges/shared.tsx b/SW.Bitween.Web/ClientApp/src/pages/exchanges/shared.tsx index 69ae5167..4f892b44 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/exchanges/shared.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/exchanges/shared.tsx @@ -160,6 +160,7 @@ export function RetryDialog({ error = null, onConfirm, onResetChange, + chooseReset = true, onClose, }: { count: number; @@ -177,6 +178,8 @@ export function RetryDialog({ * for an exchange whose subscription is gone - so the caller has to be able to ask again. */ onResetChange?: (reset: boolean) => void; + /** Whether the current settings may be chosen instead of the captured ones; a partner's always uses them. */ + chooseReset?: boolean; onClose: () => void; }) { const [reset, setReset] = useState(false); @@ -291,7 +294,7 @@ export function RetryDialog({ )} {/* Not once it's under way: it keeps the choice it started with. */} - {!progress && ( + {!progress && chooseReset && ( + + +
    + ); +} diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalExchangesPage.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalExchangesPage.tsx new file mode 100644 index 00000000..716e4fef --- /dev/null +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalExchangesPage.tsx @@ -0,0 +1,14 @@ +import { ExchangesPage } from "../exchanges/ExchangesPage"; +import { PartnerExchangeSource } from "../exchanges/exchangeSource"; + +/** + * A partner's people's Exchanges page: Bitween's own, reading their exchanges through the portal's + * API, without our tools and the links into our pages. + */ +export function PortalExchangesPage() { + return ( + + + + ); +} diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingPage.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingPage.tsx index 37ee5a8e..44b4ce2f 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingPage.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingPage.tsx @@ -1,10 +1,11 @@ import { useMemo, useState } from "react"; -import { Link, useParams } from "react-router"; +import { useParams } from "react-router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft } from "lucide-react"; import { api } from "../../api"; import { keys } from "../../api/queryKeys"; import { useSession } from "../../auth/useSession"; +import { PageHeader } from "../../components/layout/PageHeader"; +import { usePageTitle } from "../../lib/pageTitle"; import { useSessionCan } from "../../auth/useSessionCan"; import { Badge, Button, FormError, LoadError, LoadingBlock } from "../../components/ui/basics"; import { Select } from "../../components/ui/forms"; @@ -28,6 +29,7 @@ export function PortalMappingPage() { const [sample, setSample] = useState(null); const mapping = useQuery({ queryKey: keys.portal.mapping(id), queryFn: () => api.getPortalMapping(id) }); + usePageTitle(mapping.data?.subscriptionName); const samples = useQuery({ queryKey: keys.portal.samples(id), queryFn: () => api.listPortalMappingSamples(id), @@ -80,19 +82,8 @@ export function PortalMappingPage() { .sort((a, b) => b.submittedAt - a.submittedAt)[0]?.data; return ( -
    -
    - - - Back to the portal - -
    -

    {m.subscriptionName}

    -

    {session?.partner?.name} · Mapping

    -
    -
    - -
    +
    +

    What you receive

    @@ -210,7 +201,6 @@ export function PortalMappingPage() { )}
    -
    {editing && ( diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingsPage.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingsPage.tsx new file mode 100644 index 00000000..351e51df --- /dev/null +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalMappingsPage.tsx @@ -0,0 +1,72 @@ +import { useNavigate } from "react-router"; +import { useQuery } from "@tanstack/react-query"; +import { api, type PortalMappingPlace } from "../../api"; +import { keys } from "../../api/queryKeys"; +import { PageHeader } from "../../components/layout/PageHeader"; +import { Badge, EmptyState, LoadError, LoadingBlock } from "../../components/ui/basics"; +import { Table } from "../../components/ui/Table"; +import { formatDateTime, timeAgo } from "../../lib/dates"; + +function MappingBadges({ m }: { m: PortalMappingPlace }) { + return ( + + {m.waiting && ( + + Waiting + + )} + {m.setAside ? ( + + Set aside + + ) : m.customized ? ( + + Yours + + ) : ( + Ours + )} + + ); +} + +/** Every place they're connected, and whether what they receive there is shaped their own way. */ +export function PortalMappingsPage() { + const navigate = useNavigate(); + const mappings = useQuery({ queryKey: keys.portal.mappings, queryFn: () => api.listPortalMappings() }); + + return ( +
    + + {mappings.isPending ? ( + + ) : mappings.isError ? ( + void mappings.refetch()} /> + ) : mappings.data.length === 0 ? ( + When something runs for your company, it shows here. + ) : ( + m.subscriptionId} + onRowClick={(m) => void navigate(`/portal/mappings/${m.subscriptionId}`)} + columns={[ + { header: "Subscription", wrap: true, cell: (m) => {m.subscriptionName} }, + { header: "How you're connected", headerTitle: "Your own subscription, an API gateway, or a bus gateway route", cell: (m) => m.via }, + { header: "Information type", cell: (m) => m.documentName }, + { header: "Mapping", headerTitle: "Ours, or your own version", cell: (m) => }, + { + header: "Changed", + headerTitle: "When your own version last changed", + align: "right", + cell: (m) => (m.modifiedOn ? {timeAgo(m.modifiedOn)} : "-"), + }, + ]} + card={(m) => ({ title: m.subscriptionName, status: , subtitle: `${m.via} · ${m.documentName}` })} + /> + )} + + ); +} diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPage.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPage.tsx deleted file mode 100644 index 74b80bc6..00000000 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPage.tsx +++ /dev/null @@ -1,401 +0,0 @@ -import { useState } from "react"; -import { Link } from "react-router"; -import { keepPreviousData, useQuery } from "@tanstack/react-query"; -import { Download, ExternalLink, Inbox, LogOut } from "lucide-react"; -import { api, type PortalExchange, type PortalExchangeStatus } from "../../api"; -import { keys } from "../../api/queryKeys"; -import { useSession } from "../../auth/useSession"; -import { useSessionCan } from "../../auth/useSessionCan"; -import { Badge, Button, EmptyState, LoadError, LoadingBlock } from "../../components/ui/basics"; -import { ExceptionBlock } from "../../components/ui/Exception"; -import { Select } from "../../components/ui/forms"; -import { Dialog } from "../../components/ui/overlays"; -import { Panel } from "../../components/ui/Panel"; -import { SegmentedControl } from "../../components/ui/SegmentedControl"; -import { duration, formatDateTime, timeAgo } from "../../lib/dates"; -import { bytes, whole } from "../../lib/numbers"; -import { XchangeId } from "../exchanges/shared"; -import { YourDetails } from "./YourDetails"; - -const PAGE_SIZE = 25; - -const STATUS: Record = { - success: { label: "Delivered", tone: "ok", title: "Finished without an error." }, - failed: { label: "Failed", tone: "danger", title: "Finished with an error. Open it to see why, if your role shows errors." }, - running: { label: "Running", tone: "neutral", title: "Started and not finished yet." }, -}; - -const FILE_LABELS: Record = { - input: { label: "Received", title: "What came in, before any mapping." }, - output: { label: "Sent", title: "What was delivered, after mapping." }, - response: { label: "Response", title: "What the receiving system answered." }, -}; - -/** - * The partner portal: the one page a partner's person sees. Their subscriptions and exchanges only; - * the server scopes every call to their partner, so nothing here has to filter. - */ -export function PortalPage() { - const { session, signOut } = useSession(); - const canExchanges = useSessionCan("portal-exchanges.view"); - const canSubscriptions = useSessionCan("portal-subscriptions.view"); - const canMappings = useSessionCan("portal-mappings.view"); - const canManagePeople = useSessionCan("portal-people.edit"); - const canDetails = useSessionCan("portal-properties.view"); - const canPeople = useSessionCan("portal-people.view") || canManagePeople; - - return ( -
    -
    - -
    -

    {session?.partner?.name}

    -

    - Partner portal -

    -
    - {canPeople && ( - - People - - )} - {session?.user.displayName} - - Password - - -
    - -
    - {!canExchanges && !canSubscriptions && !canMappings && !canDetails ? ( - } title="Nothing to show yet"> - Your role doesn't include anything to see here. Ask whoever set up your account to give you a role. - - ) : ( - <> - {canExchanges && } -
    - {canExchanges ? :
    } -
    - {canDetails && } - {canMappings && } - {canSubscriptions && } -
    -
    - - )} -
    -
    - ); -} - -function Summary() { - const summary = useQuery({ queryKey: keys.portal.summary, queryFn: () => api.getPortalSummary(), refetchInterval: 60_000 }); - if (summary.isError) return void summary.refetch()} />; - const tiles = [ - { label: "Delivered", value: summary.data?.succeeded, title: "Exchanges in the last 24 hours that finished without an error." }, - { label: "Failed", value: summary.data?.failed, title: "Exchanges in the last 24 hours that finished with an error." }, - { label: "Running", value: summary.data?.running, title: "Exchanges in the last 24 hours that haven't finished yet." }, - ]; - return ( -
    - {tiles.map((t) => ( -
    -
    {t.label} · 24 h
    -
    {t.value == null ? "-" : whole(t.value)}
    -
    - ))} -
    - ); -} - -function Mappings() { - const mappings = useQuery({ queryKey: keys.portal.mappings, queryFn: () => api.listPortalMappings() }); - return ( - - {mappings.isPending ? ( - - ) : mappings.isError ? ( - void mappings.refetch()} /> - ) : mappings.data.length === 0 ? ( -

    Nothing is connected to you yet.

    - ) : ( -
      - {mappings.data.map((m) => ( -
    • - -
      -
      - {m.subscriptionName} -
      -
      - {m.via} -
      -
      - {m.waiting && ( - - Waiting - - )} - {m.setAside ? ( - - Set aside - - ) : m.customized ? ( - - Yours - - ) : ( - Ours - )} - -
    • - ))} -
    - )} -
    - ); -} - -function Subscriptions() { - const subscriptions = useQuery({ queryKey: keys.portal.subscriptions, queryFn: () => api.listPortalSubscriptions() }); - return ( - - {subscriptions.isPending ? ( - - ) : subscriptions.isError ? ( - void subscriptions.refetch()} /> - ) : subscriptions.data.length === 0 ? ( -

    None yet.

    - ) : ( -
      - {subscriptions.data.map((s) => ( -
    • -
      -
      - {s.name} -
      -
      - {s.documentName} -
      -
      - {s.paused && ( - - Paused - - )} -
    • - ))} -
    - )} -
    - ); -} - -function Exchanges() { - const canSubscriptions = useSessionCan("portal-subscriptions.view"); - const [status, setStatus] = useState("all"); - const [subscriptionId, setSubscriptionId] = useState(""); - const [page, setPage] = useState(0); - // Kept as the row opened, and followed as the list refreshes: an exchange opened while running - // shows its result once it has one. Off the page after a refresh, the last copy stays open. - const [opened, setOpen] = useState(null); - - const query = { status: status === "all" ? null : status, subscriptionId: subscriptionId || null, page, size: PAGE_SIZE }; - const exchanges = useQuery({ - queryKey: keys.portal.exchanges(query), - queryFn: () => api.searchPortalExchanges(query), - placeholderData: keepPreviousData, - refetchInterval: page === 0 ? 30_000 : false, - }); - const subscriptions = useQuery({ - queryKey: keys.portal.subscriptions, - queryFn: () => api.listPortalSubscriptions(), - enabled: canSubscriptions, - }); - - return ( - - { - setStatus(v); - setPage(0); - }} - options={[ - { value: "all", label: "All", title: "Every exchange" }, - { value: "failed", label: "Failed", title: STATUS.failed.title }, - { value: "running", label: "Running", title: STATUS.running.title }, - { value: "success", label: "Delivered", title: STATUS.success.title }, - ]} - /> - {/* Still shown while a filter is on, even if the list has shrunk, so it can be cleared. */} - {canSubscriptions && ((subscriptions.data?.length ?? 0) > 1 || subscriptionId !== "") && ( -
    -
    - - - - - - - - - - - {exchanges.data.result.map((x) => ( - setOpen(x)} - className="cursor-pointer border-b border-ink-100 hover:bg-ink-50 focus-within:bg-ink-50" - > - - - - - - - ))} - -
    StartedStatusSubscriptionInformation typeTook
    - {/* The row is a shortcut for the mouse; this is the control, for everyone. */} - - - - {STATUS[x.status].label} - - {x.subscriptionName ?? "-"}{x.documentName} - {x.finishedOn ? duration(x.startedOn, x.finishedOn) : "-"} -
    -
    - )} - {exchanges.data && (page > 0 || exchanges.data.hasMore) && ( -
    - {/* Off while the next page loads: the rows and "more" shown are still the last page's. */} - - Page {page + 1} - -
    - )} - {opened && ( - x.id === opened.id) ?? opened} onClose={() => setOpen(null)} /> - )} - - ); -} - -function ExchangeDialog({ x, onClose }: { x: PortalExchange; onClose: () => void }) { - return ( - -
    -
    Id
    -
    - -
    -
    Status
    -
    - - {STATUS[x.status].label} - -
    -
    Subscription
    -
    {x.subscriptionName ?? "-"}
    -
    Information type
    -
    {x.documentName}
    -
    Started
    -
    {formatDateTime(x.startedOn)}
    -
    Finished
    -
    - {x.finishedOn ? `${formatDateTime(x.finishedOn)} (took ${duration(x.startedOn, x.finishedOn)})` : "Not yet"} -
    -
    - - {x.error && ( -
    - -
    - )} - - {x.files && ( -
    -

    Files

    - {x.files.length === 0 ? ( -

    This exchange has no files.

    - ) : ( - - )} -
    - )} -
    - ); -} diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPeoplePage.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPeoplePage.tsx index 07b45940..e5a1b3f0 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPeoplePage.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/PortalPeoplePage.tsx @@ -1,16 +1,15 @@ import { useState } from "react"; -import { Link } from "react-router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, UserPlus } from "lucide-react"; +import { UserPlus } from "lucide-react"; import { api, type PortalInvite, type PortalPerson } from "../../api"; import { keys } from "../../api/queryKeys"; -import { useSession } from "../../auth/useSession"; import { useSessionCan } from "../../auth/useSessionCan"; import { Badge, Button, FormError, LoadError, LoadingBlock } from "../../components/ui/basics"; import { CopyField } from "../../components/ui/CopyField"; import { Field, Select, TextInput } from "../../components/ui/forms"; import { ConfirmDialog, Dialog } from "../../components/ui/overlays"; import { Panel } from "../../components/ui/Panel"; +import { PageHeader } from "../../components/layout/PageHeader"; import { Table } from "../../components/ui/Table"; import { formatDateTime, timeAgo } from "../../lib/dates"; @@ -20,7 +19,6 @@ import { formatDateTime, timeAgo } from "../../lib/dates"; * their admins, so another admin's row has nothing to change. */ export function PortalPeoplePage() { - const { session } = useSession(); const canEdit = useSessionCan("portal-people.edit"); const queryClient = useQueryClient(); const people = useQuery({ queryKey: keys.portal.people, queryFn: () => api.listPortalPeople() }); @@ -68,19 +66,8 @@ export function PortalPeoplePage() { ); return ( -
    -
    - - - Back to the portal - -
    -

    People

    -

    {session?.partner?.name} · Who can sign in to this portal

    -
    -
    - -
    +
    + )} -
    {adding && roles.data && ( api.listPortalSubscriptions() }); + const paused = (p: boolean) => + p ? ( + + Paused + + ) : ( + + Running + + ); + + return ( +
    + + {subscriptions.isPending ? ( + + ) : subscriptions.isError ? ( + void subscriptions.refetch()} /> + ) : subscriptions.data.length === 0 ? ( + When something runs for your company, it shows here. + ) : ( + s.id} + columns={[ + { header: "Name", wrap: true, cell: (s) => {s.name} }, + { header: "Information type", headerTitle: "The kind of information it carries", cell: (s) => s.documentName }, + { header: "State", headerTitle: "Running, or paused", align: "right", cell: (s) => paused(s.paused) }, + ]} + card={(s) => ({ title: s.name, status: paused(s.paused), subtitle: s.documentName })} + /> + )} + + ); +} diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/YourDetails.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/YourDetails.tsx index 380d8af9..df8ee6c3 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/YourDetails.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/YourDetails.tsx @@ -28,13 +28,13 @@ export function YourDetails() { if (details.isPending) return ( - + ); if (details.isError) return ( - + void details.refetch()} /> ); @@ -43,8 +43,8 @@ export function YourDetails() { const editable = d.properties.filter((p) => p.editable); return ( 0 && ( diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx new file mode 100644 index 00000000..cdace858 --- /dev/null +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx @@ -0,0 +1,129 @@ +import { cleanup, screen, waitFor, within } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { describe, expect, it } from "vitest"; +import { ALL_PERMISSIONS, apiPath, renderApp } from "../../../__tests__/support/renderApp"; + +const ACME = { id: 7, name: "Acme Freight" }; +const LOOK = ["portal-exchanges.view", "portal-exchange-files.view", "portal-exchange-errors.view", "portal-subscriptions.view"]; +const RETRY = [...LOOK, "portal-exchanges.operate"]; + +/** A row as the portal's search answers it: our team's row, stripped on the server. */ +const failed = { + id: "00000000-0000-4000-8000-000000000001", + subscriptionId: 3, + subscriptionName: "Acme webhook", + documentId: 5, + documentName: "SHIPMENT", + mapperId: "mapper", + status: false, + responseBad: null, + exception: "The remote server returned 500", + startedOn: "2026-11-24T10:00:00Z", + finishedOn: "2026-11-24T10:00:02Z", + inputFileName: "in.json", + inputFileSize: 12, + inputUrl: "https://bitween.test/api/files/seal/in", + outputFileSize: 0, + responseFileSize: 0, + promotedProperties: { orderNo: "A-1" }, + retryFor: null, + hasRetry: false, + aggregationXchangeId: null, + correlationId: null, + partnerId: 7, + scheduledRetryOn: null, +}; + +/** The portal's API, recording what the Exchanges page asked of it. */ +function portal(rows: unknown[] = [failed]) { + const asked: string[] = []; + const retried: unknown[] = []; + const handlers = [ + http.get(apiPath("/portal/xchangesearch"), ({ request }) => { + asked.push(new URL(request.url).search); + return HttpResponse.json({ result: rows, totalCount: rows.length }); + }), + http.get(apiPath("/portal/xchangesummary"), () => + HttpResponse.json({ counts: { processing: 0, success: 0, badResponse: 0, failed: rows.length }, buckets: [], bucketMinutes: 0 }), + ), + http.get(apiPath("/portal/subscriptions"), () => + HttpResponse.json([{ id: 3, name: "Acme webhook", type: "Internal", documentName: "SHIPMENT", paused: false }]), + ), + http.get(apiPath("/portal/informationtypes"), () => + HttpResponse.json([{ id: 5, name: "SHIPMENT", code: null, promotedPropertyKeys: ["orderNo"] }]), + ), + http.get("https://bitween.test/api/files/seal/in", () => HttpResponse.text('{"orderNo":"A-1"}')), + http.post(apiPath("/portal/retry"), async ({ request }) => { + retried.push(await request.json()); + return HttpResponse.json({ xchangeId: "00000000-0000-4000-8000-000000000002" }); + }), + ]; + return { handlers, asked, retried }; +} + +describe("the partner portal, in the app's own frame", () => { + it("lands a partner's person on their Exchanges, with only their pages in the sidebar", async () => { + const { handlers, asked } = portal(); + const { router } = renderApp("/exchanges", { as: { partner: ACME, permissions: RETRY }, handlers }); + + const nav = await screen.findByRole("navigation", { name: "Main" }); + await waitFor(() => expect(router.state.location.pathname).toBe("/portal")); + expect(within(nav).getByRole("link", { name: "Exchanges" })).toHaveAttribute("href", "/portal"); + expect(within(nav).getByRole("link", { name: "Subscriptions" })).toBeVisible(); + expect(within(nav).queryByRole("link", { name: "Partners" })).not.toBeInTheDocument(); + expect(await screen.findByText("Acme webhook")).toBeVisible(); + expect(asked.length).toBeGreaterThan(0); + }); + + it("takes a partner's person from a look-alike address to the portal", async () => { + for (const path of ["/portal-old", "/portal/nothing-here"]) { + const { router } = renderApp(path, { as: { partner: ACME, permissions: RETRY }, handlers: portal().handlers }); + await waitFor(() => expect(router.state.location.pathname).toBe("/portal")); + cleanup(); + } + }); + + it("keeps our own people out of the portal, and its pages out of their sidebar", async () => { + const { router } = renderApp("/portal", { handlers: portal().handlers, as: { permissions: ALL_PERMISSIONS } }); + const nav = await screen.findByRole("navigation", { name: "Main" }); + await waitFor(() => expect(router.state.location.pathname).not.toBe("/portal")); + expect(within(nav).queryByText("Partner portal")).not.toBeInTheDocument(); + }); + + it("opens an exchange with its document, error and Retry, and none of our tools", async () => { + const { handlers, retried } = portal(); + const { user } = renderApp("/portal", { as: { partner: ACME, permissions: RETRY }, handlers }); + + await user.click((await screen.findAllByText("Acme webhook"))[0]); + expect((await screen.findAllByText(/The remote server returned 500/)).length).toBeGreaterThan(1); + expect(await screen.findByText(/"orderNo"/)).toBeVisible(); + // No links into our pages, no bulk selection, no AI. + expect(screen.queryByRole("link", { name: "Acme webhook" })).not.toBeInTheDocument(); + expect(screen.queryByRole("checkbox")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /Explain/i })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /Ask/i })).not.toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: /Retry/ })); + // Always the current settings: no choice to make. + const dialog = await screen.findByRole("dialog", { name: "Retry this exchange?" }); + expect(within(dialog).queryByRole("checkbox")).not.toBeInTheDocument(); + await user.click(within(dialog).getByRole("button", { name: "Retry" })); + await waitFor(() => expect(retried).toEqual([{ xchangeId: failed.id }])); + }); + + it("offers no Retry to a role that may only look, and no filter on errors it can't read", async () => { + const { user } = renderApp("/portal", { + as: { partner: ACME, permissions: ["portal-exchanges.view"] }, + handlers: portal([{ ...failed, exception: null }]).handlers, + }); + await user.click((await screen.findAllByText("Acme webhook"))[0]); + await screen.findByText("Exchange id"); + expect(screen.queryByRole("button", { name: /Retry/ })).not.toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "Filter" })); + const menu = screen.getByRole("menu", { name: "Add a filter" }); + expect(within(menu).getByRole("menuitem", { name: "Subscription" })).toBeVisible(); + expect(within(menu).queryByRole("menuitem", { name: "Partner" })).not.toBeInTheDocument(); + expect(within(menu).queryByRole("menuitem", { name: /Error message/ })).not.toBeInTheDocument(); + }); +}); diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPage.test.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPage.test.tsx deleted file mode 100644 index c7500afb..00000000 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPage.test.tsx +++ /dev/null @@ -1,105 +0,0 @@ -import { cleanup, screen, waitFor, within } from "@testing-library/react"; -import { http, HttpResponse } from "msw"; -import { describe, expect, it } from "vitest"; -import { apiPath, renderApp } from "../../../__tests__/support/renderApp"; - -const ACME = { id: 7, name: "Acme Freight" }; -const EVERYTHING = [ - "portal-subscriptions.view", - "portal-exchanges.view", - "portal-exchange-files.view", - "portal-exchange-errors.view", -]; - -const failed = { - id: "x-failed-1", - startedOn: "2026-11-24T10:00:00Z", - finishedOn: "2026-11-24T10:00:02Z", - status: "failed", - documentName: "Shipment", - subscriptionId: 3, - subscriptionName: "Acme webhook", - error: "The remote server returned 500", - files: [{ kind: "input", name: "in.json", size: 120, url: "https://bitween.test/api/files/seal/in" }], -}; - -/** The portal's API, recording which exchange searches were asked for. */ -function portal(rows: unknown[] = [failed]) { - const searches: string[] = []; - const handlers = [ - http.get(apiPath("/portal/summary"), () => HttpResponse.json({ partnerName: ACME.name, running: 1, succeeded: 40, failed: 2 })), - http.get(apiPath("/portal/subscriptions"), () => - HttpResponse.json([ - { id: 3, name: "Acme webhook", type: "Internal", documentName: "Shipment", paused: false }, - { id: 4, name: "Acme pickups", type: "Receiving", documentName: "Pickup", paused: true }, - ]), - ), - http.get(apiPath("/portal/xchanges"), ({ request }) => { - searches.push(new URL(request.url).search); - return HttpResponse.json({ result: rows, hasMore: false }); - }), - ]; - return { handlers, searches }; -} - -describe("the partner portal", () => { - it("is where a partner's person lands, whatever page they asked for", async () => { - const { router } = renderApp("/exchanges", { as: { partner: ACME, permissions: EVERYTHING }, handlers: portal().handlers }); - - expect(await screen.findByRole("heading", { name: ACME.name })).toBeVisible(); - expect(router.state.location.pathname).toBe("/portal"); - // None of the app's own navigation is there to be tried. - expect(screen.queryByRole("navigation")).not.toBeInTheDocument(); - }); - - it("takes a partner's person from a look-alike address to the portal, never the app's frame", async () => { - for (const path of ["/portal-old", "/portal/nothing-here"]) { - const { router } = renderApp(path, { as: { partner: ACME, permissions: EVERYTHING }, handlers: portal().handlers }); - expect(await screen.findByRole("heading", { name: ACME.name })).toBeVisible(); - expect(router.state.location.pathname).toBe("/portal"); - expect(screen.queryByRole("navigation")).not.toBeInTheDocument(); - cleanup(); - } - }); - - it("sends our own people back to the app", async () => { - const { router } = renderApp("/portal", { handlers: portal().handlers }); - await screen.findByRole("navigation"); - expect(router.state.location.pathname).not.toBe("/portal"); - }); - - it("shows their exchanges and subscriptions, and an exchange's error and files", async () => { - const { handlers, searches } = portal(); - const { user } = renderApp("/portal", { as: { partner: ACME, permissions: EVERYTHING }, handlers }); - - const subscriptions = within((await screen.findByRole("heading", { name: "Subscriptions" })).closest("section")!); - expect(await subscriptions.findByText("Acme pickups")).toBeVisible(); - expect(subscriptions.getByText("Paused")).toBeVisible(); - expect(await screen.findByText("40")).toBeVisible(); - - await user.click(await screen.findByRole("button", { name: /Open the exchange of/ })); - const dialog = within(screen.getByRole("dialog", { name: "Exchange" })); - expect(dialog.getByText(/The remote server returned 500/)).toBeVisible(); - expect(dialog.getByRole("link", { name: "Download Received" })).toHaveAttribute("href", failed.files[0].url); - await user.click(dialog.getByRole("button", { name: /close/i })); - - await user.click(screen.getByRole("radio", { name: "Failed" })); - // The rows on screen are the last search's until the filtered one answers. - await waitFor(() => expect(searches.at(-1)).toContain("status=failed")); - }); - - it("shows only what the role allows", async () => { - renderApp("/portal", { - as: { partner: ACME, permissions: ["portal-exchanges.view"] }, - handlers: portal([{ ...failed, error: null, files: null }]).handlers, - }); - - expect(await screen.findByRole("row", { name: /Acme webhook/ })).toBeVisible(); - expect(screen.queryByRole("heading", { name: "Subscriptions" })).not.toBeInTheDocument(); - }); - - it("says so when the role allows nothing", async () => { - renderApp("/portal", { as: { partner: ACME, permissions: [] }, handlers: portal().handlers }); - expect(await screen.findByText("Nothing to show yet")).toBeVisible(); - }); -}); diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPeople.test.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPeople.test.tsx index 63be0894..8f0de37b 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPeople.test.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalPeople.test.tsx @@ -85,12 +85,13 @@ describe("a partner's admin's people page", () => { await waitFor(() => expect(disabled).toEqual([{ accountId: 3, disabled: true }])); }); - it("is reached from the portal only by someone who may see their people", async () => { - renderApp("/portal", { + it("is in the sidebar only for someone who may see their people", async () => { + renderApp("/portal/mappings", { as: { partner: ACME, permissions: ["portal-mappings.view"] }, handlers: [http.get(apiPath("/portal/mappings"), () => HttpResponse.json([]))], }); - await screen.findByText("Partner portal"); - expect(screen.queryByRole("link", { name: "People" })).not.toBeInTheDocument(); + const nav = await screen.findByRole("navigation", { name: "Main" }); + expect(within(nav).getByRole("link", { name: "Mappings" })).toBeVisible(); + expect(within(nav).queryByRole("link", { name: "People" })).not.toBeInTheDocument(); }); }); diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/YourDetails.test.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/YourDetails.test.tsx index 115dd11b..1fbae236 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/YourDetails.test.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/YourDetails.test.tsx @@ -35,7 +35,7 @@ function backend(needsApproval = false) { describe("a partner's own details in the portal", () => { it("shows what we show them, a secret without its value, and changes only what they may", async () => { const { handlers, saved } = backend(); - const { user } = renderApp("/portal", { + const { user } = renderApp("/portal/details", { as: { partner: ACME, permissions: ["portal-properties.view", "portal-properties.edit"] }, handlers, }); @@ -56,7 +56,7 @@ describe("a partner's own details in the portal", () => { it("says a change waits for approval when their changes need it", async () => { const { handlers } = backend(true); - const { user } = renderApp("/portal", { + const { user } = renderApp("/portal/details", { as: { partner: ACME, permissions: ["portal-properties.view", "portal-properties.edit"] }, handlers, }); @@ -67,7 +67,7 @@ describe("a partner's own details in the portal", () => { }); it("can't be changed by a role that may only look", async () => { - renderApp("/portal", { as: { partner: ACME, permissions: ["portal-properties.view"] }, handlers: backend().handlers }); + renderApp("/portal/details", { as: { partner: ACME, permissions: ["portal-properties.view"] }, handlers: backend().handlers }); await screen.findByText("https://acme/in"); expect(screen.queryByRole("button", { name: "Change" })).not.toBeInTheDocument(); }); diff --git a/SW.Bitween.Web/ClientApp/src/pages/team/RoleEditor.tsx b/SW.Bitween.Web/ClientApp/src/pages/team/RoleEditor.tsx index ae19bfdb..d518b978 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/team/RoleEditor.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/team/RoleEditor.tsx @@ -29,8 +29,17 @@ import { usePageTitle } from "../../lib/pageTitle"; import { usePhone } from "../../lib/useMediaQuery"; /** Live answer to "what would someone with this role actually see?" */ -function AccessPreview({ permissions, total }: { permissions: Set; total: number }) { - const groups = visibleGroups([...permissions]); +function AccessPreview({ + permissions, + total, + partner = false, +}: { + permissions: Set; + total: number; + /** A partner role: their portal's sidebar, not ours. */ + partner?: boolean; +}) { + const groups = visibleGroups([...permissions], partner); return (

    @@ -442,7 +451,7 @@ export function RoleEditor() { whatever is ticked here. Nothing else in Bitween opens for them.

    ) : ( - + )} {/* A role that doesn't exist yet has no history, and a system role's grants are diff --git a/SW.Bitween.Web/ClientApp/src/routePages.tsx b/SW.Bitween.Web/ClientApp/src/routePages.tsx index 1bcad0bd..604e2a78 100644 --- a/SW.Bitween.Web/ClientApp/src/routePages.tsx +++ b/SW.Bitween.Web/ClientApp/src/routePages.tsx @@ -15,7 +15,12 @@ export const AdapterEditorPage = lazy(() => import("./pages/adapters/AdapterEdit export const AdaptersPage = lazy(() => import("./pages/adapters/AdaptersPage").then((m) => ({ default: m.AdaptersPage }))); export const PortalMappingPage = lazy(() => import("./pages/portal/PortalMappingPage").then((m) => ({ default: m.PortalMappingPage }))); export const PortalPeoplePage = lazy(() => import("./pages/portal/PortalPeoplePage").then((m) => ({ default: m.PortalPeoplePage }))); -export const PortalPage = lazy(() => import("./pages/portal/PortalPage").then((m) => ({ default: m.PortalPage }))); +export const PortalExchangesPage = lazy(() => import("./pages/portal/PortalExchangesPage").then((m) => ({ default: m.PortalExchangesPage }))); +export const PortalMappingsPage = lazy(() => import("./pages/portal/PortalMappingsPage").then((m) => ({ default: m.PortalMappingsPage }))); +export const PortalSubscriptionsPage = lazy(() => + import("./pages/portal/PortalSubscriptionsPage").then((m) => ({ default: m.PortalSubscriptionsPage })), +); +export const PortalDetailsPage = lazy(() => import("./pages/portal/PortalDetailsPage").then((m) => ({ default: m.PortalDetailsPage }))); export const ProfilePage = lazy(() => import("./pages/ProfilePage").then((m) => ({ default: m.ProfilePage }))); export const AuditPage = lazy(() => import("./pages/audit/AuditPage").then((m) => ({ default: m.AuditPage }))); export const NodesPage = lazy(() => import("./pages/nodes/NodesPage").then((m) => ({ default: m.NodesPage }))); diff --git a/SW.Bitween.Web/ClientApp/src/router.tsx b/SW.Bitween.Web/ClientApp/src/router.tsx index 51f0d074..87c1eae2 100644 --- a/SW.Bitween.Web/ClientApp/src/router.tsx +++ b/SW.Bitween.Web/ClientApp/src/router.tsx @@ -54,7 +54,10 @@ import { PartnerChangesPage, PortalMappingPage, PortalPeoplePage, - PortalPage, + PortalExchangesPage, + PortalMappingsPage, + PortalSubscriptionsPage, + PortalDetailsPage, ProfilePage, QueueHealthPage, ResponseSubscriptionsPage, @@ -115,6 +118,12 @@ const PAGE_ELEMENTS: Record = { partners: , partner: , partnerChanges: , + portalExchanges: , + portalMappings: , + portalMapping: , + portalSubscriptions: , + portalDetails: , + portalPeople: , dataSources: , dataSourceNew: , dataSource: , @@ -161,16 +170,18 @@ export interface PageHandle { const pageRoutes: RouteObject[] = (Object.keys(PAGES) as PageId[]).map((id) => { const { path, permission, alsoFor } = PAGES[id]; const element = PAGE_ELEMENTS[id]; + const guarded = permission ? ( + + {element} + + ) : ( + element + ); return { path, handle: { page: id } satisfies PageHandle, - element: permission ? ( - - {element} - - ) : ( - element - ), + // A partner's people's pages are theirs alone, whatever else a session holds. + element: PAGES[id].audience === "partner" ? {guarded} : guarded, }; }); @@ -205,40 +216,6 @@ export const routes: RouteObject[] = [ ), }, - // A partner's person sees this and nothing else; it has its own frame, without the app's - // sidebar, none of whose pages they may open. - { - path: PORTAL_PATH.slice(1), - element: , - children: [ - { - index: true, - element: ( - }> - - - ), - }, - { - path: "mappings/:subscriptionId", - element: ( - }> - - - ), - }, - { - path: "people", - element: ( - }> - - - ), - }, - // Anything else under /portal is not a page: back to the portal, never the app's frame. - { path: "*", element: }, - ], - }, { element: , children: [ @@ -247,6 +224,8 @@ export const routes: RouteObject[] = [ // itself is no longer a page - only a bookmark people may still hold. { path: "team", element: }, ...pageRoutes, + // Anything else under /portal is not a page: back to the portal's first page. + { path: "portal/*", element: }, { path: "*", element: }, ], }, diff --git a/docs/security.md b/docs/security.md index 086c9d25..4d12c8ac 100644 --- a/docs/security.md +++ b/docs/security.md @@ -100,7 +100,7 @@ A permission is written `area.action`. Every account, person or service account, | Administration | `adapter-source` | view, edit, operate | | Administration | `mirror` | view, operate | | Partner portal | `portal-subscriptions` | view | -| Partner portal | `portal-exchanges` | view | +| Partner portal | `portal-exchanges` | view, operate | | Partner portal | `portal-exchange-files` | view | | Partner portal | `portal-exchange-errors` | view | | Partner portal | `portal-mappings` | view, edit | @@ -141,10 +141,11 @@ A partner's own people can sign in and see their partner's data, and nothing els - **Partner accounts.** On the Members page, choose **A partner's person** when adding someone, and pick the partner. The partner is fixed once the account exists. The list shows who belongs to which partner under **Belongs to**. - **Partner roles.** The built-in **Partner viewer** is picked for a new partner's person, ready to use. For anything else, create a role and choose **A partner's people** under **Who it's for**. A partner role holds only the Partner portal permissions, and any other role holds none of them. Partner accounts hold only partner roles. Roles are shared across partners: the role says what someone may do, and the account's partner says whose data. Only someone who holds the Partner portal permissions, which today means an Administrator, can create partner roles or give them out. -- **What they see.** After signing in, a partner account goes to `/portal`: the last 24 hours of its exchanges, its exchanges newest first, and its subscriptions. Each permission opens one part. `portal-exchange-files` adds the exchange files and `portal-exchange-errors` adds why an exchange failed. Errors can name addresses and systems on your side, so give that permission with care. +- **What they see.** A partner's people use Bitween's own frame with their own sidebar: **Exchanges**, **Mappings**, **Subscriptions**, **Your details** and **People**, each shown only to a role that opens it, and none of your pages. After signing in they land on `/portal`, their Exchanges: Bitween's own list, status counts, filters and exchange drawer, reading only their exchanges through `/api/portal`. They filter by subscription, information type, correlation id, exchange id, promoted property, retries and scheduled retries; not by partner, run or aggregation. The drawer shows the documents, the error and the retry chain, without links into your pages, bulk actions, the volume chart or the AI features. `portal-exchange-files` adds the exchange files and `portal-exchange-errors` adds why an exchange failed. Errors can name addresses and systems on your side, so give that permission with care. The server strips what is yours to know from every row (adapters, storage keys, aggregation and response wiring, retry policy reasons) and refuses filters and sorts on anything else. - **What they can't reach.** Partner accounts get 403 from every endpoint outside `/api/portal`, apart from signing in and out, their profile, changing their password and opening file links. This is enforced in one place for every kind of token, including `/mcp`. Administrators get 403 from `/api/portal`, because they have no partner. - **Which exchanges.** An exchange belongs to a partner when it carries that partner's id. Exchanges from before that column existed carry none and don't show in the portal. - A partner with portal users can't be deleted until they are removed. +- **Retrying.** With `portal-exchanges.operate`, which Partner editor and Partner admin hold, a failed exchange has **Retry**. It runs again with the subscription's current settings and their own mapping and details as they are now, so a fix they just made is used. Only their own failed exchanges, only the latest attempt, and not while a retry policy has one scheduled. Each retry is in the audit trail as made from the partner portal. - **Their own people.** Someone with `portal-people.edit`, such as the built-in **Partner admin**, gets a **People** page in the portal listing their company's people. They invite someone by email, or with a link to pass on when there is no mail server, and can change a person's role, send the invite again, disable and remove them. They can give only partner roles that don't include `portal-people.edit`, and only what they hold themselves. They can't change their own account, or another of their admins, which only your team can. Only your team makes someone a partner admin, on the Members page. An email already used anywhere in Bitween is refused without saying where. - **Their own mappings.** The **Mappings** card lists every place the partner is connected: subscriptions that belong to them, API gateways they are attached to, and bus gateway routes that name them. With `portal-mappings.edit` they can make their own version of a place's mapping in the mapping editor, starting from yours, and preview it against one of their recent exchanges. Their version is used for their exchanges only, from the next one on, including retries; everyone else on the same gateway keeps your mapping, and **Go back to ours** deletes theirs. It works for subscriptions that map with the native mapper or don't map at all. Their rules can read the document and the partner properties they can see, but no other partner property or global value that your mapping doesn't already send them, by rule or by `{{globals.…}}` placeholder; saving and previewing refuse it. If your mapping later stops reading a global value theirs reads, theirs is set aside and they get yours until they change it; the portal and the subscription page both say so. Only their rules are kept, never the editor's sample documents. Every change is in the audit trail as **Partner mapping**, in full. The subscription's **Transformation** panel lists the partners with their own mapping, who changed it last and when, with **See rules**, and **Remove** for someone with `subscriptions.edit`, which puts that partner back on your mapping. From ea8016e9ba72bb9aced19e4d31780e4c3b22a402 Mon Sep 17 00:00:00 2001 From: Hamza Alqurneh Date: Wed, 25 Nov 2026 16:34:40 +0300 Subject: [PATCH 2/2] fix: retries keep the bus response, partner id filter skips roll-ups, partner landing page, palette recents per side --- SW.Bitween.Api/Domain/Xchange/Xchange.cs | 2 ++ SW.Bitween.Api/Resources/Xchanges/Search.cs | 2 +- .../Resources/Xchanges/XchangeFilters.cs | 25 ++++++++------ .../Tests/PortalExchangeViewsTests.cs | 26 ++++++++++++++ .../XchangeRetryResponseTests.cs | 29 ++++++++++++++++ SW.Bitween.Web/ClientApp/src/auth/guards.tsx | 7 ++-- .../src/components/layout/CommandPalette.tsx | 6 ++-- .../layout/__tests__/CommandPalette.test.tsx | 34 ++++++++++++++++++- .../portal/__tests__/PortalFrame.test.tsx | 9 +++++ docs/security.md | 2 +- 10 files changed, 124 insertions(+), 18 deletions(-) create mode 100644 SW.Bitween.UnitTests/XchangeRetryResponseTests.cs diff --git a/SW.Bitween.Api/Domain/Xchange/Xchange.cs b/SW.Bitween.Api/Domain/Xchange/Xchange.cs index 6e823cf3..7f055dab 100644 --- a/SW.Bitween.Api/Domain/Xchange/Xchange.cs +++ b/SW.Bitween.Api/Domain/Xchange/Xchange.cs @@ -95,6 +95,7 @@ public Xchange(Xchange xchange, XchangeFile file, IWorkGroup workGroup, bool man SourceXchangeId = xchange.SourceXchangeId; SourceValues = xchange.SourceValues; ResponseSubscriptionId = xchange.ResponseSubscriptionId; + ResponseMessageTypeName = xchange.ResponseMessageTypeName; RetryFor = xchange.Id; CorrelationId = xchange.CorrelationId; } @@ -119,6 +120,7 @@ public Xchange(Subscription subscription, Xchange xchange, XchangeFile file, Par SourceXchangeId = xchange.SourceXchangeId; SourceValues = xchange.SourceValues; ResponseSubscriptionId = subscription.ResponseSubscriptionId; + ResponseMessageTypeName = subscription.ResponseMessageTypeName; RetryFor = xchange.Id; CorrelationId = xchange.CorrelationId; } diff --git a/SW.Bitween.Api/Resources/Xchanges/Search.cs b/SW.Bitween.Api/Resources/Xchanges/Search.cs index c061ec0d..b8c2920c 100644 --- a/SW.Bitween.Api/Resources/Xchanges/Search.cs +++ b/SW.Bitween.Api/Resources/Xchanges/Search.cs @@ -145,7 +145,7 @@ from delayedRetry in drGroup.DefaultIfEmpty() Warning = result.Warning }; - return query.ApplySpecialFilters(searchyRequest, dbContext); + return query.ApplySpecialFilters(searchyRequest, dbContext, rollUps: partnerId == null); } private async Task> FinishAsync(SearchyRequest searchyRequest, diff --git a/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs b/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs index 4a6b3a7f..3d2d3fb6 100644 --- a/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs +++ b/SW.Bitween.Api/Resources/Xchanges/XchangeFilters.cs @@ -94,7 +94,7 @@ from subscriber in xs.DefaultIfEmpty() PartnerId = xchange.PartnerId ?? subscriber.PartnerId }; - query = query.ApplySpecialFilters(searchyRequest, dbContext); + query = query.ApplySpecialFilters(searchyRequest, dbContext, rollUps: partnerId == null); if (status != null && !stateReady) query = query.WhereStatus(status, dbContext); return query.AsNoTracking().Search(searchyRequest.Conditions); @@ -207,10 +207,11 @@ internal static async Task ResolveReceiveAttemptFilterAsync(SearchyRequest searc /// /// Applies the special filters and removes them from , leaving - /// the plain per-column ones for Searchy to handle. + /// the plain per-column ones for Searchy to handle. false, for the + /// partner portal: an id doesn't also find the exchanges rolled up into it, which they don't see. /// internal static IQueryable ApplySpecialFilters(this IQueryable query, - SearchyRequest searchyRequest, BitweenDbContext dbContext) + SearchyRequest searchyRequest, BitweenDbContext dbContext, bool rollUps = true) { var condition = searchyRequest.Conditions.FirstOrDefault(); if (condition == null) @@ -223,17 +224,21 @@ internal static IQueryable ApplySpecialFilters(this IQueryable - i.Id == value || i.RetryFor == value || i.AggregationXchangeId == value); + query = rollUps + ? query.Where(i => i.Id == value || i.RetryFor == value || i.AggregationXchangeId == value) + : query.Where(i => i.Id == value || i.RetryFor == value); break; case SearchyRule.Contains: { var valueAsArray = idFilter.ValueStringArray; - query = query.Where(i => - valueAsArray.Any(v => i.RetryFor == v) || - valueAsArray.Any(v => i.AggregationXchangeId == v) || - valueAsArray.Any(v => i.Id == v) - ); + query = rollUps + ? query.Where(i => + valueAsArray.Any(v => i.RetryFor == v) || + valueAsArray.Any(v => i.AggregationXchangeId == v) || + valueAsArray.Any(v => i.Id == v)) + : query.Where(i => + valueAsArray.Any(v => i.RetryFor == v) || + valueAsArray.Any(v => i.Id == v)); break; } diff --git a/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs b/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs index 65e7fcb9..34b5637c 100644 --- a/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs +++ b/SW.Bitween.IntegrationTests/Tests/PortalExchangeViewsTests.cs @@ -110,6 +110,32 @@ await Assert.ThrowsAsync(() => As r.Id).ToList()); } + [Fact] + public async Task An_id_does_not_find_theirs_rolled_up_into_it() + { + var w = await SetUpAsync(); + // Theirs rolled up into another exchange: our wiring, which they aren't shown. + await using (var scope = fixture.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Add(new XchangeAggregation(w.MyFailed, w.TheirFailed)); + await db.SaveChangesAsync(); + } + + var byRollUp = Filter($"Id:1:{w.TheirFailed}"); + var found = await As>(w.SeesNothingMore, + h => h.Handle(byRollUp)); + Assert.Empty(found.Result); + var summary = await As(w.SeesNothingMore, + h => h.Handle(Filter($"Id:1:{w.TheirFailed}"))); + Assert.Equal(0, summary.Counts.Failed); + + // Their own id still finds it. + var own = await As>(w.SeesNothingMore, + h => h.Handle(Filter($"Id:1:{w.MyFailed}"))); + Assert.Equal([w.MyFailed], own.Result.Select(r => r.Id).ToList()); + } + [Fact] public async Task Counts_only_theirs() { diff --git a/SW.Bitween.UnitTests/XchangeRetryResponseTests.cs b/SW.Bitween.UnitTests/XchangeRetryResponseTests.cs new file mode 100644 index 00000000..a84b95d7 --- /dev/null +++ b/SW.Bitween.UnitTests/XchangeRetryResponseTests.cs @@ -0,0 +1,29 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SW.Bitween.Domain; +using SW.PrimitiveTypes; + +namespace SW.Bitween.UnitTests; + +/// A retry publishes the bus response its subscription is set up for, as the first attempt did. +[TestClass] +public class XchangeRetryResponseTests +{ + static Subscription Publishing(string message) => + new("Orders", 1) { ResponseMessageTypeName = message }; + + [TestMethod] + public void A_plain_retry_keeps_the_response_of_the_attempt_it_retries() + { + var first = new Xchange(Publishing("Order Placed"), new XchangeFile("{}")); + var retry = new Xchange(first, new XchangeFile("{}"), null, manualRetry: true); + Assert.AreEqual("Order Placed", retry.ResponseMessageTypeName); + } + + [TestMethod] + public void A_retry_with_the_current_settings_takes_the_subscription_s_response_now() + { + var first = new Xchange(Publishing("Order Placed"), new XchangeFile("{}")); + var retry = new Xchange(Publishing("Order Placed v2"), first, new XchangeFile("{}"), manualRetry: true); + Assert.AreEqual("Order Placed v2", retry.ResponseMessageTypeName); + } +} diff --git a/SW.Bitween.Web/ClientApp/src/auth/guards.tsx b/SW.Bitween.Web/ClientApp/src/auth/guards.tsx index ee5fa1ce..77fa4ecb 100644 --- a/SW.Bitween.Web/ClientApp/src/auth/guards.tsx +++ b/SW.Bitween.Web/ClientApp/src/auth/guards.tsx @@ -5,6 +5,7 @@ import type { PermissionKey } from "../api"; import { labelIn, usePermissionCatalog } from "../api/permissions"; import { Button } from "../components/ui/basics"; import { useSession } from "./useSession"; +import { homePath } from "../nav"; /** Redirects to /login when signed out; shows a splash while checking. */ export function RequireAuth() { @@ -45,9 +46,9 @@ export function RequireAuth() { return ; } // A partner's person has the portal and their password, and nothing else; every other screen - // would only be refused. + // would only be refused. Their first page is the one their role opens, which isn't always Exchanges. if (session.partner && !inPortal(location.pathname) && location.pathname !== "/change-password") { - return ; + return ; } return ; } @@ -55,7 +56,7 @@ export function RequireAuth() { export const PORTAL_PATH = "/portal"; /** The portal and the pages under it; "/portal-old" is neither. */ -const inPortal = (path: string) => path === PORTAL_PATH || path.startsWith(PORTAL_PATH + "/"); +export const inPortal = (path: string) => path === PORTAL_PATH || path.startsWith(PORTAL_PATH + "/"); /** The partner portal is for a partner's people; our own are sent back to the app. */ /** A partner's people's page: anyone else goes back to the app. */ diff --git a/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx b/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx index 950d0851..af13beb9 100644 --- a/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx +++ b/SW.Bitween.Web/ClientApp/src/components/layout/CommandPalette.tsx @@ -5,6 +5,7 @@ import { useNavigate } from "react-router"; import { Clock, CornerDownLeft, FileText, Plus, Search } from "lucide-react"; import { api } from "../../api"; import { keys } from "../../api/queryKeys"; +import { inPortal } from "../../auth/guards"; import { useSession } from "../../auth/useSession"; import { NAV_GROUPS } from "../../nav"; import { PAGES, type PageId } from "../../pages"; @@ -199,7 +200,8 @@ export function CommandPalette({ onClose }: { onClose: () => void }) { const results = useMemo(() => { if (!query.trim()) { - const recent = recentVisits().map((v) => ({ + // Another person's visits on this browser, ours or a partner's, aren't offered across that line. + const recent = recentVisits().filter((v) => inPortal(v.path) === partner).map((v) => ({ key: `recent:${v.path}`, section: "Recent" as const, label: v.title, @@ -219,7 +221,7 @@ export function CommandPalette({ onClose }: { onClose: () => void }) { return n <= PER_KIND; }); return [...matches(pages, query), ...capped]; - }, [query, pages, things]); + }, [query, pages, things, partner]); const go = (item: Item | null) => { if (!item) return; diff --git a/SW.Bitween.Web/ClientApp/src/components/layout/__tests__/CommandPalette.test.tsx b/SW.Bitween.Web/ClientApp/src/components/layout/__tests__/CommandPalette.test.tsx index c884221b..f4a42ca6 100644 --- a/SW.Bitween.Web/ClientApp/src/components/layout/__tests__/CommandPalette.test.tsx +++ b/SW.Bitween.Web/ClientApp/src/components/layout/__tests__/CommandPalette.test.tsx @@ -1,6 +1,6 @@ import { screen, waitFor, within } from "@testing-library/react"; import { http, HttpResponse } from "msw"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { ALL_PERMISSIONS, apiPath, renderApp } from "../../../__tests__/support/renderApp"; import { empty, page } from "../../../__tests__/support/listPage"; @@ -66,4 +66,36 @@ describe("the command palette", () => { await user.type(palette.getByRole("combobox"), "acme partner"); expect(await palette.findByText(/Nothing matches/)).toBeVisible(); }); + describe("recent visits, from whoever used this browser before", () => { + const visits = [ + { path: "/subscriptions/9", title: "Acme orders", kind: "Subscription" }, + { path: "/portal/mappings/4", title: "Their webhook mapping", kind: "Mapping" }, + ]; + afterEach(() => localStorage.removeItem("bitween-recent")); + + it("offers our own people only our pages", async () => { + localStorage.setItem("bitween-recent", JSON.stringify(visits)); + const { user } = renderApp("/global-values", { handlers }); + await screen.findByRole("heading", { name: /Global values/ }); + + await user.keyboard("{Control>}k{/Control}"); + const palette = within(screen.getByRole("dialog", { name: "Search Bitween" })); + expect(palette.getByRole("option", { name: /Acme orders/ })).toBeVisible(); + expect(palette.queryByRole("option", { name: /Their webhook mapping/ })).not.toBeInTheDocument(); + }); + + it("offers a partner's person only their portal's pages", async () => { + localStorage.setItem("bitween-recent", JSON.stringify(visits)); + const { user } = renderApp("/portal/mappings", { + handlers: [http.get(apiPath("/portal/mappings"), () => HttpResponse.json([]))], + as: { partner: { id: 7, name: "Acme Freight" }, permissions: ["portal-mappings.view"] }, + }); + await screen.findByRole("heading", { name: /Mappings/ }); + + await user.keyboard("{Control>}k{/Control}"); + const palette = within(screen.getByRole("dialog", { name: "Search Bitween" })); + expect(palette.getByRole("option", { name: /Their webhook mapping/ })).toBeVisible(); + expect(palette.queryByRole("option", { name: /Acme orders/ })).not.toBeInTheDocument(); + }); + }); }); diff --git a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx index cdace858..22476a69 100644 --- a/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx +++ b/SW.Bitween.Web/ClientApp/src/pages/portal/__tests__/PortalFrame.test.tsx @@ -83,6 +83,15 @@ describe("the partner portal, in the app's own frame", () => { } }); + it("sends a partner's person whose role has no Exchanges to the first page it does open", async () => { + const { router } = renderApp("/", { + as: { partner: ACME, permissions: ["portal-mappings.view"] }, + handlers: [http.get(apiPath("/portal/mappings"), () => HttpResponse.json([]))], + }); + await waitFor(() => expect(router.state.location.pathname).toBe("/portal/mappings")); + expect(screen.queryByText(/don't have access/i)).not.toBeInTheDocument(); + }); + it("keeps our own people out of the portal, and its pages out of their sidebar", async () => { const { router } = renderApp("/portal", { handlers: portal().handlers, as: { permissions: ALL_PERMISSIONS } }); const nav = await screen.findByRole("navigation", { name: "Main" }); diff --git a/docs/security.md b/docs/security.md index 4d12c8ac..1ebebf70 100644 --- a/docs/security.md +++ b/docs/security.md @@ -141,7 +141,7 @@ A partner's own people can sign in and see their partner's data, and nothing els - **Partner accounts.** On the Members page, choose **A partner's person** when adding someone, and pick the partner. The partner is fixed once the account exists. The list shows who belongs to which partner under **Belongs to**. - **Partner roles.** The built-in **Partner viewer** is picked for a new partner's person, ready to use. For anything else, create a role and choose **A partner's people** under **Who it's for**. A partner role holds only the Partner portal permissions, and any other role holds none of them. Partner accounts hold only partner roles. Roles are shared across partners: the role says what someone may do, and the account's partner says whose data. Only someone who holds the Partner portal permissions, which today means an Administrator, can create partner roles or give them out. -- **What they see.** A partner's people use Bitween's own frame with their own sidebar: **Exchanges**, **Mappings**, **Subscriptions**, **Your details** and **People**, each shown only to a role that opens it, and none of your pages. After signing in they land on `/portal`, their Exchanges: Bitween's own list, status counts, filters and exchange drawer, reading only their exchanges through `/api/portal`. They filter by subscription, information type, correlation id, exchange id, promoted property, retries and scheduled retries; not by partner, run or aggregation. The drawer shows the documents, the error and the retry chain, without links into your pages, bulk actions, the volume chart or the AI features. `portal-exchange-files` adds the exchange files and `portal-exchange-errors` adds why an exchange failed. Errors can name addresses and systems on your side, so give that permission with care. The server strips what is yours to know from every row (adapters, storage keys, aggregation and response wiring, retry policy reasons) and refuses filters and sorts on anything else. +- **What they see.** A partner's people use Bitween's own frame with their own sidebar: **Exchanges**, **Mappings**, **Subscriptions**, **Your details** and **People**, each shown only to a role that opens it, and none of your pages. After signing in they land on the first of those pages their role opens, usually `/portal`, their Exchanges: Bitween's own list, status counts, filters and exchange drawer, reading only their exchanges through `/api/portal`. They filter by subscription, information type, correlation id, exchange id, promoted property, retries and scheduled retries; not by partner, run or aggregation. The drawer shows the documents, the error and the retry chain, without links into your pages, bulk actions, the volume chart or the AI features. `portal-exchange-files` adds the exchange files and `portal-exchange-errors` adds why an exchange failed. Errors can name addresses and systems on your side, so give that permission with care. The server strips what is yours to know from every row (adapters, storage keys, aggregation and response wiring, retry policy reasons) and refuses filters and sorts on anything else. - **What they can't reach.** Partner accounts get 403 from every endpoint outside `/api/portal`, apart from signing in and out, their profile, changing their password and opening file links. This is enforced in one place for every kind of token, including `/mcp`. Administrators get 403 from `/api/portal`, because they have no partner. - **Which exchanges.** An exchange belongs to a partner when it carries that partner's id. Exchanges from before that column existed carry none and don't show in the portal. - A partner with portal users can't be deleted until they are removed.