This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/*.csproj, **/*.sln, **/.gitignore, **/config/**, **/Migrations/**, **/vendor/**, **/generated/**, **/gen/**, **/auto/**, **/out/**, **/fixtures/**, **/test-keys/**, **/*.key, **/*.lic, **/*.bzl, **/*.gradle, **/build/**, **/bin/**, **/obj/**, **/.idea/**, **/.vscode/**, **/.settings/**, **/*.pdl, **/*.avsc, **/*.thrift, **/*.proto, **/*.smithy, **/*.cddl, **/node_modules/**
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
contract/
  fixture-set.json
  README.md
docs/
  Admin-Console.md
  Bookings.md
  Branching.md
  Competitors.md
  Console-Shell.md
  CRM.md
  Gateway-Management.md
  Installing-On-A-Phone.md
  Issuing-A-License.md
  License-Config-Schema.md
  License-Contract.md
  License-Entitlements.md
  License-Format.md
  License-Register.md
  Localisation.md
  Notifications.md
  Operations.md
  Provisioning.md
  README.md
src/
  KnowledgeFabric.AdminConsole/
    Areas/
      Booking/
        Controllers/
          AvailabilityController.cs
          BookingsController.cs
          HomeController.cs
          HostsController.cs
          LinksController.cs
          PublicController.cs
        Models/
          AvailabilityPage.cs
          BookingLinkCard.cs
          BookingList.cs
          BookingPages.cs
          FeedForm.cs
          HostForm.cs
          HostsPage.cs
          LinkPages.cs
          PatternForm.cs
          PublicPages.cs
          WindowForm.cs
        ViewComponents/
          BookingOverviewViewComponent.cs
        Views/
          Availability/
            Picker.cshtml
            Week.cshtml
          Bookings/
            _Summary.cshtml
            Cancel.cshtml
            Index.cshtml
            Show.cshtml
          Hosts/
            _Calendars.cshtml
            Edit.cshtml
            Index.cshtml
            Remove.cshtml
            RemoveCalendar.cshtml
          Links/
            _TitleAndExpiry.cshtml
            Edit.cshtml
            End.cshtml
            Index.cshtml
            New.cshtml
          Public/
            _Heading.cshtml
            Booked.cshtml
            Cancel.cshtml
            Cancelled.cshtml
            Closed.cshtml
            Day.cshtml
            Month.cshtml
            Notice.cshtml
            Slot.cshtml
            Team.cshtml
          Shared/
            Components/
              BookingOverview/
                Default.cshtml
            _BookingLink.cshtml
          _ViewImports.cshtml
          _ViewStart.cshtml
      Competitors/
        Controllers/
          CompetitorsController.cs
          DraftsController.cs
          NewsController.cs
          SettingsController.cs
          SourcesController.cs
        Models/
          CompetitorForm.cs
          CompetitorPages.cs
          CompetitorSettings.cs
        ViewComponents/
          CompetitorsOverviewViewComponent.cs
        Views/
          Competitors/
            Address.cshtml
            Delete.cshtml
            Deleted.cshtml
            Details.cshtml
            Edit.cshtml
            Index.cshtml
            Refresh.cshtml
          News/
            Index.cshtml
          Settings/
            Index.cshtml
          Shared/
            Components/
              CompetitorsOverview/
                Default.cshtml
            _Lost.cshtml
            _NewsLines.cshtml
            _Reading.cshtml
            _Sources.cshtml
            _Storage.cshtml
          _ViewImports.cshtml
          _ViewStart.cshtml
      Crm/
        Controllers/
          BusinessCardsController.cs
          ContactsController.cs
          FollowUpsController.cs
          HomeController.cs
          ImportController.cs
          InteractionsController.cs
          IntroductionsController.cs
          StatisticsController.cs
        Models/
          BusinessCardPage.cs
          ContactCells.cs
          ContactEdit.cs
          ContactGrid.cs
          CrmImport.cs
          InteractionPanel.cs
          IntroductionCard.cs
          NextAction.cs
          PersonCell.cs
        ViewComponents/
          CrmOverviewViewComponent.cs
        Views/
          BusinessCards/
            Index.cshtml
          Contacts/
            _NewContactRow.cshtml
            Delete.cshtml
            Deleted.cshtml
            Details.cshtml
            Index.cshtml
          FollowUps/
            Index.cshtml
          Import/
            Index.cshtml
          Shared/
            Components/
              CrmOverview/
                Default.cshtml
            _ContactAssets.cshtml
            _ContactConfig.cshtml
            _ContactRow.cshtml
            _InteractionFields.cshtml
            _Interactions.cshtml
            _Introductions.cshtml
            _NextActionFields.cshtml
            _TimelineLines.cshtml
          Statistics/
            Index.cshtml
          _ViewImports.cshtml
          _ViewStart.cshtml
      Gateway/
        Controllers/
          HomeController.cs
          InstallationsController.cs
          PolicyChangeController.cs
          PolicyController.cs
          UsageController.cs
        Models/
          AllowanceWords.cs
          GatewayOperator.cs
          GatewayOverview.cs
          InstallationChange.cs
          InstallationDetails.cs
          InstallationFilter.cs
          InstallationList.cs
          LocationWords.cs
          PolicyChange.cs
          PolicyPage.cs
          UsageByLicence.cs
          UsageChart.cs
          UsageHistory.cs
        ViewComponents/
          GatewayOverviewViewComponent.cs
        Views/
          Home/
            Index.cshtml
          Installations/
            Change.cshtml
            Details.cshtml
            Index.cshtml
          Policy/
            Index.cshtml
          PolicyChange/
            _PolicyChangeHeader.cshtml
            _PolicyChangeProblems.cshtml
            _PolicyConfirm.cshtml
            _PolicyUnavailable.cshtml
            _PolicyWriteBlocked.cshtml
            Ceiling.cshtml
            MinimumVersion.cshtml
            Tier.cshtml
            Velocity.cshtml
          Shared/
            Components/
              GatewayOverview/
                Default.cshtml
            _GatewayStatusUnavailable.cshtml
            _InstallationCountry.cshtml
            _InstallationLicence.cshtml
            _InstallationsUnavailable.cshtml
            _LocationAttribution.cshtml
            _UsageChart.cshtml
            _UsageChartScripts.cshtml
            _UsageUnavailable.cshtml
          Usage/
            _InstallationUsage.cshtml
            History.cshtml
            Index.cshtml
          _ViewImports.cshtml
          _ViewStart.cshtml
      Licensing/
        Controllers/
          IssueController.cs
          RegisterController.cs
          ValidateController.cs
        ViewComponents/
          LicenceInstallationsViewComponent.cs
          LicensingOverviewViewComponent.cs
        Views/
          Issue/
            _HiddenForm.cshtml
            _Limit.cshtml
            _SigningStatus.cshtml
            _Switches.cshtml
            Index.cshtml
            Issued.cshtml
            Preview.cshtml
          Register/
            Details.cshtml
            Index.cshtml
          Shared/
            Components/
              LicenceInstallations/
                Default.cshtml
              LicensingOverview/
                Default.cshtml
            _Entitlement.cshtml
            _GatewayUnavailable.cshtml
            _Purpose.cshtml
            _RegisterAvailability.cshtml
          Validate/
            _GatewayVerdict.cshtml
            _Verdict.cshtml
            Index.cshtml
          _ViewImports.cshtml
          _ViewStart.cshtml
    Auditing/
      AuditActionFilter.cs
      AuditEntry.cs
      AuditRegistration.cs
      AuditTrail.cs
      DatabaseAuditLog.cs
      IAuditLog.cs
      InMemoryAuditLog.cs
      LoggingAuditLog.cs
      PostgresAuditTrail.cs
      SelfAuditedAttribute.cs
    Booking/
      AvailabilityPattern.cs
      AvailabilityWindow.cs
      BookedHost.cs
      BookingHost.cs
      BookingInvitations.cs
      BookingLink.cs
      BookingNotifications.cs
      BookingRecord.cs
      BookingRegistration.cs
      BookingWeek.cs
      CalendarBusyTime.cs
      CalendarFeed.cs
      CalendarFeedParser.cs
      CalendarFeedReader.cs
      GuestLink.cs
      IBookingStore.cs
      InMemoryBookingStore.cs
      JointAvailability.cs
      PostgresBookingStore.cs
      SlotCalculator.cs
      TimeZones.cs
      ZohoCalendarClient.cs
      ZohoEvent.cs
      ZohoOptions.cs
      ZohoRegistration.cs
      ZohoTokenSource.cs
    Competitors/
      Competitor.cs
      CompetitorAnalyser.cs
      CompetitorDrafting.cs
      CompetitorNews.cs
      CompetitorNewsReader.cs
      CompetitorNotifications.cs
      CompetitorScan.cs
      CompetitorSiteReader.cs
      CompetitorsOptions.cs
      CompetitorSource.cs
      CompetitorSourceAdder.cs
      CompetitorsRegistration.cs
      ICompetitorStore.cs
      InMemoryCompetitorStore.cs
      NewsCandidates.cs
      NewsFeed.cs
      PositioningStatement.cs
      PostgresCompetitorStore.cs
      ScanHealth.cs
    Controllers/
      AccountController.cs
      AuditController.cs
      CultureController.cs
      ErrorController.cs
      HomeController.cs
      NotificationsController.cs
      NotificationSettingsController.cs
      OfflineController.cs
      PreferencesController.cs
      UsersController.cs
    Crm/
      BusinessCardOptions.cs
      BusinessCardQr.cs
      BusinessCardReader.cs
      BusinessCardRegistration.cs
      Contact.cs
      ContactChange.cs
      ContactRegisterRegistration.cs
      CrmActivity.cs
      CrmCsv.cs
      CrmFunnel.cs
      CrmHistory.cs
      FollowUpReminders.cs
      FollowUps.cs
      IContactRegister.cs
      InMemoryContactRegister.cs
      Interaction.cs
      Introduction.cs
      IntroductionFunnel.cs
      IntroductionHistory.cs
      LinkedPageReader.cs
      PostgresContactRegister.cs
      PublicAddress.cs
    Data/
      ConsoleDbContext.cs
      DatabaseMigrator.cs
      DatabaseOptions.cs
      DesignTimeConsoleDbContextFactory.cs
    Gateway/
      GatewayAdminClient.cs
      GatewayEnrolmentWatch.cs
      GatewayInstallation.cs
      GatewayOptions.cs
      GatewayPolicy.cs
      GatewayRegistration.cs
      GatewayStatus.cs
      GatewayStatusCache.cs
      GatewayUsage.cs
      GatewayWatch.cs
      InstallationQuery.cs
    Licensing/
      Installations/
        LicenceInstallations.cs
      Issuing/
        EntitlementSummary.cs
        IssueForm.cs
        IssueLedger.cs
        IssueTicket.cs
        LicenceIssuer.cs
        LicenceIssuingRegistration.cs
        SigningKeyDiagnosis.cs
        SigningKeyOptions.cs
      Register/
        ILicenceRegister.cs
        InMemoryLicenceRegister.cs
        LicenceRegisterRegistration.cs
        PostgresLicenceRegister.cs
        RegisterQuery.cs
        RegisterStatistics.cs
        UnconfiguredLicenceRegister.cs
      Validation/
        LicenceValidator.cs
        TrustedKeys.cs
    Localisation/
      CatalogueNames.cs
      ClientStrings.cs
      ConsoleCultures.cs
      CountryNames.cs
      InvariantFormValueProviderFactory.cs
      LocalisationRegistration.cs
      RoleNames.cs
    Models/
      ConsoleBranding.cs
      ErrorModel.cs
      LoginModel.cs
    Notifications/
      InMemoryNotificationStore.cs
      INotificationStore.cs
      Notification.cs
      NotificationContent.cs
      NotificationOptions.cs
      NotificationPusher.cs
      NotificationRegistration.cs
      Notifier.cs
      PostgresNotificationStore.cs
      PushDevice.cs
      PushDeviceLabel.cs
      WebPushSender.cs
    Ollama/
      OllamaConnection.cs
      OllamaOptions.cs
      OllamaRegistration.cs
      OllamaSearchClient.cs
      OllamaThinking.cs
      RetiredBusinessCardKey.cs
    Preferences/
      DashboardPreferences.cs
      OverviewAreas.cs
    Properties/
      launchSettings.json
    Resources/
      ConsoleResource.cs
      ConsoleResource.it.resx
      ConsoleResource.resx
    Security/
      AuthenticationRegistration.cs
      ConsoleAuthenticationOptions.cs
      ConsoleClaims.cs
      ConsoleCredentials.cs
      ConsolePeople.cs
      ConsolePolicies.cs
      ConsoleRoles.cs
      IConsoleRoleStore.cs
      InMemoryConsoleRoleStore.cs
      LoginThrottle.cs
      PersonInitials.cs
      PostgresConsoleRoleStore.cs
      RetiredSharedPassword.cs
      RoleRequirement.cs
    Storage/
      FeatureStateRegistration.cs
      IFeatureStateStore.cs
      InMemoryFeatureStateStore.cs
      PostgresFeatureStateStore.cs
      StoredFeatureState.cs
    ViewComponents/
      NotificationBellViewComponent.cs
    Views/
      Account/
        Login.cshtml
      Audit/
        Index.cshtml
      Home/
        Index.cshtml
      Notifications/
        Index.cshtml
      NotificationSettings/
        Index.cshtml
      Offline/
        Index.cshtml
      Preferences/
        Dashboard.cshtml
      Shared/
        Components/
          NotificationBell/
            Default.cshtml
        Sections/
          Footer/
            _Footer.cshtml
          Menu/
            _VerticalMenu.cshtml
          Navbar/
            _LanguageSwitcher.cshtml
            _Navbar.cshtml
          _LaunchSplash.cshtml
          _Scripts.cshtml
          _ScriptsIncludes.cshtml
          _Styles.cshtml
        _ApexCharts.cshtml
        _BlankLayout.cshtml
        _CommonMasterLayout.cshtml
        _ContentNavbarLayout.cshtml
        _PublicLayout.cshtml
        Error.cshtml
      Users/
        Index.cshtml
      _ViewImports.cshtml
      _ViewStart.cshtml
    appsettings.Development.json
    appsettings.json
    build-vendor.js
    package.json
    Program.cs
  KnowledgeFabric.LicenseTool/
    Properties/
      launchSettings.json
    ConfigLoader.cs
    ContractReader.cs
    Entitlements.cs
    FixtureGenerator.cs
    FixtureSet.cs
    KeyGenerator.cs
    KeyRekeyer.cs
    LicenseConfig.cs
    LicenseContract.cs
    LicenseGenerator.cs
    LicenseSigner.cs
    LicenseTerms.cs
    Program.cs
    RegisterCsv.cs
    RegisterRecord.cs
CLAUDE.md
README.md
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path="contract/fixture-set.json">
{
    "evaluationInstant": "2026-07-01T12:00:00Z",
    "signingKeys": {
        "contract": {
            "privateKey": "test-keys/contract-test.private.key",
            "publicKey": "test-keys/contract-test.public.key",
            "passphrase": "contract-fixtures-test-key"
        },
        "foreign": {
            "privateKey": "test-keys/foreign-test.private.key",
            "publicKey": "test-keys/foreign-test.public.key",
            "passphrase": "foreign-fixtures-test-key"
        }
    },
    "fixtures": [
        {
            "name": "valid-full-grant",
            "asserts": "The happy path: a signed, in-force licence granting every report, feature, connector (with no count) and AI capability, with no limits.",
            "expect": {
                "signatureValid": true,
                "acceptOnUpload": true,
                "tier": "standard",
                "reports": ["insights", "resilience", "watch", "holders", "assets", "map", "skills", "workforce"],
                "features": ["offboarding", "actioncenter", "departure", "export"],
                "sources": {
                    "git": null,
                    "azureboards": null,
                    "jira": null,
                    "gcal": null,
                    "outlook": null,
                    "confluence": null,
                    "shortcut": null,
                    "onedrive": null,
                    "teams": null,
                    "publications": null,
                    "github": null
                },
                "ai": ["chat"]
            },
            "license": {
                "licenseId": "00000005-0000-4000-8000-000000000001",
                "name": "Fixture Customer",
                "email": "fixtures@knowledgefabric.invalid",
                "licenseType": "Standard",
                "tier": "standard",
                "expiration": "2027-12-31T23:59:59Z",
                "reports": ["insights", "resilience", "watch", "holders", "assets", "map", "skills", "workforce"],
                "features": ["offboarding", "actioncenter", "departure", "export"],
                "sources": ["git", "azureboards", "jira", "gcal", "outlook", "confluence", "shortcut", "onedrive", "teams", "publications", "github"],
                "ai": ["chat"],
                "attributes": {}
            }
        },
        {
            "name": "valid-no-schema-version",
            "asserts": "A licence carrying no schemaVersion attribute must be read as version 1, not refused.",
            "verbatim": true,
            "expect": {
                "signatureValid": true,
                "schemaVersion": 1,
                "acceptOnUpload": true,
                "reports": ["insights", "resilience", "watch", "holders", "assets", "map", "skills", "workforce"],
                "features": ["offboarding", "actioncenter", "departure", "export"],
                "sources": {
                    "git": null,
                    "azureboards": null,
                    "jira": null,
                    "gcal": null,
                    "outlook": null,
                    "confluence": null,
                    "shortcut": null,
                    "onedrive": null,
                    "teams": null,
                    "publications": null,
                    "github": null
                },
                "ai": ["chat"]
            },
            "license": {
                "licenseId": "00000005-0000-4000-8000-000000000002",
                "name": "Fixture Customer",
                "email": "fixtures@knowledgefabric.invalid",
                "licenseType": "Standard",
                "expiration": "2027-12-31T23:59:59Z",
                "reports": ["insights", "resilience", "watch", "holders", "assets", "map", "skills", "workforce"],
                "features": ["offboarding", "actioncenter", "departure", "export"],
                "sources": ["git", "azureboards", "jira", "gcal", "outlook", "confluence", "shortcut", "onedrive", "teams", "publications", "github"],
                "ai": ["chat"],
                "attributes": {}
            }
        },
        {
            "name": "expired",
            "asserts": "A correctly signed licence whose Expiration precedes the evaluation instant is refused as expired.",
            "expect": {
                "signatureValid": true,
                "expired": true,
                "acceptOnUpload": false,
                "reason": "expired",
                "reports": ["insights", "resilience", "watch", "holders", "assets", "map", "skills", "workforce"],
... (885 lines truncated)
</file>

<file path="contract/README.md">
# The licence contract

This directory is the **executable half** of the KnowledgeFabric licence contract: a set of signed
licence files, minted by the same code that signs a customer licence, that every reader of a licence
asserts against.

The **normative half** is [`docs/License-Contract.md`](../docs/License-Contract.md). Where this
directory and that page disagree, the page is wrong and should be corrected — the fixtures are
measured, the prose is written.

## Why fixtures instead of a shared library

[#5](https://github.com/KnowledgeFabric/kf-admin/issues/5) originally proposed a
`KnowledgeFabric.Licensing` package published to GitHub Packages and referenced by kf-app,
kf-ai-gateway and this repository. That was
[dropped](https://github.com/KnowledgeFabric/kf-admin/issues/1#issuecomment-5750795917): measured
against kf-app at `075fa03`, the contract-bearing logic is about twenty lines, and the gateway's
whole `LicenceEvaluation.cs` was then 1,910 bytes. A package, a feed and credential wiring in three
repositories is heavier machinery than the thing it shares.

So each reader keeps its own verification, and these fixtures keep the copies honest. The reasoning
is kf-app's own, from ADR D21 on the gateway stub: *"a mock would encode what we believed the
contract said and would agree with us forever."* A fixture signed by the real issuing code cannot
agree with a reader that has drifted.

## Layout

```
contract/
  fixture-set.json          the definition — what each case is and what a reader must conclude
  test-keys/                the two throwaway keypairs the set is signed with
  fixtures/
    manifest.json           the generated index: every case, its verdict, its hash
    *.lic                   27 signed fixtures
    *-test.public.key       the public keys, shipped with the fixtures
```

## Consuming the set

1. **Copy `fixtures/` into your repository.** Don't fetch it at test time — a test that reaches the
   network is a test that fails for unrelated reasons.
2. **Verify against `contract-test.public.key`**, shipped in the same directory. These fixtures are
   *not* signed with the production key, so a reader must be pointed at the test key — in kf-app
   through `LicensingSettings:PublicKey`, which is trusted beside the compiled-in keys (kf-app
   `c332de4`, `LicensingOptions.cs`). A reader that trusts a list of keys also accepts the production
   key's signatures, which no fixture carries, so the verdicts are unaffected.
3. **Freeze your clock to `evaluationInstant`** from the manifest — `2026-07-01T12:00:00Z`. Every
   expected verdict is stated at that instant. kf-app has `KnowledgeClock`
   (`Common/Time/KnowledgeClock.cs`, with `KnowledgeClockCollection` in the tests) and this is what
   makes static fixtures viable: a fixture with a fixed expiry does not go stale.
4. **Assert the `expect` block** for each fixture. `reason` uses the vocabulary in the normative
   page; `acceptOnUpload` is kf-app's upload rule specifically. `purpose` is `customer` unless the
   licence says otherwise. `reports`, `features`, `sources`,
   `ai`, `limits` and `ignoredNames` are what the licence grants, read by the rules in
   [License Entitlements](../docs/License-Entitlements.md): a connector's count is `null` for no
   limit, and is of sources for every connector but `github`, whose count is of repositories
   across every GitHub source, while `sources.max` counts each GitHub source as one ([rule
   7](../docs/License-Entitlements.md#how-a-reader-must-read-them), #168); a limit left out of
   `limits` is none (for AI, the default of `aiTier`), and `0` is a limit or count present but
   unreadable, which allows nothing (for `analysis.employees`, an allowance every
   employee is over). `aiTier` is the tier whose allowance supplies the AI limits the licence leaves
   out: `enterprise` or `standard`, which is what an absent or unknown `tier` reads as. A reader need
   assert only the parts it enforces — the gateway, the `ai.` limits and `aiTier`.

The `foreign-test.public.key` is shipped too, so a reader can demonstrate that `foreign-signed.lic`
carries a *valid signature by the wrong issuer* rather than a corrupted one. That distinction is
the whole point of that fixture.

## Regenerating

```bash
dotnet build KnowledgeFabricLicensing.sln -c Release
dotnet src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/LicenseTool.dll gen-fixtures \
  --set contract/fixture-set.json \
  --output contract/fixtures
```

`gen-fixtures` mints each case, then **reads it back and checks that it behaves the way
`fixture-set.json` claims**. A disagreement prints both values and exits non-zero — a fixture set
that lies about itself would propagate the lie to all three readers.

Regenerating a schema change is a step in shipping it, not an afterthought.

Each case is minted through the same validation `gen-license` applies, issued at `evaluationInstant`
— so `issuedAt`, and any expiry resolved from a `duration`, come out the same on every run. Cases
that exist to be wrong — no `schemaVersion`, an unsupported one, an unreadable `validFrom`, a
`TrialDays` attribute — set `"verbatim": true`, which signs their `attributes` exactly as written
instead of refusing them.

### What CI checks

`.github/workflows/build.yml` runs on every pull request. It builds, runs `gen-fixtures` into a
scratch directory, and then runs `.github/scripts/verify-committed-fixtures.sh`, which you can run
yourself from the repository root.

Those are two different checks, and the second is the one that catches a stale commit:

- **`gen-fixtures`** proves the definition and the reader still agree with each other.
- **The script** proves the *committed* files still match the *committed* manifest — the same case
  list, the same `evaluationInstant`, the same hash and byte count per file, and no stray `.lic`
... (44 lines truncated)
</file>

<file path="docs/Admin-Console.md">
# Admin Console

**kf-admin is KnowledgeFabric's internal admin console.** Licence issuing is its first tenant, the
AI gateway its second and the CRM its third. It is not what the repository is for.

The repository was `kf-licensing` until 2026-09-20. It was renamed while it is still effectively
greenfield, because the name stops being free the moment [#7](https://github.com/KnowledgeFabric/kf-admin/issues/7)
provisions: it lands in an App Service name, a resource group and an OIDC federated credential
subject, which is re-issued in Entra rather than redirected. The decision record is the
[four directions](https://github.com/KnowledgeFabric/kf-admin/issues/1#issuecomment-5750795917)
comment on #1, with [#13](https://github.com/KnowledgeFabric/kf-admin/issues/13) behind it.

**The shell exists, and so does its first feature.** `src/KnowledgeFabric.AdminConsole/` is the
application — sign-in, layout, `/health`, and the authorisation, audit and storage seams — built
for [#15](https://github.com/KnowledgeFabric/kf-admin/issues/15) and described in
[Console Shell](Console-Shell.md). Beside it are the licence-minting CLI in
`src/KnowledgeFabric.LicenseTool/` and the licensing documentation in [`docs/`](README.md). Its
licensing area issues a signed licence from a form ([#6](https://github.com/KnowledgeFabric/kf-admin/issues/6),
[Issuing a License](Issuing-A-License.md#in-the-console)) and records each one in the register of
issued licences ([#8](https://github.com/KnowledgeFabric/kf-admin/issues/8),
[License Register](License-Register.md)). A validate page shows what the product and the gateway
will make of any `.lic` file, and each register row lists the installations the gateway holds with
its licence ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). The second tenant is
the gateway itself: an AI Gateway area shows what it says of itself, its version, its global brake
and its fleet ([#64](https://github.com/KnowledgeFabric/kf-admin/issues/64),
[Gateway Management](Gateway-Management.md)), its installations, searchable, each with what it
is allowed, what it has used and the register's row for its licence
([#65](https://github.com/KnowledgeFabric/kf-admin/issues/65)), every licence in force beside
what its installation has used ([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)), and
its policy, as it stands ([#67](https://github.com/KnowledgeFabric/kf-admin/issues/67)) and changed
from here ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)), and its usage history
([#70](https://github.com/KnowledgeFabric/kf-admin/issues/70)): the pages of the epic that runs the
gateway from here
([#63](https://github.com/KnowledgeFabric/kf-admin/issues/63)). The third tenant is the CRM
([#87](https://github.com/KnowledgeFabric/kf-admin/issues/87), [CRM](CRM.md)): the partners and
ambassadors programme as records rather than a spreadsheet, starting with a contacts grid that keeps
the sheet's columns and is edited in place, each cell save attributed, version-checked and audited
([#90](https://github.com/KnowledgeFabric/kf-admin/issues/90)), and a dated log of interactions on
each contact behind its *Met?* and *With?* ([#91](https://github.com/KnowledgeFabric/kf-admin/issues/91)).
The fourth is Bookings ([#170](https://github.com/KnowledgeFabric/kf-admin/issues/170),
[Bookings](Bookings.md)): appointments booked with our people from a public page, with a Zoho
Calendar invitation to both: its two roles and the *Hosts* page an Administrator makes a person
bookable on ([#171](https://github.com/KnowledgeFabric/kf-admin/issues/171)), the Zoho connection
([#172](https://github.com/KnowledgeFabric/kf-admin/issues/172)), each host's availability
([#173](https://github.com/KnowledgeFabric/kf-admin/issues/173)), the public page at `/book/{slug}`
([#174](https://github.com/KnowledgeFabric/kf-admin/issues/174)), the event that invites both
([#175](https://github.com/KnowledgeFabric/kf-admin/issues/175)), and the bookings in the console,
upcoming, past and cancelled, each on its page, with a card on the overview
([#176](https://github.com/KnowledgeFabric/kf-admin/issues/176)). It is the one tenant with a page
anyone can reach without signing in. The fifth is Competitors
([#219](https://github.com/KnowledgeFabric/kf-admin/issues/219), [Competitors](Competitors.md)): a
profile of each of our main competitors and how we stand against them, and from its later tickets a
daily scan of what is written about them; so far its two roles, the list and each competitor's page
with the profile typed by hand ([#220](https://github.com/KnowledgeFabric/kf-admin/issues/220)), and its
settings page with the console's Ollama key and the positioning statement
([#221](https://github.com/KnowledgeFabric/kf-admin/issues/221)), a competitor drafted from its website
([#222](https://github.com/KnowledgeFabric/kf-admin/issues/222)), the daily scan that stores what is
written about each one ([#223](https://github.com/KnowledgeFabric/kf-admin/issues/223)), and the news
feeds that list it, global and on each competitor's page, with an item marked irrelevant and back
([#224](https://github.com/KnowledgeFabric/kf-admin/issues/224)).

## It is not a gateway

`kf-ai-gateway` is the gateway, in the traffic sense: it proxies and meters model calls. This is a
back-office console — people log into it and fill in forms. The two are not the same kind of thing,
and if both end up being called "the gateway" in conversation then every future discussion pays for
it. That is why this is `kf-admin` and not `kf-admin-gateway`.

## It calls the gateway's `/admin`; it does not reimplement it

The gateway already has an operator surface. In kf-ai-gateway at `241bf4a` (kf-ai-gateway#35,
#37, #38 and #40, deployed 2026-09-26), `src/KnowledgeFabric.AiGateway/Admin/AdminEndpoints.cs` maps
`/admin/status`; `/admin/installations`, each row with the licence id it holds, how many hold it and
its allowance, filtered by `licence_id=`, `shared=true`, `row=`, `status=`, `seen_since=` and
`app_version_below=`, ordered by `sort=` and paged by `limit=` and `offset=` with the total in
`X-Total-Count`; one installation, `/admin/installations/{id}`; and the revoke and restore posts, behind two bearer tokens that
`Admin/AdminOptions.cs` takes from App Service application settings: `Admin__Token` for every
method, and `Admin__ReadToken` for `GET` alone — with the endpoints **not mapped at all** when no
`Admin__Token` is configured, so an environment without one has no operator surface rather than an
open one. The endpoints the console reads beyond #35's are
[kf-ai-gateway#36](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/36)'s: its status (#37),
the allowances it serves (#38), and, still to come, its policy rows (#39).

The gateway also keeps its own data and policy: `Data/GatewayDbContext.cs` holds `Installations`,
`TierPolicies`, `EnrolmentAttempts` and the spend counters, and says in as many words that these are
policy, changed by `UPDATE` while the service runs.

kf-admin is **one human-facing console over two services**. It calls that API. It does not absorb
the gateway's logic and it does not reach into the gateway's database. Whether the `/admin` surface
itself should eventually move here is not decided; [#63](https://github.com/KnowledgeFabric/kf-admin/issues/63)
keeps it on the gateway with the console as its client, and nothing on this page assumes otherwise.

### The client

`Gateway/GatewayAdminClient.cs`, a typed `HttpClient` registered by `AddGatewayAdmin` in
`Program.cs` ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). It sits beside the
shell's other seams rather than in the licensing area, because the gateway is a second service, not a
licensing feature; licensing is its first reader.

| Setting | From | |
... (121 lines truncated)
</file>

<file path="docs/Bookings.md">
# Bookings

The console's fourth tenant ([#170](https://github.com/KnowledgeFabric/kf-admin/issues/170)):
appointments booked with KnowledgeFabric's people. A person says, from the console, when they can be
booked; anyone with their link picks a slot on a public page, and one Zoho Calendar event invites
both of them. It lives at **Bookings** in the menu (`/Booking/Bookings`), is an area like the others
([Admin Console](Admin-Console.md#features-are-areas-never-new-projects)), and is behind two roles
granted on the Users page like every other area's
([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).

Phase 0 and phase 1 are built: [#171](https://github.com/KnowledgeFabric/kf-admin/issues/171), the
area, who may do what in it, and the *Hosts* page an Administrator makes a person bookable on;
[#172](https://github.com/KnowledgeFabric/kf-admin/issues/172), the connection to Zoho Calendar and
its *Test connection*; [#173](https://github.com/KnowledgeFabric/kf-admin/issues/173), each host's
availability and the slots cut from it; [#174](https://github.com/KnowledgeFabric/kf-admin/issues/174),
the public page where anyone picks a slot and books it, and the booking it writes;
[#175](https://github.com/KnowledgeFabric/kf-admin/issues/175), the Zoho event that invites the host
and the guest, sent again when it failed and deleted when the booking is cancelled; and
[#176](https://github.com/KnowledgeFabric/kf-admin/issues/176), the bookings in the console, upcoming,
past and cancelled, each on its page, and the overview's card. **A booking invites both people, and
the team sees every booking**, so a host's link can be handed out. Phase 2 has begun with
[#177](https://github.com/KnowledgeFabric/kf-admin/issues/177), each host's weekly pattern and the
days they take off it, [#178](https://github.com/KnowledgeFabric/kf-admin/issues/178), the guest's
own link to cancel a booking and book again, and [#199](https://github.com/KnowledgeFabric/kf-admin/issues/199),
each host's calendars as private iCalendar feeds, whose busy time hides the slots their windows would
offer, and [#200](https://github.com/KnowledgeFabric/kf-admin/issues/200), a booking with several hosts
from a link naming them all, `/book/mark+vera`, offered only the times every one of them is free, and
[#201](https://github.com/KnowledgeFabric/kf-admin/issues/201), a host's own link for a meeting with
colleagues, `/book/link/{token}`, titled, expiring in a month by default, its hosts fixed, and
[#202](https://github.com/KnowledgeFabric/kf-admin/issues/202), the team page at `/book`, where a guest
ticks whom to meet among the hosts who chose to be listed. What is still to come is
[below](#what-is-not-here).

## Where it stands

| | State |
|---|---|
| The roles, `Booking.View` and `Booking.Write`, and the policies `booking:view`, `booking:write` and `booking:configure` ([#171](https://github.com/KnowledgeFabric/kf-admin/issues/171)) | **Built** |
| The area's home, `/Booking`, and the menu group ([#171](https://github.com/KnowledgeFabric/kf-admin/issues/171)) | **Built**: `/Booking` leads to the list since #176 |
| *Hosts*, `/Booking/Hosts`: who is bookable, and each one's settings ([#171](https://github.com/KnowledgeFabric/kf-admin/issues/171)) | **Built** |
| The Zoho connection and its *Test connection* ([#172](https://github.com/KnowledgeFabric/kf-admin/issues/172)) | **Built**: the client reads the calendar, and creates and deletes a booking's event since #175 ([below](#the-zoho-connection)) |
| Availability, a host's windows, and the slots cut from them ([#173](https://github.com/KnowledgeFabric/kf-admin/issues/173)) | **Built**: the week view and `SlotCalculator`, with the live bookings as busy time since #174 and the host's calendars' since #199 ([below](#availability)) |
| The public page, `/book/{slug}`, and the booking row ([#174](https://github.com/KnowledgeFabric/kf-admin/issues/174)) | **Built**: the month, the day, the form, the slot taken on save, the confirmation ([below](#the-public-page)) |
| The Zoho event, its invitation, *Send invitation again* and the cancel, and each booking's page ([#175](https://github.com/KnowledgeFabric/kf-admin/issues/175)) | **Built** ([below](#the-event)), and confirmed against the live API by the live check, 4 November 2026 ([below](#what-the-live-api-was-found-to-do)) |
| The bookings in the console, each booking's page whole, and the overview's card ([#176](https://github.com/KnowledgeFabric/kf-admin/issues/176)) | **Built** ([below](#the-bookings)) |
| A weekly pattern per host, read as windows, with days taken off ([#177](https://github.com/KnowledgeFabric/kf-admin/issues/177)) | **Built** ([below](#the-pattern)) |
| Each person sees and changes their own host settings, availability and bookings, and an Administrator everyone's ([#193](https://github.com/KnowledgeFabric/kf-admin/issues/193)) | **Built** ([above](#who-may-do-what)) |
| The guest's own cancel, and booking again, from a link on the confirmation and in the event ([#178](https://github.com/KnowledgeFabric/kf-admin/issues/178)) | **Built** ([below](#the-guests-link)) |
| A host's calendars as private iCalendar feeds, their busy time hiding slots ([#199](https://github.com/KnowledgeFabric/kf-admin/issues/199)) | **Built** ([below](#calendar-feeds)): a calendar on Zoho is served by its own private address, so [#179](https://github.com/KnowledgeFabric/kf-admin/issues/179)'s read of Zoho's busy time is not needed for it |
| A booking with several hosts, `/book/{slug}+{slug}`, offered only the times they are all free, one booking and one event holding them all ([#200](https://github.com/KnowledgeFabric/kf-admin/issues/200)) | **Built** ([below](#several-hosts-1)) |
| Host-made links for a meeting with colleagues, titled and expiring, their hosts fixed ([#201](https://github.com/KnowledgeFabric/kf-admin/issues/201)) | **Built** ([below](#booking-links) and [here](#booking-links-in-the-console)) |
| `/book` listing the hosts who opt in, for a guest to choose ([#202](https://github.com/KnowledgeFabric/kf-admin/issues/202)) | **Built** ([below](#the-team-page)) |
| A booking as a CRM interaction ([#180](https://github.com/KnowledgeFabric/kf-admin/issues/180)) | Not yet ([below](#what-is-not-here)) |

## Who may do what

Two roles, granted on `/Users` (*Booking: View* and *Booking: Write* on the page, *Prenotazioni* in
Italian), and three policies (`Security/ConsolePolicies.cs`), from #170's decision 1 as
[#193](https://github.com/KnowledgeFabric/kf-admin/issues/193) changed it: **each person sees and
changes their own, and only an Administrator anyone's**.

| Policy | Needs | What it allows |
|---|---|---|
| `booking:view` | `Booking.View` or `Booking.Write` | The menu group, **one's own** availability, read (#173), **one's own** bookings on the list and each one's page with its guest (#175, #176), and one's own week on the overview's *Bookings* card (#176). Nobody else's: a colleague's week and booking are `404` (#193) |
| `booking:write` | `Booking.Write` | Changing **one's own** availability (#173) and **one's own host settings** (#193), and sending again and cancelling **a booking made with oneself** (#175), from its page or its row on the list (#176) |
| `booking:configure` | `Administrator` | *Hosts*: who is bookable, removing a host and anyone's settings, and the *Zoho Calendar* card with its *Test connection* (#172); and anyone's availability (#173) and anyone's bookings (#175), every guest with them, since someone away still has slots open |

The public page, `/book/{slug}` ([below](#the-public-page)), asks no policy: it is anonymous by
design, the one route of the console that is.

`Administrator` and the name `admin` meet all three, as everywhere. A writer never sees or touches a
colleague's availability, settings or bookings: an Administrator does. **A booking with several hosts
is the own of every one of them** (#200, decision 9): each sees it, its guest with it, and may send it
again or cancel it under `booking:write`, as if it were theirs alone. **A booking link** (#201,
decision 9) is seen by every host on it under `booking:view` and ended by any of them under
`booking:write`, because it books their time; its maker, who leads it, makes and edits it under
`booking:write`; an Administrator sees, edits and ends every one, and makes one for any host as its lead
([below](#booking-links-in-the-console)). Until #193 (2026-11-04),
`booking:view` read every host's week and every booking with its guest, as the CRM's view role reads
every contact, and a host's settings were an Administrator's alone. `Booking.Write` is one of the write roles that read
the audit log (`ConsoleRoles.WriteRoles`), so a writer reads their own entries at `/Audit`, as every
other area's writer does. A session holding only a Booking role sees the overview rather than the
*no roles* card, since `booking:view` is one of `ConsolePolicies.AreaViews`, and the overview's
*Bookings* card ([below](#the-overview)).

## The area's home

`/Booking` leads to the list, `/Booking/Bookings` ([below](#the-bookings)), since #176. What the home
said before heads the list: whether the connection to Zoho is configured, and, to an Administrator
alone (#193), how many names are bookable and how many of those are enabled, with *Hosts* and *Test
it on Hosts* beside them. *Configured* is what the settings say, all six present, and never a call to Zoho: a
revoked refresh token still reads *configured* there, and *Refused* on the Hosts page's test. Not
configured, it says so, and no invitation can be sent.

The menu group *Bookings* has three entries: *Bookings*, the list; *Availability*, the week view
([below](#availability)); and *Hosts*, shown only to a session that meets `booking:configure`, with
an *Availability* button on each host's row.

## Hosts

... (1468 lines truncated)
</file>

<file path="docs/Branching.md">
# Branching

This repository follows the KnowledgeFabric branching strategy documented in kf-app:
**[Branching and Releasing](https://github.com/KnowledgeFabric/kf-app/blob/main/docs/DevOps/Branching-and-Releasing.md)**.

That page is the convention. This page records only what differs here, so the two cannot drift
apart on the parts they share.

## Naming

```
{type}/{ticket}
```

| Type | Use for | Example |
|---|---|---|
| `feature/` | New feature or story — work in isolation until ready for integration | `feature/2` |
| `hotfix/` | Emergency fix to production code | `hotfix/23` |
| `release/` | Short-lived stabilisation branch, named for the version | `release/1.2.0` |

`{ticket}` is the **GitHub issue number** — digits only, no `#`, nothing appended. Every branch
should trace to an issue; if there isn't one, open one first.

There is no `bug/` category. A defect is a `feature/` branch against its issue unless it is an
emergency fix to something already in production, which is `hotfix/`.

## Base branch: `main`

**This is the one place kf-admin deviates.** kf-app bases `feature/` and `release/` branches on
`develop`, with only releases reaching `main`. **kf-admin has no `develop` branch**, so every
branch is based on `main` and its pull request targets `main`.

```bash
git checkout main
git pull
git checkout -b feature/2
```

| Branch | Base here | Merges to here |
|---|---|---|
| `feature/‹ticket›` | `main` | `main` |
| `hotfix/‹ticket›` | `main` | `main` |
| `release/‹version›` | `main` | `main` |

## Releasing

kf-app's release process — the `CHANGELOG.md` update on every merge, the `VERSION` file, the
`vMAJOR.MINOR.PATCH` tag on `main`, the merge back into `develop` — **is not in force here**. This
repository has no `CHANGELOG.md`, no `VERSION` file and no tags, and the tool is not released
independently of kf-app today.

Adopt that process if and when this repository ships on its own; until then `release/` branches are
unlikely to be needed. Follow kf-app's page for the mechanics if you do.

## Agent sessions

Claude Code and similar tooling are usually handed a branch name by the harness that runs them —
`claude/friendly-heisenberg-v6drfi` and the like. **The convention above wins over that name.** A
session handed such a branch should create and push `{type}/{ticket}` for the issue it is working
on:

```bash
git checkout -B feature/5
git push -u origin feature/5
```

Those harnesses generally carry a standing instruction not to push to any branch but the one they
were given, without explicit permission. **This page and [CLAUDE.md](../CLAUDE.md) are that
permission**, given in advance so no one has to be asked mid-session.

Two cases where the handed name stays:

- **No issue number applies** — exploratory work, or a question that turns into a small change with
  no ticket. Open an issue if the work is worth a branch; otherwise the harness name is fine.
- **A pull request is already open against the handed branch.** Re-pointing it then costs the review
  thread. Leave it, and say so.

The mixed history in this repository predates this rule: #17 merged from `feature/3` while #18 and
#19 merged from `claude/…` branches, because the earlier version of this page gave the handed name
precedence.
</file>

<file path="docs/Competitors.md">
# Competitors

The console's fifth tenant ([#219](https://github.com/KnowledgeFabric/kf-admin/issues/219)): our main
competitors, one page each that says what they do and how we stand against them, and what is written about
them, found every morning by the console and read by a model. It lives at **Competitors** in the menu
(`/Competitors`), is an area like the other four
([Admin Console](Admin-Console.md#features-are-areas-never-new-projects)), and is behind two roles
granted on the Users page like every other area's
([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).

Phase 0 is built: [#220](https://github.com/KnowledgeFabric/kf-admin/issues/220), the area, who may do
what in it, the list, each competitor's page with its profile typed by hand, the delete and restore, and
the overview's card; and [#221](https://github.com/KnowledgeFabric/kf-admin/issues/221), the console's
Ollama key and the area's settings page, with the *Ollama* card and the positioning statement. Phase 1
has begun with [#222](https://github.com/KnowledgeFabric/kf-admin/issues/222): **a competitor added from
its website address**, the console reading the site and a model drafting the profile into the form for a
person to check and save ([below](#from-a-website)), the feeds and newsroom pages it finds kept as the
competitor's **sources** ([below](#sources)), and ***Refresh analysis***, a new draft beside the current
values, field by field ([below](#refresh-analysis)); [#223](https://github.com/KnowledgeFabric/kf-admin/issues/223),
**the daily scan**: at 08:30 Europe/Rome, and on *Scan now*, the console reads each competitor's feeds and
newsroom pages, Google News in English and Italian and Ollama's web search, drops what it has already
seen, and has the model keep what is news about that competitor, in two lines, with the scan's record
([below](#the-scan)); and [#224](https://github.com/KnowledgeFabric/kf-admin/issues/224), **the news
feeds**: `/Competitors/News`, everyone's items newest first, 25 a page with *More*, filtered by competitor
and kind, and the competitor's own on its page; an item a writer marks irrelevant, which leaves the feeds
and the counts and can be put back; and the overview's week ([below](#the-news-feeds)); and
[#225](https://github.com/KnowledgeFabric/kf-admin/issues/225), **who is told**: one notification per person
per scan that stored items, *New items from Talentware, EPlato and 2 more*, to everyone with a Competitors role
and nobody else, leading to the global feed ([below](#who-is-told)). What is still to come, and what #219 left
open, is [below](#what-is-still-open).

## Where it stands

| | State |
|---|---|
| The roles, `Competitors.View` and `Competitors.Write`, and the policies `competitors:view`, `competitors:write` and `competitors:configure` ([#220](https://github.com/KnowledgeFabric/kf-admin/issues/220)) | **Built** |
| The menu group: *Competitors*, *News* and *Settings* for an Administrator ([#220](https://github.com/KnowledgeFabric/kf-admin/issues/220); *News* marked *coming* until #224) | **Built** |
| The list, `/Competitors`, each competitor's page, the form, the delete and restore ([#220](https://github.com/KnowledgeFabric/kf-admin/issues/220)) | **Built** ([below](#the-list)) |
| The overview's card: how many, and the three edited last ([#220](https://github.com/KnowledgeFabric/kf-admin/issues/220)); this week's items, the last scan, and an Administrator's line on the scan ([#224](https://github.com/KnowledgeFabric/kf-admin/issues/224)) | **Built** ([below](#the-overviews-card)) |
| The console's Ollama key, the *Ollama* card and the positioning statement on `/Competitors/Settings` ([#221](https://github.com/KnowledgeFabric/kf-admin/issues/221)) | **Built** ([below](#the-settings-page)); `Ollama--ApiKey` in Key Vault before it merges |
| A competitor added from its website, the model's draft beside the form, its sources, *Refresh analysis* ([#222](https://github.com/KnowledgeFabric/kf-admin/issues/222)) | **Built** ([below](#from-a-website)) |
| The daily scan at 08:30 Europe/Rome and *Scan now*, its record and the items it stores ([#223](https://github.com/KnowledgeFabric/kf-admin/issues/223)) | **Built** ([below](#the-scan)); Ollama's search allowance still to be read off the account ([below](#what-is-still-open)) |
| The feeds, `/Competitors/News` and each competitor's own, an item marked irrelevant and back, the list's newest item ([#224](https://github.com/KnowledgeFabric/kf-admin/issues/224)) | **Built** ([below](#the-news-feeds)) |
| One notification per person per scan with items, to the people with a Competitors role alone ([#225](https://github.com/KnowledgeFabric/kf-admin/issues/225)) | **Built** ([below](#who-is-told)) |

## Who may do what

Two roles, granted on `/Users` (*Competitors: View* and *Competitors: Write* on the page, *Concorrenti*
in Italian), and three policies (`Security/ConsolePolicies.cs`), from #219's decision 1:

| Policy | Needs | What it allows |
|---|---|---|
| `competitors:view` | `Competitors.View` or `Competitors.Write` | The menu group, the list, each competitor's page, both feeds (the global one, `/Competitors/News`, and the *News* card on a competitor's page, #224), the overview's card |
| `competitors:write` | `Competitors.Write` | *Add a competitor*, *Read the site* and *Edit*; *Refresh analysis* and the *Sources* card's add, on and off, and remove (#222); *Mark as irrelevant* and *Mark as relevant* on a news item (#224) |
| `competitors:configure` | `Administrator` | *Delete* on a competitor's page, *Deleted competitors* and its *Restore*, *Settings* with the *Ollama* card and the positioning statement (#221), the *Daily scan* card with *Scan now* (#223), and the overview card's line on the scan (#224) |

`Administrator` and `admin` meet all three, as everywhere. `Competitors.Write` includes
`Competitors.View`, and like every area's write role it lets a person read the audit log, their own
entries alone unless they are an Administrator (#99). Pages ask the policies, never a role.

The names holding a Competitors role or `Administrator` are `ConsolePeople.CompetitorsAsync`, beside
the CRM's and the Bookings area's: who the scan's notification tells, and who it goes on saying anything to
([below](#who-is-told), #225). **`admin` is never one of them** (#108).

## The list

`/Competitors`: every live competitor by name, case aside, with its one-line summary, its website as a
link opening in a new tab, **its newest item's date** (#224: the newest not marked irrelevant, by the
feeds' date, linking to the feed filtered to it, or *None yet*), and when it was last edited (who, on
hover). *Add a competitor*, under `competitors:write`, opens on the website's address
while the model can be asked ([below](#from-a-website)), and on the blank form when it cannot; an
Administrator also has *Deleted competitors*.

## A competitor's page

`/Competitors/{id}`: the name, the summary and the website at the head, with who last edited it and
who added it, which model drafted the profile last and when (*Profile last drafted by gpt-oss:120b, …*,
from `analysed_model` and `analysed_at`, when a draft was ever taken), and *Edit* and *Refresh analysis*
under `competitors:write`, the second only while the model can be asked. Beneath, the profile as six
cards, each shown whole with its line breaks:

| Card | Field | What it holds |
|---|---|---|
| *What they do* | `what_they_do` | Their products and services, and who buys them |
| *How they are like us* | `similarities` | Where they and KnowledgeFabric meet: the same buyers, problem or answer |
| *How we differ* | `differences` | What sets us apart, either way |
| *Where we offer more* | `our_advantages` | Where a customer gets more from us |
| *Where they offer more* | `their_advantages` | Where a customer gets more from them |
| *Notes* | `notes` | Anything else worth keeping |

A field never written says so. Beneath them the *Sources* card ([below](#sources)), then the ***News*
card**, the competitor's own feed: its newest ten as the global feed draws them, *More* to that feed
filtered to it when it holds more, and *Show irrelevant* ([below](#the-competitors-own)); and at the
foot *Delete*, under `competitors:configure` ([below](#delete-and-restore)).

## The form

*Add a competitor* and *Edit* open one form (`CompetitorForm`), bound invariantly as every form is
(#102):

... (659 lines truncated)
</file>

<file path="docs/Console-Shell.md">
# Console Shell

The ASP.NET Core application that the admin console's features live inside — one project, one
login, one deploy, features as areas. Built for
[#15](https://github.com/KnowledgeFabric/kf-admin/issues/15); the licence issuing area that goes
inside it is [#6](https://github.com/KnowledgeFabric/kf-admin/issues/6), and hosting is
[#7](https://github.com/KnowledgeFabric/kf-admin/issues/7).

It is `src/KnowledgeFabric.AdminConsole/`, and it is in `KnowledgeFabricLicensing.sln`, so the
ordinary solution build and CI build it.

## Running it locally

```bash
dotnet build KnowledgeFabricLicensing.sln -c Release

cd src/KnowledgeFabric.AdminConsole
dotnet user-secrets set "Authentication:Users:admin" "<pick something>"
dotnet run
```

Sign in as `admin` with that password: `admin` holds every role by construction, so it sees every
area and the Users page, where it grants roles to anyone else you add as
`Authentication:Users:<their name>` (the roles are held in memory locally, and gone on restart).
Nothing signs in without a name: an `Authentication:SharedPassword` left in user-secrets is ignored,
with one warning at startup. A password goes in user-secrets, never in `appsettings.json` and never
in `launchSettings.json`.
The one passphrase this repository ever committed — in `launchSettings.json`, of all places — is
still in its history, and no longer protects the key the console signs with: `rekey` replaced it
(#3; see [Issuing a License](Issuing-A-License.md#key-custody)). Nothing sensitive goes in a tracked file.

To sign licences locally, give it the contract fixture set's throwaway key. The page says it is a
test key, what it signs validates nowhere, and outside Development the console refuses to sign with
it at all:

```bash
dotnet user-secrets set "Licensing:PrivateKey" "$(cat ../../contract/test-keys/contract-test.private.key)"
dotnet user-secrets set "Licensing:PrivateKeyPassphrase" "contract-fixtures-test-key"
```

Without them the issue form still previews, and says why it cannot sign.

With no password configured the console starts and `/health` answers, but no sign-in can succeed,
and it logs an error saying so. That is deliberate: a misconfigured deployment should fail closed
and be obvious about why, rather than fail open.

## What the shell provides

| | Where |
|---|---|
| Authentication | `Security/AuthenticationRegistration.cs` |
| Authorisation policies, and the roles they ask for | `Security/ConsolePolicies.cs`, `Security/ConsoleRoles.cs`, `Security/AuthenticationRegistration.cs` |
| Audit | `Auditing/` — `IAuditLog`, and `AuditActionFilter` registered globally |
| Feature state | `Storage/IFeatureStateStore.cs` — `feature_state` in `kf_admin` with a database, memory without one (#135) |
| The names a record may name as a person | `Security/ConsolePeople.cs` — everyone holding a CRM role, plus `admin`, for the CRM's *By* (#90), read from the role store so that no page has to |
| Database | `Data/` — the `kf_admin` context, migrated at startup ([License Register](License-Register.md)) |
| The gateway's `/admin` | `Gateway/` — `GatewayAdminClient`, reading with the read token and writing with the write token (#69), `InstallationQuery` for the installations list's filters, and `GatewayStatusCache` for the status two pages share ([Admin Console](Admin-Console.md#the-client), [Gateway Management](Gateway-Management.md)) |
| Layout, navigation, error pages | `Views/Shared/` |
| The person's own settings | `PreferencesController`, `Preferences/` — the overview's order ([User settings](#user-settings)) |
| Language | `Localisation/` — the request's culture from its cookie, `Resources/ConsoleResource.resx` and `.it.resx`, the switcher's `CultureController`, and forms bound invariantly ([Localisation](Localisation.md)) |
| Readiness | `/health` |
| Installed as an app | `wwwroot/manifest.webmanifest`, `wwwroot/sw.js`, `wwwroot/img/icons/`, `OfflineController`, `Views/Shared/Sections/_LaunchSplash.cshtml` — the manifest, the worker, the offline page and the launch animation ([Installed as an app](#installed-as-an-app)) |
| The anonymous surface | `/health`, `/offline`, the sign-in page, the error pages, the manifest and the worker's assets — and `/book/*`, the public booking page ([Bookings](Bookings.md#the-public-page), #174), the one route that shows data to an anonymous caller. It has its own layout, `Views/Shared/_PublicLayout.cshtml`, because the console's layouts carry the menu, the navbar, the manifest and the worker's registration, and a public page must carry none of them: nothing on it leads into the console, and nothing of it is cached on a phone |

### Authentication is a name and a secret of one's own

One way in ([#68](https://github.com/KnowledgeFabric/kf-admin/issues/68)), behind one cookie
session: lockout after five failed attempts per caller and per name, a rate limit on the login
endpoint, HTTPS-only cookies, anti-forgery on every form by default rather than by attribute.

One Key Vault secret per person, `Authentication--Users--<name>`, holding their password. A session
under a name is that person's: every audit entry it writes carries the name as its actor and
`Attributable = true`, and the register records it as *issued by login*. A name signs in only with
its own secret. The login page always asks for a name, and a sign-in without one is refused like a
wrong password: counted against the caller toward its lockout, and audited as `console:sign-in-failed`
with the actor `(no name)`, which no secret's name can be.

**The shared password is retired** ([#89](https://github.com/KnowledgeFabric/kf-admin/issues/89),
which records the day its secret was disabled). `Authentication--SharedPassword`, with no name, was
the first week's answer, as #6 asked for, kept beside the named secrets so that nobody was locked out
on the day the first one went in, and holding no role once [#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)
gave roles to names. Its secret is disabled in Key Vault, and the console reads it no more: a
configured `Authentication:SharedPassword` is ignored, with one warning at startup
(`Security/RetiredSharedPassword.cs`) rather than an error, so that a secret nobody disabled does not
fail a deploy. What it leaves behind is history. Every audit entry and register row written under it
names the actor `shared-credential` with `Attributable = false`, a credential rather than a person,
and the audit page still shows them as *shared password*; so `shared-credential` is reserved, and a
secret configured under that name signs no one in.

A session outlives the credential that opened it only until its next request: a name whose secret
is disabled, or a session opened by the shared password before it was retired, is signed out by the
cookie's validation rather than at the cookie's expiry.

Why not Entra ID: the console runs on the University's Azure, whose tenant cannot register the
people who operate it ([#15](https://github.com/KnowledgeFabric/kf-admin/issues/15#issuecomment-5816165987)).
Entra ID stays the end state for a tenant KnowledgeFabric controls, and replaces the named secrets
through the same seam: a person's name from the token instead of from `Authentication--Users`, and a
group for each role ([below](#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).
Swapping the scheme is a change to `AuthenticationRegistration.AddConsoleAuthentication` and to
`AccountController` — the only file that knows a password exists — and to no page, policy or
... (428 lines truncated)
</file>

<file path="docs/CRM.md">
# CRM

The console's third tenant ([#87](https://github.com/KnowledgeFabric/kf-admin/issues/87)): the
partners and ambassadors programme, run from the console instead of a shared spreadsheet. One row
per person, every change attributed to the person who made it and audited, and nobody's save
overwriting anybody's. It lives at **CRM → Partnerships** in the menu (`/Crm/Contacts`), with
**CRM → Follow-ups** (`/Crm/FollowUps`) and **CRM → Statistics** (`/Crm/Statistics`) beside it and a
section on the overview, and is an
area, not an application ([Admin Console](Admin-Console.md#features-are-areas-never-new-projects)),
behind the roles per area that [#88](https://github.com/KnowledgeFabric/kf-admin/issues/88) brought
in for it ([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).

**The page looks like the sheet** (#87, decision 10). The team sat down at `PartnersAmbassadors.xlsx`
and knew where everything was; the grid keeps the sheet's columns, in the sheet's order, under the
sheet's names but one, and one column the sheet did not have, with a frozen header, sorting by heading, a filter per column, and cells
edited in place. What changes is underneath: each cell save is one attributed, version-checked write to a row
of `crm_contacts`, and *Met?* and *With?* are drawn from a log of interactions, a row each, and the
contact's next action beneath them, rather than typed into.

**Two names are the team's, not the sheet's** ([#105](https://github.com/KnowledgeFabric/kf-admin/issues/105)):
the grid's page and its menu item are *Partnerships* (*Partnership* in Italian), and the sheet's *E*
is headed *Engagement Level*. Only what is shown moved: the URL is still `/Crm/Contacts`, the field
a cell save names is still `e`, the filter is still `?e=`, the export's column is still
`engagement`, and the overview's count is still of *Contacts*, since it counts people.

**One column is the team's, not the sheet's** ([#126](https://github.com/KnowledgeFabric/kf-admin/issues/126)):
*Presentation*, which presentations a contact has been shown, by their codes, after *With?*.

**In Italian the headings are translated** ([#107](https://github.com/KnowledgeFabric/kf-admin/issues/107)):
*Nome*, *Portato da*, *Attività attuale*, *Livello di coinvolgimento*, *Incontrato?*, *Con chi?*,
*Presentazione*, *Tipo di partnership*, *Fase*, *Note*, the [glossary](Localisation.md#glossary)'s words, from the
`Crm.Field.*` keys the grid, the follow-ups, a row's details and the import's preview share. The
sheet's names are the English ones; what a heading names underneath, its field, filter and
export column, is the same in both languages.

## Where it stands

| | State |
|---|---|
| Roles per area, `crm:view` and `crm:write` ([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)) | **Built**: every page here asks `crm:view`, held through *CRM: View* or *CRM: Write*, and every write `crm:write`, held through *CRM: Write*, but for the import and a contact's delete, an Administrator's; `admin` and an Administrator hold both |
| The shared password retired before the first contact goes in ([#89](https://github.com/KnowledgeFabric/kf-admin/issues/89)) | **Built**: nothing signs in without a name, so every CRM write names a person |
| The area and its contacts grid: the sheet's columns, edited in place; stage, track, engagement and originated-by ([#90](https://github.com/KnowledgeFabric/kf-admin/issues/90)) | **Built**, this page. `crm_contacts` is created by the migration on the first start after it deploys |
| Interactions: a dated log of calls, meetings and messages, drawn into *Met?* and *With?* ([#91](https://github.com/KnowledgeFabric/kf-admin/issues/91)) | **Built**, [below](#interactions). `crm_interactions` is created by the migration on the first start after it deploys |
| Follow-ups: the next action, a follow-ups grid, and the CRM's card on the overview ([#92](https://github.com/KnowledgeFabric/kf-admin/issues/92)) | **Built**, [below](#the-next-action). Its three columns on `crm_contacts` are added by the migration on the first start after it deploys |
| The import of the spreadsheet, once, then the sheet frozen ([#93](https://github.com/KnowledgeFabric/kf-admin/issues/93)) | **Built**: the export format, *Export CSV* and `/Crm/Import`, [below](#export-and-import). The import on production and freezing the sheet are the team's, [on the day](#the-sheets-one-off) |
| Deleting a contact an Administrator's, behind its name typed, and soft: restored from *Deleted contacts* ([#119](https://github.com/KnowledgeFabric/kf-admin/issues/119)) | **Built**, [below](#delete). `deleted_by` and `deleted_at` on `crm_contacts` are added by the migration on the first start after it deploys |
| People shown by their initials in the grid, set on the Users page ([#115](https://github.com/KnowledgeFabric/kf-admin/issues/115)) | **Built**, [below](#people-by-their-initials). `console_initials` is created by the `AddConsoleInitials` migration on the first start after it deploys; until an Administrator sets them, everyone is shown by name |
| *Presentation*: which presentations a contact has been shown, by their codes ([#126](https://github.com/KnowledgeFabric/kf-admin/issues/126)) | **Built**, [below](#the-grid). `presentation` on `crm_contacts` is added by the `AddCrmPresentation` migration on the first start after it deploys |
| Logging a call asks for the next action every time, starting empty, in one save, and *No next action planned?* when it is left empty ([#111](https://github.com/KnowledgeFabric/kf-admin/issues/111)) | **Built**, [below](#the-next-action). Nothing stored changes |
| *Current activity* and *Notes* folded to their first lines, the rest on hover and behind *more* ([#114](https://github.com/KnowledgeFabric/kf-admin/issues/114)) | **Built**, [below](#the-grid). Nothing stored changes |
| *Engagement Level* in the sheet's colours, orange for 1 to acid green for 5 ([#131](https://github.com/KnowledgeFabric/kf-admin/issues/131)) | **Built**, [below](#the-grid). Nothing stored changes |
| A next action marked *Done*: logged as an interaction, and cleared or replaced, in one submit ([#133](https://github.com/KnowledgeFabric/kf-admin/issues/133)) | **Built**, [below](#done). Nothing stored changes |
| Statistics for the go-to-market story: Roberto's funnel, the stage *Rejected*, and why a contact declined ([#120](https://github.com/KnowledgeFabric/kf-admin/issues/120)) | **Built**, [below](#statistics). `decline_reason` on `crm_contacts` is added by the `AddCrmDeclineReason` migration on the first start after it deploys; *Rejected* is a stage by name and needs none |
| A contact is an individual or represents a company: a field on the row's details, a filter, and a mark on the name ([#146](https://github.com/KnowledgeFabric/kf-admin/issues/146), part of [#145](https://github.com/KnowledgeFabric/kf-admin/issues/145)) | **Built**, [below](#individual-or-company). `entity` on `crm_contacts` and on `crm_contact_changes` is added by the `AddCrmContactEntity` migration on the first start after it deploys, null on every row |
| Introductions: the customers a partner introduced, as rows on the partner's page, each with a stage recorded as it moves ([#147](https://github.com/KnowledgeFabric/kf-admin/issues/147), part of [#145](https://github.com/KnowledgeFabric/kf-admin/issues/145)) | **In progress**, [below](#introductions): the first of its two pull requests. `crm_introductions` and `crm_introduction_changes` are created by the `AddCrmIntroductions` migration on the first start after it deploys; the card with its rows, form and cell edits, the change record and the overview's counts are built. The row's panel, delete and restore, the shared-customer warning and the export and import are the second pull request |
| The introductions funnel on the statistics page: by stage, by the partner's track and how far each got, on a day gone and over time ([#150](https://github.com/KnowledgeFabric/kf-admin/issues/150), part of [#145](https://github.com/KnowledgeFabric/kf-admin/issues/145)) | **Built**, [below](#what-the-partners-produced). Nothing stored changes: it reads `crm_introductions` and `crm_introduction_changes` |
| A contact added from a photo of a business card, read by a vision model on Ollama Cloud and checked before it is saved ([#161](https://github.com/KnowledgeFabric/kf-admin/issues/161)) | **Built**, [below](#from-a-business-card). Nothing stored changes; it needs the console's Ollama key, `Ollama--ApiKey`, in Key Vault since [#221](https://github.com/KnowledgeFabric/kf-admin/issues/221) ([Provisioning](Provisioning.md#the-ollama-key)), and until then the page says reading a card is not configured |
| A QR code on the business card read with it, its link followed to the page it leads to ([#163](https://github.com/KnowledgeFabric/kf-admin/issues/163)) | **Built**, [below](#a-qr-code-on-the-card). Nothing stored changes, and nothing to configure |
| Stage changes recorded, so the statistics can be shown over time ([#139](https://github.com/KnowledgeFabric/kf-admin/issues/139)) | **Built**: recording, [below](#the-change-record), with `crm_contact_changes` created, and a row for every contact as it stands, by the `AddCrmContactChanges` migration on the first start after it deploys; and the statistics [on a day gone and over time](#on-a-day-gone-and-over-time). Conversion between stages and time spent in each are not built: Roberto's call |

## The grid

`/Crm/Contacts`, **CRM → Partnerships** in the menu: one row per contact, every contact on the one
page. The programme is dozens of people, so there is no paging; paging is a ticket if it reaches
hundreds. The columns are the sheet's, in its order and under its names, but for *E* (#105), with
*Presentation* (#126) the one the sheet did not have:

| Column | The sheet's name | What it holds | Edited as |
|---|---|---|---|
| **Name** | *Name* | The person. The name is the link to the row's details; click beside it to change it. A contact marked a company carries a building beside it ([#146](#individual-or-company)), the organisation on hover | Text |
| **By** | *By* | Who brought them in: a console user, not initials (#87, decision 5), shown [by their initials](#people-by-their-initials) where they have some, `VS` with `vera` on hover. The dropdown offers every name holding a CRM role, [never `admin`](#admin-is-no-one) | Dropdown |
| **Current activity** | *Current Activity* | A role, or a pasted LinkedIn headline | Text |
| **Engagement Level** | *E* | How warm they are, 1 to 5, on the sheet's own scale (below), or blank | Dropdown |
| **Met?** | *Met?* | The interactions, a line each by day, as the sheet wrote them: `Call 23.09.26`; then the [next action](#the-next-action), set apart beneath them: `FIX a meeting by 15.10.26` | Never typed into: a click opens the row's [panel](#interactions) beneath it |
| **With?** | *With?* | Who from KnowledgeFabric took part in each, on the same line: `rob, vera`, or `RR, VS` [by their initials](#people-by-their-initials); then the next action's owner, the same way | As *Met?* |
| **Presentation** | None: the team's ([#126](https://github.com/KnowledgeFabric/kf-admin/issues/126)) | Which presentations they have been shown, by their codes: `C22`, or `C22,T51` once a second has been. Free text, trimmed, its case and its commas as typed, up to 200 characters; the column is sized for a code or two, and more wrap | Text |
| **Kind of partnership** | *Kind of partnership* | The track: *Ambassador*, *Business partner* or *Undecided* | Dropdown |
| **Stage** | *Proposed partnership* | Where they stand, one of the eight stages below. The sheet's one value in this column, *Pre-proposal agreed*, was a stage, so the column became one | Dropdown |
| **Notes** | *Notes* | Free text, with its line breaks | A block of text: Enter saves, Shift+Enter starts a line |

Email, phone, LinkedIn, organisation and individual or company are not columns, to keep the sheet's
width: they are on the row's details ([below](#the-rows-details)), the search box covers the
organisation, and *Name* has the filter and the mark for individual or company.

**The stages**, in the order they are passed through (#87, decision 4): *To contact*, *Contacted,
awaiting reply*, *Meeting planned* (to fix or fixed; the next action will say which), *Met*,
*Pre-proposal agreed*, *Active*, *Declined or dormant*, and *Rejected* (*Scartato*, #120): the team
decided not to go on, the person not being a fit to work with, where *Declined or dormant* is the
contact's decision. **The tracks**: *Ambassador*, *Business
partner*, *Undecided*. **The engagement scale** is the sheet's own, from its cell comment, with the
team's Italian kept in the labels (#87, decision 8): *1 Detached (Distaccato)*, *2 Lukewarm
(Tiepido)*, *3 Interested (Interessato)*, *4 Committed (Impegnato)*, *5 Passionate (Appassionato)*.
The cell shows the number, as the sheet did, with the label on hover. All three are enums in
`Crm/Contact.cs`, with their names in `CrmWords`: changed by a ticket, not a table the team edits,
because a stage deleted from under forty contacts would be the sheet's problem in a new form.

**Engagement Level is coloured as the sheet coloured it** ([#131](https://github.com/KnowledgeFabric/kf-admin/issues/131)):
orange for 1, yellow for 3, acid green for 5, and 2 and 4 between their neighbours; a blank is
uncoloured. The colour follows the cell's value, on the grid, the follow-ups and a row's details
alike, so a save recolours it at once, and an open editor drops it. Only what is shown changes: the
... (1202 lines truncated)
</file>

<file path="docs/Gateway-Management.md">
# Gateway Management

Running the AI gateway from the console ([#63](https://github.com/KnowledgeFabric/kf-admin/issues/63)):
what it knows of itself and its fleet, what it is spending, what each licence's installation has
used and has left, and the levers an operator moves. It lives at **AI Gateway** in the
menu (`/Gateway`), and is the console's second tenant after licensing: an area, not an application
([Admin Console](Admin-Console.md#features-are-areas-never-new-projects)).

The console calls the gateway's `/admin` and never its database
([Admin Console](Admin-Console.md#it-calls-the-gateways-admin-it-does-not-reimplement-it)). Anything
these pages need that the gateway does not expose is a gateway ticket, under the companion epic
[kf-ai-gateway#36](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/36), and the console
never waits on one: every page here says what it would show against a gateway that predates the
endpoint it reads.

## Where it stands

| | State |
|---|---|
| The read-only token the pages read with ([kf-ai-gateway#40](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/40)) | **Deployed and loaded** 2026-09-26: `Gateway--AdminToken` holds the gateway's `Admin__ReadToken` ([Provisioning B3](Provisioning.md#b3-load-the-secrets)) |
| The area and its overview: status, the brake, the fleet ([#64](https://github.com/KnowledgeFabric/kf-admin/issues/64)) | **Built and live** 2026-09-26, the day [kf-ai-gateway#37](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/37) deployed `GET /admin/status` (`f644650`). Against an older gateway the page says it does not report status yet |
| The gateway's card on the console's overview (#64) | **Built** |
| Installations: the fleet, searchable, and one installation with its allowance and licence ([#65](https://github.com/KnowledgeFabric/kf-admin/issues/65)) | **Built**, against [kf-ai-gateway#38](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/38) as deployed at `241bf4a`. Against an older gateway the pages say it does not report usage yet ([below](#installations)) |
| Usage by licence ([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)) | **Built**, against kf-ai-gateway#38 at `241bf4a` and the licence ids from #35: every licence in force beside its installation's usage, as a page and as CSV, and the usage columns on a register row's installations ([below](#usage-by-licence)) |
| Policy, read-only ([#67](https://github.com/KnowledgeFabric/kf-admin/issues/67)) | **Built**, against [kf-ai-gateway#39](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/39) as deployed at `34e05ec`: the three allowance rows and the gateway levers, each beside what it reaches ([below](#policy)). Against an older gateway the page says it does not report policy yet |
| Revoke and restore, audited ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)) | **Built** ([below](#revoke-and-restore)), with the durable audit log. Needs `Gateway--AdminWriteToken`, loaded once #69 is deployed ([Provisioning](Provisioning.md#the-write-token)); until then every control says the console has no write token |
| Changing policy ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)) | **Built** ([below](#changing-policy)), against kf-ai-gateway#39's `PUT`s at `34e05ec`: each allowance row, with the only-goes-up rule applied from the register, the minimum version with the fleet it refuses in view, the velocity limit and the global ceiling. The same write token, confirm step and audit log as #69 |
| Per-person sign-in ([#68](https://github.com/KnowledgeFabric/kf-admin/issues/68)) | **Built**: a secret per person ([Console Shell](Console-Shell.md#authentication-is-a-name-and-a-secret-of-ones-own)). Loading the secrets is [Operations](Operations.md#people) |
| Roles per area ([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)) | **Built**, replacing #68's writers list: every page here asks `gateway:view`, held through *Gateway: View* or *Gateway: Write*, and every write `gateway:write`, held through *Gateway: Write*; `admin` and an Administrator hold both ([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)) |
| Usage history ([#70](https://github.com/KnowledgeFabric/kf-admin/issues/70)) | **Built** ([below](#usage-history)), against [kf-ai-gateway#41](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/41)'s daily usage ledger as deployed at `431701c` on 2026-09-27, which is when its history starts: the fleet's last thirty days on the overview, an installation's on its page, last month beside this period on usage by licence, and a range page with its exports |
| Where each installation calls from ([#217](https://github.com/KnowledgeFabric/kf-admin/issues/217)) | **Built against `StubGateway`**, in the shape [kf-ai-gateway#55](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/55) proposes, which is **not deployed yet**: a country, a network and a cloud region on each installation's page, a *Country* column on the list and on a register row, and *Where the fleet is* on the overview ([below](#where-each-installation-calls-from)). Until #55 deploys, every page says the gateway does not report locations, and the overview hides its card |
| New licences and trials, told ([#235](https://github.com/KnowledgeFabric/kf-admin/issues/235)) | **Built**: a notification to everyone with a Gateway role when the gateway first holds a licence id, and when an installation enrols on `evaluation`, the product's trial. Read through #38's row filter and #35's licence ids, both deployed ([below](#new-licences-and-trials)) |

## The overview

`/Gateway`, the area's landing page, is what the gateway says of itself through `GET /admin/status`
(kf-ai-gateway#37), in three parts:

- **Status**: the version deployed, when it started and how long it has been up, and whether it had
  a telemetry sink when it started. A gateway with no sink serves every request correctly and
  reports nothing to Application Insights, which is otherwise noticed only by an alert.
- **The global brake**: tokens the whole service has spent this calendar month against the ceiling
  that pauses everyone with `503 service_paused` once it is reached (kf-ai-gateway `docs/Admin.md`,
  *Release the global brake*). A bar, the period's end, a warning from 80%, and a banner when the
  gateway says the brake is on. *On* is the gateway's own verdict, from the code its admission
  takes, so the page and the next chat cannot disagree. A brake with no ceiling is shown as off,
  with what has been spent anyway. Releasing it is raising the ceiling, which the banner links to
  ([Changing policy](#the-global-ceiling)).
- **The fleet**: installations in total, active and revoked; how many are served each allowance,
  `evaluation`, `standard` and `enterprise`; how many made an authenticated call in the last day,
  week and month; and how many licensed installations have no licence tier recorded. Those are
  served the `standard` row whatever their licence says, until kf-app sends the licence again, and
  are the rows to look for before `enterprise`'s allowance is raised (kf-ai-gateway#32,
  `docs/Admin.md`, *Raise a licence tier's allowance*).
- **Where the fleet is** (#217): active installations by the country each calls from, most first,
  with *Not located* last, which together add up to the fleet's active count
  ([Where each installation calls from](#where-each-installation-calls-from)). Against a gateway that
  does not report `by_country` the card is not drawn, and a line says the gateway did not report
  where its installations call from, as it says of the brake or the fleet.

The rows are the allowance each installation is *served*, not the wire tier, which calls both
licence rows `licensed`. They are the gateway's own counts; the register's are on the console's
[overview](License-Register.md#the-overview), and the two differ wherever a licence was issued and
never installed on an installation that uses AI.

The foot of the page gives the address the gateway attributed to the console's own request. That
is the check kf-ai-gateway `docs/Admin.md` asks for before the enrolment velocity limit is armed,
made visible: behind App Service the gateway reads the address the front end appends, and this is
what it read.

Beneath the status and the brake, **the fleet's last thirty days** from the gateway's daily usage
ledger: tokens a day, stacked by the row each installation is served now, and refusals a day, both
kinds of `429` and upstream errors ([Usage history](#usage-history)). Against a gateway without the
ledger, that section says so and the rest of the page is as it was.

### What it reads

One request, `GET /admin/status`, with the read-only token as a bearer, and, once it answers,
`GET /admin/usage/daily` for the last thirty days ([Usage history](#usage-history)). The status's shape is
kf-ai-gateway#37's, read into `Gateway/GatewayStatus.cs` in its snake_case wire names:

| Field | Shown as |
|---|---|
| `version`, `started_at`, `now` | Status |
| `telemetry.configured` | Whether Application Insights is connected |
| `brake.ceiling` (null when off), `brake.used`, `brake.period_start`, `brake.period_end`, `brake.tripped` | The global brake |
| `installations.total`, `.active`, `.revoked`, `.by_row.{evaluation,standard,enterprise}`, `.seen_last_24h`, `.seen_last_7d`, `.seen_last_30d`, `.licensed_without_licence_tier` | The fleet |
| `installations.by_country` (active installations per ISO country code), `.unlocated` (active installations with no country) | Where the fleet is (kf-ai-gateway#55), read from the same answer, so no request of its own |
| `caller.address` | The foot of the page |

Every part is optional and unknown fields are ignored, the additive rule kf-ai-gateway#36 sets for
`/admin` read from this side, so a gateway that reports more or less than this still renders. The
three `seen_last_*` names are spelled out with `JsonPropertyName` on the console side, because the
snake_case policy alone would write `seen_last24h`; kf-ai-gateway#37 says so for the gateway's side.

### Once every thirty seconds

The home page's card and the area's overview both want the status, and a sign-in lands on the one
and often goes straight to the other. `Gateway/GatewayStatusCache.cs` holds the gateway's last
answer for thirty seconds and shares it between them, so a visit asks the gateway once; two pages
... (741 lines truncated)
</file>

<file path="docs/Installing-On-A-Phone.md">
# Installing the console on a phone

The console is a progressive web app ([#166](https://github.com/KnowledgeFabric/kf-admin/issues/166),
[Console Shell](Console-Shell.md#installed-as-an-app)): installed, it opens from the home screen
under the KnowledgeFabric mark, in its own window without the browser's bars, and keeps your
sign-in for the session. Nothing about what you may see or do changes: the roles, the pages and
the sign-in are the same as in a browser tab.

## Before you start

- You need the console's address and your own name and secret, as for a browser. The console is
  reachable over HTTPS only, which installing requires.
- Installing does not sign you in. The first time the installed app opens you sign in as usual,
  and the session then holds as it does on a desktop: eight hours, sliding, unless an
  Administrator disables your secret.
- The installed app shows nothing while offline except a page saying the console cannot be
  reached. No contact, licence or gateway page is ever kept on the phone, and nothing you type
  while offline is saved or sent later. Open it again when you have a connection.
- Updates need nothing from you: the installed app is the live console, so a change that merges
  is in it within minutes, the next time a page loads.
- Opening the installed app plays a short animation after the phone's own start-up screen: the
  mark draws itself and slides aside as the name appears next to it, for about two seconds while
  the page loads behind it. A tap ends it. It plays once each time the app opens, not on every page, never in a
  browser tab, and not at all if the phone is set to reduce motion (*Settings → Accessibility*).
- Notifications are turned on separately, on each device, under *User settings → Notifications*:
  [below](#notifications).

## Android

Chrome is the browser to use. Samsung Internet and Edge also install web apps, through their own
menus.

- Open the console's address in Chrome and sign in.
- Chrome may offer **Install app** in a bar at the bottom of the page. If it does, tap it.
- If it does not, open the menu (the three dots, top right) and tap **Add to Home screen** or
  **Install app**, then **Install** in the dialog.
- The KnowledgeFabric mark appears on the home screen and in the app drawer as **KF Admin**.
- Open it from there. It opens on the overview, in its own window with a blue bar, without
  Chrome's address bar. Signing out and back in happens inside it.
- The phone's camera works in it as in Chrome: *Business card* under Partnerships opens the
  camera to read a card, the first time asking for the camera permission.
- To remove it, long-press the icon and choose **Uninstall**, or open **Settings → Apps → KF Admin
  → Uninstall**. Removing it also removes the sign-in and the cached assets on that phone.
- If **Install app** never appears: check the address starts with `https://`, that you are not
  in an Incognito tab, and that Chrome is up to date. Clearing the site's data in Chrome and
  loading the page again lets Chrome see the manifest afresh.

## iPhone and iPad

Safari is the browser to use. On iOS 16.4 and later Chrome, Edge and Firefox can also add a web
app to the home screen, through their own share menus; Safari is the one described here.

- Open the console's address in Safari and sign in.
- Tap the **Share** button (the square with an arrow, at the bottom of the screen on an iPhone and
  at the top on an iPad).
- Scroll the sheet down and tap **Add to Home Screen**. The KnowledgeFabric mark and the name
  **KF Admin** are shown; change the name if you like, then tap **Add**.
- Open it from the home screen. It opens on the overview, full screen, without Safari's bars.
- The installed app has its own sign-in, separate from Safari's: the first time it opens you sign
  in again, and from then on it keeps its own session.
- The camera works in it as in Safari: *Business card* under Partnerships opens the camera to read
  a card, the first time asking for the camera permission.
- To remove it, long-press the icon, choose **Remove App**, then **Delete App**. Removing it also
  removes its sign-in and the cached assets on that device.
- If **Add to Home Screen** is missing from the sheet, you are in a browser other than Safari on
  an iOS before 16.4, or in a Private tab; open the address in Safari. If the icon is a screenshot
  of the page rather than the mark, the page had not finished loading when you tapped Share;
  remove it and add it again.

## On a desktop

Chrome and Edge install the console too: an install icon appears at the right of the address bar,
or **Install Knowledge Fabric Admin** is in the browser's menu. It opens in its own window and is
removed from the browser's app settings or by right-clicking its icon.

## Notifications

The console can tell you when something concerns you, a booking with you for now, with the console
closed ([#209](https://github.com/KnowledgeFabric/kf-admin/issues/209), [Notifications](Notifications.md)).
They are always under the bell in the navbar too; this is about having them arrive on a device.
Turn them on in each browser and on each device where you want them: one device does not turn on
another.

- **Android**: in Chrome, installed or not, open **User settings → Notifications**, tap **Turn on for
  this device**, and **Allow**. They arrive with the app closed. If Android holds them back, check
  *Settings → Apps → KF Admin* (or Chrome) *→ Notifications*.
- **iPhone and iPad** (iOS 16.4 or later): **only from the installed app**. Add the console to the
  home screen as above, open it from there, then **User settings → Notifications → Turn on for this
  device** and **Allow**. In Safari itself the page says this browser cannot receive notifications.
  They then follow *Settings → Notifications → KF Admin* and any Focus mode, as any app's do.
- **On a desktop**: the same page in Chrome, Edge, Firefox or Safari; they arrive while the browser is
  running, with no console tab open.
- **Send a test notification**, on the same page, checks that every device listed receives them.
- **To stop them** on one device, **Turn off for this device** there, or **Remove** it from the list
  on any device. Signing out does not stop them: the device is still yours until you remove it.
</file>

<file path="docs/Issuing-A-License.md">
# Issuing a License

The operational runbook: what to have in place, how to mint a licence, how to check it before it
leaves, and what every error message means.

There are two ways to issue: **the console's issue form**, which needs only the console password,
and **the CLI**, which needs the private key, its passphrase and the .NET SDK on your machine. The
form is [below](#in-the-console); the rest of this page is the CLI.

## In the console

*Licensing → Issue a licence* ([#6](https://github.com/KnowledgeFabric/kf-admin/issues/6)).

1. **Fill in the form.** Licensee name and email, what the licence is for — *Customer* unless you
   choose *Internal* (our own development, staging and test installations) or *Demo* (sales demos and
   partner installations), which keeps it out of the register's figures — optionally a company and
   a tier, the term —
   either a length, as a number of days, weeks, months or years (12 months unless you change it;
   buttons fill in 3 and 6 months and 1, 2 and 3 years), or a last day — an optional *valid from*
   day, what the licence grants, any free-form attributes as `name=value` lines, and your own name.
   What it grants is five collapsible sections — reports, features, connectors, analysis limits and
   AI — each starting with everything on and no limit, each header saying what the section grants
   now. A licence grants only what is left on; see [below](#what-the-licence-grants). Days are UTC: *valid from* starts at 00:00:00 and an expiry day ends at
   23:59:59. Months and years follow the calendar, the same as the CLI's `duration`: the form
   writes 12 months as `P12M`, which ends on the same day as `P1Y`.
2. **Preview.** The form is judged by `LicenseTerms` — the code that judges a CLI config — so it
   refuses exactly what `gen-license` refuses, all at once. The preview shows the licence XML as it
   will be signed, with its licence id already fixed, and a line per section of what it grants,
   marked where it differs from the default. It warns when the expiry has passed or the licence
   grants nothing. The signing key is not touched to preview.
3. **Sign and record.** Signs exactly what was previewed — the preview is sealed, so nothing on the
   page can change it — writes the register row, and only then offers the download,
   `<customer>-<licenceId>.lic`. Pressing it twice issues one licence. A preview can be signed for 30
   minutes; after that, preview again.
   Before recording it, the console reads the new licence back against the public key every
   product image trusts, and refuses it if that key does not verify it.
4. **Check it and deliver it** as in [steps 5 and 6](#5-check-it-before-it-leaves) below.
   *Licensing → Validate a licence* does the reading for you: upload the file and it shows what
   the product and the AI Gateway will each do with it.

**One licence per installation**
([License Contract](License-Contract.md#one-licence-one-installation),
[#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)). A customer running several
installations, one per team say, gets a licence for each. So does each of our own: development,
staging and test are three *Internal* licences, not one. Never send one file for a second
installation. Nothing stops it working there, but the AI Gateway is to report a licence id it sees
on two installations.

**To renew**, open the licence in the register and press *Reissue*: the form comes back filled in
from it, keeping its licence id, so the register counts it as the same licence. The term runs on
from the file you reissued ([#42](https://github.com/KnowledgeFabric/kf-admin/issues/42)): *valid
from* is blank, so the new file is in force as soon as it is issued, and *Expires on* is 12
calendar months after the old file's expiry day. A customer who renews a month early loses nothing:
reissuing on 15 October a licence that expires on 30 November fills in 30 November of the next year.
If the old file has already expired, the form keeps its default of 12 months from issue. Change
either if the customer bought a different term. To correct a licence rather than renew it, set
*Expires on* back to the old file's expiry day.

**Leave *valid from* blank on a renewal.** A future *valid from* means the file must be installed
on or after that day: the AI Gateway refuses it before then and keeps nothing to switch on later
([License Contract](License-Contract.md#validfrom-is-honoured-by-the-gateway-and-by-kf-app-from-its-next-release)), so
the installation drops to `evaluation` when the old file expires unless someone sends the new one
again. A renewal in force from issue has neither problem. What it accepts:

- **The old and new files overlap until the old one expires.** That gives the customer no extra
  time, because the new expiry is fixed, and no extra capacity: both files carry the same licence
  id, which covers one installation.
- **The new terms apply from when the customer installs the file,** not from the renewal date.
  That is right for an upgrade. For a downgrade, ask the customer to install it on the renewal date.

Keep *valid from* for a licence that genuinely must not work before a date. That file has to be
installed on or after its start.

A licence issued before #38 carries only the old area keys, which grant nothing; its form starts
from everything on, with a notice to check each section.

What the form will not do, deliberately: issue a trial (trial files are legacy since kf-app#870,
and the product refuses one), sign with a key other than the one in Key Vault, or grant a report,
connector or feature the catalogue does not have. When signing fails the page says why, and
[Operations](Operations.md#issuing-a-licence-fails) has the causes.

### What the licence grants

([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38); the names and rules are in
[License Entitlements](License-Entitlements.md).)

| Section | On the form | In the licence |
|---|---|---|
| Reports | A switch per report | `reports`: the ones left on |
| Features | A switch per feature — Offboarding Planner, Action Center, Departure Simulator, Export | `features` |
| Connectors | A switch and a count per connector (blank: any number), and a total. Each count says what it counts: sources, but repositories for GitHub ([#168](https://github.com/KnowledgeFabric/kf-admin/issues/168)) | `sources`, e.g. `git,jira:3,github:5`, and `sources.max` |
| Analysis | An employee allowance, and limits on knowledge assets and months of history (blank: none) | `analysis.employees`, `analysis.assets`, `analysis.history` |
| AI | The assistant's switch, a token budget, its period and requests a minute (blank: the licence tier's default) | `ai`, `ai.tokens`, `ai.period`, `ai.rpm` |

- **Anything switched off is not granted — and neither is anything the product adds later.** A new
  report reaches a customer only through a licence that names it, so a renewal is when a customer
  gets what shipped since.
- **Choosing a tier fills in its connector cap** — ten for Standard, the product's "Up to 10
  Knowledge Sources", to be confirmed with product management — unless you have typed one.
- **The AI numbers are the AI Gateway's for this installation**, not the assistant's alone: they
... (269 lines truncated)
</file>

<file path="docs/License-Config-Schema.md">
# License Config Schema

`gen-license` takes a single JSON file describing the licence to mint. This is the reference for
that file, as implemented by `LicenseConfig.cs`, `ConfigLoader.cs` and `LicenseTerms.cs` in this
repository.

> [!IMPORTANT]
> **Normative for the licence contract.** Where this page says what a reader *must* do, it binds
> kf-app and kf-ai-gateway as well as this repository; where it reports what the code does today,
> with a kf-app citation, it is descriptive. The contract itself — `schemaVersion`, the two
> compatibility rules and the signed fixture set — is
> [License Contract](License-Contract.md) ([#5](https://github.com/KnowledgeFabric/kf-admin/issues/5)).

## Fields

| Field | Type | Required | Notes |
|---|---|---|---|
| `name` | string | No (but always set it) | Customer name → `Customer/Name`. Not validated; an empty string is accepted silently. |
| `email` | string | No (but always set it) | Customer email → `Customer/Email`. Not validated — not even for `@`. |
| `company` | string | No | Customer company → `Customer/Company`. Display-only in kf-app today. Omitted from the file when not set. |
| `licenseType` | string enum | **Yes** | `Standard` **only**. Matching is case-insensitive, so `standard` works. `Trial` is refused — see [below](#licensetype). Anything else is a hard error. |
| `tier` | string | No | `standard` or `enterprise` → the `tier` attribute. Exact, lowercase. Omitted from the file when not set. Chooses the AI Gateway's defaults and nothing else — see [below](#tier). |
| `purpose` | string | No | `customer`, `internal` or `demo` → the `purpose` attribute. Exact, lowercase. **Written on every licence: `customer` when left out.** Grants nothing; it tells the register which licences are not a customer's ([License Contract](License-Contract.md#attribute-names-this-contract-defines)). |
| `expiration` | ISO 8601 date-time **with an offset** | One of `expiration` / `duration` | → `Expiration`. A value with no offset is refused — see [below](#dates-and-timezones). |
| `duration` | ISO 8601 duration | One of `expiration` / `duration` | Resolved into `Expiration` at issue time. See [below](#duration). |
| `validFrom` | ISO 8601 date-time **with an offset** | No | → the `validFrom` attribute, in UTC. Must be before the expiration. **The gateway honours it; kf-app does not yet** — see [below](#validfrom). |
| `licenseId` | GUID | No | → `Id`. A fresh GUID when absent. Lets the register ([#8](https://github.com/KnowledgeFabric/kf-admin/issues/8)) pre-allocate the id. The gateway does not read it: storing it was left out of kf-ai-gateway#7. The empty GUID is refused. |
| `reports` | array of names | No | → `reports`. The reports granted, e.g. `["insights", "map"]`. See [the entitlement](#the-entitlement). |
| `features` | array of names | No | → `features`. The features granted, e.g. `["offboarding"]`. |
| `sources` | array of entries | No | → `sources`. The connectors granted: `"git"` for any number, `"jira:3"` for three sources. `github`'s count is of repositories: `"github:5"` allows five ([License Entitlements](License-Entitlements.md#how-a-reader-must-read-them), rule 7). |
| `sources.max` | positive integer | No | → `sources.max`. Knowledge sources in total. |
| `analysis.employees` | positive integer | No | → `analysis.employees`. |
| `analysis.assets` | positive integer | No | → `analysis.assets`. |
| `analysis.history` | positive integer | No | → `analysis.history`, in months. |
| `ai` | array of names | No | → `ai`. Today only `"chat"`, the assistant. |
| `ai.tokens` | positive integer | No | → `ai.tokens`. Blank for the default of the licence's [`tier`](#tier). |
| `ai.period` | `month` or `30d` | No | → `ai.period`. Blank for the default of the licence's [`tier`](#tier). |
| `ai.rpm` | positive integer | No | → `ai.rpm`. Blank for the default of the licence's [`tier`](#tier). |
| `attributes` | object (string → string) | No | Free-form metadata, inert in the product. The names below are refused. |

Every problem in a config is reported in one run, prefixed `The licence config is not valid:`.

### The entitlement

What the licence grants and limits ([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38)).
Each field is named after the licence attribute it becomes, dots and all, so a config reads the way
the licence it mints does. The names, and what each one means to a reader, are in
[License Entitlements](License-Entitlements.md).

- **A list grants what it names and nothing else.** A config with no `reports` grants no reports. A
  config granting nothing at all is minted, with a warning.
- **A name the catalogue does not have is refused**, and so is one listed twice or one that is not
  lowercase letters and digits. `gen-license --allow-unknown-names` writes an unknown name with a
  warning instead, for a product build that is ahead of the tool; a reader that does not know the
  name either ignores it.
- **A limit left out is no limit**, or for the three `ai.` limits the default of the licence's
  `tier`. A limit or a count below 1 is refused: leave it out instead.
- **Lists are written in catalogue order**, whatever order the config gives, and an empty list is
  left out of the licence.

A config written before #38, with `features` as an object of `"true"` values, fails to load with a
message saying so.

`trialDays` is **not** a field. The product's trial is not a file (kf-app#870), and kf-app's copy
of the tool, which had the field, is deleted (kf-app#982). Adding it here does nothing: unknown
fields are silently ignored (below).

### What the tool writes on its own

Every licence `gen-license` issues carries two attributes no config sets
([#4](https://github.com/KnowledgeFabric/kf-admin/issues/4)):

| Attribute | Value |
|---|---|
| `schemaVersion` | `1`. The date and tier levers on this page are additive, so they do **not** bump it; the entitlement changed version 1 in place before anything was deployed — see [License Contract](License-Contract.md#the-version-is-bumped-only-by-a-break). |
| `issuedAt` | The moment of issue, ISO 8601 in UTC to the second, e.g. `2026-09-24T08:18:27Z`. Informational. |

`Quantity` stays `1`, and there is no config field for it. A licence covers one installation
([License Contract](License-Contract.md#one-licence-one-installation),
[#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)), so a customer with several
installations gets one config, and one licence, for each.

### Names `attributes` may not use

| Name | Why |
|---|---|
| `TrialDays` | Reserved by kf-app: its presence marks the file as a trial, and the product **refuses** to install one. |
| `reports`, `features`, `sources`, `ai`, and anything starting `ai.`, `sources.` or `analysis.` | The entitlement, set through the config's own fields. The prefixes are held so a later limit cannot collide with a free-form attribute already issued. |
| `schemaVersion`, `issuedAt` | Written by the tool. |
| `validFrom`, `tier`, `purpose` | Set through the top-level field of the same name, which validates them. |

Names are compared case-sensitively, as readers compare them: `trialdays` is not refused, and is not
read as a trial either.

### `licenseType`

The valid values come from `Standard.Licensing.LicenseType`, which — confirmed by reflection against
the 1.2.1 assembly — defines exactly two members:

```
... (236 lines truncated)
</file>

<file path="docs/License-Contract.md">
# License Contract

What a KnowledgeFabric licence means, stated once, for the three codebases that read or write one:
the issuing side here, the product (`kf-app`), and the AI Gateway (`kf-ai-gateway`).

> [!IMPORTANT]
> **This page is normative.** Where an implementation disagrees with it, the implementation is
> wrong. That is a change from the rest of `docs/`, which describes what the code does today — see
> [Normative and descriptive](#normative-and-descriptive) below.

Established by [#5](https://github.com/KnowledgeFabric/kf-admin/issues/5), under the directions
recorded on [#1](https://github.com/KnowledgeFabric/kf-admin/issues/1#issuecomment-5750795917).

## There is no shared library

#5 originally proposed a `KnowledgeFabric.Licensing` class library, published to GitHub Packages
from CI and referenced by three repositories. **That was dropped.** Measured against kf-app at
`075fa03`, strip the process-wide cache, the semaphore, the repository reads, the DTO mapping, the
trial-precedence rule and the logging out of the 13 KB `LicenseService.cs`, and the
contract-bearing logic is about twenty lines. The gateway's entire `LicenceEvaluation.cs` was then
1,910 bytes. A package, a feed and credential wiring in three repositories is heavier machinery
than the thing it shares.

What holds the contract together instead:

| | |
|---|---|
| **This page**, plus [License Format](License-Format.md), [License Config Schema](License-Config-Schema.md) and [License Entitlements](License-Entitlements.md) | The normative spec. kf-app's `docs/Licensing/*` should point here rather than restate. |
| **`schemaVersion`** and the two compatibility rules | Replaces the compiler. Without a shared binary, this field is the only thing standing between a new lever and an older reader misreading it. |
| **[The fixture set](../contract/README.md)** | 27 signed licences, minted by the real issuing code, committed into each reader, asserted against by each reader's own tests. |
| **Names as data** | Report, feature, connector and attribute names are strings, never enum ordinals. |

**Each reader keeps its own verification.** Three small copies of twenty lines, kept honest by the
fixtures, rather than one package and a feed. This repository's copy is
`src/KnowledgeFabric.LicenseTool/ContractReader.cs` — it exists to verify the fixture set and to
back the "validate a licence" page in [#6](https://github.com/KnowledgeFabric/kf-admin/issues/6).
It is not published, packaged or referenced by another repository, and it is not the dropped
library returning under another name.

## `schemaVersion` and the two compatibility rules

Every licence carries a `schemaVersion` attribute. **A licence without one is version `1`** — that
is not an error, and readers must not refuse it. (Every licence this repository issues has carried
it since [#4](https://github.com/KnowledgeFabric/kf-admin/issues/4); reading it is every reader's
task.)

`schemaVersion` is a **single integer**, an ISO-8601-free plain decimal parsed with
`CultureInfo.InvariantCulture`. There is no minor component.

The two rules are paired, and both are required:

1. **Unknown attributes are carried and ignored.** A reader encountering an attribute it does not
   know does not refuse, warn or drop it. `Standard.Licensing` preserves them, and this is what lets
   a commercial lever ship from the issuing side before the product that enforces it has been
   released.
2. **An unknown major version is refused, legibly.** A reader encountering a `schemaVersion` above
   the highest it knows refuses the licence, with a message naming the version it read and the
   version it supports. It must never guess.

### The version is bumped only by a break

This is the load-bearing consequence, and it decides what #4 emits. Because rule 1 already makes
additive levers safe, **`schemaVersion` is bumped only when a licence genuinely cannot be read
correctly by an older reader** — for example if the meaning of an existing attribute changes, or a
new attribute becomes mandatory to interpret an old one.

Adding `tier`, `validFrom`, `issuedAt` and `Customer/Company` (#4) is *not* such a change: an older
reader that ignores them reaches the same conclusion it reaches today. Those levers therefore ship at
`schemaVersion` **1**. (`duration` never reaches a licence at all — the issuing side resolves it into
an ordinary `Expiration`.)

Letting `tier` choose the AI Gateway's default allowance
([#46](https://github.com/KnowledgeFabric/kf-admin/issues/46)) is not one either. The gateway is its
only reader, and it is one service rather than a fleet of installations, so there is no older copy
of it in the field to protect. The two tiers' allowances also start equal, so until the gateway reads
`tier` it still reaches the conclusion the contract requires: Enterprise's allowance is raised only
after it does.

The entitlement model ([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38)) is the one
exception, and it is not a precedent. It replaced the five area keys rather than adding to them — a
reader of the old keys finds nothing it can open — which is a break by the rule above. It stayed at
`1` only because it landed before anything was deployed, so there was no older reader in the field
to protect. The same change after the first deployment would have to be version `2`.

The alternative — stamping `2` on every licence minted after #4, as that ticket's table once
proposed — would make every installation older than the #4 release refuse every newly issued
licence. Rule 2 is a safety catch for a real incompatibility, not a version counter.

A licence that is unreadable as an integer (`schemaVersion` of `"x"`, or `"1.1"`) is treated as
**unsupported**, not as version 1. Guessing is the single thing rule 2 exists to prevent. Versions
start at `1`, so a value below it is nonsense rather than an old licence and is likewise
unsupported — note that a naive "not newer than I support" test accepts `-1`.

## Names and encodings

Everything crossing the licence boundary is a **string**. A licence is signed and long-lived: an
enum ordinal inside one changes the meaning of every licence already issued the day someone
reorders that enum — retroactively, silently and unverifiably. `Standard.Licensing` stores every
value as a string anyway, so there is nothing to save. This applies in particular to
`KnowledgeSourceTypes`, whose members a licence names through `sources` ([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38)).
... (222 lines truncated)
</file>

<file path="docs/License-Entitlements.md">
# License Entitlements

What a licence grants and limits: which reports, features, connectors and AI capabilities it
switches on, and how far analysis and AI use may go. This page is the catalogue of names, how each
is written in a licence, and how a reader must read them.

> [!IMPORTANT]
> **Normative for the licence contract.** Where this page says what a reader *must* do, it binds
> kf-app and kf-ai-gateway as well as this repository; where it reports what the code does today,
> with a kf-app or kf-ai-gateway citation, it is descriptive. The contract itself — `schemaVersion`,
> the two compatibility rules and the signed fixture set — is
> [License Contract](License-Contract.md) ([#5](https://github.com/KnowledgeFabric/kf-admin/issues/5)).

Established by [#38](https://github.com/KnowledgeFabric/kf-admin/issues/38) on 2026-09-24. It
replaced the five area keys a licence used to carry (`Administration`, `Configuration`, `Reporting`,
`ActionCenter`, `AI`), and took in #9, #10, #11 and #12, which are closed into it.

## The model

- **A licence grants what it names, and nothing else.** Reports, features, connectors and AI
  capabilities are lists. Anything a list does not name is off — including a report, feature or
  connector the product adds after the licence was issued. A new report reaches a customer only
  through a licence that names it.
- **Limits are numbers, and a missing one is no limit.** For the AI Gateway's three limits, a missing
  one means the default for the licence's `tier` instead ([rule 10](#how-a-reader-must-read-them)).
- **`analysis.employees` is an allowance, not a limit**
  ([#44](https://github.com/KnowledgeFabric/kf-admin/issues/44)). The product counts employees
  against it and may tell the customer when there are more, but going over refuses nothing and
  leaves nobody out of an analysis ([rule 9](#how-a-reader-must-read-them)). Commercially it is a
  true-up term, settled at renewal. Nothing reports the count to KnowledgeFabric — kf-app tells
  only the customer's administrator ([below](#kf-app)) — so settling it means asking the customer.
- **Everything is in `LicenseAttributes`.** `ProductFeatures` is written empty. The five area keys it
  used to carry grant nothing: a licence carrying only those grants nothing at all
  (the `legacy-area-keys` fixture).
- **`schemaVersion` stayed 1.** This replaced the old model rather than adding to it, which would
  normally be a break. It changed version 1 in place because nothing had been deployed: there was no
  installation for an older reader to be running on.

## Attributes

| Attribute | Holds | When absent |
|---|---|---|
| `reports` | The [reports](#reports) granted, as a list | No reports |
| `features` | The [features](#features) granted, as a list | No features |
| `sources` | The [connectors](#connectors) granted, as a list, each optionally with a count | No connectors |
| `sources.max` | How many knowledge sources the installation may have in total | No limit |
| `analysis.employees` | How many employees the licence is sized for: an allowance, not a limit | No allowance |
| `analysis.assets` | How many knowledge assets an analysis may cover | No limit |
| `analysis.history` | How many months back an analysis may read | No limit |
| `ai` | The [AI capabilities](#ai-capabilities) granted, as a list | No AI capability |
| `ai.tokens` | Tokens per budget period at the AI Gateway | Its tier's default |
| `ai.period` | The AI budget period: `month` or `30d` | Its tier's default |
| `ai.rpm` | Requests per minute at the AI Gateway | Its tier's default |

A licence issued with every section at its default — everything on, no limits — carries the four
lists and nothing else:

```xml
<ProductFeatures />
<LicenseAttributes>
  <Attribute name="schemaVersion">1</Attribute>
  <Attribute name="issuedAt">2026-07-01T12:00:00Z</Attribute>
  <Attribute name="reports">insights,resilience,watch,holders,assets,map,skills,workforce</Attribute>
  <Attribute name="features">offboarding,actioncenter,departure,export</Attribute>
  <Attribute name="sources">git,azureboards,jira,gcal,outlook,confluence,shortcut,onedrive,teams,publications,github</Attribute>
  <Attribute name="ai">chat</Attribute>
</LicenseAttributes>
```

One with limits reads the same way: `<Attribute name="sources">git,jira:3,gcal,teams:2,github:5</Attribute>`
and `<Attribute name="sources.max">10</Attribute>` allow any number of Git and Google Calendar
sources, three Jira and two Teams, five GitHub repositories, and ten sources in all
([rule 7](#how-a-reader-must-read-them)).

## How they are written

- **Lists are comma-separated, with no spaces.** The issuing side writes them in catalogue order,
  whatever order it was given, so two licences granting the same thing read the same. An empty list
  is left out rather than written empty: both grant nothing, and absent is shorter.
- **Names are lowercase ASCII letters and digits, starting with a letter,** and case-sensitive:
  `Insights` is not `insights`. Each is the shortest readable name for the thing (`teams`, not
  `Microsoft Teams`); the display name is in the catalogue below, not in the licence.
- **A `sources` entry is a name, or a name, a colon and a count:** `git` allows any number, `jira:3`
  allows three. A count is of sources, but for `github`, whose count is of repositories
  ([rule 7](#how-a-reader-must-read-them)).
- **Numbers are positive whole numbers,** written in digits only — no sign, no separators, no
  decimal point — as `CultureInfo.InvariantCulture` writes them.

Why this shape: one attribute per section rather than one per item keeps a licence small. Measured
with the contract test key on 2026-09-24, a licence with every section filled in, every limit set,
a `validFrom`, a tier, a purpose, a company and an order reference is **1,567 bytes**. Written one
attribute per item it is 2,552 bytes, and with names like `sources.GOOGLE_CALENDAR.max` it is
2,804. kf-app's column has no limit since kf-app#980, but it was `nvarchar(3000)` when this was
decided, and the per-item shape would have left little room for a long company name or free-form
attributes. The largest fixture is 1,206 bytes.

## How a reader must read them

1. **A report, feature, connector or AI capability is granted only if its list names it.**
2. **A name the reader does not know is ignored, never refused.** The rest of the list still
... (352 lines truncated)
</file>

<file path="docs/License-Format.md">
# License Format

A KnowledgeFabric licence is a small signed XML document, produced by
[`Standard.Licensing`](https://www.nuget.org/packages/Standard.Licensing) 1.2.1 and conventionally
saved as `license.lic`. This page describes every element and — more usefully — says which of them
the product actually acts on.

> [!IMPORTANT]
> **Normative for the licence contract.** Where this page says what a reader *must* do, it binds
> kf-app and kf-ai-gateway as well as this repository; where it reports what the code does today,
> with a kf-app citation, it is descriptive. The contract itself — `schemaVersion`, the two
> compatibility rules and the signed fixture set — is
> [License Contract](License-Contract.md) ([#5](https://github.com/KnowledgeFabric/kf-admin/issues/5)).

## A complete licence file

This is real output from `gen-license`, not a sketch:

```xml
<License>
  <Id>9865dcd8-3d95-4dcd-9bd4-8e83f0cc01d5</Id>
  <Type>Standard</Type>
  <Quantity>1</Quantity>
  <ProductFeatures />
  <LicenseAttributes>
    <Attribute name="schemaVersion">1</Attribute>
    <Attribute name="issuedAt">2026-09-24T18:23:25Z</Attribute>
    <Attribute name="validFrom">2026-10-01T00:00:00Z</Attribute>
    <Attribute name="tier">standard</Attribute>
    <Attribute name="purpose">customer</Attribute>
    <Attribute name="reports">insights,resilience,watch,holders,assets,map,skills,workforce</Attribute>
    <Attribute name="features">offboarding,actioncenter,departure,export</Attribute>
    <Attribute name="sources">git,azureboards,jira:3,gcal,outlook,confluence,shortcut,onedrive,teams,publications,github</Attribute>
    <Attribute name="sources.max">10</Attribute>
    <Attribute name="ai">chat</Attribute>
    <Attribute name="orderRef">PO-4471</Attribute>
  </LicenseAttributes>
  <Customer>
    <Name>Acme Corp</Name>
    <Email>ops@acme.example</Email>
    <Company>Acme Corporation Ltd</Company>
  </Customer>
  <Expiration>Fri, 01 Oct 2027 00:00:00 GMT</Expiration>
  <Signature>MEYCIQDN1qj9HsWVl/S7vIqj+oinS2c7SeICQ/7+Sh3zC2t0CwIhALzW4UbQFLsMlO5lHwrXaurAyJVpeIOKcwhGjvDpbKsB</Signature>
</License>
```

It was minted from `"validFrom": "2026-10-01T00:00:00Z"` and `"duration": "P1Y"`, with a `tier`, a
`company`, an entitlement granting everything with at most three Jira sources and ten sources in
all, and one free-form attribute. `purpose` is `customer` because the config left it out.
`Customer/Company` and each attribute but `schemaVersion`, `issuedAt` and `purpose` are written only
when the config sets them. `ProductFeatures` is always empty
([License Entitlements](License-Entitlements.md)).

The file is written as UTF-8 **with a byte-order mark**. The product reads it through a
`StreamReader`, which strips the BOM, so this is harmless — but it is why the file does not start
with a literal `<` when inspected byte by byte.

## Element reference

| Element | Comes from | Does the product act on it? |
|---|---|---|
| `Id` | `licenseId` in the config, otherwise a **fresh GUID on every run** | No. Stored and surfaced on the licence screen; never compared against anything. It is what [one licence, one installation](License-Contract.md#one-licence-one-installation) is counted on, and the gateway must record it on each installation ([#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)). It does not yet: storing it was left out of kf-ai-gateway#7 (kf-ai-gateway `c82878f`), and is [kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35). |
| `Type` | `licenseType` in the config | **Display only.** It is stored and shown, but it gates nothing — the entitlement decides what the licence grants. A `Standard` licence granting nothing unlocks nothing. kf-app's licence page shows it rather than `tier`, so a licence issued with `tier` `enterprise` still reads "Standard" there. |
| `Quantity` | Hard-coded `WithMaximumUtilization(1)` | **No, and no reader may.** Always 1. It is *not* a seat count or a count of installations, and must not be sold as either. A licence covers one installation, and that rule is on `Id` ([License Contract](License-Contract.md#one-licence-one-installation), [#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)): a customer with several installations gets a licence for each, not a larger `Quantity`. |
| `ProductFeatures/Feature[@name]` | Nothing: always empty | **No.** It carried the five area keys until #38 removed them, and kf-app reads it for nothing since kf-app#985 (`c332de4`). A licence from before #38, carrying only those keys, grants nothing — see [License Entitlements](License-Entitlements.md#what-the-readers-do-today). |
| `LicenseAttributes/Attribute[@name]` | `schemaVersion` and `issuedAt` from the tool; `validFrom`, `tier` and `purpose` from the config fields of those names; the entitlement from the config fields of the same names; the rest from `attributes` | **Per the contract, this is the entitlement:** `reports`, `features`, `sources`, `ai` and their limits ([License Entitlements](License-Entitlements.md)). kf-app at `c332de4` reads the entitlement, `schemaVersion`, `purpose` and `TrialDays`, whose effect is a **rejection** — this tool refuses to write it; kf-app 1.6.2 does not honour `validFrom`, and kf-app#979, on `develop` and not yet released, does. kf-ai-gateway at `c82878f` reads `schemaVersion`, `TrialDays`, `validFrom`, the three AI limits (kf-ai-gateway#28) and `tier`, which chooses the allowance for the limits a licence leaves out (kf-ai-gateway#32). Free-form attributes are inert metadata. |
| `Customer/Name`, `Customer/Email` | `name`, `email` in the config | Display only — stored on the licence record and shown in Administration. |
| `Customer/Company` | `company` in the config; absent when not set | Display only. |
| `Expiration` | `expiration` in the config, or `duration` resolved at issue time; rendered RFC 1123 in UTC | **Yes.** Checked when the file is uploaded, and again on every gated request. |
| `Signature` | ECDSA over the document, using the private key | **Yes.** Verified on upload and every time the stored licence is loaded. |

### About `Signature`

The signature is **ECDSA (secp256r1/P-256)**, not RSA — an older wiki page in kf-app calls it RSA,
which is wrong. A public key is 124 base64 characters and begins
`MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE`, the SubjectPublicKeyInfo prefix for an EC P-256 key.

The signature covers the whole document. Editing *any* element by hand — including something
apparently cosmetic like `Customer/Name` — invalidates it, and the product will refuse the file.
Reissue rather than edit.

## How the product validates a licence

From `KnowledgeFabric.Logic/Services/Licensing/LicenseService.cs` in kf-app at `5e9fb51`, on
`develop`, with kf-app#979, which is not in a release yet. kf-app 1.6.2 (`c332de4`) differs where
noted. There are two distinct paths, and they do **not** check the same things.

**On upload** (`UploadLicenseAsync`) — the strict path, refusing in the
[contract's](License-Contract.md#the-verification-algorithm) order and words (kf-app#985):

1. Parse the XML (`License.Load`). It will not parse ⇒ `unverifiable`.
2. Take the trusted public keys (see below). None ⇒ `unverifiable`.
3. Find a trusted key that verifies the signature (`LicenceSignature.FindVerifyingKey`). None ⇒
   `unverifiable`.
4. Read `schemaVersion`, absent meaning 1. Unreadable, below 1 or above 1 ⇒ `unsupported-schema`,
   with a message naming the version it read and the one it supports.
5. **Refuse any licence carrying a `TrialDays` attribute** ⇒ `trial-licence`. A trial signs no
   expiry date, so storing one as an installed licence would install a licence that never lapses.
6. The dates, by one rule (`LicenceTerm.StandingAt`) with the contract's precedence: the expiry,
... (90 lines truncated)
</file>

<file path="docs/License-Register.md">
# License Register

The register of issued licences ([#8](https://github.com/KnowledgeFabric/kf-admin/issues/8)): which
licences have been issued, to whom, by whom and when, with the signed file itself so it can be sent
again. It lives in the console at **Licensing → Licence register** (`/Licensing/Register`).

Without it, the only trace of an issued licence is one audit line in Application Insights, kept for
30 days, recording *that* something was issued but not *what*
([Provisioning, Part C](Provisioning.md#part-c--the-registers-database)). "What did we give customer
X?" and "send them the file again" had no answer.

## Where it stands

| | State |
|---|---|
| The register itself: store, schema, pages, CSV export | **Built** |
| The CLI's offline record (`gen-license --register-csv`) | **Built** |
| The database it runs on | **Provisioned** 2026-09-24 — `kf_admin` on the gateway's server. [Part C](Provisioning.md#part-c--the-registers-database) |
| A row written on every licence the console issues | **Built** with the issue form ([#6](https://github.com/KnowledgeFabric/kf-admin/issues/6)) |
| "Reissue" | **Built**: a row's *Reissue* opens the issue form pre-filled from it, keeping the licence id. The term runs on from the row's expiry, with no *valid from* ([#42](https://github.com/KnowledgeFabric/kf-admin/issues/42); [Issuing a License](Issuing-A-License.md#in-the-console)) |
| Statistics on the console's overview | **Built** ([#37](https://github.com/KnowledgeFabric/kf-admin/issues/37)): see [The overview](#the-overview) |
| Filtering the list by purpose, tier and whether expired | **Built** ([#85](https://github.com/KnowledgeFabric/kf-admin/issues/85)): see [The pages](#the-pages) |
| Going from a row to the installations running it | **Built** ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)): a row lists the installations holding its licence id, and the overview lists every licence on more than one ([Installations](#installations)). A licence covers one installation ([#47](https://github.com/KnowledgeFabric/kf-admin/issues/47), [License Contract](License-Contract.md#one-licence-one-installation)), and the register is where a licence on a second one shows. The gateway records the licence id since [kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35) (`cb44c56`, deployed 2026-09-26), and `Gateway--AdminToken` was loaded the same day with the gateway's read-only token ([Provisioning B3](Provisioning.md#b3-load-the-secrets)), so the pages show installations. One licensed before that deploy has no id until kf-app sends its licence again ([Operations](Operations.md#a-licences-installations-or-the-gateways-status-are-missing)) |
| What each licence's installation has used | **Built** ([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)): a row's installations show tokens used this period against the limit, and requests a minute, and **AI Gateway → Usage by licence** puts every licence in force beside them, as a page and as CSV ([Gateway Management](Gateway-Management.md#usage-by-licence)) |

## Storage: a database on the gateway's PostgreSQL server

Decided on 2026-09-24. The register is the `kf_admin` database, with its own login, on the
PostgreSQL Flexible Server the gateway already runs.

**Why this and not the other two options on #8:**

- **It adds no database engine to anything we host, whatever kf-app#971 decides.** #8 tied the
  choice to kf-app#971 (should kf-app move from SQL Server to PostgreSQL?). That ticket is about
  the database inside a customer's installation, which runs on the customer's machines, not ours.
  The only relational server KnowledgeFabric runs itself is the gateway's PostgreSQL server, so
  putting the register there costs no new engine either way. The sequencing comment on #1
  suggested Table Storage to avoid waiting on kf-app#971. That turned out to be unnecessary,
  because kf-app#971 never affected the choice.
- **Point-in-time restore, for 35 days**, already set on the server. This is a compliance record,
  and Table Storage has no point-in-time restore.
- **No new bill and no new operational knowledge.** Provisioning is the gateway's A2 section again,
  and backups, the driver and the migration pattern all come from the gateway.

**What it costs**, from the gateway's
[What sharing costs](https://github.com/KnowledgeFabric/kf-ai-gateway/blob/main/docs/Provisioning-Environments.md):
the register shares the server's CPU credits (a negligible load, a few hundred rows a year), and a
point-in-time restore acts on the whole server. To recover the register, restore the server to a
new server, move `kf_admin` alone, and repoint only the console's connection string. Also, a
database on a shared server is only safe if its login can reach nothing else, so the isolation
check in Part C is mandatory.

**Azure SQL** was not chosen because it would add a second engine for one small table. **Table
Storage** was not chosen because it has no point-in-time restore and cannot search the way the
list page does.

### Its own store, not `IFeatureStateStore`

The shell's storage seam is a keyed document per collection with no queries, and it says a feature
that wants more should say so out loud ([Console Shell](Console-Shell.md)). The register wants
search, ordering and a uniqueness rule, so it has its own interface, `ILicenceRegister`
(`src/KnowledgeFabric.AdminConsole/Licensing/Register/`).

## What a row holds

Every licence-derived field is **read back out of the signed XML**, not taken from the form that
produced it. A row therefore cannot disagree with the file it describes. The code is
`RegisterRecord.FromLicense`, in `src/KnowledgeFabric.LicenseTool/RegisterRecord.cs`. That one
source file is compiled into both the CLI and the console: the console links it rather than
referencing the CLI project, and it is not a package.

| Field | From |
|---|---|
| Licence id | `Id`. The join key with the gateway, once it stores it (above). **Not unique**: a renewal may reuse it, and each issue is its own row |
| Customer name, email, company | `Customer/Name`, `Customer/Email`, `Customer/Company` (set by the config's optional `company`, #4) |
| Type, tier, schema version | `Type`, and the `tier` and `schemaVersion` attributes. Schema version is 1 when absent, per the [contract](License-Contract.md) |
| Purpose | The `purpose` attribute: `customer`, `internal` or `demo`, and `customer` for a licence issued before it existed. Internal and demo rows carry a badge in the list, which filters on it (#85). The overview does not filter on it yet; when it does, every row issued before #38 was issued before anything was deployed, so all of them were internal |
| Valid from, expiration | The `validFrom` attribute and `Expiration`, in UTC |
| What it grants | The entitlement attributes — `reports`, `features`, `sources`, `ai` and their limits ([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38), [License Entitlements](License-Entitlements.md)) — read by `Entitlements.Read`, the rules every reader follows. Every attribute is kept as JSON, so a new limit needs no migration |
| Area keys | Every `ProductFeatures` entry, as written. Empty since #38; a row from before it holds the five area keys, which grant nothing now and are shown as such |
| Issued by | A name entered when issuing (#6), or the operating-system user for the CLI |
| Issued by login | Who was signed in: the name a person signed in with (#68), or `shared-credential` for a session under the shared password before it was retired (#89), which is why *issued by* also exists |
| Issued at | The `issuedAt` attribute when the licence carries one, otherwise when it was recorded |
| SHA-256 | Of the file's bytes: UTF-8 **with** a byte-order mark, exactly as `gen-license` writes it. A downloaded file and the file first handed over hash the same |
| Licence XML | The whole signed document |

The SHA-256 is unique. Recording the same file twice returns the row already held and adds nothing.

## Where rows come from

**The console's issue form (#6), before it hands the file over.** `ILicenceRegister.RecordAsync`
throws when there is no database. Issuing fails on that rather than hand the file over anyway: a
licence that reached a customer but not the register is exactly the gap this register closes. The
form never serves the file itself — signing records the row and redirects to it, and the download is
the register's (so it is audited as `licence:redownload`, after the `licence:issue` entry that
records the signing).

**The CLI, when you ask it to.** Issuing offline, add `--register-csv <file>` (and optionally
`--issued-by "<name>"`) to `gen-license`. It appends one row to that CSV file, writing the header
when the file is new. The columns are the same as the console's export. If the licence was written
... (172 lines truncated)
</file>

<file path="docs/Localisation.md">
# Localisation

How the admin console speaks more than one language, built for
[#102](https://github.com/KnowledgeFabric/kf-admin/issues/102): English, the default, and Italian,
chosen by a cookie switcher in the navbar as kf-app's is. The code is `src/KnowledgeFabric.AdminConsole/`,
in `Localisation/`, `Resources/` and `Controllers/CultureController.cs`; the tests are
`LocalisationTests`, `CultureSwitchTests` and `InvariantUnderItalianTests`.

**The rule that matters most: culture changes what people see, nothing else.** Anything sent, signed,
stored, exported, imported or logged stays invariant and English. The second half of this page is how
that is kept true.

## What a person sees

A request has a culture from its cookie, `.AspNetCore.Culture`, and English without one
(`Localisation/LocalisationRegistration.cs`, `UseConsoleLocalisation`). Only the cookie is read: not
`Accept-Language`, because English is the default by decision and a test run must read the same
whatever machine it runs on, and not a `culture=` query string, because the pages that forward their
query strings to the gateway must never carry a parameter nobody asked for (CLAUDE.md: a `400` from
the gateway is the console's bug). The culture reaches `<html lang>`, every string, every number
written for reading (`N0`: `418,220` or `418.220`) and every month and day name on a chart or a card.
Fixed ISO timestamps, `2026-09-26 15:30 UTC`, stay as they are, and so does the CRM's sheet date,
`23.09.26`, which is the sheet's own form.

The switcher is a `POST` to `/culture` (`CultureController`), one small form per language in the
navbar's `dropdown-language` and beneath the login card, under the global anti-forgery filter like
every form. It refuses a culture outside `ConsoleCultures.Supported` with `400`, writes the cookie for
a year, `HttpOnly` and `Secure`, and comes back to the page the person was on **with its query
string**: the filtered and paged pages live in theirs, and kf-app's switcher, which drops it, is the
one thing not copied.

### One shared resource

`Resources/ConsoleResource.resx` is English and `Resources/ConsoleResource.it.resx` is Italian; both
are named after the empty marker class `Resources/ConsoleResource.cs`, which is how the resource
manager finds them, so the class, its namespace and the files' base name move together or not at all.
Keys are dotted, by area and page: `Menu.Licensing.Register`, `Licensing.Issue.Form.IssuedBy`,
`Licensing.Validate.Verdict.Refused`, `Generic.Apply`. Placeholders are `{0}`, `{1}`. A plural is two
keys, `.One` and `.Many`, and the code picks one, as kf-app does. A value may hold simple inline
markup, `<code>`, `<strong>`, `<em>`, and a link or a name is passed as an argument, which is
encoded. A `<` that is not markup is written `&lt;`. A link's text is a key of its own, and when
the sentence puts a preposition before it, the Italian may need the preposition inside the link
(*nel registro di audit*), so a link text named in two sentences gets a key for each
(`Gateway.Policy.InstallationsList` beside `Gateway.Usage.TheInstallationsList`).

Both files hold exactly the same keys, each key the same placeholders, and no empty value:
`LocalisationTests` says so, and also that every literal key a view or a C# file asks for exists, so
a key mistyped in a view fails the build's tests rather than reading as its own name on a page.

### Where strings are read

| Where | How |
|---|---|
| A view | `@T["Key"]` for text, `@T["Key", arg]` with arguments, `@T["Key"].Value` in an attribute, and `@S["Key", arg].Value` in an attribute with arguments: `T`'s `.Value` is the string before its arguments are filled in, `Grant {0} to {1}`, because the HTML localizer fills them in only when it is written as HTML (`LocalisationTests` refuses `T["Key", arg].Value`). `S` for a string a helper needs, too. Both are injected by every `_ViewImports.cshtml`, root and areas. `T` is an `IHtmlLocalizer<ConsoleResource>`, so markup in a value renders and an argument is encoded. |
| A controller or a service | `IStringLocalizer<ConsoleResource>`, injected. Page titles are set here. |
| A model's attributes | `[Display(Name = "Key")]`, `[Required(ErrorMessage = "Key")]`: `AddDataAnnotationsLocalization` reads every one from the shared resource, and the framework's own binding messages are set from `Binding.*`. Give every attribute a message, or the framework's English shows. |
| A role's name | `T.Role(role)`, `S.Role(role)` (`Localisation/RoleNames.cs`): the stored role name never changes, its words do. |
| The licence catalogue | `S.ReportName(entry)`, `S.LimitUnit(limit)`, `S.PurposeName(code)`, `S.TierName(code)` (`Localisation/CatalogueNames.cs`): `LicenseContract` is the CLI's shared file and carries the contract's English, so the console maps each code to `Catalogue.*` and falls back to the contract's words. The report and feature names are kf-app's own menu labels, so their Italian is kf-app's (`Licence.Grant.*`). |
| An enum's label | A key per value, `Licensing.Issue.Unit.Months`; the stored value is the enum's name and never a label. |
| A country's name | `S.CountryName(code)` (`Localisation/CountryNames.cs`, #217): `Country.IT`, *Italy* or *Italia*, written from CLDR 48 for the 249 ISO 3166-1 codes and `XK`; a code the resource does not know reads as itself. Never `RegionInfo`, whose `DisplayName` does not follow the UI culture (on .NET 8 with ICU it is each country's own name, *Deutschland*, whatever the reader's language). The code is what is compared and logged. |
| JavaScript | `kfI18n.t('Key', ...args)` and `kfI18n.culture` (`wwwroot/js/site.js`), read once from the JSON block the layout embeds: the request's culture and every key under `Js.`, serialised so that it can never close its own `<script>` (`Localisation/ClientStrings.cs`). The one way a translation reaches a script; a script carries no English of its own and formats a number with `kfI18n.number`, never with a locale it chose. `Js.Summary.*` are also what `EntitlementSummary` reads on the server, so the form's headers say the same thing before and after a change. |

What the CLI's shared files say stays as they say it. `LicenseTerms` is the signer's own code, used by
the CLI too, and its warnings and problems are English sentences; the preview shows them under a
translated label, *The signer reports:*, after the form's own checks, which are the console's and
translated, have had their say.

### How to add a string

1. Add the key to **both** `.resx` files, English and Italian, with the same placeholders. The
   parity test fails until you do.
2. Read it: `@T["Key"]` in a view, the injected localizer in C#, `kfI18n.t` in a script (a `Js.`
   key), an attribute's `Name` or `ErrorMessage` on a model.
3. If it is a domain term, use the [glossary](#glossary)'s word. If the term is new, add it to the
   glossary first, so the next page says it the same way.
4. Nothing that is sent, stored, audited or exported goes through a key: a value people read is the
   only thing that does.

### How to add a language

1. Add the culture to `ConsoleCultures.Supported` and `NativeName` (`Localisation/ConsoleCultures.cs`).
   The middleware, the switcher and the parity test read that list.
2. Add `Resources/ConsoleResource.<culture>.resx` with every key the English file has. The parity
   test compares English to Italian today; extend `LocalisationTests` to the new culture so it is
   held to the same rule.
3. Check the dates and numbers the culture writes: `N0` and month names follow it automatically;
   anything else is read, not written.
4. Nothing else changes: no view, no controller, no script.

## What leaves the page stays invariant

The culture a request has would, left alone, reach `ToString()`, string interpolation, `Parse` and
MVC's form binding. These are the places it is kept out, with a test for each in
`InvariantUnderItalianTests`:

- **Forms bind with the invariant culture, globally.** `InvariantFormValueProviderFactory` replaces
  MVC's `FormValueProviderFactory` and `JQueryFormValueProviderFactory`. A browser submits
  `type="number"`, `type="date"` and `type="datetime-local"` in one form whatever its language,
  `1.5`, `2026-10-10`, `2026-10-10T12:00`, so the invariant culture is the correct one for every form
  here, and a decimal field added later cannot read `1.5` as fifteen. Query strings and route values
... (204 lines truncated)
</file>

<file path="docs/Notifications.md">
# Notifications

Each person's notifications ([#209](https://github.com/KnowledgeFabric/kf-admin/issues/209)): an
inbox in the console under a bell, and the same notifications pushed to the browsers and phones each
person turns them on in, so they arrive with the console closed. The Bookings area was the first to
use them: a host hears of a booking, a booking whose invitation did not go, and a cancel. The CRM
reminds each owner of their follow-ups every morning (#210), the gateway's watch tells the people
who can raise its ceiling when its brake passes 80% or trips, or its status cannot be read (#211), and the
competitors' daily scan tells the people with a Competitors role which competitors have news (#225).

| What | Where |
|---|---|
| The bell, with the unread count | The navbar, on every page, for everyone signed in but `admin` |
| The inbox | `/Notifications` (`NotificationsController`) |
| Turning a device on, the devices, a test | *User settings → Notifications*, `/Preferences/Notifications` (`NotificationSettingsController`, `wwwroot/js/notification-settings.js`) |
| What a device shows, and a click | `wwwroot/sw.js`, the service worker #166 installed |
| The store | `console_notifications` and `console_push_devices` in `kf_admin` (`Notifications/PostgresNotificationStore.cs`), memory without a database |
| Sending | `Notifications/NotificationPusher.cs` and `WebPushSender.cs`, in the background |
| The booking kinds | `Booking/BookingNotifications.cs` |
| The morning's follow-up reminders | `Crm/FollowUpReminders.cs` |
| The gateway watch | `Gateway/GatewayWatch.cs` |
| The competitors' news | `Competitors/CompetitorNotifications.cs` |

## Where it works

| Platform | Works? | Conditions |
|---|---|---|
| Desktop Chrome, Edge, Firefox | Yes | In the background while the browser runs; no console tab needed |
| macOS Safari 16+ | Yes | Same |
| Android: Chrome, Samsung Internet, Edge | Yes | Installed or not; arrives with the app closed |
| iPhone and iPad, iOS/iPadOS 16.4+ | Yes, installed only | The console added to the home screen ([Installing on a Phone](Installing-On-A-Phone.md)), opened from there, and turned on in it: in Safari itself the page says the browser cannot receive them |

It is the W3C Push API: the console encrypts each message to the browser's own keys (RFC 8291,
`aes128gcm`), signs it with its VAPID key (RFC 8292) and posts it to the browser's push service
(RFC 8030): Google's for Chrome and Edge on Android, Mozilla's, Apple's, Microsoft's. The push
service cannot read it. There is no vendor account and no per-message cost. The library is
[Lib.Net.Http.WebPush](https://github.com/tpeczek/Lib.Net.Http.WebPush) 3.3.1, MIT, with its one
dependency, Lib.Net.Http.EncryptedContentEncoding, MIT.

## The inbox

- **Two layers, the inbox first.** Every notification is a row for its recipient whatever happens to
  the push: no device, push not configured, a push service down, a browser that refused. The bell
  counts the unread on every page load, never cached; `/Notifications` lists the newest 50, newest
  first, and *Mark all as read* reads them all.
- **A row holds what happened, never what it says**: a kind (`booking:new`), a subject's id (the
  booking's), when, read, and how its push went. **What it says is drawn from the subject every time
  it is shown or pushed**, in the reader's language, by the area that owns the kind
  (`INotificationContent`). So a guest's name is never copied into the notification, and a booking an
  operator erases leaves a row that says *No longer available*.
- **It says nothing to someone who may no longer see it.** A booking's notification is said only to a
  host the booking still holds whose name still holds a Booking role, and a scan's news only to a name that
  still holds a Competitors role or `Administrator`; to anyone else it is *No longer available*, and it is
  not pushed.
- **Opening one** (`GET /Notifications/{id}`, what a push's click opens) marks it read and leads to its
  page: the booking's, which applies its own policy. Someone else's id is a `404`. Reading is not
  audited.
- **Kept 90 days**, read or not, then deleted by the pusher (`NotificationPusher.Retention`).
- **`admin` is never notified** ([#108](https://github.com/KnowledgeFabric/kf-admin/issues/108)): it is
  no one, never a host, so it has no bell, and both pages say so. `Notifier` drops it whatever an area
  asks.

## Devices

*User settings → Notifications* is anyone's but `admin`'s, and only their own.

- **This browser** is the card's first line, and the page's script asks the browser rather than the
  server whether it is on: *Turn on for this device* asks for permission from the click (Safari asks
  only then), subscribes with the console's public key, and sends the subscription; the server keeps it
  and answers its id, which the script keeps in the browser's storage to mark *this browser* in the
  list. *Turn off for this device* unsubscribes and removes it. A browser that refused is told to allow
  notifications in its site settings; one without push, and an iPhone's Safari, are told to add the
  console to the home screen first.
- **A device is a row of `console_push_devices`**: the person's name, the subscription's endpoint and
  two keys, a label from the user agent (*Chrome, Android*; product names, the same in both languages),
  the language the person used the console in when they turned it on, when, and when a push service
  last took a message for it. **One browser is one row** (`ux_console_push_devices_endpoint`): turned on
  again, or by someone else signed in there, it is the same row, now theirs. **Ten per person**
  (`PushDevice.MaxPerPerson`); the eleventh is `409`, *remove one first*.
- **The endpoint is a secret**, as a calendar feed's address is ([Bookings](Bookings.md#calendar-feeds)):
  never shown back, to the person or an Administrator; a device is listed by its label, the push
  service's host, and its dates. It is stored as it is, because sending needs it and the unique index
  decides one browser is one row; a subscription made with the console's public key accepts only a
  message signed with the console's private key, so the endpoint alone sends nothing.
- **An endpoint is checked before it is kept**: `https`, a public host on the default port
  (`PublicAddress.IsFollowable`), at most 2048, and the two keys base64url of exactly 65 and 16 bytes;
  anything else is `400`. The pusher connects through `PublicAddress.ConnectAsync`, as the card's QR
  link and a calendar feed do, so a signed-in browser cannot make the console post to its own network.
- **Signing out does not remove a device.** It is the person's until they remove it here, or until its
  push service answers `404` or `410` (the browser unsubscribed, the push service forgot it), when the
  pusher deletes it and the person turns it on again there.
- **Send a test notification** writes a `console:test` notification to oneself, pushed to every device
  listed: the first manual check.
- **Without a database** the page says devices and notifications are kept in memory and lost on restart.

## Sending

The **pusher** (`NotificationPusher`, run by `NotificationPusherLoop`, a hosted service) sends what is
still to be pushed. `Notifier` wakes it after writing; it also looks every 30 seconds. **The outbox is
the inbox**: a row is pending while `pushed_at` is null, so a restart or a deploy loses nothing.
... (191 lines truncated)
</file>

<file path="docs/Operations.md">
# Operating the admin console

What to do once the environment in [Provisioning](Provisioning.md) exists: deploying, rotating each
of the three secrets, and where to look when something fails. Written for whoever is on the end of
the phone, not for whoever built it.

The one thing to know before anything else: **rotating the passphrase is cheap and rotating the key
pair is not.** They sound like the same operation and they are three orders of magnitude apart. The
difference is [below](#rotating-the-key-pair).

---

## Deploying

A merge to `main` deploys. There is nothing to press, and there is no second environment it reaches
first — `production` is the only one there is, which is the decision recorded in
[Provisioning](Provisioning.md#what-the-environment-is). The console can issue now (#6), so a required
reviewer on that Environment is due — it makes each deploy a decision somebody makes; until one is
added, a merge is a deploy that reaches the signing key.

`.github/workflows/deploy.yml` calls `_deploy-environment.yml` for the `production` environment, which
builds the solution, mints and verifies the contract fixture set, publishes the console, signs in to
Azure with OIDC, deploys the package, and then polls `/health` until it answers 200 or five minutes
pass. A failed build never reaches the deploy step; a deploy whose `/health` never answers fails red
rather than passing quietly.

**To redeploy the same commit** — after changing an application setting, or to shake out a bad
restart — *Actions → Deploy → Run workflow* on `main`. It republishes the same code.

**What a deploy does not do.** It never writes an application setting and it has no access to Key
Vault. Changing a secret or a setting is a Portal operation, and takes effect on the App Service's
next restart, which *Apply* triggers for you.

**What survives a deploy.** Signed-in sessions do: the data-protection keys that encrypt the cookie
live under the App Service's `%HOME%` and persist across restarts. What does not survive is
in-process state — the sign-in lockout counters in `LoginThrottle`, and the feature state in
`InMemoryFeatureStateStore` when there is no database (with one, each person's dashboard order is a
row of `feature_state` in `kf_admin` since [#135](https://github.com/KnowledgeFabric/kf-admin/issues/135),
and survives). A deploy therefore clears an attacker's lockout as well as an
unlucky colleague's. It is bounded and rare, errs toward availability, and is the sort of thing that
belongs in a runbook rather than in somebody's memory.

**The register's database is the one thing with data in it**, once
[Part C](Provisioning.md#part-c--the-registers-database) is done. A deploy does not touch its
contents; it can change its schema, because pending migrations are applied at startup, before the
new version serves anything. Its backups are the gateway server's: 35 days of point-in-time restore,
which acts on the whole server — see
[License Register](License-Register.md#storage-a-database-on-the-gateways-postgresql-server) for how
to recover this database alone without rolling the gateway back with it.

---

## People

Since [#68](https://github.com/KnowledgeFabric/kf-admin/issues/68) each person signs in under
their own name with a secret of their own
([Console Shell](Console-Shell.md#authentication-is-a-name-and-a-secret-of-ones-own)),
and since [#88](https://github.com/KnowledgeFabric/kf-admin/issues/88) what they may do is the roles
their name holds, granted on the console's Users page
([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).
So adding a person takes two people's rights: someone with Key Vault rights loads the secret, then
`admin` or an Administrator grants the roles. A secret is read at startup, so nothing about one takes
effect until *App Service → Overview → Restart*; a role takes effect at that person's next request,
with no restart. The name in a secret's name is letters, digits and single hyphens, and matches
whatever its case.

**Adding a person.** *Key Vault → Secrets → + Generate/Import*, name `Authentication--Users--<name>`,
value a generated password (`openssl rand -base64 24` is fine). Restart. Give them the name and the
password separately. Until they are granted a role they sign in to an overview that says they have
none, and see nothing else.

**Granting roles.** Sign in as `admin`, or as anyone holding *Administrator*, and open **Users** in
the menu. The person's name is listed once their secret is loaded and the console restarted, marked
*no roles*. Press *Grant* under each role they need: *View* or *Write* for each area they work in
(*Write* includes *View*), and *Administrator* only for someone who is to manage roles too. Each
grant counts from their next request and is in the audit log as `console:role-grant`. *Revoke*
undoes one the same way, as `console:role-revoke`. A name whose secret has been disabled stays on
the page marked *no secret* while it holds a role: revoke them all to take it off.

**Setting initials.** On the same page, type the person's initials in the *Initials* column beside
their name and press *Save*: one to four letters, `VS` for `vera`. The CRM's grid then shows them in
place of the name, which it keeps on hover (#115); every record, filter, export and audit entry still
names them. Blank shows the name again. Each change is in the audit log as `console:initials`. Two
people with the same initials are warned about, not refused: give one of them another.

**Granting the Booking roles** ([#171](https://github.com/KnowledgeFabric/kf-admin/issues/171),
[Bookings](Bookings.md#who-may-do-what)). *Booking: View* lets a person see the Bookings area;
*Booking: Write* lets them change their own availability (#173), and will let them cancel what is
booked with them when that page lands. Grant *Booking: Write* to anyone who is to be booked, and *Booking: View* to
anyone who only needs to see who is booked with whom. Who is bookable, and the Zoho connection, are
an Administrator's: a writer never touches a colleague's settings. Holding a role does not make a
person bookable; the next paragraph does.

**Granting the Competitors roles** ([#220](https://github.com/KnowledgeFabric/kf-admin/issues/220),
[Competitors](Competitors.md#who-may-do-what)). *Competitors: View* lets a person read the list,
each competitor's page and the news feeds (#224), and will let them be told of each morning's news
(#225); *Competitors: Write* lets them add a competitor, edit its profile and mark a news item
irrelevant too, and read their own entries in the audit log. Grant *Write* to whoever keeps the profiles, *View* to everyone else who should know
how we stand against them. Deleting and restoring a competitor, and the area's settings, are an
Administrator's.
... (1043 lines truncated)
</file>

<file path="docs/Provisioning.md">
# Provisioning the admin console's environment

How the admin console's Azure environment is built, in the order it has to be built, and what each
setting is for. Written to be followed rather than read: if a step here is wrong, fix the step.

Companion documents: [Operations](Operations.md) is what to do once it exists — rotating the
passphrase, redeploying, and where to look when issuing fails. [Console Shell](Console-Shell.md) is
the application being hosted. The decisions behind the shape are on
[#7](https://github.com/KnowledgeFabric/kf-admin/issues/7) and in the epic,
[#1](https://github.com/KnowledgeFabric/kf-admin/issues/1).

This follows kf-ai-gateway's [`docs/Provisioning-Environments.md`](https://github.com/KnowledgeFabric/kf-ai-gateway/blob/main/docs/Provisioning-Environments.md)
step for step wherever it can, because a second style of running an App Service costs more than it
buys. Where it deviates — the signing key goes in Key Vault, not in application settings — the
reason is set out under [Part B](#part-b--key-vault-and-the-signing-key) and it is the whole reason
this document is not just a link to that one.

> **Portal, not CLI.** Every step is written as Azure Portal navigation. Blade names drift between
> Portal releases; the setting and the reason for it do not. When the label has moved, match on
> what the step is trying to achieve.

---

## What the environment is

**One environment, and there is not going to be a second one.** One App Service in West Europe,
deployed from `main`, issuing real customer licences. Decided on 2026-09-23, and it is a different
statement from the gateway's "production is deferred": nothing is being put off here, so nothing is
waiting to be renamed.

| | |
|---|---|
| Hostname | `admin.knowledgefabric.io` |
| App Service | `app-kf-admin` |
| Deployed from | `main` |
| Resource group | `rg-kf-admin-weu-01` — everything the console owns, and nothing it does not |
| App Service plan | `P0v3` in `rg-kf-staging-weu-01`, **shared with the gateway's `app-stg-ai-gw`** |
| Key Vault | `kv-kf-admin-weu` |
| Application Insights | `app-kf-admin`, on its own workspace `log-kfadmin-weu-1` |
| GitHub Environment | `production` |

**Nothing here is named `stg` or `sandbox`**, because none of it is. The gateway carries names that
stopped being true — its own doc has to say so: *"The name `ai-sb`, and the `stg` in every resource
name, no longer mean what they say."* That happened because a tier token was chosen before the tier
was certain. Here it was certain first, so there is no token. If a second environment is ever built,
it is the one that gets a qualifier.

### Why one is enough, and what it costs

The usual case for a staging tier is somewhere to try a risky change. The console declines it, and
the reason is worth stating rather than assuming, because the argument is **not** "the risk is
small".

The failure that actually hurts here is minting a **wrong but valid** licence: a wrong expiry, a
report left out of the grant, a knowledge-source type written as an ordinal rather than a string, an absent
`schemaVersion`. That file is signed, long-lived, handed to a customer and installed, and there is no
recall. A staging console minting licences nobody inspects would not catch any of it.

What catches it is the contract fixture set — 26 signed cases, verified on every build and again on
every deploy — and #6's validate page showing the product's verdict and the gateway's side by side.
Those are the pre-issue check. **A change is proven by the fixtures and the validate page, never by
"we tried it on staging"**, and that stays true whether or not a second environment ever exists.

What it does cost: a bad deploy is felt by whoever is issuing a licence at the time. The fallback is
the CLI on a developer machine, which is how licences are issued today anyway — so the floor is the
status quo rather than an outage.

### Two consequences to schedule

**A required reviewer, the day #6 can issue.** With one environment there is no gated tier above
this one, so a merge to `main` reaches the signing key with nobody looking. That is acceptable
precisely while the console cannot issue anything. The day #6 lands, the `production` Environment
gets a **required reviewer** — *Settings → Environments → production → Required reviewers* — and a
deploy becomes a decision somebody makes. Put it on #6 rather than trusting this paragraph.

**A deployment slot, if a bad deploy ever bites.** It is the cheap substitute for the tier being
declined — deploy to the slot, check the real artifact, swap — and the `P0v3` already has slots, so
it costs nothing but the setting up. Deliberately not done now, and two things to know before doing
it: a slot gets **its own** system-assigned identity, so it needs its own `Key Vault Secrets User`
assignment or it cannot read a secret; and application settings **swap with the slot** unless each
is marked as a deployment slot setting, which is the trap. Also check what a swap does to sign-in
cookies: the data-protection keys that encrypt them live under each slot's own `%HOME%`.

### Sharing the gateway's plan

The console is idle almost all the time: a handful of sign-ins and a licence or two a week. A plan
of its own would be a B1 doing nothing, so it joins the gateway's `P0v3`. Two things follow.

**The plan is pinned to one instance, and the console needs that as much as the gateway does.** The
gateway's request limiter holds its window in process; the console's sign-in lockout
(`LoginThrottle`, backed by `IMemoryCache`) does the same, and so does its feature state
(`InMemoryFeatureStateStore`) on a console without a database; with one it is `feature_state` in
`kf_admin` (#135), which every instance shares. A second instance would silently double the number of password guesses an attacker gets
before lockout, with nothing failing loudly to announce it. The gateway's provisioning doc already
requires one instance and already has the alert on instance count that enforces it — that alert now
covers this app too, and whoever answers it should know there are two applications behind it.

**A shared plan is shared CPU.** Deploying the console restarts the console, not the gateway; but
they draw on the same compute, and the plan's `P0v3` is not large. Nothing the console does is
CPU-heavy — signing a licence is milliseconds — so this is a thing to know rather than a thing to
... (1097 lines truncated)
</file>

<file path="docs/README.md">
# KnowledgeFabric Licensing Documentation

Reference documentation for the licensing side of `kf-admin` — the tool that mints the signing keys
and the signed licence files that a KnowledgeFabric installation is unlocked with.

Start at the [repository README](../README.md) for a build-and-issue walkthrough. These pages are
the detail behind it.

## Pages

- [License Contract](License-Contract.md) — **normative.** What a licence means for all three
  codebases that read or write one: `schemaVersion`, the two compatibility rules, the names and
  encodings, the verification algorithm, and the signed fixture set that stands in for a shared
  library.
- [Admin Console](Admin-Console.md) — what this repository is: the internal admin console, with
  licence issuing as its first tenant, and what does not belong in it.
- [Console Shell](Console-Shell.md) — the ASP.NET Core application the console's features live
  inside: how sign-in works and why it is temporary, the roles per area and the Users page they are
  granted on, the audit and storage seams, the Vuexy template and how to recolour and rebuild it.
- [Installing on a Phone](Installing-On-A-Phone.md) — how to put the console on a home screen,
  on Android and on an iPhone, what the installed app keeps and what it never does, and how to
  remove it.
- [Notifications](Notifications.md) — each person's notifications: the bell and the inbox, the
  devices they are pushed to on a desktop, an Android phone and an installed iPhone app, how a push is
  encrypted, signed, sent and retried in the background, what is never logged, the Bookings area's four
  kinds and who hears of each, the CRM's morning follow-up reminders, the gateway watch on its brake
  and status, the key pair and what happens without it, and how an area adds a kind.
- [Provisioning](Provisioning.md) — how the console's Azure environment is built, Portal step by
  Portal step: the App Service on the gateway's plan, the Key Vault the signing key lives in and why
  it does not live in an application setting, Application Insights, the OIDC federated credentials
  the deploy authenticates with, and what currently guards the site.
- [Operations](Operations.md) — running it: deploying, adding people and granting their roles,
  rotating a person's password and the passphrase, why rotating the key pair is a different order
  of operation entirely, and where to look when a deploy, a sign-in or an issue fails.
- [Gateway Management](Gateway-Management.md) — running the AI gateway from the console: the area's
  overview of the gateway's status, its global brake and its fleet; its installations, filtered and
  paged, and each one's allowance, usage and licence; every licence in force beside what its
  installation has used, as a page and as CSV; the policy as it stands, each lever beside what it
  reaches, and changing it, with the only-goes-up rule applied from the register; the usage history,
  day by day from the gateway's ledger, for the fleet, an installation and a chosen range; revoking and
  restoring an installation, and the audit log both are recorded in; what the pages
  read and how often, what they say when the gateway cannot answer, and the pages still to come.
- [Localisation](Localisation.md) — how the console speaks English and Italian: the one shared
  resource and its dotted keys, the cookie switcher, how a string reaches a view, a controller, an
  attribute or a script, how to add a string or a language, the rule that culture changes what people
  see and nothing else, with every place that rule is enforced, and the glossary of domain terms.
- [CRM](CRM.md) — the partners and ambassadors programme as records, from the console instead of a
  spreadsheet: the contacts grid with the sheet's columns, edited in place, its stages, tracks and
  engagement scale, how a cell save carries the row's version so that nobody overwrites anybody, the
  interactions drawn into *Met?* and *With?* and the panel they are logged from, the next action
  beneath them and the follow-ups grid that lists it, the overview's counts, the row's details and
  delete, what is audited, and where the personal data it holds may and may not go.
- [Bookings](Bookings.md) — appointments booked with KnowledgeFabric's people: the area's two
  roles and three policies, the *Hosts* page an Administrator makes a person bookable on, each host's
  display name, email, time zone, link and levers, how a save carries the row's version, the
  connection to Zoho Calendar (its token, what is sent and what comes back, *Test connection* and
  the live check), each host's availability as windows on dates and the slots the calculator cuts
  from them, the public page where anyone books a slot in their own zone and the booking it writes,
  what guards it, the Zoho event that invites both, the bookings list with its tabs and each
  booking's page, cancelling, the overview's card, what is audited, the guest's personal data and its
  erasure, the three tables, and what is not here yet.
- [Competitors](Competitors.md) — our main competitors, one page each: the area's two roles and
  three policies, the list, each competitor's page with what they do and how we stand against them,
  the form that adds and edits one and how a save carries the row's version, the delete and restore,
  the overview's card, the settings page with the console's Ollama key, *Test connection* and the
  positioning statement every analysis carries; a competitor added from its website, what the console
  fetches and how, what the model is told and returns and that it can be wrong, the sources and their
  card, and *Refresh analysis* (#222); the daily scan (#223): when it runs and its record, the sources in
  order, what is a candidate, what the model is asked, what is stored, *Scan now* and the settings; the
  news feeds (#224): the global one, its filters and *More* by keyset, the competitor's own, an item marked
  irrelevant and back, and the overview's week and scan; what is audited, what is personal data here and
  what is not, the four tables, and what #219 left open and what is still to come (the notification).
- [License Register](License-Register.md) — the register of issued licences: why it is a database
  on the gateway's PostgreSQL server, what a row holds and where rows come from, the pages, the
  CSV format shared with the CLI, the installations the gateway holds with each licence, and how the
  console behaves with and without its database.
- [Issuing a License](Issuing-A-License.md) — the operational runbook: issuing from the console's
  form, or offline with the CLI — who issues, key custody, step by step, and every failure mode with
  its cause.
- [License Config Schema](License-Config-Schema.md) — every field of the configuration JSON, worked
  examples per licence type, and the expiration/timezone rule.
- [License Format](License-Format.md) — the anatomy of a `.lic` file, element by element, and which
  elements the product validates rather than merely displays.
- [License Entitlements](License-Entitlements.md) — what a licence grants and limits: the reports,
  features, connectors, analysis limits and AI limits it names, how each is written and read, and
  what the product and the gateway do with them today.
- [Branching](Branching.md) — branch naming, and how this repository's flow differs from kf-app's.

## Scope and provenance

Everything here was derived on 2026-09-20 by building this repository and running the tool, and by
reading the consuming code in [`kf-app`](https://github.com/KnowledgeFabric/kf-app) at commit
`075fa03`. Statements about what the *product* does cite the kf-app file they came from, because
that behaviour lives in a different repository and can change without anything here changing.

### Normative and descriptive

Most of these pages *describe* what the code does. Four of them also *bind* it, because the licence
contract has no shared library or published package to enforce it — [License Contract](License-Contract.md),
[License Format](License-Format.md), [License Config Schema](License-Config-Schema.md) and
... (37 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Controllers/AvailabilityController.cs">
public sealed class AvailabilityController(
⋮----
ILogger<AvailabilityController> logger) : Controller
⋮----
public async Task<IActionResult> Index(CancellationToken cancellationToken)
⋮----
hosts = await store.HostsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The Bookings area's hosts could not be read for the availability page.");
return View("Picker", new AvailabilityPicker([], ConsolePeople.IsPerson(SignedInAs), await MayConfigureAsync(), store.Storage, Unreadable: true));
⋮----
var self = ConsoleRoles.Normalise(SignedInAs);
if (hosts.Any(host => host.Name == self))
⋮----
return View("Picker", new AvailabilityPicker(mayConfigure ? hosts : [], ConsolePeople.IsPerson(SignedInAs), mayConfigure, store.Storage));
⋮----
public async Task<IActionResult> Week(string host, string? week, CancellationToken cancellationToken)
⋮----
var current = await store.FindHostAsync(host, cancellationToken);
⋮----
return await WeekAsync(current, WindowForm.ReadDay(week), new WindowForm(), NoProblems, StatusCodes.Status200OK, cancellationToken);
⋮----
public async Task<IActionResult> Add(string host, [FromForm] WindowForm form, CancellationToken cancellationToken)
⋮----
var shownWeek = WindowForm.ReadDay(form.Day) ?? WindowForm.ReadDay(form.Week);
⋮----
var (window, problems) = form.Parse(current, zone, clock.GetUtcNow(), SignedInAs, text);
⋮----
WindowAdd added;
⋮----
added = await store.AddWindowAsync(window, CancellationToken.None);
⋮----
logger.LogError(ex, "A window could not be added for the host {Name}; nothing was written.", current.Name);
⋮----
var stored = AvailabilityCell.Of(added.Window!, zone, SlotRules.Of(current), clock.GetUtcNow());
⋮----
return RedirectToAction(nameof(Week), new { host = current.Name, week = WindowForm.Date(WindowTimes.MondayOf(stored.Day)) });
⋮----
var existing = AvailabilityCell.Of(added.Window!, zone, SlotRules.Of(current), clock.GetUtcNow());
⋮----
public async Task<IActionResult> Remove(string host, Guid id, string? week, CancellationToken cancellationToken)
⋮----
var shownWeek = WindowForm.ReadDay(week);
⋮----
return await WeekAsync(current, shownWeek, new WindowForm(), NoProblems, StatusCodes.Status400BadRequest, cancellationToken,
⋮----
var window = await store.FindWindowAsync(current.Name, id, cancellationToken);
⋮----
return await WeekAsync(current, shownWeek, new WindowForm(), NoProblems, StatusCodes.Status200OK, cancellationToken, alreadyRemoved: true);
⋮----
var cell = AvailabilityCell.Of(window, zone, SlotRules.Of(current), clock.GetUtcNow());
⋮----
return await WeekAsync(current, cell.Day, new WindowForm(), NoProblems, StatusCodes.Status400BadRequest, cancellationToken,
⋮----
removed = await store.RemoveWindowAsync(current.Name, id, CancellationToken.None);
⋮----
logger.LogError(ex, "The window {Id} of the host {Name} could not be removed; nothing was.", id, current.Name);
return await WeekAsync(current, cell.Day, new WindowForm(), NoProblems, StatusCodes.Status500InternalServerError, cancellationToken,
⋮----
return await WeekAsync(current, cell.Day, new WindowForm(), NoProblems, StatusCodes.Status200OK, cancellationToken, alreadyRemoved: true);
⋮----
return RedirectToAction(nameof(Week), new { host = current.Name, week = WindowForm.Date(WindowTimes.MondayOf(cell.Day)) });
⋮----
public async Task<IActionResult> SetPattern(string host, int weekday, [FromForm] PatternForm form, CancellationToken cancellationToken)
⋮----
if (current is null || !Weekdays.IsWeekday(weekday))
⋮----
var shownWeek = WindowForm.ReadDay(form.Week);
⋮----
var (spans, expected, problems) = form.Parse(text);
⋮----
page => page with { PatternSent = (weekday, form.Padded()), PatternProblems = problems });
⋮----
PatternSave saved;
⋮----
saved = await store.SetPatternAsync(current.Name, weekday, expected, spans, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "The pattern of the host {Name} could not be saved; nothing was written.", current.Name);
return await WeekAsync(current, shownWeek, new WindowForm(), NoProblems, StatusCodes.Status500InternalServerError, cancellationToken,
page => page with { PatternSent = (weekday, form.Padded()) }, problem: text["Booking.Pattern.NotSaved"]);
⋮----
["weekday"] = Weekdays.Invariant(weekday),
["before"] = SpanTimes.Invariant(saved.Before.Select(span => span.Times)),
["spans"] = SpanTimes.Invariant(saved.After.Select(span => span.Times)),
⋮----
return await WeekAsync(current, shownWeek, new WindowForm(), NoProblems, StatusCodes.Status409Conflict, cancellationToken,
page => page with { PatternStale = (weekday, saved.Before.Select(span => span.Times).ToList(), spans) });
⋮----
var clash = AvailabilityCell.Of(saved.Clash!, ZoneOf(current), SlotRules.Of(current), clock.GetUtcNow());
⋮----
page => page with { PatternSent = (weekday, form.Padded()), PatternClash = (weekday, clash) });
⋮----
public async Task<IActionResult> AddDayOff(string host, [FromForm] DayOffForm form, CancellationToken cancellationToken)
⋮----
var day = WindowForm.ReadDay(form.Day);
var shownWeek = day ?? WindowForm.ReadDay(form.Week);
⋮----
DayOffChange added;
⋮----
added = await store.AddDayOffAsync(new DayOff { HostName = current.Name, Day = day!.Value, CreatedBy = SignedInAs, CreatedAt = clock.GetUtcNow() }, CancellationToken.None);
... (104 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Controllers/BookingsController.cs">
public sealed class BookingsController(
⋮----
ILogger<BookingsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? tab, string? who, string? host, CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
⋮----
var mayWrite = (await authorization.AuthorizeAsync(User, ConsolePolicies.BookingWrite)).Succeeded;
var mayConfigure = (await authorization.AuthorizeAsync(User, ConsolePolicies.BookingConfigure)).Succeeded;
⋮----
var query = BookingListQuery.Read(tab, who, host, signedInIsHost: false, everyone: mayConfigure);
⋮----
hosts = await store.HostsAsync(cancellationToken);
var isHost = hosts.Any(row => row.Name == ConsoleRoles.Normalise(self));
query = BookingListQuery.Read(tab, who, host, isHost, everyone: mayConfigure);
⋮----
hosts = hosts.Where(row => row.Name == ConsoleRoles.Normalise(self)).ToList();
⋮----
var (from, to) = query.Range(now);
bookings = query.Select(await store.AllBookingsAsync(from, to, cancellationToken), self, now);
⋮----
if (bookings.Any(booking => booking.LinkId is not null))
⋮----
linkTitles = (await store.LinksAsync(cancellationToken)).ToDictionary(link => link.Id, link => link.Title);
⋮----
logger.LogError(ex, "The bookings could not be read for the list.");
⋮----
var selfKey = ConsoleRoles.Normalise(self);
⋮----
.Select(booking => new BookingListRow(booking, ZoneOf(booking),
mayConfigure || (mayWrite && booking.Holds(selfKey)),
booking.LinkId is { } linkId ? linkTitles.GetValueOrDefault(linkId) : null))
.ToList();
⋮----
var selfIsHost = hosts.Any(row => row.Name == selfKey);
return View(new BookingListPage(
⋮----
OwnLinks = selfIsHost ? await BookingLinkCard.OpenLinksOfAsync(store, options.Value, selfKey, now, cancellationToken) : [],
⋮----
public async Task<IActionResult> Show(Guid id, CancellationToken cancellationToken)
⋮----
var booking = await store.FindBookingAsync(id, cancellationToken);
⋮----
return await PageAsync(booking, BookingNotice.Read(TempData[NoticeKey] as string), null, StatusCodes.Status200OK, cancellationToken);
⋮----
public async Task<IActionResult> Resend(Guid id, CancellationToken cancellationToken)
⋮----
var sent = await invitations.SendAsync(booking, hosts, Auditor, resend: true);
⋮----
public async Task<IActionResult> Cancel(Guid id, CancellationToken cancellationToken)
⋮----
/// <summary>
/// The cancel: redirects to the page once the row is cancelled, whatever Zoho said of the event;
/// <c>400</c> with the form when the reason is missing or too long; <c>409</c> with the booking as
/// it stands when its version has moved; <c>200</c> with the page, recording nothing, when it was
/// already cancelled.
/// </summary>
⋮----
public async Task<IActionResult> Cancel(Guid id, [FromForm] string? version, [FromForm] string? reason, CancellationToken cancellationToken)
⋮----
if (!uint.TryParse(version, NumberStyles.None, CultureInfo.InvariantCulture, out var read))
⋮----
BookingCancel cancelled;
⋮----
cancelled = await invitations.CancelAsync(id, read, typed, Auditor);
⋮----
logger.LogError(ex, "The booking {Id} could not be cancelled; nothing was.", id);
⋮----
private async Task<bool> MaySeeAsync(BookingRecord booking) =>
booking.Holds(SignedInAs)
|| (await authorization.AuthorizeAsync(User, ConsolePolicies.BookingConfigure)).Succeeded;
⋮----
private async Task<bool> MayActAsync(BookingRecord booking)
⋮----
if ((await authorization.AuthorizeAsync(User, ConsolePolicies.BookingConfigure)).Succeeded)
⋮----
return booking.Holds(SignedInAs)
&& (await authorization.AuthorizeAsync(User, ConsolePolicies.BookingWrite)).Succeeded;
⋮----
private async Task<IReadOnlyList<BookingHost>> HostsOfAsync(BookingRecord booking, CancellationToken cancellationToken)
⋮----
if (await store.FindHostAsync(name, cancellationToken) is { } host)
⋮----
hosts.Add(host);
⋮----
private async Task<BookingPage> BookingPageAsync(
⋮----
var lead = hosts.FirstOrDefault(host => host.Name == booking.HostName);
var names = booking.Hosts.Select(name => hosts.FirstOrDefault(host => host.Name == name)?.DisplayName ?? name).ToList();
⋮----
return new BookingPage(booking, lead, ZoneOf(booking), mayAct, notice, problem, clock.GetUtcNow())
⋮----
HostsDisplayName = HostSet.Join(names, text),
LinkTitle = booking.LinkId is { } linkId ? (await store.FindLinkAsync(linkId, cancellationToken))?.Title : null,
⋮----
private async Task<IActionResult> PageAsync(BookingRecord booking, string? notice, string? problem, int status, CancellationToken cancellationToken)
⋮----
private async Task<IActionResult> CancelFormAsync(
⋮----
... (12 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Controllers/HomeController.cs">
public sealed class HomeController : Controller
⋮----
public IActionResult Index() => RedirectToAction("Index", "Bookings");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Controllers/HostsController.cs">
public sealed class HostsController(
⋮----
ILogger<HostsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(CancellationToken cancellationToken)
⋮----
var hosts = await store.HostsAsync(cancellationToken);
⋮----
return View(HostsPage.Build(store.Storage, names, hosts, unreadable, options.CurrentValue) with { Zoho = CardOf() });
⋮----
public async Task<IActionResult> TestZoho(CancellationToken cancellationToken)
⋮----
var read = await zoho.GetCalendarAsync(cancellationToken);
var tested = new ZohoTest(read.Outcome, read.Value?.Name, read.Code);
⋮----
return View(nameof(Index), HostsPage.Build(store.Storage, names, hosts, unreadable, options.CurrentValue) with { Zoho = CardOf(tested) });
⋮----
private ZohoCard CardOf(ZohoTest? tested = null) => new(zoho.IsConfigured, zoho.Missing, tested);
⋮----
public async Task<IActionResult> Edit(string name, CancellationToken cancellationToken)
⋮----
if (ConsoleRoles.IsAdmin(name) || (!mayConfigure && !IsSelf(name)))
⋮----
return await FormAsync(new HostEditPage(shown, current, current is null ? HostForm.Defaults() : HostForm.Of(current, withVersion: true),
hasRole, store.Storage, options.CurrentValue, NoProblems, MayConfigure: mayConfigure) { FeedNoticeWarns = TempData.Peek(AddedCount) is 0, FeedNotice = current is null ? null : FeedNoticeFromTempData(current) }, cancellationToken: cancellationToken);
⋮----
public async Task<IActionResult> Edit(string name, [FromForm] HostForm form, CancellationToken cancellationToken)
⋮----
var version = form.ReadVersion();
⋮----
var page = new HostEditPage(shown, current, form, hasRole, store.Storage, options.CurrentValue, NoProblems, MayConfigure: mayConfigure);
⋮----
var (settings, problems) = form.Parse(text);
⋮----
var now = clock.GetUtcNow();
HostSave save;
⋮----
save = await store.SaveHostAsync(name, read, settings, SignedInAs, now, CancellationToken.None);
⋮----
var host = settings.Copy();
var created = new BookingHost
⋮----
Name = ConsoleRoles.Normalise(name),
⋮----
host.CopySettingsTo(created);
save = await store.AddHostAsync(created, CancellationToken.None);
⋮----
logger.LogError(ex, "The host {Name} could not be saved; nothing was written.", ConsoleRoles.Normalise(name));
⋮----
await AuditAsync("booking:host-set", ConsoleRoles.Normalise(name), new Dictionary<string, string?>
⋮----
["fields"] = string.Join(",", save.Changed),
⋮----
Form = HostForm.Of(colleague, withVersion: true),
⋮----
Lost = BookingHost.Differences(colleague, Merged(colleague, settings)),
⋮----
public async Task<IActionResult> Remove(string name, CancellationToken cancellationToken)
⋮----
if (ConsoleRoles.IsAdmin(name))
⋮----
return View("Remove", new HostRemovePage(
⋮----
HasBookings: await store.HasBookingsAsync(current.Name, cancellationToken),
OnLinks: await store.HasLinksAsync(current.Name, cancellationToken)));
⋮----
public async Task<IActionResult> Remove(string name, string? version, CancellationToken cancellationToken)
⋮----
var read = new HostForm { Version = version }.ReadVersion();
⋮----
save = await store.RemoveHostAsync(name, read.Value, CancellationToken.None);
⋮----
logger.LogError(ex, "The host {Name} could not be removed; nothing was.", ConsoleRoles.Normalise(name));
var refused = View("Remove", new HostRemovePage(shown, current, Problem: text["Booking.Hosts.NotRemoved"]));
⋮----
await AuditAsync("booking:host-remove", ConsoleRoles.Normalise(name), new Dictionary<string, string?>());
⋮----
var stale = View("Remove", new HostRemovePage(shown, save.Host!, Conflict: true));
⋮----
var kept = View("Remove", new HostRemovePage(shown, current, HasBookings: true));
⋮----
var linked = View("Remove", new HostRemovePage(shown, current, OnLinks: true));
⋮----
private async Task<(string Shown, BookingHost? Current, bool HasRole)> ResolveAsync(string name, CancellationToken cancellationToken)
⋮----
var key = ConsoleRoles.Normalise(name);
⋮----
var person = names.FirstOrDefault(candidate => ConsoleRoles.Normalise(candidate) == key);
var current = await store.FindHostAsync(key, cancellationToken);
⋮----
return (person ?? current?.Name ?? name.Trim(), current, person is not null);
⋮----
private async Task<(IReadOnlyList<string> Names, bool Unreadable)> PeopleAsync(CancellationToken cancellationToken)
⋮----
return (await people.BookingAsync(cancellationToken), false);
⋮----
logger.LogError(ex, "The Hosts page could not read who holds a Booking role.");
⋮----
private static BookingHost Merged(BookingHost colleague, BookingHost typed)
⋮----
... (86 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Controllers/LinksController.cs">
public sealed class LinksController(
⋮----
ILogger<LinksController> logger) : Controller
⋮----
private static class Notices
⋮----
public static string? Read(string? key) => key is Created or Saved or Ended ? key : null;
⋮----
public async Task<IActionResult> Index(string? tab, string? host, CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
var self = ConsoleRoles.Normalise(SignedInAs);
⋮----
var query = BookingLinkListQuery.Read(tab, host, everyone: mayConfigure);
⋮----
hosts = await store.HostsAsync(cancellationToken);
var links = query.Select(await store.LinksAsync(cancellationToken), self, mayConfigure, now);
⋮----
rows = links.Select(link => Row(link, hosts, served, counts, self, mayWrite, mayConfigure, now)).ToList();
⋮----
logger.LogError(ex, "The booking links could not be read for the list.");
⋮----
var created = Guid.TryParse(TempData[CreatedKey] as string, CultureInfo.InvariantCulture, out var id) ? id : (Guid?)null;
var mayMake = mayConfigure || (mayWrite && hosts.Any(row => row.Name == self));
⋮----
return View(new BookingLinkListPage(
⋮----
created, Notices.Read(TempData[NoticeKey] as string)));
⋮----
public async Task<IActionResult> New(string? host, CancellationToken cancellationToken)
⋮----
var hosts = await store.HostsAsync(cancellationToken);
⋮----
var asked = mayConfigure && !string.IsNullOrWhiteSpace(host) ? ConsoleRoles.Normalise(host) : self;
var lead = hosts.FirstOrDefault(row => row.Name == asked) ?? (mayConfigure ? null : hosts.FirstOrDefault(row => row.Name == self));
⋮----
var today = lead is null ? DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime) : WindowTimes.DayIn(clock.GetUtcNow(), ZoneOf(lead));
var suggestion = lead is null ? string.Empty : BookingLinkTitles.Suggest([lead.DisplayName], text);
var form = new BookingLinkForm
⋮----
ExpiresOn = BookingLinkForm.Day(BookingLink.DefaultExpiryDay(today)),
⋮----
public async Task<IActionResult> Create([FromForm] BookingLinkForm form, [FromForm] string? suggested, CancellationToken cancellationToken)
⋮----
var asked = string.IsNullOrWhiteSpace(form.Lead) ? (mayConfigure ? null : self) : ConsoleRoles.Normalise(form.Lead);
⋮----
var lead = asked is null ? null : hosts.FirstOrDefault(row => row.Name == asked);
⋮----
else if (!served.Contains(lead.Name))
⋮----
foreach (var name in form.Colleagues.Where(name => !string.IsNullOrWhiteSpace(name)).Select(ConsoleRoles.Normalise).Distinct(StringComparer.Ordinal))
⋮----
var colleague = hosts.FirstOrDefault(row => row.Name == name);
if (colleague is null || colleague.Name == lead?.Name || ConsoleRoles.IsAdmin(name))
⋮----
if (!served.Contains(colleague.Name))
⋮----
colleagues.Add(colleague);
⋮----
problems.TryAdd(BookingLinkForm.Fields.Colleagues, text["Booking.Links.Problem.Colleagues", BookingRecord.MaxHosts - 1]);
⋮----
var today = WindowTimes.DayIn(clock.GetUtcNow(), zone);
⋮----
var suggestion = BookingLinkTitles.Suggest(linkHosts.Select(row => row.DisplayName).ToList(), text);
⋮----
if (suggested is not null && (form.Title ?? string.Empty).Trim() == suggested.Trim())
⋮----
var title = form.ReadTitle(suggestion, problems, text);
form.ReadExpiry(zone, today, problems, text, out var expiresAt);
⋮----
var link = new BookingLink
⋮----
Id = Guid.NewGuid(),
Token = BookingLink.NewToken(),
⋮----
Hosts = [.. linkHosts.Select(row => row.Name)],
⋮----
LinkChange added;
⋮----
added = await store.AddLinkAsync(link, CancellationToken.None);
⋮----
logger.LogError(ex, "A booking link led by {Lead} could not be written; nothing was.", lead.Name);
⋮----
["hosts"] = string.Join(",", stored.Hosts),
⋮----
TempData[CreatedKey] = stored.Id.ToString("D", CultureInfo.InvariantCulture);
⋮----
return Redirect(Url.Action(nameof(Index)) + $"#link-{stored.Id:D}");
⋮----
public async Task<IActionResult> Edit(Guid id, CancellationToken cancellationToken)
⋮----
var lead = hosts.FirstOrDefault(row => row.Name == link!.HostName);
⋮----
ExpiresOn = BookingLinkForm.Day(link.ExpiresAt is { } expires ? BookingLink.ExpiryDayOf(expires, zone) : BookingLink.DefaultExpiryDay(today)),
⋮----
Version = link.Version.ToString(CultureInfo.InvariantCulture),
⋮----
public async Task<IActionResult> Edit(Guid id, [FromForm] BookingLinkForm form, CancellationToken cancellationToken)
⋮----
if (!uint.TryParse(form.Version, NumberStyles.None, CultureInfo.InvariantCulture, out var version))
... (121 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Controllers/PublicController.cs">
public sealed class PublicController(
⋮----
ILogger<PublicController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? tz, CancellationToken cancellationToken)
⋮----
var zone = PublicZone.Parse(tz);
⋮----
var listed = (await store.HostsAsync(cancellationToken)).Where(host => host.Listed && host.Enabled).ToList();
⋮----
var shown = PublicTeam.Order(listed.Where(host => holders.Contains(host.Name)));
⋮----
var members = shown.Select(host => new PublicTeamMember(host.Slug, host.DisplayName)).ToList();
⋮----
if (sent.Count == 0 && !Request.Query.ContainsKey(PublicTeam.ContinueQuery))
⋮----
return PublicView("Team", new PublicTeamPage(members, zone), "Booking.Team.Title");
⋮----
var (chosen, problem) = PublicTeam.Choose(shown, sent.OfType<string>());
⋮----
var ticked = sent.OfType<string>().Where(slug => shown.Any(host => host.Slug == slug)).ToHashSet(StringComparer.Ordinal);
var refused = PublicView("Team", new PublicTeamPage(members, zone, Chosen: ticked, Problem: why), "Booking.Team.Title");
⋮----
return Redirect(Url.PublicLink(nameof(Month), new HostSet(chosen), new { tz = zone.Query }));
⋮----
private ViewResult TeamClosed(PublicZone zone) =>
PublicView("Team", new PublicTeamPage([], zone, Closed: true), "Booking.Public.Closed");
⋮----
public async Task<IActionResult> Month(string slug, string? month, string? tz, CancellationToken cancellationToken)
⋮----
return await MonthAsync(hosts!, PublicZone.Parse(tz), PublicRoutes.ReadMonth(month), cancellationToken);
⋮----
public async Task<IActionResult> LinkMonth(string token, string? month, string? tz, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> Day(string slug, string day, string? tz, CancellationToken cancellationToken)
⋮----
if (PublicRoutes.ReadDay(day) is not { } date)
⋮----
return await DayAsync(hosts!, PublicZone.Parse(tz), date, null, StatusCodes.Status200OK, cancellationToken);
⋮----
public async Task<IActionResult> LinkDay(string token, string day, string? tz, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> Slot(string slug, string day, string time, string? tz, CancellationToken cancellationToken)
⋮----
if (PublicRoutes.ReadSlot(day, time) is not { } instant)
⋮----
public async Task<IActionResult> LinkSlot(string token, string day, string time, string? tz, CancellationToken cancellationToken)
⋮----
private async Task<IActionResult> SlotAsync(HostSet hosts, DateTimeOffset instant, string? tz, CancellationToken cancellationToken)
⋮----
return await DayAsync(hosts, zone, zone.DayOf(instant), text["Booking.Public.SlotGone"], StatusCodes.Status200OK, cancellationToken);
⋮----
var form = new BookingForm { Slot = BookingRecord.Instant(instant), Tz = zone.Id };
⋮----
public async Task<IActionResult> Book(string slug, [FromForm] BookingForm form, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> LinkBook(string token, [FromForm] BookingForm form, CancellationToken cancellationToken)
⋮----
private async Task<IActionResult> BookAsync(HostSet set, BookingForm form, CancellationToken cancellationToken)
⋮----
if (PublicRoutes.ReadInstant(form.Slot) is not { } instant)
⋮----
var zone = PublicZone.Parse(form.Tz);
⋮----
var length = TimeSpan.FromMinutes(set.DurationMinutes);
RememberBooked(instant, instant + length, zone, sent: true, GuestLink.New().Token);
return Redirect(Url.PublicLink(nameof(Booked), set));
⋮----
return await DayAsync(set, zone, zone.DayOf(instant), text["Booking.Public.JustTaken"], StatusCodes.Status409Conflict, cancellationToken);
⋮----
var (guest, problems) = form.Parse(text);
⋮----
if (await store.CountLiveBookingsAsync(host.Name, guest.Email, cancellationToken) >= BookingRecord.MaxLivePerEmail)
⋮----
var now = clock.GetUtcNow();
var (cancelToken, cancelTokenHash) = GuestLink.New();
var booking = new BookingRecord
⋮----
Id = Guid.NewGuid(),
⋮----
BookingAdd added;
⋮----
added = await store.AddBookingAsync(booking, CancellationToken.None);
⋮----
logger.LogError(ex, "A booking with the hosts {Names} could not be written; nothing was.", string.Join(",", set.Names));
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
Target: stored.Id.ToString(),
⋮----
var invited = await invitations.SendAsync(stored, set.Hosts, Guest(), resend: false, cancelToken);
⋮----
public async Task<IActionResult> Booked(string slug, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> LinkBooked(string token, CancellationToken cancellationToken)
⋮----
private IActionResult BookedPage(HostSet hosts)
⋮----
var zone = PublicZone.Parse(TempData[BookedZone] as string);
... (170 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/AvailabilityPage.cs">
public DateOnly Sunday => Monday.AddDays(6);
⋮----
public DateOnly PreviousMonday => Monday.AddDays(-7);
⋮----
public DateOnly? NextMonday => Monday < LastMonday ? Monday.AddDays(7) : null;
⋮----
public DateOnly? ThisMonday => WindowTimes.MondayOf(Today) is var current && current != Monday ? current : null;
⋮----
public string HostsDisplayNames(IReadOnlyList<string> names, IStringLocalizer<ConsoleResource> text) =>
HostSet.Join(names.Select(name => OtherHosts.GetValueOrDefault(name) ?? name).ToList(), text);
⋮----
public IEnumerable<(BookingRecord Booking, TimeOnly Start, TimeOnly End)> BookingsOn(DateOnly day) => Bookings
.Select(booking => (Booking: booking, Start: TimeZoneInfo.ConvertTime(booking.StartsAt, Zone).DateTime, End: TimeZoneInfo.ConvertTime(booking.EndsAt, Zone).DateTime))
.Where(item => DateOnly.FromDateTime(item.Start) == day)
.OrderBy(item => item.Booking.StartsAt)
.Select(item => (item.Booking, TimeOnly.FromDateTime(item.Start), TimeOnly.FromDateTime(item.End)));
⋮----
public string? ProblemOf(string field) => Problems.GetValueOrDefault(field);
⋮----
public SlotRules Rules => SlotRules.Of(Host);
⋮----
public IReadOnlyList<string> CalendarBarsOn(DateOnly day)
⋮----
var start = WindowTimes.StartOfDay(day, Zone);
var end = WindowTimes.StartOfDay(day.AddDays(1), Zone);
⋮----
.Where(busy => busy.Start < end && start < busy.End)
.Select(busy =>
⋮----
var width = Math.Max((to - from).TotalMinutes / length * 100, 0.5);
return string.Create(CultureInfo.InvariantCulture, $"left:{left:0.##}%;width:{width:0.##}%");
⋮----
.ToList();
⋮----
public IReadOnlyList<SpanTimes> SpansOn(int weekday) =>
Pattern.Where(span => span.Weekday == weekday).Select(span => span.Times).Order().ToList();
⋮----
public PatternForm PatternFormFor(int weekday) =>
PatternSent is { } sent && sent.Weekday == weekday ? sent.Form : PatternForm.For(SpansOn(weekday), WindowForm.Date(Monday));
⋮----
public bool PatternOpen(int weekday) =>
⋮----
public bool IsOff(DateOnly day) => DaysOff.Any(dayOff => dayOff.Day == day);
⋮----
public IEnumerable<DayOff> UpcomingDaysOff => DaysOff.Where(dayOff => dayOff.Day >= Today).OrderBy(dayOff => dayOff.Day);
⋮----
public bool MayTakeOff(DateOnly day) => CanChange && day >= Today && day <= LastDay;
⋮----
public static IReadOnlyList<AvailabilityDay> Week(
⋮----
.Select(window => AvailabilityCell.Of(window, zone, rules, now, busy))
.Where(cell => cell.Day >= monday && cell.Day <= monday.AddDays(6))
.OrderBy(cell => cell.Window.StartsAt)
⋮----
return Enumerable.Range(0, 7)
.Select(offset => monday.AddDays(offset))
.Select(day => new AvailabilityDay(day, day == today, day < today, cells.Where(cell => cell.Day == day).ToList(), daysOff?.Contains(day) == true))
⋮----
public static AvailabilityCell Of(AvailabilityWindow window, TimeZoneInfo hostZone, SlotRules rules, DateTimeOffset now, IReadOnlyList<BusyInterval>? busy = null)
⋮----
var (start, end) = window.LocalTimes(hostZone);
⋮----
return new AvailabilityCell(
⋮----
DateOnly.FromDateTime(start),
TimeOnly.FromDateTime(start),
TimeOnly.FromDateTime(end),
⋮----
window.HasEnded(now),
SlotCalculator.Yield(window, rules, now, busy ?? []));
⋮----
public string Times => $"{WindowForm.Time(Start)}–{WindowForm.Time(End)}";
⋮----
var left = Start.ToTimeSpan().TotalMinutes / day * 100;
var width = Math.Max((End.ToTimeSpan().TotalMinutes / day * 100) - left, 1);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/BookingLinkCard.cs">
public static async Task<IReadOnlyList<OpenBookingLink>> OpenLinksOfAsync(
⋮----
links = await store.LinksAsync(cancellationToken);
⋮----
return new BookingLinkListQuery(BookingLinkState.Open, null)
.Select(links, hostName, everyone: false, now)
.Select(link => new OpenBookingLink(link.Id, link.Title, BookingLink.LinkFor(options.PublicBaseUrl, link.Token), link.ExpiresAt))
.ToList();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/BookingList.cs">
public static BookingListQuery Read(string? tab, string? who, string? host, bool signedInIsHost, bool everyone = true)
⋮----
var readTab = tab?.Trim().ToLowerInvariant() switch
⋮----
var mine = !everyone || (who?.Trim().ToLowerInvariant() switch
⋮----
var filter = mine || string.IsNullOrWhiteSpace(host) ? null : ConsoleRoles.Normalise(host);
return new BookingListQuery(readTab, mine, filter);
⋮----
public static string Word(BookingTab tab) => tab switch
⋮----
public IReadOnlyList<BookingRecord> Select(IEnumerable<BookingRecord> all, string self, DateTimeOffset now)
⋮----
var whose = Mine ? ConsoleRoles.Normalise(self) : Host;
var rows = all.Where(booking => whose is null || booking.Holds(whose));
⋮----
.Where(booking => booking.IsLive && booking.EndsAt <= now)
.OrderByDescending(booking => booking.StartsAt).ThenBy(booking => booking.HostName, StringComparer.Ordinal)
.ToList(),
⋮----
.Where(booking => !booking.IsLive)
⋮----
.Where(booking => booking.IsLive && booking.EndsAt > now)
.OrderBy(booking => booking.StartsAt).ThenBy(booking => booking.HostName, StringComparer.Ordinal)
⋮----
public (DateTimeOffset? From, DateTimeOffset? To) Range(DateTimeOffset now) => Tab switch
⋮----
public DateTime HostStart => TimeZoneInfo.ConvertTime(Booking.StartsAt, HostZone).DateTime;
⋮----
public DateTime HostEnd => TimeZoneInfo.ConvertTime(Booking.EndsAt, HostZone).DateTime;
⋮----
public string DisplayNameOf(string name) => Hosts.FirstOrDefault(host => host.Name == name)?.DisplayName ?? name;
⋮----
public int Enabled => Hosts.Count(host => host.Enabled);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/BookingPages.cs">
public string DisplayNameOf(string name) =>
Hosts.FirstOrDefault(host => host.Name == name)?.DisplayName ?? (Host is { } lead && lead.Name == name ? lead.DisplayName : name);
⋮----
public DateTime HostStart => TimeZoneInfo.ConvertTime(Booking.StartsAt, HostZone).DateTime;
⋮----
public DateTime HostEnd => TimeZoneInfo.ConvertTime(Booking.EndsAt, HostZone).DateTime;
⋮----
public (DateTime Start, DateTime End)? GuestTimes => WindowTimes.Find(Booking.GuestTimeZone) is { } zone
? (TimeZoneInfo.ConvertTime(Booking.StartsAt, zone).DateTime, TimeZoneInfo.ConvertTime(Booking.EndsAt, zone).DateTime)
⋮----
public static class BookingNotice
⋮----
public static string? Read(string? word) => word is not null && Known.Contains(word) ? word : null;
⋮----
public static string KeyOf(string word) => word switch
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/FeedForm.cs">
public sealed class FeedForm
⋮----
public static class Fields
⋮----
public FeedForm Redrawn() => new() { Label = Label };
⋮----
public (string? Label, Uri? Address, IReadOnlyDictionary<string, string> Problems) Parse(IStringLocalizer<ConsoleResource> text)
⋮----
var (address, problem) = CalendarFeedAddress.Read(Address);
⋮----
public static string ProblemOf(FeedOutcome outcome, IStringLocalizer<ConsoleResource> text) => outcome switch
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/HostForm.cs">
public sealed class HostForm
⋮----
public static HostForm Defaults() => Of(new BookingHost { TimeZone = TimeZones.Default });
⋮----
public static HostForm Of(BookingHost host, bool withVersion = false) => new()
⋮----
public bool IsEnabled => string.Equals(Enabled?.Trim(), "true", StringComparison.OrdinalIgnoreCase);
⋮----
public bool IsListed => string.Equals(Listed?.Trim(), "true", StringComparison.OrdinalIgnoreCase);
⋮----
public uint? ReadVersion() =>
uint.TryParse(Version, NumberStyles.None, CultureInfo.InvariantCulture, out var version) ? version : null;
⋮----
public (BookingHost? Settings, IReadOnlyDictionary<string, string> Problems) Parse(IStringLocalizer<ConsoleResource> text)
⋮----
var settings = new BookingHost();
⋮----
else if (!TimeZones.IsKnown(zone))
⋮----
if (BookingHost.IsReservedSlug(slug))
⋮----
else if (!BookingHost.IsSlug(slug))
⋮----
if (Whole(DurationMinutes) is { } duration && BookingHost.IsDuration(duration))
⋮----
if (string.IsNullOrWhiteSpace(StepMinutes))
⋮----
else if (Whole(StepMinutes) is { } step && BookingHost.IsStep(step))
⋮----
if (Whole(NoticeHours) is { } notice && BookingHost.IsNotice(notice))
⋮----
if (Whole(HorizonDays) is { } horizon && BookingHost.IsHorizon(horizon))
⋮----
if (Whole(BufferMinutes) is { } buffer && BookingHost.IsBuffer(buffer))
⋮----
settings.Location = string.IsNullOrEmpty(location) ? null : location;
⋮----
public static bool IsAddress(string value) =>
!value.Any(char.IsWhiteSpace)
&& value.IndexOf('@') is > 0 and var at && at < value.Length - 1
&& MailAddress.TryCreate(value, out var address)
&& string.Equals(address.Address, value, StringComparison.Ordinal);
⋮----
private static int? Whole(string? value) =>
int.TryParse(value?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var number) ? number : null;
⋮----
private static string N(int value) => value.ToString(CultureInfo.InvariantCulture);
⋮----
private static string N(uint value) => value.ToString(CultureInfo.InvariantCulture);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/HostsPage.cs">
public static HostsPage Build(
⋮----
var byName = hosts.ToDictionary(host => host.Name, StringComparer.Ordinal);
⋮----
.Where(ConsolePeople.IsPerson)
.Select(name => new HostRow(name, byName.GetValueOrDefault(ConsoleRoles.Normalise(name)), HasRole: true))
.ToList();
⋮----
var listed = rows.Select(row => ConsoleRoles.Normalise(row.Name)).ToHashSet(StringComparer.Ordinal);
rows.AddRange(hosts
.Where(host => !listed.Contains(host.Name) && ConsolePeople.IsPerson(host.Name))
.Select(host => new HostRow(host.Name, host, HasRole: false)));
⋮----
return new HostsPage(storage, rows.OrderBy(row => row.Name, StringComparer.OrdinalIgnoreCase).ToList(), peopleUnreadable, options);
⋮----
public int Bookable => Rows.Count(row => row.Host is not null);
⋮----
public int Enabled => Rows.Count(row => row.Host is { Enabled: true });
⋮----
public string AuditOutcome => Outcome == ZohoOutcome.Ok ? "Read" : Outcome.ToString();
⋮----
public string Key => ConsoleRoles.Normalise(Name);
⋮----
public string? ProblemOf(string field) => Problems.GetValueOrDefault(field);
⋮----
public string? FeedProblemOf(string field) => FeedProblems.GetValueOrDefault(field);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/LinkPages.cs">
public static class BookingLinkTitles
⋮----
public static string Suggest(IReadOnlyList<string> displayNames, IStringLocalizer<ConsoleResource> text)
⋮----
var names = displayNames.Select(name => name.Trim()).ToList();
var title = text["Booking.Links.SuggestedTitle", HostSet.Join(names, text)].Value.Trim();
return title.Length <= BookingLink.TitleLength ? title : title[..(BookingLink.TitleLength - 1)].TrimEnd() + "…";
⋮----
public static BookingLinkListQuery Read(string? tab, string? host, bool everyone)
⋮----
var readTab = tab?.Trim().ToLowerInvariant() switch
⋮----
return new BookingLinkListQuery(readTab, everyone && !string.IsNullOrWhiteSpace(host) ? ConsoleRoles.Normalise(host) : null);
⋮----
public static string Word(BookingLinkState tab) => tab switch
⋮----
public IReadOnlyList<BookingLink> Select(IEnumerable<BookingLink> all, string self, bool everyone, DateTimeOffset now)
⋮----
.Where(link => everyone || link.Holds(self))
.Where(link => Host is null || link.Holds(Host))
.Where(link => link.StateAt(now) == Tab);
⋮----
? rows.OrderBy(link => link.ExpiresAt ?? DateTimeOffset.MaxValue).ThenByDescending(link => link.CreatedAt).ToList()
: rows.OrderByDescending(link => link.EndedAt ?? link.ExpiresAt ?? link.CreatedAt).ThenByDescending(link => link.CreatedAt).ToList();
⋮----
public string DisplayNameOf(string name) => Hosts.FirstOrDefault(host => host.Name == name)?.DisplayName ?? name;
⋮----
public sealed class BookingLinkForm
⋮----
public static class Fields
⋮----
public static string Day(DateOnly day) => day.ToString(DayFormat, CultureInfo.InvariantCulture);
⋮----
public static DateOnly? ReadDay(string? value) =>
DateOnly.TryParseExact(value?.Trim(), DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) ? day : null;
⋮----
public string? ReadTitle(string suggestion, IDictionary<string, string> problems, IStringLocalizer<ConsoleResource> text)
⋮----
public bool ReadExpiry(TimeZoneInfo zone, DateOnly today, IDictionary<string, string> problems, IStringLocalizer<ConsoleResource> text, out DateTimeOffset? expiresAt)
⋮----
expiresAt = BookingLink.ExpiresAtFor(day, zone);
⋮----
public string? ProblemOf(string field) => Problems.GetValueOrDefault(field);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/PatternForm.cs">
public sealed class PatternForm
⋮----
public static class Fields
⋮----
public static string Start(int row) => $"start-{row}";
⋮----
public static string End(int row) => $"end-{row}";
⋮----
Enumerable.Range(0, Math.Max(Starts.Count, Ends.Count))
.Select(i => (Starts.ElementAtOrDefault(i), Ends.ElementAtOrDefault(i)))
.ToList();
⋮----
public static PatternForm For(IReadOnlyList<SpanTimes> spans, string week)
⋮----
var form = new PatternForm { Expected = SpanTimes.Invariant(spans), Week = week };
foreach (var span in spans.Order())
⋮----
form.Starts.Add(WindowForm.Time(span.Starts));
form.Ends.Add(WindowForm.Time(span.Ends));
⋮----
return form.Padded();
⋮----
public PatternForm Padded()
⋮----
var rows = Math.Min(Math.Max(Rows.Count(row => !IsBlank(row)) + 2, 2), PatternSpan.MaxPerDay);
⋮----
Starts.Add(null);
⋮----
Ends.Add(null);
⋮----
public (IReadOnlyList<SpanTimes>? Spans, IReadOnlyList<SpanTimes>? Expected, IReadOnlyDictionary<string, string> Problems) Parse(
⋮----
var start = WindowForm.ReadTime(startText);
var end = WindowForm.ReadTime(endText);
⋮----
problems[Fields.Start(i)] = string.IsNullOrWhiteSpace(startText) ? text["Booking.Pattern.Problem.Incomplete"] : text["Booking.Availability.Problem.Time"];
⋮----
problems[Fields.End(i)] = string.IsNullOrWhiteSpace(endText) ? text["Booking.Pattern.Problem.Incomplete"] : text["Booking.Availability.Problem.Time"];
⋮----
var times = new SpanTimes(start.Value, end.Value);
switch (times.Problem())
⋮----
problems[start.Value.Minute % AvailabilityWindow.MinuteStep != 0 ? Fields.Start(i) : Fields.End(i)] =
⋮----
problems[Fields.End(i)] = text["Booking.Availability.Problem.EndNotAfterStart"];
⋮----
problems[Fields.End(i)] = text["Booking.Availability.Problem.TooLong", (int)AvailabilityWindow.MaxLength.TotalHours];
⋮----
spans.Add((i, times));
⋮----
foreach (var (index, other) in SpanTimes.Overlapping(spans.Select(span => span.Times).ToList()))
⋮----
problems[Fields.Start(spans[index].Row)] = text["Booking.Pattern.Problem.Overlap", Times(other)];
⋮----
var expected = SpanTimes.Read(Expected);
⋮----
: (spans.Select(span => span.Times).Order().ToList(), expected, problems);
⋮----
public static string Times(SpanTimes span) => $"{WindowForm.Time(span.Starts)}–{WindowForm.Time(span.Ends)}";
⋮----
public static string? Times(IEnumerable<SpanTimes> spans) =>
spans.Order().Select(Times).ToList() is { Count: > 0 } all ? string.Join(", ", all) : null;
⋮----
private static bool IsBlank((string? Start, string? End) row) =>
string.IsNullOrWhiteSpace(row.Start) && string.IsNullOrWhiteSpace(row.End);
⋮----
public sealed class DayOffForm
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/PublicPages.cs">
public static readonly PublicZone Utc = new(TimeZoneInfo.Utc, "UTC", Given: false);
⋮----
public static readonly PublicZone Default = WindowTimes.Find(TimeZones.Default) is { } rome
? new PublicZone(rome, TimeZones.Default, Given: false)
⋮----
public static PublicZone Parse(string? tz)
⋮----
if (string.IsNullOrEmpty(name))
⋮----
return TimeZones.IsKnown(name) && WindowTimes.Find(name) is { } zone ? new PublicZone(zone, name, Given: true) : Default;
⋮----
public DateOnly DayOf(DateTimeOffset instant) => WindowTimes.DayIn(instant, Zone);
⋮----
public DateTime LocalTime(DateTimeOffset instant) => TimeZoneInfo.ConvertTime(instant, Zone).DateTime;
⋮----
public static class PublicRoutes
⋮----
public static string Day(DateOnly day) => day.ToString(DayFormat, CultureInfo.InvariantCulture);
⋮----
public static string Month(DateOnly firstOfMonth) => firstOfMonth.ToString(MonthFormat, CultureInfo.InvariantCulture);
⋮----
public static (string Day, string Time) Slot(DateTimeOffset start)
⋮----
var utc = start.ToUniversalTime();
return (utc.ToString(DayFormat, CultureInfo.InvariantCulture), utc.ToString(TimeFormat, CultureInfo.InvariantCulture));
⋮----
public static DateOnly? ReadDay(string? value) =>
DateOnly.TryParseExact(value?.Trim(), DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) ? day : null;
⋮----
public static DateOnly? ReadMonth(string? value) =>
DateOnly.TryParseExact(value?.Trim(), MonthFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var first) ? first : null;
⋮----
public static DateTimeOffset? ReadSlot(string? day, string? time)
⋮----
|| !TimeOnly.TryParseExact(time?.Trim(), TimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var at))
⋮----
return new DateTimeOffset(date.ToDateTime(at), TimeSpan.Zero);
⋮----
public static DateTimeOffset? ReadInstant(string? value) =>
DateTimeOffset.TryParseExact(value?.Trim(), "yyyy-MM-dd'T'HH:mm'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var instant)
⋮----
public static class PublicLinks
⋮----
public static string PublicLink(this IUrlHelper url, string action, object values) =>
Readable(url.Action(action, "Public", values) ?? "/book");
⋮----
public static string PublicLink(this IUrlHelper url, string action, HostSet hosts, object? values = null)
⋮----
var route = new RouteValueDictionary(values);
⋮----
return url.Action(LinkAction(action), "Public", route) ?? BookingLink.PathPrefix;
⋮----
return Readable(url.Action(action, "Public", route) ?? "/book");
⋮----
public static string LinkAction(string action) => "Link" + action;
⋮----
public static string Readable(string url)
⋮----
var query = url.IndexOf('?', StringComparison.Ordinal);
⋮----
return path.Replace("%2B", "+", StringComparison.OrdinalIgnoreCase) + (query < 0 ? string.Empty : url[query..]);
⋮----
public sealed class BookingForm
⋮----
public static class Fields
⋮----
public bool IsHoneypotFilled => !string.IsNullOrWhiteSpace(Website);
⋮----
public (GuestDetails? Guest, IReadOnlyDictionary<string, string> Problems) Parse(IStringLocalizer<ConsoleResource> text)
⋮----
else if (!HostForm.IsAddress(email))
⋮----
return problems.Count > 0 ? (null, problems) : (new GuestDetails(name, email, organisation, note), problems);
⋮----
private static string? Blank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
⋮----
public string Slug => string.Join(Separator, Hosts.Select(host => host.Slug));
⋮----
public IReadOnlyList<string> Names => Hosts.Select(host => host.Name).ToList();
⋮----
public int DurationMinutes => Hosts.Max(host => host.DurationMinutes);
⋮----
public int HorizonDays => Hosts.Min(host => host.HorizonDays);
⋮----
public static IReadOnlyList<string>? ReadSlugs(string? value)
⋮----
if (string.IsNullOrEmpty(value))
⋮----
var slugs = value.Split(Separator);
⋮----
|| slugs.Any(slug => !BookingHost.IsSlug(slug))
|| slugs.Distinct(StringComparer.Ordinal).Count() != slugs.Length)
⋮----
public string DisplayNames(IStringLocalizer<ConsoleResource> text) => Join(Hosts.Select(host => host.DisplayName).ToList(), text);
⋮----
public static string Join(IReadOnlyList<string> names, IStringLocalizer<ConsoleResource> text) => names.Count switch
⋮----
_ => text["Booking.Joint.And", string.Join(", ", names.Take(names.Count - 1)), names[^1]].Value,
⋮----
public DateOnly? PreviousMonth => First > FirstMonth ? First.AddMonths(-1) : null;
... (45 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Models/WindowForm.cs">
public sealed class WindowForm
⋮----
public static class Fields
⋮----
public (AvailabilityWindow? Window, IReadOnlyDictionary<string, string> Problems) Parse(
⋮----
var placement = WindowTimes.Place(day.Value, start.Value, end.Value, zone);
⋮----
if (startsAt >= now.AddDays(host.HorizonDays))
⋮----
return (new AvailabilityWindow
⋮----
Id = Guid.NewGuid(),
⋮----
public static DateOnly? ReadDay(string? value) =>
DateOnly.TryParseExact(value?.Trim(), DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) ? day : null;
⋮----
public static TimeOnly? ReadTime(string? value) =>
TimeOnly.TryParseExact(value?.Trim(), [TimeFormat, "HH:mm:ss"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var time) ? time : null;
⋮----
public static string Time(TimeOnly time) => time.ToString(TimeFormat, CultureInfo.InvariantCulture);
⋮----
public static string Date(DateOnly day) => day.ToString(DayFormat, CultureInfo.InvariantCulture);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/ViewComponents/BookingOverviewViewComponent.cs">
public sealed class BookingOverviewViewComponent(
⋮----
ILogger<BookingOverviewViewComponent> logger) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync()
⋮----
if (!(await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.BookingView)).Succeeded)
⋮----
var now = clock.GetUtcNow();
⋮----
var everyone = (await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.BookingConfigure)).Succeeded;
⋮----
hosts = await store.HostsAsync(cancellationToken);
var isHost = hosts.Any(host => host.Name == ConsoleRoles.Normalise(self));
var start = BookingWeek.WeekStart(now);
⋮----
IEnumerable<BookingRecord> inWeek = await store.AllBookingsAsync(start, start.AddDays(7), cancellationToken);
⋮----
// One's own, a joint booking one holds included (#200).
inWeek = inWeek.Where(booking => booking.Holds(self));
hosts = hosts.Where(host => host.Name == ConsoleRoles.Normalise(self)).ToList();
⋮----
var ahead = isHost ? await store.AllBookingsAsync(now, null, cancellationToken) : [];
week = BookingWeek.Compute(inWeek, ahead, self, isHost, now);
⋮----
// One's own count alone: a joint booking's colleagues are not counted on one's own card (#193).
week = week with { PerHost = week.PerHost.Where(count => count.Host == ConsoleRoles.Normalise(self)).ToList() };
⋮----
logger.LogError(ex, "The overview could not read the bookings.");
⋮----
return View(ViewPath, new BookingOverview(store.Storage, week, hosts, everyone));
⋮----
/// <summary>The overview's Bookings card. <see cref="Week"/> is null when the store could not be read.</summary>
⋮----
public string DisplayNameOf(string name) => Hosts.FirstOrDefault(host => host.Name == name)?.DisplayName ?? name;
⋮----
public static TimeZoneInfo ZoneOf(BookingRecord booking) => WindowTimes.Find(booking.HostTimeZone) ?? TimeZoneInfo.Utc;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Availability/Picker.cshtml">
@model AvailabilityPicker

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Availability.Title"]</h5>
        <p class="text-body mb-0">@T["Booking.Availability.Intro"]</p>
        @if (Model.SelfIsPerson)
        {
            <p class="text-body mt-2 mb-0" id="availability-not-a-host">@(Model.MayConfigure ? T["Booking.Availability.NotAHost.Configure"] : T["Booking.Availability.NotAHost"])</p>
        }
    </div>
</div>

@if (Model.Storage == BookingStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">@T["Booking.Hosts.NoDatabase"]</div>
}
else if (Model.Storage == BookingStorage.Ephemeral)
{
    <div class="alert alert-secondary" role="status">@T["Booking.Availability.Ephemeral"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-danger" role="alert">@T["Booking.Availability.Unreadable"]</div>
}

@* Every host to pick from is an Administrator's alone (#193). *@
@if (Model.MayConfigure)
{
    <div class="card" id="availability-picker">
        <div class="card-header">
            <h6 class="card-title mb-0">@T["Booking.Availability.Picker.Title"]</h6>
        </div>

        @if (Model.Hosts.Count == 0)
        {
            <div class="card-body">
                <p class="text-body mb-0" id="availability-no-hosts">@T["Booking.Home.NoHosts"]</p>
                @if (Model.MayConfigure)
                {
                    <a asp-controller="Hosts" asp-action="Index" class="btn btn-sm btn-primary mt-3">@T["Menu.Booking.Hosts"]</a>
                }
            </div>
        }
        else
        {
            <div class="list-group list-group-flush">
                @foreach (var host in Model.Hosts)
                {
                    <a asp-action="Week" asp-route-host="@host.Name" class="list-group-item list-group-item-action d-flex flex-wrap align-items-center gap-2" id="pick-@host.Name">
                        <span class="fw-medium">@host.DisplayName</span>
                        <span class="text-body small">@host.Name</span>
                        <span class="text-body small ms-auto">@host.TimeZone</span>
                        @if (!host.Enabled)
                        {
                            <span class="badge bg-label-warning">@T["Booking.Hosts.State.Disabled"]</span>
                        }
                    </a>
                }
            </div>
        }
    </div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Availability/Week.cshtml">
@model AvailabilityPage
@using System.Globalization
@using Microsoft.Extensions.Options
@inject IOptions<BookingOptions> BookingSettings
@inject ZohoCalendarClient Zoho
@{
    var host = Model.Host;
    var culture = CultureInfo.CurrentCulture;
    string Day(DateOnly day) => day.ToString("dddd d MMMM", culture);
    string Range() => $"{Model.Monday.ToString("d MMMM", culture)} – {Model.Sunday.ToString("d MMMM yyyy", culture)}";
    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";
    string PatternInvalid(string field) => Model.PatternProblems.ContainsKey(field) ? " is-invalid" : "";
    string Weekday(int weekday) => culture.DateTimeFormat.GetDayName(Weekdays.DayOfWeek(weekday));
    string Spans(IEnumerable<SpanTimes> spans) => PatternForm.Times(spans) ?? S["Booking.Pattern.None"];
    var form = Model.Form;
    var rules = Model.Rules;
    var zone = Model.Zone;
    string Since(DateTimeOffset instant)
    {
        var local = TimeZoneInfo.ConvertTime(instant, zone);
        var time = local.ToString("HH:mm", CultureInfo.InvariantCulture);
        return DateOnly.FromDateTime(local.DateTime) == Model.Today ? time : local.ToString("d MMMM", culture) + " " + time;
    }
    string Labels(IEnumerable<FeedState> feeds) => string.Join(", ", feeds.Select(feed => $"“{feed.Feed.Label}”"));
}

<div class="card mb-4">
    <div class="card-body d-flex flex-wrap align-items-start gap-3">
        <div class="flex-grow-1">
            <h5 class="card-title mb-1">@T["Booking.Availability.Week.Title", host.DisplayName]</h5>
            <p class="small text-body mb-2">
                <span class="me-2">@host.Name</span>
                <span class="badge bg-label-secondary" id="availability-zone">@host.TimeZone</span>
                @if (!host.Enabled)
                {
                    <span class="badge bg-label-warning ms-1">@T["Booking.Hosts.State.Disabled"]</span>
                }
            </p>
            <p class="text-body mb-0" id="availability-rules">@T["Booking.Availability.Rules", rules.DurationMinutes, rules.StepMinutes, rules.NoticeHours, rules.BufferMinutes, rules.HorizonDays]</p>
            @if (!Model.MayChange)
            {
                <p class="text-body mt-2 mb-0" id="availability-read-only">@T["Booking.Availability.ReadOnly", host.DisplayName]</p>
            }
        </div>

        <div class="d-flex flex-wrap gap-2">
            @if (Model.Hosts.Count > 1)
            {
                <div class="dropdown">
                    <button type="button" class="btn btn-sm btn-label-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                        @T["Booking.Availability.Picker.Other"]
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" id="availability-hosts">
                        @foreach (var other in Model.Hosts)
                        {
                            <li>
                                <a class="dropdown-item@(other.Name == host.Name ? " active" : "")" asp-action="Week" asp-route-host="@other.Name">@other.DisplayName <span class="small text-body">@other.Name</span></a>
                            </li>
                        }
                    </ul>
                </div>
            }
            @* A host's settings: anyone's to an Administrator, one's own to its host under booking:write (#193). *@
            @if (Model.MayConfigure || Model.MayChange)
            {
                <a asp-controller="Hosts" asp-action="Edit" asp-route-name="@host.Name" class="btn btn-sm btn-label-primary" id="availability-settings">@T["Booking.Availability.Settings"]</a>
            }
        </div>
    </div>
</div>

@* The host's link, to be shared: the week is where a host says when they can be booked. *@
@* With, since #201, the host's open booking links and Make a link with colleagues, by the week's own rule for changing it. *@
<partial name="_BookingLink" model="new BookingLinkCard(host, BookingSettings.Value.LinkFor(host.Slug), ConsoleRoles.Normalise(User.Identity?.Name ?? string.Empty) == host.Name, Zoho.IsConfigured) { OpenLinks = Model.OpenLinks, MayMakeLink = Model.MayChange || Model.MayConfigure, TeamLink = BookingSettings.Value.TeamLink }" />

@* The host's calendars (#199): which hide slots, and a line for each that does not now (decision 8). *@
@if (Model.Calendars.Feeds.Count > 0)
{
    <div id="availability-calendars" class="mb-4">
        @if (!Model.CalendarsServed)
        {
            <div class="alert alert-secondary mb-2" role="status" id="calendars-not-read">@T["Booking.Feed.Week.NotRead"]</div>
        }
        else
        {
            @foreach (var state in Model.Calendars.NotHiding)
            {
                <div class="alert alert-warning mb-2" role="status" id="calendar-not-hiding-@state.Feed.Id">
                    @if (state.Outcome == FeedOutcome.Unprotectable)
                    {
                        @T["Booking.Feed.Week.Unprotectable", state.Feed.Label]
                    }
                    else if (state.LastGoodAt is { } lastGood)
                    {
                        @T["Booking.Feed.Week.Stale", state.Feed.Label, Since(lastGood)]
                    }
                    else
                    {
                        @T["Booking.Feed.Week.Never", state.Feed.Label]
                    }
... (413 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Bookings/_Summary.cshtml">
@model BookingPage
@using System.Globalization
@{
    var booking = Model.Booking;
    var culture = CultureInfo.CurrentCulture;
    string When(DateTime start, DateTime end) =>
        $"{start.ToString("dddd d MMMM yyyy", culture)}, {start.ToString("HH:mm", CultureInfo.InvariantCulture)}–{end.ToString("HH:mm", CultureInfo.InvariantCulture)}";
}

<dl class="row mb-0">
    <dt class="col-5 col-md-3">@T["Booking.Detail.When"]</dt>
    <dd class="col-7 col-md-9" id="booking-when" title="@BookingRecord.Instant(booking.StartsAt)">
        @When(Model.HostStart, Model.HostEnd) <span class="small text-body">(@booking.HostTimeZone)</span>
        @if (Model.GuestTimes is { } guest)
        {
            <div class="small text-body" id="booking-when-guest">@T["Booking.Detail.ForGuest"] @When(guest.Start, guest.End) (@Model.GuestZone)</div>
        }
        else
        {
            <div class="small text-body" id="booking-when-guest">@T["Booking.Detail.ForGuest"] @Model.GuestZone</div>
        }
    </dd>
    @if (booking.IsJoint)
    {
        @* Every host of a joint booking, in its order, the lead marked (#200). *@
        <dt class="col-5 col-md-3">@T["Booking.Joint.Hosts"]</dt>
        <dd class="col-7 col-md-9">
            <ul class="list-unstyled mb-0" id="booking-hosts">
                @foreach (var name in booking.Hosts)
                {
                    <li data-booking-host="@name">
                        @Model.DisplayNameOf(name) <span class="small text-body">@name</span>
                        @if (name == booking.HostName)
                        {
                            <span class="badge bg-label-primary ms-1" id="booking-lead">@T["Booking.Joint.LeadBadge"]</span>
                        }
                    </li>
                }
            </ul>
        </dd>
    }
    else
    {
        <dt class="col-5 col-md-3">@T["Booking.Detail.Host"]</dt>
        <dd class="col-7 col-md-9">@Model.DisplayNameOf(booking.HostName) <span class="small text-body">@booking.HostName</span></dd>
    }
    @if (Model.LinkTitle is { } linkTitle)
    {
        @* Booked through a host's link (#201): its title as it stands now. *@
        <dt class="col-5 col-md-3">@T["Booking.Links.Detail.Through"]</dt>
        <dd class="col-7 col-md-9" id="booking-link">@T["Booking.Links.From", linkTitle]</dd>
    }
    <dt class="col-5 col-md-3">@T["Booking.Detail.Guest"]</dt>
    <dd class="col-7 col-md-9" id="booking-guest">@booking.GuestName</dd>
    <dt class="col-5 col-md-3">@T["Booking.Detail.Email"]</dt>
    <dd class="col-7 col-md-9" id="booking-guest-email"><a href="mailto:@booking.GuestEmail">@booking.GuestEmail</a></dd>
    <dt class="col-5 col-md-3">@T["Booking.Detail.Organisation"]</dt>
    <dd class="col-7 col-md-9" id="booking-guest-organisation">@(booking.GuestOrganisation ?? "-")</dd>
    <dt class="col-5 col-md-3">@T["Booking.Detail.Note"]</dt>
    <dd class="col-7 col-md-9" id="booking-guest-note" style="white-space: pre-line">@(booking.GuestNote ?? "-")</dd>
    <dt class="col-5 col-md-3">@T["Booking.Detail.Language"]</dt>
    <dd class="col-7 col-md-9" id="booking-guest-language" data-culture="@booking.GuestCulture">@(Model.GuestLanguageKey is { } language ? T[language] : booking.GuestCulture)</dd>
</dl>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Bookings/Cancel.cshtml">
@model BookingCancelPage
@{
    var page = Model.Booking;
    var booking = page.Booking;
}

<div class="mb-4">
    <a asp-action="Show" asp-route-id="@booking.Id" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Detail.Back"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Cancel.Title", page.HostDisplayName]</h5>
        <p class="mb-0">@T[booking.Invitation == InvitationState.Sent ? "Booking.Cancel.Lead" : "Booking.Cancel.LeadNoEvent"]</p>
    </div>
</div>

@if (Model.Conflict)
{
    <div class="alert alert-danger" role="alert" id="booking-conflict">@T["Booking.Cancel.Conflict"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="booking-cancel-problem">@problem</div>
}

<div class="card">
    <div class="card-body">
        <partial name="_Summary" model="page" />
    </div>
    @if (booking.IsLive)
    {
        <form method="post" asp-action="Cancel" asp-route-id="@booking.Id" class="card-footer" novalidate>
            <input type="hidden" name="version" value="@booking.Version" />
            <div class="mb-3">
                <label for="cancel-reason" class="form-label">@T["Booking.Cancel.Reason"]</label>
                <textarea id="cancel-reason" name="reason" class="form-control@(Model.Problem is null || Model.Conflict ? "" : " is-invalid")" rows="3" maxlength="@BookingRecord.CancelReasonLength" required>@Model.Reason</textarea>
                <div class="form-text">@T["Booking.Cancel.ReasonHint", BookingRecord.CancelReasonLength]</div>
            </div>
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-danger" id="confirm-cancel">@T["Booking.Cancel.Confirm"]</button>
                <a asp-action="Show" asp-route-id="@booking.Id" class="btn btn-label-secondary">@T["Booking.Cancel.Keep"]</a>
            </div>
        </form>
    }
    else
    {
        <div class="card-footer">
            <a asp-action="Show" asp-route-id="@booking.Id" class="btn btn-label-secondary">@T["Booking.Detail.Back"]</a>
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Bookings/Index.cshtml">
@model BookingListPage
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Crm.Models
@using Microsoft.Extensions.Options
@inject IOptions<BookingOptions> BookingSettings
@{
    var query = Model.Query;
    var count = Model.Rows.Count;
    var culture = CultureInfo.CurrentCulture;

    // Each link keeps what the others chose: a tab keeps whose and the host, Mine and Everyone's keep the tab.
    Dictionary<string, string> Route(BookingTab tab, bool mine, string? host)
    {
        var route = new Dictionary<string, string>
        {
            ["tab"] = BookingListQuery.Word(tab),
            ["who"] = mine ? BookingListQuery.MineWord : BookingListQuery.EveryoneWord,
        };
        if (!mine && host is not null)
        {
            route["host"] = host;
        }
        return route;
    }

    var tabs = new[]
    {
        (BookingTab.Upcoming, "Booking.List.Tab.Upcoming"),
        (BookingTab.Past, "Booking.List.Tab.Past"),
        (BookingTab.Cancelled, "Booking.List.Tab.Cancelled"),
    };

    var hostKnown = query.Host is null || Model.Hosts.Any(host => host.Name == query.Host);

    var (orderKey, emptyKey) = query.Tab switch
    {
        BookingTab.Past => ("Booking.List.Order.Past", "Booking.List.Empty.Past"),
        BookingTab.Cancelled => ("Booking.List.Order.Cancelled", "Booking.List.Empty.Cancelled"),
        _ => ("Booking.List.Order.Upcoming", "Booking.List.Empty.Upcoming"),
    };
}
@*
    The bookings (#176): the store's range read, filtered by tab and host, a row each. Nothing here is
    edited in place, since nothing on a booking is edited: DataTables orders the rows and holds the
    header, as on the CRM's grids, and each row's actions are #175's, offered by its rule.
*@

@section PageStyles {
    <link rel="stylesheet" href="~/vendor/libs/datatables-bs5/datatables.bootstrap5.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/vendor/libs/datatables-fixedheader-bs5/fixedheader.bootstrap5.css" asp-append-version="true" />
}

@section PageScripts {
    <script src="~/vendor/libs/datatables-bs5/datatables-bootstrap5.js" asp-append-version="true"></script>
    <script src="~/vendor/libs/datatables-fixedheader-bs5/fixedheader-bootstrap5.js" asp-append-version="true"></script>
    <script src="~/js/booking-list.js" asp-append-version="true"></script>
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card" id="booking-area">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Booking.List.Title"]</h5>
                <p class="text-body mb-3">@T["Booking.Home.Intro"]</p>
                <div class="d-flex flex-wrap gap-4 small">
                    @* How many hosts there are is an Administrator's to see, as the list of them is (#193). *@
                    @if (Model.MayConfigure)
                    {
                        <div id="booking-hosts-summary">
                            @if (Model.Unreadable)
                            {
                                <span>@T["Booking.Home.HostsUnreadable"]</span>
                            }
                            else if (Model.Hosts.Count == 0)
                            {
                                <span>@T["Booking.Home.NoHosts"]</span>
                            }
                            else
                            {
                                <span>@(Model.Hosts.Count == 1 ? T["Booking.Home.HostsCount.One"] : T["Booking.Home.HostsCount.Many", Model.Hosts.Count]) @(Model.Enabled == 1 ? T["Booking.Home.EnabledCount.One"] : T["Booking.Home.EnabledCount.Many", Model.Enabled])</span>
                            }
                            <a asp-controller="Hosts" asp-action="Index" class="ms-1">@T["Menu.Booking.Hosts"]</a>
                        </div>
                    }
                    <div id="booking-zoho-summary">
                        @if (Model.ZohoConfigured)
                        {
                            <span id="zoho-configured">@T["Booking.Home.Zoho.Configured"]</span>
                        }
                        else
                        {
                            <span id="zoho-not-configured" class="text-warning">@T["Booking.Home.Zoho.NotConfigured"]</span>
                        }
                        @if (Model.MayConfigure)
                        {
                            <a asp-controller="Hosts" asp-action="Index" asp-fragment="zoho-calendar" class="ms-1">@T["Booking.Home.Zoho.Check"]</a>
                        }
                    </div>
                </div>
            </div>
... (168 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Bookings/Show.cshtml">
@model BookingPage
@{
    var booking = Model.Booking;
    // The week the link opens: the signed-in host's own when the booking is theirs, the lead's otherwise (#200).
    var self = ConsoleRoles.Normalise(User.Identity?.Name ?? string.Empty);
    var weekHost = booking.Holds(self) ? self : booking.HostName;
    var (stateClass, stateKey) = booking.Invitation switch
    {
        InvitationState.Sent => ("bg-label-success", "Booking.Invitation.State.Sent"),
        InvitationState.Cancelled => ("bg-label-secondary", "Booking.Invitation.State.Cancelled"),
        InvitationState.CancelFailed => ("bg-label-danger", "Booking.Invitation.State.CancelFailed"),
        _ => ("bg-label-warning", "Booking.Invitation.State.NotSent"),
    };
}

<div class="mb-4 d-flex flex-wrap gap-4">
    <a asp-action="Index" asp-route-tab="@BookingListQuery.Word(Model.ListTab)" class="text-body" id="booking-list-link">
        <i class="ti ti-arrow-left me-1"></i>@T["Booking.Detail.List"]
    </a>
    <a asp-controller="Availability" asp-action="Week" asp-route-host="@weekHost" asp-route-week="@WindowForm.Date(DateOnly.FromDateTime(Model.HostStart))" class="text-body" id="booking-week">
        <i class="ti ti-calendar-week me-1"></i>@T["Booking.Detail.Week"]
    </a>
</div>

@if (Model.Notice is { } notice)
{
    <div class="alert @(notice == BookingNotice.CancelFailed ? "alert-warning" : "alert-success")" role="status" id="booking-notice" data-notice="@notice">@T[BookingNotice.KeyOf(notice)]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="booking-problem">@problem</div>
}

<div class="card mb-4" id="booking" data-status="@booking.Status" data-invitation="@booking.Invitation">
    <div class="card-header d-flex flex-wrap align-items-center gap-2">
        <h5 class="card-title mb-0 me-auto">@T["Booking.Detail.Title", Model.HostDisplayName]</h5>
        @if (booking.IsLive)
        {
            <span class="badge bg-label-primary" id="booking-status">@T["Booking.Status.Booked"]</span>
        }
        else
        {
            <span class="badge bg-label-secondary" id="booking-status">@T[booking.Status == BookingStatus.CancelledByGuest ? "Booking.Status.CancelledByGuest" : "Booking.Status.CancelledByHost"]</span>
        }
    </div>
    <div class="card-body">
        <partial name="_Summary" model="Model" />

        <hr class="my-3" />

        <dl class="row mb-0">
            <dt class="col-5 col-md-3">@T["Booking.Invitation.Label"]</dt>
            <dd class="col-7 col-md-9">
                <span class="badge @stateClass" id="booking-invitation">@T[stateKey]</span>
                @if (booking.ZohoEventUid is { } uid && booking.Invitation != InvitationState.NotSent)
                {
                    <div class="small text-body mt-1" id="booking-event-uid">@T["Booking.Detail.EventUid"] <code>@uid</code></div>
                }
            </dd>
            @if (!booking.IsLive)
            {
                <dt class="col-5 col-md-3">@T["Booking.Cancel.Reason"]</dt>
                <dd class="col-7 col-md-9" id="booking-cancel-reason" style="white-space: pre-line">@(booking.CancelReason ?? "-")</dd>
                @if (booking.CancelledAt is { } at)
                {
                    <dt class="col-5 col-md-3">@T["Booking.Cancel.ByLabel"]</dt>
                    <dd class="col-7 col-md-9" id="booking-cancelled-by">@(booking.Status == BookingStatus.CancelledByGuest ? S["Booking.Cancel.ByTheGuest"].Value : booking.CancelledBy), @(at.UtcDateTime.ToString("yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture)) UTC</dd>
                }
            }
        </dl>

        @if (booking.Invitation == InvitationState.CancelFailed)
        {
            <div class="alert alert-warning mt-3 mb-0" role="alert" id="booking-cancel-by-hand">@T["Booking.Invitation.CancelByHand", booking.ZohoEventUid ?? "-"]</div>
        }
        else if (booking.IsLive && booking.Invitation == InvitationState.NotSent)
        {
            <p class="small text-body mt-3 mb-0" id="booking-not-sent">@T["Booking.Invitation.NotSentHint"]</p>
        }
    </div>
    @if (Model.OffersResend || Model.OffersCancel)
    {
        <div class="card-footer d-flex flex-wrap gap-2">
            @if (Model.OffersResend)
            {
                <form method="post" asp-action="Resend" asp-route-id="@booking.Id">
                    <button type="submit" class="btn btn-primary" id="booking-resend"><i class="ti ti-send me-1"></i>@T["Booking.Invitation.Resend"]</button>
                </form>
            }
            @if (Model.OffersCancel)
            {
                <a asp-action="Cancel" asp-route-id="@booking.Id" class="btn btn-label-danger" id="booking-cancel">@T["Booking.Cancel.Button"]</a>
            }
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Hosts/_Calendars.cshtml">
@model HostEditPage
@using System.Globalization
@{
    // A host's calendar feeds (#199): each by its label and hint, never its address, with how it was
    // last read; Read now, a remove behind a confirm step, and Add a calendar with where each provider
    // keeps its secret address, folded away until asked for.
    var host = Model.Current!;
    var calendars = Model.Calendars!;
    var key = host.Name;
    var zone = WindowTimes.Find(host.TimeZone) ?? TimeZoneInfo.Utc;
    var culture = CultureInfo.CurrentCulture;
    string When(DateTimeOffset instant)
    {
        var local = TimeZoneInfo.ConvertTime(instant, zone);
        return local.ToString("d MMM", culture) + " " + local.ToString("HH:mm", CultureInfo.InvariantCulture);
    }
    string Invalid(string field) => Model.FeedProblemOf(field) is null ? "" : " is-invalid";
    string Outcome(FeedOutcome outcome) => S["Booking.Feed.Outcome." + outcome];

    // Each provider, most used first: its title, its numbered steps, a note, and how a leaked address
    // is withdrawn. Any other provider is the accordion's last item, a paragraph of its own.
    (string Id, string Title, string[] Steps, string Note, string Reset)[] providers =
    [
        ("google", S["Booking.Feed.Help.Google.Title"], [S["Booking.Feed.Help.Google.Step1"], S["Booking.Feed.Help.Google.Step2"]], S["Booking.Feed.Help.Google.Note"], S["Booking.Feed.Help.Google.Reset"]),
        ("outlook", S["Booking.Feed.Help.Outlook.Title"], [S["Booking.Feed.Help.Outlook.Step1"], S["Booking.Feed.Help.Outlook.Step2"], S["Booking.Feed.Help.Outlook.Step3"]], S["Booking.Feed.Help.Outlook.Note"], S["Booking.Feed.Help.Outlook.Reset"]),
        ("icloud", S["Booking.Feed.Help.ICloud.Title"], [S["Booking.Feed.Help.ICloud.Step1"], S["Booking.Feed.Help.ICloud.Step2"], S["Booking.Feed.Help.ICloud.Step3"]], S["Booking.Feed.Help.ICloud.Note"], S["Booking.Feed.Help.ICloud.Reset"]),
        ("zoho", S["Booking.Feed.Help.Zoho.Title"], [S["Booking.Feed.Help.Zoho.Step1"], S["Booking.Feed.Help.Zoho.Step2"]], S["Booking.Feed.Help.Zoho.Note"], S["Booking.Feed.Help.Zoho.Reset"]),
    ];
    var helpOpen = Model.FeedProblemOf(FeedForm.Fields.Address) is not null;
}

<div class="card mt-4" id="calendars">
    <div class="card-header d-flex flex-wrap align-items-start gap-2">
        <div class="flex-grow-1">
            <h5 class="card-title mb-1">@T["Booking.Feed.Title"]</h5>
            <p class="small text-body mb-0">@T["Booking.Feed.Lead"]</p>
        </div>
        @if (calendars.Feeds.Count > 0 && Model.CanChange)
        {
            <form method="post" asp-action="ReadCalendars" asp-route-name="@key" id="calendars-read">
                <button type="submit" class="btn btn-sm btn-label-primary" title="@S["Booking.Feed.ReadNow.Hint"]">
                    <i class="ti ti-refresh me-1"></i>@T["Booking.Feed.ReadNow"]
                </button>
            </form>
        }
    </div>

    <div class="card-body">
        @if (Model.FeedNotice is { } notice)
        {
            <div class="alert @(Model.FeedNoticeWarns ? "alert-warning" : "alert-success")" role="status" id="calendars-notice">@notice</div>
        }

        @if (!Model.CalendarsServed && calendars.Feeds.Count > 0)
        {
            <div class="alert alert-secondary" role="status" id="calendars-not-read">@T["Booking.Feed.NotRead"]</div>
        }

        @if (calendars.Feeds.Count == 0)
        {
            <p class="text-body" id="calendars-none">@T["Booking.Feed.None"]</p>
        }
        else
        {
            @* Relative, so the hidden header's label scrolls with the table rather than widening the page. *@
            <div class="table-responsive position-relative mb-3">
                <table class="table table-sm align-middle mb-0" id="calendars-list">
                    <thead>
                        <tr>
                            <th>@T["Booking.Feed.Column.Label"]</th>
                            <th>@T["Booking.Feed.Column.Address"]</th>
                            <th>@T["Booking.Feed.Column.LastRead"]</th>
                            <th class="text-end">@T["Booking.Feed.Column.Busy", host.HorizonDays]</th>
                            <th><span class="visually-hidden">@T["Booking.Feed.Remove"]</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var state in calendars.Feeds)
                        {
                            var feed = state.Feed;
                            <tr id="calendar-@feed.Id" data-outcome="@state.Outcome" data-hiding="@(state.Hiding ? "true" : "false")">
                                <td class="fw-medium">@feed.Label</td>
                                <td><code class="text-break">@feed.UrlHint</code></td>
                                <td>
                                    @if (state.LastReadAt is { } read && state.Outcome is { } outcome)
                                    {
                                        <span title="@read.UtcDateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) UTC">@When(read)</span>
                                        <span class="badge @(outcome == FeedOutcome.Read ? "bg-label-success" : "bg-label-warning") ms-1">@Outcome(outcome)</span>
                                    }
                                    else
                                    {
                                        <span class="text-body">@T["Booking.Feed.NeverRead"]</span>
                                    }
                                </td>
                                <td class="text-end">@(feed.LastBusyCount?.ToString(CultureInfo.InvariantCulture) ?? "–")</td>
                                <td class="text-end">
                                    @if (Model.CanChange)
                                    {
                                        <a asp-action="RemoveCalendar" asp-route-name="@key" asp-route-id="@feed.Id" class="btn btn-sm btn-text-danger">@T["Booking.Feed.Remove"]</a>
                                    }
... (107 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Hosts/Edit.cshtml">
@model HostEditPage
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var form = Model.Form;
    var key = ConsoleRoles.Normalise(Model.Name);

    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";

    string FieldName(string field) => field switch
    {
        BookingHost.Fields.DisplayName => S["Booking.Host.Field.DisplayName"],
        BookingHost.Fields.Email => S["Booking.Host.Field.Email"],
        BookingHost.Fields.TimeZone => S["Booking.Host.Field.TimeZone"],
        BookingHost.Fields.Slug => S["Booking.Host.Field.Slug"],
        BookingHost.Fields.Duration => S["Booking.Host.Field.Duration"],
        BookingHost.Fields.Step => S["Booking.Host.Field.Step"],
        BookingHost.Fields.Notice => S["Booking.Host.Field.Notice"],
        BookingHost.Fields.Horizon => S["Booking.Host.Field.Horizon"],
        BookingHost.Fields.Buffer => S["Booking.Host.Field.Buffer"],
        BookingHost.Fields.Location => S["Booking.Host.Field.Location"],
        BookingHost.Fields.Listed => S["Booking.Host.Field.Listed"],
        _ => S["Booking.Host.Field.Enabled"],
    };
}

@section PageScripts {
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
}

<div class="mb-4">
    @* Back to the list for an Administrator; to one's own week for a host on their own form (#193). *@
    @if (Model.MayConfigure)
    {
        <a asp-action="Index" class="text-body" id="host-back"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Hosts.Title"]</a>
    }
    else
    {
        <a asp-controller="Availability" asp-action="Week" asp-route-host="@key" class="text-body" id="host-back"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Availability.Title"]</a>
    }
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@(Model.IsNew ? T["Booking.Host.New.Title", Model.Name] : T["Booking.Host.Edit.Title", Model.Name])</h5>
        <p class="text-body mb-0">@(Model.IsNew ? T["Booking.Host.New.Lead"] : T["Booking.Host.Edit.Lead"])</p>
        @if (Model.Current is { } current)
        {
            <p class="small text-body mt-2 mb-0">@T["Booking.Host.LastChanged", current.UpdatedBy, Instant(current.UpdatedAt)]</p>
        }
        @if (!Model.HasRole && !Model.IsNew)
        {
            <div class="alert alert-warning mt-3 mb-0" role="status" id="host-no-role">@T["Booking.Host.NoRole", Model.Name]</div>
        }
    </div>
</div>

@if (Model.Conflict is { } conflict)
{
    <div class="alert alert-danger" role="alert" id="host-conflict">
        <h6 class="alert-heading mb-1">@T["Booking.Host.Conflict.Title"]</h6>
        <p class="mb-1">@T["Booking.Host.Conflict", conflict.UpdatedBy, Instant(conflict.UpdatedAt)]</p>
        @if (Model.Lost is { Count: > 0 } lost)
        {
            <p class="mb-0">@T["Booking.Host.Conflict.Lost", string.Join(", ", lost.Select(FieldName))]</p>
        }
    </div>
}

@if (Model.Removed)
{
    <div class="alert alert-danger" role="alert" id="host-removed">@T["Booking.Host.Removed", Model.Name]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

@if (Model.Problems.Count > 0)
{
    <div class="alert alert-danger" role="alert" id="host-problems">@T["Booking.Host.Problems"]</div>
}

<form method="post" asp-action="Edit" asp-route-name="@key" class="card" novalidate>
    <input type="hidden" name="Version" value="@form.Version" />

    <div class="card-body">
        <div class="row g-4">
            <div class="col-12 col-md-6">
                <label class="form-label" for="host-display-name">@T["Booking.Host.Field.DisplayName"]</label>
                <input class="form-control@(Invalid(BookingHost.Fields.DisplayName))" id="host-display-name" name="DisplayName" value="@form.DisplayName"
                       maxlength="@BookingHost.DisplayNameLength" required />
                <div class="form-text">@T["Booking.Host.Hint.DisplayName"]</div>
                <div class="invalid-feedback">@Model.ProblemOf(BookingHost.Fields.DisplayName)</div>
            </div>

            <div class="col-12 col-md-6">
                <label class="form-label" for="host-email">@T["Booking.Host.Field.Email"]</label>
                <input type="email" class="form-control@(Invalid(BookingHost.Fields.Email))" id="host-email" name="Email" value="@form.Email"
... (142 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Hosts/Index.cshtml">
@model HostsPage

@section PageScripts {
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-controller="Bookings" asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Home.Title"]</a>
</div>

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Booking.Hosts.Title"]</h5>
                <p class="text-body mb-2">@T["Booking.Hosts.Intro"]</p>
                <p class="text-body mb-0">@T["Booking.Hosts.LinkAnswers"]</p>
            </div>
        </div>
    </div>
</div>

@if (Model.Storage == BookingStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">@T["Booking.Hosts.NoDatabase"]</div>
}
else if (Model.Storage == BookingStorage.Ephemeral)
{
    <div class="alert alert-secondary" role="status">@T["Booking.Hosts.Ephemeral"]</div>
}

@if (Model.PeopleUnreadable)
{
    <div class="alert alert-warning" role="alert">@T["Booking.Hosts.PeopleUnreadable"]</div>
}

<div class="card">
    <div class="card-header">
        <h6 class="card-title mb-0">@T["Booking.Hosts.Count", Model.Bookable, Model.Rows.Count]</h6>
    </div>

    @if (Model.Rows.Count == 0)
    {
        <div class="card-body">
            <p class="text-body mb-0" id="no-people">@T["Booking.Hosts.NoPeople"]</p>
        </div>
    }
    else
    {
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>@T["Booking.Hosts.Column.Name"]</th>
                        <th>@T["Booking.Hosts.Column.State"]</th>
                        <th>@T["Booking.Host.Field.DisplayName"]</th>
                        <th>@T["Booking.Host.Field.Slug"]</th>
                        <th>@T["Booking.Host.Field.Duration"]</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var row in Model.Rows)
                    {
                        var host = row.Host;
                        <tr id="host-@row.Key">
                            <td class="fw-medium">@row.Name</td>
                            <td>
                                @if (host is null)
                                {
                                    <span class="badge bg-label-secondary">@T["Booking.Hosts.State.NotBookable"]</span>
                                }
                                else if (host.Enabled)
                                {
                                    <span class="badge bg-label-success">@T["Booking.Hosts.State.Enabled"]</span>
                                }
                                else
                                {
                                    <span class="badge bg-label-warning">@T["Booking.Hosts.State.Disabled"]</span>
                                }

                                @if (!row.HasRole)
                                {
                                    <span class="badge bg-label-danger" title="@S["Booking.Hosts.State.NoRole.Hint"]">@T["Booking.Hosts.State.NoRole"]</span>
                                }
                            </td>
                            @if (host is null)
                            {
                                <td colspan="3" class="text-body">-</td>
                                <td class="text-end">
                                    @if (Model.CanChange && row.HasRole)
                                    {
                                        <a asp-action="Edit" asp-route-name="@row.Key" class="btn btn-sm btn-primary text-nowrap">@T["Booking.Hosts.MakeBookable"]</a>
                                    }
                                </td>
                            }
                            else
                            {
                                var link = Model.Options.LinkFor(host.Slug);
                                <td>
... (93 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Hosts/Remove.cshtml">
@model HostRemovePage
@{
    var host = Model.Host;
    var key = ConsoleRoles.Normalise(Model.Name);
}

<div class="mb-4">
    <a asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Hosts.Title"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Host.Remove.Title", Model.Name]</h5>
        <p class="mb-0">@T["Booking.Host.Remove.Lead"]</p>
    </div>
</div>

@if (Model.Conflict)
{
    <div class="alert alert-danger" role="alert" id="host-conflict">
        <h6 class="alert-heading mb-1">@T["Booking.Host.Conflict.Title"]</h6>
        <p class="mb-0">@T["Booking.Host.Remove.Conflict", host.UpdatedBy, host.UpdatedAt.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC"]</p>
    </div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

@if (Model.HasBookings)
{
    <div class="alert alert-warning" role="alert" id="host-has-bookings">@T["Booking.Host.Remove.HasBookings", Model.Name]</div>
}
else if (Model.OnLinks)
{
    <div class="alert alert-warning" role="alert" id="host-on-links">@T["Booking.Host.Remove.OnLinks", Model.Name]</div>
}

<div class="card">
    <div class="card-body">
        <dl class="row mb-0">
            <dt class="col-5 col-md-3">@T["Booking.Host.Field.DisplayName"]</dt>
            <dd class="col-7 col-md-9">@host.DisplayName</dd>
            <dt class="col-5 col-md-3">@T["Booking.Host.Field.Slug"]</dt>
            <dd class="col-7 col-md-9"><code>@host.Slug</code></dd>
            <dt class="col-5 col-md-3">@T["Booking.Hosts.Column.State"]</dt>
            <dd class="col-7 col-md-9">@(host.Enabled ? T["Booking.Hosts.State.Enabled"] : T["Booking.Hosts.State.Disabled"])</dd>
        </dl>
    </div>
    <div class="card-footer">
        <form method="post" asp-action="Remove" asp-route-name="@key" class="d-flex gap-2">
            <input type="hidden" name="version" value="@host.Version" />
            @if (Model.Kept)
            {
                <a asp-action="Edit" asp-route-name="@key" class="btn btn-primary" id="disable-instead">@T["Booking.Host.Remove.DisableInstead"]</a>
            }
            else
            {
                <button type="submit" class="btn btn-danger" id="confirm-remove">@T["Booking.Host.Remove.Confirm"]</button>
            }
            <a asp-action="Index" class="btn btn-label-secondary">@T["Booking.Host.Cancel"]</a>
        </form>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Hosts/RemoveCalendar.cshtml">
@model HostCalendarRemovePage
@{
    var feed = Model.Feed;
    var key = Model.Host.Name;
}

<div class="mb-4">
    <a asp-action="Edit" asp-route-name="@key" asp-fragment="calendars" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Host.Edit.Title", Model.Name]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Feed.Remove.Title", feed.Label]</h5>
        <p class="mb-0">@T["Booking.Feed.Remove.Lead", Model.Host.DisplayName]</p>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <dl class="row mb-0">
            <dt class="col-5 col-md-3">@T["Booking.Feed.Column.Label"]</dt>
            <dd class="col-7 col-md-9">@feed.Label</dd>
            <dt class="col-5 col-md-3">@T["Booking.Feed.Column.Address"]</dt>
            <dd class="col-7 col-md-9"><code>@feed.UrlHint</code></dd>
        </dl>
    </div>
    <div class="card-footer">
        <form method="post" asp-action="RemoveCalendarConfirmed" asp-route-name="@key" asp-route-id="@feed.Id" class="d-flex gap-2">
            <button type="submit" class="btn btn-danger" id="confirm-remove-calendar">@T["Booking.Feed.Remove.Confirm"]</button>
            <a asp-action="Edit" asp-route-name="@key" class="btn btn-label-secondary">@T["Booking.Host.Cancel"]</a>
        </form>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Links/_TitleAndExpiry.cshtml">
@model BookingLinkFormPage
@*
    The two things a booking link's maker may set and change (#201, decisions 2 and 4): its title,
    prefilled with the suggestion, and Expires on, a month out, or Never expires.
*@
@{
    var form = Model.Form;
    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";
}

<div class="mb-3">
    <label class="form-label" for="link-title">@T["Booking.Links.Field.Title"]</label>
    <input type="text" class="form-control@(Invalid(BookingLinkForm.Fields.Title))" id="link-title" name="Title" value="@form.Title"
           maxlength="@BookingLink.TitleLength" data-link-title-input autocomplete="off" />
    <input type="hidden" name="suggested" value="@Model.Suggestion" data-link-suggested />
    <div class="invalid-feedback">@Model.ProblemOf(BookingLinkForm.Fields.Title)</div>
    <div class="form-text">@T["Booking.Links.Hint.Title", BookingLink.TitleLength]</div>
</div>

<div class="mb-3">
    <label class="form-label" for="link-expires">@T["Booking.Links.Field.ExpiresOn"]</label>
    <div class="d-flex flex-wrap align-items-center gap-3">
        <input type="date" class="form-control w-auto@(Invalid(BookingLinkForm.Fields.ExpiresOn))" id="link-expires" name="ExpiresOn" value="@form.ExpiresOn"
               min="@BookingLinkForm.Day(Model.Today)" data-link-expires />
        <div class="form-check mb-0">
            <input class="form-check-input" type="checkbox" id="link-never" name="NeverExpires" value="true" checked="@form.NeverExpires" data-link-never />
            <label class="form-check-label" for="link-never">@T["Booking.Links.Field.NeverExpires"]</label>
        </div>
    </div>
    @if (Model.ProblemOf(BookingLinkForm.Fields.ExpiresOn) is { } expiresProblem)
    {
        <div class="invalid-feedback d-block">@expiresProblem</div>
    }
    @* In the lead's zone: named once there is a lead, said so while an Administrator has yet to choose one. *@
    <div class="form-text">@T["Booking.Links.Hint.ExpiresOn", Model.Lead?.TimeZone ?? S["Booking.Links.LeadsZone"].Value]</div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Links/Edit.cshtml">
@model BookingLinkFormPage
@using KnowledgeFabric.AdminConsole.Areas.Crm.Models
@*
    A booking link's title and expiry, its maker's to change (#201, decision 5): its hosts are shown and
    never offered, since to change who is on it is to end it and make another.
*@
@{
    var link = Model.Link!;
}

@section PageScripts {
    <script src="~/js/booking-links.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-action="Index" class="text-body" id="link-back"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Links.Title"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Links.Edit.Title"]</h5>
        <p class="text-body mb-2">@T["Booking.Links.Edit.Lead"]</p>
        <p class="mb-0" id="link-hosts" data-link-hosts="@string.Join(",", link.Hosts)">@T["Booking.Joint.With", HostSet.Join(Model.LinkHostNames, S)]</p>
    </div>
</div>

@if (Model.Conflict)
{
    <div class="alert alert-danger" role="alert" id="link-conflict">
        <h6 class="alert-heading mb-1">@T["Booking.Links.Conflict.Title"]</h6>
        <p class="mb-0">@T["Booking.Links.Conflict.Detail", link.Title]</p>
    </div>
}

@if (Model.EndedMeanwhile)
{
    <div class="alert alert-warning" role="alert" id="link-ended">@T["Booking.Links.EndedMeanwhile"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="link-problem">@problem</div>
}

@if (Model.Problems.Count > 0)
{
    <div class="alert alert-danger" role="alert" id="link-problems">@T["Booking.Links.Problems"]</div>
}

<div class="card">
    @if (Model.EndedMeanwhile)
    {
        <div class="card-body">
            <a asp-action="Index" asp-route-tab="ended" class="btn btn-label-secondary">@T["Booking.Links.Back"]</a>
        </div>
    }
    else
    {
        <form method="post" asp-action="Edit" asp-route-id="@link.Id" class="card-body" id="link-form" novalidate>
            <input type="hidden" name="Version" value="@Model.Form.Version" />
            <partial name="_TitleAndExpiry" model="Model" />
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary" id="link-save">@T["Booking.Links.Save"]</button>
                <a asp-action="Index" class="btn btn-label-secondary">@T["Booking.Links.Back"]</a>
            </div>
        </form>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Links/End.cshtml">
@model BookingLinkEndPage
@*
    Ending a booking link (#201, decision 9): a confirm step, final, leaving the bookings it made alone.
*@
@{
    var link = Model.Link;
}

<div class="mb-4">
    <a asp-action="Index" class="text-body" id="link-back"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Links.Title"]</a>
</div>

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="link-problem">@problem</div>
}

<div class="card">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Links.End.Title"]</h5>
        <p class="fw-medium mb-1" id="link-end-title">@link.Title</p>
        <p class="text-body mb-3" id="link-end-hosts">@T["Booking.Joint.With", HostSet.Join(Model.HostNames, S)]</p>
        <p class="mb-1">@T["Booking.Links.End.Lead"]</p>
        <p class="text-body mb-0" id="link-end-bookings" data-bookings="@Model.LiveBookings">
            @(Model.LiveBookings == 1 ? T["Booking.Links.End.Bookings.One"] : T["Booking.Links.End.Bookings.Many", Model.LiveBookings])
        </p>
    </div>
    <form method="post" asp-action="End" asp-route-id="@link.Id" class="card-footer d-flex gap-2">
        <button type="submit" class="btn btn-danger" id="link-end-confirm">@T["Booking.Links.End.Confirm"]</button>
        <a asp-action="Index" class="btn btn-label-secondary">@T["Booking.Links.End.Keep"]</a>
    </form>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Links/Index.cshtml">
@model BookingLinkListPage
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Crm.Models
@{
    var query = Model.Query;
    var culture = CultureInfo.CurrentCulture;
    var tabs = new[]
    {
        (BookingLinkState.Open, "Booking.Links.Tab.Open"),
        (BookingLinkState.Expired, "Booking.Links.Tab.Expired"),
        (BookingLinkState.Ended, "Booking.Links.Tab.Ended"),
    };

    Dictionary<string, string> Route(BookingLinkState tab, string? host)
    {
        var route = new Dictionary<string, string> { ["tab"] = BookingLinkListQuery.Word(tab) };
        if (host is not null)
        {
            route["host"] = host;
        }
        return route;
    }

    var hostKnown = query.Host is null || Model.Hosts.Any(host => host.Name == query.Host);
    var emptyKey = query.Tab switch
    {
        BookingLinkState.Expired => "Booking.Links.Empty.Expired",
        BookingLinkState.Ended => "Booking.Links.Empty.Ended",
        _ => "Booking.Links.Empty.Open",
    };
}
@*
    A host's links for a meeting with colleagues (#201): the links one is on, or to an Administrator
    every host's, a row each, with Copy link, Edit for the maker and End for any host on it.
*@

<div class="card mb-4" id="booking-links-area">
    <div class="card-body d-flex flex-wrap align-items-start gap-3">
        <div class="flex-grow-1">
            <h5 class="card-title mb-2">@T["Booking.Links.Title"]</h5>
            <p class="text-body mb-0">@T["Booking.Links.Intro"]</p>
        </div>
        @if (Model.MayMake)
        {
            <a asp-action="New" class="btn btn-primary" id="booking-links-new"><i class="ti ti-link-plus me-1"></i>@T["Booking.Links.Make"]</a>
        }
    </div>
</div>

@if (Model.Storage == BookingStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">@T["Booking.Hosts.NoDatabase"]</div>
}
else if (Model.Storage == BookingStorage.Ephemeral)
{
    <div class="alert alert-secondary" role="status">@T["Booking.Hosts.Ephemeral"]</div>
}

@if (Model.Notice is { } notice)
{
    <div class="alert alert-success" role="status" id="booking-links-notice" data-notice="@notice">@T[notice]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-warning" role="alert" id="booking-links-unreadable">@T["Booking.Links.Unreadable"]</div>
}

<div class="card" id="booking-links" data-tab="@BookingLinkListQuery.Word(query.Tab)">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs">
            @foreach (var (tab, key) in tabs)
            {
                <li class="nav-item">
                    <a asp-action="Index" asp-all-route-data="Route(tab, query.Host)"
                       class="nav-link@(tab == query.Tab ? " active" : "")" aria-current="@(tab == query.Tab ? "page" : null)"
                       data-links-tab="@BookingLinkListQuery.Word(tab)">@T[key]</a>
                </li>
            }
        </ul>
    </div>
    <div class="card-body pt-4">
        @* Every host's links, and the filter by host, are an Administrator's alone (#193). *@
        @if (Model.MayConfigure)
        {
            <form method="get" asp-action="Index" class="d-flex gap-2 align-items-center mb-3" id="booking-links-host-filter" role="search">
                <input type="hidden" name="tab" value="@BookingLinkListQuery.Word(query.Tab)" />
                <select name="host" class="form-select form-select-sm w-auto" aria-label="@S["Booking.List.Filter.Host"]" data-submit-on-change>
                    <option value="">@T["Booking.List.AnyHost"]</option>
                    @if (!hostKnown)
                    {
                        <option value="@query.Host" selected="selected">@query.Host</option>
                    }
                    @foreach (var host in Model.Hosts)
                    {
                        <option value="@host.Name" selected="@(host.Name == query.Host)">@Model.Initials.Choice(host.Name)</option>
                    }
                </select>
                <noscript><button type="submit" class="btn btn-sm btn-label-secondary">@T["Booking.List.Filter.Apply"]</button></noscript>
            </form>
... (79 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Links/New.cshtml">
@model BookingLinkFormPage
@*
    A new booking link (#201): the lead (an Administrator's to choose, anyone else's their own), the
    colleagues as checkboxes, the title kept in step with them until the host types in it, and the expiry.
*@
@{
    var form = Model.Form;
    var lead = Model.Lead;
    var ticked = form.Colleagues.Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";
}

@section PageScripts {
    <script src="~/js/booking-links.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-action="Index" class="text-body" id="link-back"><i class="ti ti-arrow-left me-1"></i>@T["Booking.Links.Title"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Booking.Links.New.Title"]</h5>
        <p class="text-body mb-0">@T["Booking.Links.New.Lead", BookingRecord.MaxHosts - 1]</p>
    </div>
</div>

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="link-problem">@problem</div>
}

@if (Model.Problems.Count > 0)
{
    <div class="alert alert-danger" role="alert" id="link-problems">@T["Booking.Links.Problems"]</div>
}

<div class="card">
    <form method="post" asp-action="Create" class="card-body" id="link-form" novalidate
          data-title-template="@S["Booking.Links.SuggestedTitle"]" data-and-template="@S["Booking.Joint.And"]" data-title-length="@BookingLink.TitleLength">

        @if (Model.Leads.Count > 0)
        {
            @* An Administrator makes a link for any host as its lead (#193). *@
            <div class="mb-3">
                <label class="form-label" for="link-lead">@T["Booking.Links.Field.Lead"]</label>
                <select class="form-select w-auto@(Invalid(BookingLinkForm.Fields.Lead))" id="link-lead" name="Lead" data-link-lead>
                    <option value="" data-display-name="">@T["Booking.Links.ChooseLead"]</option>
                    @foreach (var person in Model.Leads)
                    {
                        <option value="@person.Host.Name" selected="@(person.Host.Name == lead?.Name)" data-display-name="@person.Host.DisplayName" disabled="@(!person.Served)">@person.Choice</option>
                    }
                </select>
                <div class="invalid-feedback">@Model.ProblemOf(BookingLinkForm.Fields.Lead)</div>
                <div class="form-text">@T["Booking.Links.Hint.Lead"]</div>
            </div>
        }
        else if (lead is not null)
        {
            <input type="hidden" name="Lead" value="@lead.Name" />
            <p class="mb-3" id="link-lead-own" data-link-lead-name="@lead.DisplayName">@T["Booking.Links.YouLead", lead.DisplayName]</p>
            @if (Model.ProblemOf(BookingLinkForm.Fields.Lead) is { } leadProblem)
            {
                <div class="alert alert-warning" role="alert" id="link-lead-problem">@leadProblem</div>
            }
        }

        <fieldset class="mb-3">
            <legend class="form-label fs-6">@T["Booking.Links.Field.Colleagues", BookingRecord.MaxHosts - 1]</legend>
            @if (Model.Colleagues.All(person => person.Host.Name == lead?.Name))
            {
                <p class="text-body mb-0" id="link-no-colleagues">@T["Booking.Links.NoColleagues"]</p>
            }
            <div class="d-flex flex-wrap gap-3@(Invalid(BookingLinkForm.Fields.Colleagues))" id="link-colleagues">
                @foreach (var person in Model.Colleagues)
                {
                    var name = person.Host.Name;
                    var id = $"link-colleague-{name}";
                    <div class="form-check mb-0@(name == lead?.Name ? " d-none" : "")" data-link-colleague-of="@name">
                        <input class="form-check-input" type="checkbox" id="@id" name="Colleagues" value="@name"
                               checked="@ticked.Contains(name)" disabled="@(name == lead?.Name)" data-display-name="@person.Host.DisplayName" data-link-colleague />
                        <label class="form-check-label" for="@id">@person.Choice</label>
                    </div>
                }
            </div>
            @if (Model.ProblemOf(BookingLinkForm.Fields.Colleagues) is { } colleaguesProblem)
            {
                <div class="invalid-feedback d-block" id="link-colleagues-problem">@colleaguesProblem</div>
            }
        </fieldset>

        <partial name="_TitleAndExpiry" model="Model" />

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary" id="link-create">@T["Booking.Links.Create"]</button>
            <a asp-action="Index" class="btn btn-label-secondary">@T["Booking.Links.Back"]</a>
        </div>
    </form>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/_Heading.cshtml">
@model PublicPage
@*
    The public page's heading (#174): one host's name, or a set's, headed With and every host's
    display name in the order the link named them (#200), or a host's booking link's title and its
    hosts (#201).
*@
@if (Model.Hosts.Link is { } link)
{
    @* A host's booking link (#201): headed by its title, as the host typed it, then every host on it. *@
    <h4 class="card-title mb-1" id="public-link-title">@link.Title</h4>
    <p class="fw-medium mb-1" id="public-host" data-link-hosts="@Model.Hosts.Hosts.Count">@T["Booking.Joint.With", Model.Hosts.DisplayNames(S)]</p>
}
else if (Model.Hosts.IsJoint)
{
    <h4 class="card-title mb-1" id="public-host" data-hosts="@Model.Hosts.Slug">@T["Booking.Joint.With", Model.Hosts.DisplayNames(S)]</h4>
}
else
{
    <h4 class="card-title mb-1" id="public-host">@T["Booking.Public.Heading", Model.Host.DisplayName]</h4>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Booked.cshtml">
@model PublicBookedPage
@using System.Globalization
@{
    Layout = "_PublicLayout";
    var culture = CultureInfo.CurrentCulture;
    var lead = Model.Host;
    string When(DateTime start, DateTime end) =>
        $"{start.ToString("dddd d MMMM yyyy", culture)}, {start.ToString("HH:mm", CultureInfo.InvariantCulture)}–{end.ToString("HH:mm", CultureInfo.InvariantCulture)}";
}

<div class="card">
    <div class="card-body">
        <div class="d-flex align-items-center gap-2 mb-2">
            <i class="ti ti-circle-check text-success ti-lg"></i>
            <h4 class="card-title mb-0" id="public-booked">@T["Booking.Public.Booked.Heading", Model.Hosts.DisplayNames(S)]</h4>
        </div>
        @if (Model.Hosts.Link is { } link)
        {
            @* Booked through a host's link (#201): its title, as the host typed it. *@
            <p class="fw-medium mb-1" id="booked-link-title">@link.Title</p>
        }
        <p class="mb-1 text-capitalize" id="booked-guest">@When(Model.GuestStart, Model.GuestEnd) <span class="small text-body">(@Model.Zone.Id)</span></p>
        @if (Model.ZonesDiffer)
        {
            <p class="small text-body mb-3 text-capitalize" id="booked-host">@T["Booking.Public.ForHost", lead.DisplayName] @When(Model.HostStart, Model.HostEnd) (@Model.HostZone.Id)</p>
        }
        @if (Model.Sent)
        {
            <p class="text-body mb-0" id="booked-invitation" data-sent="true">@T["Booking.Public.Booked.Invitation"]</p>
        }
        else
        {
            <p class="text-body mb-0" id="booked-invitation" data-sent="false">@T["Booking.Invitation.WillFollow"]</p>
        }
        @if (Model.CancelPath is { } cancelPath)
        {
            @* The guest's own link (#178), which the invitation carries too. *@
            <p class="text-body mt-3 mb-0" id="booked-change">@T["Booking.Public.Cancel.Change"] <a href="@cancelPath" id="booked-cancel-link" rel="nofollow">@T["Booking.Public.Cancel.ChangeLink"]</a></p>
        }
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Cancel.cshtml">
@model PublicCancelPage
@using System.Globalization
@{
    // The guest's link (#178): the slot and every host's display name (#200), nothing more of the booking.
    Layout = "_PublicLayout";
    var culture = CultureInfo.CurrentCulture;
    var lead = Model.Host;
    string When(DateTime start, DateTime end) =>
        $"{start.ToString("dddd d MMMM yyyy", culture)}, {start.ToString("HH:mm", CultureInfo.InvariantCulture)}–{end.ToString("HH:mm", CultureInfo.InvariantCulture)}";
}

<div class="card">
    <div class="card-body">
        <h4 class="card-title mb-1" id="public-cancel">@T["Booking.Public.Cancel.Heading", Model.Hosts.DisplayNames(S)]</h4>
        <p class="mb-1 text-capitalize" id="cancel-guest">@When(Model.GuestStart, Model.GuestEnd) <span class="small text-body">(@Model.Zone.Id)</span></p>
        @if (Model.ZonesDiffer)
        {
            <p class="small text-body mb-3 text-capitalize" id="cancel-host">@T["Booking.Public.ForHost", lead.DisplayName] @When(Model.HostStart, Model.HostEnd) (@Model.HostZone.Id)</p>
        }
        else
        {
            <p class="mb-3"></p>
        }

        <p class="text-body" id="cancel-lead">@T["Booking.Public.Cancel.Lead"]</p>

        <form method="post" asp-action="CancelByGuest" asp-route-token="@Model.Token" id="cancel-form">
            <button type="submit" class="btn btn-danger" id="public-cancel-booking">@T["Booking.Public.Cancel.Button"]</button>
        </form>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Cancelled.cshtml">
@model PublicCancelledPage
@using System.Globalization
@{
    // The guest's cancel done (#178), once: the slot that was, and where to book again.
    Layout = "_PublicLayout";
    var culture = CultureInfo.CurrentCulture;
    var lead = Model.Host;
    string When(DateTime start, DateTime end) =>
        $"{start.ToString("dddd d MMMM yyyy", culture)}, {start.ToString("HH:mm", CultureInfo.InvariantCulture)}–{end.ToString("HH:mm", CultureInfo.InvariantCulture)}";
    var eventKey = Model.EventDeleted switch
    {
        "Deleted" => "Booking.Public.Cancel.Done.Deleted",
        "NotSent" => null,
        _ => "Booking.Public.Cancel.Done.Pending",
    };
}

<div class="card">
    <div class="card-body">
        <div class="d-flex align-items-center gap-2 mb-2">
            <i class="ti ti-circle-x text-body ti-lg"></i>
            <h4 class="card-title mb-0" id="public-cancelled">@T["Booking.Public.Cancel.Done.Heading", Model.Hosts.DisplayNames(S)]</h4>
        </div>
        <p class="mb-1 text-capitalize text-decoration-line-through" id="cancelled-guest">@When(Model.GuestStart, Model.GuestEnd) <span class="small text-body">(@Model.Zone.Id)</span></p>
        @if (Model.ZonesDiffer)
        {
            <p class="small text-body mb-3 text-capitalize" id="cancelled-host">@T["Booking.Public.ForHost", lead.DisplayName] @When(Model.HostStart, Model.HostEnd) (@Model.HostZone.Id)</p>
        }
        else
        {
            <p class="mb-3"></p>
        }
        @if (eventKey is not null)
        {
            <p class="text-body" id="cancelled-event" data-event="@Model.EventDeleted">@T[eventKey]</p>
        }
        @if (Model.MayBookAgain)
        {
            <a href="@Url.PublicLink("Month", Model.Hosts, new { tz = Model.Zone.Query })" class="btn btn-primary" id="public-book-again">@T["Booking.Public.Cancel.Rebook"]</a>
        }
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Closed.cshtml">
@model PublicClosedPage
@{
    Layout = "_PublicLayout";
}

<div class="card">
    <div class="card-body">
        <partial name="_Heading" model="Model" />
        <p class="mb-1 fw-medium" id="public-closed">@T["Booking.Public.Closed"]</p>
        <p class="text-body mb-0">@T["Booking.Public.Closed.Detail"]</p>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Day.cshtml">
@model PublicDayPage
@using System.Globalization
@{
    Layout = "_PublicLayout";
    var culture = CultureInfo.CurrentCulture;
    var hosts = Model.Hosts;
    var zone = Model.Zone;
}

<div class="mb-3">
    <a href="@Url.PublicLink("Month", hosts, new { month = PublicRoutes.Month(Model.Month), tz = zone.Query })" class="text-body" id="back-to-month">
        <i class="ti ti-arrow-left me-1"></i>@T["Booking.Public.BackToMonth"]
    </a>
</div>

@if (Model.Note is { } note)
{
    <div class="alert alert-warning" role="alert" id="public-note">@note</div>
}

<div class="card">
    <div class="card-body">
        <partial name="_Heading" model="Model" />
        <p class="text-body mb-3 text-capitalize" id="public-day">@Model.Day.ToString("dddd d MMMM yyyy", culture)</p>

        @if (Model.Slots.Count == 0)
        {
            <p class="text-body mb-0" id="day-empty">@T["Booking.Public.NoSlotsThisDay"]</p>
        }
        else
        {
            <p class="small text-body mb-2">@T["Booking.Public.ChooseSlot", Model.DurationMinutes]</p>
            <div class="booking-slots" id="day-slots">
                @foreach (var slot in Model.Slots)
                {
                    var route = slot.Route;
                    <a href="@Url.PublicLink("Slot", hosts, new { day = route.Day, time = route.Time, tz = zone.Query })"
                       class="btn btn-label-primary booking-slot" data-start="@BookingRecord.Instant(slot.Slot.Start)">@slot.LocalStart.ToString("HH:mm", CultureInfo.InvariantCulture)</a>
                }
            </div>
        }
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Month.cshtml">
@model PublicMonthPage
@using System.Globalization
@{
    Layout = "_PublicLayout";
    var culture = CultureInfo.CurrentCulture;
    var hosts = Model.Hosts;
    var zone = Model.Zone;
    // The week's day names, Monday first, as the culture abbreviates them.
    var dayNames = Enumerable.Range(1, 7).Select(offset => culture.DateTimeFormat.AbbreviatedDayNames[offset % 7]).ToList();
}

<div class="card mb-4">
    <div class="card-body">
        <partial name="_Heading" model="Model" />
        <p class="text-body mb-0">@T["Booking.Public.Lead", Model.DurationMinutes]</p>
        @if (hosts.IsJoint)
        {
            <p class="text-body mt-2 mb-0" id="public-joint-lead">@T["Booking.Joint.Lead"]</p>
        }
    </div>
</div>

@if (Model.NoTimeInCommon)
{
    @* A set with no slot offered before its horizon (#200): said, with each host's own page. *@
    <div class="card" id="public-no-common-time">
        <div class="card-body">
            <p class="fw-medium mb-2">@T["Booking.Joint.NoTimeInCommon", hosts.DisplayNames(S), hosts.HorizonDays]</p>
            @* A booking link's hosts are fixed (#201, decision 5): it leads nowhere else, so it lists no host's own page. *@
            @if (hosts.Link is null)
            {
                <p class="text-body mb-2">@T["Booking.Joint.OwnPages"]</p>
                <ul class="mb-0" id="public-own-pages">
                    @foreach (var one in hosts.Hosts)
                    {
                        <li><a href="@Url.PublicLink("Month", new { slug = one.Slug, tz = zone.Query })" data-own-page="@one.Slug">@one.DisplayName</a></li>
                    }
                </ul>
            }
            else
            {
                <p class="text-body mb-0" id="public-link-ask">@T["Booking.Links.Public.NoTimeInCommon"]</p>
            }
        </div>
    </div>
    return;
}

<div class="card">
    <div class="card-header d-flex flex-wrap align-items-center gap-2">
        <h5 class="card-title mb-0 me-auto text-capitalize" id="public-month">@Model.First.ToString("MMMM yyyy", culture)</h5>
        @if (Model.PreviousMonth is { } previous)
        {
            <a href="@Url.PublicLink("Month", hosts, new { month = PublicRoutes.Month(previous), tz = zone.Query })" class="btn btn-sm btn-label-secondary" id="month-previous">
                <i class="ti ti-chevron-left me-1"></i>@T["Booking.Public.PreviousMonth"]
            </a>
        }
        @if (Model.NextMonth is { } next)
        {
            <a href="@Url.PublicLink("Month", hosts, new { month = PublicRoutes.Month(next), tz = zone.Query })" class="btn btn-sm btn-label-secondary" id="month-next">
                @T["Booking.Public.NextMonth"]<i class="ti ti-chevron-right ms-1"></i>
            </a>
        }
    </div>
    <div class="card-body">
        @if (!Model.OffersAnything)
        {
            <p class="text-body mb-3" id="month-empty">@T["Booking.Public.NoSlotsThisMonth"]</p>
        }

        <table class="table table-borderless booking-month mb-0">
            <thead>
                <tr>
                    @foreach (var name in dayNames)
                    {
                        <th class="text-center small text-body text-capitalize">@name</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (var week in Model.Weeks)
                {
                    <tr>
                        @foreach (var day in week)
                        {
                            if (day is null)
                            {
                                <td></td>
                                continue;
                            }

                            <td class="text-center p-1" id="day-@PublicRoutes.Day(day.Date)" data-slots="@day.Slots">
                                @if (day.Slots > 0)
                                {
                                    <a href="@Url.PublicLink("Day", hosts, new { day = PublicRoutes.Day(day.Date), tz = zone.Query })"
                                       class="btn btn-sm btn-primary w-100 booking-day" title="@S[day.Slots == 1 ? "Booking.Public.SlotCount.One" : "Booking.Public.SlotCount.Many", day.Slots]">
                                        @day.Date.Day
                                    </a>
                                }
                                else
... (12 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Notice.cshtml">
@model PublicNoticePage
@{
    // A public page that names no host (#178): the guest's link that no longer works, said one way
    // whatever the reason, and a cancel that could not be written.
    Layout = "_PublicLayout";
}

<div class="card">
    <div class="card-body">
        <h4 class="card-title mb-1" id="public-notice" data-notice="@Model.HeadingKey">@T[Model.HeadingKey]</h4>
        <p class="text-body mb-0">@T[Model.DetailKey]</p>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Slot.cshtml">
@model PublicSlotPage
@using System.Globalization
@{
    Layout = "_PublicLayout";
    var culture = CultureInfo.CurrentCulture;
    var hosts = Model.Hosts;
    var lead = Model.Host;
    var zone = Model.Zone;
    var slot = Model.Slot;
    var form = Model.Form;
    string When(DateTime start, DateTime end) =>
        $"{start.ToString("dddd d MMMM yyyy", culture)}, {start.ToString("HH:mm", CultureInfo.InvariantCulture)}–{end.ToString("HH:mm", CultureInfo.InvariantCulture)}";
    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";
}

<div class="mb-3">
    <a href="@Url.PublicLink("Day", hosts, new { day = PublicRoutes.Day(zone.DayOf(slot.Slot.Start)), tz = zone.Query })" class="text-body" id="back-to-day">
        <i class="ti ti-arrow-left me-1"></i>@T["Booking.Public.BackToDay"]
    </a>
</div>

<div class="card">
    <div class="card-body">
        <partial name="_Heading" model="Model" />
        <p class="mb-1 text-capitalize" id="slot-guest">@When(slot.LocalStart, slot.LocalEnd) <span class="small text-body">(@zone.Id)</span></p>
        @if (Model.ZonesDiffer)
        {
            @* On the lead's clock where it differs from the guest's (#200, decision 4). *@
            <p class="small text-body mb-3 text-capitalize" id="slot-host">@T["Booking.Public.ForHost", lead.DisplayName] @When(Model.HostStart, Model.HostEnd) (@Model.HostZone.Id)</p>
        }
        else
        {
            <p class="mb-3"></p>
        }

        @if (Model.Problem is { } problem)
        {
            <div class="alert alert-danger" role="alert" id="public-problem">@problem</div>
        }

        @if (Model.Problems.Count > 0)
        {
            <div class="alert alert-danger" role="alert" id="public-problems">@T["Booking.Public.Problems"]</div>
        }

        <form method="post" action="@Url.PublicLink("Book", hosts)" asp-antiforgery="true" id="public-form" novalidate>
            <input type="hidden" name="Slot" value="@form.Slot" />
            <input type="hidden" name="Tz" value="@form.Tz" />

            <div class="mb-3">
                <label class="form-label" for="guest-name">@T["Booking.Public.Field.Name"]</label>
                <input type="text" class="form-control@(Invalid(BookingForm.Fields.Name))" id="guest-name" name="Name" value="@form.Name" maxlength="@BookingRecord.GuestNameLength" autocomplete="name" required />
                <div class="invalid-feedback">@Model.ProblemOf(BookingForm.Fields.Name)</div>
            </div>

            <div class="mb-3">
                <label class="form-label" for="guest-email">@T["Booking.Public.Field.Email"]</label>
                <input type="email" class="form-control@(Invalid(BookingForm.Fields.Email))" id="guest-email" name="Email" value="@form.Email" maxlength="@BookingRecord.GuestEmailLength" autocomplete="email" required />
                <div class="invalid-feedback">@Model.ProblemOf(BookingForm.Fields.Email)</div>
                <div class="form-text">@T["Booking.Public.Hint.Email"]</div>
            </div>

            <div class="mb-3">
                <label class="form-label" for="guest-organisation">@T["Booking.Public.Field.Organisation"] <span class="text-body">@T["Booking.Public.Optional"]</span></label>
                <input type="text" class="form-control@(Invalid(BookingForm.Fields.Organisation))" id="guest-organisation" name="Organisation" value="@form.Organisation" maxlength="@BookingRecord.GuestOrganisationLength" autocomplete="organization" />
                <div class="invalid-feedback">@Model.ProblemOf(BookingForm.Fields.Organisation)</div>
            </div>

            <div class="mb-3">
                <label class="form-label" for="guest-note">@T["Booking.Public.Field.Note"] <span class="text-body">@T["Booking.Public.Optional"]</span></label>
                <textarea class="form-control@(Invalid(BookingForm.Fields.Note))" id="guest-note" name="Note" rows="3" maxlength="@BookingRecord.GuestNoteLength">@form.Note</textarea>
                <div class="invalid-feedback">@Model.ProblemOf(BookingForm.Fields.Note)</div>
            </div>

            @*
                The honeypot (#170, decision 8): a field no person sees, hidden by the stylesheet and
                not by type=hidden, so a script that fills every field fills it. Filled, nothing is written.
            *@
            <div class="booking-aside" aria-hidden="true">
                <label for="guest-website">@T["Booking.Public.Field.Website"]</label>
                <input type="text" id="guest-website" name="Website" value="" tabindex="-1" autocomplete="off" />
            </div>

            <button type="submit" class="btn btn-primary" id="public-book">@T["Booking.Public.Book"]</button>
        </form>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Public/Team.cshtml">
@model PublicTeamPage
@{
    // The team page (#202): the hosts who chose to be listed, by display name alone, ticked one or more
    // and sent back as ?host= to be redirected to the set's month. Nothing else of a host is shown.
    Layout = "_PublicLayout";
}

<div class="card">
    <div class="card-body">
        <h4 class="card-title mb-1" id="public-team">@T["Booking.Team.Title"]</h4>

        @if (Model.Closed)
        {
            <p class="mb-1 fw-medium" id="public-closed">@T["Booking.Public.Closed"]</p>
            <p class="text-body mb-0">@T["Booking.Team.Closed.Detail"]</p>
        }
        else
        {
            <p class="text-body mb-1">@T["Booking.Team.Lead"]</p>
            <p class="text-body mb-3" id="public-team-joint">@T["Booking.Team.Joint", Model.MaxHosts]</p>

            @if (Model.Problem is { } problem)
            {
                <div class="alert alert-danger" role="alert" id="public-team-problem">@problem</div>
            }

            <form method="get" action="@Url.Action("Index", "Public")" id="public-team-form" data-team-max="@Model.MaxHosts" novalidate>
                @if (Model.Zone.Query is { } tz)
                {
                    <input type="hidden" name="tz" value="@tz" />
                }
                <fieldset class="mb-3">
                    <legend class="form-label fs-6">@T["Booking.Team.Choose"]</legend>
                    @foreach (var member in Model.Members)
                    {
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="checkbox" name="@PublicTeam.HostQuery" value="@member.Slug" id="team-@member.Slug"
                                   checked="@Model.IsChosen(member)" data-team-host />
                            <label class="form-check-label" for="team-@member.Slug">@member.DisplayName</label>
                        </div>
                    }
                </fieldset>
                <button type="submit" class="btn btn-primary" name="@PublicTeam.ContinueQuery" value="1" id="public-team-continue">@T["Booking.Team.Continue"]</button>
            </form>
        }
    </div>
</div>

@section Scripts {
    <script src="~/js/booking-team.js" asp-append-version="true"></script>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Shared/Components/BookingOverview/Default.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Booking.ViewComponents
@model BookingOverview
@{
    var week = Model.Week;
    var culture = CultureInfo.CurrentCulture;
    // Everyone's list for an Administrator, one's own for anyone else (#193), who sees only their own count.
    var who = Model.Everyone ? BookingListQuery.EveryoneWord : BookingListQuery.MineWord;
    string Day(DateOnly day) => day.ToString("d MMM", culture);
}

@* The Bookings area's card on the overview (#176): this week's bookings, Monday to Sunday UTC, a count per host linking to the list filtered to them, and the signed-in host's next booking. *@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card" id="booking-overview">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Menu.Booking"]</h5>
                <p class="card-subtitle mb-0">@T["Booking.Overview.Lead"]</p>
            </div>
            <div class="card-body">
                @if (Model.Storage == BookingStorage.Unavailable)
                {
                    <p class="text-body mb-0">@T["Booking.Overview.NoDatabase"]</p>
                }
                else if (week is null)
                {
                    <div class="alert alert-danger mb-0" role="alert">@T["Booking.Overview.Unreadable"]</div>
                }
                else
                {
                    <div class="row g-4">
                        <div class="col-md-6" id="booking-overview-week" data-monday="@week.Monday.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)" data-total="@week.Total">
                            <span class="text-heading">@T["Booking.Overview.ThisWeek"]</span>
                            <h4 class="mb-1 mt-1"><a asp-area="Booking" asp-controller="Bookings" asp-action="Index" asp-route-who="@who">@week.Total</a></h4>
                            <small class="text-body d-block mb-2">@T["Booking.Overview.Week", Day(week.Monday), Day(week.Sunday)]</small>
                            @if (week.PerHost.Count == 0)
                            {
                                <p class="text-body mb-0" id="booking-overview-none">@T["Booking.Overview.None"]</p>
                            }
                            else
                            {
                                <ul class="list-unstyled mb-0" style="max-width: 22rem">
                                    @foreach (var host in week.PerHost)
                                    {
                                        <li class="d-flex justify-content-between gap-3" data-booking-host="@host.Host" data-count="@host.Count">
                                            @if (Model.Everyone)
                                            {
                                                <a asp-area="Booking" asp-controller="Bookings" asp-action="Index" asp-route-who="everyone" asp-route-host="@host.Host" title="@host.Host">@Model.DisplayNameOf(host.Host)</a>
                                            }
                                            else
                                            {
                                                <a asp-area="Booking" asp-controller="Bookings" asp-action="Index" asp-route-who="mine" title="@host.Host">@Model.DisplayNameOf(host.Host)</a>
                                            }
                                            <span class="fw-medium">@host.Count</span>
                                        </li>
                                    }
                                </ul>
                            }
                        </div>
                        @if (week.Next is { } next)
                        {
                            var zone = BookingOverview.ZoneOf(next);
                            var start = TimeZoneInfo.ConvertTime(next.StartsAt, zone).DateTime;
                            var end = TimeZoneInfo.ConvertTime(next.EndsAt, zone).DateTime;

                            <div class="col-md-6" id="booking-overview-next" data-booking="@next.Id">
                                <span class="text-heading">@T["Booking.Overview.Next"]</span>
                                <h6 class="mb-1 mt-1">
                                    <a asp-area="Booking" asp-controller="Bookings" asp-action="Show" asp-route-id="@next.Id" title="@BookingRecord.Instant(next.StartsAt)">
                                        @start.ToString("dddd d MMMM", culture), @start.ToString("HH:mm", CultureInfo.InvariantCulture)–@end.ToString("HH:mm", CultureInfo.InvariantCulture)
                                    </a>
                                </h6>
                                <small class="text-body">@(next.GuestName)@(next.GuestOrganisation is { } organisation ? $", {organisation}" : "") · @next.HostTimeZone</small>
                            </div>
                        }
                    </div>
                }
            </div>
        </div>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/Shared/_BookingLink.cshtml">
@model BookingLinkCard
@*
    A host's booking link, made prominent to be shared: the link itself, opening the public page in a
    new tab, a copy button, and whether it answers now. On the host's week, and on the bookings list
    for the signed-in host.
*@
<div class="card @(Model.InRow ? "" : "mb-4 ")border border-primary" id="booking-link-card" data-booking-link-host="@Model.Host.Name">
    <div class="card-body d-flex flex-wrap align-items-center gap-3">
        <span class="avatar flex-shrink-0">
            <span class="avatar-initial rounded bg-label-primary"><i class="ti ti-share ti-md"></i></span>
        </span>
        <div class="flex-grow-1" style="min-width: 0">
            <h6 class="mb-1">@(Model.Own ? T["Booking.Link.Title.Own"] : T["Booking.Link.Title", Model.Host.DisplayName])</h6>
            <div class="d-flex flex-wrap align-items-center gap-1">
                <a href="@Model.Link" target="_blank" rel="noopener noreferrer" class="fw-medium text-break" id="booking-link" data-booking-link>@Model.Link</a>
                <button type="button" class="btn btn-sm btn-label-primary" data-copy="@Model.Link" id="booking-link-copy"
                        title="@S["Booking.Hosts.CopyLink"]" aria-label="@S["Booking.Hosts.CopyLink"]">
                    <i class="ti ti-copy me-1"></i>@T["Booking.Link.Copy"]
                </button>
            </div>
            @if (Model.ClosedKey is { } closed)
            {
                <p class="small text-warning mb-0 mt-1" id="booking-link-state" data-open="false">@T[closed]</p>
            }
            else
            {
                <p class="small text-body mb-0 mt-1" id="booking-link-state" data-open="true">@(Model.Own ? T["Booking.Link.Share.Own"] : T["Booking.Link.Share", Model.Host.DisplayName])</p>
            }
            @if (Model.ShownTeamLink is { } team)
            {
                @* The team page (#202), while the host is listed on it. *@
                <p class="small text-body mb-0 mt-1" id="booking-link-team">
                    @(Model.Own ? T["Booking.Link.Team.Own"] : T["Booking.Link.Team", Model.Host.DisplayName])
                    <a href="@team" target="_blank" rel="noopener noreferrer" class="text-break">@team</a>
                    <button type="button" class="btn btn-sm btn-icon btn-text-secondary" data-copy="@team"
                            title="@S["Booking.Hosts.CopyLink"]" aria-label="@S["Booking.Hosts.CopyLink"]">
                        <i class="ti ti-copy"></i>
                    </button>
                </p>
            }
        </div>
        @if (Model.MayMakeLink)
        {
            @* A link of the host's own for a meeting with colleagues (#201). *@
            <a asp-area="Booking" asp-controller="Links" asp-action="New" asp-route-host="@Model.Host.Name" class="btn btn-sm btn-label-primary" id="booking-link-make">
                <i class="ti ti-link-plus me-1"></i>@T["Booking.Links.Make"]
            </a>
        }
    </div>
    @if (Model.OpenLinks.Count > 0)
    {
        @* The host's open booking links (#201), beneath their own link, each to copy. *@
        <div class="card-body border-top pt-3" id="booking-link-open-links">
            <h6 class="small text-uppercase text-body mb-2">@T["Booking.Links.Card.Heading"]</h6>
            <ul class="list-unstyled mb-0">
                @foreach (var link in Model.OpenLinks)
                {
                    <li class="d-flex flex-wrap align-items-center gap-2 mb-1" data-open-link="@link.Id">
                        <a href="@link.Address" target="_blank" rel="noopener noreferrer" class="fw-medium text-break">@link.Title</a>
                        <button type="button" class="btn btn-xs btn-sm btn-label-primary py-0" data-copy="@link.Address" title="@S["Booking.Links.Copy"]" aria-label="@S["Booking.Links.Copy"]">
                            <i class="ti ti-copy"></i>
                        </button>
                    </li>
                }
            </ul>
            <a asp-area="Booking" asp-controller="Links" asp-action="Index" class="small" id="booking-link-all-links">@T["Booking.Links.Card.All"]</a>
        </div>
    }
</div>
<script src="~/js/copy-id.js" asp-append-version="true"></script>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/_ViewImports.cshtml">
@using KnowledgeFabric.AdminConsole
@using KnowledgeFabric.AdminConsole.Models
@using KnowledgeFabric.AdminConsole.Security
@using KnowledgeFabric.AdminConsole.Booking
@using KnowledgeFabric.AdminConsole.Areas.Booking.Controllers
@using KnowledgeFabric.AdminConsole.Areas.Booking.Models
@using Microsoft.AspNetCore.Mvc.Localization
@using KnowledgeFabric.AdminConsole.Localisation
@using KnowledgeFabric.AdminConsole.Resources
@using Microsoft.Extensions.Localization
@inject IHtmlLocalizer<ConsoleResource> T
@inject IStringLocalizer<ConsoleResource> S
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Booking/Views/_ViewStart.cshtml">
@{
    Layout = "_ContentNavbarLayout";
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Controllers/CompetitorsController.cs">
public sealed class CompetitorsController(
⋮----
ILogger<CompetitorsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(CancellationToken cancellationToken)
⋮----
rows = await store.ListAsync(cancellationToken);
latest = await store.LatestNewsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The competitors could not be read.");
⋮----
return View(new CompetitorList(
⋮----
public async Task<IActionResult> Details(Guid id, CancellationToken cancellationToken)
⋮----
var competitor = await store.FindAsync(id, cancellationToken);
⋮----
sources = await store.SourcesAsync(id, cancellationToken);
⋮----
logger.LogError(ex, "The sources of the competitor {Id} could not be read.", id);
⋮----
return View(new CompetitorPage(
⋮----
Source: new SourceCard(Done: TempData[SourceDone] as string),
News: await NewsCard.ReadAsync(store, id, logger, cancellationToken)));
⋮----
public IActionResult New(bool typed = false)
⋮----
return View("Address", new CompetitorAddressPage(store.Storage, null, analyser.Model));
⋮----
return View("Edit", new CompetitorEditPage(
null, new CompetitorForm(), store.Storage, CompetitorEditPage.NoProblems, DraftOffered: drafts, DraftUnavailable: !analyser.IsConfigured));
⋮----
public async Task<IActionResult> Create([FromForm] CompetitorForm form)
⋮----
var page = new CompetitorEditPage(
null, form, store.Storage, CompetitorEditPage.NoProblems, Reading: ReadingNote.Of(form),
⋮----
var (profile, problems) = form.Parse(text);
⋮----
var now = clock.GetUtcNow();
var competitor = new Competitor
⋮----
Id = Guid.NewGuid(),
⋮----
profile.CopyProfileTo(competitor);
⋮----
var drafted = form.Stamp(now);
⋮----
CompetitorSave save;
⋮----
save = await store.AddAsync(competitor, sources, CancellationToken.None);
⋮----
logger.LogError(ex, "A competitor could not be added; nothing was written.");
⋮----
var extra = new Dictionary<string, string?> { ["sources"] = sources.Count.ToString(System.Globalization.CultureInfo.InvariantCulture) };
⋮----
public async Task<IActionResult> Edit(Guid id, CancellationToken cancellationToken)
⋮----
return View(new CompetitorEditPage(competitor, CompetitorForm.Of(competitor), store.Storage, CompetitorEditPage.NoProblems));
⋮----
public async Task<IActionResult> Edit(Guid id, [FromForm] CompetitorForm form, CancellationToken cancellationToken)
⋮----
var current = await store.FindAsync(id, cancellationToken);
⋮----
var page = new CompetitorEditPage(current, form, store.Storage, CompetitorEditPage.NoProblems);
⋮----
if (form.ReadVersion() is not { } version)
⋮----
save = await store.SaveAsync(id, version, profile, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "The competitor {Id} could not be saved; nothing was written.", id);
⋮----
Form = CompetitorForm.Of(colleague),
⋮----
Lost = form.Lost(colleague),
⋮----
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> DeleteConfirmed(Guid id, string? confirmName, CancellationToken cancellationToken)
⋮----
if (string.IsNullOrWhiteSpace(confirmName) || Competitor.NormaliseName(confirmName) != Competitor.NormaliseName(competitor.Name))
⋮----
deleted = await store.DeleteAsync(id, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "The competitor {Id} could not be deleted; nothing changed.", id);
⋮----
public async Task<IActionResult> DeletedCompetitors(Guid? restored, CancellationToken cancellationToken)
⋮----
rows = await store.DeletedAsync(cancellationToken);
back = restored is { } id ? await store.FindAsync(id, cancellationToken) : null;
⋮----
logger.LogError(ex, "The deleted competitors could not be read.");
⋮----
return DeletedView(new DeletedCompetitors(store.Storage, rows, back, unreadable), StatusCodes.Status200OK);
⋮----
public async Task<IActionResult> Restore(Guid id, CancellationToken cancellationToken)
⋮----
save = await store.RestoreAsync(id, CancellationToken.None);
⋮----
... (44 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Controllers/DraftsController.cs">
public sealed class DraftsController(
⋮----
ILogger<DraftsController> logger) : Controller
⋮----
public async Task<IActionResult> Read([FromForm] CompetitorAddressForm address, CancellationToken cancellationToken)
⋮----
: !Competitor.IsWebsite(typed) ? text["Competitors.Problem.NotAWebsite"].Value
: !CompetitorSource.IsAddress(typed) ? text["Competitors.Problem.NotPublic"].Value
⋮----
var refused = View(CompetitorsController.AddressViewPath, new CompetitorAddressPage(store.Storage, typed, drafting.Model, problem));
⋮----
var reading = await drafting.ReadAsync(new Uri(typed), cancellationToken);
⋮----
var form = new CompetitorForm { Website = typed };
⋮----
form = new CompetitorForm
⋮----
AnalysedAt = reading.At.ToString("O", CultureInfo.InvariantCulture),
ReadPages = reading.Site.PagesRead.Count.ToString(CultureInfo.InvariantCulture),
⋮----
Offered = Offers(reading).Select(offer => offer.Value).ToList(),
⋮----
return View(CompetitorsController.EditViewPath, new CompetitorEditPage(
⋮----
public async Task<IActionResult> Refresh(Guid id, CancellationToken cancellationToken)
⋮----
var competitor = await store.FindAsync(id, cancellationToken);
⋮----
var reading = CompetitorSource.IsAddress(competitor.Website)
? await drafting.ReadAsync(new Uri(competitor.Website), cancellationToken)
: new DraftReading(new SiteReading(SiteReadOutcome.Refused), null, false, [], clock.GetUtcNow());
await AuditAnalysedAsync(competitor.Id.ToString(), reading, FromRefresh);
⋮----
? RefreshForm.Of(competitor, reading.Analysis!, reading.Site, reading.WithoutPositioning, reading.At, Offers(reading))
⋮----
return RefreshView(new RefreshPage(store.Storage, competitor, form, Note(reading), sources, CompetitorEditPage.NoProblems), StatusCodes.Status200OK);
⋮----
public async Task<IActionResult> SaveRefresh(Guid id, [FromForm] RefreshForm form, CancellationToken cancellationToken)
⋮----
var current = await store.FindAsync(id, cancellationToken);
⋮----
var page = new RefreshPage(store.Storage, current, form, form.Note(), sources, CompetitorEditPage.NoProblems);
⋮----
if (form.ReadVersion() is not { } version)
⋮----
var taken = form.Taken();
var edit = CompetitorForm.Of(current);
⋮----
edit.Set(field, form.DraftOf(field));
⋮----
var (profile, problems) = edit.Parse(text);
⋮----
var now = clock.GetUtcNow();
CompetitorSave save;
⋮----
save = await store.SaveAsync(id, version, profile, SignedInAs, now, taken.Count > 0 ? form.Stamp(now) : null, CancellationToken.None);
⋮----
logger.LogError(ex, "The competitor {Id}'s refreshed analysis could not be saved; nothing was written.", id);
⋮----
await AuditAsync("competitors:edit", id.ToString(), new Dictionary<string, string?>
⋮----
["fields"] = string.Join(",", save.Changed),
⋮----
form.Version = colleague.Version.ToString(CultureInfo.InvariantCulture);
⋮----
public async Task<IActionResult> AddOfferedSource(Guid id, [FromForm] RefreshForm form, CancellationToken cancellationToken)
⋮----
var offer = OfferedSource.Parse(form.AddSource, kept: false);
SourceRequest added;
⋮----
added = new SourceRequest(SourceRequestOutcome.NotAKind);
⋮----
new RefreshPage(store.Storage, current, form, form.Note(), [], CompetitorEditPage.NoProblems, SourceProblem: text["Competitors.NoDatabase"]),
⋮----
added = await adder.AddAsync(id, offer.Kind.ToString(), offer.Address, SignedInAs, cancellationToken);
⋮----
logger.LogError(ex, "A source could not be added to the competitor {Id}; nothing was written.", id);
⋮----
new RefreshPage(store.Storage, current, form, form.Note(), await SourcesAsync(id, cancellationToken), CompetitorEditPage.NoProblems,
⋮----
var page = new RefreshPage(
store.Storage, current, form, form.Note(), await SourcesAsync(id, cancellationToken), CompetitorEditPage.NoProblems,
⋮----
internal static string SourceProblemText(IStringLocalizer<ConsoleResource> text, SourceRequestOutcome outcome) => outcome switch
⋮----
private static IEnumerable<OfferedSource> Offers(DraftReading reading) =>
reading.Found.Select(found => new OfferedSource(found.Kind, found.Address));
⋮----
private static ReadingNote Note(DraftReading reading) => new(
⋮----
private static string? NameOf(SiteReading site) =>
site.Name is { Length: > 0 } name ? (name.Length > Competitor.NameLength ? name[..Competitor.NameLength].TrimEnd() : name) : null;
⋮----
private static string? OrNull(string text) => text.Length == 0 ? null : text;
⋮----
private async Task<IReadOnlyList<CompetitorSource>> SourcesAsync(Guid id, CancellationToken cancellationToken)
⋮----
return await store.SourcesAsync(id, cancellationToken);
⋮----
logger.LogError(ex, "The sources of the competitor {Id} could not be read.", id);
... (19 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Controllers/NewsController.cs">
public sealed class NewsController(
⋮----
ILogger<NewsController> logger) : Controller
⋮----
public async Task<IActionResult> Index([FromQuery] NewsFeedQuery query, CancellationToken cancellationToken)
⋮----
if (!query.TryRead(out var competitorId, out var kind, out var irrelevant, out var cursor))
⋮----
competitors = await store.ListAsync(cancellationToken);
if (competitorId is { } id && competitors.All(competitor => competitor.Id != id))
⋮----
page = await store.FeedAsync(new NewsQuery { CompetitorId = competitorId, Kind = kind, Irrelevant = irrelevant, After = cursor }, cancellationToken);
⋮----
logger.LogError(ex, "The competitors' news could not be read.");
⋮----
var names = competitors.ToDictionary(competitor => competitor.Id, competitor => competitor.Name);
⋮----
.Where(item => names.ContainsKey(item.CompetitorId))
.Select(item => new NewsLine(item, names[item.CompetitorId]))
.ToList();
⋮----
return View(new NewsFeedPage(
⋮----
competitors.FirstOrDefault(competitor => competitor.Id == competitorId),
⋮----
MayWrite: (await authorization.AuthorizeAsync(User, ConsolePolicies.CompetitorsWrite)).Succeeded,
⋮----
public Task<IActionResult> Irrelevant(Guid itemId, [FromForm] NewsMarkForm form) => MarkAsync(itemId, irrelevant: true, form.ReturnUrl);
⋮----
public Task<IActionResult> Relevant(Guid itemId, [FromForm] NewsMarkForm form) => MarkAsync(itemId, irrelevant: false, form.ReturnUrl);
⋮----
private async Task<IActionResult> MarkAsync(Guid itemId, bool irrelevant, string? returnUrl)
⋮----
NewsMark mark;
⋮----
mark = await store.MarkNewsAsync(itemId, irrelevant, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "The news item {Item} could not be marked; nothing changed.", itemId);
⋮----
if (Request.Headers.Accept.ToString().Contains("application/json", StringComparison.Ordinal))
⋮----
return Redirect(returnUrl is not null && Url.IsLocalUrl(returnUrl) ? returnUrl : Url.Action(nameof(Index))!);
⋮----
private Task AuditAsync(string action, CompetitorNewsItem item) =>
auditLog.RecordAsync(
new AuditEntry(
⋮----
Target: item.CompetitorId.ToString(),
OccurredAt: clock.GetUtcNow(),
⋮----
["item"] = item.Id.ToString(),
["kind"] = item.Kind.ToString(),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Controllers/SettingsController.cs">
public sealed class SettingsController(
⋮----
ILogger<SettingsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(CancellationToken cancellationToken)
⋮----
/// <summary>
/// <em>Scan now</em> (#223): a manual scan started in the background, and the page it redirects to.
/// <c>409</c> with the card saying why when the model cannot be asked, there is nowhere to record it, or
/// a scan is running; audited <c>competitors:scan</c> with the scan's id once its row is written.
/// </summary>
⋮----
public async Task<IActionResult> ScanNow(CancellationToken cancellationToken)
⋮----
started = await scans.StartAsync(SignedInAs, CancellationToken.None);
⋮----
logger.LogError(ex, "A scan could not be started; nothing was recorded.");
⋮----
await AuditAsync("competitors:scan", started.Id.ToString(), new Dictionary<string, string?>
⋮----
public async Task<IActionResult> TestOllama(CancellationToken cancellationToken)
⋮----
var tested = await ollama.TestAsync(model, cancellationToken);
⋮----
["outcome"] = tested.Outcome.ToString(),
⋮----
public async Task<IActionResult> SavePositioning(string? statement, string? read, CancellationToken cancellationToken)
⋮----
var typed = PositioningStatement.Normalise(statement);
var asRead = PositioningStatement.Normalise(read);
⋮----
if (PositioningStatement.IsTooLong(typed))
⋮----
return Page(OllamaCardOf(), new PositioningCard(
⋮----
PositioningSave save;
⋮----
save = await positioning.SaveAsync(asRead, typed, SignedInAs, CancellationToken.None);
⋮----
logger.LogError(ex, "The positioning statement could not be saved; nothing was written.");
return Page(OllamaCardOf(), new PositioningCard(positioning.Storage, null, typed, asRead, Problem: text["Competitors.Positioning.NotSaved"]),
⋮----
["length"] = save.Current!.Text.Length.ToString(CultureInfo.InvariantCulture),
⋮----
return Page(OllamaCardOf(), PositioningCard.Of(positioning.Storage, theirs) with { Conflict = true, Typed = typed },
⋮----
private OllamaCard OllamaCardOf(OllamaTest? tested = null) => OllamaCard.Of(ollamaOptions.CurrentValue, options.CurrentValue, tested);
⋮----
private async Task<PositioningCard> PositioningCardAsync(CancellationToken cancellationToken)
⋮----
return PositioningCard.Of(positioning.Storage, await positioning.ReadAsync(cancellationToken));
⋮----
logger.LogError(ex, "The positioning statement could not be read.");
return PositioningCard.UnreadableIn(positioning.Storage);
⋮----
private async Task<StoredPositioning?> CurrentOrNullAsync(CancellationToken cancellationToken) =>
⋮----
private async Task<ScanCard> ScanCardAsync(CancellationToken cancellationToken)
⋮----
var card = new ScanCard(newsReader.IsConfigured, store.Storage, settings.At, settings.Zone.Id, Last: null, Running: scans.IsRunning);
⋮----
return card with { Last = await store.LastScanAsync(cancellationToken) };
⋮----
logger.LogError(ex, "The last scan could not be read.");
⋮----
private ViewResult Page(OllamaCard card, PositioningCard statement, ScanCard scan, int status = StatusCodes.Status200OK)
⋮----
var view = View(nameof(Index), new CompetitorSettingsPage(card, statement, scan));
⋮----
private Task AuditAsync(string action, string target, Dictionary<string, string?> details) =>
auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Controllers/SourcesController.cs">
public sealed class SourcesController(
⋮----
ILogger<SourcesController> logger) : Controller
⋮----
public async Task<IActionResult> Add(Guid id, [FromForm] SourceForm source, CancellationToken cancellationToken)
⋮----
var competitor = await store.FindAsync(id, cancellationToken);
⋮----
var typed = new SourceCard(kind, value);
⋮----
SourceRequest added;
⋮----
added = await adder.AddAsync(id, kind, value, SignedInAs, cancellationToken);
⋮----
logger.LogError(ex, "A source could not be added to the competitor {Id}; nothing was written.", id);
⋮----
competitor, typed with { Problem = DraftsController.SourceProblemText(text, added.Outcome) }, StatusCodes.Status400BadRequest, cancellationToken);
⋮----
public async Task<IActionResult> SetEnabled(Guid id, Guid sourceId, bool enabled, CancellationToken cancellationToken)
⋮----
if (await store.FindAsync(id, cancellationToken) is null)
⋮----
source = await store.SetSourceEnabledAsync(id, sourceId, enabled, CancellationToken.None);
⋮----
logger.LogError(ex, "The source {Source} of the competitor {Id} could not be changed; nothing was written.", sourceId, id);
⋮----
await AuditAsync("competitors:source-set", source.CompetitorId.ToString(), details);
⋮----
public async Task<IActionResult> Remove(Guid id, Guid sourceId, CancellationToken cancellationToken)
⋮----
removed = await store.RemoveSourceAsync(id, sourceId, CancellationToken.None);
⋮----
logger.LogError(ex, "The source {Source} of the competitor {Id} could not be removed; nothing changed.", sourceId, id);
⋮----
internal static Dictionary<string, string?> Details(CompetitorSource source) => new()
⋮----
["source"] = source.Id.ToString(),
["kind"] = source.Kind.ToString(),
⋮----
private RedirectToActionResult RedirectToCard(Guid id) =>
⋮----
private async Task<IActionResult> DetailsAsync(Competitor competitor, SourceCard card, int status, CancellationToken cancellationToken)
⋮----
sources = await store.SourcesAsync(competitor.Id, cancellationToken);
⋮----
logger.LogError(ex, "The sources of the competitor {Id} could not be read.", competitor.Id);
⋮----
var view = View(CompetitorsController.DetailsViewPath, new CompetitorPage(
⋮----
MayConfigure: (await authorization.AuthorizeAsync(User, ConsolePolicies.CompetitorsConfigure)).Succeeded,
⋮----
News: await NewsCard.ReadAsync(store, competitor.Id, logger, cancellationToken)));
⋮----
private Task AuditAsync(string action, CompetitorSource source) =>
AuditAsync(action, source.CompetitorId.ToString(), Details(source));
⋮----
private Task AuditAsync(string action, string target, Dictionary<string, string?> details) =>
auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Models/CompetitorForm.cs">
public sealed class CompetitorForm
⋮----
public DraftStamp? Stamp(DateTimeOffset now)
⋮----
if (!IsDraft || string.IsNullOrWhiteSpace(AnalysedModel))
⋮----
var model = AnalysedModel.Trim();
⋮----
var at = DateTimeOffset.TryParse(AnalysedAt, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var read) && read <= now
⋮----
return new DraftStamp(model, at);
⋮----
public IReadOnlyList<OfferedSource> OfferedSources() =>
Offered.Select(value => OfferedSource.Parse(value, Keep.Contains(value)))
⋮----
.DistinctBy(source => source.Value)
.ToList();
⋮----
public IReadOnlyList<OfferedSource> KeptSources() =>
Keep.Select(value => OfferedSource.Parse(value, kept: true))
⋮----
.DistinctBy(source => CompetitorSource.NormaliseAddress(source.Address))
⋮----
public static CompetitorForm Of(Competitor competitor) => new()
⋮----
Version = competitor.Version.ToString(CultureInfo.InvariantCulture),
⋮----
public uint? ReadVersion() =>
uint.TryParse(Version, NumberStyles.None, CultureInfo.InvariantCulture, out var version) ? version : null;
⋮----
public string? TextOf(string field) => field switch
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Not a competitor's field."),
⋮----
public void Set(string field, string? value)
⋮----
default: throw new ArgumentOutOfRangeException(nameof(field), field, "Not a competitor's field.");
⋮----
public (Competitor? Profile, IReadOnlyDictionary<string, string> Problems) Parse(IStringLocalizer<ConsoleResource> text)
⋮----
var profile = new Competitor();
⋮----
else if (!Competitor.IsWebsite(website))
⋮----
else if (!Competitor.IsOneLine(summary))
⋮----
return string.IsNullOrEmpty(trimmed) ? null : trimmed;
⋮----
public IReadOnlyList<string> Lost(Competitor colleague) =>
⋮----
.Where(field => !string.Equals(Normalised(TextOf(field)), Normalised(colleague.TextOf(field)), StringComparison.Ordinal))
⋮----
private static string? Normalised(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Models/CompetitorPages.cs">
public static class CompetitorFieldNames
⋮----
public static string LabelKey(string field) => $"Competitors.Field.{Suffix(field)}";
⋮----
public static string HintKey(string field) => $"Competitors.Hint.{Suffix(field)}";
⋮----
public static string InputName(string field) => Suffix(field);
⋮----
private static string Suffix(string field) => field switch
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Not a competitor's field."),
⋮----
public DateTimeOffset? LatestOf(Guid competitorId) =>
Latest is not null && Latest.TryGetValue(competitorId, out var latest) ? latest : null;
⋮----
public static readonly NewsCard None = new([], false);
⋮----
public static async Task<NewsCard> ReadAsync(ICompetitorStore store, Guid competitorId, ILogger logger, CancellationToken cancellationToken)
⋮----
var page = await store.FeedAsync(new NewsQuery { CompetitorId = competitorId, Take = NewsFeed.CardSize }, cancellationToken);
return new NewsCard(page.Items, More: page.Next is not null);
⋮----
logger.LogError(ex, "The news of the competitor {Id} could not be read.", competitorId);
return new NewsCard([], false, Unreadable: true);
⋮----
public string Date => Item.SortAt.UtcDateTime.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
⋮----
public string Found => Item.FoundAt.UtcDateTime.ToString("yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " UTC";
⋮----
public static class NewsKindNames
⋮----
public static string LabelKey(NewsKind kind) => $"Competitors.News.Kind.{kind}";
⋮----
public static string Badge(NewsKind kind) => kind switch
⋮----
public Dictionary<string, string> Route(bool irrelevant, NewsCursor? cursor = null)
⋮----
route[NewsFeedQuery.CompetitorKey] = Competitor.Id.ToString("D", System.Globalization.CultureInfo.InvariantCulture);
⋮----
route[NewsFeedQuery.KindKey] = kind.ToString();
⋮----
public sealed class NewsFeedQuery
⋮----
public bool TryRead(out Guid? competitor, out NewsKind? kind, out bool irrelevant, out NewsCursor? cursor)
⋮----
if (!string.IsNullOrEmpty(Competitor))
⋮----
if (!Guid.TryParse(Competitor, out var id))
⋮----
if (!string.IsNullOrEmpty(Kind))
⋮----
var name = Enum.GetNames<NewsKind>().FirstOrDefault(each => string.Equals(each, Kind, StringComparison.OrdinalIgnoreCase));
⋮----
return NewsCursor.TryParse(Before, Id, out cursor);
⋮----
public sealed class NewsMarkForm
⋮----
public static readonly SourceCard None = new();
⋮----
public string? Host => Uri.TryCreate(Address, UriKind.Absolute, out var uri) ? uri.IdnHost : null;
⋮----
public static OfferedSource? Parse(string? value, bool kept)
⋮----
var address = value![(bar + 1)..].Trim();
⋮----
nameof(CompetitorSourceKind.Feed) when CompetitorSource.IsAddress(address) => new(CompetitorSourceKind.Feed, address, kept),
nameof(CompetitorSourceKind.Page) when CompetitorSource.IsAddress(address) => new(CompetitorSourceKind.Page, address, kept),
⋮----
public static ReadingNote? Of(CompetitorForm form) => form.IsDraft
⋮----
int.TryParse(form.ReadPages, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var pages) ? pages : 0,
⋮----
public sealed class CompetitorAddressForm
⋮----
public sealed class SourceForm
⋮----
public IReadOnlyList<OfferedSource> Offered => Form.OfferedSources();
⋮----
public string? ProblemOf(string field) => Problems.GetValueOrDefault(field);
⋮----
public string? LostText(string field) =>
Typed is not null && Lost is not null && Lost.Contains(field) ? Typed.TextOf(field) : null;
⋮----
public sealed class RefreshForm
⋮----
public static RefreshForm Of(Competitor competitor, CompetitorAnalysis analysis, SiteReading site, bool withoutPositioning, DateTimeOffset at, IEnumerable<OfferedSource> offered) => new()
⋮----
Version = competitor.Version.ToString(System.Globalization.CultureInfo.InvariantCulture),
⋮----
AnalysedAt = at.ToString("O", System.Globalization.CultureInfo.InvariantCulture),
ReadPages = site.PagesRead.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
⋮----
Draft = CompetitorDraft.Fields.ToDictionary(field => field, field => (string?)analysis.Draft!.TextOf(field), StringComparer.Ordinal),
Choice = CompetitorDraft.Fields.ToDictionary(field => field, _ => (string?)Keep, StringComparer.Ordinal),
Offered = offered.Select(source => source.Value).ToList(),
⋮----
public uint? ReadVersion() =>
uint.TryParse(Version, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var version) ? version : null;
⋮----
public string DraftOf(string field) => (Draft.GetValueOrDefault(field) ?? string.Empty).Replace("\r\n", "\n").Trim();
... (22 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Models/CompetitorSettings.cs">
public static OllamaCard Of(OllamaOptions ollama, CompetitorsOptions competitors, OllamaTest? tested = null) => new(
KeyConfigured: !string.IsNullOrWhiteSpace(ollama.ApiKey),
⋮----
.Where(setting => !setting.Configured)
.Select(setting => setting.Setting)
.ToList();
⋮----
public static PositioningCard Of(FeatureStateStorage storage, StoredPositioning? current) =>
⋮----
public static PositioningCard UnreadableIn(FeatureStateStorage storage) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/ViewComponents/CompetitorsOverviewViewComponent.cs">
public sealed class CompetitorsOverviewViewComponent(
⋮----
ILogger<CompetitorsOverviewViewComponent> logger) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync()
⋮----
if (!(await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.CompetitorsView)).Succeeded)
⋮----
var mayConfigure = (await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.CompetitorsConfigure)).Succeeded;
⋮----
CompetitorsOverview overview;
⋮----
var rows = await store.ListAsync(cancellationToken);
var names = rows.ToDictionary(row => row.Id, row => row.Name);
⋮----
var now = clock.GetUtcNow();
var monday = NewsFeed.WeekStart(now);
var week = new NewsQuery { FoundFrom = monday, FoundBefore = monday.AddDays(7), Take = NewsFeed.OverviewLines };
var newest = await store.FeedAsync(week, cancellationToken);
var count = await store.CountNewsAsync(week, cancellationToken);
⋮----
var last = await store.LastScanAsync(cancellationToken);
⋮----
var scheduledToday = await store.ScheduledScanSinceAsync(options.StartOf(options.DayOf(now)), cancellationToken);
health = ScanHealth.Of(last, runner.IsRunning, scheduledToday, now, options);
⋮----
overview = new CompetitorsOverview(
⋮----
rows.OrderByDescending(row => row.UpdatedAt).ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase).Take(RecentCount).ToList(),
⋮----
WeekNewest: newest.Items.Where(item => names.ContainsKey(item.CompetitorId)).Select(item => new NewsLine(item, names[item.CompetitorId])).ToList(),
⋮----
logger.LogError(ex, "The overview could not read the competitors.");
overview = new CompetitorsOverview(store.Storage, 0, [], Unreadable: true);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Address.cshtml">
@model CompetitorAddressPage
@*
    Add a competitor from its website (#222): one field, the address. Read the site fetches it and has
    the model draft the profile into the form that follows; nothing is saved until that form is.
    Type it instead opens the blank form.
*@

@section PageScripts {
    <script src="~/js/competitors-reading.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-controller="Competitors" asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Competitors"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Competitors.New.Title"]</h5>
        <p class="text-body mb-0">@T["Competitors.Address.Lead"]</p>
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

<form method="post" asp-controller="Drafts" asp-action="Read" class="card mb-4" novalidate id="competitor-address-form" data-competitors-reading>
    <div class="card-body">
        <label class="form-label" for="competitor-address">@T["Competitors.Field.Website"]</label>
        <input type="url" class="form-control form-control-lg@(Model.Problem is null ? "" : " is-invalid")" id="competitor-address" name="Website"
               value="@Model.Website" maxlength="@Competitor.WebsiteLength" required autocomplete="off" spellcheck="false" placeholder="https://" autofocus />
        <div class="form-text">@T["Competitors.Address.Hint"]</div>
        <div class="invalid-feedback" id="competitor-address-problem">@Model.Problem</div>

        <div class="d-none mt-3" role="status" data-competitors-reading-status>
            <span class="spinner-border spinner-border-sm me-2" aria-hidden="true"></span>@T["Competitors.Address.Reading"]
        </div>

        <p class="small text-body-secondary mt-3 mb-0">@T["Competitors.Address.Privacy", Model.Model ?? string.Empty]</p>
    </div>
    <div class="card-footer d-flex flex-wrap gap-2">
        <button type="submit" class="btn btn-primary" id="competitor-read">
            <i class="ti ti-world-search me-1" aria-hidden="true"></i>@T["Competitors.Address.Read"]
        </button>
        <a asp-controller="Competitors" asp-action="New" asp-route-typed="true" class="btn btn-label-secondary" id="competitor-type-instead">@T["Competitors.Address.TypeInstead"]</a>
    </div>
</form>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Delete.cshtml">
@model CompetitorDeletion
@{
    var competitor = Model.Competitor;
}

<div class="mb-4">
    <a asp-action="Details" asp-route-id="@competitor.Id" class="text-body"><i class="ti ti-arrow-left me-1"></i>@competitor.Name</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Competitors.Delete.Heading", competitor.Name]</h5>
        <p class="mb-0">@T["Competitors.Delete.Lead"]</p>
    </div>
</div>

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="competitor-delete-problem">@problem</div>
}

<div class="row g-4">
    <div class="col-12 col-lg-5">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Competitors.Delete.TheCompetitor"]</h6>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-5">@T["Competitors.Field.Name"]</dt>
                    <dd class="col-7">@competitor.Name</dd>
                    <dt class="col-5">@T["Competitors.Field.Summary"]</dt>
                    <dd class="col-7">@competitor.Summary</dd>
                    <dt class="col-5">@T["Competitors.Field.Website"]</dt>
                    <dd class="col-7 text-break">@competitor.Website</dd>
                    <dt class="col-5">@T["Competitors.Delete.AddedBy"]</dt>
                    <dd class="col-7 mb-0">@competitor.CreatedBy, @competitor.CreatedAt.UtcDateTime.ToString("yyyy-MM-dd")</dd>
                </dl>
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-7">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Competitors.Delete.WhatItDoes"]</h6>
            </div>
            <div class="card-body">
                <p>@T["Competitors.Delete.Detail", Html.Raw($"<strong>{Html.Encode(Model.SignedInAs)}</strong>")]</p>
                <form method="post" asp-action="DeleteConfirmed" asp-route-id="@competitor.Id">
                    <div class="mb-3">
                        <label class="form-label" for="competitor-delete-name">@T["Competitors.Delete.TypeName", Html.Raw($"<strong>{Html.Encode(competitor.Name)}</strong>")]</label>
                        <input type="text" class="form-control" id="competitor-delete-name" name="confirmName" required autocomplete="off" spellcheck="false" />
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-danger">@T["Competitors.Delete.Submit"]</button>
                        <a asp-action="Details" asp-route-id="@competitor.Id" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Deleted.cshtml">
@model DeletedCompetitors
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
}

<div class="mb-4">
    <a asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Competitors"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Competitors.Deleted.Title"]</h5>
        <p class="mb-0">@T["Competitors.Deleted.Lead"]</p>
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

@if (Model.Unreadable)
{
    <div class="alert alert-danger" role="alert">@T["Competitors.Deleted.Unreadable"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="competitors-restore-problem">@problem</div>
}

@if (Model.Restored is { } restored)
{
    <div class="alert alert-success" role="status" id="competitors-restored">
        @T["Competitors.Deleted.Restored", Html.Raw($"<a href=\"{Url.Action("Details", new { id = restored.Id })}\">{Html.Encode(restored.Name)}</a>")]
    </div>
}

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">@(Model.Rows.Count == 1 ? T["Competitors.Deleted.Count.One"] : T["Competitors.Deleted.Count.Many", Model.Rows.Count])</h5>
    </div>
    @if (Model.Rows.Count == 0)
    {
        <div class="card-body pt-0">
            <p class="mb-0 text-body-secondary">@T["Competitors.Deleted.Empty"]</p>
        </div>
    }
    else
    {
        <div class="table-responsive">
            <table class="table table-sm mb-0" id="competitors-deleted-list">
                <thead>
                    <tr>
                        <th>@T["Competitors.Field.Name"]</th>
                        <th>@T["Competitors.Field.Summary"]</th>
                        <th>@T["Competitors.Deleted.DeletedBy"]</th>
                        <th>@T["Competitors.Deleted.DeletedAt"]</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var competitor in Model.Rows)
                    {
                        <tr data-competitor="@competitor.Id">
                            <td class="fw-medium">@competitor.Name</td>
                            <td>@competitor.Summary</td>
                            <td>@competitor.DeletedBy</td>
                            <td class="text-nowrap">@Instant(competitor.DeletedAt!.Value)</td>
                            <td class="text-end text-nowrap">
                                <a asp-area="" asp-controller="Audit" asp-action="Index" asp-route-target="@competitor.Id" class="me-2 small">@T["Menu.Audit"]</a>
                                <form method="post" asp-action="Restore" asp-route-id="@competitor.Id" class="d-inline">
                                    <button type="submit" class="btn btn-sm btn-outline-primary">@T["Competitors.Deleted.Restore"]</button>
                                </form>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Details.cshtml">
@model CompetitorPage

@section PageScripts {
    <script src="~/js/competitors-reading.js" asp-append-version="true"></script>
    <script src="~/js/competitor-news.js" asp-append-version="true"></script>
}

@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var competitor = Model.Competitor;
    var news = Model.News ?? NewsCard.None;
    var newsLines = new NewsLines(
        news.Items.Select(item => new NewsLine(item, competitor.Name)).ToList(),
        ShowCompetitor: false,
        MayMark: Model.MayWrite && Model.CanChange,
        ReturnUrl: Context.Request.Path + Context.Request.QueryString,
        Empty: T["Competitors.News.Card.Empty"].Value);
}

<div class="mb-4">
    <a asp-controller="Competitors" asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Competitors"]</a>
</div>

<div class="card mb-4" id="competitor-heading">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-start gap-3">
        <div>
            <h5 class="card-title mb-1">@competitor.Name</h5>
            <p class="text-body mb-1">@competitor.Summary</p>
            <a href="@competitor.Website" target="_blank" rel="noopener noreferrer" class="text-break" id="competitor-website">
                <i class="ti ti-external-link me-1" aria-hidden="true"></i>@competitor.Website
            </a>
        </div>
        @if (Model.MayWrite && Model.CanChange)
        {
            <div class="d-flex flex-wrap gap-2">
                @if (Model.MayRefresh)
                {
                    @* Refresh analysis (#222, decision 8): the site read again, the new draft shown beside the current values. Writes nothing. *@
                    <form method="post" asp-controller="Drafts" asp-action="Refresh" asp-route-id="@competitor.Id" class="d-inline" id="competitor-refresh-form" data-competitors-reading>
                        <button type="submit" class="btn btn-label-primary text-nowrap" id="competitor-refresh">
                            <i class="ti ti-refresh me-1" aria-hidden="true"></i>@T["Competitors.Refresh"]
                        </button>
                    </form>
                }
                <a asp-controller="Competitors" asp-action="Edit" asp-route-id="@competitor.Id" class="btn btn-primary text-nowrap" id="competitor-edit">
                    <i class="ti ti-pencil me-1" aria-hidden="true"></i>@T["Competitors.Edit"]
                </a>
            </div>
        }
    </div>
    <div class="card-body pt-0">
        <p class="small text-body mb-0">
            @T["Competitors.Details.Edited", competitor.UpdatedBy, Instant(competitor.UpdatedAt)]
            · @T["Competitors.Details.Added", competitor.CreatedBy, Instant(competitor.CreatedAt)]
        </p>
        @if (competitor.AnalysedAt is { } analysedAt)
        {
            <p class="small text-body mt-1 mb-0" id="competitor-analysed">@T["Competitors.Details.Analysed", competitor.AnalysedModel ?? string.Empty, Instant(analysedAt)]</p>
        }
        @if (Model.MayWrite && Model.CanChange && Model.MayRefresh)
        {
            <div class="small text-body mt-1 d-none" role="status" data-competitors-reading-status>
                <span class="spinner-border spinner-border-sm me-2" aria-hidden="true"></span>@T["Competitors.Refresh.Reading"]
            </div>
        }
        @if (!Model.MayWrite)
        {
            <p class="small text-body mt-1 mb-0">@T["Competitors.Details.ViewOnly", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.CompetitorsWrite))}</strong>")]</p>
        }
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

@if (Model.Saved)
{
    <div class="alert alert-success" role="status" id="competitor-saved">@T["Competitors.Details.Saved"]</div>
}

@* The profile (#220), each field a card shown whole, in English whatever the page's language (#219, decision 7). *@
<div class="row g-4 mb-4" id="competitor-profile">
    @foreach (var field in Competitor.ProfileFields)
    {
        var value = competitor.TextOf(field);
        <div class="col-12 col-lg-6">
            <div class="card h-100" data-field="@field">
                <div class="card-header pb-2">
                    <h6 class="card-title mb-0">@T[CompetitorFieldNames.LabelKey(field)]</h6>
                </div>
                <div class="card-body pt-0">
                    @if (string.IsNullOrEmpty(value))
                    {
                        <p class="text-body-secondary mb-0 fst-italic">@T["Competitors.Details.NotWritten"]</p>
                    }
                    else
                    {
                        <p class="mb-0 text-break" style="white-space: pre-line">@value</p>
                    }
                </div>
... (49 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Edit.cshtml">
@model CompetitorEditPage
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var form = Model.Form;
    var current = Model.Current;

    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";
    string Id(string field) => "competitor-" + field.Replace('_', '-');
}

<div class="mb-4">
    @if (current is null)
    {
        <a asp-controller="Competitors" asp-action="Index" class="text-body" id="competitor-back"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Competitors"]</a>
    }
    else
    {
        <a asp-controller="Competitors" asp-action="Details" asp-route-id="@current.Id" class="text-body" id="competitor-back"><i class="ti ti-arrow-left me-1"></i>@current.Name</a>
    }
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@(Model.IsNew ? T["Competitors.New.Title"] : T["Competitors.Edit.Title", current!.Name])</h5>
        <p class="text-body mb-0">@T["Competitors.Form.Lead"]</p>
        @if (current is not null)
        {
            <p class="small text-body mt-2 mb-0">@T["Competitors.Details.Edited", current.UpdatedBy, Instant(current.UpdatedAt)]</p>
        }
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

@* What reading the site came to (#222): the draft below, or why the form is empty. *@
@if (Model.Reading is { } reading)
{
    <partial name="_Reading" model="reading" />
    @if (!reading.Drafted)
    {
        <p class="text-body mb-4" id="competitor-type-it">@T["Competitors.Reading.TypeIt"]</p>
    }
}
else if (Model.IsNew && Model.DraftOffered)
{
    <p class="mb-4"><a asp-controller="Competitors" asp-action="New" id="competitor-read-instead"><i class="ti ti-world-search me-1" aria-hidden="true"></i>@T["Competitors.Address.ReadInstead"]</a></p>
}
else if (Model.IsNew && Model.DraftUnavailable)
{
    <div class="alert alert-secondary" role="status" id="competitor-draft-unavailable">@T["Competitors.Address.Unavailable"]</div>
}

@if (Model.Conflict is { } conflict)
{
    <div class="alert alert-danger" role="alert" id="competitor-conflict">
        <h6 class="alert-heading mb-1">@T["Competitors.Conflict.Title"]</h6>
        <p class="mb-1">@T["Competitors.Conflict", conflict.UpdatedBy, Instant(conflict.UpdatedAt)]</p>
        @if (Model.Lost is { Count: > 0 } lost)
        {
            <p class="mb-0">@T["Competitors.Conflict.Lost", string.Join(", ", lost.Select(field => S[CompetitorFieldNames.LabelKey(field)].Value))]</p>
        }
    </div>
}

@if (Model.Deleted)
{
    <div class="alert alert-danger" role="alert" id="competitor-gone">@T["Competitors.Form.Deleted"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="competitor-problem">@problem</div>
}

@if (Model.Problems.Count > 0)
{
    <div class="alert alert-danger" role="alert" id="competitor-problems">
        @T["Competitors.Form.Problems"]
        @if (Model.NameTaken is { } other)
        {
            <a asp-controller="Competitors" asp-action="Details" asp-route-id="@other.Id" class="ms-1" id="competitor-name-taken">@other.Name</a>
        }
    </div>
}

@{
    var action = Model.IsNew ? "Create" : "Edit";
}

<form method="post" asp-controller="Competitors" asp-action="@action" asp-route-id="@(current?.Id)" class="card mb-4" novalidate id="competitor-form">
    @if (!Model.IsNew)
    {
        <input type="hidden" name="Version" value="@form.Version" />
    }

    @* A draft's reading (#222), carried to the save: which model made it and when, and the sources it offered. *@
    @if (Model.IsNew && form.IsDraft)
    {
        <input type="hidden" name="From" value="@form.From" />
... (98 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Index.cshtml">
@model CompetitorList
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
}

<div class="card mb-4">
    <div class="card-body d-flex flex-wrap justify-content-between align-items-start gap-3">
        <div>
            <h5 class="card-title mb-2">@T["Menu.Competitors"]</h5>
            <p class="text-body mb-0">@T["Competitors.List.Lead"]</p>
        </div>
        <div class="d-flex flex-wrap gap-2">
            @if (Model.MayConfigure)
            {
                <a asp-action="DeletedCompetitors" class="btn btn-label-secondary text-nowrap" id="competitors-deleted-link">
                    <i class="ti ti-trash me-1" aria-hidden="true"></i>@T["Competitors.Deleted.Title"]
                </a>
            }
            @if (Model.MayWrite && Model.CanChange)
            {
                <a asp-action="New" class="btn btn-primary text-nowrap" id="competitors-add">
                    <i class="ti ti-plus me-1" aria-hidden="true"></i>@T["Competitors.Add"]
                </a>
            }
        </div>
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

@if (Model.Deleted is { } deleted)
{
    <div class="alert alert-success" role="status" id="competitors-deleted">
        @(Model.MayConfigure ? T["Competitors.List.Deleted.Restorable", deleted] : T["Competitors.List.Deleted", deleted])
    </div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-danger" role="alert">@T["Competitors.Unreadable"]</div>
}

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">@(Model.Rows.Count == 1 ? T["Competitors.Count.One"] : T["Competitors.Count.Many", Model.Rows.Count])</h5>
    </div>
    @if (Model.Rows.Count == 0)
    {
        <div class="card-body pt-0">
            <p class="mb-0 text-body-secondary" id="competitors-empty">
                @(Model.MayWrite && Model.CanChange ? T["Competitors.List.Empty.Write"] : T["Competitors.List.Empty"])
            </p>
        </div>
    }
    else
    {
        <div class="table-responsive">
            <table class="table mb-0" id="competitors-list">
                <thead>
                    <tr>
                        <th>@T["Competitors.Field.Name"]</th>
                        <th>@T["Competitors.Field.Summary"]</th>
                        <th>@T["Competitors.Field.Website"]</th>
                        <th class="text-nowrap">@T["Competitors.List.LatestNews"]</th>
                        <th class="text-nowrap">@T["Competitors.List.LastEdited"]</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var competitor in Model.Rows)
                    {
                        <tr data-competitor="@competitor.Id">
                            <td class="fw-medium text-nowrap">
                                <a asp-action="Details" asp-route-id="@competitor.Id">@competitor.Name</a>
                            </td>
                            <td>@competitor.Summary</td>
                            <td class="text-break">
                                <a href="@competitor.Website" target="_blank" rel="noopener noreferrer">@competitor.Website</a>
                            </td>
                            @* Its newest item's date (#224), linking to the feed filtered to it. *@
                            <td class="text-nowrap small" data-latest-news>
                                @if (Model.LatestOf(competitor.Id) is { } latest)
                                {
                                    <a asp-controller="News" asp-action="Index" asp-route-competitor="@competitor.Id">@latest.UtcDateTime.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)</a>
                                }
                                else
                                {
                                    <span class="text-body-secondary">@T["Competitors.List.NoNews"]</span>
                                }
                            </td>
                            <td class="text-nowrap small" title="@competitor.UpdatedBy">@Instant(competitor.UpdatedAt)</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Competitors/Refresh.cshtml">
@model RefreshPage
@*
    Refresh analysis (#222, decision 8): the competitor's site read again and drafted, each field's
    current value beside the draft, Keep or Take the draft, saved whole as one edit with the version the
    competitor was read at. A field kept is never touched. New feeds and pages are offered an Add each,
    never added silently; an Add keeps the draft on the page.
*@
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var current = Model.Current;
    var form = Model.Form;
    var offered = Model.Offered;
}

<div class="mb-4">
    <a asp-controller="Competitors" asp-action="Details" asp-route-id="@current.Id" class="text-body" id="competitor-back"><i class="ti ti-arrow-left me-1"></i>@current.Name</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Competitors.Refresh.Title", current.Name]</h5>
        <p class="text-body mb-0">@T["Competitors.Refresh.Lead"]</p>
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

<partial name="_Reading" model="Model.Reading" />

@if (form is null)
{
    <p class="text-body mb-3" id="competitor-refresh-unchanged">@T["Competitors.Refresh.NothingChanged"]</p>
    <a asp-controller="Competitors" asp-action="Details" asp-route-id="@current.Id" class="btn btn-label-secondary">@T["Competitors.Refresh.Back"]</a>
    return;
}

@if (Model.Conflict is { } conflict)
{
    <div class="alert alert-danger" role="alert" id="competitor-conflict">
        <h6 class="alert-heading mb-1">@T["Competitors.Conflict.Title"]</h6>
        <p class="mb-0">@T["Competitors.Refresh.Conflict", conflict.UpdatedBy, Instant(conflict.UpdatedAt)]</p>
    </div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert" id="competitor-problem">@problem</div>
}

@if (Model.Problems.Count > 0)
{
    <div class="alert alert-danger" role="alert" id="competitor-problems">
        @T["Competitors.Form.Problems"]
        @if (Model.NameTaken is { } other)
        {
            <a asp-controller="Competitors" asp-action="Details" asp-route-id="@other.Id" class="ms-1" id="competitor-name-taken">@other.Name</a>
        }
    </div>
}

<form method="post" asp-controller="Drafts" asp-action="SaveRefresh" asp-route-id="@current.Id" novalidate id="competitor-refresh-save">
    <input type="hidden" name="Version" value="@form.Version" />
    <input type="hidden" name="AnalysedModel" value="@form.AnalysedModel" />
    <input type="hidden" name="AnalysedAt" value="@form.AnalysedAt" />
    <input type="hidden" name="ReadPages" value="@form.ReadPages" />
    <input type="hidden" name="WithoutPositioning" value="@form.WithoutPositioning" />
    @foreach (var field in CompetitorDraft.Fields)
    {
        <input type="hidden" name="Draft[@field]" value="@form.DraftOf(field)" />
    }
    @foreach (var source in form.OfferedSources())
    {
        <input type="hidden" name="Offered" value="@source.Value" />
    }

    <div class="card mb-4" id="competitor-refresh-fields">
        <ul class="list-group list-group-flush">
            @* The columns' headings, on a wide screen; on a narrow one each value is labelled where it is. *@
            <li class="list-group-item d-none d-lg-block py-3" aria-hidden="true">
                <div class="row g-3">
                    <div class="col-lg-6"><span class="fw-medium text-heading">@T["Competitors.Refresh.Now"]</span></div>
                    <div class="col-lg-6"><span class="fw-medium text-heading">@T["Competitors.Refresh.Draft"]</span></div>
                </div>
            </li>
            @foreach (var field in CompetitorDraft.Fields)
            {
                var now = current.TextOf(field);
                var draft = form.DraftOf(field);
                var differs = Model.Differs(field);
                var id = "refresh-" + field.Replace('_', '-');
                <li class="list-group-item py-3" data-field="@field" data-differs="@(differs ? "true" : "false")">
                    <h6 class="mb-2">@T[CompetitorFieldNames.LabelKey(field)]</h6>
                    <div class="row g-3">
                        <div class="col-12 col-lg-6">
                            <div class="small text-body-secondary d-lg-none mb-1">@T["Competitors.Refresh.Now"]</div>
                            @if (string.IsNullOrEmpty(now))
                            {
                                <p class="text-body-secondary fst-italic mb-0">@T["Competitors.Details.NotWritten"]</p>
                            }
... (86 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/News/Index.cshtml">
@model NewsFeedPage

@section PageScripts {
    <script src="~/js/competitor-news.js" asp-append-version="true"></script>
}

@{
    var empty = Model.Irrelevant
        ? T["Competitors.News.Empty.Irrelevant"].Value
        : Model.Competitor is not null || Model.Kind is not null
            ? T["Competitors.News.Empty.Filtered"].Value
            : T["Competitors.News.Empty"].Value;
    var lines = new NewsLines(Model.Lines, ShowCompetitor: true, MayMark: Model.MayWrite && Model.CanChange, Model.ReturnUrl, empty);
}

@* The global news feed (#224): the live competitors' items, newest first, 25 a page, More by keyset. *@
<div class="card mb-4">
    <div class="card-body d-flex flex-wrap justify-content-between align-items-start gap-3">
        <div style="max-width: 40rem">
            <h5 class="card-title mb-2">@T["Menu.Competitors.News"]</h5>
            <p class="text-body mb-0">@T["Competitors.News.Lead"]</p>
        </div>
        <div class="d-flex flex-wrap align-items-center gap-2">
            <form method="get" asp-action="Index" class="d-flex flex-wrap gap-2 align-items-center" id="competitors-news-filter">
                @if (Model.Irrelevant)
                {
                    <input type="hidden" name="@NewsFeedQuery.IrrelevantKey" value="true" />
                }
                <select name="@NewsFeedQuery.CompetitorKey" class="form-select form-select-sm w-auto" aria-label="@T["Competitors.News.Filter.Competitor"].Value" data-submit-on-change id="competitors-news-competitor">
                    <option value="">@T["Competitors.News.Filter.AnyCompetitor"]</option>
                    @foreach (var competitor in Model.Competitors)
                    {
                        <option value="@competitor.Id" selected="@(competitor.Id == Model.Competitor?.Id)">@competitor.Name</option>
                    }
                </select>
                <select name="@NewsFeedQuery.KindKey" class="form-select form-select-sm w-auto" aria-label="@T["Competitors.News.Filter.Kind"].Value" data-submit-on-change id="competitors-news-kind">
                    <option value="">@T["Competitors.News.Filter.AnyKind"]</option>
                    @foreach (var kind in Enum.GetValues<NewsKind>())
                    {
                        <option value="@kind" selected="@(kind == Model.Kind)">@T[NewsKindNames.LabelKey(kind)]</option>
                    }
                </select>
                <noscript><button type="submit" class="btn btn-sm btn-label-secondary">@T["Competitors.News.Filter.Apply"]</button></noscript>
            </form>
            @if (Model.Irrelevant)
            {
                <a asp-action="Index" asp-all-route-data="Model.Route(irrelevant: false)" class="btn btn-sm btn-label-primary text-nowrap" id="competitors-news-relevant">
                    <i class="ti ti-arrow-left me-1" aria-hidden="true"></i>@T["Competitors.News.ShowRelevant"]
                </a>
            }
            else
            {
                <a asp-action="Index" asp-all-route-data="Model.Route(irrelevant: true)" class="btn btn-sm btn-label-secondary text-nowrap" id="competitors-news-irrelevant">
                    <i class="ti ti-eye-off me-1" aria-hidden="true"></i>@T["Competitors.News.ShowIrrelevant"]
                </a>
            }
        </div>
    </div>
</div>

<partial name="_Storage" model="Model.Storage" />

@if (Model.Done is "Irrelevant" or "Relevant")
{
    <div class="alert alert-success" role="status" id="competitors-news-done">@T[$"Competitors.News.Done.{Model.Done}"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-danger" role="alert" id="competitors-news-unreadable">@T["Competitors.News.Unreadable"]</div>
}

<div class="card" id="competitors-news">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <h5 class="card-title mb-0">
            @(Model.Irrelevant ? T["Competitors.News.Heading.Irrelevant"] : T["Competitors.News.Heading"])
            @if (Model.Competitor is not null)
            {
                <span class="text-body fw-normal">· <a asp-controller="Competitors" asp-action="Details" asp-route-id="@Model.Competitor.Id">@Model.Competitor.Name</a></span>
            }
        </h5>
        @if (Model.Later)
        {
            <a asp-action="Index" asp-all-route-data="Model.Route(Model.Irrelevant)" class="small" id="competitors-news-newest">
                <i class="ti ti-arrow-bar-to-up me-1" aria-hidden="true"></i>@T["Competitors.News.Newest"]
            </a>
        }
    </div>
    <div class="card-body pt-0">
        <partial name="_NewsLines" model="lines" />
    </div>
    @if (Model.Next is { } next)
    {
        <div class="card-footer pt-0 d-flex justify-content-center">
            @* By keyset, never an offset (#224): after this page's last line, so a scan landing between two clicks repeats nothing. *@
            <a asp-action="Index" asp-all-route-data="Model.Route(Model.Irrelevant, next)" class="btn btn-label-primary" id="competitors-news-more">
                @T["Competitors.News.More"]<i class="ti ti-chevron-down ms-1" aria-hidden="true"></i>
            </a>
        </div>
    }
... (2 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Settings/Index.cshtml">
@using KnowledgeFabric.AdminConsole.Ollama
@using KnowledgeFabric.AdminConsole.Storage
@model CompetitorSettingsPage
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var ollama = Model.Ollama;
    var statement = Model.Positioning;
    var scan = Model.Scan;

    var settings = new[]
    {
        (Label: "Competitors.Ollama.Setting.Key", Setting: OllamaOptions.ApiKeySecret, Configured: ollama.KeyConfigured, Id: "ollama-key"),
        (Label: "Competitors.Ollama.Setting.Address", Setting: OllamaOptions.BaseUrlSetting, Configured: ollama.AddressConfigured, Id: "ollama-address"),
        (Label: "Competitors.Ollama.Setting.Model", Setting: CompetitorsOptions.ModelSetting, Configured: ollama.ModelConfigured, Id: "ollama-model"),
    };
}

@* The area's settings (#220), an Administrator's: the console's Ollama connection and the positioning statement (#221), and the daily scan (#223). *@
<div class="card mb-4" id="competitors-settings">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Competitors.Settings.Title"]</h5>
        <p class="text-body mb-0">@T["Competitors.Settings.Lead"]</p>
    </div>
</div>

<div class="card mb-4" id="competitors-ollama">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <h6 class="card-title mb-0">@T["Competitors.Ollama.Title"]</h6>
        @if (ollama.IsConfigured)
        {
            <span class="badge bg-label-success" id="ollama-configured">@T["Competitors.Ollama.State.Configured"]</span>
        }
        else
        {
            <span class="badge bg-label-warning" id="ollama-not-configured">@T["Competitors.Ollama.State.NotConfigured"]</span>
        }
    </div>
    <div class="card-body">
        <p class="text-body mb-3">@T["Competitors.Ollama.Intro"]</p>

        @* Each setting by the name an operator sets it under, configured or missing: never its value. *@
        <ul class="list-unstyled mb-3" id="ollama-settings">
            @foreach (var (label, setting, configured, id) in settings)
            {
                <li class="d-flex flex-wrap align-items-center gap-2 mb-2" id="@id" data-configured="@(configured ? "true" : "false")">
                    @if (configured)
                    {
                        <i class="ti ti-circle-check text-success" aria-hidden="true"></i>
                    }
                    else
                    {
                        <i class="ti ti-alert-triangle text-warning" aria-hidden="true"></i>
                    }
                    <span>@T[label]</span>
                    <code>@setting</code>
                    <span class="badge @(configured ? "bg-label-success" : "bg-label-warning")">@(configured ? T["Competitors.Ollama.Setting.Set"] : T["Competitors.Ollama.Setting.Missing"])</span>
                </li>
            }
        </ul>

        @if (ollama.KeyIsRetired)
        {
            <div class="alert alert-warning" role="status" id="ollama-key-retired">
                @T["Competitors.Ollama.Setting.Retired", RetiredBusinessCardKey.Secret, OllamaOptions.ApiKeySecret]
            </div>
        }

        @if (!ollama.IsConfigured)
        {
            <p class="text-body mb-1">@T["Competitors.Ollama.Missing"]</p>
            <ul class="mb-3" id="ollama-missing">
                @foreach (var setting in ollama.Missing)
                {
                    <li><code>@setting</code></li>
                }
            </ul>
        }

        @if (ollama.Tested is { } tested)
        {
            var alert = tested.Outcome == OllamaTestOutcome.Read ? "alert-success" : "alert-warning";
            <div class="alert @alert" role="status" id="ollama-tested" data-outcome="@tested.Outcome">
                @switch (tested.Outcome)
                {
                    case OllamaTestOutcome.Read:
                        @T["Competitors.Ollama.Tested.Read", ollama.Model ?? string.Empty]
                        break;
                    case OllamaTestOutcome.NotConfigured:
                        @T["Competitors.Ollama.Tested.NotConfigured"]
                        break;
                    case OllamaTestOutcome.Unreachable:
                        @T["Competitors.Ollama.Tested.Unreachable"]
                        break;
                    case OllamaTestOutcome.KeyRefused:
                        @T["Competitors.Ollama.Tested.KeyRefused"]
                        break;
                    default:
                        @T["Competitors.Ollama.Tested.NotUnderstood"]
                        break;
... (181 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Shared/Components/CompetitorsOverview/Default.cshtml">
@using KnowledgeFabric.AdminConsole.Areas.Competitors.ViewComponents
@model CompetitorsOverview
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var newest = Model.WeekNewest ?? [];
    var health = Model.Health;
}

@*
    The Competitors area's card on the overview (#220): how many competitors, and the three most recently
    edited; since #224 this week's items, Monday to Sunday UTC by when they were found, the newest three,
    the last scan's time, and to an Administrator a line when the scan needs looking at.
*@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card" id="competitors-overview">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Menu.Competitors"]</h5>
                <p class="card-subtitle mb-0">@T["Competitors.Overview.Lead"]</p>
            </div>
            <div class="card-body">
                @if (Model.Storage == CompetitorStorage.Unavailable)
                {
                    <p class="text-body mb-0">@T["Competitors.Overview.NoDatabase"]</p>
                }
                else if (Model.Unreadable)
                {
                    <div class="alert alert-danger mb-0" role="alert">@T["Competitors.Overview.Unreadable"]</div>
                }
                else
                {
                    <div class="row g-4">
                        <div class="col-md-4" id="competitors-overview-count" data-count="@Model.Count">
                            <span class="text-heading">@T["Competitors.Overview.OnTheList"]</span>
                            <h4 class="mb-1 mt-1"><a asp-area="Competitors" asp-controller="Competitors" asp-action="Index">@Model.Count</a></h4>
                        </div>
                        <div class="col-md-8" id="competitors-overview-recent">
                            <span class="text-heading">@T["Competitors.Overview.Recent"]</span>
                            @if (Model.Recent.Count == 0)
                            {
                                <p class="text-body mb-0 mt-1" id="competitors-overview-none">@T["Competitors.Overview.None"]</p>
                            }
                            else
                            {
                                <ul class="list-unstyled mb-0 mt-1" style="max-width: 40rem">
                                    @foreach (var competitor in Model.Recent)
                                    {
                                        <li class="d-flex justify-content-between gap-3" data-competitor="@competitor.Id">
                                            <a asp-area="Competitors" asp-controller="Competitors" asp-action="Details" asp-route-id="@competitor.Id" class="text-truncate" title="@competitor.Summary">@competitor.Name</a>
                                            <small class="text-body text-nowrap" title="@competitor.UpdatedBy">@Instant(competitor.UpdatedAt)</small>
                                        </li>
                                    }
                                </ul>
                            }
                        </div>

                        @* This week's items (#224): Monday to Sunday UTC by found_at, the irrelevant left out. *@
                        <div class="col-md-4" id="competitors-overview-week" data-count="@Model.WeekCount">
                            <span class="text-heading">@T["Competitors.Overview.Week"]</span>
                            <h4 class="mb-1 mt-1">
                                <a asp-area="Competitors" asp-controller="News" asp-action="Index">@(Model.WeekCount switch
                                {
                                    0 => T["Competitors.Overview.Week.None"],
                                    1 => T["Competitors.Overview.Week.One"],
                                    _ => T["Competitors.Overview.Week.Many", Model.WeekCount],
                                })</a>
                            </h4>
                            <small class="text-body d-block" id="competitors-overview-scan">
                                @if (Model.LastScan is null)
                                {
                                    @T["Competitors.Overview.LastScan.None"]
                                }
                                else if (Model.Running && !Model.LastScan.IsFinished)
                                {
                                    @T["Competitors.Overview.LastScan.Running", Instant(Model.LastScan.StartedAt)]
                                }
                                else
                                {
                                    @T["Competitors.Overview.LastScan", Instant(Model.LastScan.StartedAt)]
                                }
                            </small>
                        </div>
                        <div class="col-md-8" id="competitors-overview-news">
                            <span class="text-heading">@T["Competitors.Overview.Newest"]</span>
                            @if (newest.Count == 0)
                            {
                                <p class="text-body mb-0 mt-1">@T["Competitors.Overview.Newest.None"]</p>
                            }
                            else
                            {
                                <ul class="list-unstyled mb-0 mt-1" style="max-width: 40rem">
                                    @foreach (var line in newest)
                                    {
                                        <li class="d-flex justify-content-between gap-3" data-news-item="@line.Item.Id">
                                            <span class="text-truncate">
                                                <a asp-area="Competitors" asp-controller="Competitors" asp-action="Details" asp-route-id="@line.Item.CompetitorId" class="fw-medium">@line.CompetitorName</a>
                                                · <a href="@line.Item.Url" target="_blank" rel="noopener noreferrer" class="text-body" title="@line.Item.Summary">@line.Item.Title</a>
                                            </span>
                                            <small class="text-body text-nowrap" title="@S["Competitors.News.Found", line.Found].Value">@line.Date</small>
... (38 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Shared/_Lost.cshtml">
@model string?

@* What was typed in a field and not saved, because a colleague saved first (#220; the positioning statement's too, #221): shown to be typed again, never merged. *@
@if (Model is not null)
{
    <details class="mt-2 competitor-lost" open>
        <summary class="small text-danger">@T["Competitors.Conflict.Typed"]</summary>
        <textarea class="form-control form-control-sm mt-1" rows="3" readonly tabindex="-1">@Model</textarea>
    </details>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Shared/_NewsLines.cshtml">
@model NewsLines

@*
    A feed's lines (#224), on /Competitors/News and in a competitor's News card: the competitor (the global
    feed's), the kind, the title to the article in a new tab, the source's host, the date, and the two lines
    folded as #114's cells are, whole on hover and behind a more toggle that is a button. To a writer, Mark
    as irrelevant, or Mark as relevant on a line marked, which wwwroot/js/competitor-news.js sends and then
    removes the line; without script the form posts and comes back to this page.
*@
<ul class="list-unstyled mb-0 competitor-news" data-competitor-news>
    @foreach (var line in Model.Lines)
    {
        var item = line.Item;
        <li class="competitor-news-line@(item.IsIrrelevant ? " competitor-news-irrelevant" : "")" data-news-item="@item.Id">
            <div class="d-flex flex-wrap flex-sm-nowrap justify-content-between align-items-start gap-2">
                <div class="competitor-news-body">
                    <div class="d-flex flex-wrap align-items-baseline column-gap-2 row-gap-1">
                        @if (Model.ShowCompetitor)
                        {
                            <a asp-area="Competitors" asp-controller="Competitors" asp-action="Details" asp-route-id="@item.CompetitorId" class="fw-medium text-nowrap" data-news-competitor>@line.CompetitorName</a>
                        }
                        <span class="badge bg-label-@NewsKindNames.Badge(item.Kind) rounded-pill" data-news-kind="@item.Kind">@T[NewsKindNames.LabelKey(item.Kind)]</span>
                        <a href="@item.Url" target="_blank" rel="noopener noreferrer" class="text-heading fw-medium competitor-news-title" data-news-title>@item.Title</a>
                    </div>
                    <div class="small text-body-secondary mt-1">
                        <span class="text-break">@item.SourceHost</span>
                        · <span title="@S["Competitors.News.Found", line.Found].Value" data-news-date>@line.Date</span>
                        @if (item.IsIrrelevant && item.IrrelevantAt is { } markedAt)
                        {
                            <span>· @T["Competitors.News.MarkedBy", item.IrrelevantBy ?? string.Empty, markedAt.UtcDateTime.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)]</span>
                        }
                    </div>
                    <div class="crm-fold competitor-news-summary mt-1" title="@item.Summary">
                        <span class="crm-fold-text">@item.Summary</span><button type="button" class="crm-fold-toggle d-none" data-fold aria-expanded="false" title="@T["Js.Crm.More.Title"].Value">@T["Js.Crm.More"]</button>
                    </div>
                </div>
                @if (Model.MayMark)
                {
                    <form method="post" asp-area="Competitors" asp-controller="News" asp-action="@(item.IsIrrelevant ? "Relevant" : "Irrelevant")" asp-route-itemId="@item.Id"
                          class="flex-shrink-0" data-news-mark>
                        <input type="hidden" name="ReturnUrl" value="@Model.ReturnUrl" />
                        <button type="submit" class="btn btn-sm btn-text-secondary text-nowrap" data-news-mark-button>
                            @if (item.IsIrrelevant)
                            {
                                <i class="ti ti-arrow-back-up me-1" aria-hidden="true"></i>@T["Competitors.News.MarkRelevant"]
                            }
                            else
                            {
                                <i class="ti ti-eye-off me-1" aria-hidden="true"></i>@T["Competitors.News.MarkIrrelevant"]
                            }
                        </button>
                    </form>
                }
            </div>
        </li>
    }
</ul>
<p class="text-body-secondary mb-0@(Model.Lines.Count == 0 ? string.Empty : " d-none")" data-news-empty>@Model.Empty</p>
<p class="text-danger small mb-0 mt-2 d-none" role="alert" data-news-problem></p>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Shared/_Reading.cshtml">
@model ReadingNote

@* What reading a competitor's site came to (#222): drafted, and that the draft can be wrong; or why there is no draft. *@
@if (Model.Drafted)
{
    <div class="alert alert-info" role="status" id="competitor-drafted" data-site="@Model.Site" data-outcome="@Model.Analysis">
        <h6 class="alert-heading mb-1"><i class="ti ti-sparkles me-1" aria-hidden="true"></i>@T["Competitors.Reading.Drafted.Title"]</h6>
        <p class="mb-1">
            @if (Model.Pages > 0)
            {
                @T["Competitors.Reading.Drafted", Model.Model ?? string.Empty, Model.Pages]
            }
            else
            {
                @T["Competitors.Reading.Drafted.NoCount", Model.Model ?? string.Empty]
            }
        </p>
        <p class="mb-0">@T["Competitors.Reading.CanBeWrong"]</p>
        @if (Model.WithoutPositioning)
        {
            <p class="mb-0 mt-2" id="competitor-drafted-without-positioning">@T["Competitors.Reading.WithoutPositioning"]</p>
        }
    </div>
}
else
{
    <div class="alert alert-warning" role="alert" id="competitor-not-drafted" data-site="@Model.Site" data-outcome="@(Model.Analysis?.ToString() ?? "NotAsked")">
        @switch (Model.Site)
        {
            case SiteReadOutcome.Refused:
                @T["Competitors.Reading.Site.Refused"]
                break;
            case SiteReadOutcome.Unreachable:
                @T["Competitors.Reading.Site.Unreachable"]
                break;
            case SiteReadOutcome.Unreadable:
                @T["Competitors.Reading.Site.Unreadable"]
                break;
            default:
                @switch (Model.Analysis)
                {
                    case AnalysisOutcome.KeyRefused:
                        @T["Competitors.Reading.Model.KeyRefused"]
                        break;
                    case AnalysisOutcome.Unreachable:
                        @T["Competitors.Reading.Model.Unreachable"]
                        break;
                    case AnalysisOutcome.NotConfigured:
                        @T["Competitors.Reading.Model.NotConfigured"]
                        break;
                    default:
                        @T["Competitors.Reading.Model.NotUnderstood"]
                        break;
                }
                break;
        }
    </div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Shared/_Sources.cshtml">
@model CompetitorPage
@*
    A competitor's sources (#222): the feeds and pages its site gave and the terms the daily scan (#223)
    searches for, each turned on or off and removed by a writer, who adds one the reading missed. A feed
    is fetched once when added and refused unless it is RSS or Atom; a page unless it is public and has
    text. At most twenty.
*@
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var competitor = Model.Competitor;
    var sources = Model.Sources ?? [];
    var card = Model.Source ?? SourceCard.None;
    var mayChange = Model.MayWrite && Model.CanChange;
    var kinds = new[] { CompetitorSourceKind.Feed, CompetitorSourceKind.Page, CompetitorSourceKind.SearchTerm };
    var chosenKind = card.Kind ?? nameof(CompetitorSourceKind.Feed);
}

<div class="card mb-4" id="competitor-sources">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <h5 class="card-title mb-0">@T["Competitors.Sources.Title"]</h5>
        <span class="small text-body" id="competitor-sources-count">@T["Competitors.Sources.Count", sources.Count, CompetitorSource.MaxPerCompetitor]</span>
    </div>
    <div class="card-body pt-0">
        <p class="text-body mb-3">@T["Competitors.Sources.Lead"]</p>

        @if (card.Done is { } done)
        {
            <div class="alert alert-success" role="status" id="competitor-source-done" data-done="@done">@T[$"Competitors.Sources.Done.{done}"]</div>
        }

        @if (Model.SourcesUnreadable)
        {
            <div class="alert alert-danger" role="alert" id="competitor-sources-unreadable">@T["Competitors.Sources.Unreadable"]</div>
        }
        else if (sources.Count == 0)
        {
            <p class="text-body-secondary fst-italic mb-3" id="competitor-sources-none">@T["Competitors.Sources.None"]</p>
        }
        else
        {
            <ul class="list-group mb-3" id="competitor-sources-list">
                @foreach (var source in sources)
                {
                    <li class="list-group-item d-flex flex-wrap align-items-center gap-2" data-source="@source.Id" data-kind="@source.Kind" data-enabled="@(source.Enabled ? "true" : "false")">
                        <span class="badge bg-label-@(source.Kind switch { CompetitorSourceKind.Feed => "info", CompetitorSourceKind.Page => "secondary", _ => "primary" })">
                            @T[$"Competitors.Sources.Kind.{source.Kind}"]
                        </span>
                        <span class="flex-grow-1 text-break @(source.Enabled ? "" : "text-body-secondary")">
                            @if (source.Kind == CompetitorSourceKind.SearchTerm)
                            {
                                <span lang="en">@source.Term</span>
                            }
                            else
                            {
                                <a href="@source.Address" target="_blank" rel="noopener noreferrer">@source.Address</a>
                            }
                            @if (!source.Enabled)
                            {
                                <span class="badge bg-label-secondary ms-1">@T["Competitors.Sources.Off"]</span>
                            }
                            @if (source.LastReadAt is { } read)
                            {
                                <span class="d-block small text-body-secondary">
                                    @if (source.LastCount is { } count)
                                    {
                                        @T["Competitors.Sources.LastRead.Count", Instant(read), count]
                                    }
                                    else
                                    {
                                        @T["Competitors.Sources.LastRead", Instant(read)]
                                    }
                                </span>
                                @* How the scan's last read went (#223), when it failed: the outcome's name, never the address. *@
                                @if (source.LastOutcome is { } outcome && outcome != nameof(SourceCheckOutcome.Read))
                                {
                                    <span class="d-block small text-warning" data-outcome="@outcome">@T["Competitors.Sources.LastFailed", outcome]</span>
                                }
                            }
                        </span>
                        @if (mayChange)
                        {
                            <form method="post" asp-controller="Sources" asp-action="SetEnabled" asp-route-id="@competitor.Id" asp-route-sourceId="@source.Id" class="d-inline">
                                <input type="hidden" name="enabled" value="@(source.Enabled ? "false" : "true")" />
                                <button type="submit" class="btn btn-sm btn-label-secondary" data-action="enabled">
                                    @(source.Enabled ? T["Competitors.Sources.TurnOff"] : T["Competitors.Sources.TurnOn"])
                                </button>
                            </form>
                            <form method="post" asp-controller="Sources" asp-action="Remove" asp-route-id="@competitor.Id" asp-route-sourceId="@source.Id" class="d-inline">
                                <button type="submit" class="btn btn-sm btn-label-danger" data-action="remove">
                                    <i class="ti ti-trash me-1" aria-hidden="true"></i>@T["Competitors.Sources.Remove"]
                                </button>
                            </form>
                        }
                    </li>
                }
            </ul>
        }

        @if (mayChange)
... (34 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/Shared/_Storage.cshtml">
@model CompetitorStorage

@* Where competitors are held, said rather than left to look empty (#220): nowhere without a database outside Development, memory in it. *@
@if (Model == CompetitorStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert" id="competitors-no-database">@T["Competitors.NoDatabase"]</div>
}
else if (Model == CompetitorStorage.Ephemeral)
{
    <div class="alert alert-secondary" role="status" id="competitors-ephemeral">@T["Competitors.Ephemeral"]</div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/_ViewImports.cshtml">
@using KnowledgeFabric.AdminConsole
@using KnowledgeFabric.AdminConsole.Models
@using KnowledgeFabric.AdminConsole.Security
@using KnowledgeFabric.AdminConsole.Competitors
@using KnowledgeFabric.AdminConsole.Areas.Competitors.Controllers
@using KnowledgeFabric.AdminConsole.Areas.Competitors.Models
@using Microsoft.AspNetCore.Mvc.Localization
@using KnowledgeFabric.AdminConsole.Localisation
@using KnowledgeFabric.AdminConsole.Resources
@using Microsoft.Extensions.Localization
@inject IHtmlLocalizer<ConsoleResource> T
@inject IStringLocalizer<ConsoleResource> S
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Competitors/Views/_ViewStart.cshtml">
@{
    Layout = "_ContentNavbarLayout";
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/BusinessCardsController.cs">
public sealed class BusinessCardsController(
⋮----
ILogger<BusinessCardsController> logger) : Controller
⋮----
public IActionResult Index() => Page(Asking());
⋮----
/// <summary>The photo read into the form, beside it. Writes nothing but its audit entry.</summary>
⋮----
public async Task<IActionResult> Read(IFormFile? image, string? qr, CancellationToken cancellationToken)
⋮----
// Not sent where it could not be saved: a card read into a form that cannot add it is personal data sent for nothing.
⋮----
using (var memory = new MemoryStream((int)image.Length))
⋮----
await image.CopyToAsync(memory, cancellationToken);
photo = memory.ToArray();
⋮----
if (!BusinessCardImage.IsPhoto(photo))
⋮----
var code = BusinessCardQr.Of(qr);
var linked = code?.Link is { } link ? await linkedPages.ReadAsync(link, cancellationToken) : null;
⋮----
var reading = await reader.ReadAsync(photo, code?.ForModel(linked), cancellationToken);
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
["outcome"] = reading.Outcome.ToString(),
⋮----
["link"] = linked?.Outcome.ToString(),
⋮----
var form = BusinessCardForm.Of(card);
⋮----
Photo = $"data:{BusinessCardImage.MediaType(photo)};base64,{Convert.ToBase64String(photo)}",
⋮----
public async Task<IActionResult> Create(BusinessCardForm form, CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
var contact = new Contact
⋮----
Id = Guid.NewGuid(),
⋮----
OriginatedBy = names.FirstOrDefault(person => string.Equals(person, SignedInAs, StringComparison.OrdinalIgnoreCase)) ?? SignedInAs,
⋮----
var cells = form.Cells();
if (!ConsolePeople.IsPerson(SignedInAs))
⋮----
cells = cells.Append((ContactFields.By, form.By));
⋮----
var (apply, problem) = ContactEdit.Parse(field, value, names, text);
⋮----
Contact stored;
⋮----
stored = await contacts.AddAsync(contact, CancellationToken.None);
⋮----
logger.LogError(ex, "A contact could not be created from a business card; nothing was written.");
⋮----
Target: stored.Id.ToString(),
⋮----
private BusinessCardPage Asking() =>
⋮----
private async Task<BusinessCardPage> ReviewingAsync(BusinessCardForm form, CancellationToken cancellationToken)
⋮----
PeopleInitials initials;
⋮----
initials = await people.InitialsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The people's initials could not be read; the form shows their names.");
⋮----
private async Task<IReadOnlyList<Contact>> SameNameAsync(string? name, CancellationToken cancellationToken)
⋮----
if (string.IsNullOrWhiteSpace(name))
⋮----
var normalised = Contact.NormaliseName(name);
var found = await contacts.SearchAsync(ContactQuery.From(name, null, null, null, null, null, null, Today), cancellationToken);
return [.. found.Where(contact => Contact.NormaliseName(contact.Name) == normalised)];
⋮----
logger.LogError(ex, "The CRM could not be read for a business card's same name; the form is shown without the warning.");
⋮----
private async Task<(IReadOnlyList<string> Names, bool Read)> PeopleAsync(CancellationToken cancellationToken)
⋮----
return (await people.CrmAsync(cancellationToken), true);
⋮----
logger.LogError(ex, "The CRM's people could not be read from the role store.");
return (ConsolePeople.OnlySignedIn(SignedInAs), false);
⋮----
private ViewResult Page(BusinessCardPage page)
⋮----
private DateOnly Today => DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/ContactsController.cs">
public sealed class ContactsController(
⋮----
ILogger<ContactsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(
⋮----
var query = ContactQuery.From(q, stage, track, by, e, since, entity, Today);
⋮----
rows = await contacts.SearchAsync(query, cancellationToken);
shared = await contacts.SharedNamesAsync(cancellationToken);
interactions = await contacts.InteractionsAsync(rows.Select(row => row.Id).ToArray(), cancellationToken);
⋮----
logger.LogError(ex, "The contacts grid could not read the CRM.");
⋮----
return View(new ContactGrid(
contacts.Storage, query, rows, shared, interactions.ToLookup(interaction => interaction.ContactId), names, await InitialsAsync(cancellationToken),
⋮----
public async Task<IActionResult> Export(CancellationToken cancellationToken)
⋮----
rows = await contacts.SearchAsync(ContactQuery.All, cancellationToken);
⋮----
logger.LogError(ex, "The CRM could not be read for an export.");
⋮----
var order = rows.Select((row, index) => (row.Id, index)).ToDictionary(pair => pair.Id, pair => pair.index);
interactions = [.. interactions.OrderBy(interaction => order[interaction.ContactId])];
⋮----
var now = clock.GetUtcNow();
await auditLog.RecordAsync(
new AuditEntry(
⋮----
["contacts"] = rows.Count.ToString(),
["interactions"] = interactions.Count.ToString(),
⋮----
return File(CrmCsv.Zip(rows, interactions), "application/zip", string.Create(CultureInfo.InvariantCulture, $"crm-export-{now:yyyyMMdd-HHmm}.zip"));
⋮----
public async Task<IActionResult> Details(Guid id, CancellationToken cancellationToken)
⋮----
var contact = await contacts.FindAsync(id, cancellationToken);
⋮----
var shared = (await contacts.SharedNamesAsync(cancellationToken)).Contains(Contact.NormaliseName(contact.Name));
var interactions = await contacts.InteractionsAsync([id], cancellationToken);
⋮----
var timeline = new InteractionPanel(contact, interactions, canEdit, names, initials, SignedInAs, Today);
var introductions = new IntroductionCard(contact, await contacts.IntroductionsAsync([id], cancellationToken), canEdit, Today);
⋮----
return View(new ContactDetails(contacts.Storage, contact, shared, timeline, introductions, names, initials, PeopleUnread: !namesRead, mayWrite, mayDelete, SignedInAs));
⋮----
public async Task<IActionResult> Create(string? name, string? by, CancellationToken cancellationToken)
⋮----
var (apply, problem) = ContactEdit.Parse(ContactFields.Name, name, names, text);
⋮----
if (!ConsolePeople.IsPerson(SignedInAs))
⋮----
(applyBy, problem) = ContactEdit.Parse(ContactFields.By, by, names, text);
⋮----
var contact = new Contact
⋮----
Id = Guid.NewGuid(),
⋮----
OriginatedBy = names.FirstOrDefault(person => string.Equals(person, SignedInAs, StringComparison.OrdinalIgnoreCase)) ?? SignedInAs,
⋮----
Contact stored;
⋮----
stored = await contacts.AddAsync(contact, CancellationToken.None);
⋮----
logger.LogError(ex, "A contact could not be created; nothing was written.");
⋮----
public async Task<IActionResult> Cell(Guid id, string? field, string? value, string? version, CancellationToken cancellationToken)
⋮----
if (!ContactFields.IsEditable(field))
⋮----
if (!uint.TryParse(version, NumberStyles.None, CultureInfo.InvariantCulture, out var read))
⋮----
var (apply, problem) = ContactEdit.Parse(field!, value, names, text);
⋮----
ContactSave save;
⋮----
save = await contacts.SaveAsync(id, read, apply, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "A contact's {Field} could not be saved; nothing was written.", field);
⋮----
public Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken) =>
⋮----
public async Task<IActionResult> DeleteConfirmed(Guid id, string? confirmName, CancellationToken cancellationToken)
⋮----
if (string.IsNullOrWhiteSpace(confirmName) || Contact.NormaliseName(confirmName) != Contact.NormaliseName(contact.Name))
⋮----
removed = await contacts.DeleteAsync(id, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "A contact could not be deleted; nothing changed.");
⋮----
public async Task<IActionResult> DeletedContacts(Guid? restored, CancellationToken cancellationToken)
⋮----
rows = await contacts.DeletedAsync(cancellationToken);
back = restored is { } id ? await contacts.FindAsync(id, cancellationToken) : null;
⋮----
logger.LogError(ex, "The deleted contacts could not be read.");
⋮----
return View("Deleted", new DeletedContacts(contacts.Storage, rows, back, unreadable));
⋮----
... (57 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/FollowUpsController.cs">
public sealed class FollowUpsController(
⋮----
ILogger<FollowUpsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? owner, string? mine, string? due, CancellationToken cancellationToken)
⋮----
var query = FollowUpQuery.From(owner, mine, due, SignedInAs, Today);
⋮----
rows = await contacts.FollowUpsAsync(query, cancellationToken);
shared = await contacts.SharedNamesAsync(cancellationToken);
interactions = await contacts.InteractionsAsync(rows.Select(row => row.Id).ToArray(), cancellationToken);
⋮----
logger.LogError(ex, "The follow-ups grid could not read the CRM.");
⋮----
names = await people.CrmAsync(cancellationToken);
⋮----
logger.LogError(ex, "The CRM's people could not be read from the role store.");
names = ConsolePeople.OnlySignedIn(SignedInAs);
⋮----
var mayWrite = (await authorization.AuthorizeAsync(User, ConsolePolicies.CrmWrite)).Succeeded;
⋮----
return View(new FollowUpGrid(
contacts.Storage, query, rows, shared, interactions.ToLookup(interaction => interaction.ContactId), names, await InitialsAsync(cancellationToken),
⋮----
private DateOnly Today => DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
⋮----
private async Task<PeopleInitials> InitialsAsync(CancellationToken cancellationToken)
⋮----
return await people.InitialsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The people's initials could not be read; the follow-ups show their names.");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/HomeController.cs">
public sealed class HomeController : Controller
⋮----
public IActionResult Index() => RedirectToAction("Index", "Contacts");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/ImportController.cs">
public sealed class ImportController(
⋮----
ILogger<ImportController> logger) : Controller
⋮----
private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
⋮----
public IActionResult Index() => Page(new CrmImportPage(contacts.Storage, SignedInAs));
⋮----
/// <summary>The two files read as what they would create, or why they cannot be. Writes nothing.</summary>
⋮----
public async Task<IActionResult> Preview(IFormFile? contactsFile, IFormFile? interactionsFile, CancellationToken cancellationToken)
⋮----
return Page(new CrmImportPage(contacts.Storage, SignedInAs, Problem: string.Join(" ", new[] { contactsProblem, interactionsProblem }.OfType<string>())));
⋮----
/// <summary>The previewed files, read again and written if they still read the same way: <c>crm:import</c>.</summary>
⋮----
public async Task<IActionResult> Confirm(string? contactsFile, string? interactionsFile, CancellationToken cancellationToken)
⋮----
return Page(new CrmImportPage(contacts.Storage, SignedInAs, Problem: text["Crm.Import.NotCameBack"]));
⋮----
return Page(new CrmImportPage(contacts.Storage, SignedInAs, Problem: text["Crm.Import.CrmUnread"]));
⋮----
present = await contacts.ImportAsync(import.Contacts, import.Interactions, CancellationToken.None);
⋮----
logger.LogError(ex, "The CRM's import could not be written; nothing was.");
⋮----
Problems = present.Select(name => text["Crm.Import.AlreadyPresent", name].Value).ToList(),
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
["contacts"] = import.Contacts.Count.ToString(),
["interactions"] = import.Interactions.Count.ToString(),
["nextActions"] = import.NextActions.ToString(),
⋮----
return Page(new CrmImportPage(contacts.Storage, SignedInAs, import, Imported: true));
⋮----
private async Task<IActionResult> PreviewAsync(string contactsText, string interactionsText, string? problem, CancellationToken cancellationToken)
⋮----
? Page(new CrmImportPage(contacts.Storage, SignedInAs, Problem: text["Crm.Import.CrmUnread"]))
⋮----
private async Task<CrmImport?> ReadImportAsync(string contactsText, string interactionsText, CancellationToken cancellationToken)
⋮----
present = await contacts.SearchAsync(ContactQuery.All, cancellationToken);
deleted = (await contacts.DeletedAsync(cancellationToken)).Select(contact => contact.Id).ToList();
names = await people.CrmAsync(cancellationToken);
⋮----
logger.LogError(ex, "The CRM or its people could not be read for an import.");
⋮----
var now = clock.GetUtcNow();
return CrmImport.Read(contactsText, interactionsText, names, present, deleted, SignedInAs, now, DateOnly.FromDateTime(now.UtcDateTime), text);
⋮----
private CrmImportPage Previewed(CrmImport import, string contactsText, string interactionsText, string? problem) =>
⋮----
private async Task<(string? Text, string? Problem)> ReadAsync(IFormFile? file, string name, CancellationToken cancellationToken)
⋮----
using var buffer = new MemoryStream();
await file.CopyToAsync(buffer, cancellationToken);
⋮----
return (Utf8.GetString(buffer.ToArray()), null);
⋮----
private static string Encode(string value) => Convert.ToBase64String(Utf8.GetBytes(value));
⋮----
private static string? Decode(string? base64)
⋮----
if (string.IsNullOrEmpty(base64))
⋮----
return Utf8.GetString(Convert.FromBase64String(base64));
⋮----
private IActionResult Page(CrmImportPage page)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/InteractionsController.cs">
public sealed class InteractionsController(
⋮----
ILogger<InteractionsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(Guid contactId, CancellationToken cancellationToken)
⋮----
var contact = await contacts.FindAsync(contactId, cancellationToken);
⋮----
/// <summary>
/// An interaction added from the panel's form: the date, the kind, who took part and what was
/// said; and, when the form sent <paramref name="contactVersion"/>, the next action that follows
⋮----
public async Task<IActionResult> Add(
⋮----
var (apply, problem) = InteractionEdit.Parse(occurredOn, kind, participants ?? [], summary, names, held: [], Today, text);
⋮----
// The next action, when the form offered it: checked with the interaction, before either is written.
⋮----
if (!uint.TryParse(contactVersion, NumberStyles.None, CultureInfo.InvariantCulture, out read))
⋮----
(next, problem) = NextActionEdit.Parse(nextAction, nextActionOwner, nextActionDue, names, contact.NextActionOwner, text);
⋮----
// None typed (#111): cleared or kept as the form's question was answered, and asked when it was not;
// cleared when the form was opened by Done (#133), the interaction being that action done.
⋮----
if (next is not null && next.Changed(contact) is { Count: > 0 } changed)
⋮----
ContactSave saved;
⋮----
saved = await contacts.SaveAsync(contactId, read, next.Apply, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "A contact's next action could not be saved with an interaction; nothing was written.");
⋮----
// Not as Done opened it: their next action may not be the one done, so an empty one is asked about again.
Form = typed with { Next = typed.Next! with { Version = theirs.Version.ToString(CultureInfo.InvariantCulture) }, Done = false },
Notice = new InteractionNotice(null,
⋮----
var now = clock.GetUtcNow();
var interaction = new Interaction
⋮----
Id = Guid.NewGuid(),
⋮----
InteractionSave save;
⋮----
save = await contacts.AddInteractionAsync(interaction, CancellationToken.None);
⋮----
logger.LogError(ex, "An interaction could not be added; nothing of it was written.");
⋮----
public async Task<IActionResult> NextAction(
⋮----
if (!uint.TryParse(version, NumberStyles.None, CultureInfo.InvariantCulture, out var read))
⋮----
var (next, problem) = NextActionEdit.Parse(nextAction, nextActionOwner, nextActionDue, names, contact.NextActionOwner, text);
⋮----
var changed = next.Changed(contact);
⋮----
ContactSave save;
⋮----
save = await contacts.SaveAsync(contactId, read, next.Apply, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "A contact's next action could not be saved; nothing was written.");
⋮----
NextTyped = typed with { Version = theirs.Version.ToString(CultureInfo.InvariantCulture) },
Notice = new InteractionNotice(contactId,
⋮----
public async Task<IActionResult> Update(
⋮----
var held = (await contacts.InteractionsAsync([contactId], cancellationToken)).FirstOrDefault(interaction => interaction.Id == id);
⋮----
var (apply, problem) = InteractionEdit.Parse(occurredOn, kind, participants ?? [], summary, names, held.Participants, Today, text);
⋮----
save = await contacts.SaveInteractionAsync(contactId, id, read, apply, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "An interaction could not be saved; nothing was written.");
⋮----
return await contacts.FindAsync(contactId, cancellationToken) is null
⋮----
Form = typed with { Version = theirs.Version.ToString(CultureInfo.InvariantCulture) },
Notice = new InteractionNotice(id,
⋮----
public async Task<IActionResult> Delete(Guid contactId, Guid id, string? version, CancellationToken cancellationToken)
⋮----
return Panel(await PanelAsync(contact, cancellationToken) with { Notice = new InteractionNotice(id, text["Crm.Interaction.NoOwnVersion"]) },
⋮----
save = await contacts.DeleteInteractionAsync(contactId, id, read, CancellationToken.None);
⋮----
logger.LogError(ex, "An interaction could not be deleted; nothing changed.");
return Panel(await PanelAsync(contact, cancellationToken) with { Notice = new InteractionNotice(id, text["Crm.Interaction.NotDeleted"]) },
⋮----
: Panel(await PanelAsync(contact, cancellationToken) with { Notice = new InteractionNotice(null, text["Crm.Interaction.AlreadyDeleted"]) });
⋮----
private PartialViewResult DeletedWhileEditing(InteractionPanel panel, InteractionForm typed) =>
⋮----
private async Task<InteractionPanel> PanelAsync(Contact contact, CancellationToken cancellationToken)
⋮----
return new InteractionPanel(
⋮----
await contacts.InteractionsAsync([contact.Id], cancellationToken),
⋮----
private PartialViewResult Panel(InteractionPanel panel, int status = StatusCodes.Status200OK)
... (42 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/IntroductionsController.cs">
public sealed class IntroductionsController(
⋮----
ILogger<IntroductionsController> logger) : Controller
⋮----
public async Task<IActionResult> Add(
⋮----
var typed = new IntroductionForm(customer ?? string.Empty, introducedOn ?? string.Empty, stage ?? string.Empty, contactPerson ?? string.Empty, notes ?? string.Empty);
⋮----
var contact = await contacts.FindAsync(contactId, cancellationToken);
⋮----
var (apply, problem) = IntroductionEdit.ParseForm(typed, Today, text);
⋮----
var now = clock.GetUtcNow();
var introduction = new Introduction
⋮----
Id = Guid.NewGuid(),
⋮----
IntroductionSave save;
⋮----
save = await contacts.AddIntroductionAsync(introduction, CancellationToken.None);
⋮----
logger.LogError(ex, "An introduction could not be added; nothing of it was written.");
⋮----
public async Task<IActionResult> Cell(Guid contactId, Guid id, string? field, string? value, string? version, CancellationToken cancellationToken)
⋮----
if (!IntroductionFields.IsEditable(field))
⋮----
if (!uint.TryParse(version, NumberStyles.None, CultureInfo.InvariantCulture, out var read))
⋮----
var (apply, problem) = IntroductionEdit.Parse(field!, value, Today, text);
⋮----
save = await contacts.SaveIntroductionAsync(contactId, id, read, apply, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "An introduction's {Field} could not be saved; nothing was written.", field);
⋮----
return await contacts.FindAsync(contactId, cancellationToken) is null
⋮----
private object Answer(Introduction introduction) => new
⋮----
version = introduction.Version.ToString(CultureInfo.InvariantCulture),
⋮----
cells = IntroductionCells.Of(introduction, text),
⋮----
private async Task<IntroductionCard> CardAsync(Contact contact, CancellationToken cancellationToken) =>
new(contact, await contacts.IntroductionsAsync([contact.Id], cancellationToken), CanEdit: await MayWriteAsync() && contacts.Storage != ContactStorage.Unavailable, Today);
⋮----
private PartialViewResult Card(IntroductionCard card, int status = StatusCodes.Status200OK)
⋮----
private Task AuditAsync(string action, Contact contact, Introduction introduction, string? field)
⋮----
["introduction"] = introduction.Id.ToString(),
⋮----
return auditLog.RecordAsync(
new AuditEntry(
⋮----
Target: contact.Id.ToString(),
OccurredAt: clock.GetUtcNow(),
⋮----
private async Task<bool> MayWriteAsync() =>
(await authorization.AuthorizeAsync(User, ConsolePolicies.CrmWrite)).Succeeded;
⋮----
private DateOnly Today => DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
⋮----
private ObjectResult Gone() =>
⋮----
private IActionResult Refused(string problem) =>
⋮----
private IActionResult Problem(string problem) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Controllers/StatisticsController.cs">
public sealed class StatisticsController(
⋮----
ILogger<StatisticsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? asOf, CancellationToken cancellationToken)
⋮----
var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
⋮----
history = CrmHistory.Of(await contacts.ChangesAsync(cancellationToken));
⋮----
logger.LogError(ex, "The CRM's statistics could not read the record of stage changes.");
⋮----
funnel = CrmFunnel.Compute(history!.AsOf(past));
tracks = history.Tracks();
⋮----
var summaries = await contacts.SummariesAsync(cancellationToken);
funnel = CrmFunnel.Compute(summaries);
tracks = summaries.ToDictionary(contact => contact.Id, contact => contact.Track);
⋮----
logger.LogError(ex, "The CRM's statistics could not read the CRM.");
⋮----
return View(new CrmStatisticsPage(contacts.Storage, funnel, today, day, problem, history?.Began, history?.Series(day ?? today), introductions));
⋮----
private async Task<IntroductionStatistics?> IntroductionsAsync(
⋮----
var history = IntroductionHistory.Of(await contacts.IntroductionChangesAsync(cancellationToken));
⋮----
? past < history.Began ? null : IntroductionFunnel.Compute(history.AsOf(past), tracks, history.Reached(past))
: IntroductionFunnel.Compute(await contacts.IntroductionSummariesAsync(cancellationToken), tracks, history.Reached(null));
⋮----
return new IntroductionStatistics(funnel, history.Began, history.Series(shown), CrmHistory.IsWeekly(history.Began, shown));
⋮----
logger.LogError(ex, "The CRM's statistics could not read the introductions.");
⋮----
private (DateOnly? Day, string? Problem) DayAsked(string? asOf, DateOnly today, CrmHistory? history)
⋮----
if (string.IsNullOrWhiteSpace(asOf))
⋮----
if (!DateOnly.TryParseExact(asOf.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
⋮----
return (null, text["Crm.Statistics.AsOf.Future", CrmStatisticsPage.LongDay(day)]);
⋮----
? text["Crm.Statistics.AsOf.BeforeRecord", CrmStatisticsPage.LongDay(start)]
⋮----
public bool Weekly => Began is not { } began || CrmHistory.IsWeekly(began, Day);
⋮----
public static string LongDay(DateOnly day) => day.ToString("d MMMM yyyy", CultureInfo.CurrentCulture);
⋮----
public static string Iso(DateOnly day) => day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/BusinessCardPage.cs">
public bool AsksBy => !ConsolePeople.IsPerson(SignedInAs);
⋮----
public string? ProblemOf(string field) => Problems is not null && Problems.TryGetValue(field, out var problem) ? problem : null;
⋮----
public static BusinessCardForm Of(BusinessCard card) =>
⋮----
new[] { Name, Headline, Organisation, Email, Phone, LinkedIn, Notes }.All(string.IsNullOrWhiteSpace);
⋮----
public IEnumerable<(string Field, string? Value)> Cells()
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/ContactCells.cs">
public static class ContactFields
⋮----
public static bool IsEditable(string? field) => field is not null && Editable.Contains(field, StringComparer.Ordinal);
⋮----
public static bool Folds(string field) => field is Headline or Notes;
⋮----
public static string Kind(string field) => field switch
⋮----
public static class ContactCells
⋮----
public static IReadOnlyDictionary<string, ContactCell> Of(Contact contact, IStringLocalizer<ConsoleResource> text, PeopleInitials initials) =>
ContactFields.Editable.ToDictionary(field => field, field => Of(contact, field, text, initials), StringComparer.Ordinal);
⋮----
public static ContactCell Of(Contact contact, string field, IStringLocalizer<ConsoleResource> text, PeopleInitials initials) => field switch
⋮----
? Text(contact.Name) with { Mark = contact.Organisation ?? ContactEntity.Company.DisplayName(text) }
⋮----
ContactFields.By => initials.Of(contact.OriginatedBy) is { } shown
? new ContactCell(contact.OriginatedBy, shown, shown.ToLowerInvariant(), contact.OriginatedBy)
⋮----
? new ContactCell(((int)engagement).ToString(CultureInfo.InvariantCulture), ((int)engagement).ToString(CultureInfo.InvariantCulture),
((int)engagement).ToString(CultureInfo.InvariantCulture), engagement.DisplayName(text))
: new ContactCell(string.Empty, string.Empty, string.Empty),
⋮----
ContactFields.Track => new ContactCell(contact.Track.ToString(), contact.Track.DisplayName(text), ((int)contact.Track).ToString(CultureInfo.InvariantCulture)),
ContactFields.Stage => new ContactCell(contact.Stage.ToString(), contact.Stage.DisplayName(text), ((int)contact.Stage).ToString(CultureInfo.InvariantCulture)),
⋮----
? new ContactCell(entity.ToString(), entity.DisplayName(text), ((int)entity).ToString(CultureInfo.InvariantCulture))
⋮----
? new ContactCell(reason.ToString(), reason.DisplayName(text), ((int)reason).ToString(CultureInfo.InvariantCulture))
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Not a field of a contact."),
⋮----
private static ContactCell Text(string? value) => new(value ?? string.Empty, value ?? string.Empty, (value ?? string.Empty).ToLowerInvariant());
⋮----
private static ContactCell Whole(string? value) => Text(value) with { Title = string.IsNullOrEmpty(value) ? null : value };
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/ContactEdit.cs">
public static class ContactEdit
⋮----
public static (Action<Contact>? Apply, string? Problem) Parse(string field, string? raw, IReadOnlyList<string> people, IStringLocalizer<ConsoleResource> text)
⋮----
var person = people.FirstOrDefault(name => string.Equals(name, value, StringComparison.OrdinalIgnoreCase));
⋮----
: !ConsolePeople.IsPerson(value) ? Refused(text["Crm.Problem.Admin"])
⋮----
return CrmWords.ParseEngagement(value) is { } engagement
⋮----
var notes = (raw ?? string.Empty).TrimEnd();
⋮----
return Refused(text["Crm.Edit.TooLong", text["Crm.Edit.Field.Notes"].Value, Contact.NotesLength.ToString("N0", CultureInfo.CurrentCulture)]);
⋮----
if (value.Length > 0 && (value.IndexOf('@') <= 0 || value.IndexOf('@') == value.Length - 1 || value.Any(char.IsWhiteSpace)))
⋮----
if (value.Length > 0 && !(Uri.TryCreate(value, UriKind.Absolute, out var url) && url.Scheme is "https" or "http"))
⋮----
private static (Action<Contact>?, string?) Optional(string value, int length, string whatKey, Func<string?, Action<Contact>> set, IStringLocalizer<ConsoleResource> text) =>
⋮----
private static (Action<Contact>?, string?) Change(Action<Contact> apply) => (apply, null);
⋮----
private static (Action<Contact>?, string?) Refused(string problem) => (null, problem);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/ContactGrid.cs">
public bool IsShared(Contact contact) => SharedNames.Contains(Contact.NormaliseName(contact.Name));
⋮----
public ContactRow RowOf(Contact contact) => new(contact, IsShared(contact), [.. Interactions[contact.Id]], NextActionLine.Of(contact, Today), Initials);
⋮----
public ContactRow RowOf(Contact contact) =>
new(contact, SharedNames.Contains(Contact.NormaliseName(contact.Name)), [.. Interactions[contact.Id]], NextActionLine.Of(contact, Query.Today), Initials);
⋮----
public int Overdue => Rows.Count(row => row.IsOverdue(Query.Today));
⋮----
public interface IContactPage
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/CrmImport.cs">
public int NextActions => Contacts.Count(contact => contact.NextAction is not null);
⋮----
public static CrmImport Read(
⋮----
var (contactRecords, contactsProblem) = CrmCsv.Read(contactsText, CrmCsv.ContactsFile, CrmCsv.ContactColumns, text);
var (interactionRecords, interactionsProblem) = CrmCsv.Read(interactionsText, CrmCsv.InteractionsFile, CrmCsv.InteractionColumns, text);
⋮----
problems.AddRange(new[] { contactsProblem, interactionsProblem }.OfType<string>());
⋮----
var presentNames = present.Select(contact => Contact.NormaliseName(contact.Name)).ToHashSet(StringComparer.Ordinal);
var presentIds = present.Select(contact => contact.Id).ToHashSet();
⋮----
if (presentIds.Contains(contact.Id))
⋮----
problems.Add(text["Crm.Import.Problem.IdPresent", CrmCsv.ContactsFile, line, contact.Id]);
⋮----
else if (deleted.Contains(contact.Id))
⋮----
problems.Add(text["Crm.Import.Problem.IdDeleted", CrmCsv.ContactsFile, line, contact.Id]);
⋮----
else if (presentNames.Contains(Contact.NormaliseName(contact.Name)))
⋮----
problems.Add(text["Crm.Import.Problem.NamePresent", CrmCsv.ContactsFile, line, contact.Name]);
⋮----
problems.Add(text["Crm.Import.Problem.NoContacts", CrmCsv.ContactsFile]);
⋮----
problems = [.. problems.Take(ProblemsListed), text["Crm.Import.Problem.More", more]];
⋮----
return new(contacts.Select(pair => pair.Contact).ToList(), interactions, problems, withoutSummary);
⋮----
private static List<(int Line, Contact Contact)> ReadContacts(
⋮----
var id = Guid.NewGuid();
if (record["id"].Trim() is { Length: > 0 } typedId)
⋮----
if (!Guid.TryParse(typedId, out id))
⋮----
problems.Add(text["Crm.Import.Problem.BadId", where]);
⋮----
else if (!ids.Add(id))
⋮----
problems.Add(text["Crm.Import.Problem.IdTwice", where, id]);
⋮----
var contact = new Contact
⋮----
if (record["track"].Trim().Length > 0)
⋮----
if (record["stage"].Trim().Length > 0)
⋮----
var owner = record["next_action_owner"].Trim() is { Length: > 0 } named ? named : contact.OriginatedBy;
var (next, nextProblem) = NextActionEdit.Parse(record["next_action"], owner, record["next_action_due"], people, held: null, text);
⋮----
problems.Add($"{where} (next_action): {nextProblem}");
⋮----
next.Apply(contact);
⋮----
contacts.Add((record.Line, contact));
⋮----
var (apply, problem) = ContactEdit.Parse(field, record[column], people, text);
⋮----
problems.Add($"{where} ({column}): {problem}");
⋮----
foreach (var group in contacts.GroupBy(pair => Contact.NormaliseName(pair.Contact.Name), StringComparer.Ordinal).Where(group => group.Count() > 1))
⋮----
if (group.Any(pair => records.Single(record => record.Line == pair.Line)["id"].Trim().Length == 0))
⋮----
problems.Add(text["Crm.Import.Problem.NameTwice", CrmCsv.ContactsFile, string.Join(", ", group.Select(pair => pair.Line)), group.First().Contact.Name]);
⋮----
private static (List<Interaction> Interactions, int WithoutSummary) ReadInteractions(
⋮----
var byId = contacts.ToDictionary(pair => pair.Contact.Id, pair => pair.Contact);
var byName = contacts.ToLookup(pair => Contact.NormaliseName(pair.Contact.Name), pair => pair.Contact, StringComparer.Ordinal);
⋮----
var name = record["contact"].Trim();
⋮----
if (record["contact_id"].Trim() is { Length: > 0 } typedId)
⋮----
if (!Guid.TryParse(typedId, out var id) || !byId.TryGetValue(id, out contact))
⋮----
problems.Add(text["Crm.Import.Problem.ContactIdUnknown", where, typedId, CrmCsv.ContactsFile]);
⋮----
if (name.Length > 0 && Contact.NormaliseName(name) != Contact.NormaliseName(contact.Name))
⋮----
problems.Add(text["Crm.Import.Problem.ContactIdMismatch", where, contact.Name, name]);
⋮----
var named = byName[Contact.NormaliseName(name)].ToList();
⋮----
problems.Add(name.Length == 0 ? text["Crm.Import.Problem.NoContact", where]
⋮----
if (summary.Trim().Length == 0)
⋮----
var participants = record["participants"].Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
var (apply, problem) = InteractionEdit.Parse(record["occurred_on"], record["kind"], participants, summary, people, held: [], today, text);
⋮----
problems.Add($"{where}: {problem}");
⋮----
var interaction = new Interaction
⋮----
Id = Guid.NewGuid(),
⋮----
... (4 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/InteractionPanel.cs">
public NextActionLine? Next => NextActionLine.Of(Contact, Today);
⋮----
public NextActionForm NextForm => NextTyped ?? NextActionForm.Of(Contact, Me ?? string.Empty);
⋮----
public NextActionForm AddNextForm => Form is { Id: null, Next: { } typed } ? typed : NextActionForm.Blank(Contact, Me ?? string.Empty);
⋮----
public IReadOnlyList<string> Owners(NextActionForm form) =>
form.Owner.Length == 0 || People.Contains(form.Owner, StringComparer.OrdinalIgnoreCase) ? People : [.. People, form.Owner];
⋮----
private string? Me => ConsolePeople.IsPerson(SignedInAs)
? People.FirstOrDefault(person => string.Equals(person, SignedInAs, StringComparison.OrdinalIgnoreCase)) ?? SignedInAs
⋮----
public string MetOrder => ContactTimeline.Order(Interactions);
⋮----
(Next?.Owner is { } owner ? People.FirstOrDefault(person => string.Equals(person, owner, StringComparison.OrdinalIgnoreCase)) : null) ?? Me;
⋮----
: new InteractionForm(
⋮----
Kind: InteractionKind.Call.ToString(),
⋮----
public InteractionForm EditForm(Interaction interaction) => Form is { Id: { } id } typed && id == interaction.Id
⋮----
: InteractionForm.Of(interaction);
⋮----
public bool IsEditing(Interaction interaction) => Form?.Id == interaction.Id;
⋮----
public IReadOnlyList<string> Offered(InteractionForm form) =>
[.. People, .. form.Participants.Where(name => !People.Contains(name, StringComparer.OrdinalIgnoreCase))];
⋮----
public static string Iso(DateOnly day) => day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
⋮----
public static InteractionForm Of(Interaction interaction) =>
new(interaction.Id, interaction.Version.ToString(CultureInfo.InvariantCulture), InteractionPanel.Iso(interaction.OccurredOn),
interaction.Kind.ToString(), interaction.Participants, interaction.Summary);
⋮----
public string Key(Guid contactId) => Id is { } id ? id.ToString("N") : "new-" + contactId.ToString("N");
⋮----
public static class ContactTimeline
⋮----
public static string Order(IReadOnlyList<Interaction> interactions) =>
interactions.Count == 0 ? string.Empty : InteractionPanel.Iso(interactions.Max(interaction => interaction.OccurredOn));
⋮----
public static class InteractionEdit
⋮----
public static readonly DateOnly Earliest = new(2000, 1, 1);
⋮----
public static (Action<Interaction>? Apply, string? Problem) Parse(
⋮----
if (!DateOnly.TryParseExact(occurredOn?.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
⋮----
if (day > today.AddDays(1))
⋮----
foreach (var typed in participants.Select(name => name.Trim()).Where(name => name.Length > 0))
⋮----
var person = people.FirstOrDefault(name => string.Equals(name, typed, StringComparison.OrdinalIgnoreCase))
?? held.FirstOrDefault(name => string.Equals(name, typed, StringComparison.OrdinalIgnoreCase));
⋮----
return Refused(ConsolePeople.IsPerson(typed) ? text["Crm.Interaction.Problem.NoRole", typed] : text["Crm.Problem.Admin"]);
⋮----
if (!names.Contains(person, StringComparer.OrdinalIgnoreCase))
⋮----
names.Add(person);
⋮----
var said = (summary ?? string.Empty).TrimEnd();
⋮----
return Refused(text["Crm.Interaction.Problem.SummaryTooLong", Interaction.SummaryLength.ToString("N0", CultureInfo.CurrentCulture)]);
⋮----
var participantsTaken = names.ToArray();
⋮----
private static (Action<Interaction>?, string?) Refused(string problem) => (null, problem);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/IntroductionCard.cs">
public static class IntroductionFields
⋮----
public static bool IsEditable(string? field) => field is not null && Editable.Contains(field, StringComparer.Ordinal);
⋮----
public static bool Folds(string field) => field is Notes;
⋮----
public static string Kind(string field) => field switch
⋮----
public static class IntroductionCells
⋮----
public static IReadOnlyDictionary<string, ContactCell> Of(Introduction introduction, IStringLocalizer<ConsoleResource> text) =>
IntroductionFields.Editable.ToDictionary(field => field, field => Of(introduction, field, text), StringComparer.Ordinal);
⋮----
public static ContactCell Of(Introduction introduction, string field, IStringLocalizer<ConsoleResource> text) => field switch
⋮----
IntroductionFields.IntroducedOn => new ContactCell(
InteractionPanel.Iso(introduction.IntroducedOn), CrmWords.SheetDate(introduction.IntroducedOn), InteractionPanel.Iso(introduction.IntroducedOn)),
IntroductionFields.Stage => new ContactCell(
introduction.Stage.ToString(), introduction.Stage.DisplayName(text), ((int)introduction.Stage).ToString(CultureInfo.InvariantCulture)),
⋮----
IntroductionFields.Notes => Text(introduction.Notes) with { Title = string.IsNullOrEmpty(introduction.Notes) ? null : introduction.Notes },
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Not a field of an introduction."),
⋮----
private static ContactCell Text(string? value) => new(value ?? string.Empty, value ?? string.Empty, (value ?? string.Empty).ToLowerInvariant());
⋮----
public static class IntroductionEdit
⋮----
public static (Action<Introduction>? Apply, string? Problem) Parse(string field, string? raw, DateOnly today, IStringLocalizer<ConsoleResource> text)
⋮----
if (!DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
⋮----
if (day > today.AddDays(1))
⋮----
var notes = (raw ?? string.Empty).TrimEnd();
⋮----
return Refused(text["Crm.Edit.TooLong", text["Crm.Introduction.Field.Notes"].Value, Introduction.NotesLength.ToString("N0", CultureInfo.CurrentCulture)]);
⋮----
if (value.Length > 0 && (value.IndexOf('@') <= 0 || value.IndexOf('@') == value.Length - 1 || value.Any(char.IsWhiteSpace)))
⋮----
public static (Action<Introduction>? Apply, string? Problem) ParseForm(IntroductionForm form, DateOnly today, IStringLocalizer<ConsoleResource> text)
⋮----
changes.Add(apply);
⋮----
return Change(introduction => changes.ForEach(apply => apply(introduction)));
⋮----
private static (Action<Introduction>?, string?) Optional(string value, int length, string whatKey, Func<string?, Action<Introduction>> set, IStringLocalizer<ConsoleResource> text) =>
⋮----
private static (Action<Introduction>?, string?) Change(Action<Introduction> apply) => (apply, null);
⋮----
private static (Action<Introduction>?, string?) Refused(string problem) => (null, problem);
⋮----
public IntroductionForm AddForm => Form ?? IntroductionForm.Blank(Today);
⋮----
public static IntroductionForm Blank(DateOnly today) =>
new(string.Empty, InteractionPanel.Iso(today), IntroductionStage.Introduced.ToString(), string.Empty, string.Empty);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/NextAction.cs">
public static NextActionLine? Of(Contact contact, DateOnly today) =>
contact.NextAction is { } text ? new(text, contact.NextActionOwner, contact.NextActionDue, contact.IsOverdue(today)) : null;
⋮----
public string? SheetDue => Due is { } due ? CrmWords.SheetDate(due) : null;
⋮----
public string Title(IStringLocalizer<ConsoleResource> text) => Due is { } due
? Overdue ? text["Crm.Next.Title.Overdue", InteractionPanel.Iso(due)] : text["Crm.Next.Title.Due", InteractionPanel.Iso(due)]
⋮----
public object Answer(IStringLocalizer<ConsoleResource> text, PeopleInitials initials) =>
new { text = Text, owner = Owner ?? string.Empty, ownerInitials = initials.Of(Owner), due = SheetDue, overdue = Overdue, title = Title(text) };
⋮----
public static NextActionForm Of(Contact contact, string signedInAs) =>
⋮----
contact.NextActionDue is { } due ? InteractionPanel.Iso(due) : string.Empty,
contact.Version.ToString(CultureInfo.InvariantCulture));
⋮----
public static NextActionForm Blank(Contact contact, string signedInAs) =>
new(string.Empty, signedInAs, string.Empty, contact.Version.ToString(CultureInfo.InvariantCulture));
⋮----
public static class NoNextAction
⋮----
public static readonly NextActionValue None = new(null, null, null);
⋮----
public static NextActionValue Of(Contact contact) => new(contact.NextAction, contact.NextActionOwner, contact.NextActionDue);
⋮----
public void Apply(Contact contact)
⋮----
public IReadOnlyList<string> Changed(Contact contact)
⋮----
if (!string.Equals(Text, contact.NextAction, StringComparison.Ordinal))
⋮----
fields.Add(ContactFields.NextAction);
⋮----
if (!string.Equals(Owner, contact.NextActionOwner, StringComparison.Ordinal))
⋮----
fields.Add(ContactFields.NextActionOwner);
⋮----
fields.Add(ContactFields.NextActionDue);
⋮----
public static class NextActionEdit
⋮----
public static (NextActionValue? Value, string? Problem) Parse(string? typed, string? owner, string? due, IReadOnlyList<string> people, string? held, IStringLocalizer<ConsoleResource> text)
⋮----
var person = people.FirstOrDefault(name => string.Equals(name, typedOwner, StringComparison.OrdinalIgnoreCase))
?? (string.Equals(held, typedOwner, StringComparison.OrdinalIgnoreCase) ? held : null);
⋮----
return Refused(ConsolePeople.IsPerson(typedOwner) ? text["Crm.Next.Problem.NoRole", typedOwner] : text["Crm.Problem.Admin"]);
⋮----
if (!DateOnly.TryParseExact(typedDue, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed))
⋮----
return (new NextActionValue(said, person, day), null);
⋮----
private static (NextActionValue?, string?) Refused(string problem) => (null, problem);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Models/PersonCell.cs">
public static class PersonCell
⋮----
public static IHtmlContent Person(this PeopleInitials initials, string name) =>
initials.Of(name) is { } shown
? new HtmlContentBuilder().AppendHtml("<span title=\"").Append(name).AppendHtml("\">").Append(shown).AppendHtml("</span>")
: new HtmlContentBuilder().Append(name);
⋮----
public static IHtmlContent People(this PeopleInitials initials, IEnumerable<string> names)
⋮----
var line = new HtmlContentBuilder();
⋮----
line.Append(", ");
⋮----
line.AppendHtml(initials.Person(name));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/ViewComponents/CrmOverviewViewComponent.cs">
public sealed class CrmOverviewViewComponent(
⋮----
ILogger<CrmOverviewViewComponent> logger) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync()
⋮----
if (!(await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.CrmView)).Succeeded)
⋮----
var today = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
⋮----
statistics = CrmStatistics.Compute(await contacts.SummariesAsync(cancellationToken), await contacts.IntroductionSummariesAsync(cancellationToken), today);
activity = CrmActivity.Compute(await contacts.InteractionSummariesAsync(CrmActivity.From(today), cancellationToken), today);
⋮----
logger.LogError(ex, "The overview could not read the CRM.");
⋮----
return View(ViewPath, new CrmOverview(contacts.Storage, statistics, activity, today));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/BusinessCards/Index.cshtml">
@model BusinessCardPage
@*
    A contact from a business card (#161): first the photo, taken or chosen; then what was read, in
    the form beside the photo, to be checked and saved. Nothing is written until the form is saved,
    and the photo is kept nowhere: it is in this page, and nowhere else. A QR code on the card is
    decoded by the script and read with it (#163); the page says what came of it.
*@
@{
    var form = Model.Form;

    string Invalid(string field) => Model.ProblemOf(field) is null ? "" : " is-invalid";
}

@section PageScripts {
    @if (form is null)
    {
        @* Only where a photo is chosen: the form beside it has no use for a QR decoder. *@
        <script src="~/vendor/libs/jsqr/jsqr.js" asp-append-version="true"></script>
    }
    <script src="~/js/crm-business-card.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-controller="Contacts" asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Crm.Contacts"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Crm.Card.Title"]</h5>
        <p class="mb-0">@T["Crm.Card.Lead"]</p>
    </div>
</div>

@if (!Model.CanAdd)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Users.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Crm.NoDatabase.Detail"]</p>
    </div>
}
else if (Model.Storage == ContactStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Crm.Ephemeral"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

@if (form is null)
{
    @if (!Model.Configured)
    {
        <div class="alert alert-warning" role="alert">
            <h6 class="alert-heading mb-1">@T["Crm.Card.NotConfigured"]</h6>
            <p class="mb-0">@T["Crm.Card.NotConfigured.Detail"]</p>
        </div>
    }
    else if (Model.CanAdd)
    {
        <div class="card">
            <div class="card-body">
                @* The script shrinks the photo to a JPEG before it is sent, and sends it as soon as it is chosen; without it, the form posts the photo as taken. *@
                <form method="post" asp-action="Read" enctype="multipart/form-data" id="crm-card-form">
                    <div class="d-flex flex-wrap gap-3 mb-3">
                        <label class="btn btn-primary btn-lg mb-0" for="crm-card-camera">
                            <i class="ti ti-camera me-2"></i>@T["Crm.Card.TakePhoto"]
                        </label>
                        <input class="visually-hidden" type="file" id="crm-card-camera" name="image" accept="image/*" capture="environment" />
                        <label class="btn btn-label-primary btn-lg mb-0" for="crm-card-file">
                            <i class="ti ti-photo me-2"></i>@T["Crm.Card.ChoosePhoto"]
                        </label>
                        <input class="visually-hidden" type="file" id="crm-card-file" name="image" accept="image/*" />
                    </div>
                    @* What a QR code on the card says, decoded from the photo by the script (#163). *@
                    <input type="hidden" name="qr" id="crm-card-qr" />
                    <noscript>
                        <button type="submit" class="btn btn-primary mb-3">@T["Crm.Card.Read"]</button>
                    </noscript>
                    <div id="crm-card-reading" class="d-none mb-3" role="status">
                        <span class="spinner-border spinner-border-sm me-2" aria-hidden="true"></span>@T["Crm.Card.Reading"]
                    </div>
                    <p class="mb-0 small text-body-secondary">@T["Crm.Card.Privacy", Model.Model ?? ""]</p>
                </form>
            </div>
        </div>
    }
}
else
{
    @switch (Model.Outcome)
    {
        case BusinessCardOutcome.Read when Model.ReadNothing:
            <div class="alert alert-warning" role="alert">@T["Crm.Card.ReadNothing"]</div>
            break;
        case BusinessCardOutcome.Read:
            <div class="alert alert-info" role="status">@T["Crm.Card.Check"]</div>
            break;
        case BusinessCardOutcome.Unreachable:
... (129 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Contacts/_NewContactRow.cshtml">
@model (string SignedInAs, IReadOnlyList<string> People, PeopleInitials Initials)
@*
    The grid's blank row (#90), its first whatever the order (#116). Only the name can be typed; the
    other cells show what the contact starts with. Once a name is typed and left, the script creates
    the contact, fills the row from the answer, moves it into the grid directly beneath, and puts a
    fresh blank row here. By is the
    signed-in name, but admin is no one a record names (#108): its By is a dropdown to choose before
    the name is typed, sent with it. By shows initials as every row's does (#115).
*@
<tr class="crm-new">
    @foreach (var (field, _) in ContactFields.Columns)
    {
        switch (field)
        {
            case ContactFields.Name:
                <td data-field="@field" data-value="" data-order="" class="crm-cell crm-name"><span class="text-body-secondary fst-italic">@T["Crm.Contacts.AddHint"]</span></td>
                break;
            case ContactFields.By when ConsolePeople.IsPerson(Model.SignedInAs):
                <td data-field="@field" data-value="" data-order="" class="crm-cell text-body-secondary" title="@T["Crm.Contacts.SetOnCreate"].Value">@Model.Initials.Shown(Model.SignedInAs)</td>
                break;
            case ContactFields.By:
                <td data-field="@field" data-value="" data-order="" class="crm-cell">
                    <select class="form-select form-select-sm" data-new-by aria-label="@T["Crm.Contacts.ChooseBy"].Value" title="@T["Crm.Contacts.ChooseBy"].Value">
                        <option value="" selected>@T["Crm.Contacts.ChooseBy.Short"]</option>
                        @foreach (var person in Model.People)
                        {
                            <option value="@person">@Model.Initials.Choice(person)</option>
                        }
                    </select>
                </td>
                break;
            case ContactFields.Track:
                <td data-field="@field" data-value="" data-order="" class="crm-cell text-body-secondary" title="@T["Crm.Contacts.SetOnCreate"].Value">@ContactTrack.Undecided.DisplayName(S)</td>
                break;
            case ContactFields.Stage:
                <td data-field="@field" data-value="" data-order="" class="crm-cell text-body-secondary" title="@T["Crm.Contacts.SetOnCreate"].Value">@ContactStage.ToContact.DisplayName(S)</td>
                break;
            case ContactFields.Met:
            case ContactFields.With:
                @* Empty until the contact exists; then a click opens its panel, as on any row. *@
                <td data-timeline="@field" data-order="" class="crm-timeline crm-@field" tabindex="0"></td>
                break;
            default:
                @* Current activity and Notes fold once filled (#114), as on any row. *@
                <td data-field="@field" data-value="" data-order="" class="crm-cell crm-@field@(ContactFields.Folds(field) ? " crm-fold" : "")"></td>
                break;
        }
    }
</tr>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Contacts/Delete.cshtml">
@model ContactDeletion
@{
    var contact = Model.Contact;
}

<div class="mb-4">
    <a asp-action="Details" asp-route-id="@contact.Id" class="text-body"><i class="ti ti-arrow-left me-1"></i>@contact.Name</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Crm.Delete.Heading", contact.Name]</h5>
        <p class="mb-0">@T["Crm.Delete.Lead"]</p>
    </div>
</div>

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

<div class="row g-4">
    <div class="col-12 col-lg-5">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Crm.Delete.TheContact"]</h6>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-5">@T["Crm.Field.Name"]</dt>
                    <dd class="col-7">@contact.Name</dd>
                    <dt class="col-5">@T["Crm.Field.Headline"]</dt>
                    <dd class="col-7">@(contact.Headline ?? "-")</dd>
                    <dt class="col-5">@T["Crm.Field.Organisation"]</dt>
                    <dd class="col-7">@(contact.Organisation ?? "-")</dd>
                    <dt class="col-5">@T["Crm.Field.Stage"]</dt>
                    <dd class="col-7">@contact.Stage.DisplayName(S)</dd>
                    <dt class="col-5">@T["Crm.Interactions"]</dt>
                    <dd class="col-7">@(Model.Interactions == 0 ? T["Crm.Delete.Interactions.None"] : Model.Interactions == 1 ? T["Crm.Delete.Interactions.One"] : T["Crm.Delete.Interactions.Many", Model.Interactions])</dd>
                    <dt class="col-5">@T["Crm.Introductions.Title"]</dt>
                    <dd class="col-7">@(Model.Introductions == 0 ? T["Crm.Delete.Introductions.None"] : Model.Introductions == 1 ? T["Crm.Delete.Introductions.One"] : T["Crm.Delete.Introductions.Many", Model.Introductions])</dd>
                    <dt class="col-5">@T["Crm.Details.EnteredBy"]</dt>
                    <dd class="col-7 mb-0">@contact.CreatedBy, @contact.CreatedAt.UtcDateTime.ToString("yyyy-MM-dd")</dd>
                </dl>
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-7">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Crm.Delete.WhatItDoes"]</h6>
            </div>
            <div class="card-body">
                @if (!Model.MayDelete)
                {
                    <div class="alert alert-secondary mb-0" role="status">
                        <h6 class="alert-heading mb-1">@T["Gateway.ViewNotDo.Title"]</h6>
                        <p class="mb-0">@T["Gateway.ViewNotDo.Detail", Html.Raw($"<strong>{Html.Encode(Model.SignedInAs)}</strong>"), Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.Administrator))}</strong>")]</p>
                    </div>
                }
                else
                {
                    <p>@T["Crm.Delete.Detail", Html.Raw($"<strong>{Html.Encode(Model.SignedInAs)}</strong>")]</p>
                    <form method="post" asp-action="DeleteConfirmed" asp-route-id="@contact.Id">
                        <div class="mb-3">
                            <label class="form-label" for="crm-delete-name">@T["Crm.Delete.TypeName", Html.Raw($"<strong>{Html.Encode(contact.Name)}</strong>")]</label>
                            <input type="text" class="form-control" id="crm-delete-name" name="confirmName" required autocomplete="off" spellcheck="false" />
                        </div>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-danger">@T["Crm.Delete.Submit"]</button>
                            <a asp-action="Details" asp-route-id="@contact.Id" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                        </div>
                    </form>
                }
            </div>
        </div>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Contacts/Deleted.cshtml">
@model DeletedContacts
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
}

<div class="mb-4">
    <a asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Crm.Contacts"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Crm.Deleted.Title"]</h5>
        <p class="mb-0">@T["Crm.Deleted.Lead"]</p>
    </div>
</div>

@if (Model.Storage == ContactStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Crm.Ephemeral"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-danger" role="alert">@T["Crm.Deleted.Unreadable"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

@if (Model.Restored is { } restored)
{
    <div class="alert alert-success" role="status">
        @T["Crm.Deleted.Restored", Html.Raw($"<a href=\"{Url.Action("Details", new { id = restored.Id })}\">{Html.Encode(restored.Name)}</a>")]
    </div>
}

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">@(Model.Rows.Count == 1 ? T["Crm.Deleted.Count.One"] : T["Crm.Deleted.Count.Many", Model.Rows.Count])</h5>
    </div>
    @if (Model.Rows.Count == 0)
    {
        <div class="card-body pt-0">
            <p class="mb-0 text-body-secondary">@T["Crm.Deleted.Empty"]</p>
        </div>
    }
    else
    {
        <div class="table-responsive">
            <table class="table table-sm mb-0">
                <thead>
                    <tr>
                        <th>@T["Crm.Field.Name"]</th>
                        <th>@T["Crm.Field.Organisation"]</th>
                        <th>@T["Crm.Field.Stage"]</th>
                        <th>@T["Crm.Deleted.DeletedBy"]</th>
                        <th>@T["Crm.Deleted.DeletedAt"]</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var contact in Model.Rows)
                    {
                        <tr data-contact="@contact.Id">
                            <td class="fw-medium">@contact.Name</td>
                            <td>@(contact.Organisation ?? "-")</td>
                            <td>@contact.Stage.DisplayName(S)</td>
                            <td>@contact.DeletedBy</td>
                            <td class="text-nowrap">@Instant(contact.DeletedAt!.Value)</td>
                            <td class="text-end text-nowrap">
                                <a asp-area="" asp-controller="Audit" asp-action="Index" asp-route-target="@contact.Id" class="me-2 small">@T["Menu.Audit"]</a>
                                <form method="post" asp-action="Restore" asp-route-id="@contact.Id" class="d-inline">
                                    <button type="submit" class="btn btn-sm btn-outline-primary">@T["Crm.Deleted.Restore"]</button>
                                </form>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Contacts/Details.cshtml">
@model ContactDetails
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var contact = Model.Contact;
    var cells = ContactCells.Of(contact, S, Model.Initials);
}

@section PageStyles {
    <partial name="_ContactAssets" model="true" />
}

@section PageScripts {
    <partial name="_ContactAssets" model="false" />
}

<div class="mb-4">
    <a asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Crm.Contacts"]</a>
</div>

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex flex-wrap justify-content-between align-items-start gap-3">
                <div>
                    <h5 class="card-title mb-1">
                        <span data-echo="@ContactFields.Name">@contact.Name</span>
                        <span class="badge bg-label-warning ms-1 crm-shared@(Model.Shared ? "" : " d-none")" title="@T["Js.Crm.SameName.Title"].Value">@T["Js.Crm.SameName"]</span>
                    </h5>
                    <p class="text-body mb-0" data-echo="@ContactFields.Headline">@contact.Headline</p>
                </div>
            </div>
            <div class="card-body pt-0">
                <p class="text-body mb-0">
                    @T["Crm.Details.Lead"]
                    @if (!Model.MayWrite)
                    {
                        <span>@T["Crm.Details.ViewOnly", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.CrmWrite))}</strong>")]</span>
                    }
                </p>
            </div>
        </div>
    </div>
</div>

@if (Model.Storage == ContactStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Crm.Ephemeral"]</div>
}

@if (Model.PeopleUnread)
{
    <div class="alert alert-warning" role="alert">@T["Crm.PeopleUnread"]</div>
}

<div id="crm-problem" class="alert alert-danger d-none" role="alert"></div>

<div class="card mb-4">
    <table id="crm-contacts" class="table table-sm crm-grid mb-0" data-frozen-header="false">
        <thead>
            <tr>
                @foreach (var (field, headingKey) in ContactFields.Columns)
                {
                    <th class="crm-unsortable" data-column="@field">@T[headingKey]</th>
                }
            </tr>
        </thead>
        <tbody>
            <partial name="_ContactRow" model="Model.Row" />
        </tbody>
    </table>
</div>

<div class="card mb-4" id="crm-timeline">
    <div class="card-header">
        <h5 class="card-title mb-1">@T["Crm.Details.Timeline"]</h5>
        <p class="card-subtitle mb-0">@T["Crm.Details.Timeline.Subtitle"]</p>
    </div>
    <div class="card-body">
        <partial name="_Interactions" model="Model.Timeline" />
    </div>
</div>

@* The customers this partner introduced (#147): rows of their own, below what is to be done and above the details. *@
<div class="card mb-4" id="crm-introductions">
    <div class="card-header">
        <h5 class="card-title mb-1">@T["Crm.Introductions.Title"]</h5>
        <p class="card-subtitle mb-0">@T["Crm.Introductions.Subtitle"]</p>
    </div>
    <div class="card-body">
        <partial name="_Introductions" model="Model.Introductions" />
    </div>
</div>

<div class="row g-4 mb-2">
    <div class="col-lg-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Crm.Details.Title"]</h5>
                <p class="card-subtitle mb-0">@T["Crm.Details.Subtitle"]</p>
... (61 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Contacts/Index.cshtml">
@model ContactGrid
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService Authorization
@{
    var mayImport = (await Authorization.AuthorizeAsync(User, ConsolePolicies.CrmImport)).Succeeded;
    var mayDelete = (await Authorization.AuthorizeAsync(User, ConsolePolicies.CrmDelete)).Succeeded;
    var query = Model.Query;
    var count = Model.Rows.Count;
    var byKnown = query.OriginatedBy is null || Model.People.Any(person => string.Equals(person, query.OriginatedBy, StringComparison.OrdinalIgnoreCase));
}

@section PageStyles {
    <partial name="_ContactAssets" model="true" />
}

@section PageScripts {
    <partial name="_ContactAssets" model="false" />
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Crm.Contacts"]</h5>
                <p class="text-body mb-0">
                    @T["Crm.Contacts.Lead"]
                    @if (Model.CanEdit)
                    {
                        <span>@T["Crm.Contacts.Lead.Edit"]</span>
                    }
                    else if (!Model.MayWrite)
                    {
                        <span>@T["Crm.Contacts.Lead.ViewOnly", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.CrmWrite))}</strong>")]</span>
                    }
                </p>
            </div>
        </div>
    </div>
</div>

@if (Model.Storage == ContactStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Users.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Crm.NoDatabase.Detail"]</p>
    </div>
}
else if (Model.Storage == ContactStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Crm.Ephemeral"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Crm.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Crm.Contacts.Unreadable.Detail"]</p>
    </div>
}

@if (Model.PeopleUnread)
{
    <div class="alert alert-warning" role="alert">@T["Crm.PeopleUnread"]</div>
}

@if (Model.Deleted)
{
    <div class="alert alert-success" role="status">
        @T["Crm.Contacts.Deleted.Notice"]
        <a asp-area="" asp-controller="Audit" asp-action="Index" asp-route-kind="crm:contact-delete">@T["Gateway.Installation.Changed.SeeIt"]</a>
    </div>
}

<div id="crm-problem" class="alert alert-danger d-none" role="alert"></div>

<div class="card">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-end gap-3">
        <div>
            <h5 class="card-title mb-1">@(query.IsFiltered
                ? count == 1 ? T["Crm.Contacts.Count.OneMatch"] : T["Crm.Contacts.Count.ManyMatch", count]
                : count == 1 ? T["Crm.Contacts.Count.One"] : T["Crm.Contacts.Count.Many", count])</h5>
            <p class="card-subtitle mb-0">@T["Crm.Contacts.Order"]</p>
        </div>
        <form method="get" asp-action="Index" class="d-flex flex-wrap gap-2 align-items-center" role="search">
            @foreach (var (key, value) in query.RouteValues().Where(pair => pair.Key != "q"))
            {
                <input type="hidden" name="@key" value="@value" />
            }
            <input type="search" name="q" value="@query.Text" class="form-control" style="min-width: 18rem" placeholder="@T["Crm.Contacts.SearchPlaceholder"].Value" aria-label="@T["Generic.Search"].Value" />
            <button type="submit" class="btn btn-primary">@T["Generic.Search"]</button>
            @if (query.IsFiltered)
            {
                <a asp-action="Index" class="btn btn-label-secondary">@T["Generic.Clear"]</a>
            }
            @if (Model.CanEdit)
            {
                @* A contact from a business card's photo (#161), checked before it is added. *@
                <a asp-controller="BusinessCards" asp-action="Index" class="btn btn-label-primary" title="@T["Crm.Card.Button.Title"].Value">
                    <i class="ti ti-id me-1"></i>@T["Crm.Card.Button"]
                </a>
... (124 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/FollowUps/Index.cshtml">
@model FollowUpGrid
@{
    var query = Model.Query;
    var count = Model.Rows.Count;
    var ownerKnown = query.Owner is null || Model.People.Any(person => string.Equals(person, query.Owner, StringComparison.OrdinalIgnoreCase));

    // Mine on and off, keeping the due filter: mine is one link that means each person's own.
    var withMine = new Dictionary<string, string> { ["mine"] = "true" };
    var withoutMine = new Dictionary<string, string>();
    if (query.Due is { } dueFilter)
    {
        withMine["due"] = dueFilter.ToString();
        withoutMine["due"] = dueFilter.ToString();
    }

    var whose = query.Mine ? S["Crm.FollowUps.OfYours"].Value : query.Owner is { } owner ? S["Crm.FollowUps.For", owner].Value : "";
    var overdue = Model.Overdue > 0 ? S["Crm.FollowUps.OverdueCount", Model.Overdue].Value : "";
}
@*
    The follow-ups grid (#92): the contacts grid's columns and rows, drawn by the same _ContactRow and
    edited by the same script against the same endpoints, filtered to the contacts with a next action
    and in the order the controller reads them, overdue first and then by due date. The next action is
    Met?'s last line and its owner With?'s, as on the contacts grid.
*@

@section PageStyles {
    <partial name="_ContactAssets" model="true" />
}

@section PageScripts {
    <partial name="_ContactAssets" model="false" />
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Crm.FollowUps"]</h5>
                <p class="text-body mb-0">
                    @T["Crm.FollowUps.Lead", Html.ActionLink(S["Menu.Crm.Contacts"].Value, "Index", "Contacts")]
                    @if (Model.CanEdit)
                    {
                        <span>@T["Crm.FollowUps.Lead.Edit"]</span>
                    }
                    else if (!Model.MayWrite)
                    {
                        <span>@T["Crm.FollowUps.Lead.ViewOnly", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.CrmWrite))}</strong>")]</span>
                    }
                </p>
            </div>
        </div>
    </div>
</div>

@if (Model.Storage == ContactStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Users.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Crm.FollowUps.NoDatabase.Detail"]</p>
    </div>
}
else if (Model.Storage == ContactStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Crm.Ephemeral"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Crm.FollowUps.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Crm.FollowUps.Unreadable.Detail"]</p>
    </div>
}

@if (Model.PeopleUnread)
{
    <div class="alert alert-warning" role="alert">@T["Crm.PeopleUnread"]</div>
}

<div id="crm-problem" class="alert alert-danger d-none" role="alert"></div>

<div class="card">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-end gap-3">
        <div>
            <h5 class="card-title mb-1">@(count == 1 ? T["Crm.FollowUps.Count.One"] : T["Crm.FollowUps.Count.Many", count])@whose@overdue</h5>
            <p class="card-subtitle mb-0">@T["Crm.FollowUps.Order", InteractionPanel.Iso(query.Today)]</p>
        </div>
        <div class="d-flex flex-wrap gap-2 align-items-center" role="search">
            @if (query.Mine)
            {
                <a asp-action="Index" asp-all-route-data="withoutMine" class="btn btn-sm btn-primary" aria-pressed="true" title="@T["Crm.FollowUps.Mine.On"].Value">@T["Crm.FollowUps.Mine"]</a>
            }
            else
            {
                <a asp-action="Index" asp-all-route-data="withMine" class="btn btn-sm btn-label-primary" aria-pressed="false" title="@T["Crm.FollowUps.Mine.Off"].Value">@T["Crm.FollowUps.Mine"]</a>
            }
            <select class="form-select form-select-sm w-auto" data-filter="owner" data-filter-drops="mine" aria-label="@T["Crm.FollowUps.Filter.Owner"].Value">
                <option value="">@T["Crm.FollowUps.Anyones"]</option>
                @if (!ownerKnown)
                {
... (44 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Import/Index.cshtml">
@model CrmImportPage
@{
    var import = Model.Import;
    string Counts(CrmImport files) => S["Crm.Import.Counts",
        files.Contacts.Count == 1 ? S["Crm.Import.Contacts.One"].Value : S["Crm.Import.Contacts.Many", files.Contacts.Count].Value,
        files.Interactions.Count == 1 ? S["Crm.Import.Interactions.One"].Value : S["Crm.Import.Interactions.Many", files.Interactions.Count].Value,
        files.NextActions == 1 ? S["Crm.Import.NextActions.One"].Value : S["Crm.Import.NextActions.Many", files.NextActions].Value].Value;
}

<div class="mb-4">
    <a asp-controller="Contacts" asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Crm.Contacts"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T["Crm.Import.Title"]</h5>
        <p class="mb-0">@T["Crm.Import.Lead"]</p>
    </div>
</div>

@if (Model.Storage == ContactStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Users.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Crm.Import.NoDatabase.Detail"]</p>
    </div>
}
else if (Model.Storage == ContactStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Crm.Import.Ephemeral"]</div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

@if (Model.Imported && import is not null)
{
    <div class="alert alert-success" role="status">
        <h6 class="alert-heading mb-1">@T["Crm.Import.Imported"]</h6>
        <p class="mb-0">
            @T["Crm.Import.Imported.Detail", Counts(import), Html.Raw($"<strong>{Html.Encode(Model.SignedInAs)}</strong>")]
            @Html.ActionLink(S["Crm.Import.TheContacts"].Value, "Index", "Contacts"), @T["Crm.Import.And"]
            @Html.ActionLink(S["Crm.Import.TheFollowUps"].Value, "Index", "FollowUps").
        </p>
    </div>
}
else if (import is null)
{
    <div class="card">
        <div class="card-header">
            <h6 class="card-title mb-0">@T["Crm.Import.TheFiles"]</h6>
        </div>
        <div class="card-body">
            <form method="post" asp-action="Preview" enctype="multipart/form-data">
                <div class="row g-4 mb-4">
                    <div class="col-12 col-md-6">
                        <label class="form-label" for="contactsFile">contacts.csv</label>
                        <input class="form-control" type="file" id="contactsFile" name="contactsFile" accept=".csv,text/csv" required />
                        <div class="form-text">@string.Join(", ", CrmCsv.ContactColumns)</div>
                    </div>
                    <div class="col-12 col-md-6">
                        <label class="form-label" for="interactionsFile">interactions.csv</label>
                        <input class="form-control" type="file" id="interactionsFile" name="interactionsFile" accept=".csv,text/csv" required />
                        <div class="form-text">@string.Join(", ", CrmCsv.InteractionColumns)</div>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">@T["Licensing.Issue.Preview"]</button>
            </form>
        </div>
    </div>
}
else
{
    @if (!import.Ready)
    {
        <div class="alert alert-danger" role="alert">
            <h6 class="alert-heading mb-1">@T["Crm.Import.NotYet"]</h6>
            <p class="mb-2">@T["Crm.Import.NotYet.Detail"]</p>
            <ul class="mb-0">
                @foreach (var line in import.Problems)
                {
                    <li>@line</li>
                }
            </ul>
        </div>
    }
    else
    {
        <div class="card mb-4">
            <div class="card-body">
                <h6 class="card-title mb-2">@T["Crm.Import.WillCreate"]</h6>
                <p class="mb-3">
                    @T["Crm.Import.WillCreate.Detail", Counts(import), Html.Raw($"<strong>{Html.Encode(Model.SignedInAs)}</strong>")]
                    @if (import.WithoutSummary > 0)
                    {
                        <span>@(import.WithoutSummary == 1 ? T["Crm.Import.WithoutSummary.One", Html.Raw($"<em>{Html.Encode(CrmImport.NoSummary)}</em>")] : T["Crm.Import.WithoutSummary.Many", import.WithoutSummary, Html.Raw($"<em>{Html.Encode(CrmImport.NoSummary)}</em>")])</span>
                    }
                </p>
... (54 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/Components/CrmOverview/Default.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Crm.ViewComponents
@model CrmOverview
@{
    var stats = Model.Statistics;
    // Drawn only where the counts are: a console with no CRM store says so and draws nothing.
    var activity = Model.Storage == ContactStorage.Unavailable ? null : Model.Activity;
    var culture = CultureInfo.CurrentCulture;
}

@* The CRM's section of the console's overview (#90, #92): contacts by stage, by track and by individual or company (#156), and the follow-ups due and overdue, each a link to the grid filtered to it; and the customers introduced by stage (#147), on the partners' pages and nowhere else, so only their total links, to their funnel on the statistics page (#150); and the interactions logged per week (#158), the team's and no one's own, linking nowhere. *@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card" id="crm-overview">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Menu.Crm"]</h5>
                <p class="card-subtitle mb-0">@T["Crm.Overview.Lead"]</p>
            </div>
            <div class="card-body">
                @if (Model.Storage == ContactStorage.Unavailable)
                {
                    <p class="text-body mb-0">@T["Crm.Overview.NoDatabase"]</p>
                }
                else if (stats is null)
                {
                    <div class="alert alert-danger mb-0" role="alert">
                        <h6 class="alert-heading mb-1">@T["Crm.Unreadable.Title"]</h6>
                        <p class="mb-0">@T["Crm.Overview.Unreadable.Detail"]</p>
                    </div>
                }
                else
                {
                    <div class="row g-4 mb-4">
                        <div class="col-sm-6 col-xl-3" data-crm-count="contacts">
                            <span class="text-heading">@T["Crm.Overview.Contacts"]</span>
                            <h4 class="mb-1 mt-1"><a asp-area="Crm" asp-controller="Contacts" asp-action="Index">@stats.Contacts</a></h4>
                            <small class="text-body">@(Model.Storage == ContactStorage.Ephemeral ? T["Crm.Overview.InMemory"] : T["Crm.Overview.InProgramme"])</small>
                        </div>
                        <div class="col-sm-6 col-xl-3" data-crm-count="follow-ups">
                            <span class="text-heading">@T["Menu.Crm.FollowUps"]</span>
                            <h4 class="mb-1 mt-1"><a asp-area="Crm" asp-controller="FollowUps" asp-action="Index">@stats.FollowUps</a></h4>
                            <small class="text-body">
                                @T["Crm.Overview.WithNext"]@(stats.Undated > 0 ? S["Crm.Overview.Undated", stats.Undated].Value : "").
                                <a asp-area="Crm" asp-controller="FollowUps" asp-action="Index" asp-route-mine="true">@T["Crm.Overview.Yours"]</a>
                            </small>
                        </div>
                        <div class="col-sm-6 col-xl-3" data-crm-count="due-week">
                            <span class="text-heading">@T["Crm.Due.Week"]</span>
                            <h4 class="mb-1 mt-1"><a asp-area="Crm" asp-controller="FollowUps" asp-action="Index" asp-route-due="@FollowUpDue.Week">@stats.DueThisWeek</a></h4>
                            <small class="text-body">@T["Crm.Overview.TodayTo", CrmWords.SheetDate(Model.Today.AddDays(6))]</small>
                        </div>
                        <div class="col-sm-6 col-xl-3" data-crm-count="overdue">
                            <span class="text-heading">@T["Crm.Due.Overdue"]</span>
                            <h4 class="mb-1 mt-1@(stats.Overdue > 0 ? " text-danger" : "")"><a asp-area="Crm" asp-controller="FollowUps" asp-action="Index" asp-route-due="@FollowUpDue.Overdue" class="@(stats.Overdue > 0 ? "text-danger" : "")">@stats.Overdue</a></h4>
                            <small class="text-body">@T["Crm.Overview.DueBeforeToday"]</small>
                        </div>
                    </div>

                    <div class="row g-4">
                        <div class="col-md-5">
                            <h6 class="mb-2">@T["Crm.Overview.ByStage"]</h6>
                            <table class="table table-sm mb-0" data-crm-counts="stage">
                                <tbody>
                                    @foreach (var (stage, count) in stats.ByStage)
                                    {
                                        <tr>
                                            <td><a asp-area="Crm" asp-controller="Contacts" asp-action="Index" asp-route-stage="@stage">@stage.DisplayName(S)</a></td>
                                            <td class="text-end" data-stage="@stage">@count</td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                        <div class="col-md-3">
                            <h6 class="mb-2">@T["Crm.Overview.ByTrack"]</h6>
                            <table class="table table-sm mb-0" data-crm-counts="track">
                                <tbody>
                                    @foreach (var (track, count) in stats.ByTrack)
                                    {
                                        <tr>
                                            <td><a asp-area="Crm" asp-controller="Contacts" asp-action="Index" asp-route-track="@track">@track.DisplayName(S)</a></td>
                                            <td class="text-end" data-track="@track">@count</td>
                                        </tr>
                                    }
                                </tbody>
                            </table>

                            <h6 class="mb-2 mt-4">@T["Crm.Overview.ByEntity"]</h6>
                            <table class="table table-sm mb-0" data-crm-counts="entity">
                                <tbody>
                                    @foreach (var (entity, count) in stats.ByEntity)
                                    {
                                        // Null is nobody having said either way: Name's own filter for it (#146).
                                        var key = entity?.ToString() ?? ContactQuery.NotSaid;
                                        <tr>
                                            <td><a asp-area="Crm" asp-controller="Contacts" asp-action="Index" asp-route-entity="@key">@(entity?.DisplayName(S) ?? S["Crm.Entity.NotSaid"].Value)</a></td>
                                            <td class="text-end" data-entity="@key">@count</td>
                                        </tr>
                                    }
                                </tbody>
... (88 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_ContactAssets.cshtml">
@model bool
@*
    The grid's scripts, on the grid and on a row's details alike. DataTables and FixedHeader are the
    template's own table library, copied across as docs/Console-Shell.md allows; crm-contacts.js is
    the in-place editing, done by hand against the area's endpoints. The model says whether to load
    the styles (true, in PageStyles) or the scripts (false, in PageScripts).
*@
@if (Model)
{
    <link rel="stylesheet" href="~/vendor/libs/datatables-bs5/datatables.bootstrap5.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/vendor/libs/datatables-fixedheader-bs5/fixedheader.bootstrap5.css" asp-append-version="true" />
}
else
{
    <script src="~/vendor/libs/datatables-bs5/datatables-bootstrap5.js" asp-append-version="true"></script>
    <script src="~/vendor/libs/datatables-fixedheader-bs5/fixedheader-bootstrap5.js" asp-append-version="true"></script>
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
    <script src="~/js/crm-contacts.js" asp-append-version="true"></script>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_ContactConfig.cshtml">
@model IContactPage
@*
    What wwwroot/js/crm-contacts.js needs, on the grid and on a row's details alike: whether this
    session may edit, the dropdowns' choices in the page's language, By's labels for the people with
    initials, "VS — vera" (#115), which editor each field opens,
    and where to send a save or fetch a row's interactions; and the same for the Customers introduced
    card (#147), whose cells are an introduction's and go to its own endpoint. The anti-forgery token
    goes with every save as the hidden input every form carries.
*@
@Html.AntiForgeryToken()
<script type="application/json" id="crm-config">@Json.Serialize(new
{
    canEdit = Model.CanEdit,
    signedInAs = Model.SignedInAs,
    people = Model.People,
    labels = Model.People.Where(person => Model.Initials.Of(person) is not null).ToDictionary(person => person, Model.Initials.Choice),
    stages = CrmWords.Stages.Select(stage => new { value = stage.ToString(), label = stage.DisplayName(S) }),
    tracks = CrmWords.Tracks.Select(track => new { value = track.ToString(), label = track.DisplayName(S) }),
    entities = CrmWords.Entities.Select(entity => new { value = entity.ToString(), label = entity.DisplayName(S) }),
    engagements = CrmWords.Engagements.Select(engagement => new { value = ((int)engagement).ToString(), label = engagement.DisplayName(S) }),
    declineReasons = CrmWords.DeclineReasons.Select(reason => new { value = reason.ToString(), label = reason.DisplayName(S) }),
    kinds = ContactFields.Editable.ToDictionary(field => field, ContactFields.Kind),
    urls = new
    {
        create = Url.Action("Create", "Contacts", new { area = "Crm" }),
        cell = Url.Action("Cell", "Contacts", new { area = "Crm", id = Guid.Empty }),
        details = Url.Action("Details", "Contacts", new { area = "Crm", id = Guid.Empty }),
        interactions = Url.Action("Index", "Interactions", new { area = "Crm", contactId = Guid.Empty }),
    },
    introductions = new
    {
        stages = IntroductionWords.Stages.Select(stage => new { value = stage.ToString(), label = stage.DisplayName(S) }),
        kinds = IntroductionFields.Editable.ToDictionary(field => field, IntroductionFields.Kind),
        urls = new
        {
            add = Url.Action("Add", "Introductions", new { area = "Crm", contactId = Guid.Empty }),
            cell = Url.Action("Cell", "Introductions", new { area = "Crm", contactId = Guid.Empty, id = Guid.Empty }),
        },
    },
})</script>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_ContactRow.cshtml">
@model ContactRow
@{
    var contact = Model.Contact;
    var cells = ContactCells.Of(contact, S, Model.Initials);
}
@*
    One contact as the grid draws it: a cell per column in the sheet's order, each carrying the
    value an editor starts from and the key it sorts by, which wwwroot/js/crm-contacts.js redraws
    from what a save answers. Met? and With? are drawn from the interactions (#91), a line each by
    date, and the next action (#92) beneath them, never typed into: a click on either opens the row's
    panel beneath it, and Met? sorts by the latest interaction. A cell's text is on the cell's own line, since the notes keep their line breaks as typed.
    A person, in By and in With?, is shown by their initials with the name on hover (#115); data-value keeps the name.
    A contact marked a company carries a building beside its name (#146), the organisation on hover; data-value keeps the bare name.
    Current activity and Notes fold to their first lines (#114), the whole text on hover and behind a
    more / less toggle the script shows when the text is cut; the editor still starts from data-value.
*@
<tr data-contact="@contact.Id" data-version="@contact.Version">
    @foreach (var (field, _) in ContactFields.Columns)
    {
        if (field is ContactFields.Met or ContactFields.With)
        {
            var met = field == ContactFields.Met;
            <td data-timeline="@field" data-order="@(met ? ContactTimeline.Order(Model.Interactions) : "")" class="crm-timeline crm-@field" tabindex="0" title="@T["Crm.Contacts.ClickForInteractions"].Value"><partial name="_TimelineLines" model="new TimelineCell(Model.Interactions, Model.Next, met, Model.Initials)" /></td>
            continue;
        }

        var cell = cells[field];
        if (field == ContactFields.Name)
        {
            <td data-field="@field" data-value="@cell.Value" data-order="@cell.Order" class="crm-cell crm-name">
                @* A company's mark is held to the name's last word by a no-break space, so a narrow column never leaves it on a line of its own. *@
                <a asp-area="Crm" asp-controller="Contacts" asp-action="Details" asp-route-id="@contact.Id" class="fw-medium">@cell.Display</a>@if (cell.Mark is { } mark)
                {
                    <text>&nbsp;<i class="ti ti-building ti-xs text-body-secondary crm-company" role="img" title="@mark" aria-label="@mark"></i></text>
                }
                <span class="badge bg-label-warning ms-1 crm-shared@(Model.Shared ? "" : " d-none")" title="@T["Js.Crm.SameName.Title"].Value">@T["Js.Crm.SameName"]</span>
            </td>
        }
        else if (ContactFields.Folds(field))
        {
            @* Folded to its first lines (#114), on one line of markup since the notes' line breaks are drawn as typed. *@
            <td data-field="@field" data-value="@cell.Value" data-order="@cell.Order" title="@cell.Title" class="crm-cell crm-@field crm-fold"><span class="crm-fold-text">@cell.Display</span><button type="button" class="crm-fold-toggle d-none" data-fold aria-expanded="false" title="@T["Js.Crm.More.Title"].Value">@T["Js.Crm.More"]</button></td>
        }
        else
        {
            <td data-field="@field" data-value="@cell.Value" data-order="@cell.Order" title="@cell.Title" class="crm-cell crm-@field">@cell.Display</td>
        }
    }
</tr>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_InteractionFields.cshtml">
@model (InteractionPanel Panel, InteractionForm Form)
@{
    var form = Model.Form;
    var key = form.Key(Model.Panel.ContactId);
}
@*
    An interaction's fields, the same in the add form and in an interaction's edit form: when, what
    kind, who from KnowledgeFabric took part, and what was said. Drawn with what was typed when the
    form is shown again, with why it was refused under it.
*@
<div class="row g-2">
    <div class="col-6 col-md-3">
        <label class="form-label small mb-1" for="occurred-@key">@T["Crm.Interaction.When"]</label>
        <input type="date" class="form-control form-control-sm" id="occurred-@key" name="occurredOn" value="@form.OccurredOn"
               max="@InteractionPanel.Iso(Model.Panel.Today.AddDays(1))" required />
    </div>
    <div class="col-6 col-md-3">
        <label class="form-label small mb-1" for="kind-@key">@T["Crm.Interaction.Kind"]</label>
        <select class="form-select form-select-sm" id="kind-@key" name="kind">
            @foreach (var kind in CrmWords.Kinds)
            {
                <option value="@kind" selected="@string.Equals(kind.ToString(), form.Kind, StringComparison.OrdinalIgnoreCase)">@kind.DisplayName(S)</option>
            }
        </select>
    </div>
    <div class="col-12 col-md-6">
        <span class="form-label small d-block mb-1">@T["Crm.Interaction.With"]</span>
        @foreach (var (person, index) in Model.Panel.Offered(form).Select((person, index) => (person, index)))
        {
            <div class="form-check form-check-inline mb-0">
                <input class="form-check-input" type="checkbox" id="with-@key-@index" name="participants" value="@person"
                       checked="@form.Participants.Contains(person, StringComparer.OrdinalIgnoreCase)" />
                <label class="form-check-label" for="with-@key-@index">@Model.Panel.Initials.Choice(person)</label>
            </div>
        }
    </div>
    <div class="col-12">
        <label class="form-label small mb-1" for="summary-@key">@T["Crm.Interaction.Summary"]</label>
        <textarea class="form-control form-control-sm" id="summary-@key" name="summary" rows="3" maxlength="@Interaction.SummaryLength" required>@form.Summary</textarea>
    </div>
</div>
@if (form.Problem is { } problem)
{
    <div class="crm-problem small text-danger mt-1" role="alert">@problem</div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_Interactions.cshtml">
@model InteractionPanel
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    // The next action's two forms on one page, perhaps beside other rows' panels: keys for their element ids.
    var nextKey = Model.ContactId.ToString("N");
    var addNextKey = "add-" + nextKey;
}
@*
    A contact's interactions (#91) and its next action (#92): beneath the row on the grid, fetched
    from InteractionsController when Met? or With? is clicked, and in place on the row's details.
    Every answer of that controller is this panel drawn again, and the two hidden blocks at its top
    are the row's Met? and With? as they now read, which wwwroot/js/crm-contacts.js copies into the
    row. data-version is the contact's version as the panel was drawn, which a next-action save is
    checked against, since the next action is part of the contact; data-saved-from, empty unless the
    request that drew it saved one, is the version it was saved from. A session without CRM: Write gets
    the interactions and the next action, and no form. Done (#133) saves at once: the add form's own
    request, as a call today, with the action's text as its summary and its owner taking part, and the
    next action cleared. What it logged is edited afterwards like any interaction.
*@
<div class="crm-panel" data-panel-of="@Model.ContactId" data-met-order="@Model.MetOrder" data-version="@Model.Contact.Version" data-saved-from="@Model.SavedFrom">
    <div class="d-none" data-cell-of="met"><partial name="_TimelineLines" model="new TimelineCell(Model.Interactions, Model.Next, true, Model.Initials)" /></div>
    <div class="d-none" data-cell-of="with"><partial name="_TimelineLines" model="new TimelineCell(Model.Interactions, Model.Next, false, Model.Initials)" /></div>

    @if (Model.Notice is { About: null } notice)
    {
        <div class="alert alert-warning py-2" role="status">@notice.Text</div>
    }

    <div class="crm-next-action mb-3" data-next-action>
        <div class="d-flex flex-wrap align-items-baseline gap-2">
            <span class="fw-medium">@T["Crm.Next"]</span>
            @if (Model.Next is { } next)
            {
                <span class="@(next.Overdue ? "text-danger" : "")" data-next-text>@next.Text</span>
                <span class="text-body-secondary">
                    @(next.Owner is { } owner ? S["Crm.Next.ForOwner", owner].Value : "")@(next.Due is { } due ? S["Crm.Next.Due", CrmWords.SheetDate(due)].Value : S["Crm.Next.NoDueDate"].Value)
                </span>
                @if (next.Overdue)
                {
                    <span class="badge bg-label-danger">@T["Js.Crm.Overdue"]</span>
                }
            }
            else
            {
                <span class="text-body-secondary">@T["Crm.Next.None"]</span>
            }
            @if (Model.CanEdit)
            {
                <span class="ms-auto text-nowrap">
                    @if (Model.Next is { } toDo)
                    {
                        <form method="post" asp-area="Crm" asp-controller="Interactions" asp-action="Add" asp-route-contactId="@Model.ContactId"
                              class="d-inline" data-interaction-form="done">
                            <input type="hidden" name="occurredOn" value="@InteractionPanel.Iso(Model.Today)" />
                            <input type="hidden" name="kind" value="@InteractionKind.Call" />
                            @if (Model.DoneWith is { } doneWith)
                            {
                                <input type="hidden" name="participants" value="@doneWith" />
                            }
                            <input type="hidden" name="summary" value="@toDo.Text" />
                            <input type="hidden" name="contactVersion" value="@Model.Contact.Version" data-contact-version />
                            <input type="hidden" name="nextAction" value="" />
                            <input type="hidden" name="nextActionOwner" value="" />
                            <input type="hidden" name="nextActionDue" value="" />
                            <input type="hidden" name="nextActionChoice" value="@NoNextAction.Done" />
                            <button type="submit" class="btn btn-sm btn-text-success" title="@T["Crm.Next.Done.Title"].Value">@T["Crm.Next.Done"]</button>
                        </form>
                    }
                    <button type="button" class="btn btn-sm btn-text-primary" data-interaction-action="next">@(Model.Next is null ? T["Crm.Next.Set"] : T["Crm.Next.Change"])</button>
                    @if (Model.Next is not null)
                    {
                        <form method="post" asp-area="Crm" asp-controller="Interactions" asp-action="NextAction" asp-route-contactId="@Model.ContactId"
                              class="d-inline" data-interaction-form="clear">
                            <input type="hidden" name="version" value="@Model.Contact.Version" data-contact-version />
                            <input type="hidden" name="nextAction" value="" />
                            <input type="hidden" name="nextActionOwner" value="" />
                            <input type="hidden" name="nextActionDue" value="" />
                            <button type="submit" class="btn btn-sm btn-text-danger" title="@T["Crm.Next.Clear.Title"].Value">@T["Generic.Clear"]</button>
                        </form>
                    }
                </span>
            }
        </div>

        @if (Model.Notice is { About: { } nextAbout } aboutNext && nextAbout == Model.ContactId)
        {
            <div class="alert alert-warning py-2 mt-2 mb-0" role="status">@aboutNext.Text</div>
        }

        @if (Model.CanEdit)
        {
            var nextForm = Model.NextForm;

            <form method="post" asp-area="Crm" asp-controller="Interactions" asp-action="NextAction" asp-route-contactId="@Model.ContactId"
                  class="crm-interaction-form mt-2@(Model.NextTyped is null ? " d-none" : "")" data-interaction-form="next">
                <input type="hidden" name="version" value="@nextForm.Version" data-contact-version />
                <partial name="_NextActionFields" model="(Model, nextForm, nextKey)" />
                <div class="d-flex gap-2 mt-2">
                    <button type="submit" class="btn btn-sm btn-primary">@T["Generic.Save"]</button>
... (122 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_Introductions.cshtml">
@model IntroductionCard
@{
    var key = Model.ContactId.ToString("N");
}
@*
    The Customers introduced card (#147) on a contact's page: one row per introduction, by the day
    it was made, each cell edited in place by wwwroot/js/crm-contacts.js against
    IntroductionsController's cell endpoint with the introduction's own version (data-version), and
    for a session that may write the form to add one. Every answer of that controller's add is this
    card drawn again, which the script puts in place of it. The partner is not a cell (#145,
    decision 2). A session without CRM: Write gets the rows and no form.
*@
<div class="crm-introductions" data-introductions-of="@Model.ContactId">
    @if (Model.Rows.Count == 0)
    {
        <p class="text-body-secondary mb-3">@T["Crm.Introductions.None"]</p>
    }
    else
    {
        <div class="table-responsive mb-3">
            <table class="table table-sm crm-grid crm-introductions-grid mb-0">
                <thead>
                    <tr>
                        @foreach (var (field, headingKey) in IntroductionFields.Columns)
                        {
                            <th data-column="@field">@T[headingKey]</th>
                        }
                    </tr>
                </thead>
                <tbody>
                    @foreach (var introduction in Model.Rows)
                    {
                        var cells = IntroductionCells.Of(introduction, S);

                        <tr data-introduction="@introduction.Id" data-contact-of="@introduction.ContactId" data-version="@introduction.Version">
                            @foreach (var (field, _) in IntroductionFields.Columns)
                            {
                                var cell = cells[field];
                                if (field == IntroductionFields.Customer)
                                {
                                    <td data-field="@field" data-value="@cell.Value" data-order="@cell.Order" class="crm-cell crm-introduction-@field"><span class="fw-medium">@cell.Display</span></td>
                                }
                                else if (IntroductionFields.Folds(field))
                                {
                                    @* Folded to its first lines (#114), on one line of markup since the notes' line breaks are drawn as typed. *@
                                    <td data-field="@field" data-value="@cell.Value" data-order="@cell.Order" title="@cell.Title" class="crm-cell crm-notes crm-introduction-@field crm-fold"><span class="crm-fold-text">@cell.Display</span><button type="button" class="crm-fold-toggle d-none" data-fold aria-expanded="false" title="@T["Js.Crm.More.Title"].Value">@T["Js.Crm.More"]</button></td>
                                }
                                else
                                {
                                    <td data-field="@field" data-value="@cell.Value" data-order="@cell.Order" title="@cell.Title" class="crm-cell crm-field crm-introduction-@field">@cell.Display</td>
                                }
                            }
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }

    @if (Model.CanEdit)
    {
        var add = Model.AddForm;

        <form method="post" asp-area="Crm" asp-controller="Introductions" asp-action="Add" asp-route-contactId="@Model.ContactId"
              class="crm-introduction-form crm-introduction-add" data-introduction-form="add">
            <h6 class="mb-2">@T["Crm.Introductions.Log"]</h6>
            <div class="row g-2">
                <div class="col-12 col-md-4">
                    <label class="form-label small mb-1" for="introduction-customer-@key">@T["Crm.Introduction.Customer"]</label>
                    <input type="text" class="form-control form-control-sm" id="introduction-customer-@key" name="customer" value="@add.Customer"
                           maxlength="@Introduction.CustomerLength" required />
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label small mb-1" for="introduction-on-@key">@T["Crm.Introduction.IntroducedOn"]</label>
                    <input type="date" class="form-control form-control-sm" id="introduction-on-@key" name="introducedOn" value="@add.IntroducedOn"
                           max="@InteractionPanel.Iso(Model.Today.AddDays(1))" required />
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label small mb-1" for="introduction-stage-@key">@T["Crm.Introduction.Stage"]</label>
                    <select class="form-select form-select-sm" id="introduction-stage-@key" name="stage">
                        @foreach (var stage in IntroductionWords.Stages)
                        {
                            <option value="@stage" selected="@string.Equals(stage.ToString(), add.Stage, StringComparison.OrdinalIgnoreCase)">@stage.DisplayName(S)</option>
                        }
                    </select>
                </div>
                <div class="col-12 col-md-4">
                    <label class="form-label small mb-1" for="introduction-person-@key">@T["Crm.Introduction.ContactPerson"]</label>
                    <input type="text" class="form-control form-control-sm" id="introduction-person-@key" name="contactPerson" value="@add.ContactPerson"
                           maxlength="@Introduction.ContactPersonLength" />
                </div>
                <div class="col-12">
                    <label class="form-label small mb-1" for="introduction-notes-@key">@T["Crm.Introduction.Notes"]</label>
                    <textarea class="form-control form-control-sm" id="introduction-notes-@key" name="notes" rows="2" maxlength="@Introduction.NotesLength">@add.Notes</textarea>
                </div>
            </div>
            @if (add.Problem is { } problem)
            {
                <div class="crm-problem small text-danger mt-1" role="alert">@problem</div>
            }
... (11 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_NextActionFields.cshtml">
@model (InteractionPanel Panel, NextActionForm Form, string Key)
@{
    var form = Model.Form;
    var key = Model.Key;
}
@*
    A next action's three fields (#92), the same in the panel's next-action form and in its add form:
    what is to be done, by whom, and by when. Without the text there is none, whatever the owner says;
    the owner starts at the signed-in name, or at no one for admin, whom no record names (#108). Drawn with what was typed when the form is shown again,
    with why it was refused under it.
*@
<div class="row g-2">
    <div class="col-12 col-md-6">
        <label class="form-label small mb-1" for="next-text-@key">@T["Crm.Next.What"]</label>
        <input type="text" class="form-control form-control-sm" id="next-text-@key" name="nextAction" value="@form.Text"
               maxlength="@Contact.NextActionLength" placeholder="@T["Crm.Next.Placeholder"].Value" autocomplete="off" />
    </div>
    <div class="col-6 col-md-3">
        <label class="form-label small mb-1" for="next-owner-@key">@T["Crm.Next.ByWhom"]</label>
        <select class="form-select form-select-sm" id="next-owner-@key" name="nextActionOwner">
            @if (form.Owner.Length == 0)
            {
                <option value="" selected></option>
            }
            @foreach (var person in Model.Panel.Owners(form))
            {
                <option value="@person" selected="@string.Equals(person, form.Owner, StringComparison.OrdinalIgnoreCase)">@Model.Panel.Initials.Choice(person)</option>
            }
        </select>
    </div>
    <div class="col-6 col-md-3">
        <label class="form-label small mb-1" for="next-due-@key">@T["Crm.Next.ByWhen"]</label>
        <input type="date" class="form-control form-control-sm" id="next-due-@key" name="nextActionDue" value="@form.Due" />
    </div>
</div>
@if (form.Problem is { } problem)
{
    <div class="crm-problem small text-danger mt-1" role="alert">@problem</div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Shared/_TimelineLines.cshtml">
@model TimelineCell
@*
    One of the grid's two drawn cells: a line per interaction, by date, as the sheet wrote them (#91),
    Met? reading "Call 23.09.26" and With? who took part on the same line, "rob, vera"; then the next
    action (#92), set apart beneath them as the sheet put "FIX a meeting" after the calls: in Met? its
    text and due date, "FIX a meeting by 15.10.26", marked when overdue, and in With? its owner. A
    person in With? is shown by their initials, "RR, VS", each with the name on hover (#115).
    wwwroot/js/crm-contacts.js redraws the next action's line alone after a cell save, so its markup
    there and here change together.
*@
@foreach (var interaction in Model.Interactions)
{
    <div class="crm-line">@(Model.Met ? CrmWords.MetLine(interaction, S) : Model.Initials.People(interaction.Participants))</div>
}
@if (Model.Next is { } next)
{
    var marked = "crm-line crm-next" + (next.Overdue ? " crm-overdue" : "");
    if (Model.Met)
    {
        <div class="@marked" title="@next.Title(S)"><span class="crm-next-text">@next.Text</span>@if (next.SheetDue is { } due) {<span class="crm-next-due"> @T["Js.Crm.By", due]</span>}@if (next.Overdue) {<span class="badge bg-label-danger ms-1">@T["Js.Crm.Overdue"]</span>}</div>
    }
    else
    {
        <div class="@marked" title="@next.Title(S)">@if (next.Owner is { } owner) {@Model.Initials.Person(owner)}</div>
    }
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/Statistics/Index.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Crm.Controllers
@model CrmStatisticsPage
@{
    var funnel = Model.Funnel;

    // A day gone has no grid to link to: the grid is today's.
    var linked = Model.AsOf is null;

    string Stages(IEnumerable<ContactStage> stages) => string.Join(", ", stages.Select(stage => stage.DisplayName(S)));

    // The funnel's lines in Roberto's order, each indented under the line it divides. The three ways a
    // discussion ends, at level 3, carry their share of the concluded ones.
    var lines = new List<FunnelLine>();
    if (funnel is not null)
    {
        lines.Add(new("identified", 0, S["Crm.Statistics.Identified"], funnel.Identified, Stages: S["Crm.Statistics.AllStages"]));
        lines.Add(new("to-schedule", 1, S["Crm.Statistics.ToSchedule"], funnel.ToSchedule, Stages: Stages(CrmFunnel.ToScheduleStages)));
        lines.Add(new("to-meet-soon", 1, S["Crm.Statistics.ToMeetSoon"], funnel.ToMeetSoon, Stages: Stages(CrmFunnel.ToMeetSoonStages), Link: ContactStage.MeetingPlanned));
        lines.Add(new("met", 1, S["Crm.Statistics.Met"], funnel.Met, Stages: S["Crm.Statistics.MetStages", ContactStage.Met.DisplayName(S)]));
        lines.Add(new("in-discussion", 2, S["Crm.Statistics.InDiscussion"], funnel.InDiscussion, Stages: Stages(CrmFunnel.InDiscussionStages), Link: ContactStage.Met));
        lines.Add(new("concluded", 2, S["Crm.Statistics.Concluded"], funnel.Concluded, Stages: S["Crm.Statistics.ConcludedStages"]));
        lines.Add(new("accepted", 3, S["Crm.Statistics.Accepted"], funnel.Accepted, "text-success fw-semibold", Stages(CrmFunnel.AcceptedStages)));
        lines.AddRange(funnel.AcceptedByTrack.Select(line => new FunnelLine($"accepted-{line.Track}", 4, line.Track.DisplayName(S), line.Count)));
        lines.Add(new("declined", 3, S["Crm.Statistics.Declined"], funnel.Declined, "text-danger fw-semibold", Stages(CrmFunnel.DeclinedStages), ContactStage.DeclinedOrDormant));
        lines.AddRange(funnel.DeclinedByReason.Select(line => new FunnelLine(
            $"declined-{line.Reason?.ToString() ?? "unsaid"}", 4, line.Reason?.DisplayName(S) ?? S["Crm.Statistics.NoReason"], line.Count)));
        lines.Add(new("rejected", 3, S["Crm.Statistics.Rejected"], funnel.Rejected, "fw-semibold", Stages(CrmFunnel.RejectedStages), ContactStage.Rejected));
    }

    // Each point of the series links to the funnel as it stood that day; today's is the page without a day.
    string PointLink(DateOnly day) => day == Model.Today
        ? Url.Action("Index")!
        : Url.Action("Index", new { asOf = CrmStatisticsPage.Iso(day) })!;

    var series = Model.Series ?? [];
    var chart = new
    {
        labels = series.Select(point => point.Day.ToString(Model.Weekly ? "d MMM" : "MMM yyyy", CultureInfo.CurrentCulture)).ToList(),
        titles = series.Select(point => point.Day.ToString("ddd d MMMM yyyy", CultureInfo.CurrentCulture)).ToList(),
        links = series.Select(point => PointLink(point.Day)).ToList(),
        series = new[]
        {
            new { name = S["Crm.Statistics.Identified"].Value, data = series.Select(point => point.Funnel.Identified).ToList() },
            new { name = S["Crm.Statistics.Met"].Value, data = series.Select(point => point.Funnel.Met).ToList() },
            new { name = S["Crm.Statistics.Accepted"].Value, data = series.Select(point => point.Funnel.Accepted).ToList() },
        },
    };

    // What the partners produced (#150), in the same form: every stage a line beneath the customers
    // introduced, then by the partner's track, then how far they ever got, each a share of the
    // customers introduced. No line links anywhere: introductions have no grid (#145, decision 12).
    var introductions = Model.Introductions;
    var produced = introductions?.Funnel;

    string? OfIntroduced(int count) => produced?.OfIntroduced(count) is { } fraction ? fraction.ToString("P0", CultureInfo.CurrentCulture) : null;
    string IntroductionStages(IEnumerable<IntroductionStage> stages) => string.Join(", ", stages.Select(stage => stage.DisplayName(S)));

    var byStage = new List<FunnelLine>();
    var byTrack = new List<FunnelLine>();
    var reached = new List<FunnelLine>();
    if (produced is not null)
    {
        byStage.Add(new("introduced", 0, S["Crm.Statistics.Introduced"], produced.Introduced, Stages: S["Crm.Statistics.AllStages"]));
        byStage.AddRange(produced.ByStage.Select(line => new FunnelLine(
            $"stage-{line.Stage}", 1,
            line.Stage == IntroductionStage.Introduced ? S["Crm.Statistics.NotYetMet"] : line.Stage.DisplayName(S),
            line.Count,
            line.Stage == IntroductionStage.UnderContract ? "text-success fw-semibold" : null,
            line.Stage.DisplayName(S),
            Share: OfIntroduced(line.Count))));
        byTrack.AddRange(produced.ByTrack.Select(line => new FunnelLine($"track-{line.Track}", 1, line.Track.DisplayName(S), line.Count, Share: OfIntroduced(line.Count))));
        reached.Add(new("reached-pilot", 1, S["Crm.Statistics.ReachedPilot"], produced.ReachedPilot,
            Stages: S["Crm.Statistics.EverAt", IntroductionStages(IntroductionFunnel.PilotOrFurther)], Share: OfIntroduced(produced.ReachedPilot)));
        reached.Add(new("reached-contract", 1, S["Crm.Statistics.ReachedContract"], produced.ReachedContract, "text-success fw-semibold",
            S["Crm.Statistics.EverAt", IntroductionStages(IntroductionFunnel.ContractOrFurther)], Share: OfIntroduced(produced.ReachedContract)));
    }

    var introductionSeries = produced is null ? [] : introductions!.Series;
    var introductionChart = new
    {
        labels = introductionSeries.Select(point => point.Day.ToString(introductions!.Weekly ? "d MMM" : "MMM yyyy", CultureInfo.CurrentCulture)).ToList(),
        titles = introductionSeries.Select(point => point.Day.ToString("ddd d MMMM yyyy", CultureInfo.CurrentCulture)).ToList(),
        links = introductionSeries.Select(point => PointLink(point.Day)).ToList(),
        series = new[]
        {
            new { name = S["Crm.Statistics.Introduced"].Value, data = introductionSeries.Select(point => point.Introduced).ToList() },
            new { name = S["Crm.IntroductionStage.UnderContract"].Value, data = introductionSeries.Select(point => point.UnderContract).ToList() },
        },
    };

    // The chart library and its script, once, when either chart is drawn.
    var charted = (Model.Began is not null && series.Count >= 2) || introductionSeries.Count >= 2;
}
@*
    The programme's statistics (#120): Roberto's funnel for the go-to-market story, a line each,
    indented under the line it divides, with the stages each line counts beside it so the numbers can
    be checked against the grid. Counts only: no line names a contact (#87, decision 9). A line of
    one stage links to the grid filtered to it, today; on a day gone (#139) the funnel is the change
    record replayed to that day, and its three headline lines are drawn over time beneath it.
... (313 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/_ViewImports.cshtml">
@using KnowledgeFabric.AdminConsole
@using KnowledgeFabric.AdminConsole.Models
@using KnowledgeFabric.AdminConsole.Security
@using KnowledgeFabric.AdminConsole.Crm
@using KnowledgeFabric.AdminConsole.Areas.Crm.Models
@using Microsoft.AspNetCore.Mvc.Localization
@using KnowledgeFabric.AdminConsole.Localisation
@using KnowledgeFabric.AdminConsole.Resources
@using Microsoft.Extensions.Localization
@inject IHtmlLocalizer<ConsoleResource> T
@inject IStringLocalizer<ConsoleResource> S
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Crm/Views/_ViewStart.cshtml">
@{
    Layout = "_ContentNavbarLayout";
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Controllers/HomeController.cs">
public sealed class HomeController(
⋮----
IStringLocalizer<ConsoleResource> text) : Controller
⋮----
public async Task<IActionResult> Index(CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
var cached = await cache.GetAsync(gateway.StatusAsync, cancellationToken);
⋮----
? await gateway.UsageDailyAsync(UsageRange.Last(UsageDays, UsageRange.Today(now)), cancellationToken: cancellationToken)
⋮----
return View(new GatewayOverview(cached, options.Value.BaseAddress?.Host, now) { Usage = usage });
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Controllers/InstallationsController.cs">
public sealed class InstallationsController(
⋮----
ILogger<InstallationsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(
⋮----
var filter = new InstallationFilter(row, status, seen, below, q, sort, Math.Clamp(page, 1, InstallationFilter.MaxPage));
var (query, problem) = filter.ToQuery(clock.GetUtcNow(), text);
⋮----
return View(new InstallationList(filter, problem, GatewayAnswer.Of(GatewayOutcome.Answered), EmptyRegister, RegisterRead: true, null, Host));
⋮----
var one = await gateway.InstallationAsync(id, cancellationToken);
⋮----
return View(new InstallationList(filter, null, new GatewayAnswer(one.Outcome, [], one.Detail), EmptyRegister, RegisterRead: true, null, Host));
⋮----
var listed = gateway.InstallationsAsync(query, cancellationToken);
⋮----
return View(new InstallationList(filter, null, await listed, names, read, searchedLicence, Host));
⋮----
public async Task<IActionResult> Details(Guid id, string? changed, int? days, CancellationToken cancellationToken)
⋮----
ViewData["changed"] = Changes.Contains(changed) ? changed : null;
⋮----
var answer = await gateway.InstallationAsync(id, cancellationToken);
⋮----
? gateway.UsageDailyAsync(UsageRange.Last(InstallationDetails.UsageDaysOf(days), UsageRange.Today(clock.GetUtcNow())), id, cancellationToken)
⋮----
return View(new InstallationDetails(id, answer, licenceRow, licenceFiles, registerRead, Host)
⋮----
public Task<IActionResult> Revoke(Guid id, CancellationToken cancellationToken) =>
ConfirmAsync(id, InstallationChangeKind.Revoke, new InstallationChangeForm(), failure: null, cancellationToken);
⋮----
public Task<IActionResult> Restore(Guid id, CancellationToken cancellationToken) =>
ConfirmAsync(id, InstallationChangeKind.Restore, new InstallationChangeForm(), failure: null, cancellationToken);
⋮----
public Task<IActionResult> Revoke(Guid id, InstallationChangeForm form, CancellationToken cancellationToken) =>
⋮----
public Task<IActionResult> Restore(Guid id, InstallationChangeForm form, CancellationToken cancellationToken) =>
⋮----
private async Task<IActionResult> ChangeAsync(Guid id, InstallationChangeKind kind, InstallationChangeForm form, CancellationToken cancellationToken)
⋮----
var shared = GatewayOperator.IsShared(User);
⋮----
if (shared && !GatewayOperator.IsNameable(name))
⋮----
ModelState.AddModelError(nameof(form.Name), text["Gateway.YourName.Required"]);
⋮----
return await ConfirmAsync(id, kind, form, GatewayInstallationAnswer.Of(GatewayOutcome.WritesNotConfigured), cancellationToken);
⋮----
var current = await gateway.InstallationAsync(id, cancellationToken);
⋮----
var operatorName = GatewayOperator.For(User, name);
⋮----
? await gateway.RevokeAsync(id, operatorName, cancellationToken)
: await gateway.RestoreAsync(id, operatorName, cancellationToken);
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
Target: id.ToString(),
OccurredAt: clock.GetUtcNow(),
⋮----
["reason"] = form.Reason!.Trim(),
⋮----
["revokedAt"] = changed.RevokedAt?.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", System.Globalization.CultureInfo.InvariantCulture),
⋮----
private async Task<IActionResult> ConfirmAsync(
⋮----
return View("Change", new InstallationChange(
⋮----
NeedsName: GatewayOperator.IsShared(User),
⋮----
private async Task<bool> MayWriteAsync() =>
(await authorization.AuthorizeAsync(User, ConsolePolicies.GatewayWrite)).Succeeded;
⋮----
private async Task<(RegisterRecord? Latest, int Files, bool Read)> LicenceFilesAsync(Guid? licenceId, CancellationToken cancellationToken)
⋮----
var files = (await register.SearchAsync(new RegisterQuery { Text = id.ToString() }, 1, 100, cancellationToken)).Rows
.Where(file => file.LicenseId == id)
.ToList();
⋮----
return (files.FirstOrDefault(), files.Count, true);
⋮----
logger.LogError(ex, "An installation's page could not read the licence register.");
⋮----
private async Task<(IReadOnlyDictionary<Guid, RegisterSummary> Names, bool Read)> NamesAsync(CancellationToken cancellationToken)
⋮----
return (RegisterSummary.LatestByLicence(await register.SummariesAsync(cancellationToken)), true);
⋮----
logger.LogError(ex, "The installations list could not read the licence register.");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Controllers/PolicyChangeController.cs">
public sealed class PolicyChangeController(
⋮----
ILogger<PolicyChangeController> logger) : Controller
⋮----
private static readonly JsonSerializerOptions Wire = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
⋮----
public async Task<IActionResult> Tier(string tier, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> Tier(string tier, TierChangeForm form, CancellationToken cancellationToken)
⋮----
ModelState.Clear();
⋮----
var proposed = form.Read(ModelState, text);
⋮----
ModelState.AddModelError("", text["Gateway.Tier.NoChange"]);
⋮----
lowerings = AllowanceRule.Lowerings(current.Levers, proposed, text);
⋮----
var seen = PolicyChangeForm.Fingerprint(current.Levers);
⋮----
var operatorName = GatewayOperator.For(User, form.Name);
var answer = await gateway.ChangeTierAsync(row, proposed!, operatorName, cancellationToken);
⋮----
["installationsServed"] = written.InstallationsServed.ToString(),
⋮----
public async Task<IActionResult> MinimumVersion(CancellationToken cancellationToken)
⋮----
var current = await gateway.PolicyAsync(cancellationToken);
var form = new MinimumVersionForm { MinimumAppVersion = current.Policy?.MinimumAppVersion };
⋮----
return View("MinimumVersion", new MinimumVersionChange(PolicyChangeStep.Edit, current, await WriterAsync(), form));
⋮----
public async Task<IActionResult> MinimumVersion(MinimumVersionForm form, CancellationToken cancellationToken)
⋮----
var change = new MinimumVersionChange(PolicyChangeStep.Edit, current, await WriterAsync(), form);
⋮----
var version = form.Read(ModelState, text);
⋮----
ModelState.AddModelError(nameof(form.MinimumAppVersion), text["Gateway.Minimum.NoChange"]);
⋮----
change = change with { Proposed = version, RowProblems = version is null ? [] : PolicyChange.Problems(after, text) };
⋮----
change = change with { Step = PolicyChangeStep.Review, Refused = await gateway.ActiveBelowAsync(version!, cancellationToken) };
var seen = PolicyChangeForm.Fingerprint(before.MinimumAppVersion);
⋮----
var answer = await gateway.ChangePolicyAsync(after, operatorName, cancellationToken);
⋮----
["refusedAtNewMinimum"] = change.Refused!.Installations.Count.ToString(),
⋮----
public async Task<IActionResult> Velocity(CancellationToken cancellationToken)
⋮----
var form = new VelocityForm
⋮----
public async Task<IActionResult> Velocity(VelocityForm form, CancellationToken cancellationToken)
⋮----
if (form.TryRead(ModelState, change.WasArmed, text, out var perHour, out var perDay)
⋮----
ModelState.AddModelError("", before.VelocityArmed ? text["Gateway.Velocity.NoChange"] : text["Gateway.Velocity.NoChange.Off"]);
⋮----
change = change with { Proposed = (perHour, perDay), RowProblems = ModelState.IsValid ? PolicyChange.Problems(after, text) : [] };
⋮----
var seen = PolicyChangeForm.Fingerprint(new { before.EnrolmentsPerHour, before.EnrolmentsPerDay });
⋮----
public async Task<IActionResult> Ceiling(CancellationToken cancellationToken)
⋮----
var form = new CeilingForm { BrakeOn = ceiling is not null, GlobalTokenCeiling = ceiling?.ToString(CultureInfo.InvariantCulture) };
⋮----
return View("Ceiling", new CeilingChange(PolicyChangeStep.Edit, current, await WriterAsync(), form, await gateway.StatusAsync(cancellationToken)));
⋮----
public async Task<IActionResult> Ceiling(CeilingForm form, CancellationToken cancellationToken)
⋮----
var status = gateway.StatusAsync(cancellationToken);
⋮----
var change = new CeilingChange(PolicyChangeStep.Edit, current, await WriterAsync(), form, await status);
⋮----
if (form.TryRead(ModelState, text, out var ceiling) && ceiling == before.GlobalTokenCeiling)
⋮----
ModelState.AddModelError(nameof(form.GlobalTokenCeiling), ceiling is null
⋮----
change = change with { Read = ModelState.IsValid, Proposed = ceiling, RowProblems = ModelState.IsValid ? PolicyChange.Problems(after, text) : [] };
⋮----
var seen = PolicyChangeForm.Fingerprint(before.GlobalTokenCeiling);
⋮----
cache.Forget();
⋮----
["usedThisMonth"] = change.Brake?.Used.ToString(),
⋮----
private async Task<Blocked?> BlockedAsync(PolicyChangeForm form)
⋮----
form.CheckConfirm(ModelState, GatewayOperator.IsShared(User), text);
⋮----
return new Blocked(null);
⋮----
return new Blocked(GatewayOutcome.WritesNotConfigured);
⋮----
return (await authorization.AuthorizeAsync(User, ConsolePolicies.GatewayWrite)).Succeeded ? null : new Blocked(null);
⋮----
private async Task RecordAsync<TRow>(
⋮----
var shared = GatewayOperator.IsShared(User);
... (54 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Controllers/PolicyController.cs">
public sealed class PolicyController(
⋮----
ILogger<PolicyController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? changed, CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
⋮----
var policy = gateway.PolicyAsync(cancellationToken);
var status = cache.GetAsync(gateway.StatusAsync, cancellationToken);
⋮----
if (InstallationQuery.IsVersion(minimum))
⋮----
if (PolicyPage.IsAbove(LicenceValidator.ProductRelease, minimum))
⋮----
return View(new PolicyPage(answer, await status, licences, belowMinimum, belowRelease, options.Value.BaseAddress?.Host, now)
⋮----
MayWrite = (await authorization.AuthorizeAsync(User, ConsolePolicies.GatewayWrite)).Succeeded,
Changed = Changes.Contains(changed) ? changed : null,
⋮----
private async Task<VersionCount> BelowAsync(string version, CancellationToken cancellationToken)
⋮----
var answer = await gateway.InstallationsAsync(
new InstallationQuery { AppVersionBelow = version, Revoked = false, Limit = 1 }, cancellationToken);
⋮----
return new VersionCount(version, answer.Outcome, answer.Outcome == GatewayOutcome.Answered ? answer.Total : null);
⋮----
private async Task<IReadOnlyDictionary<string, int>?> LicencesInForceAsync(DateTime nowUtc, CancellationToken cancellationToken)
⋮----
return PolicyPage.CountByAllowance(await register.SummariesAsync(cancellationToken), nowUtc);
⋮----
logger.LogError(ex, "The policy page could not read the licence register.");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Controllers/UsageController.cs">
public sealed class UsageController(
⋮----
ILogger<UsageController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? purpose, string? sort, string? tier, CancellationToken cancellationToken)
⋮----
return View(await UsageAsync(new UsageFilter(purpose, sort, tier), cancellationToken));
⋮----
public async Task<IActionResult> Export(string? purpose, string? sort, string? tier, CancellationToken cancellationToken)
⋮----
var usage = await UsageAsync(new UsageFilter(purpose, sort, tier), cancellationToken);
⋮----
return RedirectToAction(nameof(Index), usage.Filter.RouteValues());
⋮----
var csv = new StringBuilder();
csv.Append(RegisterRecord.CsvLine(UsageByLicence.CsvColumns)).Append("\r\n");
⋮----
foreach (var line in usage.CsvLines())
⋮----
csv.Append(line).Append("\r\n");
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
["licences"] = usage.Licences.Count.ToString(),
["rows"] = lines.ToString(),
⋮----
var fileName = string.Create(CultureInfo.InvariantCulture, $"gateway-usage-{usage.AsOfUtc:yyyyMMdd-HHmm}.csv");
return File(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(csv.ToString()), "text/csv", fileName);
⋮----
public async Task<IActionResult> History(string? from, string? to, int? top, CancellationToken cancellationToken)
⋮----
public async Task<IActionResult> HistoryExport(string? from, string? to, int? top, string? what, CancellationToken cancellationToken)
⋮----
csv.Append(RegisterRecord.CsvLine(days ? UsageHistory.DaysCsvColumns : UsageHistory.TopCsvColumns)).Append("\r\n");
⋮----
foreach (var line in days ? history.DaysCsvLines() : history.TopCsvLines())
⋮----
["from"] = UsageRange.Format(range.From),
["to"] = UsageRange.Format(range.To),
⋮----
var fileName = string.Create(CultureInfo.InvariantCulture, $"gateway-usage-{(days ? "days" : "top")}-{range.From:yyyyMMdd}-{range.To:yyyyMMdd}.csv");
⋮----
private async Task<UsageHistory> HistoryAsync(string? from, string? to, int? top, CancellationToken cancellationToken)
⋮----
var today = UsageRange.Today(clock.GetUtcNow());
var request = UsageHistoryRequest.Read(from, to, top, today, text);
⋮----
return new UsageHistory(request, today, null, null, [], host);
⋮----
var daily = gateway.UsageDailyAsync(range, cancellationToken: cancellationToken);
var summary = await gateway.UsageSummaryAsync(range, request.Top, cancellationToken);
⋮----
if (listed.Any(installation => installation.Row is "standard" or "enterprise"))
⋮----
var licensed = gateway.LicensedInstallationsAsync(cancellationToken);
⋮----
licences = RegisterSummary.LatestByLicence(summaries);
⋮----
.Where(installation => installation.LicenceId is not null)
.ToDictionary(installation => installation.InstallationId, installation => installation.LicenceId!.Value)
⋮----
var ranked = listed.Select((installation, i) =>
⋮----
Guid? licenceId = licenceIds.TryGetValue(installation.InstallationId, out var id) ? id : null;
return new TopInstallation(i + 1, installation, licenceId, licenceId is { } held ? licences.GetValueOrDefault(held) : null);
}).ToList();
⋮----
return new UsageHistory(request, today, summary, await daily, ranked, host);
⋮----
private async Task<UsageByLicence> UsageAsync(UsageFilter filter, CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
⋮----
var installations = gateway.LicensedInstallationsAsync(cancellationToken);
⋮----
var usage = UsageByLicence.Join(filter, summaries, read, await installations, now.UtcDateTime, options.Value.BaseAddress?.Host, text);
⋮----
var lastMonth = UsageRange.PreviousMonth(UsageRange.Today(now));
⋮----
? new GatewayUsageTokensAnswer(GatewayOutcome.Answered, lastMonth, new Dictionary<Guid, long>(), Unread: 0, Detail: null)
: await gateway.TokensInAsync(lastMonth, ids, cancellationToken),
⋮----
private async Task<(IReadOnlyList<RegisterSummary> Rows, bool Read)> SummariesAsync(CancellationToken cancellationToken)
⋮----
return (await register.SummariesAsync(cancellationToken), true);
⋮----
logger.LogError(ex, "The usage by licence could not read the licence register.");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/AllowanceWords.cs">
public static class AllowanceWords
⋮----
private static readonly TimeSpan Rolling = TimeSpan.FromDays(30);
⋮----
public static string N(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
⋮----
public static string RowOwner(GatewayAllowance allowance, IStringLocalizer<ConsoleResource> text) =>
string.IsNullOrWhiteSpace(allowance.Row) ? text["Gateway.Allowance.ItsRows"] : text["Gateway.Allowance.TheRows", allowance.Row!];
⋮----
public static string LicenceOwner(IStringLocalizer<ConsoleResource> text) => text["Gateway.Allowance.TheLicences"];
⋮----
public static string? Requests(GatewayAllowance allowance, IStringLocalizer<ConsoleResource> text) => allowance.Requests is { } requests
⋮----
public static string? Tokens(GatewayAllowance allowance, DateTimeOffset enrolledAt, IStringLocalizer<ConsoleResource> text)
⋮----
public static string LicencePeriod(string word, IStringLocalizer<ConsoleResource> text) => word switch
⋮----
public static string RowPeriod(DateTimeOffset resetAt, DateTimeOffset enrolledAt, IStringLocalizer<ConsoleResource> text)
⋮----
var reset = resetAt.ToUniversalTime();
⋮----
var sinceEnrolment = reset - enrolledAt.ToUniversalTime();
⋮----
public static bool HasUnreadableLimit(GatewayAllowance allowance) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/GatewayOperator.cs">
public static class GatewayOperator
⋮----
public static bool IsShared(ClaimsPrincipal user) =>
⋮----
public static bool IsNameable(string? typed) =>
!string.IsNullOrWhiteSpace(typed) && GatewayAdminClient.IsOperatorName(typed.Trim() + SharedSuffix);
⋮----
public static string For(ClaimsPrincipal user, string? typed) =>
IsShared(user) ? typed!.Trim() + SharedSuffix : user.Identity!.Name!;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/GatewayOverview.cs">
public string? Uptime(IStringLocalizer<ConsoleResource> text)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/InstallationChange.cs">
public sealed class InstallationChangeForm
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/InstallationDetails.cs">
public static int UsageDaysOf(int? asked) => asked is { } days && UsageRanges.Contains(days) ? days : DefaultUsageDays;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/InstallationFilter.cs">
("day", "Gateway.Seen.day", TimeSpan.FromDays(1)),
("week", "Gateway.Seen.week", TimeSpan.FromDays(7)),
("month", "Gateway.Seen.month", TimeSpan.FromDays(30)),
("longer", "Gateway.Seen.longer", TimeSpan.FromDays(30)),
⋮----
public Guid? SearchId => Guid.TryParse(Q?.Trim(), out var id) ? id : null;
⋮----
RowFilter is not null || StatusFilter is not null || SeenWindows.Any(window => window.Value == Seen)
|| !string.IsNullOrWhiteSpace(Below) || !string.IsNullOrWhiteSpace(Q);
⋮----
: Sorts.FirstOrDefault(sort => sort.Value == Sort).Sort;
⋮----
private InstallationRow? RowFilter => Rows.Any(row => row.Value == Row) ? Enum.Parse<InstallationRow>(Row!, ignoreCase: true) : null;
⋮----
public (InstallationQuery? Query, string? Problem) ToQuery(DateTimeOffset now, IStringLocalizer<ConsoleResource> text)
⋮----
if (!string.IsNullOrWhiteSpace(Below) && !InstallationQuery.IsVersion(Below))
⋮----
return (null, text["Gateway.Installations.Problem.Version", Below.Trim()]);
⋮----
if (!string.IsNullOrWhiteSpace(Q) && SearchId is null)
⋮----
var window = SeenWindows.FirstOrDefault(seen => seen.Value == Seen);
⋮----
return (new InstallationQuery
⋮----
AppVersionBelow = string.IsNullOrWhiteSpace(Below) ? null : Below.Trim(),
⋮----
Offset = (Math.Max(1, Page) - 1) * PageSize,
⋮----
public IDictionary<string, string> RouteValues(int page)
⋮----
if (!string.IsNullOrWhiteSpace(value))
⋮----
values[name] = value.Trim();
⋮----
values["page"] = page.ToString(System.Globalization.CultureInfo.InvariantCulture);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/InstallationList.cs">
public int Page => Math.Max(1, Filter.Page);
⋮----
? Math.Max(1, (total + InstallationFilter.PageSize - 1) / InstallationFilter.PageSize)
⋮----
public InstallationLicence LicenceOf(GatewayInstallation installation)
⋮----
return installation.IsLicensed ? InstallationLicence.IdNotRecorded() : InstallationLicence.None();
⋮----
return InstallationLicence.RegisterUnread(licenceId);
⋮----
return Register.TryGetValue(licenceId, out var row)
? InstallationLicence.InRegister(licenceId, row)
: InstallationLicence.NotInRegister(licenceId);
⋮----
public static InstallationLicence InRegister(Guid licenceId, RegisterSummary row) => new(InstallationLicenceState.InRegister, licenceId, row);
⋮----
public static InstallationLicence NotInRegister(Guid licenceId) => new(InstallationLicenceState.NotInRegister, licenceId, null);
⋮----
public static InstallationLicence RegisterUnread(Guid licenceId) => new(InstallationLicenceState.RegisterUnread, licenceId, null);
⋮----
public static InstallationLicence IdNotRecorded() => new(InstallationLicenceState.IdNotRecorded, null, null);
⋮----
public static InstallationLicence None() => new(InstallationLicenceState.None, null, null);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/LocationWords.cs">
public static class LocationWords
⋮----
public static LocationState StateOf(GatewayLocation? location) => location switch
⋮----
public static string? Country(GatewayLocation location, IStringLocalizer<ConsoleResource> text) =>
string.IsNullOrWhiteSpace(location.Country) ? null : text.CountryName(location.Country);
⋮----
public static string? Network(GatewayNetwork? network)
⋮----
var name = string.IsNullOrWhiteSpace(network?.Name) ? null : network!.Name!.Trim();
⋮----
public static string Asn(long number) => "AS" + number.ToString(System.Globalization.CultureInfo.InvariantCulture);
⋮----
public static string? Provider(GatewayCloud? cloud, IStringLocalizer<ConsoleResource> text)
⋮----
if (string.IsNullOrWhiteSpace(cloud?.Provider))
⋮----
var code = cloud!.Provider!.Trim().ToLowerInvariant();
⋮----
return found.ResourceNotFound ? cloud.Provider.Trim() : found.Value;
⋮----
public static string? Cloud(GatewayCloud? cloud, IStringLocalizer<ConsoleResource> text)
⋮----
var region = string.IsNullOrWhiteSpace(cloud?.Region) ? null : cloud!.Region!.Trim();
⋮----
public static string? Hover(GatewayLocation location, IStringLocalizer<ConsoleResource> text)
⋮----
var parts = new[] { Network(location.Network), Cloud(location.Cloud, text) }.Where(part => part is not null).ToList();
return parts.Count == 0 ? null : string.Join(" · ", parts);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/PolicyChange.cs">
public abstract class PolicyChangeForm
⋮----
public void CheckConfirm(ModelStateDictionary errors, bool shared, IStringLocalizer<ConsoleResource> text)
⋮----
if (string.IsNullOrEmpty(reason))
⋮----
errors.AddModelError(nameof(Reason), text["Gateway.Reason.Required"]);
⋮----
errors.AddModelError(nameof(Reason), text["Gateway.Reason.Length"]);
⋮----
if (shared && !GatewayOperator.IsNameable(Name))
⋮----
errors.AddModelError(nameof(Name), text["Gateway.YourName.Required"]);
⋮----
else if (shared && Name!.Trim().Length > 100)
⋮----
errors.AddModelError(nameof(Name), text["Gateway.YourName.Length"]);
⋮----
public static bool TryWhole(string? typed, long minimum, long maximum, out long value)
⋮----
var digits = typed?.Replace("_", "").Replace(" ", "").Replace("\u00A0", "").Trim();
if (string.IsNullOrEmpty(digits))
⋮----
// Groups of three with one separator, or no groups at all: 1.5 is not a whole number, and
// 1,5 is not one either, whichever language wrote it.
if (Regex.IsMatch(digits, "^[0-9]{1,3}(?:([.,])[0-9]{3})+$"))
⋮----
digits = digits.Replace(",", "").Replace(".", "");
⋮----
return long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out value)
⋮----
/// <summary>"a whole number from 1 to 2,147,483,647", or "a whole number, 1 or more" when the column is a <c>bigint</c>, in the page's language and its digits.</summary>
public static string Range(long maximum, IStringLocalizer<ConsoleResource> text) =>
maximum == long.MaxValue ? text["Gateway.Range.Unbounded"] : text["Gateway.Range.UpTo", PolicyPage.N(maximum)];
⋮----
public static string Fingerprint<T>(T values) => JsonSerializer.Serialize(values, PolicyChange.Wire);
⋮----
public sealed class TierChangeForm : PolicyChangeForm
⋮----
public static TierChangeForm Of(GatewayTierLevers levers) => new()
⋮----
RequestsPerWindow = levers.RequestsPerWindow.ToString(CultureInfo.InvariantCulture),
RequestWindowSeconds = levers.RequestWindowSeconds.ToString(CultureInfo.InvariantCulture),
TokenBudget = levers.TokenBudget.ToString(CultureInfo.InvariantCulture),
⋮----
MaxPredictTokens = levers.MaxPredictTokens.ToString(CultureInfo.InvariantCulture),
⋮----
public GatewayTierLevers? Read(ModelStateDictionary errors, IStringLocalizer<ConsoleResource> text)
⋮----
if (period is null || !BudgetPeriods.All.Contains(period, StringComparer.Ordinal))
⋮----
errors.AddModelError(nameof(BudgetPeriod), text["Gateway.Tier.Problem.Period"]);
⋮----
: new GatewayTierLevers((int)requests, (int)window, budget.Value, period, (int)maxPredict);
⋮----
private static long? Whole(ModelStateDictionary errors, string field, string? typed, string labelKey, long maximum, IStringLocalizer<ConsoleResource> text)
⋮----
errors.AddModelError(field, text["Gateway.Tier.Problem.MustBe", text[labelKey].Value, Range(maximum, text)]);
⋮----
public sealed class MinimumVersionForm : PolicyChangeForm
⋮----
public string? Read(ModelStateDictionary errors, IStringLocalizer<ConsoleResource> text)
⋮----
if (string.IsNullOrEmpty(version))
⋮----
errors.AddModelError(nameof(MinimumAppVersion), text["Gateway.Minimum.Problem.Required"]);
⋮----
if (!InstallationQuery.IsVersion(version))
⋮----
errors.AddModelError(nameof(MinimumAppVersion), text["Gateway.Minimum.Problem.NotAVersion", version]);
⋮----
errors.AddModelError(nameof(MinimumAppVersion), text["Gateway.Minimum.Problem.TooLong", MaxLength]);
⋮----
public sealed class VelocityForm : PolicyChangeForm
⋮----
public bool TryRead(ModelStateDictionary errors, bool wasArmed, IStringLocalizer<ConsoleResource> text, out int? perHour, out int? perDay)
⋮----
if (!string.IsNullOrWhiteSpace(EnrolmentsPerHour))
⋮----
errors.AddModelError(nameof(EnrolmentsPerHour), text["Gateway.Velocity.Problem.Hourly", Range(int.MaxValue, text)]);
⋮----
if (!string.IsNullOrWhiteSpace(EnrolmentsPerDay))
⋮----
errors.AddModelError(nameof(EnrolmentsPerDay), text["Gateway.Velocity.Problem.Daily", Range(int.MaxValue, text)]);
⋮----
errors.AddModelError(nameof(EnrolmentsPerHour), text["Gateway.Velocity.Problem.None"]);
⋮----
errors.AddModelError(nameof(EnrolmentsPerHour), text["Gateway.Velocity.Problem.HourlyAboveDaily"]);
⋮----
errors.AddModelError(nameof(AddressChecked), text["Gateway.Velocity.Problem.Unchecked"]);
⋮----
public sealed class CeilingForm : PolicyChangeForm
⋮----
public bool TryRead(ModelStateDictionary errors, IStringLocalizer<ConsoleResource> text, out long? ceiling)
⋮----
errors.AddModelError(nameof(GlobalTokenCeiling), text["Gateway.Ceiling.Problem", Range(long.MaxValue, text)]);
⋮----
public static class AllowanceRule
⋮----
public static bool IsLicenceRow(InstallationRow row) => row is InstallationRow.Standard or InstallationRow.Enterprise;
... (48 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/PolicyPage.cs">
public static IReadOnlyDictionary<string, int> CountByAllowance(IEnumerable<RegisterSummary> register, DateTime nowUtc) =>
RegisterSummary.InForce(register, nowUtc)
.GroupBy(licence => LicenseContract.Tiers.ForAi(licence.Current.Tier))
.ToDictionary(allowance => allowance.Key, allowance => allowance.Count(), StringComparer.Ordinal);
⋮----
public static bool IsAbove(string release, string? minimum) =>
⋮----
public static string Requests(GatewayTier tier, IStringLocalizer<ConsoleResource> text) => Requests(tier.RequestsPerWindow, tier.RequestWindowSeconds, text);
⋮----
public static string Requests(int requests, int windowSeconds, IStringLocalizer<ConsoleResource> text) => windowSeconds == 60
⋮----
public static string Period(string? word, IStringLocalizer<ConsoleResource> text) => word switch
⋮----
public static string PeriodName(string? word, IStringLocalizer<ConsoleResource> text) => word switch
⋮----
public static string N(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
⋮----
private static Version? Numeric(string? value) =>
!string.IsNullOrWhiteSpace(value) && Version.TryParse(value.Trim().Split('-', '+')[0], out var version) ? version : null;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/UsageByLicence.cs">
public long? LastMonthTokens(Guid installationId) =>
LastMonth is { Outcome: GatewayOutcome.Answered } lastMonth && lastMonth.Tokens.TryGetValue(installationId, out var tokens) ? tokens : null;
⋮----
Licences.SelectMany(licence => licence.Installations).Select(usage => usage.Installation.InstallationId).Distinct().ToList();
⋮----
public int Enrolled => Licences.Count(licence => licence.IsEnrolled);
⋮----
public int NotEnrolled => Licences.Count(licence => !licence.IsEnrolled);
⋮----
public int NearLimit => Licences.Count(licence => licence.IsNearLimit);
⋮----
public int Shared => Licences.Count(licence => licence.IsShared);
⋮----
public int ServedOtherwise => Licences.Count(licence => licence.IsServedOtherwise);
⋮----
public static UsageByLicence Join(
⋮----
var inForce = RegisterSummary.InForce(register, nowUtc);
var ids = inForce.Select(licence => licence.LicenceId).ToHashSet();
⋮----
.Where(installation => installation.LicenceId is { } id && ids.Contains(id))
.ToLookup(installation => installation.LicenceId!.Value);
⋮----
var active = installations.Where(installation => !installation.IsRevoked).ToList();
⋮----
.Where(licence => filter.Allowance is not { } allowance || LicenseContract.Tiers.ForAi(licence.Current.Tier) == allowance)
.Select(licence => LicenceUsage.Of(licence, byLicence[licence.LicenceId], text))
.ToList();
⋮----
? all.Where(licence => licence.Current.Purpose == LicenseContract.Purposes.Customer).ToList()
⋮----
return new UsageByLicence(
⋮----
WithoutLicenceId: active.Count(installation => installation.LicenceId is null),
HoldingOtherIds: active.Count(installation => installation.LicenceId is { } id && !ids.Contains(id)),
⋮----
public IEnumerable<string> CsvLines()
⋮----
licence.LicenceId.ToString(),
⋮----
yield return RegisterRecord.CsvLine(register.Concat(Enumerable.Repeat(string.Empty, 9)));
⋮----
yield return RegisterRecord.CsvLine(register.Concat(
⋮----
installation.InstallationId.ToString(),
⋮----
private static IReadOnlyList<LicenceUsage> Order(IEnumerable<LicenceUsage> licences, UsageSort sort)
⋮----
UsageSort.LeastUsed => licences.OrderBy(licence => licence.Percent ?? -1),
UsageSort.Expiring => licences.OrderBy(licence => licence.CoveredUntilUtc),
UsageSort.Customer => licences.OrderBy(licence => licence.Current.CustomerName, byName),
_ => licences.OrderByDescending(licence => licence.Percent ?? -1),
⋮----
.ThenBy(licence => licence.Current.CustomerName, byName)
.ThenBy(licence => licence.LicenceId)
⋮----
private static string Iso(DateTime value) =>
value.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
⋮----
private static string Number(long? value) =>
⋮----
public static LicenceUsage Of(LicenceInForce licence, IEnumerable<GatewayInstallation> installations, IStringLocalizer<ConsoleResource> text) => new(
⋮----
.OrderBy(installation => installation.IsRevoked)
.ThenByDescending(installation => installation.LastSeenAt)
.Select(installation => InstallationUsage.Of(installation, licence, text))
.ToList());
⋮----
public IEnumerable<InstallationUsage> Holding => Installations.Where(usage => !usage.Installation.IsRevoked);
⋮----
public bool IsShared => Holding.Count() > 1;
⋮----
public int? Percent => Holding.Select(usage => usage.Percent).Max();
⋮----
public bool IsServedOtherwise => Holding.Any(usage => usage.Differences.Count > 0);
⋮----
public static InstallationUsage Of(GatewayInstallation installation, LicenceInForce licence, IStringLocalizer<ConsoleResource> text)
⋮----
return new InstallationUsage(installation, []);
⋮----
var tierRow = LicenseContract.Tiers.ForAi(current.Tier);
if (allowance.Row is { } row && !string.Equals(row, tierRow, StringComparison.OrdinalIgnoreCase))
⋮----
differences.Add(text["Gateway.Usage.Differs.Row", row, tierRow]);
⋮----
if (expiresAt is { } held && Math.Abs((held - current.ExpirationUtc).TotalSeconds) >= 1)
⋮----
differences.Add(text["Gateway.Usage.Differs.Expiry", Day(held), Day(current.ExpirationUtc)]);
⋮----
differences.Add(Differs(
served?.Tokens is { } tokens ? text["Gateway.Usage.Differs.Served.Tokens", AllowanceWords.N(tokens)] : text["Gateway.Usage.Differs.Served.RowBudget"],
carried.AiTokens is { } set ? text["Gateway.Usage.Differs.Sets", AllowanceWords.N(set)] : text["Gateway.Usage.Differs.LeavesBudget"]));
⋮----
if (!string.Equals(carried.AiPeriod, served?.Period, StringComparison.Ordinal))
⋮----
served?.Rpm is { } rpm ? text["Gateway.Usage.Differs.Served.Rpm", AllowanceWords.N(rpm)] : text["Gateway.Usage.Differs.Served.RowRpm"],
carried.AiRequestsPerMinute is { } set ? text["Gateway.Usage.Differs.Sets", AllowanceWords.N(set)] : text["Gateway.Usage.Differs.LeavesRpm"]));
⋮----
return new InstallationUsage(installation, differences);
⋮----
... (12 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/UsageChart.cs">
public static UsageChart TokensByRow(IReadOnlyList<GatewayUsageDay> days, IStringLocalizer<ConsoleResource> text) => Of(
⋮----
Rows.Select(row => new UsageSeries(text[$"Gateway.Row.{row.Row}"], row.Colour, days.Select(day => day.Row(row.Row).Tokens).ToList())));
⋮----
public static UsageChart Refusals(IReadOnlyList<GatewayUsageDay> days, IStringLocalizer<ConsoleResource> text) => Of(
⋮----
new UsageSeries(text["Gateway.Usage.Series.RateLimited"], "warning", days.Select(day => day.RefusalsRateLimited).ToList()),
new UsageSeries(text["Gateway.Usage.Series.BudgetSpent"], "danger", days.Select(day => day.RefusalsBudgetExhausted).ToList()),
new UsageSeries(text["Gateway.Usage.Series.Upstream"], "info", days.Select(day => day.UpstreamErrors).ToList()),
⋮----
public static UsageChart Tokens(IReadOnlyList<GatewayUsageDay> days, IStringLocalizer<ConsoleResource> text) => Of(
⋮----
[new UsageSeries(text["Gateway.History.Tokens"], "primary", days.Select(day => day.Tokens).ToList())]);
⋮----
public static UsageChart Requests(IReadOnlyList<GatewayUsageDay> days, IStringLocalizer<ConsoleResource> text) => Of(
⋮----
new UsageSeries(text["Gateway.Usage.Series.Answered"], "primary", days.Select(day => day.Counts.Served).ToList()),
⋮----
public static string Title(string row) => row.Length == 0 ? row : char.ToUpperInvariant(row[0]) + row[1..];
⋮----
private static UsageChart Of(IReadOnlyList<GatewayUsageDay> days, string unit, IEnumerable<UsageSeries> series) => new(
⋮----
days.Select(day => day.Day.ToString("ddd d MMMM yyyy", CultureInfo.CurrentCulture)).ToList(),
days.Select(day => day.Day.ToString("d MMM", CultureInfo.CurrentCulture)).ToList(),
series.ToList(),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Models/UsageHistory.cs">
public static UsageHistoryRequest Read(string? from, string? to, int? top, DateOnly today, IStringLocalizer<ConsoleResource> text)
⋮----
var listed = top is { } asked && TopChoices.Contains(asked) ? asked : DefaultTop;
⋮----
if (string.IsNullOrWhiteSpace(from) && string.IsNullOrWhiteSpace(to))
⋮----
return new UsageHistoryRequest(null, null, listed, UsageRange.Last(DefaultDays, today), null);
⋮----
var first = string.IsNullOrWhiteSpace(from) ? to : from;
var last = string.IsNullOrWhiteSpace(to) ? from : to;
⋮----
if (!UsageRange.TryParse(first, out var start))
⋮----
return new UsageHistoryRequest(from, to, listed, null, text["Gateway.History.Problem.NotADate", first ?? "", "2026-09-01"]);
⋮----
if (!UsageRange.TryParse(last, out var end))
⋮----
return new UsageHistoryRequest(from, to, listed, null, text["Gateway.History.Problem.NotADate", last ?? "", "2026-09-30"]);
⋮----
var range = new UsageRange(start, end);
⋮----
return new UsageHistoryRequest(from, to, listed, null, text["Gateway.History.Problem.Backwards"]);
⋮----
? new UsageHistoryRequest(from, to, listed, range, null)
: new UsageHistoryRequest(from, to, listed, null,
⋮----
public static IReadOnlyList<(string Label, UsageRange Range)> Presets(DateOnly today)
⋮----
var month = new DateOnly(today.Year, today.Month, 1);
⋮----
("Gateway.History.Preset.Last7", UsageRange.Last(7, today)),
("Gateway.History.Preset.Last30", UsageRange.Last(30, today)),
("Gateway.History.Preset.ThisMonth", new UsageRange(month, today)),
("Gateway.History.Preset.LastMonth", UsageRange.PreviousMonth(today)),
("Gateway.History.Preset.Last90", UsageRange.Last(90, today)),
("Gateway.History.Preset.Last365", UsageRange.Last(365, today)),
⋮----
public Dictionary<string, string> RouteValues(UsageRange range)
⋮----
["from"] = UsageRange.Format(range.From),
["to"] = UsageRange.Format(range.To),
⋮----
values["top"] = Top.ToString(CultureInfo.InvariantCulture);
⋮----
.. Rows.SelectMany(row => new[]
⋮----
public GatewayUsageTotals Row(string row) =>
Answered?.ByRow?.GetValueOrDefault(row) ?? new GatewayUsageTotals(0, 0, 0, 0, 0, 0);
⋮----
var rows = Rows.Select(Row).ToList();
var rest = new GatewayUsageTotals(
summary.Totals.Tokens - rows.Sum(row => row.Tokens),
summary.Totals.Requests - rows.Sum(row => row.Requests),
summary.Totals.RefusalsRateLimited - rows.Sum(row => row.RefusalsRateLimited),
summary.Totals.RefusalsBudgetExhausted - rows.Sum(row => row.RefusalsBudgetExhausted),
summary.Totals.UpstreamErrors - rows.Sum(row => row.UpstreamErrors),
summary.Totals.Installations - rows.Sum(row => row.Installations));
⋮----
public int? Share(long tokens) =>
Answered is { Totals.Tokens: > 0 } summary ? (int)Math.Round(100.0 * tokens / summary.Totals.Tokens) : null;
⋮----
public IEnumerable<string> DaysCsvLines() => (Daily?.Days ?? []).Select(day => RegisterRecord.CsvLine(
⋮----
UsageRange.Format(day.Day),
⋮----
.. Rows.SelectMany(row => Counts(day.Row(row))),
⋮----
public IEnumerable<string> TopCsvLines() => Top.Select(top => RegisterRecord.CsvLine(
⋮----
top.Rank.ToString(CultureInfo.InvariantCulture),
top.Usage.InstallationId.ToString(),
⋮----
private static IEnumerable<string> Counts(GatewayUsageCounts counts) =>
⋮----
.Select(count => count.ToString(CultureInfo.InvariantCulture));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/ViewComponents/GatewayOverviewViewComponent.cs">
public sealed class GatewayOverviewViewComponent(
⋮----
TimeProvider clock) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync()
⋮----
if (!(await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.GatewayView)).Succeeded)
⋮----
var cached = await cache.GetAsync(gateway.StatusAsync, HttpContext.RequestAborted);
return View(ViewPath, new GatewayOverview(cached, options.Value.BaseAddress?.Host, clock.GetUtcNow()));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Home/Index.cshtml">
@using System.Globalization
@model GatewayOverview
@{
    static string N(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
    static string Instant(DateTimeOffset? value) => value is null ? "-" : value.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
    static string Day(DateTimeOffset? value) => value is null ? "-" : value.Value.UtcDateTime.ToString("yyyy-MM-dd");

    var status = Model.Status;
    var brake = Model.Brake;
    var fleet = Model.Fleet;
    var host = Model.Host;
    var at = host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(host)}</code>");
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Gateway"]</h5>
                <p class="text-body mb-0">@T["Gateway.Overview.Lead", at]</p>
            </div>
        </div>
    </div>
</div>

@if (!Model.Answered || status is null)
{
    <div class="row g-4">
        <div class="col-12">
            <partial name="_GatewayStatusUnavailable" model="Model.Answer" />
        </div>
    </div>
    return;
}

<div class="row g-4 mb-4">
    <div class="col-xl-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Overview.Status"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Overview.Status.AsOf", Model.AskedAt.UtcDateTime.ToString("HH:mm:ss"), GatewayStatusCache.Lifetime.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)]</p>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-sm-4">@T["Gateway.Overview.Version"]</dt>
                    <dd class="col-sm-8"><code>@(status.Version ?? T["Gateway.NotReported.Lower"].Value)</code></dd>
                    <dt class="col-sm-4">@T["Gateway.Overview.Started"]</dt>
                    <dd class="col-sm-8">
                        @Instant(status.StartedAt)
                        @if (Model.Uptime(S) is { } up)
                        {
                            <div class="small text-body">@T["Gateway.Overview.Up", up]</div>
                        }
                    </dd>
                    <dt class="col-sm-4">@T["Gateway.Overview.Telemetry"]</dt>
                    <dd class="col-sm-8 mb-0">
                        @if (status.Telemetry is null)
                        {
                            <span>@T["Gateway.NotReported"]</span>
                        }
                        else if (status.Telemetry.Configured)
                        {
                            <span class="badge bg-label-success">@T["Gateway.Overview.Telemetry.Connected"]</span>
                        }
                        else
                        {
                            <span class="badge bg-label-warning">@T["Gateway.Overview.Telemetry.None"]</span>
                            <div class="small text-body">@T["Gateway.Overview.Telemetry.None.Detail"]</div>
                        }
                    </dd>
                </dl>
            </div>
        </div>
    </div>

    @* The global brake: kf-app#817's cap inside the gateway, released only by raising the ceiling. *@
    <div class="col-xl-8">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Brake.Title"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Brake.Lead"]</p>
            </div>
            <div class="card-body">
                @if (brake is null)
                {
                    <p class="text-body mb-0">@T["Gateway.Brake.NotReported"]</p>
                }
                else if (brake.IsOff)
                {
                    <div class="alert alert-secondary" role="status">
                        <h6 class="alert-heading mb-1">@T["Gateway.Brake.Off.Title"]</h6>
                        <p class="mb-0">@T["Gateway.Brake.Off.Detail"]</p>
                    </div>
                    <p class="text-body mb-0">@T["Gateway.Brake.SpentSince", Day(brake.PeriodStart), Html.Raw($"<strong>{N(brake.Used)}</strong>")]</p>
                }
                else
                {
                    var percent = brake.Percent ?? 0;
                    var bar = brake.Tripped ? "bg-danger" : percent >= 80 ? "bg-warning" : "bg-primary";

... (293 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Installations/Change.cshtml">
@model InstallationChange
@{
    static string Instant(DateTimeOffset? value) => value is null ? "-" : value.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";

    var installation = Model.Installation;
    var verb = Model.IsRevoke ? S["Gateway.Revoke"].Value : S["Gateway.Restore"].Value;
    var action = Model.IsRevoke ? "Revoke" : "Restore";
    var host = Model.Host;
    var at = host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(host)}</code>");
}

<div class="mb-4">
    <a asp-action="Details" asp-route-id="@Model.InstallationId" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Gateway.Installation.Title"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@T[Model.IsRevoke ? "Gateway.Change.Revoke.Title" : "Gateway.Change.Restore.Title", Html.Raw($"<code>{Model.InstallationId}</code>")]</h5>
        <p class="mb-0">@T["Gateway.Change.Lead", at]</p>
    </div>
</div>

@if (installation is null)
{
    <partial name="_InstallationsUnavailable" model="(Model.Current.Outcome, Model.Current.Detail)" />
    return;
}

@if (Model.Failure is { } failure)
{
    <div class="alert alert-danger" role="alert">
        @switch (failure.Outcome)
        {
            case GatewayOutcome.WriteRefused:
                <h6 class="alert-heading mb-1">@T["Gateway.Write.WriteRefused.Title"]</h6>
                <p class="mb-0">@T["Gateway.Write.WriteRefused.Detail"]</p>
                break;
            case GatewayOutcome.TokenRefused:
                <h6 class="alert-heading mb-1">@T["Gateway.Write.TokenRefused.Title"]</h6>
                <p class="mb-0">@T["Gateway.Write.TokenRefused.Detail"]</p>
                break;
            case GatewayOutcome.WritesNotConfigured:
                <h6 class="alert-heading mb-1">@T["Gateway.NoWriteToken.Title"]</h6>
                <p class="mb-0">@T["Gateway.Write.NotConfigured.Detail"]</p>
                break;
            case GatewayOutcome.UnknownInstallation:
                <h6 class="alert-heading mb-1">@T["Gateway.Change.Unknown.Title"]</h6>
                <p class="mb-0">@T["Gateway.Change.Unknown.Detail"]</p>
                break;
            case GatewayOutcome.RequestRefused:
                <h6 class="alert-heading mb-1">@T["Gateway.Write.RequestRefused.Title"]</h6>
                <p class="mb-0">@failure.Detail @T["Gateway.Write.RequestRefused.Detail"]</p>
                break;
            default:
                <h6 class="alert-heading mb-1">@T["Gateway.Change.Unsure.Title"]</h6>
                <p class="mb-0">@failure.Detail @T["Gateway.Change.Unsure.Detail"]</p>
                break;
        }
    </div>
}

<div class="row g-4">
    <div class="col-12 col-lg-5">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Gateway.Change.TheInstallation"]</h6>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-5">@T["Licensing.Installations.Column.Status"]</dt>
                    <dd class="col-7">
                        <span class="badge @(installation.IsRevoked ? "bg-label-secondary" : "bg-label-success")">@(installation.Status ?? (installation.IsRevoked ? "revoked" : "active"))</span>
                        @if (installation.IsRevoked)
                        {
                            <div class="small">@T["Gateway.Since", Instant(installation.RevokedAt)]</div>
                        }
                    </dd>
                    <dt class="col-5">@T["Gateway.Installation.AppVersion"]</dt>
                    <dd class="col-7">@(installation.AppVersion ?? "-")</dd>
                    <dt class="col-5">@T["Licensing.Installations.Column.LastSeen"]</dt>
                    <dd class="col-7">@Instant(installation.LastSeenAt)</dd>
                    <dt class="col-5">@T["Gateway.Installations.Column.Licence"]</dt>
                    <dd class="col-7 mb-0">
                        @if (Model.LicenceRow is { } row)
                        {
                            <a asp-area="Licensing" asp-controller="Register" asp-action="Details" asp-route-id="@row.RecordId">@row.CustomerName</a>
                            @if (installation.LicenceHolders is > 1)
                            {
                                <div class="small text-warning">@T["Gateway.Change.HeldBy", installation.LicenceHolders]</div>
                            }
                        }
                        else if (installation.LicenceId is { } licenceId)
                        {
                            <code title="@licenceId">@licenceId.ToString()[..8]</code>
                            <div class="small text-body-secondary">@T["Licensing.Overview.Shared.NotInRegister"]</div>
                        }
                        else
                        {
                            <span class="text-body-secondary">@T["Gateway.Licence.None"]</span>
                        }
... (93 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Installations/Details.cshtml">
@model InstallationDetails
@{
    static string Instant(DateTimeOffset? value) => value is null ? "-" : value.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
    static string Seconds(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss") + " UTC";
    static string Day(DateTime value) => value.ToString("yyyy-MM-dd");

    var installation = Model.Installation;
    var allowance = Model.Allowance;
    var licenceRow = Model.LicenceRow;
    var at = Model.Host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(Model.Host)}</code>");
}

@section PageScripts {
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Gateway.Installations"]</a>
</div>

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body d-flex flex-wrap justify-content-between align-items-start gap-3">
                <div>
                    <h5 class="card-title mb-1">@T["Gateway.Installation.Title"]</h5>
                    <p class="mb-0">
                        <code>@Model.InstallationId</code>
                        <button type="button" class="btn btn-sm btn-icon btn-text-secondary" data-copy="@Model.InstallationId"
                                title="@T["Gateway.CopyId"].Value" aria-label="@S["Gateway.CopyId.Aria", Model.InstallationId].Value">
                            <i class="ti ti-copy"></i>
                        </button>
                    </p>
                </div>
                @if (installation is not null)
                {
                    <span class="badge fs-6 @(installation.IsRevoked ? "bg-label-secondary" : "bg-label-success")">@(installation.Status ?? (installation.IsRevoked ? "revoked" : "active"))</span>
                }
            </div>
        </div>
    </div>
</div>

@if (ViewData["changed"] is string changed && installation is not null)
{
    <div class="alert alert-success" role="status">
        @if (changed == "revoked")
        {
            <span>@T["Gateway.Installation.Changed.Revoked"]</span>
        }
        else
        {
            <span>@T["Gateway.Installation.Changed.Restored"]</span>
        }
        <a asp-area="" asp-controller="Audit" asp-action="Index" asp-route-target="@Model.InstallationId">@T["Gateway.Installation.Changed.SeeIt"]</a>
    </div>
}

@if (installation is null)
{
    <div class="row g-4">
        <div class="col-12">
            @if (Model.Answer.Outcome == GatewayOutcome.NotReported)
            {
                <div class="alert alert-secondary mb-0" role="status">
                    <h6 class="alert-heading mb-1">@T["Gateway.Installation.NoLookup.Title"]</h6>
                    <p class="mb-0">@T["Gateway.Installation.NoLookup.Detail"]</p>
                </div>
            }
            else
            {
                <partial name="_InstallationsUnavailable" model="(Model.Answer.Outcome, Model.Answer.Detail)" />
            }
        </div>
    </div>
    return;
}

<div class="row g-4 mb-4">
    @* Everything the gateway holds of it, but the credential: the gateway does not return it, and nothing here asks. *@
    <div class="col-xl-5">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Installation.OnGateway"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Installation.OnGateway.Lead", at]</p>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-sm-5">@T["Gateway.Installation.AppVersion"]</dt>
                    <dd class="col-sm-7">@(installation.AppVersion ?? "-")</dd>

                    <dt class="col-sm-5">@T["Licensing.Tier"]</dt>
                    <dd class="col-sm-7">
                        <code>@(installation.Tier ?? "-")</code>
                        @if (allowance?.Row is { } served)
                        {
                            <div class="small text-body">@T["Gateway.Installation.ServedRow", served]</div>
                        }
                    </dd>

... (403 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Installations/Index.cshtml">
@model InstallationList
@{
    static string Instant(DateTimeOffset? value) => value is null ? "-" : value.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
    static string Minute(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm");
    static string Day(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd");
    static string Short(Guid id) => id.ToString()[..8];

    var filter = Model.Filter;
    var answer = Model.Answer;
    var host = Model.Host;
    var at = host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(host)}</code>");
}

@section PageScripts {
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Gateway.Installations"]</h5>
                <p class="text-body mb-0">@T["Gateway.Installations.Lead", at]</p>
            </div>
        </div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-body">
        <form method="get" asp-action="Index" class="row g-3 align-items-end" role="search">
            <div class="col-12 col-lg-6">
                <label for="q" class="form-label">@T["Gateway.Installations.Search"]</label>
                <input type="search" id="q" name="q" value="@filter.Q" class="form-control" placeholder="@T["Gateway.Installations.Search.Placeholder"].Value" />
            </div>
            <div class="col-6 col-lg-3">
                <label for="sort" class="form-label">@T["Gateway.Installations.Order"]</label>
                <select id="sort" name="sort" class="form-select">
                    @foreach (var (value, label, sortOrder) in InstallationFilter.Sorts)
                    {
                        <option value="@value" selected="@(filter.SortOrder == sortOrder)">@T[label]</option>
                    }
                </select>
            </div>
            <div class="col-6 col-lg-3 d-flex gap-2">
                <button type="submit" class="btn btn-primary flex-fill">@T["Generic.Apply"]</button>
                <a asp-action="Index" class="btn btn-label-secondary flex-fill">@T["Generic.Clear"]</a>
            </div>
            <div class="col-6 col-lg-3">
                <label for="row" class="form-label">@T["Gateway.Installations.Row"]</label>
                <select id="row" name="row" class="form-select">
                    <option value="">@T["Generic.Any"]</option>
                    @foreach (var (value, label) in InstallationFilter.Rows)
                    {
                        <option value="@value" selected="@(filter.Row == value)">@T[label]</option>
                    }
                </select>
            </div>
            <div class="col-6 col-lg-3">
                <label for="status" class="form-label">@T["Gateway.Installations.Status"]</label>
                <select id="status" name="status" class="form-select">
                    <option value="">@T["Generic.Any"]</option>
                    @foreach (var (value, label) in InstallationFilter.Statuses)
                    {
                        <option value="@value" selected="@(filter.Status == value)">@T[label]</option>
                    }
                </select>
            </div>
            <div class="col-6 col-lg-3">
                <label for="seen" class="form-label">@T["Gateway.Installations.LastSeen"]</label>
                <select id="seen" name="seen" class="form-select">
                    <option value="">@T["Generic.AnyTime"]</option>
                    @foreach (var (value, label, _) in InstallationFilter.SeenWindows)
                    {
                        <option value="@value" selected="@(filter.Seen == value)">@T[label]</option>
                    }
                </select>
            </div>
            <div class="col-6 col-lg-3">
                <label for="below" class="form-label">@T["Gateway.Installations.Below"]</label>
                <input type="text" id="below" name="below" value="@filter.Below" class="form-control" placeholder="1.7.0" />
            </div>
        </form>
        @if (filter.IsLongGone)
        {
            <p class="small text-body-secondary mt-3 mb-0">@T["Gateway.Installations.LongGone"]</p>
        }
    </div>
</div>

@if (Model.Problem is { } problem)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Gateway.Installations.NotAsked"]</h6>
        <p class="mb-0">@problem</p>
    </div>
    return;
}

@if (answer.Outcome != GatewayOutcome.Answered)
... (163 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Policy/Index.cshtml">
@using KnowledgeFabric.AdminConsole.Licensing.Validation
@model PolicyPage
@{
    static string N(long value) => PolicyPage.N(value);
    static string Minute(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm");

    var host = Model.Host;
    var levers = Model.Levers;
    var status = Model.GatewayStatus;
    var licenceRows = new[] { "standard", "enterprise" };
    var at = host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(host)}</code>");

    var mayChange = Model.CanWrite && Model.MayWrite;
    var cannotChange = !Model.CanWrite
        ? S["Gateway.Policy.NoWriteToken"].Value
        : S["Gateway.Policy.ViewOnly", T.Role(ConsoleRoles.GatewayWrite)].Value;

    // What stands in for a count the gateway would not give.
    string Unanswered(VersionCount count) => count.Outcome == GatewayOutcome.NotReported
        ? S["Gateway.Policy.Count.NotReported"].Value
        : S["Gateway.Policy.Count.NoAnswer"].Value;

    string Installations(int count) => count == 1 ? S["Gateway.Policy.ActiveInstallations.One"].Value : S["Gateway.Policy.ActiveInstallations.Many", N(count)].Value;
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Gateway.Policy"]</h5>
                <p class="text-body mb-2">@T["Gateway.Policy.Lead", at, Minute(Model.AsOf)]</p>
                <p class="text-body mb-0">
                    @T["Gateway.Policy.Lead.Change", Html.ActionLink(S["Gateway.Policy.TheAuditLog"].Value, "Index", "Audit", new { area = "" })]
                    @if (!mayChange)
                    {
                        <span class="text-body-secondary">@cannotChange</span>
                    }
                </p>
            </div>
        </div>
    </div>
</div>

@if (Model.Changed is { } changed)
{
    var isTier = changed is "evaluation" or "standard" or "enterprise";
    var what = changed switch
    {
        "minimum" => S["Gateway.Policy.Changed.Minimum"].Value,
        "velocity" => S["Gateway.Policy.Changed.Velocity"].Value,
        "ceiling" => S["Gateway.Policy.Changed.Ceiling"].Value,
        _ => S["Gateway.Policy.Changed.Tier", changed].Value,
    };
    <div class="alert alert-success" role="status">
        @T["Gateway.Policy.Changed", what]
        <a asp-area="" asp-controller="Audit" asp-action="Index" asp-route-kind="@(isTier ? "gateway:tier" : "gateway:policy")" asp-route-target="@(isTier ? changed : "gateway")">@T["Gateway.Policy.Changed.AuditLink"]</a>
        @T["Gateway.Policy.Changed.HasEntry"]
    </div>
}

@if (!Model.Answered)
{
    @if (Model.Answer.Outcome == GatewayOutcome.NotReported)
    {
        <div class="alert alert-secondary" role="status">
            <h6 class="alert-heading mb-1">@T["Gateway.Policy.NotReported.Title"]</h6>
            <p class="mb-0">@T["Gateway.Policy.NotReported.Detail"]</p>
        </div>
    }
    else
    {
        <partial name="_InstallationsUnavailable" model="(Model.Answer.Outcome, Model.Answer.Detail)" />
    }
    return;
}

<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-1">@T["Gateway.Policy.Tiers"]</h5>
        <p class="card-subtitle mb-0">@T["Gateway.Policy.Tiers.Lead"]</p>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>@T["Licensing.Installations.Column.Row"]</th>
                    <th class="text-nowrap">@T["Gateway.Installation.Requests"]</th>
                    <th class="text-nowrap">@T["Gateway.Policy.TokenBudget"]</th>
                    <th class="text-nowrap">@T["Gateway.Installation.LongestReply"]</th>
                    <th class="text-nowrap">@T["Gateway.Policy.InstallationsServed"]</th>
                    <th class="text-nowrap">@T["Gateway.Policy.LicencesInForce"]</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var tier in Model.Answer.Tiers)
                {
                    var isLicenceRow = licenceRows.Contains(tier.Tier);
                    <tr>
                        <td class="fw-medium">@tier.Tier</td>
... (210 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/_PolicyChangeHeader.cshtml">
@model (string Title, string Request, string? Host)

@* The top of every policy form (#71): the way back, what is changed, and how. The title is a key
   whose one argument is the tier, or none. *@
@{
    var at = Model.Host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(Model.Host)}</code>");
}

<div class="mb-4">
    <a asp-controller="Policy" asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Menu.Gateway.Policy"]</a>
</div>

<div class="card mb-4">
    <div class="card-body">
        <h5 class="card-title mb-2">@Html.Raw(Model.Title)</h5>
        <p class="mb-0">@T["Gateway.Change.Policy.Lead", at, Html.Raw($"<code>{Html.Encode(Model.Request)}</code>")]</p>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/_PolicyChangeProblems.cshtml">
@model PolicyChange

@* What stopped a change (#71): a lever changed on the gateway since the review, a write the gateway
   did not make, the form's own objections, or a row carrying values the gateway will not take back. *@

@if (Model.Stale)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Gateway.Change.Stale.Title"]</h6>
        <p class="mb-0">@T["Gateway.Change.Stale.Detail"]</p>
    </div>
}

@if (Model.FailedWith is { } outcome)
{
    <div class="alert alert-danger" role="alert">
        @switch (outcome)
        {
            case GatewayOutcome.WriteRefused:
                <h6 class="alert-heading mb-1">@T["Gateway.Write.WriteRefused.Title"]</h6>
                <p class="mb-0">@T["Gateway.Write.WriteRefused.Detail"]</p>
                break;
            case GatewayOutcome.TokenRefused:
                <h6 class="alert-heading mb-1">@T["Gateway.Write.TokenRefused.Title"]</h6>
                <p class="mb-0">@T["Gateway.Write.TokenRefused.Detail"]</p>
                break;
            case GatewayOutcome.WritesNotConfigured:
                <h6 class="alert-heading mb-1">@T["Gateway.NoWriteToken.Title"]</h6>
                <p class="mb-0">@T["Gateway.Write.NotConfigured.Detail"]</p>
                break;
            case GatewayOutcome.NotReported:
                <h6 class="alert-heading mb-1">@T["Gateway.Change.NoPolicyWrites.Title"]</h6>
                <p class="mb-0">@T["Gateway.Change.NoPolicyWrites.Detail"]</p>
                break;
            case GatewayOutcome.RequestRefused:
                <h6 class="alert-heading mb-1">@T["Gateway.Write.RequestRefused.Title"]</h6>
                <p class="mb-0">@Model.FailureDetail @T["Gateway.Change.Policy.RequestRefused.Detail"]</p>
                break;
            default:
                <h6 class="alert-heading mb-1">@T["Gateway.Change.Unsure.Title"]</h6>
                <p class="mb-0">@Model.FailureDetail @T["Gateway.Change.Policy.Unsure.Detail", Html.ActionLink(S["Gateway.Change.ThePolicyPage"].Value, "Index", "Policy")]</p>
                break;
        }
    </div>
}

@if (ViewData.ModelState[""]?.Errors is { Count: > 0 } formErrors)
{
    <div class="alert alert-warning" role="alert">
        @foreach (var error in formErrors)
        {
            <p class="mb-0">@error.ErrorMessage</p>
        }
    </div>
}

@if (Model.RowProblems.Count > 0)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Gateway.Change.RowProblems.Title"]</h6>
        <p class="mb-2">@T["Gateway.Change.RowProblems.Detail", string.Join(S["Gateway.Change.RowProblems.And"].Value, Model.RowProblems)]</p>
        <p class="mb-0">
            <a asp-action="MinimumVersion">@T["Gateway.Change.RowProblems.Minimum"]</a> · <a asp-action="Velocity">@T["Gateway.Change.RowProblems.Velocity"]</a> ·
            <a asp-action="Ceiling">@T["Gateway.Change.RowProblems.Ceiling"]</a>
        </p>
    </div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/_PolicyConfirm.cshtml">
@model (PolicyChange Change, PolicyChangeForm Form, string Verb, bool Danger)

@* The confirm step's fields and buttons (#71), inside the form that carries the change: why, who
   under the shared password, and the two ways on. The same fields revoking an installation asks (#69). *@

@{
    var writer = Model.Change.Writer;
    string? Error(string key) => ViewData.ModelState[key]?.Errors.FirstOrDefault()?.ErrorMessage;
}

<input type="hidden" name="Seen" value="@Model.Form.Seen" />

@if (!writer.CanSubmit)
{
    <partial name="_PolicyWriteBlocked" model="writer" />
    <div class="d-flex gap-2 mt-3">
        <button type="submit" name="Step" value="@PolicyChangeForm.EditStep" class="btn btn-label-secondary">@T["Generic.Edit"]</button>
        <a asp-controller="Policy" asp-action="Index" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
    </div>
}
else
{
    <div class="mb-3">
        <label for="Reason" class="form-label">@T["Gateway.Reason"]</label>
        <textarea id="Reason" name="Reason" class="form-control" rows="2" maxlength="500"
                  placeholder="@T["Gateway.Change.Reason.Placeholder"].Value">@Model.Form.Reason</textarea>
        @if (Error(nameof(PolicyChangeForm.Reason)) is { } reasonError)
        {
            <div class="text-danger small mt-1">@reasonError</div>
        }
    </div>
    @if (writer.NeedsName)
    {
        <div class="mb-3">
            <label for="Name" class="form-label">@T["Gateway.YourName"]</label>
            <input type="text" id="Name" name="Name" value="@Model.Form.Name" class="form-control" maxlength="100" autocomplete="name" />
            @if (Error(nameof(PolicyChangeForm.Name)) is { } nameError)
            {
                <div class="text-danger small mt-1">@nameError</div>
            }
            <div class="form-text">@T["Gateway.SharedPassword.NameHelp"]</div>
        </div>
    }
    else
    {
        <p class="small text-body mb-3">@T["Gateway.RecordedAs", Html.Raw($"<strong>{Html.Encode(writer.SignedInAs)}</strong>")]</p>
    }
    <div class="d-flex flex-wrap gap-2">
        <button type="submit" name="Step" value="@PolicyChangeForm.ConfirmStep" class="btn @(Model.Danger ? "btn-danger" : "btn-primary")">@Model.Verb</button>
        <button type="submit" name="Step" value="@PolicyChangeForm.EditStep" class="btn btn-label-secondary">@T["Generic.Edit"]</button>
        <a asp-controller="Policy" asp-action="Index" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
    </div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/_PolicyUnavailable.cshtml">
@model GatewayPolicyAnswer

@* Why a policy form has nothing to change (#71): the gateway did not give its rows. The words are
   the policy page's, where the cause is the same. *@

@if (Model.Outcome == GatewayOutcome.NotReported)
{
    <div class="alert alert-secondary mb-0" role="status">
        <h6 class="alert-heading mb-1">@T["Gateway.Policy.NotReported.Title"]</h6>
        <p class="mb-0">@T["Gateway.Policy.NotReported.Detail"]</p>
    </div>
}
else
{
    <partial name="_InstallationsUnavailable" model="(Model.Outcome, Model.Detail)" />
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/_PolicyWriteBlocked.cshtml">
@model PolicyWriter

@* Why this session cannot change the gateway (#71): no write token, or no Gateway: Write (#88). Nothing when it can. *@

@if (!Model.CanWrite)
{
    <div class="alert alert-secondary mb-0" role="status">
        <h6 class="alert-heading mb-1">@T["Gateway.NoWriteToken.Title"]</h6>
        <p class="mb-0">@T["Gateway.NoWriteToken.Detail"]</p>
    </div>
}
else if (!Model.MayWrite)
{
    <div class="alert alert-secondary mb-0" role="status">
        <h6 class="alert-heading mb-1">@T["Gateway.ViewNotDo.Title"]</h6>
        <p class="mb-0"><span>@T["Gateway.ViewNotDo.Detail", Html.Raw($"<strong>{Html.Encode(Model.SignedInAs)}</strong>"), Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.GatewayWrite))}</strong>")]</span></p>
    </div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/Ceiling.cshtml">
@model CeilingChange
@{
    ViewData["title"] = S["Gateway.Ceiling.Title"].Value;

    static string N(long value) => PolicyPage.N(value);
    static string Minute(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm");
    string Ceiling(long? ceiling) => ceiling is { } tokens ? S["Gateway.Ceiling.TokensAMonth", N(tokens)] : S["Gateway.Policy.NoBrake"];
    string? Error(string key) => ViewData.ModelState[key]?.Errors.FirstOrDefault()?.ErrorMessage;

    var form = Model.Form;
    var levers = Model.Levers;
    var brake = Model.Brake;
    var review = Model.Step == PolicyChangeStep.Review && Model.Read;
    var header = (Html.Encode(S["Gateway.Ceiling.Title"].Value), "PUT /admin/policy", Model.Writer.Host);
}

<partial name="_PolicyChangeHeader" model="header" />

@if (!Model.Answered)
{
    <partial name="_PolicyUnavailable" model="Model.Current" />
    return;
}

<partial name="_PolicyChangeProblems" model="Model" />

<div class="row g-4">
    <div class="col-12 col-lg-7">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@(review ? T["Gateway.Change.TheChange"] : T["Gateway.Ceiling.TheCeiling"])</h6>
            </div>
            <div class="card-body">
                @if (review)
                {
                    var proposed = Model.Proposed;
                    <dl class="row mb-3">
                        <dt class="col-4">@T["Gateway.Change.Now"]</dt>
                        <dd class="col-8">@Ceiling(levers!.GlobalTokenCeiling)</dd>
                        <dt class="col-4">@T["Gateway.Change.After"]</dt>
                        <dd class="col-8 fw-medium">@Ceiling(proposed)</dd>
                    </dl>

                    @switch (Model.Effect)
                    {
                        case CeilingEffect.Releases:
                            <div class="alert alert-success mb-3" role="status">@T["Gateway.Ceiling.Releases", N(brake!.Used), proposed is null ? S["Gateway.Ceiling.Releases.NoCeiling"].Value : S["Gateway.Ceiling.Releases.Below"].Value]</div>
                            break;
                        case CeilingEffect.StaysOn:
                            <div class="alert alert-warning mb-3" role="alert">@T["Gateway.Ceiling.StaysOn", N(brake!.Used)]</div>
                            break;
                        case CeilingEffect.Trips:
                            <div class="alert alert-danger mb-3" role="alert">@T["Gateway.Ceiling.Trips", N(brake!.Used)]</div>
                            break;
                        case CeilingEffect.Headroom:
                            <p class="mb-3">@T["Gateway.Ceiling.Headroom", N(brake!.Used), N(proposed!.Value - brake.Used)]@(brake.PeriodEnd is { } end ? S["Gateway.Ceiling.Headroom.Until", Minute(end)].Value : "").</p>
                            break;
                        case CeilingEffect.Off:
                            <p class="mb-3">@T["Gateway.Ceiling.Off"]</p>
                            break;
                        default:
                            <p class="text-body-secondary mb-3">@T["Gateway.Policy.BrakeUnknown"]</p>
                            break;
                    }

                    <form method="post" asp-action="Ceiling">
                        <input type="hidden" name="BrakeOn" value="@(form.BrakeOn ? "true" : "false")" />
                        <input type="hidden" name="GlobalTokenCeiling" value="@form.GlobalTokenCeiling" />
                        @{
                            var verb = proposed is null ? S["Gateway.Ceiling.TurnOff"].Value : S["Gateway.Ceiling.ChangeCeiling"].Value;
                            var confirm = ((PolicyChange)Model, (PolicyChangeForm)form, verb, Model.Effect is CeilingEffect.Trips or CeilingEffect.Off);
                        }
                        <partial name="_PolicyConfirm" model="confirm" />
                    </form>
                }
                else
                {
                    <form method="post" asp-action="Ceiling">
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="radio" name="BrakeOn" id="BrakeOn" value="true" checked="@form.BrakeOn" />
                            <label class="form-check-label" for="BrakeOn">@T["Gateway.Ceiling.Option.Ceiling"]</label>
                        </div>
                        <div class="ps-4 mb-3">
                            <input type="text" inputmode="numeric" id="GlobalTokenCeiling" name="GlobalTokenCeiling" value="@form.GlobalTokenCeiling"
                                   class="form-control" aria-label="@T["Gateway.Ceiling.Aria"].Value" />
                            <div class="form-text">@T["Gateway.Change.NowValue", Ceiling(levers!.GlobalTokenCeiling)].</div>
                            @if (Error(nameof(CeilingForm.GlobalTokenCeiling)) is { } ceilingError)
                            {
                                <div class="text-danger small mt-1">@ceilingError</div>
                            }
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="radio" name="BrakeOn" id="BrakeOff" value="false" checked="@(!form.BrakeOn)" />
                            <label class="form-check-label" for="BrakeOff">@T["Gateway.Ceiling.Option.NoBrake"]</label>
                        </div>
                        @if (!Model.Writer.CanSubmit)
                        {
                            <div class="mb-3"><partial name="_PolicyWriteBlocked" model="Model.Writer" /></div>
                        }
                        <div class="d-flex gap-2">
... (40 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/MinimumVersion.cshtml">
@model MinimumVersionChange
@{
    ViewData["title"] = S["Gateway.Minimum.Title"].Value;

    static string N(long value) => PolicyPage.N(value);
    string? Error(string key) => ViewData.ModelState[key]?.Errors.FirstOrDefault()?.ErrorMessage;

    var form = Model.Form;
    var now = Model.Levers?.MinimumAppVersion;
    var proposed = Model.Proposed;
    var review = Model.Step == PolicyChangeStep.Review && proposed is not null;
    var header = (Html.Encode(S["Gateway.Minimum.Title"].Value), "PUT /admin/policy", Model.Writer.Host);
    var confirm = ((PolicyChange)Model, (PolicyChangeForm)form, S["Gateway.Minimum.ChangeMinimum"].Value, true);
}

<partial name="_PolicyChangeHeader" model="header" />

@if (!Model.Answered)
{
    <partial name="_PolicyUnavailable" model="Model.Current" />
    return;
}

<partial name="_PolicyChangeProblems" model="Model" />

<div class="row g-4">
    <div class="col-12 col-lg-7">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@(review ? T["Gateway.Change.TheChange"] : T["Gateway.Minimum.TheMinimum"])</h6>
            </div>
            <div class="card-body">
                @if (review)
                {
                    <dl class="row mb-3">
                        <dt class="col-4">@T["Gateway.Change.Now"]</dt>
                        <dd class="col-8"><code>@(now ?? "-")</code></dd>
                        <dt class="col-4">@T["Gateway.Change.After"]</dt>
                        <dd class="col-8"><code class="fw-medium">@proposed</code></dd>
                    </dl>

                    @if (Model.Refused is { } refused && !Model.FleetInView)
                    {
                        <div class="alert alert-warning" role="alert">
                            <h6 class="alert-heading mb-1">@T["Gateway.Minimum.NotAnswered.Title"]</h6>
                            <p class="mb-0">@(refused.Detail ?? S["Gateway.Minimum.NotAnswered.Default"].Value) @T["Gateway.Minimum.NotAnswered.Detail"]</p>
                        </div>
                    }
                    else
                    {
                        var count = Model.Refused!.Installations.Count;
                        <p class="mb-2">
                            @T[count == 1 ? "Gateway.Minimum.Refuses.One" : "Gateway.Minimum.Refuses.Many", Html.Raw($"<code>{Html.Encode(proposed)}</code>"), Html.ActionLink(count == 1 ? S["Gateway.Policy.ActiveInstallations.One"].Value : S["Gateway.Policy.ActiveInstallations.Many", N(count)].Value, "Index", "Installations", new { below = proposed, status = "active" })]
                        </p>
                        @if (Model.ByVersion.Count > 0)
                        {
                            <div class="table-responsive mb-3">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>@T["Gateway.Minimum.VersionReported"]</th>
                                            <th class="text-end">@T["Licensing.Installations"]</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (var tally in Model.ByVersion)
                                        {
                                            <tr>
                                                <td>@if (tally.Version.Length > 0) { <code>@tally.Version</code> } else { <span class="text-body-secondary">@T["Gateway.Minimum.NoneReported"]</span> }</td>
                                                <td class="text-end">@N(tally.Installations)</td>
                                            </tr>
                                        }
                                    </tbody>
                                </table>
                            </div>
                        }
                        @if (PolicyPage.IsAbove(now ?? "", proposed) && InstallationQuery.IsVersion(now))
                        {
                            <p class="small mb-3">@T["Gateway.Minimum.BelowNow"]</p>
                        }
                    }

                    <form method="post" asp-action="MinimumVersion">
                        <input type="hidden" name="MinimumAppVersion" value="@form.MinimumAppVersion" />
                        @if (Model.FleetInView)
                        {
                            <partial name="_PolicyConfirm" model="confirm" />
                        }
                        else
                        {
                            <input type="hidden" name="Seen" value="@form.Seen" />
                            <div class="d-flex gap-2">
                                <button type="submit" name="Step" value="@PolicyChangeForm.ReviewStep" class="btn btn-primary">@T["Gateway.Minimum.AskAgain"]</button>
                                <button type="submit" name="Step" value="@PolicyChangeForm.EditStep" class="btn btn-label-secondary">@T["Generic.Edit"]</button>
                            </div>
                        }
                    </form>
                }
                else
                {
... (39 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/Tier.cshtml">
@model TierChange
@{
    ViewData["title"] = S["Gateway.Tier.Title", Model.Tier].Value;

    static string N(long value) => PolicyPage.N(value);
    string? Error(string key) => ViewData.ModelState[key]?.Errors.FirstOrDefault()?.ErrorMessage;

    var tier = Model.Tier;
    var current = Model.CurrentRow;
    var form = Model.Form;
    var proposed = Model.Proposed;
    var review = Model.Step == PolicyChangeStep.Review && proposed is not null;
    var licences = Model.LicencesInForce ?? 0;
    var licencesText = licences == 1 ? S["Gateway.Tier.InForce.One"].Value : S["Gateway.Tier.InForce.Many", N(licences)].Value;
    var header = (S["Gateway.Tier.Title.Html", $"<code>{Html.Encode(tier)}</code>"].Value, $"PUT /admin/tiers/{tier}", Model.Writer.Host);
    var confirm = ((PolicyChange)Model, (PolicyChangeForm)form, S["Gateway.Tier.Title", tier].Value, false);
}

<partial name="_PolicyChangeHeader" model="header" />

@if (!Model.Answered)
{
    <partial name="_PolicyUnavailable" model="Model.Current" />
    return;
}

@if (current is null)
{
    <div class="alert alert-secondary" role="status">@T["Gateway.Tier.NoRow", Html.Raw($"<code>{Html.Encode(tier)}</code>")]</div>
    return;
}

<partial name="_PolicyChangeProblems" model="Model" />

@if (Model.Lowerings.Count > 0)
{
    <div class="alert alert-danger" role="alert">
        <h6 class="alert-heading mb-1">@T["Gateway.Tier.OnlyUp.Title", Html.Raw($"<code>{Html.Encode(tier)}</code>")]</h6>
        <p class="mb-2">
            @if (Model.RegisterRead)
            {
                <span>@T["Gateway.Tier.OnlyUp.Holds", Html.ActionLink(licencesText, "Index", "Usage", new { tier })]</span>
            }
            else
            {
                <span>@T["Gateway.Tier.OnlyUp.Unread"]</span>
            }
        </p>
        <ul class="mb-2">
            @foreach (var lowering in Model.Lowerings)
            {
                <li>@lowering.</li>
            }
        </ul>
        <p class="mb-0">@T["Gateway.Tier.OnlyUp.Why"]</p>
    </div>
}

<div class="row g-4">
    <div class="col-12 col-lg-7">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@(review ? T["Gateway.Change.TheChange"] : T["Gateway.Tier.TheRow"])</h6>
            </div>

            @if (review)
            {
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th></th>
                                <th>@T["Gateway.Change.Now"]</th>
                                <th>@T["Gateway.Change.After"]</th>
                            </tr>
                        </thead>
                        <tbody>
                            @{
                                var was = current.Levers;
                                var rows = new (string Label, string Now, string After)[]
                                {
                                    (S["Gateway.Installation.Requests"], PolicyPage.Requests(was.RequestsPerWindow, was.RequestWindowSeconds, S), PolicyPage.Requests(proposed!.RequestsPerWindow, proposed.RequestWindowSeconds, S)),
                                    (S["Gateway.Policy.TokenBudget"], $"{N(was.TokenBudget)} {PolicyPage.Period(was.BudgetPeriod, S)}", $"{N(proposed.TokenBudget)} {PolicyPage.Period(proposed.BudgetPeriod, S)}"),
                                    (S["Gateway.Installation.LongestReply"], S["Gateway.Tokens", N(was.MaxPredictTokens)], S["Gateway.Tokens", N(proposed.MaxPredictTokens)]),
                                };
                            }
                            @foreach (var (label, now, after) in rows)
                            {
                                <tr>
                                    <td class="fw-medium">@label</td>
                                    <td>@now</td>
                                    <td class="@(now == after ? "text-body-secondary" : "fw-medium")">@(now == after ? T["Gateway.Change.Unchanged"].Value : after)</td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
                <div class="card-body">
                    <form method="post" asp-action="Tier" asp-route-tier="@tier">
                        <input type="hidden" name="RequestsPerWindow" value="@form.RequestsPerWindow" />
... (122 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/PolicyChange/Velocity.cshtml">
@model VelocityChange
@{
    ViewData["title"] = S["Gateway.Velocity.Title"].Value;

    static string N(long value) => PolicyPage.N(value);
    string Limits(int? perHour, int? perDay) => perHour is null && perDay is null
        ? S["Gateway.Policy.Off"]
        : S["Gateway.Policy.Velocity.Limits.Short", perHour is { } hourly ? S["Gateway.Policy.Velocity.AnHour", N(hourly)].Value : S["Gateway.Policy.Velocity.NoHourly"].Value, perDay is { } daily ? S["Gateway.Policy.Velocity.ADay", N(daily)].Value : S["Gateway.Policy.Velocity.NoDaily"].Value];
    string? Error(string key) => ViewData.ModelState[key]?.Errors.FirstOrDefault()?.ErrorMessage;

    var form = Model.Form;
    var levers = Model.Levers;
    var review = Model.Step == PolicyChangeStep.Review && Model.Proposed is not null;
    var address = Model.CallerAddress;
    var header = (Html.Encode(S["Gateway.Velocity.Title"].Value), "PUT /admin/policy", Model.Writer.Host);
}

<partial name="_PolicyChangeHeader" model="header" />

@if (!Model.Answered)
{
    <partial name="_PolicyUnavailable" model="Model.Current" />
    return;
}

<partial name="_PolicyChangeProblems" model="Model" />

<div class="row g-4">
    <div class="col-12 col-lg-7">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@(review ? T["Gateway.Change.TheChange"] : T["Gateway.Velocity.TheLimit"])</h6>
            </div>
            <div class="card-body">
                @if (review)
                {
                    var (perHour, perDay) = Model.Proposed!.Value;
                    var arming = (perHour is not null || perDay is not null) && !Model.WasArmed;
                    <dl class="row mb-3">
                        <dt class="col-4">@T["Gateway.Change.Now"]</dt>
                        <dd class="col-8">@Limits(levers!.EnrolmentsPerHour, levers.EnrolmentsPerDay)</dd>
                        <dt class="col-4">@T["Gateway.Change.After"]</dt>
                        <dd class="col-8 fw-medium">@Limits(perHour, perDay)</dd>
                    </dl>
                    @if (perHour is null && perDay is null)
                    {
                        <p class="mb-3">@T["Gateway.Velocity.Review.Off"]</p>
                    }
                    else
                    {
                        <p class="mb-3">
                            @T["Gateway.Velocity.Review.PastIt"]
                            @(arming ? T["Gateway.Velocity.Review.StartsEmpty"] : null)
                        </p>
                    }
                    @if (arming)
                    {
                        <div class="alert alert-warning small mb-3" role="alert">@T["Gateway.Velocity.Review.Ticked", address ?? S["Gateway.Velocity.NotAvailableHere"].Value]</div>
                    }

                    <form method="post" asp-action="Velocity">
                        <input type="hidden" name="Armed" value="@(form.Armed ? "true" : "false")" />
                        <input type="hidden" name="EnrolmentsPerHour" value="@form.EnrolmentsPerHour" />
                        <input type="hidden" name="EnrolmentsPerDay" value="@form.EnrolmentsPerDay" />
                        <input type="hidden" name="AddressChecked" value="@(form.AddressChecked ? "true" : "false")" />
                        @{
                            var verb = arming ? S["Gateway.Velocity.Arm"].Value : perHour is null && perDay is null ? S["Gateway.Velocity.TurnOff"].Value : S["Gateway.Velocity.ChangeLimit"].Value;
                            var confirm = ((PolicyChange)Model, (PolicyChangeForm)form, verb, arming);
                        }
                        <partial name="_PolicyConfirm" model="confirm" />
                    </form>
                }
                else
                {
                    <form method="post" asp-action="Velocity">
                        <div class="mb-3">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="Armed" id="ArmedOff" value="false" checked="@(!form.Armed)" />
                                <label class="form-check-label" for="ArmedOff">@T["Gateway.Velocity.OffOption"]</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="Armed" id="ArmedOn" value="true" checked="@form.Armed" />
                                <label class="form-check-label" for="ArmedOn">@T["Gateway.Velocity.ArmedOption"]</label>
                            </div>
                        </div>
                        <div class="row g-3 mb-3 ps-4">
                            <div class="col-sm-6">
                                <label for="EnrolmentsPerHour" class="form-label">@T["Gateway.Velocity.PerHour"]</label>
                                <input type="text" inputmode="numeric" id="EnrolmentsPerHour" name="EnrolmentsPerHour" value="@form.EnrolmentsPerHour" class="form-control" placeholder="5" />
                                <div class="form-text">@T["Gateway.Velocity.PerHour.Now", levers!.EnrolmentsPerHour is { } hourly ? N(hourly) : S["Gateway.Velocity.None"].Value]</div>
                                @if (Error(nameof(VelocityForm.EnrolmentsPerHour)) is { } hourError)
                                {
                                    <div class="text-danger small mt-1">@hourError</div>
                                }
                            </div>
                            <div class="col-sm-6">
                                <label for="EnrolmentsPerDay" class="form-label">@T["Gateway.Velocity.PerDay"]</label>
                                <input type="text" inputmode="numeric" id="EnrolmentsPerDay" name="EnrolmentsPerDay" value="@form.EnrolmentsPerDay" class="form-control" placeholder="20" />
                                <div class="form-text">@T["Gateway.Velocity.PerDay.Now", levers.EnrolmentsPerDay is { } daily ? N(daily) : S["Gateway.Velocity.None"].Value]</div>
                                @if (Error(nameof(VelocityForm.EnrolmentsPerDay)) is { } dayError)
... (59 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/Components/GatewayOverview/Default.cshtml">
@using System.Globalization
@model GatewayOverview
@{
    static string N(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
    var status = Model.Status;
    var brake = Model.Brake;
    var fleet = Model.Fleet;
}

@* The gateway area's card on the console's overview (#64): the brake and the fleet in one line each. *@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-start gap-3">
                <div>
                    <h5 class="card-title mb-1">@T["Menu.Gateway"]</h5>
                    <p class="card-subtitle mb-0">
                        @if (Model.Host is { } host)
                        {
                            <span>@T["Gateway.Card.Lead", Html.Raw($"<code>{Html.Encode(host)}</code>"), Model.AskedAt.UtcDateTime.ToString("HH:mm:ss")]</span>
                        }
                        else
                        {
                            <span>@T["Gateway.Card.Lead.NoHost"]</span>
                        }
                    </p>
                </div>
                <a asp-area="Gateway" asp-controller="Home" asp-action="Index" class="btn btn-sm btn-label-secondary">@T["Menu.Gateway"]</a>
            </div>
            <div class="card-body">
                @if (!Model.Answered || status is null)
                {
                    <partial name="~/Areas/Gateway/Views/Shared/_GatewayStatusUnavailable.cshtml" model="Model.Answer" />
                }
                else
                {
                    <div class="row g-4">
                        <div class="col-sm-4">
                            <span class="text-heading">@T["Gateway.Card.Gateway"]</span>
                            <h5 class="mb-1 mt-1"><span class="badge bg-label-success">@T["Gateway.Card.Answering"]</span></h5>
                            <small class="text-body">@T["Gateway.Card.Version", Html.Raw($"<code>{Html.Encode(status.Version ?? T["Gateway.NotReported.Lower"].Value)}</code>")]</small>
                        </div>
                        <div class="col-sm-4">
                            <span class="text-heading">@T["Gateway.Card.Brake"]</span>
                            @if (brake is null)
                            {
                                <h5 class="mb-1 mt-1">-</h5>
                                <small class="text-body">@T["Gateway.NotReported"]</small>
                            }
                            else if (brake.IsOff)
                            {
                                <h5 class="mb-1 mt-1"><span class="badge bg-label-secondary">@T["Gateway.Card.Brake.Off"]</span></h5>
                                <small class="text-body">@T["Gateway.Card.Brake.Off.Detail", N(brake.Used)]</small>
                            }
                            else if (brake.Tripped)
                            {
                                <h5 class="mb-1 mt-1"><span class="badge bg-danger">@T["Gateway.Card.Brake.Tripped"]</span></h5>
                                <small class="text-body">@T["Gateway.Card.Brake.Tripped.Detail"]</small>
                            }
                            else
                            {
                                <h5 class="mb-1 mt-1">@(brake.Percent ?? 0)%</h5>
                                <small class="text-body">@T["Gateway.Card.Brake.Used", N(brake.Used), N(brake.Ceiling!.Value)]</small>
                            }
                        </div>
                        <div class="col-sm-4">
                            <span class="text-heading">@T["Menu.Gateway.Installations"]</span>
                            @if (fleet is null)
                            {
                                <h5 class="mb-1 mt-1">-</h5>
                                <small class="text-body">@T["Gateway.NotReported"]</small>
                            }
                            else
                            {
                                <h5 class="mb-1 mt-1">@T["Gateway.Card.Active", fleet.Active]</h5>
                                <small class="text-body">@T["Gateway.Card.Seen", fleet.SeenLast24h, fleet.Revoked]</small>
                            }
                        </div>
                    </div>
                }
            </div>
        </div>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_GatewayStatusUnavailable.cshtml">
@model GatewayStatusAnswer

@* Why there is no status to show (#64). Every outcome but Answered lands here, so the pages that read
   the gateway always render, and say which of these it is. The register's pages have their own copy
   of this for the installations they ask about; the words match where the cause is the same. *@

@switch (Model.Outcome)
{
    case GatewayOutcome.NotConfigured:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Gateway.Unavailable.NotConfigured.Title"]</h6>
            <p class="mb-0">@T["Gateway.Unavailable.NotConfigured.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NotReported:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Gateway.Unavailable.NoStatus.Title"]</h6>
            <p class="mb-0">@T["Gateway.Unavailable.NoStatus.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.RequestRefused:
        <div class="alert alert-danger mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.RequestRefused.Title"]</h6>
            <p class="mb-0">@Model.Detail @T["Licensing.Gateway.RequestRefused.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.TokenRefused:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.TokenRefused.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.TokenRefused.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NoAdminSurface:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.NoAdminSurface.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.NoAdminSurface.Detail"]</p>
        </div>
        break;

    default:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.Unreachable.Title"]</h6>
            <p class="mb-0">@Model.Detail @T["Licensing.Gateway.Unreachable.Detail"]</p>
        </div>
        break;
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_InstallationCountry.cshtml">
@model GatewayLocation?
@* An installation's country as a cell (#217): its name in the page's language, the network and cloud
   region on hover; "Not located" when the gateway has not located it; and nothing at all from a
   gateway before kf-ai-gateway#55, which does not report locations. *@
@switch (LocationWords.StateOf(Model))
{
    case LocationState.Located:
        var country = LocationWords.Country(Model!, S);
        <span class="text-nowrap @(country is null ? "small text-body-secondary" : "")" title="@LocationWords.Hover(Model!, S)">@(country ?? S["Gateway.Location.Country.Unknown.Short"].Value)</span>
        break;

    case LocationState.NotLocated:
        <span class="small text-body-secondary text-nowrap" title="@T["Gateway.Location.NotLocated.Title"].Value">@T["Gateway.Location.NotLocated.Short"]</span>
        break;
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_InstallationLicence.cshtml">
@model InstallationLicence

@* One installation's licence as the register knows it (#65): its customer, or why there is none to name. *@

@switch (Model.State)
{
    case InstallationLicenceState.InRegister:
        var row = Model.Row!;
        <a asp-area="Licensing" asp-controller="Register" asp-action="Details" asp-route-id="@row.RecordId" class="fw-medium">@row.CustomerName</a>
        <div class="small text-body">@row.Company</div>
        break;

    case InstallationLicenceState.NotInRegister:
        <span class="badge bg-label-warning" title="@T["Gateway.Licence.NotInRegister.Title"].Value">@T["Licensing.Overview.Shared.NotInRegister"]</span>
        <div class="small"><code title="@Model.LicenceId">@(Model.LicenceId!.Value.ToString()[..8])</code></div>
        break;

    case InstallationLicenceState.RegisterUnread:
        <span class="text-body-secondary" title="@T["Gateway.Licence.RegisterUnread.Title"].Value">@T["Gateway.Licence.RegisterUnread"]</span>
        <div class="small"><code title="@Model.LicenceId">@(Model.LicenceId!.Value.ToString()[..8])</code></div>
        break;

    case InstallationLicenceState.IdNotRecorded:
        <span class="text-body" title="@T["Gateway.Licence.IdNotRecorded.Title"].Value">@T["Gateway.Licence.IdNotRecorded"]</span>
        break;

    default:
        <span class="text-body-secondary">@T["Gateway.Licence.None"]</span>
        break;
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_InstallationsUnavailable.cshtml">
@model (GatewayOutcome Outcome, string? Detail)

@* Why the gateway's installations are missing (#65). Every outcome but Answered lands here, so the
   installations pages always render, and say which of these it is. The words match the other pages'
   where the cause is the same. *@

@switch (Model.Outcome)
{
    case GatewayOutcome.NotConfigured:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Gateway.Unavailable.NotConfigured.Title"]</h6>
            <p class="mb-0">@T["Gateway.Unavailable.NotConfigured.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NotReported:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Gateway.Unavailable.NoFilters.Title"]</h6>
            <p class="mb-0">@T["Gateway.Unavailable.NoFilters.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NoLicenceIds:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.NoLicenceIds.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.NoLicenceIds.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.UnknownInstallation:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Gateway.Unavailable.Unknown.Title"]</h6>
            <p class="mb-0">@T["Gateway.Unavailable.Unknown.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.RequestRefused:
        <div class="alert alert-danger mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.RequestRefused.Title"]</h6>
            <p class="mb-0">@Model.Detail @T["Licensing.Gateway.RequestRefused.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.TokenRefused:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.TokenRefused.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.TokenRefused.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NoAdminSurface:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.NoAdminSurface.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.NoAdminSurface.Detail"]</p>
        </div>
        break;

    default:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.Unreachable.Title"]</h6>
            <p class="mb-0">@Model.Detail @T["Licensing.Gateway.Unreachable.Detail"]</p>
        </div>
        break;
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_LocationAttribution.cshtml">
@* The data source's attribution (#217), which its licence requires on every page that shows its
   results: DB-IP's IP to Country Lite and IP to ASN Lite, CC BY 4.0, the source kf-ai-gateway#55
   suggests. The link text is DB-IP's own wording, so it is not translated. If the gateway ships another
   source, IPinfo Lite (CC BY-SA 4.0) say, this is the one place that changes. *@
<span>@T["Gateway.Location.Attribution",
    Html.Raw("<a href=\"https://db-ip.com\" target=\"_blank\" rel=\"noopener noreferrer\">IP Geolocation by DB-IP</a>"),
    Html.Raw("<a href=\"https://creativecommons.org/licenses/by/4.0/\" target=\"_blank\" rel=\"noopener noreferrer\">CC BY 4.0</a>")]</span>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_UsageChart.cshtml">
@model (UsageChart Chart, string Id, int Height)

@* One chart of the daily usage ledger (#70): where it goes, and its numbers beside it as JSON.
   wwwroot/js/gateway-usage.js draws it; the page includes _UsageChartScripts once. *@

<div data-usage-chart="@Model.Id" data-height="@Model.Height" style="min-height: @(Model.Height)px"></div>
<script type="application/json" id="@Model.Id">@Json.Serialize(Model.Chart)</script>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_UsageChartScripts.cshtml">
@* The chart library and the script that draws every _UsageChart on the page (#70), once a page.
   Deferred scripts run in order once the page is parsed. *@
<link rel="stylesheet" href="~/vendor/libs/apex-charts/apex-charts.css" asp-append-version="true" />
<script src="~/vendor/libs/apex-charts/apexcharts.js" asp-append-version="true" defer></script>
<script src="~/js/gateway-usage.js" asp-append-version="true" defer></script>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Shared/_UsageUnavailable.cshtml">
@model (GatewayOutcome Outcome, string? Detail)

@* Why a usage history section has nothing to draw (#70). A gateway from before kf-ai-gateway#41 has
   no ledger; everything else is said as the installations pages say it. *@

@if (Model.Outcome == GatewayOutcome.NotReported)
{
    <div class="alert alert-secondary mb-0" role="status">
        <h6 class="alert-heading mb-1">@T["Gateway.Usage.NoLedger.Title"]</h6>
        <p class="mb-0">@T["Gateway.Usage.NoLedger.Detail"]</p>
    </div>
}
else
{
    <partial name="_InstallationsUnavailable" model="Model" />
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Usage/_InstallationUsage.cshtml">
@model (InstallationUsage Usage, UsageByLicence Page)

@* One installation holding a licence (#66): the four gateway cells of the usage table, and of a
   licence's second and later installations' rows. Last month's tokens (#70) come from the page,
   which asked for every installation at once. *@

@{
    static string Minute(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm");
    static string Short(Guid id) => id.ToString()[..8];

    var usage = Model.Usage;
    var installation = usage.Installation;
    var allowance = usage.Allowance;
    var tokens = allowance?.Tokens;
    var lastMonth = Model.Page.LastMonthTokens(installation.InstallationId);
    var lastMonthWhy = Model.Page.LastMonth switch
    {
        null => S["Gateway.Usage.LastMonth.NotRead"].Value,
        { Outcome: GatewayOutcome.NotReported } => S["Gateway.Usage.NoLedger.Title"].Value,
        { Outcome: GatewayOutcome.Answered } => S["Gateway.Usage.LastMonth.TooMany"].Value,
        _ => S["Gateway.Usage.LastMonth.NoAnswer"].Value,
    };
}

<td>
    <div class="text-nowrap">
        <a asp-controller="Installations" asp-action="Details" asp-route-id="@installation.InstallationId" title="@installation.InstallationId"><code>@Short(installation.InstallationId)</code></a>
        <button type="button" class="btn btn-sm btn-icon btn-text-secondary" data-copy="@installation.InstallationId"
                title="@T["Gateway.CopyWholeId"].Value" aria-label="@S["Gateway.CopyId.Aria", installation.InstallationId].Value">
            <i class="ti ti-copy"></i>
        </button>
        @if (installation.IsRevoked)
        {
            <span class="badge bg-label-secondary">@T["Gateway.Status.revoked.Lower"]</span>
        }
    </div>
    <div class="small text-body text-nowrap" title="@T["Gateway.Usage.LastCall"].Value">@T["Gateway.Usage.Seen", Minute(installation.LastSeenAt)]</div>
    @if (usage.Differences.Count > 0)
    {
        <ul class="small text-danger ps-3 mb-0 mt-1" style="max-width: 22rem">
            @foreach (var difference in usage.Differences)
            {
                <li>@difference</li>
            }
        </ul>
    }
</td>

@if (installation.IsRevoked)
{
    <td class="small text-body-secondary">@T["Licensing.Installations.ServedNothing"]</td>
}
else if (allowance is null)
{
    <td class="small text-body-secondary">@T["Licensing.Installations.NotReported"]</td>
}
else
{
    <td style="min-width: 11rem">
        @if (tokens is not null)
        {
            var bar = tokens.Percent >= 100 ? "bg-danger" : tokens.Percent >= UsageByLicence.NearLimitPercent ? "bg-warning" : "bg-primary";
            <div class="small text-nowrap">
                @AllowanceWords.N(tokens.Used) <span class="text-body-secondary">@T["Licensing.Installations.OfLimit", AllowanceWords.N(tokens.Limit), tokens.Percent]</span>
            </div>
            <div class="progress" style="height: 6px" role="progressbar" aria-label="@T["Licensing.Installations.TokensAgainstLimit"].Value"
                 aria-valuenow="@tokens.Percent" aria-valuemin="0" aria-valuemax="100">
                <div class="progress-bar @bar" style="width: @tokens.Percent%"></div>
            </div>
            <div class="small text-body-secondary mt-1">@AllowanceWords.Tokens(allowance, installation.CreatedAt, S)</div>
            <div class="small text-body-secondary text-nowrap">@T["Licensing.Installations.Resets", Minute(tokens.ResetAt) + " UTC"]</div>
        }
        else
        {
            <span class="small text-body-secondary">@T["Licensing.Installations.NotReported"]</span>
        }
    </td>
}

<td class="small text-nowrap">
    @if (lastMonth is { } spent)
    {
        <span>@AllowanceWords.N(spent)</span>
    }
    else
    {
        <span class="text-body-secondary" title="@lastMonthWhy">-</span>
    }
</td>

<td class="small">@(installation.IsRevoked || allowance is null ? "-" : AllowanceWords.Requests(allowance, S) ?? "-")</td>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Usage/History.cshtml">
@using System.Globalization
@model UsageHistory
@{
    static string N(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
    static string Short(Guid id) => id.ToString()[..8];
    static string LongDay(DateOnly day) => day.ToString("d MMMM yyyy", CultureInfo.CurrentCulture);

    var request = Model.Request;
    var range = request.Range;
    var summary = Model.Answered;
    var host = Model.Host;
    var at = host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(host)}</code>");
    string Refusals(long rateLimited, long budget) => S["Gateway.History.RefusedDetail", N(rateLimited), N(budget)].Value;
}

@section PageScripts {
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Gateway.UsageHistory"]</h5>
                <p class="text-body mb-3">@T["Gateway.History.Lead", at]</p>

                <form method="get" asp-action="History" class="row g-3 align-items-end mb-3">
                    <div class="col-sm-6 col-lg-3">
                        <label for="from" class="form-label">@T["Gateway.History.From"]</label>
                        <input type="date" id="from" name="from" class="form-control" value="@(request.From ?? (range is null ? null : UsageRange.Format(range.From)))" />
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <label for="to" class="form-label">@T["Gateway.History.To"]</label>
                        <input type="date" id="to" name="to" class="form-control" value="@(request.To ?? (range is null ? null : UsageRange.Format(range.To)))" />
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <label for="top" class="form-label">@T["Gateway.History.TopInstallations"]</label>
                        <select id="top" name="top" class="form-select">
                            @foreach (var choice in UsageHistoryRequest.TopChoices)
                            {
                                <option value="@choice" selected="@(choice == request.Top)">@choice</option>
                            }
                        </select>
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <button type="submit" class="btn btn-primary w-100">@T["Gateway.History.Show"]</button>
                    </div>
                </form>

                <div class="d-flex flex-wrap gap-2">
                    @foreach (var (label, preset) in UsageHistoryRequest.Presets(Model.Today))
                    {
                        <a asp-action="History" asp-all-route-data="request.RouteValues(preset)"
                           class="btn btn-sm @(preset == range ? "btn-primary" : "btn-label-primary")">@T[label]</a>
                    }
                </div>
            </div>
        </div>
    </div>
</div>

@if (range is null)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Gateway.History.NotARange"]</h6>
        <p class="mb-0">@request.Problem</p>
    </div>
    return;
}

@if (summary is null)
{
    <partial name="_UsageUnavailable" model="(Model.Summary!.Outcome, Model.Summary.Detail)" />
    return;
}

@{
    var totals = summary.Totals;
    var unrowed = Model.Unrowed;
    var routeValues = request.RouteValues(range);
    var daysExport = new Dictionary<string, string>(routeValues) { ["what"] = "days" };
    var topExport = new Dictionary<string, string>(routeValues) { ["what"] = "top" };
}

<div class="row g-4 mb-4">
    @foreach (var (label, value, note) in new (string, long, string)[]
    {
        (S["Gateway.History.Tokens"], totals.Tokens, S["Gateway.History.Tokens.Note"]),
        (S["Gateway.History.Requests"], totals.Requests, S["Gateway.History.Requests.Note"]),
        (S["Gateway.History.Refused"], totals.RefusalsRateLimited + totals.RefusalsBudgetExhausted, Refusals(totals.RefusalsRateLimited, totals.RefusalsBudgetExhausted)),
        (S["Gateway.History.UpstreamErrors"], totals.UpstreamErrors, S["Gateway.History.UpstreamErrors.Note"]),
        (S["Licensing.Installations"], totals.Installations, S["Gateway.History.Installations.Note"]),
    })
    {
        <div class="col-sm-6 col-xl">
            <div class="card h-100">
                <div class="card-body">
                    <span class="text-heading">@label</span>
                    <h4 class="mb-1 mt-1">@N(value)</h4>
                    <small class="text-body">@note</small>
... (176 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/Usage/Index.cshtml">
@using KnowledgeFabric.AdminConsole.Licensing.Register
@using KnowledgeFabric.AdminConsole.Licensing.Validation
@model UsageByLicence
@{
    static string Day(DateTime value) => value.ToString("yyyy-MM-dd");

    var filter = Model.Filter;
    var host = Model.Host;
    var availability = ViewData["availability"] as RegisterAvailability? ?? RegisterAvailability.Durable;
    var at = host is null ? Html.Raw("") : Html.Raw($" {Html.Encode(S["Gateway.At"].Value)} <code>{Html.Encode(host)}</code>");

    // What a gateway column says in place of a number when the gateway gave none.
    var unanswered = Model.Gateway.Outcome switch
    {
        GatewayOutcome.NotConfigured => S["Gateway.Usage.Unanswered.NotConfigured"].Value,
        GatewayOutcome.NotReported => S["Gateway.Usage.Unanswered.NotReported"].Value,
        _ => S["Gateway.Usage.Unanswered.NoAnswer"].Value,
    };

    // Last month's column (#70): the month by name, in the page's language, once the ledger answered.
    var lastMonth = Model.LastMonth;
    var lastMonthHeading = lastMonth is { Outcome: GatewayOutcome.Answered }
        ? S["Gateway.Usage.TokensIn", lastMonth.Range.From.ToString("MMMM", System.Globalization.CultureInfo.CurrentCulture)].Value
        : S["Gateway.Usage.TokensLastMonth"].Value;
}

@section PageScripts {
    <script src="~/js/copy-id.js" asp-append-version="true"></script>
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Menu.Gateway.UsageByLicence"]</h5>
                <p class="text-body mb-0">@T["Gateway.Usage.Lead", at, Model.AsOfUtc.ToString("yyyy-MM-dd HH:mm")]</p>
            </div>
        </div>
    </div>
</div>

<partial name="~/Areas/Licensing/Views/Shared/_RegisterAvailability.cshtml" model="availability" />

@if (!Model.RegisterRead)
{
    @if (availability != RegisterAvailability.Unavailable)
    {
        <div class="alert alert-warning" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Overview.Unreadable.Title"]</h6>
            <p class="mb-0">@T["Gateway.Usage.RegisterUnread.Detail"]</p>
        </div>
    }
    return;
}

<div class="card mb-4">
    <div class="card-body">
        <form method="get" asp-action="Index" class="row g-3 align-items-end">
            <div class="col-12 col-md-6 col-xl-3">
                <label for="tier" class="form-label">@T["Gateway.Usage.Allowance"]</label>
                <select id="tier" name="tier" class="form-select">
                    <option value="">@T["Licensing.Register.EveryTier"]</option>
                    <option value="standard" selected="@(filter.Allowance == "standard")">@T["Gateway.Usage.Allowance.standard"]</option>
                    <option value="enterprise" selected="@(filter.Allowance == "enterprise")">@T["Gateway.Usage.Allowance.enterprise"]</option>
                </select>
            </div>
            <div class="col-12 col-md-6 col-xl-3">
                <label for="purpose" class="form-label">@T["Licensing.Purpose"]</label>
                <select id="purpose" name="purpose" class="form-select">
                    <option value="">@T["Gateway.Usage.EveryLicence"]</option>
                    <option value="@UsageFilter.CustomerPurpose" selected="@filter.CustomersOnly">@T["Gateway.Usage.CustomersOnly"]</option>
                </select>
            </div>
            <div class="col-12 col-md-6 col-xl-3">
                <label for="sort" class="form-label">@T["Gateway.Installations.Order"]</label>
                <select id="sort" name="sort" class="form-select">
                    @foreach (var (value, label, sortOrder) in UsageFilter.Sorts)
                    {
                        <option value="@value" selected="@(filter.SortOrder == sortOrder)">@T[label]</option>
                    }
                </select>
            </div>
            <div class="col-12 col-md-6 col-xl-3 d-flex gap-2">
                <button type="submit" class="btn btn-primary flex-fill">@T["Generic.Apply"]</button>
                @if (Model.GatewayAnswered)
                {
                    <a asp-action="Export" asp-all-route-data="@filter.RouteValues()" class="btn btn-label-secondary flex-fill">
                        <i class="ti ti-download me-1"></i>@T["Generic.ExportCsv"]
                    </a>
                }
            </div>
        </form>
    </div>
</div>

@if (!Model.GatewayAnswered)
{
    <div class="mb-4">
        @if (Model.Gateway.Outcome == GatewayOutcome.NotReported)
        {
... (176 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/_ViewImports.cshtml">
@using KnowledgeFabric.AdminConsole
@using KnowledgeFabric.AdminConsole.Models
@using KnowledgeFabric.AdminConsole.Security
@using KnowledgeFabric.AdminConsole.Gateway
@using KnowledgeFabric.AdminConsole.Areas.Gateway.Models
@using Microsoft.AspNetCore.Mvc.Localization
@using KnowledgeFabric.AdminConsole.Localisation
@using KnowledgeFabric.AdminConsole.Resources
@using Microsoft.Extensions.Localization
@inject IHtmlLocalizer<ConsoleResource> T
@inject IStringLocalizer<ConsoleResource> S
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Gateway/Views/_ViewStart.cshtml">
@{
    Layout = "_ContentNavbarLayout";
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Controllers/IssueController.cs">
public sealed class IssueController(
⋮----
ILogger<IssueController> logger) : Controller
⋮----
public async Task<IActionResult> Index(Guid? from, CancellationToken cancellationToken)
⋮----
var form = new IssueForm();
⋮----
var record = await register.FindAsync(from.Value, cancellationToken);
⋮----
form = FromRecord(record, clock.GetUtcNow().UtcDateTime, out var dropped);
⋮----
public async Task<IActionResult> Edit(IssueForm form)
⋮----
ModelState.Clear();
⋮----
public async Task<IActionResult> Preview(IssueForm form)
⋮----
var config = form.ToConfig(text, out var formProblems);
⋮----
var now = clock.GetUtcNow();
var issuedAt = now.AddTicks(-(now.Ticks % TimeSpan.TicksPerSecond));
⋮----
config.LicenseId ??= Guid.NewGuid().ToString();
⋮----
LicencePreview preview;
⋮----
preview = issuer.Preview(config, issuedAt);
⋮----
var ticket = new IssueTicket(Guid.NewGuid(), config, issuedAt, form.IssuedBy.Trim(), form.ReissueOf);
⋮----
return View(new IssuePreviewModel(form, preview, tickets.Protect(ticket), issuer.KeyState, register.Availability));
⋮----
public async Task<IActionResult> Sign(string? ticket, IssueForm form)
⋮----
var opened = tickets.Unprotect(ticket);
⋮----
if (!ledger.TryBegin(opened.TicketId, out var alreadyRecorded))
⋮----
RegisterRecord stored;
⋮----
var licenseXml = issuer.Sign(opened.Config, opened.IssuedAt);
⋮----
var record = RegisterRecord.FromLicense(
⋮----
recordedAtUtc: clock.GetUtcNow().UtcDateTime);
⋮----
stored = await register.RecordAsync(record, CancellationToken.None);
⋮----
ledger.Abandon(opened.TicketId);
⋮----
logger.LogError(ex, "Issuing licence {LicenseId} failed; nothing was handed over.", opened.Config.LicenseId);
⋮----
["error"] = ex.GetType().Name,
⋮----
ledger.Complete(opened.TicketId, stored.RecordId);
⋮----
await Audit("licence:issue", stored.LicenseId.ToString(), new Dictionary<string, string?>
⋮----
["recordId"] = stored.RecordId.ToString(),
⋮----
["expiration"] = stored.ExpirationUtc.ToString("O"),
⋮----
public async Task<IActionResult> Issued(Guid id, CancellationToken cancellationToken)
⋮----
var record = await register.FindAsync(id, cancellationToken);
⋮----
private async Task<IActionResult> FormViewAsync(IssueForm form, IEnumerable<string>? problems = null)
⋮----
ModelState.AddModelError(string.Empty, problem);
⋮----
var mayIssue = await authorization.AuthorizeAsync(User, ConsolePolicies.LicensingWrite);
⋮----
private string FailureMessage(Exception ex) => ex switch
⋮----
LicenseConfigException config => text["Licensing.Issue.Failure.Config", string.Join(" ", config.Problems)],
⋮----
private static IssueForm FromRecord(RegisterRecord record, DateTime nowUtc, out List<string> dropped)
⋮----
foreach (var (name, value) in record.Attributes.OrderBy(pair => pair.Key, StringComparer.Ordinal))
⋮----
if (IssuerWrittenAttributes.Contains(name)
|| LicenseContract.Attributes.Entitlements.Contains(name, StringComparer.Ordinal))
⋮----
if (LicenseContract.IsReservedAttributeName(name))
⋮----
dropped.Add(name);
⋮----
carried.Add($"{name}={value}");
⋮----
var form = new IssueForm
⋮----
Attributes = carried.Count == 0 ? null : string.Join("\n", carried),
⋮----
form.Expiration = DateOnly.FromDateTime(record.ExpirationUtc).AddMonths(IssueForm.DefaultTermMonths);
⋮----
dropped.AddRange(entitlements.IgnoredNames);
⋮----
form.Reports = entitlements.Reports.ToList();
form.Features = entitlements.Features.ToList();
... (13 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Controllers/RegisterController.cs">
public sealed class RegisterController(
⋮----
IStringLocalizer<ConsoleResource> text) : Controller
⋮----
public async Task<IActionResult> Index(
⋮----
var query = RegisterQuery.From(q, purpose, tier, status, clock.GetUtcNow().UtcDateTime);
var results = await register.SearchAsync(query, Math.Max(1, page), PageSize, cancellationToken);
return View(new RegisterList(query, results, register.Availability));
⋮----
public async Task<IActionResult> Details(Guid id, CancellationToken cancellationToken)
⋮----
var record = await register.FindAsync(id, cancellationToken);
⋮----
public async Task<IActionResult> Download(Guid id, CancellationToken cancellationToken)
⋮----
await Audit("licence:redownload", record.LicenseId.ToString(), new Dictionary<string, string?>
⋮----
["recordId"] = record.RecordId.ToString(),
⋮----
return File(RegisterRecord.FileBytes(record.LicenseXml), "application/xml", record.FileName);
⋮----
public async Task<IActionResult> Export(string? q, string? purpose, string? tier, string? status, CancellationToken cancellationToken)
⋮----
var csv = new StringBuilder();
csv.Append(RegisterRecord.CsvLine(RegisterRecord.CsvColumns)).Append("\r\n");
⋮----
await foreach (var record in register.ExportAsync(query, cancellationToken))
⋮----
csv.Append(RegisterRecord.CsvLine(record.CsvFields())).Append("\r\n");
⋮----
["rows"] = rows.ToString(System.Globalization.CultureInfo.InvariantCulture),
⋮----
var fileName = string.Create(CultureInfo.InvariantCulture, $"licence-register-{DateTime.UtcNow:yyyyMMdd-HHmm}.csv");
return File(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(csv.ToString()), "text/csv", fileName);
⋮----
private Task Audit(string action, string? target, IReadOnlyDictionary<string, string?> details, CancellationToken cancellationToken) =>
auditLog.RecordAsync(
new AuditEntry(
⋮----
public Dictionary<string, string> RouteValues(int page)
⋮----
var values = Query.RouteValues();
values["page"] = page.ToString(System.Globalization.CultureInfo.InvariantCulture);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Controllers/ValidateController.cs">
public sealed class ValidateController(
⋮----
IStringLocalizer<ConsoleResource> text) : Controller
⋮----
public IActionResult Index()
⋮----
return View(new ValidatePageModel());
⋮----
public async Task<IActionResult> Index(IFormFile? file, string? pasted, bool trustContractTestKey, DateTime? asOf, CancellationToken cancellationToken)
⋮----
var model = new ValidatePageModel { TrustContractTestKey = trustContractTestKey, AsOf = asOf };
⋮----
ModelState.AddModelError(string.Empty, file is { Length: > MaxLicenceBytes }
⋮----
? TrustedKeys.Product.Append(TrustedKeys.ContractTest).ToList()
: TrustedKeys.Product.ToList();
⋮----
var instant = asOf is null ? clock.GetUtcNow().UtcDateTime : DateTime.SpecifyKind(asOf.Value, DateTimeKind.Utc);
⋮----
var report = LicenceValidator.Validate(licenseXml, keys, instant, text);
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
["inRegister"] = (inRegister is not null).ToString(),
⋮----
private static async Task<string?> ReadLicenceAsync(IFormFile? file, string? pasted, CancellationToken cancellationToken)
⋮----
using var buffer = new MemoryStream();
await file.CopyToAsync(buffer, cancellationToken);
⋮----
return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetString(buffer.ToArray()).TrimStart('﻿');
⋮----
if (file is null or { Length: 0 } && !string.IsNullOrWhiteSpace(pasted) && pasted.Length <= MaxLicenceBytes)
⋮----
return pasted.Trim();
⋮----
private async Task<(Guid? LicenseId, RegisterRecord? Exact, int SameId)> FindInRegisterAsync(string licenseXml, CancellationToken cancellationToken)
⋮----
Guid licenseId;
⋮----
licenseId = Standard.Licensing.License.Load(licenseXml).Id;
⋮----
var rows = (await register.SearchAsync(new RegisterQuery { Text = licenseId.ToString() }, 1, 100, cancellationToken)).Rows
.Where(row => row.LicenseId == licenseId)
.ToList();
⋮----
var sha256 = RegisterRecord.Sha256Of(licenseXml);
return (licenseId, rows.FirstOrDefault(row => row.Sha256 == sha256), rows.Count);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/ViewComponents/LicenceInstallationsViewComponent.cs">
public sealed class LicenceInstallationsViewComponent(GatewayAdminClient gateway) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync(Guid licenceId)
⋮----
var answer = await gateway.InstallationsHoldingAsync(licenceId, HttpContext.RequestAborted);
return View(new LicenceInstallations(licenceId, answer));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/ViewComponents/LicensingOverviewViewComponent.cs">
public sealed class LicensingOverviewViewComponent(
⋮----
ILogger<LicensingOverviewViewComponent> logger) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync()
⋮----
if (!(await authorization.AuthorizeAsync(UserClaimsPrincipal, ConsolePolicies.LicensingView)).Succeeded)
⋮----
var nowUtc = clock.GetUtcNow().UtcDateTime;
⋮----
var sharedAnswer = gateway.SharedAsync(cancellationToken);
⋮----
summaries = await register.SummariesAsync(cancellationToken);
statistics = RegisterStatistics.Compute(summaries, nowUtc);
⋮----
logger.LogError(ex, "The overview could not read the licence register.");
⋮----
var shared = SharedLicence.Find(gatewayAnswer.Installations, summaries);
⋮----
return View(ViewPath, new LicensingOverviewModel(register.Availability, statistics, nowUtc, gatewayAnswer, shared));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/_HiddenForm.cshtml">
@using System.Globalization
@model IssueForm

@* The form as posted, carried through the preview so "Edit" returns to it intact. Never what is
   signed: that is the sealed ticket alone. Every value is written invariant, as the form posted it (#102). *@

<input type="hidden" asp-for="IssuedBy" />
<input type="hidden" asp-for="CustomerName" />
<input type="hidden" asp-for="CustomerEmail" />
<input type="hidden" asp-for="Company" />
<input type="hidden" asp-for="Tier" />
<input type="hidden" asp-for="Purpose" />
<input type="hidden" name="ValidFrom" value='@Model.ValidFrom?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)' />
<input type="hidden" asp-for="Term" />
<input type="hidden" name="DurationAmount" value="@Model.DurationAmount?.ToString(CultureInfo.InvariantCulture)" />
<input type="hidden" asp-for="DurationUnit" />
<input type="hidden" name="Expiration" value='@Model.Expiration?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)' />
<input type="hidden" asp-for="Attributes" />
<input type="hidden" asp-for="LicenseId" />
<input type="hidden" asp-for="ReissueOf" />
<input type="hidden" name="SourcesMax" value="@Model.SourcesMax?.ToString(CultureInfo.InvariantCulture)" />
<input type="hidden" name="AnalysisEmployees" value="@Model.AnalysisEmployees?.ToString(CultureInfo.InvariantCulture)" />
<input type="hidden" name="AnalysisAssets" value="@Model.AnalysisAssets?.ToString(CultureInfo.InvariantCulture)" />
<input type="hidden" name="AnalysisHistory" value="@Model.AnalysisHistory?.ToString(CultureInfo.InvariantCulture)" />
<input type="hidden" name="AiTokens" value="@Model.AiTokens?.ToString(CultureInfo.InvariantCulture)" />
<input type="hidden" asp-for="AiPeriod" />
<input type="hidden" name="AiRequestsPerMinute" value="@Model.AiRequestsPerMinute?.ToString(CultureInfo.InvariantCulture)" />
@foreach (var (field, names) in new[] { ("Reports", Model.Reports), ("Features", Model.Features), ("Sources", Model.Sources), ("Ai", Model.Ai) })
{
    foreach (var name in names.Where(name => !string.IsNullOrEmpty(name)))
    {
        <input type="hidden" name="@field" value="@name" />
    }

    @* Present even when every switch is off, so an empty list binds as empty rather than as the default of all on. *@
    <input type="hidden" name="@field" value="" />
}
@foreach (var (source, count) in Model.SourceCounts.Where(pair => pair.Value is not null))
{
    <input type="hidden" name="SourceCounts[@source]" value="@count?.ToString(CultureInfo.InvariantCulture)" />
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/_Limit.cshtml">
@model (LicenseContract.LimitEntry Limit, string Field, long? Value)

@* A number that is blank when there is no limit - or, for the AI Gateway, when the tier's default applies. *@

<div>
    <label for="@Model.Field" class="form-label">@S.LimitName(Model.Limit)</label>
    <div class="input-group">
        @* The value is written invariant: a number input takes digits whatever the language (#102). *@
        <input type="number" min="1" step="1" class="form-control" id="@Model.Field" name="@Model.Field" value="@Model.Value?.ToString(System.Globalization.CultureInfo.InvariantCulture)"
               placeholder="@S.LimitAbsentMeans(Model.Limit).TrimEnd('.')" data-limit />
        <span class="input-group-text">@S.LimitUnit(Model.Limit)</span>
    </div>
    <div class="form-text">@S.LimitDescription(Model.Limit)</div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/_SigningStatus.cshtml">
@model (SigningKeyState KeyState, RegisterAvailability Availability)

@* Why this page can or cannot sign, said before anyone fills in the form rather than after. *@

@switch (Model.KeyState)
{
    case SigningKeyState.NotConfigured:
        <div class="alert alert-warning" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Signing.NoKey.Title"]</h6>
            <p class="mb-0">@T["Licensing.Signing.NoKey.Detail"]</p>
        </div>
        break;
    case SigningKeyState.ContractTestKeyRefused:
        <div class="alert alert-danger" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Signing.TestKeyRefused.Title"]</h6>
            <p class="mb-0">@T["Licensing.Signing.TestKeyRefused.Detail"]</p>
        </div>
        break;
    case SigningKeyState.ContractTestKey:
        <div class="alert alert-info" role="alert">@T["Licensing.Signing.TestKey"]</div>
        break;
}

@if (Model.Availability == RegisterAvailability.Unavailable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Licensing.Register.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Licensing.Signing.NoDatabase.Detail"]</p>
    </div>
}
else if (Model.Availability == RegisterAvailability.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Licensing.Signing.Ephemeral"]</div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/_Switches.cshtml">
@model (string Field, string Noun, List<(string Name, string DisplayName, string Description)> Catalogue, List<string> Selected)

@* One switch per catalogue entry. The licence names the ones left on and nothing else. *@

<div class="d-flex gap-3 small mb-2">
    <button type="button" class="btn btn-link p-0" data-select="@Model.Field" data-select-value="true">@T["Licensing.Issue.AllOn"]</button>
    <button type="button" class="btn btn-link p-0" data-select="@Model.Field" data-select-value="false">@T["Licensing.Issue.AllOff"]</button>
</div>
<div class="d-flex flex-column gap-2">
    @foreach (var entry in Model.Catalogue)
    {
        var id = Model.Noun + "-" + entry.Name;
        <div class="form-check form-switch mb-0">
            <input class="form-check-input" type="checkbox" name="@Model.Field" value="@entry.Name" id="@id"
                   @(Model.Selected.Contains(entry.Name) ? "checked" : "") />
            <label class="form-check-label" for="@id">
                @entry.DisplayName
                <span class="d-block small text-body-secondary">@entry.Description</span>
            </label>
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/Index.cshtml">
@model IssueForm
@{
    var keyState = (SigningKeyState)ViewData["keyState"]!;
    var availability = (RegisterAvailability)ViewData["availability"]!;
    var dropped = ViewData["dropped"] as IReadOnlyList<string>;
    var predates = ViewData["predatesEntitlements"] is true;
    var mayIssue = ViewData["mayIssue"] is true;
    var reissue = Model.LicenseId is not null;
    var summary = EntitlementSummary.Brief(Model.ToEntitlements(), S).ToDictionary(line => line.Section, line => line.Summary);

    // One click for the usual terms; the number and the unit take anything else.
    var termPresets = new (int Amount, LicenceTermUnit Unit, string Label)[]
    {
        (3, LicenceTermUnit.Months, S["Licensing.Issue.Term.Months", 3]),
        (6, LicenceTermUnit.Months, S["Licensing.Issue.Term.Months", 6]),
        (1, LicenceTermUnit.Years, S["Licensing.Issue.Term.OneYear"]),
        (2, LicenceTermUnit.Years, S["Licensing.Issue.Term.Years", 2]),
        (3, LicenceTermUnit.Years, S["Licensing.Issue.Term.Years", 3]),
    };
}

@section PageScripts {
    <script src="~/js/issue-form.js" asp-append-version="true"></script>
}

<div class="mb-4">
    <a asp-controller="Register" asp-action="@(Model.ReissueOf is null ? "Index" : "Details")" asp-route-id="@Model.ReissueOf" class="text-body">
        <i class="ti ti-arrow-left me-1"></i>@T["Licensing.Register.Title"]
    </a>
</div>

<partial name="_SigningStatus" model="(keyState, availability)" />

@if (!mayIssue)
{
    @* Said before the form rather than as a refusal after it: a role decides who issues (#88). *@
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Licensing.Issue.ViewOnly.Title"]</h6>
        <p class="mb-0">@T["Licensing.Issue.ViewOnly.Detail", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.LicensingWrite))}</strong>"), Html.Raw($"<strong>{Html.Encode(User.Identity?.Name)}</strong>")]</p>
    </div>
}

@if (dropped is { Count: > 0 })
{
    <div class="alert alert-warning" role="alert">@T["Licensing.Issue.Dropped", string.Join(", ", dropped)]</div>
}

@if (predates)
{
    <div class="alert alert-warning" role="alert">@T["Licensing.Issue.Predates"]</div>
}

<form method="post" asp-action="Preview" novalidate>
    <input type="hidden" asp-for="LicenseId" />
    <input type="hidden" asp-for="ReissueOf" />
    @* Posted even when every switch in a section is off, so the list binds as empty rather than as the default of all on. *@
    <input type="hidden" name="Reports" value="" />
    <input type="hidden" name="Features" value="" />
    <input type="hidden" name="Sources" value="" />
    <input type="hidden" name="Ai" value="" />

    <div asp-validation-summary="All" class="alert alert-danger @(ViewData.ModelState.IsValid ? "d-none" : "")" role="alert"></div>

    <div class="row g-4">
        <div class="col-lg-7">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-1">@(reissue ? T["Licensing.Issue.ReissueTitle"] : T["Licensing.Issue.Title"])</h5>
                    <p class="text-body mb-0">
                        @if (reissue)
                        {
                            @T["Licensing.Issue.ReissueLead", Html.Raw($"<code>{Model.LicenseId}</code>")]
                        }
                        else
                        {
                            @T["Licensing.Issue.Lead"]
                        }
                    </p>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label asp-for="CustomerName" class="form-label"></label>
                            <input asp-for="CustomerName" class="form-control" autocomplete="off" />
                            <span asp-validation-for="CustomerName" class="text-danger small"></span>
                        </div>
                        <div class="col-md-6">
                            <label asp-for="CustomerEmail" class="form-label"></label>
                            <input asp-for="CustomerEmail" class="form-control" autocomplete="off" />
                            <span asp-validation-for="CustomerEmail" class="text-danger small"></span>
                        </div>
                        <div class="col-12">
                            <span class="form-label d-block" id="purpose-label">@T["Licensing.Issue.PurposeLabel"]</span>
                            <div role="radiogroup" aria-labelledby="purpose-label">
                                @foreach (var purpose in LicenseContract.Purposes.All)
                                {
                                    <div class="form-check form-check-inline">
                                        <input type="radio" class="form-check-input" name="Purpose" id="purpose-@purpose.Name" value="@purpose.Name"
                                               @(Model.Purpose == purpose.Name ? "checked" : "") />
                                        <label class="form-check-label" for="purpose-@purpose.Name" title="@S.PurposeDescription(purpose.Name)">@S.PurposeName(purpose.Name)</label>
... (238 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/Issued.cshtml">
@model RegisterRecord

<div class="card">
    <div class="card-body text-center py-5">
        <i class="ti ti-circle-check ti-xl text-success mb-3 d-block"></i>
        <h4 class="mb-2">@T["Licensing.Issued.Title", Model.CustomerName]</h4>
        <p class="text-body mb-1">
            @T["Licensing.Issued.Expires", Model.ExpirationUtc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC", Html.Raw($"<code>{Model.LicenseId}</code>")]
        </p>
        <p class="text-body mb-4">@T["Licensing.Issued.Recorded"]</p>

        <div class="d-flex flex-wrap justify-content-center gap-2">
            <a asp-controller="Register" asp-action="Download" asp-route-id="@Model.RecordId" class="btn btn-primary">
                <i class="ti ti-file-download me-1"></i> @T["Licensing.Issued.Download", Model.FileName]
            </a>
            <a asp-controller="Register" asp-action="Details" asp-route-id="@Model.RecordId" class="btn btn-label-secondary">
                @T["Licensing.Issued.ViewInRegister"]
            </a>
            <a asp-action="Index" class="btn btn-label-secondary">@T["Licensing.Issued.IssueAnother"]</a>
        </div>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Issue/Preview.cshtml">
@model IssuePreviewModel
@{
    var terms = Model.Preview.Terms;
    string Instant(DateTime value) => value.ToString("yyyy-MM-dd HH:mm:ss") + " UTC";
    var validFrom = terms.Attributes.TryGetValue(LicenseContract.Attributes.ValidFrom, out var from) ? from : null;
    var tier = terms.Attributes.TryGetValue(LicenseContract.Attributes.Tier, out var t) ? t : null;
    var purpose = LicenseContract.Purposes.Of(terms.Attributes);
    var entitlement = EntitlementSummary.Describe(Entitlements.Read(terms.Attributes), S);
}

<partial name="_SigningStatus" model="(Model.KeyState, Model.Availability)" />

@* The signer's own warnings: the CLI's shared code, in its words (#102). *@
@foreach (var warning in Model.Preview.Warnings)
{
    <div class="alert alert-warning" role="alert"><span class="fw-medium">@T["Licensing.Issue.SignerSays"]</span> @warning</div>
}

<div class="row g-4">
    <div class="col-lg-5">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-1">@terms.Name</h5>
                <p class="text-body mb-0">@terms.Email@(terms.Company is null ? "" : " · " + terms.Company)</p>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-sm-5">@T["Licensing.LicenceId"]</dt>
                    <dd class="col-sm-7"><code class="text-break">@terms.LicenseId</code></dd>

                    <dt class="col-sm-5">@T["Licensing.Type"]</dt>
                    <dd class="col-sm-7">@terms.LicenseType</dd>

                    <dt class="col-sm-5">@T["Licensing.Purpose"]</dt>
                    <dd class="col-sm-7"><partial name="_Purpose" model="purpose" /></dd>

                    <dt class="col-sm-5">@T["Licensing.Tier"]</dt>
                    <dd class="col-sm-7">@(tier ?? "-")</dd>

                    <dt class="col-sm-5">@T["Licensing.ValidFrom"]</dt>
                    <dd class="col-sm-7">@(validFrom is null ? T["Licensing.Issue.OnIssue"].Value : validFrom.Replace("T", " ").TrimEnd('Z') + " UTC")</dd>

                    <dt class="col-sm-5">@T["Licensing.Column.Expires"]</dt>
                    <dd class="col-sm-7">@Instant(terms.ExpirationUtc)</dd>

                    <partial name="_Entitlement" model="(entitlement, 5)" />

                    <dt class="col-sm-5">@T["Licensing.Column.IssuedBy"]</dt>
                    <dd class="col-sm-7">@Model.Form.IssuedBy</dd>

                    <dt class="col-sm-5">@T["Licensing.Issue.Size"]</dt>
                    <dd class="col-sm-7 mb-0">@T["Licensing.Issue.BytesSigned", Model.Preview.SignedBytes]</dd>
                </dl>
            </div>
        </div>

        <div class="card">
            <div class="card-body d-flex flex-column gap-2">
                @* Sign posts the sealed ticket - which is all that is signed - and the form, which is used
                   only to come back here if signing fails. *@
                <form method="post" asp-action="Sign" id="sign-form">
                    <input type="hidden" name="ticket" value="@Model.Ticket" />
                    <partial name="_HiddenForm" model="Model.Form" />
                    <button type="submit" class="btn btn-primary w-100" @(Model.CanSign ? "" : "disabled")>
                        <i class="ti ti-signature me-1"></i> @T["Licensing.Issue.SignAndRecord"]
                    </button>
                </form>
                <form method="post" asp-action="Edit">
                    <partial name="_HiddenForm" model="Model.Form" />
                    <button type="submit" class="btn btn-label-secondary w-100">
                        <i class="ti ti-pencil me-1"></i> @T["Generic.Edit"]
                    </button>
                </form>
                <p class="small text-body mb-0">@T["Licensing.Issue.SigningHelp", (int)IssueTicketProtector.Lifetime.TotalMinutes]</p>
            </div>
        </div>
    </div>

    <div class="col-lg-7">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-1">@T["Licensing.LicenceXml"]</h6>
                <p class="small text-body mb-0">@T["Licensing.Issue.XmlLead"]</p>
            </div>
            <div class="card-body">
                <pre class="mb-0"><code>@Model.Preview.Xml</code></pre>
            </div>
        </div>
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Register/Details.cshtml">
@using KnowledgeFabric.AdminConsole.Areas.Licensing.ViewComponents
@model RegisterRecord
@{
    string Instant(DateTime? value) => value is null ? "-" : value.Value.ToString("yyyy-MM-dd HH:mm:ss") + " UTC";
    var otherAttributes = Model.OtherAttributes.ToList();
    var entitlements = Model.Entitlements;
}

<div class="mb-4">
    <a asp-action="Index" class="text-body"><i class="ti ti-arrow-left me-1"></i>@T["Licensing.Register.Title"]</a>
</div>

<div class="row g-4">
    <div class="col-lg-7">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-start gap-3">
                <div>
                    <h5 class="card-title mb-1">@Model.CustomerName</h5>
                    <p class="text-body mb-0">@Model.CustomerEmail</p>
                </div>
                <div class="d-flex flex-wrap gap-2">
                    <a asp-controller="Issue" asp-action="Index" asp-route-from="@Model.RecordId" class="btn btn-label-secondary">
                        <i class="ti ti-refresh me-1"></i> @T["Licensing.Reissue"]
                    </a>
                    <a asp-action="Download" asp-route-id="@Model.RecordId" class="btn btn-primary">
                        <i class="ti ti-file-download me-1"></i> @T["Licensing.Register.DownloadLic"]
                    </a>
                </div>
            </div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-sm-4">@T["Licensing.Column.Company"]</dt>
                    <dd class="col-sm-8">@(Model.Company ?? "-")</dd>

                    <dt class="col-sm-4">@T["Licensing.LicenceId"]</dt>
                    <dd class="col-sm-8"><code>@Model.LicenseId</code></dd>

                    <dt class="col-sm-4">@T["Licensing.Type"]</dt>
                    <dd class="col-sm-8">@Model.LicenseType</dd>

                    <dt class="col-sm-4">@T["Licensing.Purpose"]</dt>
                    <dd class="col-sm-8"><partial name="_Purpose" model="Model.Purpose" /></dd>

                    <dt class="col-sm-4">@T["Licensing.Tier"]</dt>
                    <dd class="col-sm-8">@(Model.Tier ?? "-")</dd>

                    <dt class="col-sm-4">@T["Licensing.SchemaVersion"]</dt>
                    <dd class="col-sm-8">@(Model.SchemaVersion?.ToString() ?? T["Licensing.Unreadable"].Value)</dd>

                    <dt class="col-sm-4">@T["Licensing.ValidFrom"]</dt>
                    <dd class="col-sm-8">@(Model.ValidFromUtc is null ? T["Licensing.Register.OnInstallation"].Value : Instant(Model.ValidFromUtc))</dd>

                    <dt class="col-sm-4">@T["Licensing.Column.Expires"]</dt>
                    <dd class="col-sm-8">@Instant(Model.ExpirationUtc)</dd>

                    <partial name="_Entitlement" model="(EntitlementSummary.Describe(entitlements, S), 4)" />

                    @if (entitlements.IgnoredNames.Count > 0)
                    {
                        <dt class="col-sm-4">@T["Licensing.Register.NotKnownHere"]</dt>
                        <dd class="col-sm-8">
                            @string.Join(", ", entitlements.IgnoredNames)
                            <div class="small text-body">@T["Licensing.Register.NotKnownHere.Detail"]</div>
                        </dd>
                    }

                    @if (Model.Features.Count > 0)
                    {
                        <dt class="col-sm-4">@T["Licensing.AreaKeys"]</dt>
                        <dd class="col-sm-8">
                            @foreach (var feature in Model.Features.OrderBy(pair => pair.Key, StringComparer.Ordinal))
                            {
                                <span class="badge bg-label-secondary me-1 mb-1">@feature.Key: @feature.Value</span>
                            }
                            <div class="small text-body">@T["Licensing.Register.AreaKeys.Detail"]</div>
                        </dd>
                    }

                    <dt class="col-sm-4">@T["Licensing.OtherAttributes"]</dt>
                    <dd class="col-sm-8 mb-0">
                        @if (otherAttributes.Count == 0) { <span>-</span> }
                        @foreach (var pair in otherAttributes) { <div><code>@pair.Key</code> = @pair.Value</div> }
                    </dd>
                </dl>
            </div>
        </div>
    </div>

    <div class="col-lg-5">
        <div class="card">
            <div class="card-header"><h6 class="card-title mb-0">@T["Licensing.Register.Issue"]</h6></div>
            <div class="card-body">
                <dl class="row mb-0">
                    <dt class="col-sm-5">@T["Licensing.Column.Issued"]</dt>
                    <dd class="col-sm-7">@Instant(Model.IssuedAtUtc)</dd>

                    <dt class="col-sm-5">@T["Licensing.Column.IssuedBy"]</dt>
                    <dd class="col-sm-7">@Model.IssuedBy</dd>

                    <dt class="col-sm-5">@T["Licensing.Register.SignedInAs"]</dt>
... (26 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Register/Index.cshtml">
@model RegisterList
@{
    var query = Model.Query;
    var results = Model.Results;
}

<partial name="_RegisterAvailability" model="Model.Availability" />

<div class="card">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div>
            <h5 class="card-title mb-1">@T["Licensing.Register.Title"]</h5>
            <p class="text-body mb-0">
                @T["Licensing.Register.Lead"]
                @if (query.IsFiltered)
                {
                    @(results.TotalCount == 1 ? T["Licensing.Register.Count.OneMatch"] : T["Licensing.Register.Count.ManyMatch", results.TotalCount])
                }
                else
                {
                    @(results.TotalCount == 1 ? T["Licensing.Register.Count.One"] : T["Licensing.Register.Count.Many", results.TotalCount])
                }
            </p>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a asp-action="Export" asp-all-route-data="@query.RouteValues()" class="btn btn-label-secondary">
                <i class="ti ti-download me-1"></i> CSV
            </a>
            <a asp-controller="Issue" asp-action="Index" class="btn btn-primary">
                <i class="ti ti-file-plus me-1"></i> @T["Licensing.Register.Issue"]
            </a>
        </div>
    </div>

    <div class="card-body">
        <form method="get" asp-action="Index" class="row g-3 align-items-end" role="search">
            <div class="col-12 col-xl-4">
                <label for="q" class="form-label">@T["Generic.Search"]</label>
                <input type="search" id="q" name="q" value="@query.Text" class="form-control" placeholder="@T["Licensing.Register.SearchPlaceholder"].Value" />
            </div>
            <div class="col-12 col-md-4 col-xl-2">
                <label for="purpose" class="form-label">@T["Licensing.Purpose"]</label>
                <select id="purpose" name="purpose" class="form-select">
                    <option value="">@T["Licensing.Register.EveryPurpose"]</option>
                    @foreach (var purpose in LicenseContract.Purposes.All)
                    {
                        <option value="@purpose.Name" selected="@(query.Purpose == purpose.Name)">@S.PurposeName(purpose.Name)</option>
                    }
                </select>
            </div>
            <div class="col-12 col-md-4 col-xl-2">
                <label for="tier" class="form-label">@T["Licensing.Tier"]</label>
                <select id="tier" name="tier" class="form-select">
                    <option value="">@T["Licensing.Register.EveryTier"]</option>
                    @foreach (var tier in LicenseContract.Tiers.All)
                    {
                        <option value="@tier" selected="@(query.Tier == tier)">@S.TierName(tier)</option>
                    }
                    <option value="@RegisterQuery.NoTier" selected="@(query.Tier == RegisterQuery.NoTier)">@S.TierName(null)</option>
                </select>
            </div>
            <div class="col-12 col-md-4 col-xl-2">
                <label for="status" class="form-label">@T["Licensing.Register.Status"]</label>
                <select id="status" name="status" class="form-select">
                    <option value="">@T["Licensing.Register.Status.Both"]</option>
                    <option value="@RegisterQuery.Active" selected="@(query.Status == RegisterStatus.Active)">@T["Licensing.Register.Status.Active"]</option>
                    <option value="@RegisterQuery.Expired" selected="@(query.Status == RegisterStatus.Expired)">@T["Licensing.Register.Status.Expired"]</option>
                </select>
            </div>
            <div class="col-12 col-xl-2 d-flex gap-2">
                <button type="submit" class="btn btn-primary flex-fill">@T["Generic.Apply"]</button>
                <a asp-action="Index" class="btn btn-label-secondary flex-fill">@T["Generic.Clear"]</a>
            </div>
        </form>
    </div>

    <div class="table-responsive text-nowrap">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>@T["Licensing.Column.Customer"]</th>
                    <th>@T["Licensing.Column.Company"]</th>
                    <th>@T["Licensing.Tier"]</th>
                    <th>@T["Licensing.Column.Expires"]</th>
                    <th>@T["Licensing.Column.Issued"]</th>
                    <th>@T["Licensing.Column.IssuedBy"]</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @if (results.Rows.Count == 0)
                {
                    <tr>
                        <td colspan="7" class="text-center text-body py-4">
                            @(query.IsFiltered ? T["Licensing.Register.Empty.Filtered"] : T["Licensing.Register.Empty"])
                        </td>
                    </tr>
                }
                @foreach (var row in results.Rows)
                {
... (52 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Shared/Components/LicenceInstallations/Default.cshtml">
@using KnowledgeFabric.AdminConsole.Areas.Gateway.Models
@using KnowledgeFabric.AdminConsole.Licensing.Installations
@model LicenceInstallations
@{
    static string Instant(DateTimeOffset? value) => value is null ? "-" : value.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm") + " UTC";
    static string Day(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd");
}

<div class="card">
    <div class="card-header">
        <h6 class="card-title mb-1">@T["Licensing.Installations"]</h6>
        <p class="card-subtitle mb-0">@T["Licensing.Installations.Lead", Html.Raw($"<code>{Model.LicenceId}</code>")]</p>
    </div>

    @if (Model.Answer.Outcome != GatewayOutcome.Answered)
    {
        <div class="card-body">
            <partial name="_GatewayUnavailable" model="Model.Answer" />
        </div>
    }
    else
    {
        @if (Model.IsShared)
        {
            <div class="card-body pb-0">
                <div class="alert alert-warning mb-0" role="alert">
                    <h6 class="alert-heading mb-1">@T["Licensing.Installations.Shared.Title", Model.Holding]</h6>
                    <p class="mb-0">@T["Licensing.Installations.Shared.Detail"]</p>
                </div>
            </div>
        }

        @if (Model.Answer.Installations.Count == 0)
        {
            <div class="card-body">
                <p class="text-body mb-0">@T["Licensing.Installations.None"]</p>
            </div>
        }
        else
        {
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>@T["Licensing.Installations.Column.Installation"]</th>
                            <th>@T["Gateway.Location.Country"]</th>
                            <th>@T["Licensing.Installations.Column.Version"]</th>
                            <th>@T["Licensing.Installations.Column.Row"]</th>
                            <th>@T["Licensing.Installations.Column.Status"]</th>
                            <th>@T["Licensing.Installations.Column.Enrolled"]</th>
                            <th class="text-nowrap">@T["Licensing.Installations.Column.LastSeen"]</th>
                            <th class="text-nowrap">@T["Licensing.Installations.Column.TokensUsed"]</th>
                            <th class="text-nowrap">@T["Licensing.Installations.Column.RequestsAMinute"]</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var installation in Model.Rows)
                        {
                            <tr>
                                <td class="text-nowrap">
                                    @* Short, as on the installations list: the whole id is the link's and its title. *@
                                    <a asp-area="Gateway" asp-controller="Installations" asp-action="Details" asp-route-id="@installation.InstallationId" title="@installation.InstallationId"><code>@installation.InstallationId.ToString()[..8]</code></a>
                                    @if (Model.IsShared && !installation.IsRevoked)
                                    {
                                        @* The shared flag's remedy, beside each installation holding the licence (#69). *@
                                        <a asp-area="Gateway" asp-controller="Installations" asp-action="Revoke" asp-route-id="@installation.InstallationId"
                                           class="btn btn-sm btn-outline-danger ms-2">@T["Licensing.Installations.Revoke"]</a>
                                    }
                                </td>
                                @* Where it calls from (#217): its country, the network and cloud region on hover. *@
                                <td><partial name="~/Areas/Gateway/Views/Shared/_InstallationCountry.cshtml" model="installation.Location" /></td>
                                <td>@(installation.AppVersion ?? "-")</td>
                                <td>
                                    @if (installation.Allowance?.Row is { } served)
                                    {
                                        <span>@served</span>
                                    }
                                    else
                                    {
                                        <span class="text-body-secondary" title="@T["Licensing.Installations.WireTier"].Value">@(installation.Tier ?? "-")</span>
                                    }
                                </td>
                                <td>
                                    <span class="badge @(installation.IsRevoked ? "bg-label-secondary" : "bg-label-success")">@(installation.Status ?? (installation.IsRevoked ? "revoked" : "active"))</span>
                                    @if (installation.IsRevoked)
                                    {
                                        <div class="small text-body text-nowrap">@Instant(installation.RevokedAt)</div>
                                    }
                                </td>
                                <td class="text-nowrap" title="@Instant(installation.CreatedAt)">@Day(installation.CreatedAt)</td>
                                <td class="text-nowrap">@Instant(installation.LastSeenAt)</td>
                                @if (installation.IsRevoked)
                                {
                                    <td colspan="2" class="small text-body-secondary">@T["Licensing.Installations.ServedNothing"]</td>
                                }
                                else if (installation.Allowance is not { } allowance)
                                {
                                    <td colspan="2" class="small text-body-secondary" title="@T["Licensing.Installations.NotReported.Title"].Value">@T["Licensing.Installations.NotReported"]</td>
                                }
                                else
... (41 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Shared/Components/LicensingOverview/Default.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Licensing.ViewComponents
@model LicensingOverviewModel
@{
    var stats = Model.Statistics;
    var today = DateOnly.FromDateTime(Model.NowUtc);

    string Count(int n, string key) => n == 1 ? S[key + ".One"] : S[key + ".Many", n];

    string DaysLeft(DateTime expiresUtc)
    {
        var days = DateOnly.FromDateTime(expiresUtc).DayNumber - today.DayNumber;
        return days switch
        {
            <= 0 => S["Licensing.Overview.Today"],
            1 => S["Licensing.Overview.Tomorrow"],
            _ => S["Licensing.Overview.InDays", days],
        };
    }

    // The palette's own names, by the tier's code, resolved to colours in script from window.config (wwwroot/js/config.js).
    static string TierColour(string code) => code switch
    {
        LicenseContract.Tiers.Standard => "primary",
        LicenseContract.Tiers.Enterprise => "warning",
        RegisterStatistics.NoTier => "secondary",
        _ => "info",
    };

    // The chart's month names in the page's language: read, never parsed (#102).
    var culture = CultureInfo.CurrentCulture;
}

<partial name="~/Areas/Licensing/Views/Shared/_RegisterAvailability.cshtml" model="Model.Availability" />

@if (stats is null)
{
    <div class="alert alert-danger" role="alert">
        <h6 class="alert-heading mb-1">@T["Licensing.Overview.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Licensing.Overview.Unreadable.Detail"]</p>
    </div>
    return;
}

@if (Model.Availability == RegisterAvailability.Unavailable)
{
    return;
}

<div class="row g-4 mb-4">
    <div class="col-sm-6 col-xl-3">
        <div class="card h-100">
            <div class="card-body d-flex justify-content-between align-items-start">
                <div>
                    <span class="text-heading">@T["Licensing.Overview.LicencesIssued"]</span>
                    <h4 class="mb-1 mt-1">@stats.Licences</h4>
                    <small class="text-body">@Count(stats.Files, "Licensing.Overview.Files"), @Count(stats.Reissues, "Licensing.Overview.Reissues")</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-primary"><i class="ti ti-certificate ti-26px"></i></span>
                </div>
            </div>
        </div>
    </div>

    <div class="col-sm-6 col-xl-3">
        <div class="card h-100">
            <div class="card-body d-flex justify-content-between align-items-start">
                <div>
                    <span class="text-heading">@T["Licensing.Overview.Active"]</span>
                    <h4 class="mb-1 mt-1">@stats.Active</h4>
                    <small class="text-body">
                        @T["Licensing.Overview.InForceToday"]@(stats.NotYetInForce > 0 ? S["Licensing.Overview.MoreNotYetInForce", stats.NotYetInForce].Value : "")
                    </small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-success"><i class="ti ti-circle-check ti-26px"></i></span>
                </div>
            </div>
        </div>
    </div>

    <div class="col-sm-6 col-xl-3">
        <div class="card h-100">
            <div class="card-body d-flex justify-content-between align-items-start">
                <div>
                    <span class="text-heading">@T["Licensing.Overview.ExpiringWithinMonth"]</span>
                    <h4 class="mb-1 mt-1">@stats.ExpiringSoon</h4>
                    <small class="text-body">@T["Licensing.Overview.ByUnlessReissued", stats.ExpiringByUtc.ToString("yyyy-MM-dd")]</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-warning"><i class="ti ti-hourglass-high ti-26px"></i></span>
                </div>
            </div>
        </div>
    </div>

    <div class="col-sm-6 col-xl-3">
        <div class="card h-100">
            <div class="card-body d-flex justify-content-between align-items-start">
... (243 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Shared/_Entitlement.cshtml">
@model (IReadOnlyList<EntitlementLine> Lines, int LabelColumns)

@* What a licence grants, a line per section, as rows of the surrounding <dl class="row">. A section
   left at its default reads plainly; one that differs is marked, so a restricted licence stands out. *@

@foreach (var line in Model.Lines)
{
    <dt class="col-sm-@Model.LabelColumns">@T["Licensing.Section." + line.Section]</dt>
    <dd class="col-sm-@(12 - Model.LabelColumns)">
        @if (!line.IsDefault)
        {
            <span class="badge bg-label-warning me-1">@T["Licensing.Badge.Custom"]</span>
        }
        @line.Summary
    </dd>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Shared/_GatewayUnavailable.cshtml">
@model GatewayAnswer

@* Why the gateway's installations are missing (#58). Every outcome but Answered lands here, so a
   page that reads the gateway always renders, and says which of these it is. *@

@switch (Model.Outcome)
{
    case GatewayOutcome.NotConfigured:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.NotConfigured.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.NotConfigured.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NoLicenceIds:
        <div class="alert alert-secondary mb-0" role="status">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.NoLicenceIds.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.NoLicenceIds.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.RequestRefused:
        <div class="alert alert-danger mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.RequestRefused.Title"]</h6>
            <p class="mb-0">@Model.Detail @T["Licensing.Gateway.RequestRefused.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.TokenRefused:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.TokenRefused.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.TokenRefused.Detail"]</p>
        </div>
        break;

    case GatewayOutcome.NoAdminSurface:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.NoAdminSurface.Title"]</h6>
            <p class="mb-0">@T["Licensing.Gateway.NoAdminSurface.Detail"]</p>
        </div>
        break;

    default:
        <div class="alert alert-warning mb-0" role="alert">
            <h6 class="alert-heading mb-1">@T["Licensing.Gateway.Unreachable.Title"]</h6>
            <p class="mb-0">@Model.Detail @T["Licensing.Gateway.Unreachable.Detail"]</p>
        </div>
        break;
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Shared/_Purpose.cshtml">
@model string

@* What a licence is for. A customer's reads plainly; internal and demo licences carry a badge, so
   they are never mistaken for one sold. *@

@{
    var known = LicenseContract.Purposes.All.Any(purpose => purpose.Name == Model);
}
@if (Model == LicenseContract.Purposes.Customer)
{
    <span>@S.PurposeName(Model)</span>
}
else
{
    <span class="badge @(known ? "bg-label-info" : "bg-label-secondary")" title="@S.PurposeDescription(Model)">@S.PurposeName(Model)</span>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Shared/_RegisterAvailability.cshtml">
@model RegisterAvailability

@* What kind of register this is, on every page that reads it, so an empty one is not mistaken for a quiet one. *@

@if (Model == RegisterAvailability.Unavailable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Licensing.Register.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Licensing.Register.NoDatabase.Detail"]</p>
    </div>
}
else if (Model == RegisterAvailability.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Licensing.Register.Ephemeral"]</div>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Validate/_GatewayVerdict.cshtml">
@using System.Globalization
@model (string Heading, string Source, GatewayVerdict Verdict)

@* The gateway's own fields, as it would answer them: wire words, never translated. *@

<div class="d-flex justify-content-between align-items-start gap-2 mb-1">
    <span class="fw-medium">@Model.Heading</span>
    <span class="badge @(Model.Verdict.Tier == "licensed" ? "bg-label-success" : "bg-label-warning")">@Model.Verdict.Tier</span>
</div>
<p class="mb-1">
    <code>licence.status</code> <code>@Model.Verdict.Status</code>,
    <code>reason</code> <code>@(Model.Verdict.Reason ?? "null")</code>@(Model.Verdict.ExpiresAtUtc is { } expires ? ", expires_at " + expires.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture) : "")
</p>
@if (Model.Verdict.Cause is { } cause && cause != Model.Verdict.Reason)
{
    <p class="small mb-1">@T["Licensing.Validate.Gateway.LoggedAs", Html.Raw($"<code>{Html.Encode(cause)}</code>")]</p>
}
@if (Model.Verdict.Allowance is { } allowance)
{
    <p class="small mb-1">@allowance</p>
}
<p class="small text-body-secondary mb-0">@Model.Source</p>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Validate/_Verdict.cshtml">
@model (string Heading, string Source, ReaderVerdict Verdict)

@* The reason stays the contract's word: it is what the reader reports, not a translation of it. *@

<div class="d-flex justify-content-between align-items-start gap-2 mb-1">
    <span class="fw-medium">@Model.Heading</span>
    <span class="badge @(!Model.Verdict.Accepts ? "bg-label-danger" : Model.Verdict.GrantsNothing ? "bg-label-warning" : "bg-label-success")">
        @(!Model.Verdict.Accepts ? T["Licensing.Validate.Verdict.Refused"] : Model.Verdict.GrantsNothing ? T["Licensing.Validate.Verdict.AcceptedGrantsNothing"] : T["Licensing.Validate.Verdict.Accepted"])@(Model.Verdict.Reason is null ? "" : ": " + Model.Verdict.Reason)
    </span>
</div>
<p class="mb-1">@Model.Verdict.Summary</p>
<p class="small text-body-secondary mb-0">@Model.Source</p>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/Validate/Index.cshtml">
@using System.Globalization
@model ValidatePageModel
@{
    var report = Model.Report;
    string Instant(DateTime? value) => value is null ? "-" : value.Value.ToString("yyyy-MM-dd HH:mm:ss") + " UTC";
    string Badge(bool ok) => ok ? "bg-label-success" : "bg-label-danger";
    var productToday = S["Licensing.Validate.Source.ProductToday", LicenceValidator.ProductCommit].Value;
    var gatewayToday = S["Licensing.Validate.Source.GatewayToday", LicenceValidator.GatewayCommit].Value;
}

<div class="row g-4">
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Licensing.Validate.Title"]</h5>
                <p class="text-body mb-0">@T["Licensing.Validate.Lead"]</p>
            </div>
            <div class="card-body">
                <form method="post" asp-action="Index" enctype="multipart/form-data">
                    <div asp-validation-summary="All" class="alert alert-danger @(ViewData.ModelState.IsValid ? "d-none" : "")" role="alert"></div>

                    <div class="mb-3">
                        <label for="file" class="form-label">@T["Licensing.Validate.File"]</label>
                        <input type="file" id="file" name="file" accept=".lic,.xml" class="form-control" />
                    </div>
                    <div class="mb-3">
                        <label for="pasted" class="form-label">@T["Licensing.Validate.OrPaste"]</label>
                        <textarea id="pasted" name="pasted" rows="4" class="form-control font-monospace" placeholder="<License>…"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="asOf" class="form-label">@T["Licensing.Validate.AsOf"] <span class="text-body-secondary">@T["Licensing.Validate.AsOf.Optional"]</span></label>
                        @* ISO, invariant: what a datetime-local input takes whatever the language (#102). *@
                        <input type="datetime-local" id="asOf" name="asOf" class="form-control"
                               value='@Model.AsOf?.ToString("yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture)' />
                        <div class="form-text">@T["Licensing.Validate.AsOf.Help"]</div>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="trustContractTestKey" name="trustContractTestKey" value="true"
                               @(Model.TrustContractTestKey ? "checked" : "") />
                        <label class="form-check-label" for="trustContractTestKey">@T["Licensing.Validate.TrustTestKey"]</label>
                        <div class="form-text">@T["Licensing.Validate.TrustTestKey.Help"]</div>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="ti ti-shield-check me-1"></i> @T["Licensing.Validate.Submit"]
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        @if (report is null)
        {
            <div class="card">
                <div class="card-body text-body">
                    <p>@T["Licensing.Validate.Explainer.Readers"]</p>
                    <p class="mb-0">@T["Licensing.Validate.Explainer.Keys"]</p>
                </div>
            </div>
        }
        else
        {
            var contract = report.Contract;

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-1">@(Model.FileName ?? T["Licensing.Validate.PastedLicence"].Value)</h5>
                    <p class="text-body mb-0">@T["Licensing.Validate.EvaluatedAsOf", Instant(report.EvaluatedAtUtc)]</p>
                </div>
                <div class="card-body">
                    <dl class="row mb-0">
                        <dt class="col-sm-4">@T["Licensing.Validate.Signature"]</dt>
                        <dd class="col-sm-8">
                            <span class="badge @Badge(contract.SignatureValid)">@(contract.SignatureValid ? T["Licensing.Validate.Signature.Valid"] : T["Licensing.Validate.Signature.NotVerified"])</span>
                            @if (report.VerifiedBy is { } key)
                            {
                                <span class="ms-1">@T["Licensing.Validate.Signature.By", T["Licensing.Validate.Key." + (key.IsTestKey ? "ContractTest" : "Product")].Value]</span>
                                @if (key.IsTestKey)
                                {
                                    <span class="badge bg-label-warning ms-1">@T["Licensing.Validate.Signature.TestKey"]</span>
                                }
                            }
                            else if (contract.Loaded)
                            {
                                <span class="ms-1">@T["Licensing.Validate.Signature.NoTrustedKey"]</span>
                            }
                        </dd>

                        <dt class="col-sm-4">@T["Licensing.LicenceId"]</dt>
                        <dd class="col-sm-8"><code>@(Model.LicenseId?.ToString() ?? "-")</code></dd>

                        <dt class="col-sm-4">@T["Licensing.SchemaVersion"]</dt>
                        <dd class="col-sm-8">
                            @(contract.Loaded ? contract.SchemaVersion.ToString() : "-")
                            @if (contract.Loaded && !contract.SchemaSupported)
                            {
                                <span class="badge bg-label-danger ms-1">@T["Licensing.Validate.Unsupported"]</span>
                            }
                        </dd>

... (150 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/_ViewImports.cshtml">
@using KnowledgeFabric.AdminConsole
@using KnowledgeFabric.AdminConsole.Models
@using KnowledgeFabric.AdminConsole.Security
@using KnowledgeFabric.AdminConsole.Gateway
@using KnowledgeFabric.AdminConsole.Licensing.Register
@using KnowledgeFabric.AdminConsole.Licensing.Issuing
@using KnowledgeFabric.AdminConsole.Licensing.Validation
@using KnowledgeFabric.AdminConsole.Areas.Licensing.Controllers
@using LicenseTool
@using Microsoft.AspNetCore.Mvc.Localization
@using KnowledgeFabric.AdminConsole.Localisation
@using KnowledgeFabric.AdminConsole.Resources
@using Microsoft.Extensions.Localization
@inject IHtmlLocalizer<ConsoleResource> T
@inject IStringLocalizer<ConsoleResource> S
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</file>

<file path="src/KnowledgeFabric.AdminConsole/Areas/Licensing/Views/_ViewStart.cshtml">
@{
    Layout = "_ContentNavbarLayout";
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/AuditActionFilter.cs">
public sealed class AuditActionFilter : IAsyncActionFilter
⋮----
private readonly IAuditLog _auditLog;
⋮----
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
⋮----
var recordsItsOwn = context.ActionDescriptor.EndpointMetadata.OfType<SelfAuditedAttribute>().Any();
⋮----
if (SafeMethods.Contains(httpContext.Request.Method) || recordsItsOwn)
⋮----
var area = routeValues.TryGetValue("area", out var a) && !string.IsNullOrEmpty(a) ? a : "console";
var controller = routeValues.TryGetValue("controller", out var c) ? c : null;
var action = routeValues.TryGetValue("action", out var act) ? act : null;
⋮----
var entry = new AuditEntry(
⋮----
Action: $"{area}:{controller}.{action}".ToLowerInvariant(),
⋮----
["status"] = executed.HttpContext.Response.StatusCode.ToString(),
["failed"] = (executed.Exception is not null).ToString()
⋮----
await _auditLog.RecordAsync(entry, httpContext.RequestAborted);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/AuditEntry.cs">

</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/AuditRegistration.cs">
public static class AuditRegistration
⋮----
public static IServiceCollection AddConsoleAudit(
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
else if (environment.IsDevelopment())
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/AuditTrail.cs">
public interface IAuditTrail
⋮----
Task<AuditPage> SearchAsync(AuditQuery query, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<string>> ActionsAsync(string? actor = null, CancellationToken cancellationToken = default);
⋮----
public string? ActionFilter => string.IsNullOrWhiteSpace(Action) ? null : Action.Trim();
⋮----
public string? TargetFilter => string.IsNullOrWhiteSpace(Target) ? null : Target.Trim();
⋮----
public string? ActorFilter => string.IsNullOrWhiteSpace(Actor) ? null : Security.ConsoleRoles.Normalise(Actor);
⋮----
public int PageCount => Math.Max(1, (TotalCount + PageSize - 1) / PageSize);
⋮----
public sealed class StoredAuditEntry
⋮----
public static StoredAuditEntry From(AuditEntry entry) => new()
⋮----
OccurredAt = entry.OccurredAt.ToUniversalTime(),
⋮----
private static string? Clip(string? value, int length) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/DatabaseAuditLog.cs">
public sealed class DatabaseAuditLog(
⋮----
ILogger<DatabaseAuditLog> logger) : IAuditLog
⋮----
public async Task RecordAsync(AuditEntry entry, CancellationToken cancellationToken = default)
⋮----
await lines.RecordAsync(entry, cancellationToken);
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
db.AuditEntries.Add(StoredAuditEntry.From(entry));
await db.SaveChangesAsync(CancellationToken.None);
⋮----
logger.LogError(
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/IAuditLog.cs">
public interface IAuditLog
⋮----
Task RecordAsync(AuditEntry entry, CancellationToken cancellationToken = default);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/InMemoryAuditLog.cs">
public sealed class InMemoryAuditLog(LoggingAuditLog lines) : IAuditLog, IAuditTrail
⋮----
public async Task RecordAsync(AuditEntry entry, CancellationToken cancellationToken = default)
⋮----
await lines.RecordAsync(entry, cancellationToken);
⋮----
var stored = StoredAuditEntry.From(entry);
_entries.Add(new StoredAuditEntry
⋮----
public Task<AuditPage> SearchAsync(AuditQuery query, CancellationToken cancellationToken = default)
⋮----
.Where(entry => query.ActorFilter is not { } actor || Security.ConsoleRoles.Normalise(entry.Actor) == actor)
.Where(entry => query.ActionFilter is not { } action || entry.Action == action)
.Where(entry => query.TargetFilter is not { } target
⋮----
.OrderByDescending(entry => entry.OccurredAt)
.ThenByDescending(entry => entry.Id)
.ToList();
⋮----
var page = matching.Skip((query.Page - 1) * query.PageSize).Take(query.PageSize).ToList();
return Task.FromResult(new AuditPage(page, query.Page, query.PageSize, matching.Count));
⋮----
public Task<IReadOnlyList<string>> ActionsAsync(string? actor = null, CancellationToken cancellationToken = default)
⋮----
var only = string.IsNullOrWhiteSpace(actor) ? null : Security.ConsoleRoles.Normalise(actor);
⋮----
.Where(entry => only is null || Security.ConsoleRoles.Normalise(entry.Actor) == only)
.Select(entry => entry.Action).Distinct().Order(StringComparer.Ordinal).ToList());
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/LoggingAuditLog.cs">
public sealed class LoggingAuditLog : IAuditLog
⋮----
public Task RecordAsync(AuditEntry entry, CancellationToken cancellationToken = default)
⋮----
_logger.LogInformation(
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/PostgresAuditTrail.cs">
public sealed class PostgresAuditTrail(ConsoleDbContext db) : IAuditTrail
⋮----
public async Task<AuditPage> SearchAsync(AuditQuery query, CancellationToken cancellationToken = default)
⋮----
entries = entries.Where(entry => entry.Action == action);
⋮----
var pattern = "%" + target.Replace(@"\", @"\\").Replace("%", @"\%").Replace("_", @"\_") + "%";
entries = entries.Where(entry => EF.Functions.ILike(entry.Target ?? "", pattern, @"\"));
⋮----
var total = await entries.CountAsync(cancellationToken);
⋮----
.OrderByDescending(entry => entry.OccurredAt)
.ThenByDescending(entry => entry.Id)
.Skip((query.Page - 1) * query.PageSize)
.Take(query.PageSize)
.ToListAsync(cancellationToken);
⋮----
return new AuditPage(page, query.Page, query.PageSize, total);
⋮----
public async Task<IReadOnlyList<string>> ActionsAsync(string? actor = null, CancellationToken cancellationToken = default) =>
await Of(string.IsNullOrWhiteSpace(actor) ? null : Security.ConsoleRoles.Normalise(actor))
.Select(entry => entry.Action)
.Distinct()
.OrderBy(action => action)
⋮----
private IQueryable<StoredAuditEntry> Of(string? actor)
⋮----
var entries = db.AuditEntries.AsNoTracking();
return actor is null ? entries : entries.Where(entry => entry.Actor.Trim().ToLower() == actor);
⋮----
public sealed class LogsOnlyAuditTrail : IAuditTrail
⋮----
public Task<AuditPage> SearchAsync(AuditQuery query, CancellationToken cancellationToken = default) =>
Task.FromResult(new AuditPage([], query.Page, query.PageSize, 0));
⋮----
public Task<IReadOnlyList<string>> ActionsAsync(string? actor = null, CancellationToken cancellationToken = default) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Auditing/SelfAuditedAttribute.cs">

</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/AvailabilityPattern.cs">
public sealed class PatternSpan
⋮----
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(HostName) || HostName != ConsoleRoles.Normalise(HostName) || ConsoleRoles.IsAdmin(HostName))
⋮----
problems.Add("host_name");
⋮----
if (!Weekdays.IsWeekday(Weekday))
⋮----
problems.Add("weekday");
⋮----
if (Times.Problem() is not null)
⋮----
problems.Add("times");
⋮----
public static void EnsureValidSet(string hostName, int weekday, IReadOnlyList<SpanTimes> spans)
⋮----
throw new ArgumentException($"A weekday holds at most {MaxPerDay} spans.", nameof(spans));
⋮----
if (SpanTimes.Overlapping(spans).Count > 0)
⋮----
throw new ArgumentException("Two spans of one weekday overlap.", nameof(spans));
⋮----
var span = new PatternSpan { HostName = hostName, Weekday = weekday, Starts = times.Starts, Ends = times.Ends };
if (span.Problems() is { Count: > 0 } problems)
⋮----
throw new ArgumentException($"A span cannot be stored with {string.Join(", ", problems)} as given.", nameof(spans));
⋮----
public static (IReadOnlyList<PatternSpan> Kept, IReadOnlyList<PatternSpan> Removed, IReadOnlyList<SpanTimes> Added) Diff(
⋮----
var kept = current.Where(row => spans.Contains(row.Times)).ToList();
var removed = current.Where(row => !spans.Contains(row.Times)).ToList();
var added = spans.Where(times => !current.Any(row => row.Times == times)).Distinct().ToList();
⋮----
public PatternSpan Copy() => new()
⋮----
public sealed class DayOff
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException("A day off needs a host, and admin is never one.");
⋮----
public DayOff Copy() => new() { HostName = HostName, Day = Day, CreatedBy = CreatedBy, CreatedAt = CreatedAt };
⋮----
public bool Overlaps(SpanTimes other) => Starts < other.Ends && other.Starts < Ends;
⋮----
public WindowProblem? Problem()
⋮----
public string Invariant() =>
$"{Starts.ToString("HH:mm", CultureInfo.InvariantCulture)}-{Ends.ToString("HH:mm", CultureInfo.InvariantCulture)}";
⋮----
public int CompareTo(SpanTimes other) =>
Starts != other.Starts ? Starts.CompareTo(other.Starts) : Ends.CompareTo(other.Ends);
⋮----
/// <summary>A weekday's spans as <see cref="Invariant"/> writes each, by start, comma-separated; empty for none.</summary>
public static string Invariant(IEnumerable<SpanTimes> spans) => string.Join(",", spans.Order().Select(span => span.Invariant()));
⋮----
public static IReadOnlyList<SpanTimes>? Read(string? value)
⋮----
if (string.IsNullOrWhiteSpace(value))
⋮----
foreach (var part in value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
⋮----
var times = part.Split('-');
⋮----
|| !TimeOnly.TryParseExact(times[0], "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out var starts)
|| !TimeOnly.TryParseExact(times[1], "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out var ends))
⋮----
spans.Add(new SpanTimes(starts, ends));
⋮----
return spans.Order().ToList();
⋮----
public static IReadOnlyList<(int Index, SpanTimes Other)> Overlapping(IReadOnlyList<SpanTimes> spans)
⋮----
if (spans[i].Overlaps(spans[j]))
⋮----
found.Add((i, spans[j]));
⋮----
private static bool OnStep(TimeOnly time) =>
⋮----
public static class Weekdays
⋮----
public static bool IsWeekday(int weekday) => weekday is >= 0 and < Count;
⋮----
public static int Of(DateOnly day) => ((int)day.DayOfWeek + 6) % 7;
⋮----
public static DayOfWeek DayOfWeek(int weekday) => (System.DayOfWeek)((weekday + 1) % 7);
⋮----
public static string Invariant(int weekday) => DayOfWeek(weekday).ToString();
⋮----
public static class PatternWindows
⋮----
public static IReadOnlyList<AvailabilityWindow> Instances(
⋮----
var bySpan = spans.ToList();
⋮----
var zone = WindowTimes.Find(host.TimeZone) ?? TimeZoneInfo.Utc;
var horizon = now.AddDays(host.HorizonDays);
var off = daysOff.ToHashSet();
... (59 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/AvailabilityWindow.cs">
public sealed class AvailabilityWindow
⋮----
public static readonly TimeSpan MaxLength = TimeSpan.FromHours(14);
⋮----
public bool Overlaps(DateTimeOffset start, DateTimeOffset end) => StartsAt < end && start < EndsAt;
⋮----
public bool HasEnded(DateTimeOffset now) => EndsAt <= now;
⋮----
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(HostName) || HostName != ConsoleRoles.Normalise(HostName) || ConsoleRoles.IsAdmin(HostName))
⋮----
problems.Add("host_name");
⋮----
problems.Add("utc");
⋮----
problems.Add("length");
⋮----
problems.Add("step");
⋮----
if (string.IsNullOrWhiteSpace(TimeZone) || TimeZone.Length > BookingHost.TimeZoneLength)
⋮----
problems.Add("time_zone");
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A window cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public (DateTime Start, DateTime End) LocalTimes(TimeZoneInfo fallback)
⋮----
var zone = WindowTimes.Find(TimeZone) ?? fallback;
return (TimeZoneInfo.ConvertTime(StartsAt, zone).DateTime, TimeZoneInfo.ConvertTime(EndsAt, zone).DateTime);
⋮----
public AvailabilityWindow Copy() => new()
⋮----
private static bool OnStep(DateTimeOffset instant) =>
⋮----
public static class WindowTimes
⋮----
public static TimeZoneInfo? Find(string? iana)
⋮----
if (string.IsNullOrWhiteSpace(iana))
⋮----
return TimeZoneInfo.FindSystemTimeZoneById(iana);
⋮----
public static WindowPlacement Place(DateOnly day, TimeOnly start, TimeOnly end, TimeZoneInfo zone)
⋮----
return WindowPlacement.Refused(WindowProblem.NotOnStep);
⋮----
return WindowPlacement.Refused(WindowProblem.TooLong);
⋮----
public static WindowPlacement Instants(DateOnly day, TimeOnly start, TimeOnly end, TimeZoneInfo zone)
⋮----
return WindowPlacement.Refused(WindowProblem.EndNotAfterStart);
⋮----
var first = ToUtc(day.ToDateTime(start), zone, earliest: true);
⋮----
return WindowPlacement.Refused(WindowProblem.StartSkipped);
⋮----
var last = ToUtc(day.ToDateTime(end), zone, earliest: false);
⋮----
return WindowPlacement.Refused(WindowProblem.EndSkipped);
⋮----
return new WindowPlacement(first, last, null);
⋮----
public static DateOnly MondayOf(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7));
⋮----
public static DateOnly DayIn(DateTimeOffset instant, TimeZoneInfo zone) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(instant, zone).DateTime);
⋮----
public static DateTimeOffset StartOfDay(DateOnly day, TimeZoneInfo zone)
⋮----
if (ToUtc(day.ToDateTime(TimeOnly.MinValue).AddMinutes(minutes), zone, earliest: true) is { } instant)
⋮----
return new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
⋮----
private static bool OnStep(TimeOnly time) =>
⋮----
private static DateTimeOffset? ToUtc(DateTime local, TimeZoneInfo zone, bool earliest)
⋮----
local = DateTime.SpecifyKind(local, DateTimeKind.Unspecified);
⋮----
if (zone.IsInvalidTime(local))
⋮----
var offset = zone.IsAmbiguousTime(local)
? (earliest ? zone.GetAmbiguousTimeOffsets(local).Max() : zone.GetAmbiguousTimeOffsets(local).Min())
: zone.GetUtcOffset(local);
⋮----
return new DateTimeOffset(local, offset).ToUniversalTime();
⋮----
public static WindowPlacement Refused(WindowProblem problem) => new(null, null, problem);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookedHost.cs">
public sealed class BookedHost
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingHost.cs">
public sealed partial class BookingHost
⋮----
public static class Fields
⋮----
public static bool IsSlug(string? slug) =>
slug is { Length: >= SlugMinLength and <= SlugLength } && SlugPattern().IsMatch(slug) && !IsReservedSlug(slug);
⋮----
public static bool IsReservedSlug(string? slug) => slug is not null && ReservedSlugs.Contains(slug);
⋮----
public static bool IsDuration(int minutes) => minutes is >= MinDuration and <= MaxDuration && minutes % MinuteStep == 0;
⋮----
public static bool IsStep(int minutes) => minutes is >= MinStep and <= MaxStep && minutes % MinuteStep == 0;
⋮----
public static bool IsNotice(int hours) => hours is >= MinNotice and <= MaxNotice;
⋮----
public static bool IsHorizon(int days) => days is >= MinHorizon and <= MaxHorizon;
⋮----
public static bool IsBuffer(int minutes) => minutes is >= MinBuffer and <= MaxBuffer;
⋮----
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(Name) || Name.Length > NameLength || Name != ConsoleRoles.Normalise(Name) || ConsoleRoles.IsAdmin(Name))
⋮----
problems.Add("name");
⋮----
if (string.IsNullOrWhiteSpace(DisplayName) || DisplayName.Length > DisplayNameLength)
⋮----
problems.Add(Fields.DisplayName);
⋮----
if (string.IsNullOrWhiteSpace(Email) || Email.Length > EmailLength)
⋮----
problems.Add(Fields.Email);
⋮----
if (string.IsNullOrWhiteSpace(TimeZone) || TimeZone.Length > TimeZoneLength)
⋮----
problems.Add(Fields.TimeZone);
⋮----
problems.Add(Fields.Slug);
⋮----
problems.Add(Fields.Duration);
⋮----
problems.Add(Fields.Step);
⋮----
problems.Add(Fields.Notice);
⋮----
problems.Add(Fields.Horizon);
⋮----
problems.Add(Fields.Buffer);
⋮----
problems.Add(Fields.Location);
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A host cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public static IReadOnlyList<string> Differences(BookingHost before, BookingHost after)
⋮----
if (!EqualityComparer<T>.Default.Equals(left, right))
⋮----
changed.Add(field);
⋮----
public void CopySettingsTo(BookingHost target)
⋮----
public BookingHost Copy()
⋮----
var copy = new BookingHost
⋮----
private static partial Regex SlugPattern();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingInvitations.cs">
public sealed class BookingInvitations(
⋮----
public static string TitleFor(IReadOnlyList<BookingHost> hosts) => $"KnowledgeFabric: call with {Names(hosts)}";
⋮----
public static string HostsDetail(BookingRecord booking) => string.Join(",", booking.Hosts);
⋮----
public static string? LinkDetail(BookingRecord booking) => booking.LinkId?.ToString("D", CultureInfo.InvariantCulture);
⋮----
public static string DescriptionFor(BookingRecord booking, IReadOnlyList<BookingHost> hosts, string? cancelLink = null, string? linkTitle = null)
⋮----
var text = new StringBuilder()
.AppendLine("Booked from KnowledgeFabric's booking page.")
.AppendLine();
⋮----
if (!string.IsNullOrWhiteSpace(linkTitle))
⋮----
text.Append("Booking link: ").AppendLine(linkTitle);
⋮----
text.Append("Hosts: ").AppendLine(string.Join(", ", hosts.Select(host => host.DisplayName.Trim())));
⋮----
text.Append("Guest: ").AppendLine(booking.GuestName);
⋮----
if (!string.IsNullOrWhiteSpace(booking.GuestOrganisation))
⋮----
text.Append("Organisation: ").AppendLine(booking.GuestOrganisation);
⋮----
text.Append("Guest's time zone: ").AppendLine(booking.GuestTimeZone);
⋮----
if (!string.IsNullOrWhiteSpace(booking.GuestNote))
⋮----
text.AppendLine().AppendLine("To discuss:").AppendLine(booking.GuestNote);
⋮----
text.AppendLine().Append("Booking: ").Append(booking.Id.ToString("D", CultureInfo.InvariantCulture));
⋮----
if (!string.IsNullOrWhiteSpace(cancelLink))
⋮----
text.AppendLine().AppendLine().Append("Need to change it? Cancel this booking and choose another time: ").Append(cancelLink);
⋮----
return text.ToString().Replace("\r\n", "\n", StringComparison.Ordinal);
⋮----
public static string? LocationFor(BookingHost host)
⋮----
if (string.IsNullOrWhiteSpace(host.Location))
⋮----
var location = host.Location.Trim();
return location.Length <= ZohoWire.MaxLocation ? location : location[..(ZohoWire.MaxLocation - 1)].TrimEnd() + "…";
⋮----
public static ZohoEventRequest EventFor(BookingRecord booking, BookingHost host, string? cancelLink = null) =>
⋮----
public static ZohoEventRequest EventFor(BookingRecord booking, IReadOnlyList<BookingHost> hosts, string? cancelLink = null, string? linkTitle = null) => new(
Title: string.IsNullOrWhiteSpace(linkTitle) ? TitleFor(hosts) : linkTitle,
⋮----
Attendees: [.. hosts.Select(host => host.Email.Trim()), booking.GuestEmail.Trim()],
⋮----
Reminders: [new ZohoReminder(ZohoReminder.Popup, ReminderMinutes)]);
⋮----
private static string Names(IReadOnlyList<BookingHost> hosts)
⋮----
var names = hosts.Select(host => host.DisplayName.Trim()).ToList();
⋮----
? string.Concat(names)
: $"{string.Join(", ", names.Take(names.Count - 1))} and {names[^1]}";
⋮----
public Task<InvitationSend> SendAsync(BookingRecord booking, BookingHost host, BookingAuditor by, bool resend, string? cancelToken = null) =>
⋮----
public async Task<InvitationSend> SendAsync(BookingRecord booking, IReadOnlyList<BookingHost> hosts, BookingAuditor by, bool resend, string? cancelToken = null)
⋮----
(cancelToken, newHash) = GuestLink.New();
⋮----
var link = cancelToken is null ? null : GuestLink.LinkFor(options.Value.PublicBaseUrl, cancelToken);
var created = await zoho.CreateEventAsync(EventFor(booking, hosts, link, await LinkTitleAsync(booking)), CancellationToken.None);
⋮----
["outcome"] = created.Outcome.ToString(),
⋮----
return InvitationSend.Failed(booking, created.Outcome, created.Code);
⋮----
BookingChange recorded;
⋮----
recorded = await store.RecordInvitationAsync(booking.Id, made.Uid, made.Etag, newHash, CancellationToken.None);
⋮----
logger.LogError(ex, "Zoho created the event {Uid} for the booking {Id}, which could not be recorded; deleting the event.", made.Uid, booking.Id);
⋮----
return InvitationSend.Failed(booking, ZohoOutcome.Ok, "unrecorded");
⋮----
logger.LogWarning(
⋮----
return InvitationSend.Moved(recorded.Booking);
⋮----
return InvitationSend.Sent(recorded.Booking!);
⋮----
private Task TellBookedAsync(BookingRecord booking, bool invited, bool resend) =>
resend ? Task.CompletedTask : notifications.BookedAsync(booking, invited);
⋮----
public async Task<BookingCancel> CancelAsync(Guid id, uint version, string reason, BookingAuditor by)
⋮----
var change = await store.CancelBookingAsync(id, version, by.Actor, clock.GetUtcNow(), reason, CancellationToken.None);
⋮----
return new BookingCancel(change, null, null);
⋮----
await notifications.CancelledByHostAsync(booking, by.Actor);
... (48 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingLink.cs">
public sealed class BookingLink
⋮----
get => _hosts.Count > 0 ? _hosts : string.IsNullOrEmpty(HostName) ? [] : [HostName];
⋮----
public static class Fields
⋮----
public bool IsExpired(DateTimeOffset now) => ExpiresAt is { } expires && expires <= now;
⋮----
public BookingLinkState StateAt(DateTimeOffset now) =>
⋮----
public bool Holds(string name) => Hosts.Contains(ConsoleRoles.Normalise(name), StringComparer.Ordinal);
⋮----
public bool IsMadeBy(string name) => HostName == ConsoleRoles.Normalise(name);
⋮----
public IReadOnlyList<BookingLinkHost> HostRows() =>
Hosts.Select((host, position) => new BookingLinkHost { LinkId = Id, HostName = host, Position = position }).ToList();
⋮----
public static string NewToken() =>
Convert.ToBase64String(RandomNumberGenerator.GetBytes(TokenBytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
⋮----
public static bool IsWellFormed(string? token) =>
token is { Length: TokenLength } && token.All(c => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-' or '_');
⋮----
public static string LinkFor(string publicBaseUrl, string token) => $"{publicBaseUrl.TrimEnd('/')}{PathPrefix}{token}";
⋮----
public static string Redact(string path) =>
path.StartsWith(PathPrefix, StringComparison.OrdinalIgnoreCase) && path.Length > PathPrefix.Length ? RedactedPath : path;
⋮----
public static DateOnly DefaultExpiryDay(DateOnly today) => today.AddMonths(1);
⋮----
public static DateTimeOffset ExpiresAtFor(DateOnly day, TimeZoneInfo zone) => WindowTimes.StartOfDay(day.AddDays(1), zone);
⋮----
public static DateOnly ExpiryDayOf(DateTimeOffset expiresAt, TimeZoneInfo zone) => WindowTimes.DayIn(expiresAt.AddTicks(-1), zone);
⋮----
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(HostName) || HostName != ConsoleRoles.Normalise(HostName) || ConsoleRoles.IsAdmin(HostName))
⋮----
problems.Add("host_name");
⋮----
|| hosts.Distinct(StringComparer.Ordinal).Count() != hosts.Count
|| hosts.Any(host => string.IsNullOrWhiteSpace(host) || host != ConsoleRoles.Normalise(host) || ConsoleRoles.IsAdmin(host)
⋮----
problems.Add("hosts");
⋮----
if (string.IsNullOrWhiteSpace(Title) || Title != Title.Trim() || Title.Length > TitleLength)
⋮----
problems.Add("title");
⋮----
problems.Add("token");
⋮----
problems.Add("expires_at");
⋮----
if (string.IsNullOrWhiteSpace(CreatedBy) || CreatedBy.Length > BookingHost.NameLength)
⋮----
problems.Add("created_by");
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A booking link cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public static void EnsureEditable(string title, DateTimeOffset? expiresAt)
⋮----
if (string.IsNullOrWhiteSpace(title) || title != title.Trim() || title.Length > TitleLength)
⋮----
throw new ArgumentException($"A booking link's title is 1 to {TitleLength} characters, trimmed.", nameof(title));
⋮----
throw new ArgumentException("A booking link's expiry is stored in UTC.", nameof(expiresAt));
⋮----
public static IReadOnlyList<string> Differences(BookingLink before, string title, DateTimeOffset? expiresAt)
⋮----
if (!string.Equals(before.Title, title, StringComparison.Ordinal))
⋮----
changed.Add(Fields.Title);
⋮----
changed.Add(Fields.Expires);
⋮----
public BookingLink Copy() => new()
⋮----
Hosts = _hosts.ToList(),
⋮----
public sealed class BookingLinkHost
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingNotifications.cs">
public sealed class BookingNotifications(Notifier notifier, ConsolePeople people, ILogger<BookingNotifications> logger)
⋮----
public Task BookedAsync(BookingRecord booking, bool invited) => NotifyAsync(booking, invited ? New : NotInvited, except: null);
⋮----
public Task CancelledByGuestAsync(BookingRecord booking) => NotifyAsync(booking, GuestCancelled, except: null);
⋮----
public Task CancelledByHostAsync(BookingRecord booking, string by) => NotifyAsync(booking, HostCancelled, except: by);
⋮----
private async Task NotifyAsync(BookingRecord booking, string kind, string? except)
⋮----
var served = (await people.BookingAsync(CancellationToken.None)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
var skipped = except is null ? null : ConsoleRoles.Normalise(except);
var recipients = booking.Hosts.Where(host => served.Contains(host) && host != skipped).ToList();
⋮----
await notifier.NotifyAsync(recipients, kind, booking.Id);
⋮----
logger.LogError(ex, "The hosts of the booking {Id} could not be told of it ({Kind}).", booking.Id, kind);
⋮----
public sealed class BookingNotificationContent(IBookingStore store, ConsolePeople people, IStringLocalizer<ConsoleResource> text) : INotificationContent
⋮----
public bool Renders(string kind) => BookingNotifications.Kinds.Contains(kind, StringComparer.Ordinal);
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default)
⋮----
var booking = await store.FindBookingAsync(id, cancellationToken);
if (booking is null || !booking.Holds(notification.Recipient))
⋮----
_served ??= (await people.BookingAsync(cancellationToken)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
if (!_served.Contains(notification.Recipient))
⋮----
var recipient = await store.FindHostAsync(notification.Recipient, cancellationToken);
var zone = WindowTimes.Find(recipient?.TimeZone) ?? WindowTimes.Find(booking.HostTimeZone) ?? TimeZoneInfo.Utc;
var start = TimeZoneInfo.ConvertTime(booking.StartsAt, zone);
var when = $"{start.ToString("ddd d MMM yyyy", CultureInfo.CurrentCulture)}, {start.ToString("HH:mm", CultureInfo.InvariantCulture)}";
var guest = string.IsNullOrWhiteSpace(booking.GuestOrganisation)
⋮----
return new NotificationContent(title, body, $"Booking/Bookings/{booking.Id:D}");
⋮----
private async Task<string> CancellerAsync(BookingRecord booking, CancellationToken cancellationToken)
⋮----
if (string.IsNullOrWhiteSpace(booking.CancelledBy))
⋮----
var host = await store.FindHostAsync(ConsoleRoles.Normalise(booking.CancelledBy), cancellationToken);
return host is { DisplayName.Length: > 0 } ? host.DisplayName.Trim() : booking.CancelledBy;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingRecord.cs">
public sealed class BookingRecord
⋮----
get => _hosts.Count > 0 ? _hosts : string.IsNullOrEmpty(HostName) ? [] : [HostName];
⋮----
public bool Holds(string name) => Hosts.Contains(ConsoleRoles.Normalise(name), StringComparer.Ordinal);
⋮----
public IReadOnlyList<string> HostsBut(string name)
⋮----
var key = ConsoleRoles.Normalise(name);
return Hosts.Where(host => host != key).ToList();
⋮----
public IReadOnlyList<BookedHost> HostRows() =>
Hosts.Select((host, position) => new BookedHost
⋮----
}).ToList();
⋮----
public bool HasEvent => !string.IsNullOrWhiteSpace(ZohoEventUid) && !string.IsNullOrWhiteSpace(ZohoEtag);
⋮----
public static void EnsureCancellable(string by, string reason)
⋮----
if (string.IsNullOrWhiteSpace(by) || by.Length > BookingHost.NameLength)
⋮----
throw new ArgumentException("A booking cannot be cancelled without who cancelled it.", nameof(by));
⋮----
if (string.IsNullOrWhiteSpace(reason) || reason.Length > CancelReasonLength)
⋮----
throw new ArgumentException($"A booking's cancel needs a reason of 1 to {CancelReasonLength} characters.", nameof(reason));
⋮----
public void CancelByHost(string by, DateTimeOffset at, string reason)
⋮----
public void CancelByGuest(DateTimeOffset at)
⋮----
public bool GuestMayCancel(DateTimeOffset now) => IsLive && StartsAt > now;
⋮----
public BusyInterval AsBusy() => new(StartsAt, EndsAt);
⋮----
public static string EmailKey(string email) => email.Trim().ToLowerInvariant();
⋮----
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(HostName) || HostName != ConsoleRoles.Normalise(HostName) || ConsoleRoles.IsAdmin(HostName))
⋮----
problems.Add("host_name");
⋮----
|| hosts.Distinct(StringComparer.Ordinal).Count() != hosts.Count
|| hosts.Any(host => string.IsNullOrWhiteSpace(host) || host != ConsoleRoles.Normalise(host) || ConsoleRoles.IsAdmin(host)
⋮----
problems.Add("hosts");
⋮----
problems.Add("utc");
⋮----
problems.Add("length");
⋮----
if (string.IsNullOrWhiteSpace(HostTimeZone) || HostTimeZone.Length > BookingHost.TimeZoneLength)
⋮----
problems.Add("host_time_zone");
⋮----
if (string.IsNullOrWhiteSpace(GuestTimeZone) || GuestTimeZone.Length > BookingHost.TimeZoneLength)
⋮----
problems.Add("guest_time_zone");
⋮----
if (string.IsNullOrWhiteSpace(GuestName) || GuestName.Length > GuestNameLength)
⋮----
problems.Add("guest_name");
⋮----
if (string.IsNullOrWhiteSpace(GuestEmail) || GuestEmail.Length > GuestEmailLength)
⋮----
problems.Add("guest_email");
⋮----
problems.Add("guest_organisation");
⋮----
problems.Add("guest_note");
⋮----
if (string.IsNullOrWhiteSpace(GuestCulture) || GuestCulture.Length > CultureLength)
⋮----
problems.Add("guest_culture");
⋮----
problems.Add("cancel_token_hash");
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A booking cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public static string Instant(DateTimeOffset instant) =>
instant.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm'Z'", CultureInfo.InvariantCulture);
⋮----
public BookingRecord Copy() => new()
⋮----
Hosts = _hosts.ToList(),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingRegistration.cs">
public sealed class BookingOptions
⋮----
public string LinkFor(string slug) => $"{PublicBaseUrl.TrimEnd('/')}/book/{slug}";
⋮----
public string TeamLink => $"{PublicBaseUrl.TrimEnd('/')}/book";
⋮----
public static class BookingRegistration
⋮----
public static IServiceCollection AddBookings(
⋮----
services.Configure<BookingOptions>(configuration.GetSection(BookingOptions.SectionName));
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
else if (environment.IsDevelopment())
⋮----
public static void RedactGuestLink(Activity activity)
⋮----
if (activity.GetTagItem(UrlPathTag) is string path && BookingLink.Redact(GuestLink.Redact(path)) is var redacted && !ReferenceEquals(redacted, path))
⋮----
activity.SetTag(UrlPathTag, redacted);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/BookingWeek.cs">
public int Total => Bookings ?? PerHost.Sum(host => host.Count);
⋮----
public DateOnly Sunday => Monday.AddDays(6);
⋮----
public static DateTimeOffset WeekStart(DateTimeOffset now)
⋮----
return new DateTimeOffset(day.AddDays(-sinceMonday), TimeSpan.Zero);
⋮----
public static BookingWeek Compute(
⋮----
var end = start.AddDays(7);
⋮----
.Where(booking => booking.IsLive && booking.StartsAt >= start && booking.StartsAt < end)
.ToList();
⋮----
.SelectMany(booking => booking.Hosts)
.GroupBy(host => host, StringComparer.Ordinal)
.Select(group => new HostCount(group.Key, group.Count()))
.OrderByDescending(host => host.Count)
.ThenBy(host => host.Host, StringComparer.Ordinal)
⋮----
var key = ConsoleRoles.Normalise(self);
⋮----
? ahead.Where(booking => booking.IsLive && booking.Holds(key) && booking.EndsAt > now).MinBy(booking => booking.StartsAt)
⋮----
return new BookingWeek(DateOnly.FromDateTime(start.UtcDateTime), perHost, next, live.Count);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/CalendarBusyTime.cs">
public sealed class CalendarBusyTime(
⋮----
public static readonly TimeSpan Fresh = TimeSpan.FromMinutes(5);
⋮----
public static readonly TimeSpan Grace = TimeSpan.FromHours(6);
⋮----
public static readonly TimeSpan Behind = TimeSpan.FromDays(7);
⋮----
public async Task<HostCalendars> ForHostAsync(BookingHost host, IReadOnlyList<CalendarFeed> feeds, bool read = true, CancellationToken cancellationToken = default)
⋮----
? await Task.WhenAll(feeds.Select(feed => StateAsync(host, feed, cancellationToken)))
: feeds.Select(feed => StateOf(feed, _entries.GetValueOrDefault(feed.Id))).ToArray();
⋮----
return new HostCalendars(states, read);
⋮----
public async Task<FeedRead> ReadAsync(Uri address, BookingHost host, CancellationToken cancellationToken = default)
⋮----
var now = clock.GetUtcNow();
⋮----
FeedFetch fetched;
using (var scope = scopes.CreateScope())
⋮----
fetched = await scope.ServiceProvider.GetRequiredService<ICalendarFeedFetcher>().FetchAsync(address, cancellationToken);
⋮----
return new FeedRead(fetched.Outcome, now, from, to, [], 0);
⋮----
var parsed = CalendarFeedParser.Parse(fetched.Text!, ZoneOf(host), from, to);
⋮----
? new FeedRead(FeedOutcome.Read, now, from, to, parsed.Busy, parsed.Skipped)
: new FeedRead(FeedOutcome.NotCalendar, now, from, to, [], 0);
⋮----
public void Remember(Guid feedId, BookingHost host, FeedRead read)
⋮----
_entries[feedId] = Entry.After(null, read, host);
⋮----
public void Forget(IEnumerable<Guid> feedIds)
⋮----
_entries.TryRemove(id, out _);
⋮----
public static int CountWithinHorizon(FeedRead read, BookingHost host) =>
read.Busy.Count(b => b.End > read.At && b.Start < read.At.AddDays(host.HorizonDays));
⋮----
private async Task<FeedState> StateAsync(BookingHost host, CalendarFeed feed, CancellationToken cancellationToken)
⋮----
if (_entries.TryGetValue(feed.Id, out var entry) && entry.Serves(host, now))
⋮----
var gate = _locks.GetOrAdd(feed.Id, _ => new SemaphoreSlim(1, 1));
await gate.WaitAsync(cancellationToken);
⋮----
now = clock.GetUtcNow();
if (_entries.TryGetValue(feed.Id, out entry) && entry.Serves(host, now))
⋮----
entry = Entry.After(entry, read, host);
⋮----
gate.Release();
⋮----
private async Task<FeedRead> ReadStoredAsync(CalendarFeed feed, BookingHost host, CancellationToken cancellationToken)
⋮----
if (protector.Unprotect(feed.UrlProtected) is not { } address)
⋮----
logger.LogWarning("The calendar feed {Feed} of the host {Host} cannot be decrypted; it hides nothing until it is added again.", feed.Id, feed.HostName);
⋮----
return new FeedRead(FeedOutcome.Unprotectable, now, from, to, [], 0);
⋮----
logger.LogInformation("The calendar feed {Feed} was read with {Skipped} events whose times could not be read.", feed.Id, read.Skipped);
⋮----
logger.LogInformation("The calendar feed {Feed} of the host {Host} could not be read: {Outcome}.", feed.Id, feed.HostName, read.Outcome);
⋮----
private async Task RecordAsync(CalendarFeed feed, FeedRead read, BookingHost host)
⋮----
using var scope = scopes.CreateScope();
⋮----
await store.RecordFeedReadAsync(
⋮----
logger.LogError(ex, "How reading the calendar feed {Feed} went could not be recorded.", feed.Id);
⋮----
private FeedState StateOf(CalendarFeed feed, Entry? entry)
⋮----
return new FeedState(
⋮----
private static (DateTimeOffset From, DateTimeOffset To) RangeOf(BookingHost host, DateTimeOffset now) =>
(now - Behind, now.AddDays(host.HorizonDays + 1).AddMinutes(BookingHost.MaxBuffer));
⋮----
private static TimeZoneInfo ZoneOf(BookingHost host) => WindowTimes.Find(host.TimeZone) ?? TimeZoneInfo.Utc;
⋮----
public static Entry After(Entry? before, FeedRead read, BookingHost host) =>
⋮----
? new Entry(read.At, read.Outcome, new Good(read.At, read.To, host.TimeZone, read.Busy))
: new Entry(read.At, read.Outcome, read.Outcome == FeedOutcome.Unprotectable ? null : before?.Good);
⋮----
public bool Serves(BookingHost host, DateTimeOffset now) =>
⋮----
&& (Good is null || (Good.TimeZone == host.TimeZone && Good.To >= RangeOf(host, now).To.AddMinutes(-Fresh.TotalMinutes)));
⋮----
public static readonly HostCalendars None = new([], true);
⋮----
public IReadOnlyList<BusyInterval> Busy { get; } = Feeds.SelectMany(feed => feed.Busy).OrderBy(b => b.Start).ToList();
⋮----
public IEnumerable<FeedState> NotHiding => Feeds.Where(feed => !feed.Hiding);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/CalendarFeed.cs">
public sealed class CalendarFeed
⋮----
public CalendarFeed Copy() => new()
⋮----
public static bool SameLabel(string a, string b) => string.Equals(a.Trim(), b.Trim(), StringComparison.OrdinalIgnoreCase);
⋮----
public void EnsureValid()
⋮----
if (string.IsNullOrWhiteSpace(HostName) || HostName != ConsoleRoles.Normalise(HostName) || ConsoleRoles.IsAdmin(HostName))
⋮----
throw new ArgumentException("A calendar feed needs a host, and admin is never one.");
⋮----
if (string.IsNullOrWhiteSpace(Label) || Label.Length > LabelLength || Label != Label.Trim())
⋮----
throw new ArgumentException($"A calendar feed needs a label of at most {LabelLength} characters, trimmed.");
⋮----
if (string.IsNullOrEmpty(UrlProtected) || string.IsNullOrEmpty(UrlHint) || UrlHint.Length > HintLength)
⋮----
throw new ArgumentException("A calendar feed needs its protected address and a hint.");
⋮----
public static class CalendarFeedAddress
⋮----
public static (Uri? Address, FeedAddressProblem? Problem) Read(string? typed)
⋮----
if (text.StartsWith(scheme, StringComparison.OrdinalIgnoreCase))
⋮----
if (!Uri.TryCreate(text, UriKind.Absolute, out var address) || address.IdnHost.Length == 0)
⋮----
public static string Hint(Uri address)
⋮----
var segments = address.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
⋮----
0 => address.Query.TrimStart('?'),
> 1 when segments[^1].EndsWith(".ics", StringComparison.OrdinalIgnoreCase) => segments[^2],
⋮----
public sealed class CalendarFeedProtector(IDataProtectionProvider provider)
⋮----
private readonly IDataProtector _protector = provider.CreateProtector(Purpose);
⋮----
public string Protect(Uri address) => _protector.Protect(address.AbsoluteUri);
⋮----
public Uri? Unprotect(string payload)
⋮----
return Uri.TryCreate(_protector.Unprotect(payload), UriKind.Absolute, out var address) ? address : null;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/CalendarFeedParser.cs">
public static class CalendarFeedParser
⋮----
public static readonly TimeSpan Lookback = TimeSpan.FromDays(31);
⋮----
TimeZoneResolvers.TimeZoneResolver = id => Current.Value is { } context ? context.Resolve(id, known) : known(id);
⋮----
public static CalendarFeedParse Parse(string text, TimeZoneInfo hostZone, DateTimeOffset from, DateTimeOffset to)
⋮----
calendar = IcalCalendar.Load(text.TrimStart('\uFEFF'));
⋮----
Current.Value = new ParseContext(calendar, hostZone, from, to);
⋮----
foreach (var series in calendar.Events.GroupBy(e => e.Uid ?? Guid.NewGuid().ToString()))
⋮----
skipped += Expand(series.ToList(), hostZone, from, to, busy);
⋮----
busy.AddRange(FreeBusyPeriods(text, from, to));
⋮----
return new CalendarFeedParse(
⋮----
busy.Where(b => b.End > b.Start && b.Start < to && from < b.End).OrderBy(b => b.Start).ThenBy(b => b.End).ToList(),
⋮----
private static int Expand(IReadOnlyList<CalendarEvent> series, TimeZoneInfo hostZone, DateTimeOffset from, DateTimeOffset to, List<BusyInterval> busy)
⋮----
var start = new CalDateTime(from.UtcDateTime - Lookback, CalDateTime.UtcTzId);
var end = new CalDateTime(to.UtcDateTime, CalDateTime.UtcTzId);
var options = new EvaluationOptions { MaxUnmatchedIncrementsLimit = MaxUnmatchedIncrements };
⋮----
foreach (var instance in series.Where(e => e.RecurrenceIdentifier is not null))
⋮----
replaced.Add(InstantOf(instance.RecurrenceIdentifier!.StartTime, hostZone, earliest: true));
⋮----
foreach (var occurrence in e.GetOccurrences(start, options).TakeWhileBefore(end))
⋮----
if (!isInstance && replaced.Contains(InstantOf(period.StartTime, hostZone, earliest: true)))
⋮----
busy.Add(interval);
⋮----
internal static bool IsBusy(CalendarEvent e) =>
!string.Equals(e.Transparency?.Trim(), TransparencyType.Transparent, StringComparison.OrdinalIgnoreCase)
&& !string.Equals(e.Status?.Trim(), EventStatus.Cancelled, StringComparison.OrdinalIgnoreCase);
⋮----
private static BusyInterval? IntervalOf(Period period, TimeZoneInfo hostZone)
⋮----
DateTimeOffset first, last;
⋮----
var lastDay = end is { HasTime: false } && end.Date > start.Date ? end.Date : start.Date.AddDays(1);
first = WindowTimes.StartOfDay(start.Date, hostZone);
last = WindowTimes.StartOfDay(lastDay, hostZone);
⋮----
first = InstantOf(start, hostZone, earliest: true).ToDateTimeOffset();
last = end is null ? first : InstantOf(end, hostZone, earliest: false).ToDateTimeOffset();
⋮----
return last > first ? new BusyInterval(first, last, BusySource.Calendar) : null;
⋮----
private static Instant InstantOf(CalDateTime value, TimeZoneInfo hostZone, bool earliest)
⋮----
return Instant.FromDateTimeUtc(DateTime.SpecifyKind(value.AsUtc, DateTimeKind.Utc));
⋮----
var local = DateTime.SpecifyKind(value.HasTime ? value.Value : value.Date.ToDateTime(TimeOnly.MinValue), DateTimeKind.Unspecified);
return Instant.FromDateTimeOffset(OnHostClock(local, hostZone, earliest));
⋮----
private static DateTimeOffset OnHostClock(DateTime local, TimeZoneInfo zone, bool earliest)
⋮----
for (var step = 0; zone.IsInvalidTime(local) && step < 24 * 60; step++)
⋮----
local = local.AddMinutes(1);
⋮----
var offset = zone.IsAmbiguousTime(local)
? (earliest ? zone.GetAmbiguousTimeOffsets(local).Max() : zone.GetAmbiguousTimeOffsets(local).Min())
: zone.GetUtcOffset(local);
⋮----
return new DateTimeOffset(local, offset).ToUniversalTime();
⋮----
internal static IEnumerable<BusyInterval> FreeBusyPeriods(string text, DateTimeOffset from, DateTimeOffset to)
⋮----
if (line.Equals("BEGIN:VFREEBUSY", StringComparison.OrdinalIgnoreCase))
⋮----
if (line.Equals("END:VFREEBUSY", StringComparison.OrdinalIgnoreCase))
⋮----
if (!inside || !line.StartsWith("FREEBUSY", StringComparison.OrdinalIgnoreCase))
⋮----
var colon = line.IndexOf(':');
⋮----
var type = head.Split(';').Skip(1)
.Select(parameter => parameter.Split('=', 2))
.Where(pair => pair.Length == 2 && pair[0].Trim().Equals("FBTYPE", StringComparison.OrdinalIgnoreCase))
.Select(pair => pair[1].Trim().Trim('"'))
.FirstOrDefault() ?? "BUSY";
if (type.Equals("FREE", StringComparison.OrdinalIgnoreCase))
⋮----
foreach (var value in line[(colon + 1)..].Split(','))
⋮----
if (PeriodOf(value.Trim()) is { } period && period.End > period.Start && period.Start < to && from < period.End)
⋮----
private static BusyInterval? PeriodOf(string value)
⋮----
var parts = value.Split('/', 2);
⋮----
return new BusyInterval(start, end, BusySource.Calendar);
... (78 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/CalendarFeedReader.cs">
public interface ICalendarFeedFetcher
⋮----
Task<FeedFetch> FetchAsync(Uri address, CancellationToken cancellationToken = default);
⋮----
public sealed class CalendarFeedReader(HttpClient http, ILogger<CalendarFeedReader> logger) : ICalendarFeedFetcher
⋮----
public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
⋮----
public async Task<FeedFetch> FetchAsync(Uri address, CancellationToken cancellationToken = default)
⋮----
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
⋮----
logger.LogInformation("A calendar feed leads to an address the console does not fetch.");
⋮----
using var request = new HttpRequestMessage(HttpMethod.Get, at);
request.Headers.Accept.ParseAdd("text/calendar, */*;q=0.1");
request.Options.Set(FeedRequest, true);
⋮----
HttpResponseMessage response;
⋮----
response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
⋮----
catch (HttpRequestException ex) when (NotPublicAddressException.In(ex))
⋮----
logger.LogInformation("A calendar feed's address resolves to one that is not public.");
⋮----
logger.LogInformation("A calendar feed could not be fetched: {Failure}.", ex.GetType().Name);
⋮----
logger.LogInformation("A calendar feed redirected {Status} with no address, or too often.", (int)response.StatusCode);
⋮----
at = location.IsAbsoluteUri ? location : new Uri(at, location);
⋮----
logger.LogInformation("A calendar feed answered {Status}.", status);
⋮----
if (!Readable.Contains(type))
⋮----
logger.LogInformation("A calendar feed answered {Type}, which is not a calendar.", type.Length == 0 ? "(no type)" : type);
⋮----
logger.LogInformation("A calendar feed is over {Limit} bytes.", MaxBytes);
⋮----
logger.LogInformation("A calendar feed stopped answering: {Failure}.", ex.GetType().Name);
⋮----
/// <summary>An <c>https</c> address the card reader would follow (<see cref="PublicAddress.IsFollowable"/>): public, on its default port, with no user name.</summary>
public static bool IsFetchable(Uri address) => address.Scheme == Uri.UriSchemeHttps && PublicAddress.IsFollowable(address);
⋮----
private static bool IsRedirect(HttpStatusCode status) =>
⋮----
private static async Task<string?> BodyAsync(HttpContent content, CancellationToken cancellationToken)
⋮----
await using var stream = await content.ReadAsStreamAsync(cancellationToken);
⋮----
while (length < buffer.Length && (read = await stream.ReadAsync(buffer.AsMemory(length), cancellationToken)) > 0)
⋮----
return length > MaxBytes ? null : EncodingOf(content.Headers.ContentType).GetString(buffer, 0, length);
⋮----
private static Encoding EncodingOf(MediaTypeHeaderValue? type)
⋮----
return type?.CharSet is { Length: > 0 } charset ? Encoding.GetEncoding(charset.Trim('"')) : Encoding.UTF8;
⋮----
public static class CalendarFeedRegistration
⋮----
public static IServiceCollection AddCalendarFeeds(this IServiceCollection services)
⋮----
services.AddDataProtection();
⋮----
http.DefaultRequestHeaders.UserAgent.ParseAdd("KnowledgeFabricAdmin/1.0 (+calendar feed)");
⋮----
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
⋮----
ConnectTimeout = TimeSpan.FromSeconds(5),
⋮----
ActivityHeadersPropagator = DistributedContextPropagator.CreateNoOutputPropagator(),
⋮----
.RemoveAllLoggers();
⋮----
public static void RedactFeedRequest(Activity activity, HttpRequestMessage request)
⋮----
if (!request.Options.TryGetValue(CalendarFeedReader.FeedRequest, out var isFeed) || !isFeed || request.RequestUri is not { } address)
⋮----
if (activity.GetTagItem(tag) is not null)
⋮----
activity.SetTag(tag, tag is "url.path" or "http.target" ? "/" : hostOnly);
⋮----
activity.SetTag(UrlFullTag, hostOnly);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/GuestLink.cs">
public static class GuestLink
⋮----
public static (string Token, byte[] Hash) New()
⋮----
var token = Base64Url(RandomNumberGenerator.GetBytes(TokenBytes));
⋮----
public static byte[] Hash(string token) => SHA256.HashData(Encoding.ASCII.GetBytes(token));
⋮----
public static bool IsWellFormed(string? token) =>
token is { Length: TokenLength } && token.All(c => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-' or '_');
⋮----
public static string LinkFor(string publicBaseUrl, string token) => $"{publicBaseUrl.TrimEnd('/')}{PathPrefix}{token}";
⋮----
public static string Redact(string path) =>
path.StartsWith(PathPrefix, StringComparison.OrdinalIgnoreCase) && path.Length > PathPrefix.Length ? RedactedPath : path;
⋮----
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/IBookingStore.cs">
public interface IBookingStore
⋮----
Task<IReadOnlyList<BookingHost>> HostsAsync(CancellationToken cancellationToken = default);
⋮----
Task<BookingHost?> FindHostAsync(string name, CancellationToken cancellationToken = default);
⋮----
Task<BookingHost?> FindHostBySlugAsync(string slug, CancellationToken cancellationToken = default);
⋮----
Task<HostSave> AddHostAsync(BookingHost host, CancellationToken cancellationToken = default);
⋮----
Task<HostSave> SaveHostAsync(
⋮----
Task<HostSave> RemoveHostAsync(string name, uint version, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<AvailabilityWindow>> WindowsAsync(
⋮----
Task<AvailabilityWindow?> FindWindowAsync(string hostName, Guid id, CancellationToken cancellationToken = default);
⋮----
Task<WindowAdd> AddWindowAsync(AvailabilityWindow window, CancellationToken cancellationToken = default);
⋮----
Task<AvailabilityWindow?> RemoveWindowAsync(string hostName, Guid id, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<PatternSpan>> PatternAsync(string hostName, CancellationToken cancellationToken = default);
⋮----
Task<PatternSave> SetPatternAsync(
⋮----
Task<IReadOnlyList<DayOff>> DaysOffAsync(string hostName, DateOnly from, DateOnly to, CancellationToken cancellationToken = default);
⋮----
Task<DayOffChange> AddDayOffAsync(DayOff dayOff, CancellationToken cancellationToken = default);
⋮----
Task<DayOffChange> RemoveDayOffAsync(string hostName, DateOnly day, CancellationToken cancellationToken = default);
⋮----
Task<BookingAdd> AddBookingAsync(BookingRecord booking, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<BookingRecord>> BookingsAsync(
⋮----
Task<IReadOnlyList<BookingRecord>> AllBookingsAsync(
⋮----
Task<BookingRecord?> FindBookingAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task<int> CountLiveBookingsAsync(string hostName, string guestEmail, CancellationToken cancellationToken = default);
⋮----
Task<bool> HasBookingsAsync(string hostName, CancellationToken cancellationToken = default);
⋮----
Task<BookingChange> RecordInvitationAsync(
⋮----
Task<BookingChange> CancelBookingAsync(
⋮----
Task<BookingChange> RecordEventDeletedAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task<BookingRecord?> FindBookingByCancelTokenAsync(byte[] cancelTokenHash, CancellationToken cancellationToken = default);
⋮----
Task<BookingChange> CancelByGuestAsync(byte[] cancelTokenHash, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<CalendarFeed>> FeedsAsync(string hostName, CancellationToken cancellationToken = default);
⋮----
Task<CalendarFeed?> FindFeedAsync(string hostName, Guid id, CancellationToken cancellationToken = default);
⋮----
Task<FeedAdd> AddFeedAsync(CalendarFeed feed, CancellationToken cancellationToken = default);
⋮----
Task<CalendarFeed?> RemoveFeedAsync(string hostName, Guid id, CancellationToken cancellationToken = default);
⋮----
Task RecordFeedReadAsync(Guid id, DateTimeOffset at, FeedOutcome outcome, int? busyCount, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<BookingLink>> LinksAsync(CancellationToken cancellationToken = default);
⋮----
Task<BookingLink?> FindLinkAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task<BookingLink?> FindLinkByTokenAsync(string token, CancellationToken cancellationToken = default);
⋮----
Task<LinkChange> AddLinkAsync(BookingLink link, CancellationToken cancellationToken = default);
⋮----
Task<LinkChange> SaveLinkAsync(
⋮----
Task<LinkChange> EndLinkAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<bool> HasLinksAsync(string hostName, CancellationToken cancellationToken = default);
⋮----
public static HostSave Saved(BookingHost host, IReadOnlyList<string> changed) => new(HostSaveOutcome.Saved, host, changed);
⋮----
public static HostSave Unchanged(BookingHost host) => new(HostSaveOutcome.Unchanged, host, []);
⋮----
public static HostSave Stale(BookingHost current) => new(HostSaveOutcome.Stale, current, []);
⋮----
public static readonly HostSave SlugTaken = new(HostSaveOutcome.SlugTaken, null, []);
⋮----
public static readonly HostSave NotFound = new(HostSaveOutcome.NotFound, null, []);
⋮----
public static readonly HostSave HasBookings = new(HostSaveOutcome.HasBookings, null, []);
⋮----
public static readonly HostSave OnLinks = new(HostSaveOutcome.OnLinks, null, []);
⋮----
public static WindowAdd Added(AvailabilityWindow window) => new(WindowAddOutcome.Added, window);
⋮----
public static WindowAdd Overlaps(AvailabilityWindow existing) => new(WindowAddOutcome.Overlaps, existing);
⋮----
public static readonly WindowAdd HostNotFound = new(WindowAddOutcome.HostNotFound, null);
⋮----
public static PatternSave Saved(IReadOnlyList<PatternSpan> before, IReadOnlyList<PatternSpan> after) => new(PatternSaveOutcome.Saved, before, after);
⋮----
... (131 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/InMemoryBookingStore.cs">
public sealed class InMemoryBookingStore(TimeProvider clock) : IBookingStore
⋮----
public Task<IReadOnlyList<BookingHost>> HostsAsync(CancellationToken cancellationToken = default)
⋮----
_hosts.Values.OrderBy(host => host.Name, StringComparer.Ordinal).Select(host => host.Copy()).ToList());
⋮----
public Task<BookingHost?> FindHostAsync(string name, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_hosts.GetValueOrDefault(ConsoleRoles.Normalise(name))?.Copy());
⋮----
public Task<BookingHost?> FindHostBySlugAsync(string slug, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_hosts.Values.FirstOrDefault(host => host.Slug == slug)?.Copy());
⋮----
public Task<HostSave> AddHostAsync(BookingHost host, CancellationToken cancellationToken = default)
⋮----
host.EnsureValid();
⋮----
if (_hosts.TryGetValue(host.Name, out var existing))
⋮----
return Task.FromResult(HostSave.Stale(existing.Copy()));
⋮----
return Task.FromResult(HostSave.SlugTaken);
⋮----
var stored = host.Copy();
⋮----
return Task.FromResult(HostSave.Saved(stored.Copy(), BookingHost.AllFields));
⋮----
public Task<HostSave> SaveHostAsync(
⋮----
if (!_hosts.TryGetValue(ConsoleRoles.Normalise(name), out var row))
⋮----
return Task.FromResult(HostSave.NotFound);
⋮----
return Task.FromResult(HostSave.Stale(row.Copy()));
⋮----
var after = row.Copy();
settings.CopySettingsTo(after);
after.EnsureValid();
⋮----
var changed = BookingHost.Differences(row, after);
⋮----
return Task.FromResult(HostSave.Unchanged(row.Copy()));
⋮----
return Task.FromResult(HostSave.Saved(after.Copy(), changed));
⋮----
public Task<HostSave> RemoveHostAsync(string name, uint version, CancellationToken cancellationToken = default)
⋮----
if (_bookings.Values.Any(booking => booking.Holds(row.Name)))
⋮----
return Task.FromResult(HostSave.HasBookings);
⋮----
if (_links.Values.Any(link => link.Holds(row.Name)))
⋮----
return Task.FromResult(HostSave.OnLinks);
⋮----
_hosts.Remove(row.Name);
⋮----
foreach (var id in _windows.Values.Where(window => window.HostName == row.Name).Select(window => window.Id).ToList())
⋮----
_windows.Remove(id);
⋮----
foreach (var id in _spans.Values.Where(span => span.HostName == row.Name).Select(span => span.Id).ToList())
⋮----
_spans.Remove(id);
⋮----
foreach (var key in _daysOff.Keys.Where(key => key.Host == row.Name).ToList())
⋮----
_daysOff.Remove(key);
⋮----
foreach (var id in _feeds.Values.Where(feed => feed.HostName == row.Name).Select(feed => feed.Id).ToList())
⋮----
_feeds.Remove(id);
⋮----
return Task.FromResult(HostSave.Saved(row.Copy(), []));
⋮----
public Task<IReadOnlyList<AvailabilityWindow>> WindowsAsync(
⋮----
var key = ConsoleRoles.Normalise(hostName);
⋮----
return Task.FromResult(Read(key, from, to));
⋮----
public Task<AvailabilityWindow?> FindWindowAsync(string hostName, Guid id, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_windows.GetValueOrDefault(id) is { } window && window.HostName == key ? window.Copy() : null);
⋮----
public Task<WindowAdd> AddWindowAsync(AvailabilityWindow window, CancellationToken cancellationToken = default)
⋮----
window.EnsureValid();
⋮----
if (!_hosts.ContainsKey(window.HostName))
⋮----
return Task.FromResult(WindowAdd.HostNotFound);
⋮----
var clash = Read(window.HostName, window.StartsAt, window.EndsAt).FirstOrDefault();
⋮----
return Task.FromResult(WindowAdd.Overlaps(clash));
⋮----
var stored = window.Copy();
⋮----
... (285 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/JointAvailability.cs">
public static class JointAvailability
⋮----
public static JointInput Combine(IReadOnlyList<HostAvailability> hosts)
⋮----
throw new ArgumentException("A set of hosts has at least one.", nameof(hosts));
⋮----
var windows = hosts[0].Windows.OrderBy(window => window.StartsAt).ToList();
foreach (var other in hosts.Skip(1))
⋮----
windows = Overlap(windows, other.Windows.OrderBy(window => window.StartsAt).ToList());
⋮----
var rules = new SlotRules(
DurationMinutes: hosts.Max(host => host.Host.DurationMinutes),
StepMinutes: hosts.Max(host => host.Host.StepMinutes),
NoticeHours: hosts.Max(host => host.Host.NoticeHours),
HorizonDays: hosts.Min(host => host.Host.HorizonDays),
⋮----
.SelectMany(host => host.Busy.Select(interval => Widened(interval, host.Host.BufferMinutes)))
.OrderBy(interval => interval.Start)
.ToList();
⋮----
return new JointInput(windows, rules, busy);
⋮----
private static List<AvailabilityWindow> Overlap(List<AvailabilityWindow> first, List<AvailabilityWindow> second)
⋮----
overlaps.Add(new AvailabilityWindow
⋮----
private static BusyInterval Widened(BusyInterval interval, int bufferMinutes)
⋮----
var buffer = TimeSpan.FromMinutes(bufferMinutes);
⋮----
private static Guid IdOf(Guid first, Guid second)
⋮----
var bytes = first.ToByteArray();
var other = second.ToByteArray();
⋮----
return new Guid(bytes);
⋮----
public IReadOnlyList<Slot> Offered(DateTimeOffset now) => SlotCalculator.Offered(Windows, Rules, now, Busy);
⋮----
public IEnumerable<(Slot Slot, SlotState State)> Candidates(DateTimeOffset now) => SlotCalculator.Candidates(Windows, Rules, now, Busy);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/PostgresBookingStore.cs">
public sealed class PostgresBookingStore(ConsoleDbContext db, TimeProvider clock) : IBookingStore
⋮----
public async Task<IReadOnlyList<BookingHost>> HostsAsync(CancellationToken cancellationToken = default) =>
await db.BookingHosts.AsNoTracking().OrderBy(h => h.Name).ToListAsync(cancellationToken);
⋮----
public async Task<BookingHost?> FindHostAsync(string name, CancellationToken cancellationToken = default)
⋮----
var key = ConsoleRoles.Normalise(name);
return await db.BookingHosts.AsNoTracking().SingleOrDefaultAsync(h => h.Name == key, cancellationToken);
⋮----
public async Task<BookingHost?> FindHostBySlugAsync(string slug, CancellationToken cancellationToken = default) =>
await db.BookingHosts.AsNoTracking().SingleOrDefaultAsync(h => h.Slug == slug, cancellationToken);
⋮----
public async Task<HostSave> AddHostAsync(BookingHost host, CancellationToken cancellationToken = default)
⋮----
host.EnsureValid();
⋮----
var stored = host.Copy();
db.BookingHosts.Add(stored);
⋮----
await db.SaveChangesAsync(cancellationToken);
⋮----
db.Entry(stored).State = EntityState.Detached;
⋮----
return current is null ? HostSave.NotFound : HostSave.Stale(current);
⋮----
return HostSave.Saved(stored, BookingHost.AllFields);
⋮----
public async Task<HostSave> SaveHostAsync(
⋮----
var row = await db.BookingHosts.SingleOrDefaultAsync(h => h.Name == key, cancellationToken);
⋮----
return HostSave.Stale(row.Copy());
⋮----
var before = row.Copy();
settings.CopySettingsTo(row);
row.EnsureValid();
⋮----
var changed = BookingHost.Differences(before, row);
⋮----
return HostSave.Unchanged(before);
⋮----
db.Entry(row).State = EntityState.Detached;
⋮----
return HostSave.Saved(row.Copy(), changed);
⋮----
public async Task<HostSave> RemoveHostAsync(string name, uint version, CancellationToken cancellationToken = default)
⋮----
var removed = row.Copy();
db.BookingHosts.Remove(row);
⋮----
return HostSave.Saved(removed, []);
⋮----
public async Task<IReadOnlyList<AvailabilityWindow>> WindowsAsync(
⋮----
var key = ConsoleRoles.Normalise(hostName);
⋮----
public async Task<AvailabilityWindow?> FindWindowAsync(string hostName, Guid id, CancellationToken cancellationToken = default)
⋮----
return await db.BookingWindows.AsNoTracking().SingleOrDefaultAsync(w => w.Id == id && w.HostName == key, cancellationToken);
⋮----
public async Task<WindowAdd> AddWindowAsync(AvailabilityWindow window, CancellationToken cancellationToken = default)
⋮----
window.EnsureValid();
⋮----
return await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
⋮----
await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
⋮----
.ToListAsync(cancellationToken);
⋮----
var clash = (await ReadAsync(window.HostName, window.StartsAt, window.EndsAt, cancellationToken)).FirstOrDefault();
⋮----
return WindowAdd.Overlaps(clash);
⋮----
var stored = window.Copy();
db.BookingWindows.Add(stored);
⋮----
await transaction.CommitAsync(cancellationToken);
⋮----
return WindowAdd.Added(stored.Copy());
⋮----
public async Task<AvailabilityWindow?> RemoveWindowAsync(string hostName, Guid id, CancellationToken cancellationToken = default)
⋮----
.FromSqlInterpolated($"DELETE FROM booking_windows WHERE id = {id} AND host_name = {key} RETURNING *")
.AsNoTracking()
⋮----
return removed.SingleOrDefault();
⋮----
public async Task<IReadOnlyList<PatternSpan>> PatternAsync(string hostName, CancellationToken cancellationToken = default)
⋮----
public async Task<PatternSave> SetPatternAsync(
⋮----
PatternSpan.EnsureValidSet(key, weekday, spans);
⋮----
var before = (await SpansAsync(key, cancellationToken)).Where(span => span.Weekday == weekday).ToList();
if (!before.Select(span => span.Times).Order().SequenceEqual(expected.Order()))
⋮----
return PatternSave.Stale(before);
⋮----
... (308 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/SlotCalculator.cs">
public static class SlotCalculator
⋮----
public static IReadOnlyList<Slot> Offered(
⋮----
Candidates(windows, rules, now, busy.ToList())
.Where(candidate => candidate.State == SlotState.Offered)
.Select(candidate => candidate.Slot)
.OrderBy(slot => slot.Start)
.ToList();
⋮----
public static WindowYield Yield(AvailabilityWindow window, SlotRules rules, DateTimeOffset now, IEnumerable<BusyInterval> busy)
⋮----
var states = Candidates([window], rules, now, busy.ToList()).Select(candidate => candidate.State).ToList();
⋮----
int Count(SlotState state) => states.Count(s => s == state);
⋮----
return new WindowYield(
⋮----
public static IEnumerable<(Slot Slot, SlotState State)> Candidates(
⋮----
var duration = TimeSpan.FromMinutes(rules.DurationMinutes);
var step = TimeSpan.FromMinutes(rules.StepMinutes);
var buffer = TimeSpan.FromMinutes(rules.BufferMinutes);
var earliest = now.AddHours(rules.NoticeHours);
var horizon = now.AddDays(rules.HorizonDays);
⋮----
throw new ArgumentException("A slot needs a duration and a step.", nameof(rules));
⋮----
foreach (var window in windows.OrderBy(w => w.StartsAt))
⋮----
var slot = new Slot(start, start + duration, window.Id);
⋮----
private static SlotState BusyState(Slot slot, IReadOnlyList<BusyInterval> busy, TimeSpan buffer)
⋮----
public static SlotRules Of(BookingHost host) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/TimeZones.cs">
public static class TimeZones
⋮----
public static bool IsKnown(string? name) =>
⋮----
private static bool BinarySearch(IReadOnlyList<string> all, string name)
⋮----
var compared = string.CompareOrdinal(all[middle], name);
⋮----
private static IReadOnlyList<string> Read() =>
TimeZoneInfo.GetSystemTimeZones()
.Select(zone => zone.HasIanaId ? zone.Id : TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, out var iana) ? iana : null)
⋮----
.Distinct(StringComparer.Ordinal)
.Order(StringComparer.Ordinal)
.ToList();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/ZohoCalendarClient.cs">
public sealed class ZohoCalendarClient(
⋮----
public async Task<ZohoResult<ZohoCalendar>> GetCalendarAsync(CancellationToken cancellationToken = default)
⋮----
settings => new HttpRequestMessage(HttpMethod.Get, new Uri(settings.BaseAddress!, ZohoWire.CalendarPath(settings.CalendarUid!))),
⋮----
return ZohoResult<ZohoCalendar>.Failed(reply.Outcome, reply.Code);
⋮----
var calendar = ZohoWire.ReadCalendar(reply.Body!, options.CurrentValue.CalendarUid!);
⋮----
logger.LogWarning("Zoho's answer to the booking calendar's read was not a calendar.");
return ZohoResult<ZohoCalendar>.Failed(ZohoOutcome.Unreachable, "unreadable");
⋮----
return ZohoResult<ZohoCalendar>.Of(calendar);
⋮----
public async Task<ZohoResult<ZohoCreatedEvent>> CreateEventAsync(ZohoEventRequest request, CancellationToken cancellationToken = default)
⋮----
return ZohoResult<ZohoCreatedEvent>.Failed(ZohoOutcome.Unconfigured);
⋮----
if (request.Problems() is { Count: > 0 } problems)
⋮----
var fields = string.Join(",", problems);
logger.LogError("The console built an event Zoho would refuse, in {Fields}; it was not sent. This is a fault in the console.", fields);
return ZohoResult<ZohoCreatedEvent>.Failed(ZohoOutcome.Rejected, $"invalid:{fields}");
⋮----
settings => new HttpRequestMessage(HttpMethod.Post, new Uri(settings.BaseAddress!, ZohoWire.CreatePathAndQuery(settings.CalendarUid!, request))),
⋮----
return ZohoResult<ZohoCreatedEvent>.Failed(reply.Outcome, reply.Code);
⋮----
var created = ZohoWire.ReadCreated(reply.Body!);
⋮----
logger.LogWarning("Zoho's answer to an event's creation named no event; it may have been created.");
return ZohoResult<ZohoCreatedEvent>.Failed(ZohoOutcome.Unreachable, "unreadable");
⋮----
if (created.MissingOf(request.Attendees) is var missing and > 0)
⋮----
logger.LogError(
⋮----
return ZohoResult<ZohoCreatedEvent>.Failed(ZohoOutcome.Rejected,
⋮----
return ZohoResult<ZohoCreatedEvent>.Of(created);
⋮----
public async Task<ZohoResult<ZohoCreatedEvent>> GetEventAsync(string uid, CancellationToken cancellationToken = default)
⋮----
if (string.IsNullOrWhiteSpace(uid))
⋮----
return ZohoResult<ZohoCreatedEvent>.Failed(ZohoOutcome.Rejected, "invalid:uid");
⋮----
settings => new HttpRequestMessage(HttpMethod.Get, new Uri(settings.BaseAddress!, ZohoWire.EventPath(settings.CalendarUid!, uid))),
⋮----
return ZohoWire.ReadCreated(reply.Body!) is { } read
? ZohoResult<ZohoCreatedEvent>.Of(read)
: ZohoResult<ZohoCreatedEvent>.Failed(ZohoOutcome.Unreachable, "unreadable");
⋮----
public async Task<ZohoResult> DeleteEventAsync(string uid, string etag, CancellationToken cancellationToken = default)
⋮----
if (first.Outcome != ZohoOutcome.Rejected || string.IsNullOrWhiteSpace(uid) || string.IsNullOrWhiteSpace(etag))
⋮----
if (current.Outcome != ZohoOutcome.Ok || current.Value!.Etag.Trim() == etag.Trim())
⋮----
logger.LogInformation(
⋮----
private async Task<ZohoResult> DeleteAtAsync(string uid, string etag, CancellationToken cancellationToken)
⋮----
return ZohoResult.Failed(ZohoOutcome.Unconfigured);
⋮----
if (string.IsNullOrWhiteSpace(uid) || string.IsNullOrWhiteSpace(etag))
⋮----
logger.LogError("The console asked to delete an event without its uid or etag; nothing was sent. This is a fault in the console.");
return ZohoResult.Failed(ZohoOutcome.Rejected, "invalid:uid,etag");
⋮----
var delete = new HttpRequestMessage(HttpMethod.Delete, new Uri(settings.BaseAddress!, ZohoWire.EventPath(settings.CalendarUid!, uid)));
delete.Headers.TryAddWithoutValidation(ZohoWire.EtagHeader, etag.Trim());
⋮----
return reply.Outcome == ZohoOutcome.Ok ? ZohoResult.Done : ZohoResult.Failed(reply.Outcome, reply.Code);
⋮----
private async Task<Reply> SendAsync(string what, Func<ZohoOptions, HttpRequestMessage> build, CancellationToken cancellationToken)
⋮----
return Reply.Of(ZohoOutcome.Unconfigured);
⋮----
var access = await tokens.AccessAsync(refused, cancellationToken);
⋮----
return Reply.Of(access.Outcome, access.Code);
⋮----
request.Headers.Authorization = new AuthenticationHeaderValue(ZohoWire.AuthorizationScheme, access.Token);
⋮----
HttpResponseMessage response;
⋮----
response = await http.SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("Zoho Calendar could not be reached to {What}: {Failure}.", what, ex.GetType().Name);
return Reply.Of(ZohoOutcome.Unreachable, ex is TaskCanceledException ? "timeout" : "network");
⋮----
var body = await response.Content.ReadAsStringAsync(cancellationToken);
⋮----
return Reply.Answered(body);
⋮----
var code = ZohoWire.ErrorCode(body) ?? $"http-{(int)status}";
⋮----
logger.LogInformation("Zoho Calendar answered 401 to {What}: {Code}. Refreshing the token and trying once more.", what, code);
... (23 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/ZohoEvent.cs">
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(Title) || Title.Length > ZohoWire.MaxTitle)
⋮----
problems.Add("title");
⋮----
problems.Add("end");
⋮----
if (!TimeZones.IsKnown(TimeZone))
⋮----
problems.Add("timezone");
⋮----
if (Attendees is not { Count: > 0 } || Attendees.Any(email => string.IsNullOrWhiteSpace(email) || !email.Contains('@', StringComparison.Ordinal)))
⋮----
problems.Add("attendees");
⋮----
problems.Add("description");
⋮----
problems.Add("location");
⋮----
if (Reminders is not null && Reminders.Any(reminder => reminder.Action is not (ZohoReminder.Email or ZohoReminder.Popup)
⋮----
problems.Add("reminders");
⋮----
public int MissingOf(IEnumerable<string> sent)
⋮----
var listed = new HashSet<string>((Attendees ?? []).Select(email => email.Trim()), StringComparer.OrdinalIgnoreCase);
return sent.Count(email => !listed.Contains(email.Trim()));
⋮----
public override string ToString() => $"ZohoCreatedEvent {{ Uid = {Uid}, Etag = {Etag}, Id = {Id}, Attendees = {Attendees?.Count} }}";
⋮----
public static class ZohoWire
⋮----
public static readonly TimeSpan DefaultTokenLife = TimeSpan.FromHours(1);
⋮----
public static string CalendarPath(string calendarUid) => $"api/v1/calendars/{Segment(calendarUid)}";
⋮----
public static string EventsPath(string calendarUid) => $"{CalendarPath(calendarUid)}/events";
⋮----
public static string EventPath(string calendarUid, string eventUid) => $"{EventsPath(calendarUid)}/{Segment(eventUid)}";
⋮----
private static string Segment(string uid) => Uri.EscapeDataString(uid.Trim())
.Replace("%40", "@", StringComparison.Ordinal)
.Replace("%3D", "=", StringComparison.Ordinal);
⋮----
public static string CreatePathAndQuery(string calendarUid, ZohoEventRequest request) =>
$"{EventsPath(calendarUid)}?{EventData}={Uri.EscapeDataString(EventDataJson(request))}";
⋮----
public static string Instant(DateTimeOffset instant) =>
instant.UtcDateTime.ToString(DateFormat, CultureInfo.InvariantCulture);
⋮----
public static string EventDataJson(ZohoEventRequest request)
⋮----
var data = new JsonObject
⋮----
[Title] = request.Title.Trim(),
[DateAndTime] = new JsonObject
⋮----
if (!string.IsNullOrWhiteSpace(request.Description))
⋮----
if (!string.IsNullOrWhiteSpace(request.Location))
⋮----
data[Location] = request.Location.Trim();
⋮----
data[Attendees] = new JsonArray(request.Attendees
.Select(email => (JsonNode)new JsonObject { [Email] = email.Trim(), [Attendance] = Required, [Status] = NeedsAction })
.ToArray());
⋮----
data[Reminders] = new JsonArray(reminders
.Select(reminder => (JsonNode)new JsonObject { [Action] = reminder.Action, [Minutes] = -reminder.MinutesBefore })
⋮----
return data.ToJsonString();
⋮----
public static FormUrlEncodedContent TokenForm(ZohoOptions settings) => new(
⋮----
new(ClientId, settings.ClientId!.Trim()),
new(ClientSecret, settings.ClientSecret!.Trim()),
new(RefreshToken, settings.RefreshToken!.Trim()),
⋮----
internal static TokenAnswer? ReadToken(string body)
⋮----
? TimeSpan.FromSeconds(value)
⋮----
return new TokenAnswer(Text(root[AccessToken]), life, Text(root[ApiDomain]), CodeOf(root));
⋮----
public static ZohoCreatedEvent? ReadCreated(string body)
⋮----
? listed.OfType<JsonObject>().Select(attendee => Text(attendee[Email])).OfType<string>().ToList()
⋮----
return new ZohoCreatedEvent(uid, etag, Text(created[Id]), attendees);
⋮----
public static ZohoCalendar? ReadCalendar(string body, string calendarUid)
⋮----
return name is null ? null : new ZohoCalendar(Text(calendar![Uid]) ?? calendarUid.Trim(), name);
⋮----
public static string? ErrorCode(string body) => Parse(body) is JsonObject root ? CodeOf(root) : null;
⋮----
private static string? CodeOf(JsonObject root)
⋮----
private static string? Word(string? code)
... (19 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/ZohoOptions.cs">
public sealed class ZohoOptions
⋮----
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(10);
⋮----
missing.Add($"{SectionName}:{nameof(AccountsUrl)}");
⋮----
missing.Add($"{SectionName}:{nameof(BaseUrl)}");
⋮----
if (string.IsNullOrWhiteSpace(CalendarUid))
⋮----
missing.Add($"{SectionName}:{nameof(CalendarUid)}");
⋮----
if (string.IsNullOrWhiteSpace(ClientId))
⋮----
missing.Add(SecretName(nameof(ClientId)));
⋮----
if (string.IsNullOrWhiteSpace(ClientSecret))
⋮----
missing.Add(SecretName(nameof(ClientSecret)));
⋮----
if (string.IsNullOrWhiteSpace(RefreshToken))
⋮----
missing.Add(SecretName(nameof(RefreshToken)));
⋮----
public static string SecretName(string setting) => $"{SectionName.Replace(":", "--", StringComparison.Ordinal)}--{setting}";
⋮----
private static Uri? Address(string? url)
⋮----
if (string.IsNullOrWhiteSpace(url)
|| !Uri.TryCreate(url.Trim().TrimEnd('/') + "/", UriKind.Absolute, out var address))
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/ZohoRegistration.cs">
public static class ZohoRegistration
⋮----
public static IServiceCollection AddZohoCalendar(this IServiceCollection services, IConfiguration configuration)
⋮----
services.Configure<ZohoOptions>(configuration.GetSection(ZohoOptions.SectionName));
⋮----
services.TryAddSingleton(TimeProvider.System);
⋮----
services.AddHttpClient(ZohoTokenSource.HttpClientName, Timeout).RemoveAllLoggers();
services.AddHttpClient<ZohoCalendarClient>(Timeout).RemoveAllLoggers();
⋮----
private static void Timeout(IServiceProvider provider, HttpClient http)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Booking/ZohoTokenSource.cs">
public sealed class ZohoTokenSource(
⋮----
internal static readonly TimeSpan RefreshAhead = TimeSpan.FromMinutes(5);
⋮----
private readonly SemaphoreSlim _refreshing = new(1, 1);
⋮----
internal async Task<ZohoAccess> AccessAsync(string? refused, CancellationToken cancellationToken)
⋮----
return ZohoAccess.Failed(ZohoOutcome.Unconfigured);
⋮----
await _refreshing.WaitAsync(cancellationToken);
⋮----
? new Held(token, clock.GetUtcNow() + access.Life, settings.ClientId!, settings.RefreshToken!)
⋮----
_refreshing.Release();
⋮----
private ZohoAccess? Usable(Held? held, ZohoOptions settings, string? refused) =>
⋮----
&& clock.GetUtcNow() < held.ExpiresAt - RefreshAhead
? ZohoAccess.Of(held.Token, held.ExpiresAt - clock.GetUtcNow())
⋮----
private async Task<ZohoAccess> RefreshAsync(ZohoOptions settings, CancellationToken cancellationToken)
⋮----
var http = clients.CreateClient(HttpClientName);
⋮----
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(settings.AccountsAddress!, ZohoWire.TokenPath))
⋮----
Content = ZohoWire.TokenForm(settings),
⋮----
HttpResponseMessage response;
⋮----
response = await http.SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("Zoho's token endpoint could not be reached: {Failure}.", ex.GetType().Name);
return ZohoAccess.Failed(ZohoOutcome.Unreachable, code);
⋮----
logger.LogWarning("Zoho's token endpoint answered {Status}.", (int)status);
return ZohoAccess.Failed(ZohoOutcome.Unreachable, $"http-{(int)status}");
⋮----
var answer = ZohoWire.ReadToken(await response.Content.ReadAsStringAsync(cancellationToken));
⋮----
return ZohoAccess.Of(token, answer.Life);
⋮----
logger.LogWarning("Zoho's token endpoint answered {Status} with something that is not a token.", (int)status);
return ZohoAccess.Failed(ZohoOutcome.Unreachable, "unreadable");
⋮----
logger.LogWarning(
⋮----
return ZohoAccess.Failed(ZohoOutcome.Refused, refusal);
⋮----
private void WarnOnAnotherDataCentre(string? apiDomain, ZohoOptions settings)
⋮----
if (apiDomain is null || !Uri.TryCreate(apiDomain, UriKind.Absolute, out var domain) || settings.BaseAddress is not { } calendar)
⋮----
static string TopLevel(Uri address) => address.Host[(address.Host.LastIndexOf('.') + 1)..];
⋮----
if (!string.Equals(TopLevel(domain), TopLevel(calendar), StringComparison.OrdinalIgnoreCase))
⋮----
domain.GetLeftPart(UriPartial.Authority), calendar.GetLeftPart(UriPartial.Authority));
⋮----
public override string ToString() => $"Held {{ ExpiresAt = {ExpiresAt:O} }}";
⋮----
public static ZohoAccess Of(string token, TimeSpan life) => new(ZohoOutcome.Ok, token, life, null);
⋮----
public static ZohoAccess Failed(ZohoOutcome outcome, string? code = null) => new(outcome, null, TimeSpan.Zero, code);
⋮----
public override string ToString() => $"ZohoAccess {{ Outcome = {Outcome}, Code = {Code} }}";
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/Competitor.cs">
public sealed class Competitor
⋮----
public static class Fields
⋮----
public string? TextOf(string field) => field switch
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Not a competitor's field."),
⋮----
public static string NormaliseName(string name) => name.Trim().ToLowerInvariant();
⋮----
public static bool IsWebsite(string? value) =>
Uri.TryCreate(value, UriKind.Absolute, out var uri)
⋮----
&& !string.IsNullOrEmpty(uri.Host);
⋮----
public static bool IsOneLine(string value) => value.IndexOfAny(LineBreaks) < 0;
⋮----
public IReadOnlyList<string> Problems()
⋮----
if (string.IsNullOrWhiteSpace(Name) || Name.Length > NameLength || Name != Name.Trim())
⋮----
problems.Add(Fields.Name);
⋮----
if (string.IsNullOrWhiteSpace(Website) || Website.Length > WebsiteLength || !IsWebsite(Website))
⋮----
problems.Add(Fields.Website);
⋮----
if (string.IsNullOrWhiteSpace(Summary) || Summary.Length > SummaryLength || !IsOneLine(Summary))
⋮----
problems.Add(Fields.Summary);
⋮----
if (TextOf(field) is { } text && (text.Length == 0 || text.Length > TextLength || text != text.Trim()))
⋮----
problems.Add(field);
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A competitor cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public static IReadOnlyList<string> Changes(Competitor before, Competitor after) =>
AllFields.Where(field => !string.Equals(before.TextOf(field), after.TextOf(field), StringComparison.Ordinal)).ToList();
⋮----
public void CopyProfileTo(Competitor target)
⋮----
public Competitor Copy()
⋮----
var copy = new Competitor
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorAnalyser.cs">
public string TextOf(string field) => field switch
⋮----
public static DraftRead Failed(string reason) => new(null, reason, null, 0, 0, null, null);
⋮----
public interface ICompetitorAnalyser
⋮----
Task<CompetitorAnalysis> AnalyseAsync(SiteReading site, string? positioning, CancellationToken cancellationToken = default);
⋮----
public sealed partial class CompetitorAnalyser(
⋮----
ILogger<CompetitorAnalyser> logger) : ICompetitorAnalyser
⋮----
public async Task<CompetitorAnalysis> AnalyseAsync(SiteReading site, string? positioning, CancellationToken cancellationToken = default)
⋮----
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(account.BaseAddress!, ChatPath))
⋮----
Content = new StringContent(Body(model, site, positioning).ToJsonString(), Encoding.UTF8, "application/json"),
⋮----
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", account.ApiKey!.Trim());
⋮----
HttpResponseMessage response;
⋮----
response = await clients.CreateClient(OllamaRegistration.HttpClientName).SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("Ollama could not be reached to analyse a competitor: {Failure}.", ex.GetType().Name);
⋮----
var body = await response.Content.ReadAsStringAsync(cancellationToken);
⋮----
logger.LogWarning("Ollama answered {Status} to a competitor's analysis: {Error}", (int)response.StatusCode, ErrorOf(body));
⋮----
logger.LogWarning(
⋮----
internal static string SystemPrompt(string? positioning) =>
string.IsNullOrWhiteSpace(positioning)
⋮----
+ "<<<\n" + positioning.Trim() + "\n>>>";
⋮----
internal static string SiteForModel(SiteReading site)
⋮----
var said = new StringBuilder();
said.Append("The competitor's website: ").Append(site.Address?.AbsoluteUri).Append('\n');
⋮----
said.Append("What the site calls itself in its metadata: ").Append(name).Append('\n');
⋮----
said.Append("\n--- Page ").Append(i + 1).Append(": ").Append(site.PagesRead[i].Address.AbsoluteUri).Append(" ---\n")
.Append(site.PagesRead[i].Text).Append('\n');
⋮----
said.Append("\n--- Links on the site ---\n");
⋮----
said.Append(link.Text.Length > 0 ? link.Text : "(no words)").Append(": ").Append(link.Address.AbsoluteUri).Append('\n');
⋮----
said.Append("\n--- Feeds the site offers ---\n");
⋮----
said.Append(feed.AbsoluteUri).Append('\n');
⋮----
said.Append('\n').Append(Reminder);
return said.ToString();
⋮----
internal static JsonObject Body(string model, SiteReading site, string? positioning)
⋮----
var properties = new JsonObject();
⋮----
properties[field] = new JsonObject { ["type"] = "string" };
⋮----
properties[field] = new JsonObject { ["type"] = "array", ["items"] = new JsonObject { ["type"] = "string" } };
⋮----
return new JsonObject
⋮----
["think"] = OllamaThinking.Least(model),
["format"] = new JsonObject
⋮----
["required"] = new JsonArray(TextFields.Concat(AddressFields).Select(field => (JsonNode)JsonValue.Create(field)!).ToArray()),
⋮----
["options"] = new JsonObject { ["temperature"] = 0 },
⋮----
["messages"] = new JsonArray(new JsonNode?[]
⋮----
new JsonObject { ["role"] = "system", ["content"] = SystemPrompt(positioning) },
new JsonObject { ["role"] = "user", ["content"] = SiteForModel(site) },
⋮----
internal static CompetitorDraft? Parse(string answer) => Read(answer).Draft;
⋮----
internal static DraftRead Read(string answer)
⋮----
root = JsonNode.Parse(answer);
⋮----
return DraftRead.Failed("not-json");
⋮----
if (string.IsNullOrWhiteSpace(content))
⋮----
var texts = TextFields.ToDictionary(field => field, field => TextOf(fields, field));
if (texts.Values.All(text => text.Length == 0))
⋮----
var draft = new CompetitorDraft(
⋮----
private static readonly JsonDocumentOptions Lenient = new() { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip };
⋮----
private static (Dictionary<string, JsonNode?>? Fields, bool CutShort) FindDraftObject(string content)
⋮----
for (var start = content.IndexOf('{'); start >= 0 && tried < MaxCandidates; start = content.IndexOf('{', start + 1), tried++)
... (50 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorDrafting.cs">
public sealed class CompetitorDrafting(
⋮----
public async Task<DraftReading> ReadAsync(Uri website, CancellationToken cancellationToken)
⋮----
var site = await reader.ReadAsync(website, cancellationToken);
⋮----
return new(site, null, false, [], clock.GetUtcNow());
⋮----
statement = (await positioning.ReadAsync(cancellationToken))?.Text;
⋮----
logger.LogError(ex, "The positioning statement could not be read; the competitor is analysed without it.");
⋮----
var analysis = await analyser.AnalyseAsync(site, statement, cancellationToken);
⋮----
return new(site, analysis, string.IsNullOrWhiteSpace(statement), found, clock.GetUtcNow());
⋮----
private async Task<IReadOnlyList<FoundSource>> FoundAsync(SiteReading site, CompetitorDraft draft, CancellationToken cancellationToken)
⋮----
var found = site.FeedsFound.Select(feed => new FoundSource(CompetitorSourceKind.Feed, feed.AbsoluteUri)).ToList();
⋮----
var shown = site.LinksFound.Select(link => link.Address)
.Concat(site.PagesRead.Select(page => page.Address))
.Select(address => CompetitorSource.NormaliseAddress(address.AbsoluteUri))
.ToHashSet(StringComparer.Ordinal);
⋮----
bool Held(string address) => found.Any(source => CompetitorSource.NormaliseAddress(source.Address) == CompetitorSource.NormaliseAddress(address));
⋮----
if (!CompetitorSource.IsAddress(named) || Held(named) || !shown.Contains(CompetitorSource.NormaliseAddress(named)))
⋮----
if ((await reader.CheckFeedAsync(new Uri(named), cancellationToken)).Outcome == SourceCheckOutcome.Read)
⋮----
found.Add(new FoundSource(CompetitorSourceKind.Feed, named));
⋮----
if (CompetitorSource.IsAddress(named) && !Held(named) && site.Address is { } home
&& SitePages.SameSite(new Uri(named), home) && shown.Contains(CompetitorSource.NormaliseAddress(named)))
⋮----
found.Add(new FoundSource(CompetitorSourceKind.Page, named));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorNews.cs">
public sealed class CompetitorNewsItem
⋮----
public IReadOnlyList<string> Problems()
⋮----
problems.Add("competitor_id");
⋮----
problems.Add("scan_id");
⋮----
if (Url.Length is 0 or > UrlLength || !Uri.TryCreate(Url, UriKind.Absolute, out _))
⋮----
problems.Add("url");
⋮----
if (string.IsNullOrWhiteSpace(Title) || Title.Length > TitleLength)
⋮----
problems.Add("title");
⋮----
if (string.IsNullOrWhiteSpace(SourceHost) || SourceHost.Length > HostLength)
⋮----
problems.Add("source_host");
⋮----
if (!Enum.IsDefined(Kind))
⋮----
problems.Add("kind");
⋮----
if (string.IsNullOrWhiteSpace(Summary) || Summary.Length > SummaryLength)
⋮----
problems.Add("summary");
⋮----
problems.Add("language");
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A news item cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public CompetitorNewsItem Copy() => new()
⋮----
public CompetitorNewsItem MarkedBy(string? by, DateTimeOffset? at) => new()
⋮----
public sealed class CompetitorScanRecord
⋮----
public CompetitorScanRecord Copy() => new()
⋮----
public static IReadOnlyList<ScanNews> InOrder(IEnumerable<ScanNews> news) =>
news.OrderByDescending(each => each.Items)
.ThenBy(each => each.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(each => each.CompetitorId)
.ToList();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorNewsReader.cs">
public sealed partial class CompetitorNewsReader(
⋮----
public async Task<PageItems> ListPageItemsAsync(Uri page, string text, IReadOnlyList<SiteLink> links, CancellationToken cancellationToken = default)
⋮----
var shown = links.Take(MaxPageLinks).ToList();
var said = new StringBuilder();
said.Append("The page: ").Append(page.AbsoluteUri).Append("\n\n--- Its text ---\n").Append(text).Append('\n');
said.Append("\n--- Its links ---\n");
⋮----
said.Append(link.Text.Length > 0 ? link.Text : "(no words)").Append(": ").Append(link.Address.AbsoluteUri).Append('\n');
⋮----
var schema = Schema("items", new JsonObject
⋮----
["title"] = new JsonObject { ["type"] = "string" },
["url"] = new JsonObject { ["type"] = "string" },
["date"] = new JsonObject { ["type"] = "string" },
⋮----
var (outcome, answer) = await ChatAsync(PageInstructions, said.ToString(), schema, "a newsroom page's items", cancellationToken);
⋮----
logger.LogWarning("Ollama's answer for a newsroom page's items held no list of them.");
⋮----
byAddress.TryAdd(CompetitorSource.NormaliseAddress(link.Address.AbsoluteUri), link);
⋮----
if (!byAddress.TryGetValue(CompetitorSource.NormaliseAddress(Text(item, "url").Trim()), out var link)
|| found.Any(each => each.Address == link.Address))
⋮----
var title = FeedEntries.Title(Text(item, "title"));
found.Add(new PageItem(title.Length > 0 ? title : FeedEntries.Title(link.Text), link.Address, StartOf(Day(Text(item, "date")))));
⋮----
public async Task<Judgement> JudgeAsync(
⋮----
var schema = Schema("judgements", new JsonObject
⋮----
["candidate"] = new JsonObject { ["type"] = "string" },
["about_competitor"] = new JsonObject { ["type"] = "boolean" },
["news"] = new JsonObject { ["type"] = "boolean" },
["kind"] = new JsonObject { ["type"] = "string", ["enum"] = new JsonArray(Kinds.Select(kind => (JsonNode)JsonValue.Create(kind)!).ToArray()) },
["summary"] = new JsonObject { ["type"] = "string" },
["language"] = new JsonObject { ["type"] = "string" },
["published"] = new JsonObject { ["type"] = "string" },
["same_as"] = new JsonObject { ["type"] = "string" },
⋮----
+ $"\n\nToday is {today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}. "
+ $"News published before {notBefore.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)} is not new.";
⋮----
logger.LogWarning("Ollama's answer for a batch of candidates held no list of judgements.");
⋮----
var id = Text(each, "candidate").Trim().ToUpperInvariant();
if (!IsCandidate(id, batch.Count) || verdicts.ContainsKey(id))
⋮----
var sameAs = Text(each, "same_as").Trim().ToUpperInvariant();
verdicts[id] = new NewsVerdict(
⋮----
Enum.TryParse<NewsKind>(Text(each, "kind").Trim(), ignoreCase: true, out var kind) && Enum.IsDefined(kind) ? kind : null,
⋮----
internal static string BatchForModel(Competitor competitor, IReadOnlyList<NewsCandidate> batch, IReadOnlyList<CompetitorNewsItem> held)
⋮----
said.Append("The competitor: ").Append(competitor.Name).Append('\n');
said.Append("Their website: ").Append(competitor.Website).Append('\n');
said.Append("In one line: ").Append(competitor.Summary).Append('\n');
⋮----
said.Append("What they do: ").Append(whatTheyDo.Length > MaxWhatTheyDo ? whatTheyDo[..MaxWhatTheyDo] : whatTheyDo).Append('\n');
⋮----
said.Append("\n--- Items already held about them (same_as may name one) ---\n");
⋮----
said.Append("(none)\n");
⋮----
said.Append('S').Append(i + 1).Append(": ").Append(held[i].Title)
.Append(" (").Append(held[i].PublishedAt?.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? "no date").Append(") ")
.Append(held[i].Url).Append('\n');
⋮----
said.Append("\n--- Candidates ---\n");
⋮----
said.Append("\nC").Append(i + 1).Append('\n');
said.Append("Title: ").Append(candidate.Title.Length > 0 ? candidate.Title : "(none)").Append('\n');
said.Append("Address: ").Append(candidate.Url).Append('\n');
said.Append("Published by: ").Append(candidate.SourceHost).Append('\n');
said.Append("Published: ")
.Append(candidate.PublishedAt?.UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? "not given").Append('\n');
⋮----
said.Append("The first of its page's text:\n<<<\n").Append(text).Append("\n>>>\n");
⋮----
return said.ToString();
⋮----
private static bool IsCandidate(string id, int count) => IsNumbered(id, 'C', count);
⋮----
private static bool IsHeld(string id, int count) => IsNumbered(id, 'S', count);
⋮----
private static bool IsNumbered(string id, char prefix, int count) =>
id.Length > 1 && id[0] == prefix && int.TryParse(id[1..], NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n >= 1 && n <= count;
⋮----
private static JsonObject Schema(string list, JsonObject properties, string[] required) => new()
⋮----
["properties"] = new JsonObject
⋮----
[list] = new JsonObject
⋮----
["items"] = new JsonObject
⋮----
["required"] = new JsonArray(required.Select(name => (JsonNode)JsonValue.Create(name)!).ToArray()),
... (78 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorNotifications.cs">
public sealed class CompetitorNotifications(Notifier notifier, ConsolePeople people, ILogger<CompetitorNotifications> logger)
⋮----
public async Task<int> ScanEndedAsync(CompetitorScanRecord scan)
⋮----
var told = await people.CompetitorsAsync(CancellationToken.None);
return await notifier.NotifyAsync(told, News, scan.Id);
⋮----
logger.LogError(ex, "Nobody could be told of the {Items} items the competitors' scan {ScanId} stored.", scan.ItemsStored, scan.Id);
⋮----
public sealed class CompetitorNewsNotificationContent(
⋮----
IStringLocalizer<ConsoleResource> text) : INotificationContent
⋮----
public bool Renders(string kind) => kind == CompetitorNotifications.News;
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default)
⋮----
if (notification.SubjectId is not { } scanId || !ConsolePeople.IsPerson(notification.Recipient))
⋮----
_told ??= (await people.CompetitorsAsync(cancellationToken)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
if (!_told.Contains(notification.Recipient))
⋮----
if (!_names.TryGetValue(scanId, out var names))
⋮----
names = _names[scanId] = ScanNews.InOrder(await store.ScanNewsAsync(scanId, cancellationToken)).Select(each => each.Name).ToList();
⋮----
return new NotificationContent(text["Notifications.Competitors.Title"].Value, body, Path);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorScan.cs">
public sealed class CompetitorScanOptions
⋮----
public int Results => Math.Clamp(MaxResults, 1, OllamaSearchClient.MostResults);
⋮----
public TimeSpan LookBack => TimeSpan.FromDays(Math.Clamp(LookBackDays, 1, 31));
⋮----
public DateOnly DayOf(DateTimeOffset instant) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(instant, Zone).DateTime);
⋮----
public DateTimeOffset StartOf(DateOnly day)
⋮----
var midnight = day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
return new DateTimeOffset(midnight, Zone.GetUtcOffset(midnight));
⋮----
private static TimeZoneInfo? Find(string? name)
⋮----
if (string.IsNullOrWhiteSpace(name))
⋮----
return TimeZoneInfo.FindSystemTimeZoneById(name.Trim());
⋮----
public sealed class CompetitorScan(
⋮----
public async Task<CompetitorScanRecord> StartAsync(ScanTrigger trigger, string? by, CancellationToken cancellationToken = default)
⋮----
var record = new CompetitorScanRecord { Id = Guid.NewGuid(), StartedAt = clock.GetUtcNow(), Trigger = trigger, StartedBy = by };
await store.StartScanAsync(record, cancellationToken);
logger.LogInformation("The competitors' scan {ScanId} started ({Trigger}).", record.Id, trigger);
⋮----
public async Task<CompetitorScanRecord> ContinueAsync(CompetitorScanRecord record, CancellationToken cancellationToken = default)
⋮----
var watch = Stopwatch.StartNew();
⋮----
foreach (var competitor in await store.ListAsync(cancellationToken))
⋮----
cancellationToken.ThrowIfCancellationRequested();
⋮----
logger.LogError(ex, "The competitors' scan {ScanId} could not finish competitor {CompetitorId}; it goes on with the rest.", record.Id, competitor.Id);
⋮----
record.FinishedAt = clock.GetUtcNow();
⋮----
await store.FinishScanAsync(record, CancellationToken.None);
⋮----
logger.LogError(ex, "The competitors' scan {ScanId} could not record how it ended.", record.Id);
⋮----
logger.LogInformation(
⋮----
record.Id, record.Trigger, Math.Round(watch.Elapsed.TotalSeconds), record.CompetitorsScanned, record.SourcesRead, record.SourcesFailed,
⋮----
var told = await notifications.ScanEndedAsync(record);
⋮----
logger.LogInformation("The competitors' scan {ScanId} told {Told} people of its items.", record.Id, told);
⋮----
private async Task ScanAsync(CompetitorScanRecord record, Competitor competitor, CancellationToken cancellationToken)
⋮----
var held = (await store.NewsAsync(competitor.Id, cutoff, cancellationToken)).Take(MaxHeldShown).ToList();
var today = settings.DayOf(record.StartedAt);
var notBefore = DateOnly.FromDateTime(cutoff.UtcDateTime);
⋮----
foreach (var batch in candidates.Chunk(BatchSize))
⋮----
var judgement = await model.JudgeAsync(competitor, batch, held, today, notBefore, cancellationToken);
⋮----
logger.LogWarning(
⋮----
var published = candidate.PublishedAt ?? CompetitorNewsReader.StartOf(verdict.Published);
⋮----
var item = new CompetitorNewsItem
⋮----
Id = Guid.NewGuid(),
⋮----
Title = candidate.Title.Length > 0 ? candidate.Title : FeedEntries.Title(candidate.Url),
SourceHost = candidate.SourceHost.Length > 0 ? candidate.SourceHost : NewsAddress.Host(candidate.Url),
⋮----
FoundAt = clock.GetUtcNow(),
⋮----
if (await store.AddNewsAsync(item, cancellationToken))
⋮----
held.Insert(0, item);
⋮----
held.RemoveAt(held.Count - 1);
⋮----
private async Task<List<NewsCandidate>> ReadSourcesAsync(
⋮----
var sources = (await store.SourcesAsync(competitor.Id, cancellationToken)).Where(source => source.Enabled).ToList();
⋮----
foreach (var feed in sources.Where(source => source.Kind == CompetitorSourceKind.Feed))
⋮----
var read = await reader.ReadFeedAsync(new Uri(feed.Address!), cancellationToken);
⋮----
found.AddRange(entries);
await CountAsync(record, competitor, feed, ScanSourceKind.Feed, read.Outcome.ToString(), read.Outcome == SourceCheckOutcome.Read, entries.Count, cancellationToken);
⋮----
foreach (var page in sources.Where(source => source.Kind == CompetitorSourceKind.Page))
⋮----
var (outcome, items) = await ReadPageAsync(new Uri(page.Address!), cancellationToken);
found.AddRange(items);
⋮----
var terms = sources.Where(source => source.Kind == CompetitorSourceKind.SearchTerm).ToList();
var termReads = terms.ToDictionary(term => term.Id, _ => (Outcome: (string?)null, Count: 0));
⋮----
var read = await reader.ReadFeedAsync(GoogleNews.SearchAddress(term.Term!, edition), cancellationToken);
... (157 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorSiteReader.cs">
/// <summary>
/// Reads a competitor's website for the model (#222), and checks a feed or a page before it is a source;
/// since #223, reads a feed's entries and a page's text for the daily scan, by the same rules.
/// </summary>
public interface ICompetitorSiteReader
⋮----
/// <summary>Never throws but for cancellation: every failure is a <see cref="SiteReadOutcome"/> the page states.</summary>
Task<SiteReading> ReadAsync(Uri website, CancellationToken cancellationToken = default);
⋮----
Task<SourceCheck> CheckFeedAsync(Uri address, CancellationToken cancellationToken = default);
⋮----
Task<SourceCheck> CheckPageAsync(Uri address, CancellationToken cancellationToken = default);
⋮----
Task<FeedReading> ReadFeedAsync(Uri address, CancellationToken cancellationToken = default);
⋮----
Task<PageReading> ReadPageAsync(Uri address, CancellationToken cancellationToken = default);
⋮----
public sealed class CompetitorSiteReader(HttpClient http, ILogger<CompetitorSiteReader> logger) : ICompetitorSiteReader
⋮----
public static readonly TimeSpan PageTimeout = TimeSpan.FromSeconds(10);
⋮----
public static readonly TimeSpan ReadingTimeout = TimeSpan.FromSeconds(45);
⋮----
public async Task<SiteReading> ReadAsync(Uri website, CancellationToken cancellationToken = default)
⋮----
using var unrecorded = SuppressInstrumentationScope.Begin();
using var reading = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
reading.CancelAfter(ReadingTimeout);
⋮----
logger.LogInformation("A competitor's site was not read: {Outcome}.", home.Outcome);
⋮----
var homeText = PageText.Of(home.MediaType!, home.Body!);
⋮----
logger.LogInformation("A competitor's site answered with no text to read.");
⋮----
var homeLinks = SiteHtml.Links(home.Body!, address);
⋮----
var feedCandidates = new List<Uri>(SiteHtml.Feeds(home.Body!, address));
⋮----
foreach (var link in SitePages.Choose(homeLinks, address, MaxLinkedPages))
⋮----
if (page.Outcome != FetchOutcome.Read || !SitePages.SameSite(page.Address!, address))
⋮----
var text = PageText.Of(page.MediaType!, page.Body!);
if (text.Length == 0 || pages.Any(read => SameAddress(read.Address, page.Address!)))
⋮----
pages.Add(new SitePage(page.Address!, Cut(text, budget)));
⋮----
links.AddRange(SiteHtml.Links(page.Body!, page.Address!));
feedCandidates.AddRange(SiteHtml.Feeds(page.Body!, page.Address!));
⋮----
.Where(link => SitePages.SameSite(link.Address, address))
.DistinctBy(link => CompetitorSource.NormaliseAddress(link.Address.AbsoluteUri))
.Take(MaxLinks)
.ToList();
⋮----
feedCandidates.AddRange(links.Where(link => SiteHtml.LooksLikeFeed(link)).Select(link => link.Address));
⋮----
foreach (var candidate in feedCandidates.DistinctBy(feed => CompetitorSource.NormaliseAddress(feed.AbsoluteUri)).Take(MaxFeedCandidates))
⋮----
var origin = new Uri(address.GetLeftPart(UriPartial.Authority));
⋮----
var tried = new Uri(origin, path);
⋮----
if (!feeds.Any(feed => SameAddress(feed, tried)))
⋮----
logger.LogInformation(
⋮----
pages.Count, pages.Sum(page => page.Text.Length), onSite.Count, feeds.Count);
⋮----
return new(SiteReadOutcome.Read, address, SiteHtml.Name(home.Body!), pages, onSite, feeds);
⋮----
public async Task<SourceCheck> CheckFeedAsync(Uri address, CancellationToken cancellationToken = default)
⋮----
return FeedFormat.ItemCount(fetched.Body!) is { } count
⋮----
public async Task<SourceCheck> CheckPageAsync(Uri address, CancellationToken cancellationToken = default)
⋮----
return PageText.Of(fetched.MediaType!, fetched.Body!).Length == 0
⋮----
public async Task<FeedReading> ReadFeedAsync(Uri address, CancellationToken cancellationToken = default)
⋮----
return FeedFormat.ItemCount(fetched.Body!) is null
⋮----
: new(SourceCheckOutcome.Read, fetched.Address, FeedEntries.Parse(fetched.Body!, fetched.Address!));
⋮----
public async Task<PageReading> ReadPageAsync(Uri address, CancellationToken cancellationToken = default)
⋮----
var text = PageText.Of(fetched.MediaType!, fetched.Body!);
⋮----
: new(SourceCheckOutcome.Read, fetched.Address, text, SiteHtml.Links(fetched.Body!, fetched.Address!), SiteHtml.Published(fetched.Body!));
⋮----
private async Task AddIfFeedAsync(Uri candidate, List<Uri> feeds, CancellationToken reading, CancellationToken cancellationToken)
⋮----
if (fetched.Outcome == FetchOutcome.Read && FeedFormat.ItemCount(fetched.Body!) is not null && !feeds.Any(feed => SameAddress(feed, candidate)))
⋮----
feeds.Add(candidate);
⋮----
private static SourceCheckOutcome Check(FetchOutcome outcome) => outcome switch
⋮----
... (198 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorsOptions.cs">
public sealed class CompetitorsOptions
⋮----
public string? ModelName => string.IsNullOrWhiteSpace(Model) ? null : Model.Trim();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorSource.cs">
public sealed class CompetitorSource
⋮----
Kind != CompetitorSourceKind.SearchTerm && Uri.TryCreate(Address, UriKind.Absolute, out var uri) ? uri.IdnHost.ToLowerInvariant() : null;
⋮----
public bool SameAs(CompetitorSource other) =>
Kind == other.Kind && string.Equals(Key(this), Key(other), StringComparison.Ordinal);
⋮----
public static string Key(CompetitorSource source) => source.Kind == CompetitorSourceKind.SearchTerm
? (source.Term ?? string.Empty).Trim().ToLowerInvariant()
⋮----
public static string NormaliseAddress(string? address)
⋮----
if (!Uri.TryCreate(address?.Trim(), UriKind.Absolute, out var uri))
⋮----
return (address ?? string.Empty).Trim();
⋮----
var path = uri.AbsolutePath.Length > 1 ? uri.AbsolutePath.TrimEnd('/') : string.Empty;
return $"{uri.Scheme}://{uri.IdnHost.ToLowerInvariant()}{(uri.IsDefaultPort ? "" : ":" + uri.Port)}{path}{uri.Query}";
⋮----
public static bool IsAddress(string? value) =>
⋮----
&& Uri.TryCreate(value, UriKind.Absolute, out var uri)
&& Crm.PublicAddress.IsFollowable(uri);
⋮----
public IReadOnlyList<string> Problems()
⋮----
problems.Add("competitor_id");
⋮----
if (string.IsNullOrWhiteSpace(Term) || Term.Length > TermLength || Term != Term.Trim() || !Competitor.IsOneLine(Term) || Address is not null)
⋮----
problems.Add("term");
⋮----
else if (!Enum.IsDefined(Kind) || !IsAddress(Address) || Term is not null)
⋮----
problems.Add("address");
⋮----
public void EnsureValid()
⋮----
throw new ArgumentException($"A competitor's source cannot be stored with {string.Join(", ", problems)} as given.");
⋮----
public static void EnsureValidFor(Guid competitorId, IReadOnlyList<CompetitorSource> sources)
⋮----
throw new ArgumentException($"A competitor holds at most {MaxPerCompetitor} sources.", nameof(sources));
⋮----
sources[i].EnsureValid();
⋮----
throw new ArgumentException("A source names another competitor.", nameof(sources));
⋮----
if (sources.Take(i).Any(sources[i].SameAs))
⋮----
throw new ArgumentException("A source is given twice.", nameof(sources));
⋮----
public CompetitorSource Copy() => new()
⋮----
public static IReadOnlyList<CompetitorSource> Ordered(IEnumerable<CompetitorSource> sources) =>
sources.OrderBy(source => source.Kind).ThenBy(source => source.CreatedAt).ThenBy(source => source.Id).ToList();
⋮----
public static SourceAdd Added(CompetitorSource source) => new(SourceAddOutcome.Added, source);
⋮----
public static SourceAdd Duplicate(CompetitorSource existing) => new(SourceAddOutcome.Duplicate, existing);
⋮----
public static readonly SourceAdd TooMany = new(SourceAddOutcome.TooMany);
⋮----
public static readonly SourceAdd CompetitorNotFound = new(SourceAddOutcome.CompetitorNotFound);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorSourceAdder.cs">
public sealed class CompetitorSourceAdder(ICompetitorStore store, ICompetitorSiteReader reader, TimeProvider clock)
⋮----
public async Task<SourceRequest> AddAsync(Guid competitorId, string? kind, string? value, string by, CancellationToken cancellationToken)
⋮----
if (!Enum.TryParse<CompetitorSourceKind>(kind, ignoreCase: false, out var parsed) || !Enum.IsDefined(parsed) || int.TryParse(kind, out _))
⋮----
CompetitorSource source;
⋮----
if (text.Length is 0 or > CompetitorSource.TermLength || !Competitor.IsOneLine(text))
⋮----
source = new CompetitorSource
⋮----
Id = Guid.NewGuid(),
⋮----
CreatedAt = clock.GetUtcNow(),
⋮----
if (!Competitor.IsWebsite(text) || !CompetitorSource.IsAddress(text))
⋮----
var held = await store.SourcesAsync(competitorId, cancellationToken);
var asked = new CompetitorSource { Kind = parsed, Address = text };
if (held.FirstOrDefault(asked.SameAs) is { } existing)
⋮----
var address = new Uri(text);
⋮----
? await reader.CheckFeedAsync(address, cancellationToken)
: await reader.CheckPageAsync(address, cancellationToken);
⋮----
LastReadAt = clock.GetUtcNow(),
⋮----
var added = await store.AddSourceAsync(source, CancellationToken.None);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/CompetitorsRegistration.cs">
public static class CompetitorsRegistration
⋮----
public static IServiceCollection AddCompetitors(
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
else if (environment.IsDevelopment())
⋮----
services.Configure<CompetitorsOptions>(configuration.GetSection(CompetitorsOptions.SectionName));
⋮----
services.Configure<CompetitorScanOptions>(configuration.GetSection(CompetitorScanOptions.SectionName));
⋮----
http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; KnowledgeFabricAdmin/1.0; +competitors)");
⋮----
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
⋮----
ConnectTimeout = TimeSpan.FromSeconds(5),
⋮----
ActivityHeadersPropagator = DistributedContextPropagator.CreateNoOutputPropagator(),
⋮----
.RemoveAllLoggers();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/ICompetitorStore.cs">
public interface ICompetitorStore
⋮----
Task<IReadOnlyList<Competitor>> ListAsync(CancellationToken cancellationToken = default);
⋮----
Task<Competitor?> FindAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task<CompetitorSave> AddAsync(Competitor competitor, CancellationToken cancellationToken = default);
⋮----
Task<CompetitorSave> AddAsync(Competitor competitor, IReadOnlyList<CompetitorSource> sources, CancellationToken cancellationToken = default);
⋮----
Task<CompetitorSave> SaveAsync(
⋮----
Task<Competitor?> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Competitor>> DeletedAsync(CancellationToken cancellationToken = default);
⋮----
Task<CompetitorSave> RestoreAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<CompetitorSource>> SourcesAsync(Guid competitorId, CancellationToken cancellationToken = default);
⋮----
Task<SourceAdd> AddSourceAsync(CompetitorSource source, CancellationToken cancellationToken = default);
⋮----
Task<CompetitorSource?> SetSourceEnabledAsync(Guid competitorId, Guid sourceId, bool enabled, CancellationToken cancellationToken = default);
⋮----
Task<CompetitorSource?> RemoveSourceAsync(Guid competitorId, Guid sourceId, CancellationToken cancellationToken = default);
⋮----
Task RecordSourceReadAsync(Guid sourceId, DateTimeOffset at, string outcome, int? count, CancellationToken cancellationToken = default);
⋮----
Task StartScanAsync(CompetitorScanRecord scan, CancellationToken cancellationToken = default);
⋮----
Task FinishScanAsync(CompetitorScanRecord scan, CancellationToken cancellationToken = default);
⋮----
Task<CompetitorScanRecord?> LastScanAsync(CancellationToken cancellationToken = default);
⋮----
Task<bool> ScheduledScanSinceAsync(DateTimeOffset since, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlySet<string>> HeldNewsAddressesAsync(Guid competitorId, IReadOnlyCollection<string> urls, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<CompetitorNewsItem>> NewsAsync(Guid competitorId, DateTimeOffset? since = null, CancellationToken cancellationToken = default);
⋮----
Task<bool> AddNewsAsync(CompetitorNewsItem item, CancellationToken cancellationToken = default);
⋮----
Task<NewsPage> FeedAsync(NewsQuery query, CancellationToken cancellationToken = default);
⋮----
Task<int> CountNewsAsync(NewsQuery query, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyDictionary<Guid, DateTimeOffset>> LatestNewsAsync(CancellationToken cancellationToken = default);
⋮----
Task<NewsMark> MarkNewsAsync(Guid itemId, bool irrelevant, string by, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<ScanNews>> ScanNewsAsync(Guid scanId, CancellationToken cancellationToken = default);
⋮----
public static CompetitorSave Saved(Competitor competitor, IReadOnlyList<string> changed) => new(CompetitorSaveOutcome.Saved, competitor, changed);
⋮----
public static CompetitorSave Unchanged(Competitor competitor) => new(CompetitorSaveOutcome.Unchanged, competitor, []);
⋮----
public static CompetitorSave Stale(Competitor current) => new(CompetitorSaveOutcome.Stale, current, []);
⋮----
public static CompetitorSave NameTaken(Competitor other) => new(CompetitorSaveOutcome.NameTaken, other, []);
⋮----
public static readonly CompetitorSave NotFound = new(CompetitorSaveOutcome.NotFound, null, []);
⋮----
public sealed class UnconfiguredCompetitorStore : ICompetitorStore
⋮----
public Task<IReadOnlyList<Competitor>> ListAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<Competitor?> FindAsync(Guid id, CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorSave> AddAsync(Competitor competitor, CancellationToken cancellationToken = default) =>
throw new CompetitorStoreUnavailableException();
⋮----
public Task<CompetitorSave> SaveAsync(
⋮----
public Task<Competitor?> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<Competitor>> DeletedAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorSave> RestoreAsync(Guid id, CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorSave> AddAsync(Competitor competitor, IReadOnlyList<CompetitorSource> sources, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<CompetitorSource>> SourcesAsync(Guid competitorId, CancellationToken cancellationToken = default) =>
⋮----
public Task<SourceAdd> AddSourceAsync(CompetitorSource source, CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorSource?> SetSourceEnabledAsync(Guid competitorId, Guid sourceId, bool enabled, CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorSource?> RemoveSourceAsync(Guid competitorId, Guid sourceId, CancellationToken cancellationToken = default) =>
⋮----
public Task RecordSourceReadAsync(Guid sourceId, DateTimeOffset at, string outcome, int? count, CancellationToken cancellationToken = default) =>
⋮----
public Task StartScanAsync(CompetitorScanRecord scan, CancellationToken cancellationToken = default) =>
⋮----
public Task FinishScanAsync(CompetitorScanRecord scan, CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorScanRecord?> LastScanAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<bool> ScheduledScanSinceAsync(DateTimeOffset since, CancellationToken cancellationToken = default) =>
Task.FromResult(false);
⋮----
... (18 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/InMemoryCompetitorStore.cs">
public sealed class InMemoryCompetitorStore : ICompetitorStore
⋮----
public Task<IReadOnlyList<Competitor>> ListAsync(CancellationToken cancellationToken = default)
⋮----
.OrderBy(row => row.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(row => row.Id)
.Select(row => row.Copy())
.ToList());
⋮----
public Task<Competitor?> FindAsync(Guid id, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(Live.FirstOrDefault(row => row.Id == id)?.Copy());
⋮----
public Task<CompetitorSave> AddAsync(Competitor competitor, CancellationToken cancellationToken = default) =>
⋮----
public Task<CompetitorSave> AddAsync(Competitor competitor, IReadOnlyList<CompetitorSource> sources, CancellationToken cancellationToken = default)
⋮----
competitor.EnsureValid();
CompetitorSource.EnsureValidFor(competitor.Id, sources);
⋮----
return Task.FromResult(CompetitorSave.NameTaken(other.Copy()));
⋮----
var stored = competitor.Copy();
⋮----
_sources[source.Id] = source.Copy();
⋮----
return Task.FromResult(CompetitorSave.Saved(stored.Copy(), Competitor.AllFields));
⋮----
public Task<CompetitorSave> SaveAsync(
⋮----
var row = Live.FirstOrDefault(row => row.Id == id);
⋮----
return Task.FromResult(CompetitorSave.NotFound);
⋮----
return Task.FromResult(CompetitorSave.Stale(row.Copy()));
⋮----
var after = row.Copy();
profile.CopyProfileTo(after);
after.EnsureValid();
⋮----
var changed = Competitor.Changes(row, after);
⋮----
return Task.FromResult(CompetitorSave.Unchanged(row.Copy()));
⋮----
return Task.FromResult(CompetitorSave.Saved(after.Copy(), changed));
⋮----
public Task<Competitor?> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult<Competitor?>(row.Copy());
⋮----
public Task<IReadOnlyList<Competitor>> DeletedAsync(CancellationToken cancellationToken = default)
⋮----
.Where(row => row.IsDeleted)
.OrderByDescending(row => row.DeletedAt)
.ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase)
⋮----
public Task<CompetitorSave> RestoreAsync(Guid id, CancellationToken cancellationToken = default)
⋮----
if (!_rows.TryGetValue(id, out var row) || !row.IsDeleted)
⋮----
return Task.FromResult(CompetitorSave.Saved(row.Copy(), []));
⋮----
public Task<IReadOnlyList<CompetitorSource>> SourcesAsync(Guid competitorId, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(IsLive(competitorId)
? CompetitorSource.Ordered(SourcesOf(competitorId).Select(source => source.Copy()))
⋮----
public Task<SourceAdd> AddSourceAsync(CompetitorSource source, CancellationToken cancellationToken = default)
⋮----
source.EnsureValid();
⋮----
return Task.FromResult(SourceAdd.CompetitorNotFound);
⋮----
var held = SourcesOf(source.CompetitorId).ToList();
if (held.FirstOrDefault(source.SameAs) is { } existing)
⋮----
return Task.FromResult(SourceAdd.Duplicate(existing.Copy()));
⋮----
return Task.FromResult(SourceAdd.TooMany);
⋮----
return Task.FromResult(SourceAdd.Added(source.Copy()));
⋮----
public Task<CompetitorSource?> SetSourceEnabledAsync(Guid competitorId, Guid sourceId, bool enabled, CancellationToken cancellationToken = default)
⋮----
if (!IsLive(competitorId) || !_sources.TryGetValue(sourceId, out var source) || source.CompetitorId != competitorId)
⋮----
return Task.FromResult<CompetitorSource?>(source.Copy());
⋮----
public Task<CompetitorSource?> RemoveSourceAsync(Guid competitorId, Guid sourceId, CancellationToken cancellationToken = default)
⋮----
_sources.Remove(sourceId);
⋮----
public Task RecordSourceReadAsync(Guid sourceId, DateTimeOffset at, string outcome, int? count, CancellationToken cancellationToken = default)
⋮----
if (_sources.TryGetValue(sourceId, out var source))
⋮----
public Task StartScanAsync(CompetitorScanRecord scan, CancellationToken cancellationToken = default)
⋮----
_scans[scan.Id] = scan.Copy();
⋮----
... (90 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/NewsCandidates.cs">
public static class NewsAddress
⋮----
public static string? Canonical(string? address)
⋮----
var host = uri.IdnHost.ToLowerInvariant();
⋮----
var kept = uri.Query.TrimStart('?')
.Split('&', StringSplitOptions.RemoveEmptyEntries)
.Where(pair =>
⋮----
var name = Uri.UnescapeDataString(pair.Split('=', 2)[0]);
return !name.StartsWith("utm_", StringComparison.OrdinalIgnoreCase)
&& !Tracking.Contains(name)
&& !(isGoogleNews && name.Equals("oc", StringComparison.OrdinalIgnoreCase));
⋮----
.ToList();
⋮----
var path = uri.AbsolutePath.Length > 1 ? uri.AbsolutePath.TrimEnd('/') : "/";
⋮----
var canonical = $"{uri.Scheme}://{host}{(uri.IsDefaultPort ? "" : ":" + uri.Port.ToString(CultureInfo.InvariantCulture))}{path}"
+ (kept.Count > 0 ? "?" + string.Join('&', kept) : "");
⋮----
/// <summary>Who published an address: its host, lower-case, a leading <c>www.</c> dropped; empty when it is not one.</summary>
public static string Host(string? address)
⋮----
host = host.StartsWith("www.", StringComparison.Ordinal) ? host[4..] : host;
⋮----
/// <summary>Whether <paramref name="address"/> is Google News's own, whose page is Google's and not the article's.</summary>
public static bool IsGoogleNews(string address) =>
Uri.TryCreate(address, UriKind.Absolute, out var uri) && uri.IdnHost.Equals("news.google.com", StringComparison.OrdinalIgnoreCase);
⋮----
private static Uri? Redirected(Uri uri)
⋮----
var isGoogleUrl = (host.StartsWith("google.", StringComparison.Ordinal) || host.StartsWith("www.google.", StringComparison.Ordinal))
⋮----
foreach (var pair in uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries))
⋮----
var parts = pair.Split('=', 2);
var name = Uri.UnescapeDataString(parts[0]);
⋮----
&& TryAbsolute(Uri.UnescapeDataString(parts[1].Replace('+', ' ')), out var article))
⋮----
private static bool TryAbsolute(string? address, out Uri uri)
⋮----
if (Uri.TryCreate(address?.Trim(), UriKind.Absolute, out var parsed)
⋮----
public static partial class FeedEntries
⋮----
public static IReadOnlyList<FeedEntry> Parse(string body, Uri feed)
⋮----
var settings = new XmlReaderSettings
⋮----
using var reader = XmlReader.Create(new StringReader(body.TrimStart('﻿', ' ', '\t', '\r', '\n')), settings);
reader.Read();
⋮----
if (XNode.ReadFrom(reader) is XElement element && Entry(element, feed, atom: root == "atom") is { } entry)
⋮----
entries.Add(entry);
⋮----
private static FeedEntry? Entry(XElement element, Uri feed, bool atom)
⋮----
link = element.Elements()
.Where(e => e.Name.LocalName == "link")
.Where(e => (string?)e.Attribute("rel") is null or "alternate")
.Select(e => (string?)e.Attribute("href"))
.FirstOrDefault(href => !string.IsNullOrWhiteSpace(href));
published = NewsDates.Parse(Child(element, "published")?.Value) ?? NewsDates.Parse(Child(element, "updated")?.Value);
⋮----
if (string.IsNullOrWhiteSpace(link) && Child(element, "guid") is { } guid && (string?)guid.Attribute("isPermaLink") != "false")
⋮----
published = NewsDates.Parse(Child(element, "pubDate")?.Value)
?? NewsDates.Parse(Child(element, "date")?.Value)
?? NewsDates.Parse(Child(element, "published")?.Value)
?? NewsDates.Parse(Child(element, "updated")?.Value);
⋮----
sourceUrl = ((string?)source.Attribute("url"))?.Trim();
⋮----
if (sourceName is { Length: > 0 } publisher && title.EndsWith(" - " + publisher, StringComparison.Ordinal) && title.Length > publisher.Length + 3)
⋮----
title = title[..^(publisher.Length + 3)].TrimEnd();
⋮----
if (!string.IsNullOrWhiteSpace(link) && Uri.TryCreate(feed, link.Trim(), out var address)
⋮----
return resolved is null && title.Length == 0 ? null : new FeedEntry(title, resolved, published, sourceUrl, sourceName);
⋮----
private static XElement? Child(XElement element, string localName) =>
element.Elements().FirstOrDefault(e => e.Name.LocalName == localName);
⋮----
internal static string Title(string? text)
⋮----
if (string.IsNullOrWhiteSpace(text))
⋮----
var plain = OneLine(WebUtility.HtmlDecode(Tags().Replace(text, " ")));
return plain.Length > CompetitorNewsItem.TitleLength ? plain[..CompetitorNewsItem.TitleLength].TrimEnd() : plain;
⋮----
private static string OneLine(string text) => Whitespace().Replace(text, " ").Trim();
⋮----
private static partial Regex Tags();
⋮----
private static partial Regex Whitespace();
... (26 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/NewsFeed.cs">
public static class NewsFeed
⋮----
public static IOrderedEnumerable<CompetitorNewsItem> InOrder(IEnumerable<CompetitorNewsItem> items) =>
items.OrderByDescending(item => item.SortAt).ThenByDescending(item => item.Id);
⋮----
public static bool Matches(CompetitorNewsItem item, NewsQuery query) =>
⋮----
&& (query.After is not { } after || after.Precedes(item));
⋮----
public static DateTimeOffset WeekStart(DateTimeOffset now)
⋮----
return new DateTimeOffset(day.AddDays(-sinceMonday), TimeSpan.Zero);
⋮----
public static NewsCursor After(CompetitorNewsItem item) => new(item.SortAt.ToUniversalTime(), item.Id);
⋮----
public string BeforeText => Before.UtcDateTime.ToString(Format, CultureInfo.InvariantCulture);
⋮----
public string IdText => Id.ToString("D", CultureInfo.InvariantCulture);
⋮----
public bool Precedes(CompetitorNewsItem item) =>
item.SortAt < Before || (item.SortAt == Before && item.Id.CompareTo(Id) < 0);
⋮----
public static bool TryParse(string? before, string? id, out NewsCursor? cursor)
⋮----
if (string.IsNullOrEmpty(before) && string.IsNullOrEmpty(id))
⋮----
if (!DateTimeOffset.TryParse(before, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var at)
|| !Guid.TryParse(id, out var after))
⋮----
cursor = new NewsCursor(at.ToUniversalTime(), after);
⋮----
public static readonly NewsPage Empty = new([], null);
⋮----
public static NewsPage Of(IReadOnlyList<CompetitorNewsItem> fetched, int take) =>
⋮----
? new NewsPage(fetched.Take(take).ToList(), NewsCursor.After(fetched[take - 1]))
: new NewsPage(fetched, null);
⋮----
public static NewsMark Marked(CompetitorNewsItem item) => new(NewsMarkOutcome.Marked, item);
⋮----
public static NewsMark Unchanged(CompetitorNewsItem item) => new(NewsMarkOutcome.Unchanged, item);
⋮----
public static readonly NewsMark NotFound = new(NewsMarkOutcome.NotFound, null);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/PositioningStatement.cs">
public sealed class PositioningStatement(IFeatureStateStore store, TimeProvider clock)
⋮----
public Task<StoredPositioning?> ReadAsync(CancellationToken cancellationToken = default) =>
⋮----
public async Task<PositioningSave> SaveAsync(string? read, string? typed, string savedBy, CancellationToken cancellationToken = default)
⋮----
var saved = new StoredPositioning(text, savedBy, clock.GetUtcNow());
if (!await store.SetIfAsync(Collection, Key, held, saved, cancellationToken))
⋮----
public static string Normalise(string? text) =>
(text ?? string.Empty).Replace("\r\n", "\n").Replace('\r', '\n').Trim();
⋮----
public static bool IsTooLong(string? text) => Normalise(text).Length > MaxLength;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/PostgresCompetitorStore.cs">
public sealed class PostgresCompetitorStore(ConsoleDbContext db) : ICompetitorStore
⋮----
private IQueryable<Competitor> Live => db.Competitors.Where(c => c.DeletedAt == null);
⋮----
public async Task<IReadOnlyList<Competitor>> ListAsync(CancellationToken cancellationToken = default) =>
await Live.AsNoTracking()
.OrderBy(c => c.Name.ToLower())
.ThenBy(c => c.Id)
.ToListAsync(cancellationToken);
⋮----
public async Task<Competitor?> FindAsync(Guid id, CancellationToken cancellationToken = default) =>
await Live.AsNoTracking().SingleOrDefaultAsync(c => c.Id == id, cancellationToken);
⋮----
public Task<CompetitorSave> AddAsync(Competitor competitor, CancellationToken cancellationToken = default) =>
⋮----
public async Task<CompetitorSave> AddAsync(Competitor competitor, IReadOnlyList<CompetitorSource> sources, CancellationToken cancellationToken = default)
⋮----
competitor.EnsureValid();
CompetitorSource.EnsureValidFor(competitor.Id, sources);
⋮----
return CompetitorSave.NameTaken(holder);
⋮----
var stored = competitor.Copy();
⋮----
db.Competitors.Add(stored);
⋮----
var rows = sources.Select(source => source.Copy()).ToList();
db.CompetitorSources.AddRange(rows);
⋮----
await db.SaveChangesAsync(cancellationToken);
⋮----
return CompetitorSave.Saved(stored, Competitor.AllFields);
⋮----
public Task<CompetitorSave> SaveAsync(
⋮----
public async Task<CompetitorSave> SaveAsync(
⋮----
var row = await Live.SingleOrDefaultAsync(c => c.Id == id, cancellationToken);
⋮----
return CompetitorSave.Stale(row.Copy());
⋮----
var before = row.Copy();
profile.CopyProfileTo(row);
row.EnsureValid();
⋮----
var changed = Competitor.Changes(before, row);
⋮----
return CompetitorSave.Unchanged(before);
⋮----
db.Entry(row).State = EntityState.Detached;
⋮----
return current is null ? CompetitorSave.NotFound : CompetitorSave.Stale(current);
⋮----
return CompetitorSave.Saved(row.Copy(), changed);
⋮----
public async Task<Competitor?> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
.Where(c => c.Id == id)
.ExecuteUpdateAsync(set => set.SetProperty(c => c.DeletedBy, by).SetProperty(c => c.DeletedAt, at), cancellationToken);
⋮----
: await db.Competitors.AsNoTracking().SingleOrDefaultAsync(c => c.Id == id, cancellationToken);
⋮----
public async Task<IReadOnlyList<Competitor>> DeletedAsync(CancellationToken cancellationToken = default) =>
await db.Competitors.AsNoTracking()
.Where(c => c.DeletedAt != null)
.OrderByDescending(c => c.DeletedAt)
.ThenBy(c => c.Name.ToLower())
⋮----
public async Task<CompetitorSave> RestoreAsync(Guid id, CancellationToken cancellationToken = default)
⋮----
var row = await db.Competitors.AsNoTracking().SingleOrDefaultAsync(c => c.Id == id && c.DeletedAt != null, cancellationToken);
⋮----
.Where(c => c.Id == id && c.DeletedAt != null)
.ExecuteUpdateAsync(
set => set.SetProperty(c => c.DeletedBy, (string?)null).SetProperty(c => c.DeletedAt, (DateTimeOffset?)null),
⋮----
return current is null ? CompetitorSave.NotFound : CompetitorSave.Saved(current, []);
⋮----
public async Task<IReadOnlyList<CompetitorSource>> SourcesAsync(Guid competitorId, CancellationToken cancellationToken = default)
⋮----
.AsNoTracking()
.Where(source => source.CompetitorId == competitorId)
⋮----
return CompetitorSource.Ordered(sources);
⋮----
public async Task<SourceAdd> AddSourceAsync(CompetitorSource source, CancellationToken cancellationToken = default)
⋮----
source.EnsureValid();
⋮----
return await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
⋮----
await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
⋮----
.Where(each => each.CompetitorId == source.CompetitorId)
⋮----
if (sources.FirstOrDefault(source.SameAs) is { } existing)
⋮----
return SourceAdd.Duplicate(existing);
⋮----
var stored = source.Copy();
... (170 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Competitors/ScanHealth.cs">
public static readonly TimeSpan Grace = TimeSpan.FromMinutes(5);
⋮----
public static readonly ScanHealth Well = new(false, false, 0, 0);
⋮----
public static ScanHealth Of(CompetitorScanRecord? last, bool running, bool scheduledToday, DateTimeOffset now, CompetitorScanOptions options)
⋮----
var local = TimeZoneInfo.ConvertTime(now, options.Zone);
var due = local.TimeOfDay >= options.At.ToTimeSpan() + Grace;
⋮----
return new ScanHealth(
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/AccountController.cs">
public sealed class AccountController : Controller
⋮----
private readonly ConsoleCredentials _credentials;
private readonly LoginThrottle _throttle;
private readonly IAuditLog _auditLog;
⋮----
public IActionResult Login(string? returnUrl = null) => LoginView(new LoginModel { ReturnUrl = returnUrl });
⋮----
public async Task<IActionResult> Login(LoginModel model)
⋮----
var name = string.IsNullOrWhiteSpace(model.Name) ? null : model.Name.Trim();
⋮----
if (_throttle.IsLockedOut(Caller, name, out var retryAfter))
⋮----
var minutes = Math.Max(1, (int)Math.Ceiling(retryAfter.TotalMinutes));
ModelState.AddModelError(
⋮----
var outcome = _credentials.Verify(name, model.Password);
⋮----
_throttle.RecordFailure(Caller, name);
⋮----
ModelState.AddModelError(nameof(LoginModel.Name), _text["Account.Login.EnterName"]);
⋮----
ModelState.AddModelError(string.Empty, _text["Account.Login.NotAccepted"]);
⋮----
_throttle.Reset(Caller, name);
⋮----
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, outcome.Actor!) },
⋮----
await HttpContext.SignInAsync(
⋮----
new ClaimsPrincipal(identity));
⋮----
public async Task<IActionResult> Logout()
⋮----
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
⋮----
public IActionResult Denied() =>
⋮----
private ViewResult LoginView(LoginModel model)
⋮----
private IActionResult SafeRedirect(string? returnUrl) =>
!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)
⋮----
private Task RecordSignInAsync(string actor, string action, bool succeeded, string? reason)
⋮----
var details = new Dictionary<string, string?> { ["succeeded"] = succeeded.ToString() };
⋮----
return _auditLog.RecordAsync(new AuditEntry(
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/AuditController.cs">
public sealed class AuditController(
⋮----
ILogger<AuditController> logger) : Controller
⋮----
/// <param name="kind">The action to list, such as <c>gateway:revoke</c>. Not called <c>action</c>, which is MVC's own route value.</param>
public async Task<IActionResult> Index(string? kind, string? target, int page = 1, CancellationToken cancellationToken = default)
⋮----
var everyone = (await authorization.AuthorizeAsync(User, ConsolePolicies.ReadEveryonesAudit)).Succeeded;
⋮----
if (!everyone && string.IsNullOrWhiteSpace(actor))
⋮----
var query = new AuditQuery(kind, target, Math.Clamp(page, 1, 100_000), PageSize, actor);
⋮----
var results = await trail.SearchAsync(query, cancellationToken);
var actions = await trail.ActionsAsync(actor, cancellationToken);
return View(new AuditLogPage(trail.Storage, query, results, actions, Unreadable: false));
⋮----
logger.LogError(ex, "The audit page could not read the audit log.");
return View(new AuditLogPage(trail.Storage, query, new AuditPage([], query.Page, PageSize, 0), [], Unreadable: true));
⋮----
public Dictionary<string, string> RouteValues(int page)
⋮----
var values = new Dictionary<string, string> { ["page"] = page.ToString(System.Globalization.CultureInfo.InvariantCulture) };
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/CultureController.cs">
public sealed class CultureController : Controller
⋮----
public IActionResult Set(string? culture, string? returnUrl)
⋮----
if (!ConsoleCultures.IsSupported(culture))
⋮----
Response.Cookies.Append(
⋮----
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture!)),
new CookieOptions
⋮----
Expires = DateTimeOffset.UtcNow.AddYears(1),
⋮----
return !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/ErrorController.cs">
public sealed class ErrorController : Controller
⋮----
public IActionResult Index(int statusCode = StatusCodes.Status500InternalServerError)
⋮----
// The 500's detail is deliberately thin: what failed is in the logs, under the correlation
// id below, and an error page is not the place to describe an application's internals to
// whoever provoked it.
⋮----
var model = new ErrorModel
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/HomeController.cs">
public sealed class HomeController : Controller
⋮----
public IActionResult Index()
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/NotificationsController.cs">
public sealed class NotificationsController(
⋮----
ILogger<NotificationsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(bool gone, CancellationToken cancellationToken)
⋮----
var name = ConsoleRoles.Normalise(User.Identity!.Name!);
⋮----
held = await store.ListAsync(name, Shown, cancellationToken);
⋮----
logger.LogError(ex, "The notifications could not be read.");
return View(new NotificationsPage([], Readable: false, Gone: gone, ConsoleRoles.IsAdmin(name)));
⋮----
content = await texts.RenderAsync(notification, cancellationToken);
⋮----
logger.LogError(ex, "The notification {Id} of the kind {Kind} could not be said.", notification.Id, notification.Kind);
⋮----
rows.Add(new NotificationRow(notification.Id, content, notification.CreatedAt, notification.IsRead));
⋮----
return View(new NotificationsPage(rows, Readable: true, Gone: gone, ConsoleRoles.IsAdmin(name)));
⋮----
public async Task<IActionResult> Open(Guid id, CancellationToken cancellationToken)
⋮----
var notification = await store.FindAsync(name, id, cancellationToken);
⋮----
await store.MarkReadAsync(name, id, clock.GetUtcNow(), CancellationToken.None);
⋮----
var content = await texts.RenderAsync(notification, cancellationToken);
⋮----
: LocalRedirect(Url.Content("~/" + content.Path));
⋮----
public async Task<IActionResult> MarkAllRead(CancellationToken cancellationToken)
⋮----
await store.MarkAllReadAsync(name, clock.GetUtcNow(), CancellationToken.None);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/NotificationSettingsController.cs">
public sealed class NotificationSettingsController(
⋮----
ILogger<NotificationSettingsController> logger) : Controller
⋮----
public async Task<IActionResult> Index(string? done, CancellationToken cancellationToken)
⋮----
var administrator = (await authorization.AuthorizeAsync(User, ConsolePolicies.ManageRoles)).Succeeded;
⋮----
if (!ConsoleRoles.IsAdmin(name))
⋮----
devices = await store.DevicesAsync(name, cancellationToken);
⋮----
logger.LogError(ex, "The notification devices could not be read.");
⋮----
return View(new NotificationSettingsPage(
IsAdmin: ConsoleRoles.IsAdmin(name),
⋮----
PublicKey: missing.Count == 0 ? vapid.PublicKey.Trim() : null,
⋮----
Devices: devices.Select(device => new DeviceRow(device.Id, device.Label, device.Service, device.CreatedAt, device.LastPushedAt)).ToList(),
⋮----
public async Task<IActionResult> Add(string? endpoint, string? p256dh, string? auth, CancellationToken cancellationToken)
⋮----
if (ConsoleRoles.IsAdmin(name) || !options.CurrentValue.IsConfigured)
⋮----
var now = clock.GetUtcNow();
var saved = await store.SaveDeviceAsync(new PushDevice
⋮----
Id = Guid.NewGuid(),
⋮----
Endpoint = endpoint!.Trim(),
P256dh = p256dh!.Trim(),
Auth = auth!.Trim(),
Label = PushDeviceLabel.From(Request.Headers.UserAgent.ToString()),
⋮----
public async Task<IActionResult> Remove(Guid id, CancellationToken cancellationToken)
⋮----
var held = (await store.DevicesAsync(name, cancellationToken)).FirstOrDefault(device => device.Id == id);
if (held is not null && await store.RemoveDeviceAsync(name, id, CancellationToken.None))
⋮----
return Request.Headers.Accept.ToString().Contains("application/json", StringComparison.Ordinal)
⋮----
public async Task<IActionResult> Test(CancellationToken cancellationToken)
⋮----
if (ConsoleRoles.IsAdmin(name))
⋮----
await notifier.NotifyAsync([name], ConsoleNotificationContent.Test, subjectId: null);
⋮----
private string Self => ConsoleRoles.Normalise(User.Identity!.Name!);
⋮----
private static bool IsEndpoint(string? endpoint) =>
⋮----
&& Uri.TryCreate(endpoint.Trim(), UriKind.Absolute, out var address)
⋮----
&& PublicAddress.IsFollowable(address);
⋮----
private static bool IsKey(string? value, int bytes)
⋮----
if (string.IsNullOrWhiteSpace(value) || value.Length > PushDevice.KeyLength)
⋮----
return WebEncoders.Base64UrlDecode(value.Trim()).Length == bytes;
⋮----
private Task RecordAsync(string action, PushDevice device, Dictionary<string, string?> details)
⋮----
details["device"] = device.Id.ToString("D", CultureInfo.InvariantCulture);
⋮----
return auditLog.RecordAsync(new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
Details: details.Where(pair => pair.Value is not null).ToDictionary(pair => pair.Key, pair => pair.Value)),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/OfflineController.cs">
public sealed class OfflineController : Controller
⋮----
public IActionResult Index()
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/PreferencesController.cs">
public sealed class PreferencesController(
⋮----
ILogger<PreferencesController> logger) : Controller
⋮----
public Task<IActionResult> Dashboard(bool saved, CancellationToken cancellationToken) =>
⋮----
public async Task<IActionResult> Save(string[]? areas, CancellationToken cancellationToken)
⋮----
if (areas.Any(key => OverviewArea.Find(key) is null))
⋮----
var viewable = (await ViewableAsync()).Select(area => area.Key).ToHashSet(StringComparer.Ordinal);
var posted = areas.Where(viewable.Contains).Distinct(StringComparer.Ordinal).ToList();
⋮----
DashboardOrder held;
⋮----
held = await preferences.OrderOfAsync(name, cancellationToken);
⋮----
order = DashboardPreferences.Arrange(posted.Concat(held.Areas));
⋮----
changed = await preferences.SetAsync(name, order, CancellationToken.None);
⋮----
logger.LogError(ex, "The dashboard order of {Name} could not be written; nothing changed.", name);
⋮----
public async Task<IActionResult> Reset(CancellationToken cancellationToken)
⋮----
changed = await preferences.ResetAsync(name, CancellationToken.None);
⋮----
logger.LogError(ex, "The dashboard order of {Name} could not be reset; nothing changed.", name);
⋮----
private async Task<IActionResult> PageAsync(string? problem, bool saved, CancellationToken cancellationToken)
⋮----
var order = await preferences.OrderOfAsync(User.Identity!.Name!, cancellationToken);
⋮----
.Select(key => viewable.FirstOrDefault(area => area.Key == key))
⋮----
.ToList();
⋮----
return View("Dashboard", new DashboardPreferencesPage(areas, order.Chosen, order.Readable, preferences.Storage, problem, saved && problem is null));
⋮----
private async Task<IReadOnlyList<OverviewArea>> ViewableAsync()
⋮----
if ((await authorization.AuthorizeAsync(User, area.ViewPolicy)).Succeeded)
⋮----
viewable.Add(area);
⋮----
private Task RecordAsync(string name, IReadOnlyList<string>? order, DashboardOrder held) =>
auditLog.RecordAsync(new AuditEntry(
⋮----
Target: ConsoleRoles.Normalise(name),
OccurredAt: clock.GetUtcNow(),
⋮----
["order"] = order is null ? "default" : string.Join(",", order),
["previous"] = held.Chosen ? string.Join(",", held.Areas) : "default",
</file>

<file path="src/KnowledgeFabric.AdminConsole/Controllers/UsersController.cs">
public sealed class UsersController(
⋮----
ILogger<UsersController> logger) : Controller
⋮----
public Task<IActionResult> Index(CancellationToken cancellationToken) => PageAsync(problem: null, cancellationToken);
⋮----
public Task<IActionResult> Grant(string? name, string? role, CancellationToken cancellationToken) =>
⋮----
public Task<IActionResult> Revoke(string? name, string? role, CancellationToken cancellationToken) =>
⋮----
public async Task<IActionResult> Initials(string? name, string? initials, CancellationToken cancellationToken)
⋮----
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > RoleGrant.NameLength)
⋮----
name = name.Trim();
⋮----
if (ConsoleRoles.IsAdmin(name))
⋮----
if (PersonInitials.Parse(initials) is not { } parsed)
⋮----
var key = ConsoleRoles.Normalise(name);
⋮----
held = (await roles.InitialsAsync(cancellationToken)).FirstOrDefault(row => row.Name == key)?.Initials ?? string.Empty;
⋮----
if (options.CurrentValue.PasswordFor(name) is null && held.Length == 0 && (await roles.RolesOfAsync(name, cancellationToken)).Count == 0)
⋮----
changed = await roles.SetInitialsAsync(name, parsed, User.Identity!.Name!, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "The initials of {Name} could not be written; nothing changed.", name);
⋮----
await auditLog.RecordAsync(new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
private async Task<IActionResult> ChangeAsync(string? name, string? role, bool grant, CancellationToken cancellationToken)
⋮----
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > RoleGrant.NameLength || !ConsoleRoles.IsRole(role))
⋮----
if (grant && options.CurrentValue.PasswordFor(name) is null)
⋮----
? await roles.GrantAsync(name, role!, User.Identity!.Name!, clock.GetUtcNow(), CancellationToken.None)
: await roles.RevokeAsync(name, role!, CancellationToken.None);
⋮----
logger.LogError(ex, "{Change} {Role} for {Name} could not be written; nothing changed.", grant ? "Granting" : "Revoking", role, name);
⋮----
grant ? text["Users.Problem.NotGranted", text.Role(role!), name] : text["Users.Problem.NotRevoked", text.Role(role!), name],
⋮----
Target: ConsoleRoles.Normalise(name),
⋮----
private async Task<IActionResult> PageAsync(string? problem, CancellationToken cancellationToken)
⋮----
grants = await roles.AllAsync(cancellationToken);
initials = await roles.InitialsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The Users page could not read the roles.");
⋮----
return View("Index", UsersPage.Build(roles.Storage, options.CurrentValue.Names, grants, unreadable, problem, initials));
⋮----
public static UsersPage Build(
⋮----
.Where(row => !ConsoleRoles.IsAdmin(row.Name))
.ToDictionary(row => row.Name, row => row.Initials, StringComparer.Ordinal);
⋮----
.GroupBy(grant => grant.Name, StringComparer.Ordinal)
.ToDictionary(group => group.Key, group => (IReadOnlyDictionary<string, RoleGrant>)group.ToDictionary(grant => grant.Role, StringComparer.Ordinal), StringComparer.Ordinal);
⋮----
var admin = configured.FirstOrDefault(ConsoleRoles.IsAdmin);
rows.Add(new UserRow(admin ?? ConsoleRoles.AdminName, HasSecret: admin is not null, IsAdmin: true, none));
⋮----
.Where(name => !ConsoleRoles.IsAdmin(name))
.Select(name => new UserRow(name, HasSecret: true, IsAdmin: false, held.GetValueOrDefault(ConsoleRoles.Normalise(name)) ?? none))
.ToList();
⋮----
var seen = others.Select(row => ConsoleRoles.Normalise(row.Name)).ToHashSet(StringComparer.Ordinal);
others.AddRange(held
.Where(pair => !seen.Contains(pair.Key) && !ConsoleRoles.IsAdmin(pair.Key))
.Select(pair => new UserRow(pair.Key, HasSecret: false, IsAdmin: false, pair.Value)));
⋮----
seen.UnionWith(held.Keys);
others.AddRange(initialsOf.Keys
.Where(name => !seen.Contains(name))
.Select(name => new UserRow(name, HasSecret: false, IsAdmin: false, none)));
⋮----
.Select(row => initialsOf.GetValueOrDefault(ConsoleRoles.Normalise(row.Name)) is { } own
⋮----
.Where(other => other != row && string.Equals(initialsOf.GetValueOrDefault(ConsoleRoles.Normalise(other.Name)), own, StringComparison.Ordinal))
.Select(other => other.Name)
.OrderBy(other => other, StringComparer.OrdinalIgnoreCase)
.ToList(),
⋮----
rows.AddRange(others.OrderBy(row => row.Name, StringComparer.OrdinalIgnoreCase));
⋮----
return new UsersPage(storage, rows, unreadable, problem);
⋮----
public bool Holds(string role) => Grants.ContainsKey(role);
⋮----
public string? IncludedBy(string role)
⋮----
return ConsoleRoles.IncludedBy(role) is { } including && Holds(including) ? including : null;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/BusinessCardOptions.cs">
public sealed class BusinessCardOptions
⋮----
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/BusinessCardQr.cs">
public static BusinessCardQr? Of(string? decoded)
⋮----
if (string.IsNullOrEmpty(text) || text.Length > MaxLength)
⋮----
var link = !text.Any(char.IsWhiteSpace)
&& Uri.TryCreate(text, UriKind.Absolute, out var uri)
⋮----
return new BusinessCardQr(text, link);
⋮----
&& (link.IdnHost.Equals("linkedin.com", StringComparison.OrdinalIgnoreCase) || link.IdnHost.EndsWith(".linkedin.com", StringComparison.OrdinalIgnoreCase))
&& link.AbsolutePath.StartsWith("/in/", StringComparison.OrdinalIgnoreCase)
⋮----
/// <summary>What the model is told beside the photo: the text, or the link and what its page says.</summary>
public string ForModel(LinkedPage? page)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/BusinessCardReader.cs">
public static readonly BusinessCard Blank = new("", "", "", "", "", "", "", "");
⋮----
/// <summary>
/// What the contact's <em>Notes</em> start as: the website and the address, a line each and
/// unlabelled, since neither is a field of the contact and both say what they are.
/// </summary>
public string Notes => string.Join("\n", new[] { Website, Address }.Where(line => line.Length > 0));
⋮----
public interface IBusinessCardReader
⋮----
Task<BusinessCardReading> ReadAsync(byte[] image, string? qrCode = null, CancellationToken cancellationToken = default);
⋮----
public sealed partial class OllamaBusinessCardReader(
⋮----
: IBusinessCardReader
⋮----
public bool IsConfigured => ollama.Value.IsConfigured && !string.IsNullOrWhiteSpace(options.Value.Model);
⋮----
public string? Model => IsConfigured ? options.Value.Model!.Trim() : null;
⋮----
public async Task<BusinessCardReading> ReadAsync(byte[] image, string? qrCode = null, CancellationToken cancellationToken = default)
⋮----
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(account.BaseAddress!, ChatPath))
⋮----
Content = new StringContent(Body(options.Value.Model!.Trim(), image, qrCode).ToJsonString(), Encoding.UTF8, "application/json"),
⋮----
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", account.ApiKey!.Trim());
⋮----
HttpResponseMessage response;
⋮----
response = await http.SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("Ollama could not be reached to read a business card: {Failure}.", ex.GetType().Name);
⋮----
var body = await response.Content.ReadAsStringAsync(cancellationToken);
⋮----
logger.LogWarning(
⋮----
logger.LogWarning("Ollama's answer to a business card was not a reading of one.");
⋮----
internal static JsonObject Body(string model, byte[] image, string? qrCode = null)
⋮----
var properties = new JsonObject();
⋮----
properties[field] = new JsonObject { ["type"] = "string" };
⋮----
return new JsonObject
⋮----
["format"] = new JsonObject
⋮----
["required"] = new JsonArray(Fields.Select(field => (JsonNode)JsonValue.Create(field)!).ToArray()),
⋮----
["options"] = new JsonObject { ["temperature"] = 0 },
⋮----
["messages"] = new JsonArray(new JsonNode?[]
⋮----
new JsonObject { ["role"] = "system", ["content"] = Instructions },
new JsonObject
⋮----
["images"] = new JsonArray(new JsonNode?[] { JsonValue.Create(Convert.ToBase64String(image)) }),
⋮----
internal static BusinessCard? Parse(string answer)
⋮----
var content = JsonNode.Parse(answer)?["message"]?["content"]?.GetValue<string>();
⋮----
var start = content.IndexOf('{');
var end = content.LastIndexOf('}');
⋮----
if (JsonNode.Parse(content[start..(end + 1)]) is not JsonObject fields)
⋮----
return new BusinessCard(
⋮----
Email: Field("email").Replace(" ", ""),
⋮----
internal static string LinkedIn(string printed)
⋮----
if (printed.Length == 0 || !printed.Contains("linkedin.com", StringComparison.OrdinalIgnoreCase))
⋮----
: "https://" + printed.TrimStart('/');
⋮----
private static string OneLine(string text) => Whitespace().Replace(text, " ").Trim();
⋮----
private static string ErrorOf(string body)
⋮----
error = JsonNode.Parse(body)?["error"]?.GetValue<string>();
⋮----
private static partial Regex Whitespace();
⋮----
public static class BusinessCardImage
⋮----
public static bool IsPhoto(ReadOnlySpan<byte> bytes) =>
bytes.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xD8, 0xFF])
|| bytes.StartsWith((ReadOnlySpan<byte>)[0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A]);
⋮----
public static string MediaType(ReadOnlySpan<byte> bytes) => bytes.Length > 0 && bytes[0] == 0x89 ? "image/png" : "image/jpeg";
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/BusinessCardRegistration.cs">
public static class BusinessCardRegistration
⋮----
public static IServiceCollection AddBusinessCards(this IServiceCollection services, IConfiguration configuration)
⋮----
services.Configure<BusinessCardOptions>(configuration.GetSection(BusinessCardOptions.SectionName));
⋮----
.RemoveAllLoggers();
⋮----
http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; KnowledgeFabricAdmin/1.0; +business card)");
⋮----
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
⋮----
ConnectTimeout = TimeSpan.FromSeconds(5),
⋮----
ActivityHeadersPropagator = DistributedContextPropagator.CreateNoOutputPropagator(),
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/Contact.cs">
public sealed class Contact
⋮----
public bool IsOverdue(DateOnly today) => NextAction is not null && NextActionDue < today;
⋮----
public static string NormaliseName(string name) => name.Trim().ToLowerInvariant();
⋮----
public Contact Copy() => (Contact)MemberwiseClone();
⋮----
public static class CrmWords
⋮----
public static string DisplayName(this ContactStage stage, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Stage.{stage}"];
⋮----
public static string DisplayName(this ContactTrack track, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Track.{track}"];
⋮----
public static string DisplayName(this ContactEntity entity, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Entity.{entity}"];
⋮----
public static string DisplayName(this Engagement engagement, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Engagement.{engagement}"];
⋮----
public static string DisplayName(this DeclineReason reason, IStringLocalizer<ConsoleResource> text) => text[$"Crm.DeclineReason.{reason}"];
⋮----
public static string DisplayName(this InteractionKind kind, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Kind.{kind}"];
⋮----
public static string DisplayName(this Silence silence, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Silence.{silence}"];
⋮----
public static string DisplayName(this FollowUpDue due, IStringLocalizer<ConsoleResource> text) => text[$"Crm.Due.{due}"];
⋮----
public static DateOnly Since(this Silence silence, DateOnly today) => silence switch
⋮----
Silence.Week => today.AddDays(-7),
Silence.Month => today.AddMonths(-1),
Silence.ThreeMonths => today.AddMonths(-3),
⋮----
public static string SheetDate(DateOnly day) => day.ToString("dd.MM.yy", System.Globalization.CultureInfo.InvariantCulture);
⋮----
public static string MetLine(Interaction interaction, IStringLocalizer<ConsoleResource> text) => $"{interaction.Kind.DisplayName(text)} {SheetDate(interaction.OccurredOn)}";
⋮----
public static string WithLine(Interaction interaction) => string.Join(", ", interaction.Participants);
⋮----
public static string? NextLine(Contact contact, IStringLocalizer<ConsoleResource> text) =>
⋮----
public static TEnum? Parse<TEnum>(string? value) where TEnum : struct, Enum =>
!string.IsNullOrWhiteSpace(value) && Enum.TryParse<TEnum>(value.Trim(), ignoreCase: true, out var parsed) && Enum.IsDefined(parsed)
⋮----
public static Engagement? ParseEngagement(string? value) =>
int.TryParse(value?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var number) && Enum.IsDefined((Engagement)number) ? (Engagement)number : null;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/ContactChange.cs">
public sealed class ContactChange
⋮----
public static ContactChange Of(Contact contact, ContactChangeKind kind, string by, DateTimeOffset at) => new()
⋮----
public static (ContactStage, ContactTrack, DeclineReason?, ContactEntity?) Counted(Contact contact) =>
⋮----
public ContactChange Copy() => (ContactChange)MemberwiseClone();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/ContactRegisterRegistration.cs">
public static class ContactRegisterRegistration
⋮----
public static IServiceCollection AddCrmContacts(
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
else if (environment.IsDevelopment())
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/CrmActivity.cs">
public int Total => Weeks.Sum(week => week.Total);
⋮----
public static DateOnly WeekOf(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7));
⋮----
public static DateOnly From(DateOnly today) => WeekOf(today).AddDays(-7 * (WeekCount - 1));
⋮----
public static CrmActivity Compute(IEnumerable<InteractionSummary> interactions, DateOnly today)
⋮----
.Where(interaction => interaction.OccurredOn >= from && interaction.OccurredOn <= WeekOf(today).AddDays(6))
.GroupBy(interaction => (Week: WeekOf(interaction.OccurredOn), interaction.Kind))
.ToDictionary(group => group.Key, group => group.Count());
⋮----
return new CrmActivity(Enumerable.Range(0, WeekCount)
.Select(i => from.AddDays(7 * i))
.Select(week => new ActivityWeek(week, CrmWords.Kinds.Select(kind => (kind, counts.GetValueOrDefault((week, kind)))).ToList()))
.ToList());
⋮----
public DateOnly Ends => Starts.AddDays(6);
⋮----
public int Total => ByKind.Sum(line => line.Count);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/CrmCsv.cs">
public static class CrmCsv
⋮----
public static byte[] Zip(IReadOnlyList<Contact> contacts, IReadOnlyList<Interaction> interactions)
⋮----
using var buffer = new MemoryStream();
using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
⋮----
return buffer.ToArray();
⋮----
public static string ContactsText(IReadOnlyList<Contact> contacts)
⋮----
var csv = new StringBuilder();
csv.Append(Line(ContactColumns));
⋮----
csv.Append(Line(
⋮----
contact.Id.ToString(),
⋮----
contact.Track.ToString(),
contact.Stage.ToString(),
contact.Engagement is { } engagement ? ((int)engagement).ToString(CultureInfo.InvariantCulture) : string.Empty,
⋮----
return csv.ToString();
⋮----
public static string InteractionsText(IReadOnlyList<Contact> contacts, IReadOnlyList<Interaction> interactions)
⋮----
var names = contacts.ToDictionary(contact => contact.Id, contact => contact.Name);
⋮----
csv.Append(Line(InteractionColumns));
⋮----
interaction.ContactId.ToString(),
names.GetValueOrDefault(interaction.ContactId, string.Empty),
⋮----
interaction.Kind.ToString(),
string.Join(";", interaction.Participants),
⋮----
public static (IReadOnlyList<CsvRecord>? Records, string? Problem) Read(string text, string file, IReadOnlyList<string> columns, IStringLocalizer<ConsoleResource> words)
⋮----
var header = rows[0].Values.Select(name => name.Trim()).ToArray();
⋮----
var unknown = header.Where(name => !columns.Contains(name, StringComparer.Ordinal)).ToArray();
⋮----
return (null, words["Crm.Csv.UnknownColumn", file, string.Join(", ", unknown.Select(name => name.Length == 0 ? words["Crm.Csv.Blank"].Value : name)), string.Join(", ", columns)]);
⋮----
var twice = header.GroupBy(name => name, StringComparer.Ordinal).Where(group => group.Count() > 1).Select(group => group.Key).ToArray();
⋮----
return (null, words["Crm.Csv.ColumnTwice", file, string.Join(", ", twice)]);
⋮----
var missing = columns.Where(name => Required.Contains(name) && !header.Contains(name, StringComparer.Ordinal)).ToArray();
⋮----
return (null, words["Crm.Csv.MissingColumn", file, string.Join(", ", missing)]);
⋮----
if (columns.Contains("contact") && !header.Contains("contact") && !header.Contains("contact_id"))
⋮----
foreach (var row in rows.Skip(1))
⋮----
if (row.Values.All(value => value.Length == 0))
⋮----
records.Add(new CsvRecord(row.Line, header.Zip(row.Values).ToDictionary(pair => pair.First, pair => pair.Second, StringComparer.Ordinal)));
⋮----
private static (List<(int Line, List<string> Values)>? Rows, string? Problem) Parse(string text, IStringLocalizer<ConsoleResource> words)
⋮----
var value = new StringBuilder();
⋮----
value.Append('"');
⋮----
value.Append(c);
⋮----
values.Add(Unescape(value.ToString(), wasQuoted));
value.Clear();
⋮----
rows.Add((rowStarts, values));
⋮----
private static string Unescape(string value, bool quoted)
⋮----
value = value.Trim();
⋮----
return value.StartsWith('\'') ? value[1..] : value;
⋮----
private static string Line(IEnumerable<string> fields) => string.Join(",", fields.Select(Field)) + "\r\n";
⋮----
private static string Field(string value)
⋮----
if (value.Length > 0 && "=+-@\t\r'".Contains(value[0]))
⋮----
return value.IndexOfAny([',', '"', '\r', '\n']) >= 0 || value != value.Trim()
? "\"" + value.Replace("\"", "\"\"") + "\""
⋮----
private static string Iso(DateOnly? day) => day?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? string.Empty;
⋮----
private static void Add(ZipArchive zip, string name, string text)
⋮----
using var writer = new StreamWriter(zip.CreateEntry(name).Open(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
writer.Write(text);
⋮----
public string this[string column] => Values.GetValueOrDefault(column, string.Empty);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/CrmFunnel.cs">
public static CrmFunnel Compute(IReadOnlyCollection<ContactSummary> contacts)
⋮----
List<ContactSummary> In(IReadOnlyList<ContactStage> stages) => contacts.Where(contact => stages.Contains(contact.Stage)).ToList();
⋮----
.Select(track => (track, accepted.Count(contact => contact.Track == track)))
.Where(line => line.track != ContactTrack.Undecided || line.Item2 > 0)
.OrderBy(line => line.track switch { ContactTrack.BusinessPartner => 0, ContactTrack.Ambassador => 1, _ => 2 })
.ToList();
⋮----
.Select(reason => ((DeclineReason?)reason, declined.Count(contact => contact.DeclineReason == reason)))
.Append((null, declined.Count(contact => contact.DeclineReason is null)))
.Where(line => line.Item1 is not null || line.Item2 > 0)
⋮----
return new CrmFunnel(
⋮----
public double? OfConcluded(int count) => Concluded == 0 ? null : (double)count / Concluded;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/CrmHistory.cs">
public sealed class CrmHistory
⋮----
public static CrmHistory Of(IReadOnlyList<ContactChange> changes) =>
⋮----
changes.OrderBy(change => change.Id).ToList(),
changes.Count == 0 ? null : DayOf(changes.Min(change => change.ChangedAt)));
⋮----
public IReadOnlyList<ContactSummary> AsOf(DateOnly day)
⋮----
.Where(change => change.Live)
.Select(change => new ContactSummary(change.ContactId, change.Stage, change.Track, false, null, null, change.DeclineReason, change.Entity))
.ToList();
⋮----
public IReadOnlyDictionary<Guid, ContactTrack> Tracks()
⋮----
internal static IEnumerable<TChange> Replayed<TChange>(
⋮----
var ends = new DateTimeOffset(day.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
⋮----
if (stopped.Contains(row(change)))
⋮----
stopped.Add(row(change));
⋮----
public IReadOnlyList<(DateOnly Day, CrmFunnel Funnel)> Series(DateOnly through) =>
⋮----
? Days(began, through).Select(day => (day, CrmFunnel.Compute(AsOf(day)))).ToList()
⋮----
public static IReadOnlyList<DateOnly> Days(DateOnly began, DateOnly through)
⋮----
? began.AddDays(((int)DayOfWeek.Sunday - (int)began.DayOfWeek + 7) % 7)
: new DateOnly(began.Year, began.Month, 1).AddMonths(1).AddDays(-1);
⋮----
days.Add(next);
⋮----
next = weekly ? next.AddDays(7) : new DateOnly(next.Year, next.Month, 1).AddMonths(2).AddDays(-1);
⋮----
days.Add(through);
⋮----
public static bool IsWeekly(DateOnly began, DateOnly through) => through.DayNumber - began.DayNumber <= WeeklyUpTo * 7;
⋮----
private static DateOnly DayOf(DateTimeOffset instant) => DateOnly.FromDateTime(instant.UtcDateTime);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/FollowUpReminders.cs">
public sealed class FollowUpReminderOptions
⋮----
public DateOnly DayOf(DateTimeOffset instant) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(instant, Zone).DateTime);
⋮----
public DateTimeOffset StartOf(DateOnly day)
⋮----
var midnight = day.ToDateTime(TimeOnly.MinValue, DateTimeKind.Unspecified);
return new DateTimeOffset(midnight, Zone.GetUtcOffset(midnight));
⋮----
private static TimeZoneInfo? Find(string? name)
⋮----
if (string.IsNullOrWhiteSpace(name))
⋮----
return TimeZoneInfo.FindSystemTimeZoneById(name.Trim());
⋮----
public sealed class FollowUpReminders(
⋮----
public static bool IsDue(Contact contact, DateOnly day) =>
contact.NextAction is not null && (contact.NextActionDue == day || contact.NextActionDue == day.AddDays(-1));
⋮----
public async Task<int> RemindAsync(DateOnly day, CancellationToken cancellationToken = default)
⋮----
var told = (await notifications.RecipientsAsync(Kind, options.Value.StartOf(day), cancellationToken)).ToHashSet(StringComparer.Ordinal);
var served = (await people.CrmAsync(cancellationToken)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
var followUps = await register.FollowUpsAsync(new FollowUpQuery { Today = day }, cancellationToken);
⋮----
.Where(contact => IsDue(contact, day) && !string.IsNullOrWhiteSpace(contact.NextActionOwner))
.Select(contact => ConsoleRoles.Normalise(contact.NextActionOwner!))
.Where(owner => ConsolePeople.IsPerson(owner) && served.Contains(owner) && !told.Contains(owner))
.Distinct(StringComparer.Ordinal)
.ToList();
⋮----
var count = await notifier.NotifyAsync(owners, Kind, subjectId: null);
⋮----
logger.LogInformation("{Count} people were reminded of their follow-ups for {Day}.", count, day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
⋮----
public sealed class FollowUpReminderJob(
⋮----
private readonly SemaphoreSlim _gate = new(1, 1);
⋮----
public async Task<int?> RunIfDueAsync(CancellationToken cancellationToken = default)
⋮----
await _gate.WaitAsync(cancellationToken);
⋮----
var local = TimeZoneInfo.ConvertTime(clock.GetUtcNow(), settings.Zone);
var today = DateOnly.FromDateTime(local.DateTime);
⋮----
if (_ranOn == today || TimeOnly.FromDateTime(local.DateTime) < settings.At)
⋮----
await using var scope = scopes.CreateAsyncScope();
var told = await scope.ServiceProvider.GetRequiredService<FollowUpReminders>().RemindAsync(today, cancellationToken);
⋮----
_gate.Release();
⋮----
public sealed class FollowUpReminderLoop(FollowUpReminderJob job, ILogger<FollowUpReminderLoop> logger) : BackgroundService
⋮----
public static readonly TimeSpan Every = TimeSpan.FromMinutes(1);
⋮----
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
⋮----
await job.RunIfDueAsync(stoppingToken);
⋮----
logger.LogError(ex, "The follow-up reminders could not run; they are tried again in a minute.");
⋮----
await Task.Delay(Every, stoppingToken);
⋮----
public sealed class FollowUpNotificationContent(
⋮----
IStringLocalizer<ConsoleResource> text) : INotificationContent
⋮----
public bool Renders(string kind) => kind == FollowUpReminders.Kind;
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default)
⋮----
if (!ConsolePeople.IsPerson(notification.Recipient))
⋮----
_served ??= (await people.CrmAsync(cancellationToken)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
if (!_served.Contains(notification.Recipient))
⋮----
var day = options.Value.DayOf(notification.CreatedAt);
var actions = (await register.FollowUpsAsync(new FollowUpQuery { Owner = notification.Recipient, Today = day }, cancellationToken))
.Where(contact => FollowUpReminders.IsDue(contact, day))
⋮----
var lines = actions.Take(Named).Select(contact =>
⋮----
var body = string.Join("; ", lines);
⋮----
return new NotificationContent(title, body, Path);
⋮----
public static class FollowUpReminderRegistration
⋮----
public static IServiceCollection AddFollowUpReminders(this IServiceCollection services, IConfiguration configuration)
⋮----
services.Configure<FollowUpReminderOptions>(configuration.GetSection(FollowUpReminderOptions.SectionName));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/FollowUps.cs">
public static FollowUpQuery From(string? owner, string? mine, string? due, string signedInAs, DateOnly today)
⋮----
var isMine = bool.TryParse(mine?.Trim(), out var parsed) && parsed;
⋮----
Owner = isMine ? signedInAs : string.IsNullOrWhiteSpace(owner) ? null : owner.Trim(),
⋮----
public DateOnly WeekEnds => Today.AddDays(6);
⋮----
public bool Matches(Contact contact) =>
⋮----
&& (Owner is null || string.Equals(contact.NextActionOwner, Owner, StringComparison.OrdinalIgnoreCase))
⋮----
public Dictionary<string, string> RouteValues()
⋮----
values["due"] = due.ToString();
⋮----
public static IOrderedEnumerable<Contact> Order(IEnumerable<Contact> contacts) =>
⋮----
.OrderBy(contact => contact.NextActionDue is null)
.ThenBy(contact => contact.NextActionDue)
.ThenBy(contact => contact.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(contact => contact.CreatedAt);
⋮----
public static ContactSummary Of(Contact contact) =>
⋮----
public static CrmStatistics Compute(IReadOnlyCollection<ContactSummary> contacts, IReadOnlyCollection<IntroductionSummary> introductions, DateOnly today)
⋮----
var week = new FollowUpQuery { Today = today }.WeekEnds;
var followUps = contacts.Where(contact => contact.HasNextAction).ToList();
⋮----
return new CrmStatistics(
⋮----
CrmWords.Stages.Select(stage => (stage, contacts.Count(contact => contact.Stage == stage))).ToList(),
CrmWords.Tracks.Select(track => (track, contacts.Count(contact => contact.Track == track))).ToList(),
CrmWords.Entities.Select(entity => (ContactEntity?)entity).Append(null)
.Select(entity => (entity, contacts.Count(contact => contact.Entity == entity))).ToList(),
⋮----
followUps.Count(contact => contact.NextActionDue >= today && contact.NextActionDue <= week),
followUps.Count(contact => contact.NextActionDue < today),
followUps.Count(contact => contact.NextActionDue is null),
⋮----
IntroductionWords.Stages.Select(stage => (stage, introductions.Count(introduction => introduction.Stage == stage))).ToList());
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/IContactRegister.cs">
public interface IContactRegister
⋮----
Task<IReadOnlyList<Contact>> SearchAsync(ContactQuery query, CancellationToken cancellationToken = default);
⋮----
Task<Contact?> FindAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Contact>> FollowUpsAsync(FollowUpQuery query, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<ContactSummary>> SummariesAsync(CancellationToken cancellationToken = default);
⋮----
Task<Contact> AddAsync(Contact contact, CancellationToken cancellationToken = default);
⋮----
Task<ContactSave> SaveAsync(Guid id, uint version, Action<Contact> change, string by, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<string>> ImportAsync(IReadOnlyList<Contact> contacts, IReadOnlyList<Interaction> interactions, CancellationToken cancellationToken = default);
⋮----
Task<bool> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Contact>> DeletedAsync(CancellationToken cancellationToken = default);
⋮----
Task<Contact?> RestoreAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<ContactChange>> ChangesAsync(CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlySet<string>> SharedNamesAsync(CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Interaction>> InteractionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<InteractionSummary>> InteractionSummariesAsync(DateOnly from, CancellationToken cancellationToken = default);
⋮----
Task<InteractionSave> AddInteractionAsync(Interaction interaction, CancellationToken cancellationToken = default);
⋮----
Task<InteractionSave> SaveInteractionAsync(
⋮----
Task<InteractionSave> DeleteInteractionAsync(Guid contactId, Guid id, uint version, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Introduction>> IntroductionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<IntroductionSummary>> IntroductionSummariesAsync(CancellationToken cancellationToken = default);
⋮----
Task<IntroductionSave> AddIntroductionAsync(Introduction introduction, CancellationToken cancellationToken = default);
⋮----
Task<IntroductionSave> SaveIntroductionAsync(
⋮----
Task<IReadOnlyList<IntroductionChange>> IntroductionChangesAsync(CancellationToken cancellationToken = default);
⋮----
public static ContactSave Saved(Contact contact) => new(ContactSaveOutcome.Saved, contact);
⋮----
public static ContactSave Stale(Contact current) => new(ContactSaveOutcome.Stale, current);
⋮----
public static readonly ContactSave NotFound = new(ContactSaveOutcome.NotFound, null);
⋮----
public static InteractionSave Saved(Interaction interaction) => new(ContactSaveOutcome.Saved, interaction);
⋮----
public static InteractionSave Stale(Interaction current) => new(ContactSaveOutcome.Stale, current);
⋮----
public static readonly InteractionSave NotFound = new(ContactSaveOutcome.NotFound, null);
⋮----
public static readonly ContactQuery All = new();
⋮----
public static ContactQuery From(string? q, string? stage, string? track, string? by, string? e, string? since, string? entity, DateOnly today)
⋮----
var entityNotSaid = string.Equals(entity?.Trim(), NotSaid, StringComparison.OrdinalIgnoreCase);
⋮----
Text = string.IsNullOrWhiteSpace(q) ? null : q.Trim(),
⋮----
OriginatedBy = string.IsNullOrWhiteSpace(by) ? null : by.Trim(),
EngagementAtLeast = CrmWords.ParseEngagement(e),
⋮----
public bool Matches(Contact contact, DateOnly? lastInteraction = null) =>
⋮----
&& (OriginatedBy is null || string.Equals(contact.OriginatedBy, OriginatedBy, StringComparison.OrdinalIgnoreCase))
⋮----
public Dictionary<string, string> RouteValues()
⋮----
values["stage"] = stage.ToString();
⋮----
values["track"] = track.ToString();
⋮----
values["entity"] = entity.ToString();
⋮----
values["e"] = ((int)engagement).ToString();
⋮----
values["since"] = silence.ToString();
⋮----
private static bool Has(string? value, string term) => value?.Contains(term, StringComparison.OrdinalIgnoreCase) ?? false;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/InMemoryContactRegister.cs">
public sealed class InMemoryContactRegister : IContactRegister
⋮----
private IEnumerable<Contact> Live => _rows.Values.Where(row => row.DeletedAt is null);
⋮----
private Contact? LiveRow(Guid id) => _rows.TryGetValue(id, out var row) && row.DeletedAt is null ? row : null;
⋮----
public Task<IReadOnlyList<Contact>> SearchAsync(ContactQuery query, CancellationToken cancellationToken = default)
⋮----
.GroupBy(interaction => interaction.ContactId)
.ToDictionary(group => group.Key, group => group.Max(interaction => interaction.OccurredOn));
⋮----
.Where(row => query.Matches(row, last.TryGetValue(row.Id, out var day) ? day : null))
.OrderBy(row => row.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(row => row.CreatedAt)
.Select(row => row.Copy())
.ToList());
⋮----
public Task<Contact?> FindAsync(Guid id, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(LiveRow(id)?.Copy());
⋮----
public Task<IReadOnlyList<Contact>> FollowUpsAsync(FollowUpQuery query, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult<IReadOnlyList<Contact>>(FollowUpQuery.Order(Live.Where(query.Matches))
⋮----
public Task<IReadOnlyList<ContactSummary>> SummariesAsync(CancellationToken cancellationToken = default)
⋮----
return Task.FromResult<IReadOnlyList<ContactSummary>>(Live.Select(ContactSummary.Of).ToList());
⋮----
public Task<Contact> AddAsync(Contact contact, CancellationToken cancellationToken = default)
⋮----
var stored = contact.Copy();
⋮----
Record(ContactChange.Of(stored, ContactChangeKind.Created, stored.CreatedBy, stored.CreatedAt));
return Task.FromResult(stored.Copy());
⋮----
public Task<ContactSave> SaveAsync(Guid id, uint version, Action<Contact> change, string by, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(ContactSave.NotFound);
⋮----
return Task.FromResult(ContactSave.Stale(row.Copy()));
⋮----
var changed = row.Copy();
⋮----
if (ContactChange.Counted(changed) != ContactChange.Counted(row))
⋮----
Record(ContactChange.Of(changed, ContactChangeKind.Updated, by, at));
⋮----
return Task.FromResult(ContactSave.Saved(changed.Copy()));
⋮----
public Task<IReadOnlyList<string>> ImportAsync(IReadOnlyList<Contact> contacts, IReadOnlyList<Interaction> interactions, CancellationToken cancellationToken = default)
⋮----
var names = Live.Select(row => Contact.NormaliseName(row.Name)).ToHashSet(StringComparer.Ordinal);
⋮----
.Where(contact => _rows.ContainsKey(contact.Id) || names.Contains(Contact.NormaliseName(contact.Name)))
.Select(contact => contact.Name)
.ToList();
⋮----
Record(ContactChange.Of(stored, ContactChangeKind.Imported, stored.CreatedBy, stored.CreatedAt));
⋮----
var stored = interaction.Copy();
⋮----
public Task<bool> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(false);
⋮----
var deleted = row.Copy();
⋮----
Record(ContactChange.Of(deleted, ContactChangeKind.Deleted, by, at));
⋮----
return Task.FromResult(true);
⋮----
public Task<IReadOnlyList<Contact>> DeletedAsync(CancellationToken cancellationToken = default)
⋮----
.Where(row => row.DeletedAt is not null)
.OrderByDescending(row => row.DeletedAt)
.ThenBy(row => row.Name, StringComparer.OrdinalIgnoreCase)
⋮----
public Task<Contact?> RestoreAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
if (!_rows.TryGetValue(id, out var row) || row.DeletedAt is null)
⋮----
var restored = row.Copy();
⋮----
Record(ContactChange.Of(restored, ContactChangeKind.Restored, by, at));
⋮----
return Task.FromResult<Contact?>(restored.Copy());
⋮----
public Task<IReadOnlyList<ContactChange>> ChangesAsync(CancellationToken cancellationToken = default)
⋮----
.Select(change => change.Copy())
⋮----
private void Record(ContactChange change)
⋮----
_changes.Add(change);
⋮----
private void Record(IntroductionChange change)
⋮----
_introductionChanges.Add(change);
⋮----
... (125 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/Interaction.cs">
public sealed class Interaction
⋮----
public Interaction Copy()
⋮----
public static InteractionSummary Of(Interaction interaction) => new(interaction.OccurredOn, interaction.Kind);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/Introduction.cs">
public sealed class Introduction
⋮----
public static string NormaliseCustomer(string customer) => customer.Trim().ToLowerInvariant();
⋮----
public Introduction Copy() => (Introduction)MemberwiseClone();
⋮----
public static class IntroductionWords
⋮----
public static string DisplayName(this IntroductionStage stage, IStringLocalizer<ConsoleResource> text) => text[$"Crm.IntroductionStage.{stage}"];
⋮----
public sealed class IntroductionChange
⋮----
public static IntroductionChange Of(Introduction introduction, ContactChangeKind kind, bool live, string by, DateTimeOffset at) => new()
⋮----
public IntroductionChange Copy() => (IntroductionChange)MemberwiseClone();
⋮----
public static IntroductionSummary Of(Introduction introduction) => new(introduction.Id, introduction.ContactId, introduction.Stage);
⋮----
public static IntroductionSave Saved(Introduction introduction) => new(ContactSaveOutcome.Saved, introduction);
⋮----
public static IntroductionSave Stale(Introduction current) => new(ContactSaveOutcome.Stale, current);
⋮----
public static readonly IntroductionSave NotFound = new(ContactSaveOutcome.NotFound, null);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/IntroductionFunnel.cs">
public static IntroductionFunnel Compute(
⋮----
ContactTrack TrackOf(IntroductionSummary introduction) => tracks.GetValueOrDefault(introduction.ContactId, ContactTrack.Undecided);
⋮----
stages.Contains(introduction.Stage)
|| (reached.TryGetValue(introduction.Id, out var stood) && stages.Any(stood.Contains));
⋮----
.Select(track => (track, introductions.Count(introduction => TrackOf(introduction) == track)))
.Where(line => line.track != ContactTrack.Undecided || line.Item2 > 0)
.OrderBy(line => line.track switch { ContactTrack.BusinessPartner => 0, ContactTrack.Ambassador => 1, _ => 2 })
.ToList();
⋮----
return new IntroductionFunnel(
⋮----
IntroductionWords.Stages.Select(stage => (stage, introductions.Count(introduction => introduction.Stage == stage))).ToList(),
⋮----
introductions.Count(introduction => Reached(introduction, PilotOrFurther)),
introductions.Count(introduction => Reached(introduction, ContractOrFurther)));
⋮----
public int At(IntroductionStage stage) => ByStage.Single(line => line.Stage == stage).Count;
⋮----
public double? OfIntroduced(int count) => Introduced == 0 ? null : (double)count / Introduced;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/IntroductionHistory.cs">
public sealed class IntroductionHistory
⋮----
public static readonly DateOnly Created = new(2026, 10, 22);
⋮----
public static IntroductionHistory Of(IReadOnlyList<IntroductionChange> changes)
⋮----
var first = changes.Count == 0 ? Created : DateOnly.FromDateTime(changes.Min(change => change.ChangedAt).UtcDateTime);
return new(changes.OrderBy(change => change.Id).ToList(), first < Created ? first : Created);
⋮----
public IReadOnlyList<IntroductionSummary> AsOf(DateOnly day)
⋮----
.Where(change => change.Live)
.Select(change => new IntroductionSummary(change.IntroductionId, change.ContactId, change.Stage))
.ToList();
⋮----
public IReadOnlyDictionary<Guid, IReadOnlySet<IntroductionStage>> Reached(DateOnly? day)
⋮----
if (!reached.TryGetValue(change.IntroductionId, out var stages))
⋮----
stages.Add(change.Stage);
⋮----
return reached.ToDictionary(pair => pair.Key, pair => (IReadOnlySet<IntroductionStage>)pair.Value);
⋮----
public IReadOnlyList<IntroductionPoint> Series(DateOnly through) =>
⋮----
? CrmHistory.Days(Began, through).Select(day =>
⋮----
return new IntroductionPoint(day, introductions.Count, introductions.Count(introduction => introduction.Stage == IntroductionStage.UnderContract));
}).ToList()
⋮----
private IEnumerable<IntroductionChange> Through(DateOnly? day) => day is { } end
? CrmHistory.Replayed(_changes, change => change.IntroductionId, change => change.ChangedAt, end)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/LinkedPageReader.cs">
public interface ILinkedPageReader
⋮----
Task<LinkedPage> ReadAsync(Uri link, CancellationToken cancellationToken = default);
⋮----
public sealed partial class HttpLinkedPageReader(HttpClient http, ILogger<HttpLinkedPageReader> logger) : ILinkedPageReader
⋮----
public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
⋮----
public async Task<LinkedPage> ReadAsync(Uri link, CancellationToken cancellationToken = default)
⋮----
using var unrecorded = SuppressInstrumentationScope.Begin();
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
⋮----
if (!PublicAddress.IsFollowable(at))
⋮----
logger.LogInformation("A business card's QR code leads to an address the console does not follow.");
⋮----
using var request = new HttpRequestMessage(HttpMethod.Get, at);
request.Headers.Accept.ParseAdd("text/html, application/xhtml+xml, text/vcard, text/plain;q=0.8");
request.Headers.AcceptLanguage.ParseAdd("en, it;q=0.9");
⋮----
HttpResponseMessage response;
⋮----
response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
⋮----
catch (HttpRequestException ex) when (NotPublicAddressException.In(ex))
⋮----
logger.LogInformation("A business card's QR code leads to a name that is not a public address.");
⋮----
logger.LogInformation("A business card's QR code could not be followed: {Failure}.", ex.GetType().Name);
⋮----
logger.LogInformation("A business card's QR code redirected {Status} with no address, or too often.", (int)response.StatusCode);
⋮----
at = location.IsAbsoluteUri ? location : new Uri(at, location);
⋮----
logger.LogInformation("A business card's QR code led to a page that answered {Status}.", (int)response.StatusCode);
⋮----
if (!Readable.Contains(type))
⋮----
logger.LogInformation("A business card's QR code led to {Type}, which is not read.", type.Length == 0 ? "(no type)" : type);
⋮----
logger.LogInformation("A business card's QR code's page stopped answering: {Failure}.", ex.GetType().Name);
⋮----
var text = PageText.Of(type, body);
⋮----
private static bool IsRedirect(HttpStatusCode status) =>
⋮----
/// <summary>At most <see cref="MaxBytes"/> of the answer, in its own character set, or UTF-8.</summary>
private static async Task<string> BodyAsync(HttpContent content, CancellationToken cancellationToken)
⋮----
await using var stream = await content.ReadAsStreamAsync(cancellationToken);
⋮----
while (length < buffer.Length && (read = await stream.ReadAsync(buffer.AsMemory(length), cancellationToken)) > 0)
⋮----
return EncodingOf(content.Headers.ContentType).GetString(buffer, 0, length);
⋮----
private static Encoding EncodingOf(MediaTypeHeaderValue? type)
⋮----
return type?.CharSet is { Length: > 0 } charset ? Encoding.GetEncoding(charset.Trim('"')) : Encoding.UTF8;
⋮----
public static partial class PageText
⋮----
public static string Of(string mediaType, string body)
⋮----
private static string OfHtml(string html)
⋮----
var said = new StringBuilder();
⋮----
if (Title().Match(html) is { Success: true } title)
⋮----
foreach (Match meta in Meta().Matches(html))
⋮----
if (name is not null && content is not null && Describes(name.ToLowerInvariant()))
⋮----
foreach (Match data in StructuredData().Matches(html))
⋮----
var links = Links().Matches(html)
.Select(link => Decode(link.Groups[1].Value))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(20)
.ToList();
⋮----
Append(said, "Links", string.Join(" ", links));
⋮----
var words = Whitespace().Replace(Hidden().Replace(html, " "), " ");
words = Breaks().Replace(words, "\n");
words = Decode(Tags().Replace(words, " "));
⋮----
said.Append("Text:\n").Append(text);
⋮----
return said.ToString().Trim();
⋮----
private static bool Describes(string name) =>
⋮----
|| name.StartsWith("og:", StringComparison.Ordinal)
|| name.StartsWith("profile:", StringComparison.Ordinal)
|| name.StartsWith("business:", StringComparison.Ordinal)
⋮----
private static void Append(StringBuilder said, string label, string value)
... (39 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/PostgresContactRegister.cs">
public sealed class PostgresContactRegister(ConsoleDbContext db) : IContactRegister
⋮----
private IQueryable<Contact> Live => db.Contacts.Where(c => c.DeletedAt == null);
⋮----
private IQueryable<Interaction> LiveInteractions => db.Interactions.Where(i => Live.Any(c => c.Id == i.ContactId));
⋮----
private IQueryable<Introduction> LiveIntroductions => db.Introductions.Where(i => i.DeletedAt == null && Live.Any(c => c.Id == i.ContactId));
⋮----
public async Task<IReadOnlyList<Contact>> SearchAsync(ContactQuery query, CancellationToken cancellationToken = default)
⋮----
var rows = Live.AsNoTracking();
⋮----
var pattern = "%" + term.Replace(@"\", @"\\").Replace("%", @"\%").Replace("_", @"\_") + "%";
⋮----
rows = rows.Where(c =>
EF.Functions.ILike(c.Name, pattern, @"\")
|| EF.Functions.ILike(c.Headline ?? "", pattern, @"\")
|| EF.Functions.ILike(c.Organisation ?? "", pattern, @"\")
|| EF.Functions.ILike(c.Presentation ?? "", pattern, @"\"));
⋮----
rows = rows.Where(c => c.Stage == stage);
⋮----
rows = rows.Where(c => c.Track == track);
⋮----
rows = rows.Where(c => c.Entity == entity);
⋮----
rows = rows.Where(c => c.Entity == null);
⋮----
var key = by.ToLowerInvariant();
rows = rows.Where(c => c.OriginatedBy.ToLower() == key);
⋮----
rows = rows.Where(c => c.Engagement >= engagement);
⋮----
rows = rows.Where(c => !db.Interactions.Any(i => i.ContactId == c.Id && i.OccurredOn >= quietFrom));
⋮----
.OrderBy(c => c.Name.ToLower())
.ThenBy(c => c.CreatedAt)
.ToListAsync(cancellationToken);
⋮----
public Task<Contact?> FindAsync(Guid id, CancellationToken cancellationToken = default) =>
Live.AsNoTracking().SingleOrDefaultAsync(c => c.Id == id, cancellationToken);
⋮----
public async Task<IReadOnlyList<Contact>> FollowUpsAsync(FollowUpQuery query, CancellationToken cancellationToken = default)
⋮----
var rows = Live.AsNoTracking().Where(c => c.NextAction != null);
⋮----
var key = owner.ToLowerInvariant();
rows = rows.Where(c => c.NextActionOwner != null && c.NextActionOwner.ToLower() == key);
⋮----
FollowUpDue.Overdue => rows.Where(c => c.NextActionDue < today),
FollowUpDue.Week => rows.Where(c => c.NextActionDue >= today && c.NextActionDue <= weekEnds),
⋮----
.OrderBy(c => c.NextActionDue == null)
.ThenBy(c => c.NextActionDue)
.ThenBy(c => c.Name.ToLower())
⋮----
public async Task<IReadOnlyList<ContactSummary>> SummariesAsync(CancellationToken cancellationToken = default) =>
⋮----
.AsNoTracking()
.Select(c => new ContactSummary(c.Id, c.Stage, c.Track, c.NextAction != null, c.NextActionOwner, c.NextActionDue, c.DeclineReason, c.Entity))
⋮----
public async Task<Contact> AddAsync(Contact contact, CancellationToken cancellationToken = default)
⋮----
var created = ContactChange.Of(contact, ContactChangeKind.Created, contact.CreatedBy, contact.CreatedAt);
db.Contacts.Add(contact);
db.ContactChanges.Add(created);
⋮----
await db.SaveChangesAsync(cancellationToken);
⋮----
db.Entry(contact).State = EntityState.Detached;
⋮----
public async Task<ContactSave> SaveAsync(Guid id, uint version, Action<Contact> change, string by, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
var row = await Live.SingleOrDefaultAsync(c => c.Id == id, cancellationToken);
⋮----
db.Entry(row).State = EntityState.Detached;
return ContactSave.Stale(row);
⋮----
var before = ContactChange.Counted(row);
⋮----
var updated = ContactChange.Counted(row) == before ? null : ContactChange.Of(row, ContactChangeKind.Updated, by, at);
⋮----
db.ContactChanges.Add(updated);
⋮----
return current is null ? ContactSave.NotFound : ContactSave.Stale(current);
⋮----
return ContactSave.Saved(row);
⋮----
public async Task<IReadOnlyList<string>> ImportAsync(IReadOnlyList<Contact> contacts, IReadOnlyList<Interaction> interactions, CancellationToken cancellationToken = default)
⋮----
var ids = contacts.Select(contact => contact.Id).ToArray();
var names = contacts.Select(contact => Contact.NormaliseName(contact.Name)).Distinct().ToArray();
⋮----
return await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
⋮----
db.ChangeTracker.Clear();
⋮----
await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
⋮----
await db.Database.ExecuteSqlRawAsync("LOCK TABLE crm_contacts IN SHARE ROW EXCLUSIVE MODE", cancellationToken);
... (151 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Crm/PublicAddress.cs">
public static class PublicAddress
⋮----
private static readonly IPAddress AzurePlatform = IPAddress.Parse("168.63.129.16");
⋮----
public static bool IsFollowable(Uri link) =>
⋮----
&& !link.IdnHost.Equals("localhost", StringComparison.OrdinalIgnoreCase)
&& !link.IdnHost.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase)
&& (!IPAddress.TryParse(link.IdnHost.Trim('[', ']'), out var address) || IsPublic(address));
⋮----
public static bool IsPublic(IPAddress address)
⋮----
address = address.MapToIPv4();
⋮----
private static bool IsPublicV4(IPAddress address)
⋮----
if (address.Equals(AzurePlatform))
⋮----
var b = address.GetAddressBytes();
⋮----
private static bool IsPublicV6(IPAddress address)
⋮----
if (address.Equals(IPAddress.IPv6Any) || address.Equals(IPAddress.IPv6Loopback)
⋮----
if (b.Take(12).All(part => part == 0))
⋮----
return IsPublicV4(new IPAddress(b[12..16]));
⋮----
return IsPublicV4(new IPAddress(b[2..6]));
⋮----
public static async ValueTask<Stream> ConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
⋮----
var addresses = IPAddress.TryParse(host, out var literal)
⋮----
: await Dns.GetHostAddressesAsync(host, cancellationToken);
⋮----
if (addresses.Length == 0 || !addresses.All(IsPublic))
⋮----
throw new NotPublicAddressException();
⋮----
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
⋮----
await socket.ConnectAsync(addresses, context.DnsEndPoint.Port, cancellationToken);
return new NetworkStream(socket, ownsSocket: true);
⋮----
socket.Dispose();
⋮----
public sealed class NotPublicAddressException() : Exception("The address is not a public one.")
⋮----
public static bool In(Exception exception)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Data/ConsoleDbContext.cs">
public sealed class ConsoleDbContext(DbContextOptions<ConsoleDbContext> options) : DbContext(options)
⋮----
protected override void OnModelCreating(ModelBuilder modelBuilder)
⋮----
licence.ToTable("issued_licences");
licence.HasKey(r => r.RecordId);
⋮----
licence.Property(r => r.RecordId).HasColumnName("record_id");
licence.Property(r => r.LicenseId).HasColumnName("license_id");
licence.Property(r => r.CustomerName).HasColumnName("customer_name");
licence.Property(r => r.CustomerEmail).HasColumnName("customer_email");
licence.Property(r => r.Company).HasColumnName("company");
licence.Property(r => r.LicenseType).HasColumnName("license_type");
licence.Property(r => r.Tier).HasColumnName("tier");
licence.Property(r => r.SchemaVersion).HasColumnName("schema_version");
licence.Property(r => r.ValidFromUtc).HasColumnName("valid_from");
licence.Property(r => r.ExpirationUtc).HasColumnName("expiration");
licence.Property(r => r.IssuedBy).HasColumnName("issued_by");
licence.Property(r => r.IssuedByLogin).HasColumnName("issued_by_login");
licence.Property(r => r.IssuedAtUtc).HasColumnName("issued_at");
licence.Property(r => r.RecordedAtUtc).HasColumnName("recorded_at");
licence.Property(r => r.Sha256).HasColumnName("sha256").HasMaxLength(64);
licence.Property(r => r.LicenseXml).HasColumnName("license_xml");
⋮----
licence.Property(r => r.Features).HasColumnName("features").HasColumnType("jsonb")
.HasConversion(DictionaryAsJson.Converter, DictionaryAsJson.Comparer);
licence.Property(r => r.Attributes).HasColumnName("attributes").HasColumnType("jsonb")
⋮----
licence.HasIndex(r => r.LicenseId).HasDatabaseName("ix_issued_licences_license_id");
⋮----
licence.HasIndex(r => r.Sha256).IsUnique().HasDatabaseName("ux_issued_licences_sha256");
⋮----
licence.HasIndex(r => r.IssuedAtUtc).HasDatabaseName("ix_issued_licences_issued_at");
⋮----
audit.ToTable("audit_entries");
audit.HasKey(e => e.Id);
⋮----
audit.Property(e => e.Id).HasColumnName("id").UseIdentityAlwaysColumn();
audit.Property(e => e.OccurredAt).HasColumnName("occurred_at");
audit.Property(e => e.Actor).HasColumnName("actor").HasMaxLength(128);
audit.Property(e => e.Attributable).HasColumnName("attributable");
audit.Property(e => e.ClaimedActor).HasColumnName("claimed_actor").HasMaxLength(128);
audit.Property(e => e.Action).HasColumnName("action").HasMaxLength(128);
audit.Property(e => e.Target).HasColumnName("target").HasMaxLength(256);
audit.Property(e => e.CorrelationId).HasColumnName("correlation_id").HasMaxLength(128);
audit.Property(e => e.ClientAddress).HasColumnName("client_address").HasMaxLength(64);
audit.Property(e => e.Details).HasColumnName("details").HasColumnType("jsonb")
.HasConversion(DetailsAsJson.Converter, DetailsAsJson.Comparer);
⋮----
audit.HasIndex(e => e.OccurredAt).HasDatabaseName("ix_audit_entries_occurred_at");
audit.HasIndex(e => e.Action).HasDatabaseName("ix_audit_entries_action");
audit.HasIndex(e => e.Target).HasDatabaseName("ix_audit_entries_target");
⋮----
grant.ToTable("console_roles");
grant.HasKey(g => new { g.Name, g.Role });
⋮----
grant.Property(g => g.Name).HasColumnName("name").HasMaxLength(RoleGrant.NameLength);
grant.Property(g => g.Role).HasColumnName("role").HasMaxLength(RoleGrant.RoleLength);
grant.Property(g => g.GrantedBy).HasColumnName("granted_by").HasMaxLength(RoleGrant.NameLength);
grant.Property(g => g.GrantedAt).HasColumnName("granted_at");
⋮----
initials.ToTable("console_initials");
initials.HasKey(i => i.Name);
⋮----
initials.Property(i => i.Name).HasColumnName("name").HasMaxLength(RoleGrant.NameLength);
initials.Property(i => i.Initials).HasColumnName("initials").HasMaxLength(PersonInitials.Length);
initials.Property(i => i.SetBy).HasColumnName("set_by").HasMaxLength(RoleGrant.NameLength);
initials.Property(i => i.SetAt).HasColumnName("set_at");
⋮----
contact.ToTable("crm_contacts");
contact.HasKey(c => c.Id);
⋮----
contact.Property(c => c.Id).HasColumnName("id");
contact.Property(c => c.Name).HasColumnName("name").HasMaxLength(Contact.NameLength);
contact.Property(c => c.Headline).HasColumnName("headline").HasMaxLength(Contact.HeadlineLength);
contact.Property(c => c.Organisation).HasColumnName("organisation").HasMaxLength(Contact.OrganisationLength);
contact.Property(c => c.Email).HasColumnName("email").HasMaxLength(Contact.EmailLength);
contact.Property(c => c.Phone).HasColumnName("phone").HasMaxLength(Contact.PhoneLength);
contact.Property(c => c.LinkedInUrl).HasColumnName("linkedin_url").HasMaxLength(Contact.UrlLength);
contact.Property(c => c.Presentation).HasColumnName("presentation").HasMaxLength(Contact.PresentationLength);
⋮----
contact.Property(c => c.Track).HasColumnName("track").HasConversion<string>().HasMaxLength(32);
contact.Property(c => c.Stage).HasColumnName("stage").HasConversion<string>().HasMaxLength(32);
contact.Property(c => c.DeclineReason).HasColumnName("decline_reason").HasConversion<string>().HasMaxLength(32);
contact.Property(c => c.Entity).HasColumnName("entity").HasConversion<string>().HasMaxLength(32);
⋮----
contact.Property(c => c.Engagement).HasColumnName("engagement");
contact.Property(c => c.OriginatedBy).HasColumnName("originated_by").HasMaxLength(Contact.PersonLength);
contact.Property(c => c.Notes).HasColumnName("notes");
⋮----
contact.Property(c => c.NextAction).HasColumnName("next_action").HasMaxLength(Contact.NextActionLength);
contact.Property(c => c.NextActionOwner).HasColumnName("next_action_owner").HasMaxLength(Contact.PersonLength);
contact.Property(c => c.NextActionDue).HasColumnName("next_action_due");
contact.Property(c => c.CreatedBy).HasColumnName("created_by").HasMaxLength(Contact.PersonLength);
contact.Property(c => c.CreatedAt).HasColumnName("created_at");
contact.Property(c => c.UpdatedBy).HasColumnName("updated_by").HasMaxLength(Contact.PersonLength);
contact.Property(c => c.UpdatedAt).HasColumnName("updated_at");
⋮----
contact.Property(c => c.DeletedBy).HasColumnName("deleted_by").HasMaxLength(Contact.PersonLength);
contact.Property(c => c.DeletedAt).HasColumnName("deleted_at");
... (505 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Data/DatabaseMigrator.cs">
internal sealed class DatabaseMigrator(
⋮----
ILogger<DatabaseMigrator> logger) : IHostedLifecycleService
⋮----
public async Task StartingAsync(CancellationToken cancellationToken)
⋮----
logger.LogInformation("Database migration on startup is off; the schema is assumed to be current.");
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
await database.OpenConnectionAsync(cancellationToken);
⋮----
await database.ExecuteSqlRawAsync("SELECT pg_advisory_lock({0})", [MigrationLockKey], cancellationToken);
⋮----
await database.MigrateAsync(cancellationToken);
⋮----
await database.ExecuteSqlRawAsync("SELECT pg_advisory_unlock({0})", [MigrationLockKey], cancellationToken);
⋮----
await database.CloseConnectionAsync();
⋮----
logger.LogInformation("Database schema is current.");
⋮----
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StartedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Data/DatabaseOptions.cs">
public sealed class DatabaseOptions
⋮----
public bool IsConfigured => !string.IsNullOrWhiteSpace(ConnectionString);
⋮----
internal bool NamesAHostAndDatabase()
⋮----
var builder = new NpgsqlConnectionStringBuilder(ConnectionString);
return !string.IsNullOrWhiteSpace(builder.Host) && !string.IsNullOrWhiteSpace(builder.Database);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Data/DesignTimeConsoleDbContextFactory.cs">
internal sealed class DesignTimeConsoleDbContextFactory : IDesignTimeDbContextFactory<ConsoleDbContext>
⋮----
public ConsoleDbContext CreateDbContext(string[] args) =>
⋮----
.UseNpgsql("Host=design-time;Database=kf_admin")
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayAdminClient.cs">
public sealed class GatewayAdminClient(HttpClient http, IOptions<GatewayOptions> options, IStringLocalizer<ConsoleResource> text, ILogger<GatewayAdminClient> logger)
⋮----
private static readonly JsonSerializerOptions Wire = new(JsonSerializerDefaults.Web)
⋮----
public async Task<GatewayAnswer> InstallationsHoldingAsync(Guid licenceId, CancellationToken cancellationToken = default)
⋮----
return answer.Outcome == GatewayOutcome.Answered && answer.Installations.Any(installation => installation.LicenceId != licenceId)
? GatewayAnswer.Of(GatewayOutcome.NoLicenceIds)
⋮----
public async Task<GatewayAnswer> SharedAsync(CancellationToken cancellationToken = default)
⋮----
return answer.Outcome == GatewayOutcome.Answered && answer.Installations.Any(installation => installation.LicenceId is null)
⋮----
public async Task<GatewayAnswer> LicensedInstallationsAsync(CancellationToken cancellationToken = default)
⋮----
var answer = await EveryAsync(new InstallationQuery { Row = row }, text["Gateway.Client.OnRow", row.ToString().ToLowerInvariant()], cancellationToken);
⋮----
installations.TryAdd(installation.InstallationId, installation);
⋮----
return new GatewayAnswer(GatewayOutcome.Answered, installations.Values.ToList(), Detail: null) { Total = installations.Count };
⋮----
public Task<GatewayAnswer> ActiveBelowAsync(string version, CancellationToken cancellationToken = default) =>
InstallationQuery.IsVersion(version)
? EveryAsync(new InstallationQuery { AppVersionBelow = version.Trim(), Revoked = false }, text["Gateway.Client.Below", version.Trim()], cancellationToken)
: Task.FromResult(GatewayAnswer.Of(GatewayOutcome.RequestRefused, $"\"{version}\" is not a version the gateway reads."));
⋮----
private async Task<GatewayAnswer> EveryAsync(InstallationQuery query, string described, CancellationToken cancellationToken)
⋮----
logger.LogError(
⋮----
return GatewayAnswer.Of(
⋮----
text["Gateway.Client.TooMany", (MaxPagesWalked * MaxLimit).ToString("N0", CultureInfo.CurrentCulture), described]);
⋮----
public async Task<GatewayAnswer> InstallationsAsync(InstallationQuery query, CancellationToken cancellationToken = default)
⋮----
var answer = await ListAsync($"{InstallationsPath}?{query.QueryString()}", cancellationToken);
⋮----
logger.LogInformation("The gateway answered {Path} without {Header}: it predates kf-ai-gateway#38 and ignored its filters.", InstallationsPath, TotalHeader);
return GatewayAnswer.Of(GatewayOutcome.NotReported);
⋮----
return query.LicenceId is { } licenceId && answer.Installations.Any(installation => installation.LicenceId != licenceId)
⋮----
public async Task<GatewayInstallationAnswer> InstallationAsync(Guid installationId, CancellationToken cancellationToken = default)
⋮----
return GatewayInstallationAnswer.Of(reply.Outcome, reply.Detail);
⋮----
? GatewayInstallationAnswer.Of(GatewayOutcome.Unreachable, text["Gateway.Client.NotInstallation"])
: new GatewayInstallationAnswer(GatewayOutcome.Answered, installation, Detail: null);
⋮----
public async Task<GatewayStatusAnswer> StatusAsync(CancellationToken cancellationToken = default)
⋮----
return GatewayStatusAnswer.Of(outcome, detail);
⋮----
return GatewayStatusAnswer.Of(reply.Outcome, reply.Detail);
⋮----
? GatewayStatusAnswer.Of(GatewayOutcome.Unreachable, text["Gateway.Client.NotStatus"])
: new GatewayStatusAnswer(GatewayOutcome.Answered, status, Detail: null);
⋮----
public Task<GatewayInstallationAnswer> RevokeAsync(Guid installationId, string operatorName, CancellationToken cancellationToken = default) =>
⋮----
public Task<GatewayInstallationAnswer> RestoreAsync(Guid installationId, string operatorName, CancellationToken cancellationToken = default) =>
⋮----
public static bool IsOperatorName(string? name) =>
!string.IsNullOrWhiteSpace(name) && name.Length <= MaxOperatorLength && !name.Any(char.IsControl);
⋮----
private async Task<GatewayInstallationAnswer> ChangeAsync(Guid installationId, string verb, string operatorName, CancellationToken cancellationToken)
⋮----
return GatewayInstallationAnswer.Of(GatewayOutcome.RequestRefused, text["Gateway.Client.OperatorName", MaxOperatorLength]);
⋮----
return GatewayInstallationAnswer.Of(GatewayOutcome.UnknownInstallation);
⋮----
? GatewayInstallationAnswer.Of(GatewayOutcome.Unreachable, text["Gateway.Client.ChangedNotInstallation"])
⋮----
public async Task<GatewayPolicyAnswer> PolicyAsync(CancellationToken cancellationToken = default)
⋮----
return GatewayPolicyAnswer.Of(outcome, detail);
⋮----
return GatewayPolicyAnswer.Of(tiers.Outcome, tiers.Detail);
⋮----
logger.LogWarning("The gateway answered {TiersPath} but 404 for {Path}.", TiersPath, PolicyPath);
return GatewayPolicyAnswer.Of(GatewayOutcome.NotReported);
⋮----
return GatewayPolicyAnswer.Of(policy.Outcome, policy.Detail);
⋮----
? GatewayPolicyAnswer.Of(GatewayOutcome.Unreachable, text["Gateway.Client.NotPolicy"])
: new GatewayPolicyAnswer(GatewayOutcome.Answered, levers, rows, Detail: null);
⋮----
public async Task<GatewayWriteAnswer<GatewayPolicy>> ChangePolicyAsync(GatewayPolicy policy, string operatorName, CancellationToken cancellationToken = default)
⋮----
return GatewayWriteAnswer<GatewayPolicy>.Of(reply.Outcome, reply.Detail);
⋮----
? GatewayWriteAnswer<GatewayPolicy>.Of(GatewayOutcome.Unreachable, text["Gateway.Client.ChangedNotPolicyRow"])
⋮----
public async Task<GatewayWriteAnswer<GatewayTier>> ChangeTierAsync(
⋮----
var tier = row.ToString().ToLowerInvariant();
⋮----
return GatewayWriteAnswer<GatewayTier>.Of(reply.Outcome, reply.Detail);
⋮----
... (164 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayEnrolmentWatch.cs">
public sealed class GatewayEnrolmentWatch(
⋮----
public async Task<GatewayEnrolments> CheckAsync(CancellationToken cancellationToken = default)
⋮----
var licensed = await client.LicensedInstallationsAsync(cancellationToken);
⋮----
var held = await state.GetAsync<GatewayEnrolmentState>(Collection, Key, cancellationToken) ?? new GatewayEnrolmentState();
⋮----
var recipients = newLicences.Count + newTrials.Count > 0 ? await people.GatewayAsync(CancellationToken.None) : [];
⋮----
await state.SetAsync(Collection, Key, seen, cancellationToken);
⋮----
return newLicences.Count + newTrials.Count == 0 ? GatewayEnrolments.None : new GatewayEnrolments(newLicences, newTrials);
⋮----
private static (GatewayEnrolmentState Seen, IReadOnlyList<Guid> New) Licences(GatewayEnrolmentState held, IReadOnlyList<GatewayInstallation> installations)
⋮----
.Where(installation => installation.LicenceId is not null)
.GroupBy(installation => installation.LicenceId!.Value)
.OrderBy(licence => licence.Min(installation => installation.CreatedAt))
.ThenBy(licence => licence.Key)
.Select(licence => licence.Key)
.ToList();
⋮----
var known = held.Licences.ToHashSet();
var fresh = holding.Where(licence => !known.Contains(licence)).ToList();
⋮----
return fresh.Count == 0 ? (held, []) : (held with { Licences = Sorted(held.Licences.Concat(fresh)) }, fresh);
⋮----
private async Task<(GatewayEnrolmentState Seen, IReadOnlyList<Guid> New)?> TrialsAsync(GatewayEnrolmentState held, CancellationToken cancellationToken)
⋮----
var page = await client.InstallationsAsync(
new InstallationQuery { Row = InstallationRow.Evaluation, Limit = TrialPage, Offset = offset }, cancellationToken);
⋮----
rows.TryAdd(installation.InstallationId, installation);
⋮----
var reachedMark = since is { } mark && page.Installations.Any(installation => installation.CreatedAt < mark);
⋮----
logger.LogWarning(
⋮----
var atMark = held.TrialsAtMark.ToHashSet();
⋮----
.Where(installation => since is not { } mark || installation.CreatedAt > mark
|| (installation.CreatedAt == mark && !atMark.Contains(installation.InstallationId)))
.OrderBy(installation => installation.CreatedAt)
.ThenBy(installation => installation.InstallationId)
.Select(installation => installation.InstallationId)
.ToList()
⋮----
var newest = rows.Values.Select(installation => (DateTimeOffset?)installation.CreatedAt).Max();
⋮----
var nextAtMark = rows.Values.Where(installation => installation.CreatedAt == nextMark).Select(installation => installation.InstallationId);
⋮----
nextAtMark = nextAtMark.Concat(held.TrialsAtMark);
⋮----
private async Task TellAsync(IReadOnlyList<string> recipients, string kind, IReadOnlyList<Guid> subjects, string what)
⋮----
told += await notifier.NotifyAsync(recipients, kind, subject);
⋮----
logger.LogInformation("{Count} {What}: {Told} notifications written ({Kind}).", subjects.Count, what, told, kind);
⋮----
private static IReadOnlyList<Guid> Sorted(IEnumerable<Guid> ids) => ids.Distinct().Order().ToList();
⋮----
public static readonly GatewayEnrolments None = new([], []);
⋮----
public bool Equals(GatewayEnrolmentState? other) =>
⋮----
&& TrialsAtMark.SequenceEqual(other.TrialsAtMark)
&& (Licences is null ? other.Licences is null : other.Licences is not null && Licences.SequenceEqual(other.Licences));
⋮----
public override int GetHashCode() => HashCode.Combine(TrialsRead, TrialsSince, TrialsAtMark.Count, Licences?.Count);
⋮----
public sealed class GatewayEnrolmentNotificationContent(
⋮----
ILogger<GatewayEnrolmentNotificationContent> logger) : INotificationContent
⋮----
public bool Renders(string kind) => GatewayEnrolmentWatch.Kinds.Contains(kind, StringComparer.Ordinal);
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default)
⋮----
_people ??= (await people.GatewayAsync(cancellationToken)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
if (!_people.Contains(notification.Recipient) || notification.SubjectId is not { } subject)
⋮----
return new NotificationContent(
⋮----
var shortId = subject.ToString("D")[..8];
var body = names.TryGetValue(subject, out var row)
⋮----
return new NotificationContent(text["Notifications.Gateway.NewLicence.Title"].Value, body, $"Gateway/Installations?q={subject:D}");
⋮----
private async Task<(IReadOnlyDictionary<Guid, RegisterSummary> Names, bool Read)> RegisterAsync(CancellationToken cancellationToken)
⋮----
return (RegisterSummary.LatestByLicence(await register.SummariesAsync(cancellationToken)), true);
⋮----
logger.LogWarning(ex, "The register could not be read to say a new licence on the gateway; it is said by its id.");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayInstallation.cs">
public bool IsLicensed => string.Equals(Tier, "licensed", StringComparison.OrdinalIgnoreCase);
⋮----
public bool IsRejected => string.Equals(Status, "rejected", StringComparison.OrdinalIgnoreCase);
⋮----
public int Percent => Limit > 0 ? (int)Math.Min(100, Math.Max(0, Used) * 100 / Limit) : 100;
⋮----
public string? CountryCode => Country is { Length: 2 } code && code.All(char.IsAsciiLetter) ? code.ToUpperInvariant() : null;
⋮----
public sealed class GatewayLocationConverter : JsonConverter<GatewayLocation>
⋮----
public override GatewayLocation? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
⋮----
public override void Write(Utf8JsonWriter writer, GatewayLocation value, JsonSerializerOptions options)
⋮----
writer.WriteNullValue();
⋮----
JsonSerializer.Serialize(writer, value, options);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayOptions.cs">
public sealed class GatewayOptions
⋮----
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
⋮----
public bool IsConfigured => !string.IsNullOrWhiteSpace(AdminToken) && BaseAddress is not null;
⋮----
public bool CanWrite => IsConfigured && !string.IsNullOrWhiteSpace(AdminWriteToken);
⋮----
if (string.IsNullOrWhiteSpace(BaseUrl)
|| !Uri.TryCreate(BaseUrl.Trim().TrimEnd('/') + "/", UriKind.Absolute, out var address))
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayPolicy.cs">
/// <summary>
/// The five levers <c>PUT /admin/tiers/{tier}</c> writes, every one of them (#71): the gateway
/// refuses <c>tier</c> and <c>installations_served</c> in the body, since the path names the row
/// and the count is counted.
/// </summary>
/// <param name="BudgetPeriod">One of <see cref="BudgetPeriods"/>, exactly.</param>
⋮----
public static class BudgetPeriods
⋮----
public static GatewayPolicyAnswer Of(GatewayOutcome outcome, string? detail = null) => new(outcome, null, [], detail);
⋮----
public sealed record GatewayWriteAnswer<T>(GatewayOutcome Outcome, T? Written, string? Detail) where T : class
⋮----
public static GatewayWriteAnswer<T> Of(GatewayOutcome outcome, string? detail = null) => new(outcome, null, detail);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayRegistration.cs">
public static class GatewayRegistration
⋮----
public static IServiceCollection AddGatewayAdmin(this IServiceCollection services, IConfiguration configuration)
⋮----
services.Configure<GatewayOptions>(configuration.GetSection(GatewayOptions.SectionName));
⋮----
services.TryAddSingleton(TimeProvider.System);
⋮----
.RedactLoggedHeaders(["Authorization"]);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayStatus.cs">
public int? Percent => Ceiling is > 0 ? (int)Math.Min(100, Used * 100 / Ceiling.Value) : null;
⋮----
public IReadOnlyList<(string Country, int Count)> CountriesByCount() =>
⋮----
.Where(entry => entry.Value > 0 && !string.IsNullOrWhiteSpace(entry.Key))
.GroupBy(entry => entry.Key.Trim().ToUpperInvariant(), StringComparer.Ordinal)
.Select(group => (Country: group.Key, Count: group.Sum(entry => entry.Value)))
.OrderByDescending(entry => entry.Count)
.ThenBy(entry => entry.Country, StringComparer.Ordinal)
.ToList();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayStatusCache.cs">
public sealed class GatewayStatusCache(TimeProvider clock)
⋮----
public static readonly TimeSpan Lifetime = TimeSpan.FromSeconds(30);
⋮----
private readonly SemaphoreSlim _gate = new(1, 1);
⋮----
public async Task<CachedGatewayStatus> GetAsync(
⋮----
await _gate.WaitAsync(cancellationToken);
⋮----
var cached = new CachedGatewayStatus(answer, clock.GetUtcNow());
⋮----
_gate.Release();
⋮----
public void Forget() => _last = null;
⋮----
private CachedGatewayStatus? Fresh()
⋮----
return last is not null && clock.GetUtcNow() - last.AskedAt < Lifetime ? last : null;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayUsage.cs">
public static readonly GatewayUsageCounts Zero = new(0, 0, 0, 0, 0);
⋮----
public long Served => Math.Max(0, Requests - Refusals - UpstreamErrors);
⋮----
public GatewayUsageCounts Row(string row) => ByRow?.GetValueOrDefault(row) ?? GatewayUsageCounts.Zero;
⋮----
public static GatewayUsageDay Empty(DateOnly day, bool byRow) =>
⋮----
public static UsageRange Last(int days, DateOnly today) => new(today.AddDays(1 - days), today);
⋮----
public static UsageRange PreviousMonth(DateOnly today)
⋮----
var first = new DateOnly(today.Year, today.Month, 1);
return new UsageRange(first.AddMonths(-1), first.AddDays(-1));
⋮----
public static DateOnly Today(DateTimeOffset now) => DateOnly.FromDateTime(now.UtcDateTime);
⋮----
public IEnumerable<DateOnly> Each()
⋮----
for (var day = From; day <= To; day = day.AddDays(1))
⋮----
public static string Format(DateOnly day) => day.ToString(DateFormat, CultureInfo.InvariantCulture);
⋮----
public static bool TryParse(string? value, out DateOnly day) =>
DateOnly.TryParseExact(value?.Trim(), DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out day);
⋮----
public override string ToString() => $"{Format(From)} to {Format(To)}";
⋮----
public GatewayUsageCounts Total => Days.Aggregate(GatewayUsageCounts.Zero, (sum, day) => sum + day.Counts);
⋮----
public static GatewayUsageDailyAnswer Of(GatewayOutcome outcome, UsageRange range, string? detail = null) => new(outcome, range, [], detail);
⋮----
public static IReadOnlyList<GatewayUsageDay> Fill(UsageRange range, IEnumerable<GatewayUsageDay> given, bool byRow)
⋮----
days.TryAdd(day.Day, day);
⋮----
return range.Each().Select(day => days.GetValueOrDefault(day) ?? GatewayUsageDay.Empty(day, byRow)).ToList();
⋮----
public static GatewayUsageSummaryAnswer Of(GatewayOutcome outcome, string? detail = null) => new(outcome, null, detail);
⋮----
public static GatewayUsageTokensAnswer Of(GatewayOutcome outcome, UsageRange range, string? detail = null) =>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/GatewayWatch.cs">
public sealed class GatewayWatch(
⋮----
public static readonly TimeSpan UnreachableAfter = TimeSpan.FromMinutes(15);
⋮----
public async Task<string?> CheckAsync(CancellationToken cancellationToken = default)
⋮----
var answer = (await cache.GetAsync(client.StatusAsync, cancellationToken)).Answer;
⋮----
var now = clock.GetUtcNow();
⋮----
var seen = new GatewayWatchState(level, period, UnreachableSince: null, UnreachableTold: false);
⋮----
await state.SetAsync(Collection, Key, seen, cancellationToken);
⋮----
public static GatewayBrakeLevel LevelOf(GatewayBrake? brake) =>
⋮----
private static int Rank(GatewayBrakeLevel level) => level switch
⋮----
private async Task<string?> NotReadAsync(GatewayWatchState held, DateTimeOffset now, GatewayOutcome outcome, CancellationToken cancellationToken)
⋮----
private async Task<string?> TellAsync(string kind, string what)
⋮----
var writers = await people.GatewayWritersAsync(CancellationToken.None);
var count = await notifier.NotifyAsync(writers, kind, subjectId: null);
logger.LogInformation("{What}: {Count} people were told ({Kind}).", what, count, kind);
⋮----
public static readonly GatewayWatchState Initial = new(GatewayBrakeLevel.Below, null, null, false);
⋮----
public sealed class GatewayWatchLoop(IServiceScopeFactory scopes, ILogger<GatewayWatchLoop> logger) : BackgroundService
⋮----
public static readonly TimeSpan Every = TimeSpan.FromMinutes(5);
⋮----
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
⋮----
if (!await LookAsync<GatewayWatch>((watch, token) => watch.CheckAsync(token), "The gateway watch", stoppingToken)
|| !await LookAsync<GatewayEnrolmentWatch>((watch, token) => watch.CheckAsync(token), "The gateway's enrolment watch", stoppingToken))
⋮----
await Task.Delay(Every, stoppingToken);
⋮----
private async Task<bool> LookAsync<TWatch>(Func<TWatch, CancellationToken, Task> look, string which, CancellationToken stoppingToken)
where TWatch : notnull
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
logger.LogError(ex, "{Which} could not look; it looks again in five minutes.", which);
⋮----
public sealed class GatewayNotificationContent(ConsolePeople people, IStringLocalizer<ConsoleResource> text) : INotificationContent
⋮----
public bool Renders(string kind) => GatewayWatch.Kinds.Contains(kind, StringComparer.Ordinal);
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default)
⋮----
_writers ??= (await people.GatewayWritersAsync(cancellationToken)).Select(ConsoleRoles.Normalise).ToHashSet(StringComparer.Ordinal);
if (!_writers.Contains(notification.Recipient))
⋮----
return new NotificationContent(text[$"{key}.Title", GatewayWatch.NearPercent].Value, text[$"{key}.Body", GatewayWatch.NearPercent].Value, Path);
⋮----
public static class GatewayWatchRegistration
⋮----
public static IServiceCollection AddGatewayWatch(this IServiceCollection services)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Gateway/InstallationQuery.cs">
public static bool IsVersion(string? value) =>
!string.IsNullOrWhiteSpace(value) && Version.TryParse(value.Trim().Split('-', '+')[0], out _);
⋮----
internal string QueryString()
⋮----
parameters.Add(("licence_id", licenceId.ToString()));
⋮----
parameters.Add(("row", row.ToString().ToLowerInvariant()));
⋮----
parameters.Add(("status", revoked ? "revoked" : "active"));
⋮----
parameters.Add(("seen_since", since.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture)));
⋮----
parameters.Add(("app_version_below", version.Trim()));
⋮----
parameters.Add(("sort", Sort == InstallationSort.LastSeen ? "last_seen" : "tokens_used"));
⋮----
parameters.Add(("limit", Math.Clamp(Limit, 1, GatewayAdminClient.MaxLimit).ToString(CultureInfo.InvariantCulture)));
⋮----
parameters.Add(("offset", Offset.ToString(CultureInfo.InvariantCulture)));
⋮----
return string.Join("&", parameters.Select(parameter => $"{parameter.Name}={Uri.EscapeDataString(parameter.Value)}"));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Installations/LicenceInstallations.cs">
public int Holding => Answer.Installations.Count(installation => !installation.IsRevoked);
⋮----
.OrderBy(installation => installation.IsRevoked)
.ThenByDescending(installation => installation.LastSeenAt);
⋮----
public static IReadOnlyList<SharedLicence> Find(IEnumerable<GatewayInstallation> installations, IEnumerable<RegisterSummary> register)
⋮----
var latest = RegisterSummary.LatestByLicence(register);
⋮----
.Where(installation => installation.LicenceId is not null && !installation.IsRevoked)
.GroupBy(installation => installation.LicenceId!.Value)
.Where(licence => licence.Count() > 1)
.Select(licence => new SharedLicence(licence.Key, licence.Count(), latest.GetValueOrDefault(licence.Key)))
.OrderByDescending(licence => licence.Holding)
.ThenBy(licence => licence.Row is null ? 0 : 1)
.ThenBy(licence => licence.Row?.CustomerName, StringComparer.OrdinalIgnoreCase)
.ThenBy(licence => licence.LicenceId)
.ToList();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/EntitlementSummary.cs">
public static class EntitlementSummary
⋮----
public static IReadOnlyList<EntitlementLine> Describe(Entitlements entitlements, IStringLocalizer<ConsoleResource> text) =>
⋮----
public static IReadOnlyList<EntitlementLine> Brief(Entitlements entitlements, IStringLocalizer<ConsoleResource> text) =>
⋮----
private static IReadOnlyList<EntitlementLine> Lines(Entitlements e, IStringLocalizer<ConsoleResource> text, bool brief) => new[]
⋮----
Switches(Reports, e.Reports, LicenseContract.Reports.All.Select(entry => (entry.Name, text.ReportName(entry))), text, brief),
Switches(Features, e.Features, LicenseContract.Features.All.Select(entry => (entry.Name, text.FeatureName(entry))), text, brief),
⋮----
private static EntitlementLine Switches(
⋮----
var (summary, all) = Granted(granted, catalogue.ToList(), text, brief);
return new EntitlementLine(section, summary, all);
⋮----
private static (string Summary, bool All) Granted(
⋮----
var on = catalogue.Where(entry => granted.Contains(entry.Name)).Select(entry => entry.DisplayName).ToList();
var off = catalogue.Where(entry => !granted.Contains(entry.Name)).Select(entry => entry.DisplayName).ToList();
⋮----
? text["Js.Summary.Named", count, string.Join(", ", on)]
: text["Js.Summary.NamedOff", count, string.Join(", ", off)], false);
⋮----
private static EntitlementLine ConnectorLine(Entitlements e, IStringLocalizer<ConsoleResource> text, bool brief)
⋮----
var catalogue = LicenseContract.Sources.All.Select(entry => (entry.Name, text.SourceName(entry))).ToList();
var (granted, all) = Granted(e.Sources.Select(grant => grant.Name).ToList(), catalogue, text, brief);
⋮----
var counted = e.Sources.Where(grant => grant.Count is not null).ToList();
⋮----
parts.Add(brief
⋮----
: string.Join(", ", counted.Select(grant => UpTo(grant.Name, grant.Count!.Value, text))));
⋮----
parts.Add(max == 0 ? text["Js.Summary.InTotalUnreadable"] : text["Js.Summary.InTotal", Number(max)]);
⋮----
return new EntitlementLine(Connectors, isDefault ? text["Js.Summary.NoLimit", granted] : string.Join(" · ", parts), isDefault);
⋮----
private static EntitlementLine AnalysisLine(Entitlements e, IStringLocalizer<ConsoleResource> text)
⋮----
parts.Add(employees == 0 ? text["Js.Summary.EmployeesUnreadable"] : text["Js.Summary.Employees", Number(employees)]);
⋮----
? new EntitlementLine(Analysis, text["Js.Summary.NoLimits"], true)
: new EntitlementLine(Analysis, string.Join(" · ", parts), false);
⋮----
private static EntitlementLine AiLine(Entitlements e, IStringLocalizer<ConsoleResource> text)
⋮----
var assistantOn = e.Ai.Contains(LicenseContract.Ai.Chat, StringComparer.Ordinal);
⋮----
parts.Add(tokens == 0
⋮----
parts.Add(text["Js.Summary.TierBudgetPer", period]);
⋮----
parts.Add(rpm == 0 ? text["Js.Summary.RequestsUnreadable"] : text["Js.Summary.Requests", Number(rpm)]);
⋮----
parts.Add(text["Js.Summary.TierDefaults"]);
⋮----
return new EntitlementLine(Ai, string.Join(" · ", parts), isDefault);
⋮----
private static void Add(List<string> parts, long? limit, string unit, IStringLocalizer<ConsoleResource> text)
⋮----
parts.Add(value == 0 ? text[$"Js.Summary.{unit}Unreadable"] : text[$"Js.Summary.{unit}", Number(value)]);
⋮----
private static string UpTo(string code, long count, IStringLocalizer<ConsoleResource> text) =>
⋮----
? text["Js.Summary.UpToUnreadable", text.SourceName(code)]
: text["Js.Summary.UpTo", text.SourceName(code), Number(count), text.SourceUnit(code)];
⋮----
private static string Number(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/IssueForm.cs">
public sealed class IssueForm
⋮----
public List<string> Reports { get; set; } = LicenseContract.Reports.All.Select(entry => entry.Name).ToList();
⋮----
public List<string> Features { get; set; } = LicenseContract.Features.All.Select(entry => entry.Name).ToList();
⋮----
public List<string> Sources { get; set; } = LicenseContract.Sources.All.Select(entry => entry.Name).ToList();
⋮----
public List<string> Ai { get; set; } = LicenseContract.Ai.All.Select(entry => entry.Name).ToList();
⋮----
public LicenseConfig? ToConfig(IStringLocalizer<ConsoleResource> text, out IReadOnlyList<string> problems)
⋮----
return new LicenseConfig
⋮----
Name = CustomerName.Trim(),
Email = CustomerEmail.Trim(),
Company = string.IsNullOrWhiteSpace(Company) ? null : Company.Trim(),
⋮----
Tier = string.IsNullOrWhiteSpace(Tier) ? null : Tier.Trim(),
Purpose = string.IsNullOrWhiteSpace(Purpose) ? LicenseContract.Purposes.Customer : Purpose.Trim(),
⋮----
? Instant(Expiration.Value, new TimeOnly(23, 59, 59))
⋮----
AiPeriod = string.IsNullOrWhiteSpace(AiPeriod) ? null : AiPeriod.Trim(),
⋮----
public Entitlements ToEntitlements() => new()
⋮----
Reports = InCatalogue(Reports, LicenseContract.Reports.All.Select(entry => entry.Name)),
Features = InCatalogue(Features, LicenseContract.Features.All.Select(entry => entry.Name)),
⋮----
.Where(entry => Sources.Contains(entry.Name, StringComparer.Ordinal))
.Select(entry => new SourceGrant(entry.Name, Count(entry.Name)))
.ToList(),
Ai = InCatalogue(Ai, LicenseContract.Ai.All.Select(entry => entry.Name)),
⋮----
AiPeriod = string.IsNullOrWhiteSpace(AiPeriod) ? null : AiPeriod,
⋮----
public long? Count(string source) => SourceCounts.TryGetValue(source, out var count) ? count : null;
⋮----
private List<string> SourceEntries(List<string> errors, IStringLocalizer<ConsoleResource> text)
⋮----
errors.Add(text["Licensing.Issue.Problem.CountAtLeastOne", text.SourceName(name)]);
⋮----
entries.Add(Entitlements.FormatSource(name, count));
⋮----
private void CheckLimits(List<string> errors, IStringLocalizer<ConsoleResource> text)
⋮----
errors.Add(text["Licensing.Issue.Problem.LimitAtLeastOne", text.LimitName(limit), text.LimitAbsentMeans(limit).TrimEnd('.').ToLowerInvariant()]);
⋮----
private static List<string> Selected(IEnumerable<string>? names) =>
(names ?? Enumerable.Empty<string>()).Where(name => !string.IsNullOrWhiteSpace(name)).Distinct(StringComparer.Ordinal).ToList();
⋮----
private static List<string> InCatalogue(IEnumerable<string> names, IEnumerable<string> catalogue) =>
catalogue.Where(name => names.Contains(name, StringComparer.Ordinal)).ToList();
⋮----
private string? IsoDuration(List<string> errors, IStringLocalizer<ConsoleResource> text)
⋮----
errors.Add(text["Licensing.Issue.Problem.DurationRequired"]);
⋮----
errors.Add(text["Licensing.Issue.Problem.DurationUnit"]);
⋮----
return string.Create(CultureInfo.InvariantCulture, $"P{DurationAmount}{designator}");
⋮----
private static string Instant(DateOnly date, TimeOnly time) =>
date.ToDateTime(time).ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
⋮----
private static Dictionary<string, string> ParseAttributes(string? typed, List<string> errors, IStringLocalizer<ConsoleResource> text)
⋮----
if (string.IsNullOrWhiteSpace(typed))
⋮----
var lines = typed.Split('\n');
⋮----
var line = lines[i].Trim();
⋮----
var equals = line.IndexOf('=');
var name = equals < 0 ? string.Empty : line[..equals].Trim();
⋮----
errors.Add(text["Licensing.Issue.Problem.AttributeLine", i + 1]);
⋮----
if (!attributes.TryAdd(name, line[(equals + 1)..].Trim()))
⋮----
errors.Add(text["Licensing.Issue.Problem.AttributeTwice", i + 1, name]);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/IssueLedger.cs">
public sealed class IssueLedger
⋮----
private readonly TimeProvider _clock;
⋮----
public bool TryBegin(Guid ticketId, out Guid? recordId)
⋮----
var claimed = new Entry(_clock.GetUtcNow(), null);
if (_entries.TryAdd(ticketId, claimed))
⋮----
recordId = _entries.TryGetValue(ticketId, out var existing) ? existing.RecordId : null;
⋮----
public void Complete(Guid ticketId, Guid recordId) =>
_entries[ticketId] = new Entry(_clock.GetUtcNow(), recordId);
⋮----
public void Abandon(Guid ticketId) => _entries.TryRemove(ticketId, out _);
⋮----
private void Prune()
⋮----
var cutoff = _clock.GetUtcNow() - IssueTicketProtector.Lifetime - TimeSpan.FromMinutes(5);
⋮----
_entries.TryRemove(id, out _);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/IssueTicket.cs">
public sealed class IssueTicketProtector
⋮----
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(30);
⋮----
private readonly ITimeLimitedDataProtector _protector;
⋮----
_protector = provider.CreateProtector("KnowledgeFabric.AdminConsole.Licensing.IssueTicket.v1").ToTimeLimitedDataProtector();
⋮----
public string Protect(IssueTicket ticket) =>
_protector.Protect(JsonSerializer.Serialize(ticket), Lifetime);
⋮----
public IssueTicket? Unprotect(string? sealedTicket)
⋮----
if (string.IsNullOrWhiteSpace(sealedTicket))
⋮----
return JsonSerializer.Deserialize<IssueTicket>(_protector.Unprotect(sealedTicket));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/LicenceIssuer.cs">
public sealed class LicenceIssuer
⋮----
PreviewKeyGenerator.Create().GenerateKeyPair().ToEncryptedPrivateKeyString(PreviewPassphrase));
⋮----
private readonly IHostEnvironment _environment;
⋮----
return _environment.IsDevelopment() ? SigningKeyState.ContractTestKey : SigningKeyState.ContractTestKeyRefused;
⋮----
public LicencePreview Preview(LicenseConfig config, DateTimeOffset issuedAt)
⋮----
var terms = LicenseTerms.Resolve(config, issuedAt);
var draft = LicenseSigner.Sign(terms, PreviewKey.Value, PreviewPassphrase);
⋮----
var document = XElement.Parse(draft);
document.Element("Signature")?.Remove();
⋮----
return new LicencePreview(terms, document.ToString(), System.Text.Encoding.UTF8.GetByteCount(draft), terms.Warnings.ToList());
⋮----
public string Sign(LicenseConfig config, DateTimeOffset issuedAt)
⋮----
throw new SigningKeyUnavailableException(state);
⋮----
licenseXml = LicenseSigner.Sign(terms, key.PrivateKey!, key.PrivateKeyPassphrase!);
⋮----
throw new SigningFailedException(SigningKeyDiagnosis.Diagnose(key.PrivateKey!, key.PrivateKeyPassphrase!), ex);
⋮----
if (!trusted.Any(candidate => ContractReader.Read(licenseXml, candidate.PublicKey, issuedAt.UtcDateTime).SignatureValid))
⋮----
throw new SigningFailedException(SigningFailure.KeyNotTrusted, null);
⋮----
public sealed class SigningKeyUnavailableException(SigningKeyState state)
: InvalidOperationException($"The signing key cannot be used: {state}.")
⋮----
public sealed class SigningFailedException(SigningFailure failure, Exception? inner)
: InvalidOperationException($"Signing failed: {failure}.", inner)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/LicenceIssuingRegistration.cs">
public static class LicenceIssuingRegistration
⋮----
public static IServiceCollection AddLicenceIssuing(this IServiceCollection services, IConfiguration configuration)
⋮----
services.Configure<SigningKeyOptions>(configuration.GetSection(SigningKeyOptions.SectionName));
services.TryAddSingleton(TimeProvider.System);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/SigningKeyDiagnosis.cs">
public static class SigningKeyDiagnosis
⋮----
public static SigningFailure Diagnose(string privateKey, string passphrase)
⋮----
der = Convert.FromBase64String(privateKey.Trim());
⋮----
var trimmed = passphrase.Trim();
⋮----
private static bool Opens(byte[] der, string passphrase)
⋮----
return PrivateKeyFactory.DecryptKey(passphrase.ToCharArray(), der).IsPrivate;
⋮----
private static bool IsPublicKey(byte[] der)
⋮----
return !PublicKeyFactory.CreateKey(der).IsPrivate;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Issuing/SigningKeyOptions.cs">
public sealed class SigningKeyOptions
⋮----
!string.IsNullOrWhiteSpace(PrivateKey) && !string.IsNullOrEmpty(PrivateKeyPassphrase);
⋮----
public bool IsContractTestKey => PrivateKey is not null && ContractTestKeyFingerprints.Contains(Fingerprint(PrivateKey));
⋮----
internal static string Fingerprint(string privateKey) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(privateKey.Trim()))).ToLowerInvariant();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/ILicenceRegister.cs">
public interface ILicenceRegister
⋮----
Task<RegisterRecord> RecordAsync(RegisterRecord record, CancellationToken cancellationToken = default);
⋮----
Task<RegisterRecord?> FindAsync(Guid recordId, CancellationToken cancellationToken = default);
⋮----
Task<RegisterPage> SearchAsync(RegisterQuery query, int page, int pageSize, CancellationToken cancellationToken = default);
⋮----
IAsyncEnumerable<RegisterRecord> ExportAsync(RegisterQuery query, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<RegisterSummary>> SummariesAsync(CancellationToken cancellationToken = default);
⋮----
public int PageCount => Math.Max(1, (TotalCount + PageSize - 1) / PageSize);
⋮----
public static RegisterSummary Of(RegisterRecord row) => new(
⋮----
public string Purpose => LicenseContract.Purposes.Of(Attributes);
⋮----
public Entitlements Entitlements => Entitlements.Read(Attributes);
⋮----
public bool InForceAt(DateTime nowUtc) =>
⋮----
public static IReadOnlyDictionary<Guid, RegisterSummary> LatestByLicence(IEnumerable<RegisterSummary> rows) =>
rows.GroupBy(row => row.LicenseId)
.ToDictionary(licence => licence.Key, licence => licence.MaxBy(row => (row.IssuedAtUtc, row.RecordedAtUtc))!);
⋮----
public static IReadOnlyList<LicenceInForce> InForce(IEnumerable<RegisterSummary> rows, DateTime nowUtc) =>
rows.OrderBy(row => row.IssuedAtUtc)
.ThenBy(row => row.RecordedAtUtc)
.ThenBy(row => row.RecordId)
.GroupBy(row => row.LicenseId)
.Select(licence => (Files: licence.ToList(), InForce: licence.Where(row => row.InForceAt(nowUtc)).ToList()))
.Where(licence => licence.InForce.Count > 0)
.Select(licence => new LicenceInForce(licence.InForce[^1], licence.Files.Max(row => row.ExpirationUtc), licence.Files.Count))
.ToList();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/InMemoryLicenceRegister.cs">
public sealed class InMemoryLicenceRegister : ILicenceRegister
⋮----
public Task<RegisterRecord> RecordAsync(RegisterRecord record, CancellationToken cancellationToken = default)
⋮----
var existing = _rows.Values.FirstOrDefault(row => row.Sha256 == record.Sha256);
⋮----
return Task.FromResult(existing);
⋮----
return Task.FromResult(record);
⋮----
public Task<RegisterRecord?> FindAsync(Guid recordId, CancellationToken cancellationToken = default) =>
Task.FromResult(_rows.TryGetValue(recordId, out var row) ? row : null);
⋮----
public Task<RegisterPage> SearchAsync(RegisterQuery query, int page, int pageSize, CancellationToken cancellationToken = default)
⋮----
var matches = Matching(query).ToList();
var rows = matches.Skip((page - 1) * pageSize).Take(pageSize).ToList();
return Task.FromResult(new RegisterPage(rows, page, pageSize, matches.Count));
⋮----
public async IAsyncEnumerable<RegisterRecord> ExportAsync(
⋮----
cancellationToken.ThrowIfCancellationRequested();
⋮----
public Task<IReadOnlyList<RegisterSummary>> SummariesAsync(CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyList<RegisterSummary>>(_rows.Values.Select(RegisterSummary.Of).ToList());
⋮----
private IEnumerable<RegisterRecord> Matching(RegisterQuery query)
⋮----
.Where(row => term is null
|| row.CustomerName.Contains(term, StringComparison.OrdinalIgnoreCase)
|| row.CustomerEmail.Contains(term, StringComparison.OrdinalIgnoreCase)
⋮----
|| row.LicenseId.ToString().Contains(term, StringComparison.OrdinalIgnoreCase))
.Where(row => query.Purpose is null || row.Purpose == query.Purpose)
.Where(row => query.Tier is null || (query.Tier == RegisterQuery.NoTier ? row.Tier is null : row.Tier == query.Tier))
.Where(row => query.Status switch
⋮----
RegisterStatus.Active => !query.IsExpired(row),
RegisterStatus.Expired => query.IsExpired(row),
⋮----
.OrderByDescending(row => row.IssuedAtUtc)
.ThenByDescending(row => row.RecordedAtUtc);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/LicenceRegisterRegistration.cs">
public static class LicenceRegisterRegistration
⋮----
public static IServiceCollection AddLicenceRegister(
⋮----
var section = configuration.GetSection(DatabaseOptions.SectionName);
var database = section.Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
.Bind(section)
.Validate(
options => options.NamesAHostAndDatabase(),
⋮----
.ValidateOnStart();
⋮----
builder.UseNpgsql(
⋮----
npgsql => npgsql.EnableRetryOnFailure()));
⋮----
else if (environment.IsDevelopment())
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/PostgresLicenceRegister.cs">
public sealed class PostgresLicenceRegister(ConsoleDbContext db) : ILicenceRegister
⋮----
public async Task<RegisterRecord> RecordAsync(RegisterRecord record, CancellationToken cancellationToken = default)
⋮----
db.IssuedLicences.Add(record);
⋮----
await db.SaveChangesAsync(cancellationToken);
⋮----
db.Entry(record).State = EntityState.Detached;
⋮----
?? throw new InvalidOperationException("A unique violation was reported, but no row holds this licence's hash.", ex);
⋮----
public Task<RegisterRecord?> FindAsync(Guid recordId, CancellationToken cancellationToken = default) =>
db.IssuedLicences.AsNoTracking().SingleOrDefaultAsync(r => r.RecordId == recordId, cancellationToken);
⋮----
public async Task<RegisterPage> SearchAsync(RegisterQuery query, int page, int pageSize, CancellationToken cancellationToken = default)
⋮----
var total = await matches.CountAsync(cancellationToken);
⋮----
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync(cancellationToken);
⋮----
return new RegisterPage(rows, page, pageSize, total);
⋮----
public IAsyncEnumerable<RegisterRecord> ExportAsync(RegisterQuery query, CancellationToken cancellationToken = default) =>
Matching(query).AsAsyncEnumerable();
⋮----
public async Task<IReadOnlyList<RegisterSummary>> SummariesAsync(CancellationToken cancellationToken = default) =>
⋮----
.AsNoTracking()
.Select(r => new RegisterSummary(
⋮----
private Task<RegisterRecord?> BySha256(string sha256, CancellationToken cancellationToken) =>
db.IssuedLicences.AsNoTracking().SingleOrDefaultAsync(r => r.Sha256 == sha256, cancellationToken);
⋮----
private IQueryable<RegisterRecord> Matching(RegisterQuery query)
⋮----
var rows = db.IssuedLicences.AsNoTracking();
⋮----
var pattern = "%" + term.Replace(@"\", @"\\").Replace("%", @"\%").Replace("_", @"\_") + "%";
⋮----
rows = rows.Where(r =>
EF.Functions.ILike(r.CustomerName, pattern, @"\")
|| EF.Functions.ILike(r.CustomerEmail, pattern, @"\")
|| EF.Functions.ILike(r.Company ?? "", pattern, @"\")
|| EF.Functions.ILike(r.LicenseId.ToString(), pattern, @"\"));
⋮----
var written = JsonSerializer.Serialize(new Dictionary<string, string> { [LicenseContract.Attributes.Purpose] = purpose });
⋮----
? rows.Where(r => !EF.Functions.JsonExists(r.Attributes, LicenseContract.Attributes.Purpose)
|| EF.Functions.JsonContains(r.Attributes, written))
: rows.Where(r => EF.Functions.JsonContains(r.Attributes, written));
⋮----
? rows.Where(r => r.Tier == null)
: rows.Where(r => r.Tier == tier);
⋮----
RegisterStatus.Active => rows.Where(r => r.ExpirationUtc >= asOf),
RegisterStatus.Expired => rows.Where(r => r.ExpirationUtc < asOf),
⋮----
.OrderByDescending(r => r.IssuedAtUtc)
.ThenByDescending(r => r.RecordedAtUtc);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/RegisterQuery.cs">
public static RegisterQuery All(DateTime asOfUtc) => new() { AsOfUtc = asOfUtc };
⋮----
public static RegisterQuery From(string? text, string? purpose, string? tier, string? status, DateTime asOfUtc) => new()
⋮----
Text = string.IsNullOrWhiteSpace(text) ? null : text.Trim(),
Purpose = LicenseContract.Purposes.All.Select(entry => entry.Name).FirstOrDefault(name => Same(name, purpose)),
Tier = LicenseContract.Tiers.All.Append(NoTier).FirstOrDefault(name => Same(name, tier)),
⋮----
public bool IsExpired(RegisterRecord row) => row.ExpirationUtc < AsOfUtc;
⋮----
public Dictionary<string, string> RouteValues()
⋮----
private static bool Same(string name, string? value) => string.Equals(name, value?.Trim(), StringComparison.OrdinalIgnoreCase);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/RegisterStatistics.cs">
public static RegisterStatistics Compute(IEnumerable<RegisterSummary> rows, DateTime nowUtc)
⋮----
.OrderBy(row => row.IssuedAtUtc)
.ThenBy(row => row.RecordedAtUtc)
.ThenBy(row => row.RecordId)
.ToList();
⋮----
var licences = ordered.GroupBy(row => row.LicenseId).ToList();
var firstIssues = licences.Select(licence => licence.First().RecordId).ToHashSet();
var expiringBy = nowUtc.AddMonths(1);
⋮----
var inForce = licence.Where(row => row.InForceAt(nowUtc)).ToList();
⋮----
if (licence.Any(row => row.ExpirationUtc >= nowUtc))
⋮----
tiers[label] = tiers.GetValueOrDefault(label) + 1;
⋮----
var coveredUntil = licence.Max(row => row.ExpirationUtc);
⋮----
expiring.Add(new ExpiringLicence(current, coveredUntil));
⋮----
return new RegisterStatistics(
⋮----
.OrderBy(licence => licence.CoveredUntilUtc)
.ThenBy(licence => licence.Current.CustomerName, StringComparer.OrdinalIgnoreCase)
.ToList(),
RecentlyIssued: Enumerable.Reverse(ordered)
.Take(RecentCount)
.Select(row => new RecentIssue(row, IsReissue: !firstIssues.Contains(row.RecordId)))
.ToList());
⋮----
private static string TierLabel(string? tier)
⋮----
if (string.IsNullOrWhiteSpace(tier))
⋮----
var known = LicenseContract.Tiers.All.FirstOrDefault(name => string.Equals(name, tier.Trim(), StringComparison.OrdinalIgnoreCase));
⋮----
private static IReadOnlyList<TierCount> TierCounts(Dictionary<string, int> tiers)
⋮----
.Select(tier => TierLabel(tier))
.Select(label => new TierCount(label, tiers.GetValueOrDefault(label)))
⋮----
if (tiers.GetValueOrDefault(label) > 0)
⋮----
counts.Add(new TierCount(label, tiers[label]));
⋮----
private static IReadOnlyList<MonthCount> MonthCounts(List<RegisterSummary> ordered, HashSet<Guid> firstIssues, DateTime nowUtc)
⋮----
var thisMonth = new DateOnly(nowUtc.Year, nowUtc.Month, 1);
var months = Enumerable.Range(0, Months)
.Select(offset => thisMonth.AddMonths(offset - (Months - 1)))
.ToDictionary(month => month, _ => (New: 0, Reissued: 0));
⋮----
var month = new DateOnly(row.IssuedAtUtc.Year, row.IssuedAtUtc.Month, 1);
if (months.TryGetValue(month, out var count))
⋮----
months[month] = firstIssues.Contains(row.RecordId)
⋮----
.OrderBy(pair => pair.Key)
.Select(pair => new MonthCount(pair.Key, pair.Value.New, pair.Value.Reissued))
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Register/UnconfiguredLicenceRegister.cs">
public sealed class UnconfiguredLicenceRegister : ILicenceRegister
⋮----
public Task<RegisterRecord> RecordAsync(RegisterRecord record, CancellationToken cancellationToken = default) =>
throw new LicenceRegisterUnavailableException();
⋮----
public Task<RegisterRecord?> FindAsync(Guid recordId, CancellationToken cancellationToken = default) =>
⋮----
public Task<RegisterPage> SearchAsync(RegisterQuery query, int page, int pageSize, CancellationToken cancellationToken = default) =>
Task.FromResult(new RegisterPage(Array.Empty<RegisterRecord>(), page, pageSize, 0));
⋮----
public IAsyncEnumerable<RegisterRecord> ExportAsync(RegisterQuery query, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<RegisterSummary>> SummariesAsync(CancellationToken cancellationToken = default) =>
⋮----
private static class AsyncEnumerable
⋮----
private static async IAsyncEnumerable<RegisterRecord> Nothing()
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Validation/LicenceValidator.cs">
public static class LicenceValidator
⋮----
public static ValidationReport Validate(
⋮----
throw new ArgumentException("At least one key is needed to verify against.", nameof(keys));
⋮----
var candidate = ContractReader.Read(licenseXml, key.PublicKey, evaluationInstantUtc);
⋮----
return new ValidationReport(
⋮----
private static ReaderVerdict ProductToday(ContractVerdict v, IStringLocalizer<ConsoleResource> text) =>
⋮----
: ReaderVerdict.Refused(v.Reason, Explain(v, text));
⋮----
private static ReaderVerdict ProductPerContract(ContractVerdict v, IStringLocalizer<ConsoleResource> text)
⋮----
return ReaderVerdict.Refused(v.Reason, Explain(v, text));
⋮----
private static ReaderVerdict Installed(ContractVerdict v, string summary, IStringLocalizer<ConsoleResource> text) =>
⋮----
? ReaderVerdict.AcceptedGrantingNothing(summary + " " + text["Licensing.Validate.Verdict.GrantsNothing"])
: ReaderVerdict.Accepted(summary);
⋮----
private static GatewayVerdict GatewayToday(ContractVerdict v, IStringLocalizer<ConsoleResource> text)
⋮----
return new GatewayVerdict("licensed", "accepted", null, ReportedExpiry(v.ExpirationUtc)) { Allowance = Allowance(v.Entitlements, v.AiTier, text) };
⋮----
? new GatewayVerdict("evaluation", "rejected", cause, ReportedExpiry(v.ExpirationUtc)) { Cause = cause }
: new GatewayVerdict("evaluation", "rejected", LicenseContract.Reasons.Unverifiable, null) { Cause = cause };
⋮----
private static GatewayVerdict GatewayPerContract(ContractVerdict v, IStringLocalizer<ConsoleResource> text) =>
⋮----
? new GatewayVerdict("licensed", "accepted", null, v.ExpirationUtc) { Allowance = Allowance(v.Entitlements, v.AiTier, text) }
: new GatewayVerdict("evaluation", "rejected", v.Reason, v.SignatureValid ? v.ExpirationUtc : null);
⋮----
private static string Allowance(Entitlements e, string tier, IStringLocalizer<ConsoleResource> text)
⋮----
limits.Add(tokens == 0 ? text["Licensing.Validate.Allowance.TokensUnreadable"] : text["Licensing.Validate.Allowance.Tokens", Number(tokens)]);
⋮----
limits.Add(period == LicenseContract.AiPeriods.Month ? text["Licensing.Validate.Allowance.PeriodMonth"] : text["Licensing.Validate.Allowance.Period30d"]);
⋮----
limits.Add(rpm == 0 ? text["Licensing.Validate.Allowance.RequestsUnreadable"] : text["Licensing.Validate.Allowance.Requests", Number(rpm)]);
⋮----
: text["Licensing.Validate.Allowance.Replaces", tier, string.Join("; ", limits)];
⋮----
private static string Number(long value) => value.ToString("N0", CultureInfo.CurrentCulture);
⋮----
private static DateTime? ReportedExpiry(DateTime? expirationUtc) =>
expirationUtc >= DateTime.MaxValue.AddDays(-2) ? null : expirationUtc;
⋮----
private static string Explain(ContractVerdict v, IStringLocalizer<ConsoleResource> text) => v.Reason switch
⋮----
public static ReaderVerdict Accepted(string summary) => new(true, null, summary);
⋮----
public static ReaderVerdict AcceptedGrantingNothing(string summary) => new(true, null, summary, GrantsNothing: true);
⋮----
public static ReaderVerdict Refused(string? reason, string summary) => new(false, reason, summary);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Licensing/Validation/TrustedKeys.cs">
public static class TrustedKeys
⋮----
new TrustedKey(
⋮----
public static readonly TrustedKey ContractTest = new(
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/CatalogueNames.cs">
public static class CatalogueNames
⋮----
public static string ReportName(this IStringLocalizer<ConsoleResource> text, LicenseContract.Entry entry) =>
text.Of($"Catalogue.Report.{entry.Name}", entry.DisplayName);
⋮----
public static string ReportDescription(this IStringLocalizer<ConsoleResource> text, LicenseContract.Entry entry) =>
text.Of($"Catalogue.Report.{entry.Name}.Description", entry.Description);
⋮----
public static string FeatureName(this IStringLocalizer<ConsoleResource> text, LicenseContract.Entry entry) =>
text.Of($"Catalogue.Feature.{entry.Name}", entry.DisplayName);
⋮----
public static string FeatureDescription(this IStringLocalizer<ConsoleResource> text, LicenseContract.Entry entry) =>
text.Of($"Catalogue.Feature.{entry.Name}.Description", entry.Description);
⋮----
public static string SourceName(this IStringLocalizer<ConsoleResource> text, LicenseContract.SourceEntry entry) =>
text.Of($"Catalogue.Source.{entry.Name}", entry.DisplayName);
⋮----
public static string SourceDescription(this IStringLocalizer<ConsoleResource> text, LicenseContract.SourceEntry entry) =>
text.Of($"Catalogue.Source.{entry.Name}.Description", entry.Description);
⋮----
public static string SourceUnit(this IStringLocalizer<ConsoleResource> text, LicenseContract.SourceEntry entry) =>
text.Of($"Catalogue.Source.{entry.Name}.Unit", entry.Unit);
⋮----
public static string SourceUnit(this IStringLocalizer<ConsoleResource> text, string code)
⋮----
var entry = LicenseContract.Sources.All.FirstOrDefault(source => source.Name == code);
return entry is null ? text["Catalogue.Limit.sources.max.Unit"] : text.SourceUnit(entry);
⋮----
public static string SourceName(this IStringLocalizer<ConsoleResource> text, string code)
⋮----
return entry is null ? code : text.SourceName(entry);
⋮----
public static string AiName(this IStringLocalizer<ConsoleResource> text, LicenseContract.Entry entry) =>
text.Of($"Catalogue.Ai.{entry.Name}", entry.DisplayName);
⋮----
public static string AiDescription(this IStringLocalizer<ConsoleResource> text, LicenseContract.Entry entry) =>
text.Of($"Catalogue.Ai.{entry.Name}.Description", entry.Description);
⋮----
public static string LimitName(this IStringLocalizer<ConsoleResource> text, LicenseContract.LimitEntry limit) =>
text.Of($"Catalogue.Limit.{limit.Attribute}", limit.DisplayName);
⋮----
public static string LimitDescription(this IStringLocalizer<ConsoleResource> text, LicenseContract.LimitEntry limit) =>
text.Of($"Catalogue.Limit.{limit.Attribute}.Description", limit.Description);
⋮----
public static string LimitUnit(this IStringLocalizer<ConsoleResource> text, LicenseContract.LimitEntry limit) =>
text.Of($"Catalogue.Limit.{limit.Attribute}.Unit", limit.Unit);
⋮----
public static string LimitAbsentMeans(this IStringLocalizer<ConsoleResource> text, LicenseContract.LimitEntry limit) =>
text.Of($"Catalogue.Limit.{limit.Attribute}.AbsentMeans", limit.AbsentMeans);
⋮----
public static string PurposeName(this IStringLocalizer<ConsoleResource> text, string code)
⋮----
var entry = LicenseContract.Purposes.All.FirstOrDefault(purpose => purpose.Name == code);
return entry is null ? code : text.Of($"Catalogue.Purpose.{entry.Name}", entry.DisplayName);
⋮----
public static string? PurposeDescription(this IStringLocalizer<ConsoleResource> text, string code)
⋮----
return entry is null ? null : text.Of($"Catalogue.Purpose.{entry.Name}.Description", entry.Description);
⋮----
public static string TierName(this IStringLocalizer<ConsoleResource> text, string? code)
⋮----
if (string.IsNullOrWhiteSpace(code))
⋮----
var known = LicenseContract.Tiers.All.FirstOrDefault(tier => string.Equals(tier, code.Trim(), StringComparison.OrdinalIgnoreCase));
⋮----
public static string AiPeriodName(this IStringLocalizer<ConsoleResource> text, string? period) => period switch
⋮----
private static string Of(this IStringLocalizer<ConsoleResource> text, string key, string fallback)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/ClientStrings.cs">
public sealed class ClientStrings
⋮----
public string ToJson()
⋮----
var strings = _localizer.GetAllStrings(includeParentCultures: true)
.Where(entry => entry.Name.StartsWith(Prefix, StringComparison.Ordinal))
.ToDictionary(entry => entry.Name[Prefix.Length..], entry => entry.Value, StringComparer.Ordinal);
⋮----
return JsonSerializer.Serialize(new
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/ConsoleCultures.cs">
public static class ConsoleCultures
⋮----
public static bool IsSupported(string? culture) =>
culture is not null && Supported.Contains(culture, StringComparer.Ordinal);
⋮----
public static string NativeName(string culture) => culture switch
⋮----
_ => CultureInfo.GetCultureInfo(culture).NativeName,
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/CountryNames.cs">
public static class CountryNames
⋮----
public static string CountryName(this IStringLocalizer<ConsoleResource> text, string? code)
⋮----
if (string.IsNullOrWhiteSpace(code))
⋮----
var trimmed = code.Trim().ToUpperInvariant();
if (trimmed.Length != 2 || !trimmed.All(char.IsAsciiLetterUpper))
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/InvariantFormValueProviderFactory.cs">
public sealed class InvariantFormValueProviderFactory : IValueProviderFactory
⋮----
public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
⋮----
ArgumentNullException.ThrowIfNull(context);
⋮----
private static async Task AddValueProviderAsync(ValueProviderFactoryContext context)
⋮----
IFormCollection form;
⋮----
form = await request.ReadFormAsync();
⋮----
throw new ValueProviderException("The request's form could not be read.", ex);
⋮----
context.ValueProviders.Add(new FormValueProvider(BindingSource.Form, form, CultureInfo.InvariantCulture));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/LocalisationRegistration.cs">
public static class LocalisationRegistration
⋮----
public static IMvcBuilder AddConsoleLocalisation(this IMvcBuilder mvc)
⋮----
mvc.Services.AddLocalization();
⋮----
mvc.AddMvcOptions(options =>
⋮----
options.ValueProviderFactories.RemoveAt(i);
⋮----
options.ValueProviderFactories.Insert(0, new InvariantFormValueProviderFactory());
⋮----
var localizer = factory.Create(typeof(ConsoleResource));
⋮----
messages.SetValueMustNotBeNullAccessor(_ => localizer["Binding.ValueMustNotBeNull"]);
messages.SetMissingBindRequiredValueAccessor(name => localizer["Binding.MissingBindRequiredValue", name]);
messages.SetMissingKeyOrValueAccessor(() => localizer["Binding.MissingKeyOrValue"]);
messages.SetMissingRequestBodyRequiredValueAccessor(() => localizer["Binding.MissingRequestBodyRequiredValue"]);
messages.SetAttemptedValueIsInvalidAccessor((value, name) => localizer["Binding.AttemptedValueIsInvalid", value, name]);
messages.SetNonPropertyAttemptedValueIsInvalidAccessor(value => localizer["Binding.NonPropertyAttemptedValueIsInvalid", value]);
messages.SetUnknownValueIsInvalidAccessor(name => localizer["Binding.UnknownValueIsInvalid", name]);
messages.SetNonPropertyUnknownValueIsInvalidAccessor(() => localizer["Binding.NonPropertyUnknownValueIsInvalid"]);
messages.SetValueIsInvalidAccessor(value => localizer["Binding.ValueIsInvalid", value]);
messages.SetValueMustBeANumberAccessor(name => localizer["Binding.ValueMustBeANumber", name]);
messages.SetNonPropertyValueMustBeANumberAccessor(() => localizer["Binding.NonPropertyValueMustBeANumber"]);
⋮----
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization(options =>
⋮----
options.DataAnnotationLocalizerProvider = (_, factory) => factory.Create(typeof(ConsoleResource)));
⋮----
public static IApplicationBuilder UseConsoleLocalisation(this IApplicationBuilder app)
⋮----
var cultures = ConsoleCultures.Supported.Select(CultureInfo.GetCultureInfo).ToList();
⋮----
var options = new RequestLocalizationOptions
⋮----
DefaultRequestCulture = new RequestCulture(ConsoleCultures.Default),
⋮----
options.RequestCultureProviders.Clear();
options.RequestCultureProviders.Add(new CookieRequestCultureProvider());
⋮----
return app.UseRequestLocalization(options);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Localisation/RoleNames.cs">
public static class RoleNames
⋮----
public static string Role(this IStringLocalizer<ConsoleResource> text, string role)
⋮----
var (area, verb) = ConsoleRoles.Keys(role);
⋮----
public static string Role(this IHtmlLocalizer<ConsoleResource> text, string role)
⋮----
return verb is null ? text.GetString(area) : text.GetString("Role.Display", text.GetString(area).Value, text.GetString(verb).Value);
⋮----
public static string RoleArea(this IHtmlLocalizer<ConsoleResource> text, string role) => text.GetString(ConsoleRoles.Keys(role).Area);
⋮----
public static string RoleVerb(this IHtmlLocalizer<ConsoleResource> text, string role) =>
ConsoleRoles.Keys(role).Verb is { } verb ? text.GetString(verb) : string.Empty;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Models/ConsoleBranding.cs">
public static class ConsoleBranding
⋮----
(Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(1, 0, 0)).ToString(3);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Models/ErrorModel.cs">
public sealed class ErrorModel
</file>

<file path="src/KnowledgeFabric.AdminConsole/Models/LoginModel.cs">
public sealed class LoginModel
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/InMemoryNotificationStore.cs">
public sealed class InMemoryNotificationStore : INotificationStore
⋮----
public Task AddAsync(IReadOnlyList<Notification> notifications, CancellationToken cancellationToken = default)
⋮----
_notifications.AddRange(notifications.Select(Copy));
⋮----
public Task<IReadOnlyList<Notification>> ListAsync(string recipient, int limit, CancellationToken cancellationToken = default)
⋮----
.Where(n => n.Recipient == recipient)
.OrderByDescending(n => n.CreatedAt).ThenByDescending(n => n.Id)
.Take(limit)
.Select(Copy)
.ToList());
⋮----
public Task<int> UnreadCountAsync(string recipient, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_notifications.Count(n => n.Recipient == recipient && n.ReadAt is null));
⋮----
public Task<Notification?> FindAsync(string recipient, Guid id, CancellationToken cancellationToken = default)
⋮----
var found = _notifications.FirstOrDefault(n => n.Id == id && n.Recipient == recipient);
return Task.FromResult(found is null ? null : Copy(found));
⋮----
public Task MarkReadAsync(string recipient, Guid id, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
if (_notifications.FirstOrDefault(n => n.Id == id && n.Recipient == recipient) is { ReadAt: null } found)
⋮----
public Task<int> MarkAllReadAsync(string recipient, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
var unread = _notifications.Where(n => n.Recipient == recipient && n.ReadAt is null).ToList();
unread.ForEach(n => n.ReadAt = at);
return Task.FromResult(unread.Count);
⋮----
public Task<IReadOnlyList<Notification>> PendingAsync(DateTimeOffset since, DateTimeOffset now, int limit, CancellationToken cancellationToken = default)
⋮----
.Where(n => n.PushedAt is null && n.CreatedAt >= since && (n.NextPushAt is null || n.NextPushAt <= now))
.OrderBy(n => n.CreatedAt).ThenBy(n => n.Id)
⋮----
public Task RecordPushedAsync(Guid id, string outcome, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
if (_notifications.FirstOrDefault(n => n.Id == id) is { } found)
⋮----
public Task RecordRetryAsync(Guid id, int attempts, DateTimeOffset next, CancellationToken cancellationToken = default)
⋮----
public Task<int> ExpireAsync(DateTimeOffset before, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
var stale = _notifications.Where(n => n.PushedAt is null && n.CreatedAt < before).ToList();
⋮----
return Task.FromResult(stale.Count);
⋮----
public Task<IReadOnlyList<string>> RecipientsAsync(string kind, DateTimeOffset since, CancellationToken cancellationToken = default)
⋮----
.Where(n => n.Kind == kind && n.CreatedAt >= since)
.Select(n => n.Recipient)
.Distinct(StringComparer.Ordinal)
⋮----
public Task<int> PruneAsync(DateTimeOffset before, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_notifications.RemoveAll(n => n.CreatedAt < before));
⋮----
public Task<IReadOnlyList<PushDevice>> DevicesAsync(string name, CancellationToken cancellationToken = default)
⋮----
.Where(d => d.Name == name)
.OrderBy(d => d.CreatedAt).ThenBy(d => d.Id)
⋮----
public Task<DeviceSave> SaveDeviceAsync(PushDevice device, CancellationToken cancellationToken = default)
⋮----
if (_devices.FirstOrDefault(d => d.Endpoint == device.Endpoint) is { } held)
⋮----
if (previous is not null && _devices.Count(d => d.Name == device.Name) >= PushDevice.MaxPerPerson)
⋮----
return Task.FromResult(new DeviceSave(DeviceSaveOutcome.TooMany, null));
⋮----
return Task.FromResult(new DeviceSave(DeviceSaveOutcome.Updated, Copy(held), previous));
⋮----
if (_devices.Count(d => d.Name == device.Name) >= PushDevice.MaxPerPerson)
⋮----
_devices.Add(added);
return Task.FromResult(new DeviceSave(DeviceSaveOutcome.Added, Copy(added)));
⋮----
public Task<bool> RemoveDeviceAsync(string name, Guid id, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_devices.RemoveAll(d => d.Id == id && d.Name == name) > 0);
⋮----
public Task RemoveDeviceAsync(Guid id, CancellationToken cancellationToken = default)
⋮----
_devices.RemoveAll(d => d.Id == id);
⋮----
public Task RecordDevicePushedAsync(Guid id, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
if (_devices.FirstOrDefault(d => d.Id == id) is { } found)
⋮----
private static Notification Copy(Notification n) => new()
⋮----
private static PushDevice Copy(PushDevice d) => new()
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/INotificationStore.cs">
public interface INotificationStore
⋮----
Task AddAsync(IReadOnlyList<Notification> notifications, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Notification>> ListAsync(string recipient, int limit, CancellationToken cancellationToken = default);
⋮----
Task<int> UnreadCountAsync(string recipient, CancellationToken cancellationToken = default);
⋮----
Task<Notification?> FindAsync(string recipient, Guid id, CancellationToken cancellationToken = default);
⋮----
Task MarkReadAsync(string recipient, Guid id, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<int> MarkAllReadAsync(string recipient, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<Notification>> PendingAsync(DateTimeOffset since, DateTimeOffset now, int limit, CancellationToken cancellationToken = default);
⋮----
Task RecordPushedAsync(Guid id, string outcome, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task RecordRetryAsync(Guid id, int attempts, DateTimeOffset next, CancellationToken cancellationToken = default);
⋮----
Task<int> ExpireAsync(DateTimeOffset before, DateTimeOffset at, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<string>> RecipientsAsync(string kind, DateTimeOffset since, CancellationToken cancellationToken = default);
⋮----
Task<int> PruneAsync(DateTimeOffset before, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<PushDevice>> DevicesAsync(string name, CancellationToken cancellationToken = default);
⋮----
Task<DeviceSave> SaveDeviceAsync(PushDevice device, CancellationToken cancellationToken = default);
⋮----
Task<bool> RemoveDeviceAsync(string name, Guid id, CancellationToken cancellationToken = default);
⋮----
Task RemoveDeviceAsync(Guid id, CancellationToken cancellationToken = default);
⋮----
Task RecordDevicePushedAsync(Guid id, DateTimeOffset at, CancellationToken cancellationToken = default);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/Notification.cs">
public sealed class Notification
⋮----
public static class NotificationPushOutcomes
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/NotificationContent.cs">
public interface INotificationContent
⋮----
bool Renders(string kind);
⋮----
Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default);
⋮----
public sealed class NotificationTexts(IEnumerable<INotificationContent> contents, ILogger<NotificationTexts> logger)
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default)
⋮----
var content = contents.FirstOrDefault(each => each.Renders(notification.Kind));
⋮----
logger.LogWarning("No area says notifications of the kind {Kind}; the notification {Id} says nothing.", notification.Kind, notification.Id);
⋮----
return await content.RenderAsync(notification, cancellationToken);
⋮----
public async Task<NotificationContent?> RenderAsync(Notification notification, string? culture, CancellationToken cancellationToken = default)
⋮----
var chosen = CultureInfo.GetCultureInfo(ConsoleCultures.IsSupported(culture) ? culture! : ConsoleCultures.Default);
⋮----
public sealed class ConsoleNotificationContent(IStringLocalizer<ConsoleResource> text) : INotificationContent
⋮----
public bool Renders(string kind) => kind == Test;
⋮----
public Task<NotificationContent?> RenderAsync(Notification notification, CancellationToken cancellationToken = default) =>
Task.FromResult<NotificationContent?>(new NotificationContent(
⋮----
public static class NotificationRoutes
⋮----
public static string Open(Guid id) => $"Notifications/{id:D}";
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/NotificationOptions.cs">
public sealed class NotificationOptions
⋮----
public sealed class VapidOptions
⋮----
missing.Add(SubjectSetting);
⋮----
missing.Add(PublicKeySetting);
⋮----
missing.Add(PrivateKeySetting);
⋮----
if (missing.Count == 0 && !Pairs.GetOrAdd((PublicKey.Trim(), PrivateKey.Trim()), _ => ArePair(publicKey!, privateKey!)))
⋮----
missing.Add(NotAPair);
⋮----
private static bool IsSubject(string subject) =>
subject.StartsWith("mailto:", StringComparison.Ordinal) && subject.Length > "mailto:".Length
|| Uri.TryCreate(subject, UriKind.Absolute, out var address) && address.Scheme == Uri.UriSchemeHttps;
⋮----
private static byte[]? Decode(string value)
⋮----
if (string.IsNullOrWhiteSpace(value))
⋮----
return WebEncoders.Base64UrlDecode(value.Trim());
⋮----
private static bool ArePair(byte[] publicKey, byte[] privateKey)
⋮----
var point = new ECPoint { X = publicKey[1..33], Y = publicKey[33..] };
using var signer = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = privateKey, Q = point });
using var verifier = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = point });
⋮----
return verifier.VerifyData(probe, signer.SignData(probe, HashAlgorithmName.SHA256), HashAlgorithmName.SHA256);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/NotificationPusher.cs">
public sealed class NotificationPusher(
⋮----
public static readonly TimeSpan Idle = TimeSpan.FromSeconds(30);
⋮----
public static readonly TimeSpan PushWindow = TimeSpan.FromHours(24);
⋮----
public static readonly TimeSpan Retention = TimeSpan.FromDays(90);
⋮----
private static readonly TimeSpan PruneEvery = TimeSpan.FromHours(1);
⋮----
private readonly SemaphoreSlim _gate = new(1, 1);
private DateTimeOffset _prunedAt = DateTimeOffset.MinValue;
⋮----
public async Task<bool> PushPendingAsync(CancellationToken cancellationToken = default)
⋮----
await _gate.WaitAsync(cancellationToken);
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
var now = clock.GetUtcNow();
⋮----
var pending = await store.PendingAsync(now - PushWindow, now, BatchSize, cancellationToken);
⋮----
_gate.Release();
⋮----
private async Task PushAsync(Notification notification, INotificationStore store, NotificationTexts texts, WebPushSender sender, CancellationToken cancellationToken)
⋮----
var devices = await store.DevicesAsync(notification.Recipient, cancellationToken);
⋮----
await store.RecordPushedAsync(notification.Id, NotificationPushOutcomes.NoDevice, clock.GetUtcNow(), cancellationToken);
⋮----
if (!said.TryGetValue(device.Culture, out var content))
⋮----
content = said[device.Culture] = await texts.RenderAsync(notification, device.Culture, cancellationToken);
⋮----
await store.RecordPushedAsync(notification.Id, NotificationPushOutcomes.Withdrawn, clock.GetUtcNow(), cancellationToken);
⋮----
var payload = new PushPayload(content.Title, content.Body, NotificationRoutes.Open(notification.Id), notification.Id.ToString("N"));
switch (await sender.SendAsync(device, payload, notification.Id.ToString("N"), cancellationToken))
⋮----
await store.RecordDevicePushedAsync(device.Id, clock.GetUtcNow(), cancellationToken);
⋮----
await store.RemoveDeviceAsync(device.Id, cancellationToken);
logger.LogInformation("The device {DeviceId} is no longer known to its push service and was removed.", device.Id);
⋮----
var next = clock.GetUtcNow() + TimeSpan.FromMinutes(1 << (attempts - 1));
await store.RecordRetryAsync(notification.Id, attempts, next, cancellationToken);
⋮----
await store.RecordPushedAsync(notification.Id, outcome, clock.GetUtcNow(), cancellationToken);
⋮----
private async Task HousekeepAsync(INotificationStore store, DateTimeOffset now, CancellationToken cancellationToken)
⋮----
var expired = await store.ExpireAsync(now - PushWindow, now, cancellationToken);
⋮----
logger.LogInformation("{Count} notifications waited longer than a day and will not be pushed.", expired);
⋮----
var pruned = await store.PruneAsync(now - Retention, cancellationToken);
⋮----
logger.LogInformation("{Count} notifications older than {Days} days were deleted.", pruned, (int)Retention.TotalDays);
⋮----
public sealed class NotificationPusherLoop(NotificationPusher pusher, NotificationSignal signal, ILogger<NotificationPusherLoop> logger) : BackgroundService
⋮----
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
⋮----
if (await pusher.PushPendingAsync(stoppingToken))
⋮----
logger.LogError(ex, "A pass of the notification pusher failed; the next pass tries again.");
⋮----
await signal.WaitAsync(NotificationPusher.Idle, stoppingToken);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/NotificationRegistration.cs">
public static class NotificationRegistration
⋮----
public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
⋮----
public static IServiceCollection AddNotifications(this IServiceCollection services, IConfiguration configuration)
⋮----
services.Configure<NotificationOptions>(configuration.GetSection(NotificationOptions.SectionName));
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
.AddHttpMessageHandler(() => new PushRequestMarker())
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
⋮----
ConnectTimeout = TimeSpan.FromSeconds(5),
⋮----
ActivityHeadersPropagator = DistributedContextPropagator.CreateNoOutputPropagator(),
⋮----
.RemoveAllLoggers();
⋮----
public static void RedactPushRequest(Activity activity, HttpRequestMessage request)
⋮----
if (!request.Options.TryGetValue(PushRequest, out var isPush) || !isPush || request.RequestUri is not { } address)
⋮----
if (activity.GetTagItem(tag) is not null)
⋮----
activity.SetTag(tag, tag is "url.path" or "http.target" ? "/" : hostOnly);
⋮----
activity.SetTag(UrlFullTag, hostOnly);
⋮----
private sealed class PushRequestMarker : DelegatingHandler
⋮----
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
⋮----
request.Options.Set(PushRequest, true);
return base.SendAsync(request, cancellationToken);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/Notifier.cs">
public sealed class Notifier(INotificationStore store, NotificationSignal signal, TimeProvider clock, ILogger<Notifier> logger)
⋮----
public async Task<int> NotifyAsync(IEnumerable<string> recipients, string kind, Guid? subjectId)
⋮----
var now = clock.GetUtcNow();
⋮----
.Select(ConsoleRoles.Normalise)
.Where(name => name.Length > 0 && ConsolePeople.IsPerson(name))
.Distinct(StringComparer.Ordinal)
.Select(name => new Notification
⋮----
Id = Guid.NewGuid(),
⋮----
.ToList();
⋮----
await store.AddAsync(notifications, CancellationToken.None);
⋮----
logger.LogError(ex, "{Count} notifications of the kind {Kind} about {SubjectId} could not be written; nobody is told.",
⋮----
signal.Poke();
⋮----
public sealed class NotificationSignal
⋮----
private readonly SemaphoreSlim _poked = new(0, 1);
⋮----
public void Poke()
⋮----
_poked.Release();
⋮----
public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) => _poked.WaitAsync(timeout, cancellationToken);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/PostgresNotificationStore.cs">
public sealed class PostgresNotificationStore(ConsoleDbContext db) : INotificationStore
⋮----
public async Task AddAsync(IReadOnlyList<Notification> notifications, CancellationToken cancellationToken = default)
⋮----
db.Notifications.AddRange(notifications);
⋮----
await db.SaveChangesAsync(cancellationToken);
⋮----
public async Task<IReadOnlyList<Notification>> ListAsync(string recipient, int limit, CancellationToken cancellationToken = default) =>
await db.Notifications.AsNoTracking()
.Where(n => n.Recipient == recipient)
.OrderByDescending(n => n.CreatedAt).ThenByDescending(n => n.Id)
.Take(limit)
.ToListAsync(cancellationToken);
⋮----
public Task<int> UnreadCountAsync(string recipient, CancellationToken cancellationToken = default) =>
db.Notifications.CountAsync(n => n.Recipient == recipient && n.ReadAt == null, cancellationToken);
⋮----
public Task<Notification?> FindAsync(string recipient, Guid id, CancellationToken cancellationToken = default) =>
db.Notifications.AsNoTracking().FirstOrDefaultAsync(n => n.Id == id && n.Recipient == recipient, cancellationToken);
⋮----
public async Task MarkReadAsync(string recipient, Guid id, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
var when = at.ToUniversalTime();
⋮----
.Where(n => n.Id == id && n.Recipient == recipient && n.ReadAt == null)
.ExecuteUpdateAsync(set => set.SetProperty(n => n.ReadAt, when), cancellationToken);
⋮----
public Task<int> MarkAllReadAsync(string recipient, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
.Where(n => n.Recipient == recipient && n.ReadAt == null)
⋮----
public async Task<IReadOnlyList<Notification>> PendingAsync(DateTimeOffset since, DateTimeOffset now, int limit, CancellationToken cancellationToken = default)
⋮----
var from = since.ToUniversalTime();
var until = now.ToUniversalTime();
return await db.Notifications.AsNoTracking()
.Where(n => n.PushedAt == null && n.CreatedAt >= from && (n.NextPushAt == null || n.NextPushAt <= until))
.OrderBy(n => n.CreatedAt).ThenBy(n => n.Id)
⋮----
public async Task RecordPushedAsync(Guid id, string outcome, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
.Where(n => n.Id == id)
.ExecuteUpdateAsync(set => set
.SetProperty(n => n.PushedAt, when)
.SetProperty(n => n.PushOutcome, outcome)
.SetProperty(n => n.NextPushAt, (DateTimeOffset?)null), cancellationToken);
⋮----
public async Task RecordRetryAsync(Guid id, int attempts, DateTimeOffset next, CancellationToken cancellationToken = default)
⋮----
var when = next.ToUniversalTime();
⋮----
.SetProperty(n => n.PushAttempts, attempts)
.SetProperty(n => n.NextPushAt, when), cancellationToken);
⋮----
public Task<int> ExpireAsync(DateTimeOffset before, DateTimeOffset at, CancellationToken cancellationToken = default)
⋮----
var cutoff = before.ToUniversalTime();
⋮----
.Where(n => n.PushedAt == null && n.CreatedAt < cutoff)
⋮----
.SetProperty(n => n.PushOutcome, NotificationPushOutcomes.Expired)
⋮----
public async Task<IReadOnlyList<string>> RecipientsAsync(string kind, DateTimeOffset since, CancellationToken cancellationToken = default)
⋮----
.Where(n => n.Kind == kind && n.CreatedAt >= from)
.Select(n => n.Recipient)
.Distinct()
⋮----
public Task<int> PruneAsync(DateTimeOffset before, CancellationToken cancellationToken = default)
⋮----
return db.Notifications.Where(n => n.CreatedAt < cutoff).ExecuteDeleteAsync(cancellationToken);
⋮----
public async Task<IReadOnlyList<PushDevice>> DevicesAsync(string name, CancellationToken cancellationToken = default) =>
await db.PushDevices.AsNoTracking()
.Where(d => d.Name == name)
.OrderBy(d => d.CreatedAt).ThenBy(d => d.Id)
⋮----
public async Task<DeviceSave> SaveDeviceAsync(PushDevice device, CancellationToken cancellationToken = default)
⋮----
private async Task<DeviceSave> TrySaveDeviceAsync(PushDevice device, CancellationToken cancellationToken)
⋮----
var held = tracked = await db.PushDevices.FirstOrDefaultAsync(d => d.Endpoint == device.Endpoint, cancellationToken);
⋮----
&& await db.PushDevices.CountAsync(d => d.Name == device.Name, cancellationToken) >= PushDevice.MaxPerPerson)
⋮----
return new DeviceSave(DeviceSaveOutcome.TooMany, null);
⋮----
added.CreatedAt = device.CreatedAt.ToUniversalTime();
db.PushDevices.Add(added);
⋮----
return new DeviceSave(DeviceSaveOutcome.Added, added);
⋮----
held.CreatedAt = device.CreatedAt.ToUniversalTime();
⋮----
return new DeviceSave(DeviceSaveOutcome.Updated, held, previous);
⋮----
db.Entry(tracked).State = EntityState.Detached;
⋮----
private void Detach(IEnumerable<Notification> notifications)
... (16 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/PushDevice.cs">
public sealed class PushDevice
⋮----
public string Service => Uri.TryCreate(Endpoint, UriKind.Absolute, out var address) ? address.IdnHost : string.Empty;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/PushDeviceLabel.cs">
public static class PushDeviceLabel
⋮----
public static string From(string? userAgent)
⋮----
private static string Browser(string agent) =>
⋮----
private static string System(string agent) =>
⋮----
private static bool Has(string agent, string token) => agent.Contains(token, StringComparison.Ordinal);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Notifications/WebPushSender.cs">
public sealed class WebPushSender(HttpClient http, IOptionsMonitor<NotificationOptions> options, ILogger<WebPushSender> logger)
⋮----
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
⋮----
private readonly PushServiceClient _client = new(http) { AutoRetryAfter = false };
⋮----
public async Task<PushResult> SendAsync(PushDevice device, PushPayload payload, string topic, CancellationToken cancellationToken)
⋮----
var subscription = new PushSubscription { Endpoint = device.Endpoint };
subscription.SetKey(PushEncryptionKeyName.P256DH, device.P256dh);
subscription.SetKey(PushEncryptionKeyName.Auth, device.Auth);
⋮----
var message = new PushMessage(JsonSerializer.Serialize(payload, Json))
⋮----
using var authentication = new VapidAuthentication(vapid.PublicKey.Trim(), vapid.PrivateKey.Trim()) { Subject = vapid.Subject.Trim() };
await _client.RequestPushMessageDeliveryAsync(subscription, message, authentication, VapidAuthenticationScheme.Vapid, cancellationToken);
⋮----
logger.LogWarning("{Service} answered {Status} to a push for the device {DeviceId}: {Result}.", device.Service, status, device.Id, result);
⋮----
catch (Exception ex) when (Crm.NotPublicAddressException.In(ex))
⋮----
logger.LogWarning("The device {DeviceId}'s endpoint does not resolve to a public address; nothing was sent.", device.Id);
⋮----
logger.LogWarning("{Service} could not be reached for a push to the device {DeviceId} ({Error}); to be tried again.",
device.Service, device.Id, ex.GetType().Name);
⋮----
logger.LogWarning("The device {DeviceId}'s subscription could not be used for a push ({Error}).", device.Id, ex.GetType().Name);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Ollama/OllamaConnection.cs">
public sealed class OllamaConnection(IHttpClientFactory clients, IOptionsMonitor<OllamaOptions> options, ILogger<OllamaConnection> logger)
⋮----
public async Task<OllamaTest> TestAsync(string? model, CancellationToken cancellationToken = default)
⋮----
if (!settings.IsConfigured || string.IsNullOrWhiteSpace(model))
⋮----
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(settings.BaseAddress!, ChatPath))
⋮----
Content = new StringContent(Body(model.Trim()).ToJsonString(), Encoding.UTF8, "application/json"),
⋮----
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", settings.ApiKey!.Trim());
⋮----
HttpResponseMessage response;
⋮----
response = await clients.CreateClient(OllamaRegistration.HttpClientName).SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("Ollama could not be reached to test the connection: {Failure}.", ex.GetType().Name);
⋮----
logger.LogWarning(
⋮----
(int)response.StatusCode, ErrorOf(await response.Content.ReadAsStringAsync(cancellationToken)));
⋮----
internal static JsonObject Body(string model) => new()
⋮----
["messages"] = new JsonArray(new JsonNode?[]
⋮----
new JsonObject { ["role"] = "user", ["content"] = Prompt },
⋮----
["options"] = new JsonObject { ["num_predict"] = 1, ["temperature"] = 0 },
⋮----
private static string ErrorOf(string body)
⋮----
error = JsonNode.Parse(body)?["error"]?.GetValue<string>();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Ollama/OllamaOptions.cs">
public sealed class OllamaOptions
⋮----
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60);
⋮----
public bool IsConfigured => !string.IsNullOrWhiteSpace(ApiKey) && BaseAddress is not null;
⋮----
if (string.IsNullOrWhiteSpace(ApiKey))
⋮----
missing.Add(ApiKeySecret);
⋮----
missing.Add(BaseUrlSetting);
⋮----
if (string.IsNullOrWhiteSpace(BaseUrl)
|| !Uri.TryCreate(BaseUrl.Trim().TrimEnd('/') + "/", UriKind.Absolute, out var address))
</file>

<file path="src/KnowledgeFabric.AdminConsole/Ollama/OllamaRegistration.cs">
public static class OllamaRegistration
⋮----
public static IServiceCollection AddOllama(this IServiceCollection services, IConfiguration configuration)
⋮----
.Bind(configuration.GetSection(OllamaOptions.SectionName))
⋮----
if (RetiredBusinessCardKey.FallbackFrom(settings) is { } retired)
⋮----
services.AddHttpClient(HttpClientName, (provider, http) =>
⋮----
.RemoveAllLoggers();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Ollama/OllamaSearchClient.cs">
public static WebSearch Failed(SearchOutcome outcome, int? status = null) => new(outcome, [], status);
⋮----
public interface ISearchClient
⋮----
Task<WebSearch> SearchAsync(string query, int maxResults, CancellationToken cancellationToken = default);
⋮----
public sealed partial class OllamaSearchClient(
⋮----
ILogger<OllamaSearchClient> logger) : ISearchClient
⋮----
public async Task<WebSearch> SearchAsync(string query, int maxResults, CancellationToken cancellationToken = default)
⋮----
if (!account.IsConfigured || string.IsNullOrWhiteSpace(query))
⋮----
return WebSearch.Failed(SearchOutcome.NotConfigured);
⋮----
var body = new JsonObject
⋮----
[QueryField] = query.Trim(),
[MaxResultsField] = Math.Clamp(maxResults, 1, MostResults),
⋮----
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(account.BaseAddress!, SearchPath))
⋮----
Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json"),
⋮----
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", account.ApiKey!.Trim());
⋮----
HttpResponseMessage response;
⋮----
response = await clients.CreateClient(OllamaRegistration.HttpClientName).SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("Ollama's web search could not be reached: {Failure}.", ex.GetType().Name);
return WebSearch.Failed(SearchOutcome.Unreachable);
⋮----
var answer = await response.Content.ReadAsStringAsync(cancellationToken);
⋮----
logger.LogWarning("Ollama's web search answered {Status}: {Error}", (int)response.StatusCode, ErrorOf(answer));
return WebSearch.Failed(outcome, (int)response.StatusCode);
⋮----
logger.LogWarning("Ollama's web search answered something that is not a list of results.");
return WebSearch.Failed(SearchOutcome.NotUnderstood, (int)response.StatusCode);
⋮----
return new WebSearch(SearchOutcome.Read, results, (int)response.StatusCode);
⋮----
internal static IReadOnlyList<SearchResult>? Parse(string answer)
⋮----
if (JsonNode.Parse(answer)?[ResultsField] is not JsonArray items)
⋮----
var url = Text(item, UrlField).Trim();
if (url.Length is 0 or > MaxUrl || !Uri.TryCreate(url, UriKind.Absolute, out var address)
⋮----
results.Add(new SearchResult(
Cut(Whitespace().Replace(Text(item, TitleField), " ").Trim(), MaxTitle),
⋮----
Cut(Text(item, ContentField).Trim(), MaxContent)));
⋮----
private static string Text(JsonObject item, string field) =>
⋮----
private static string Cut(string text, int length) => text.Length > length ? text[..length] : text;
⋮----
private static string ErrorOf(string body)
⋮----
error = JsonNode.Parse(body)?["error"]?.GetValue<string>();
⋮----
private static partial Regex Whitespace();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Ollama/OllamaThinking.cs">
public static class OllamaThinking
⋮----
public static bool ByLevel(string model) => model.Trim().StartsWith("gpt-oss", StringComparison.OrdinalIgnoreCase);
⋮----
public static JsonNode Least(string model) => ByLevel(model) ? JsonValue.Create(LowestLevel)! : JsonValue.Create(false);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Ollama/RetiredBusinessCardKey.cs">
public sealed class RetiredBusinessCardKey(IConfiguration configuration, ILogger<RetiredBusinessCardKey> logger) : IHostedService
⋮----
public static string? FallbackFrom(IConfiguration configuration) =>
string.IsNullOrWhiteSpace(configuration[OllamaOptions.ApiKeySetting]) && configuration[Key] is { } retired && !string.IsNullOrWhiteSpace(retired)
⋮----
public Task StartAsync(CancellationToken cancellationToken)
⋮----
logger.LogWarning(
⋮----
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Preferences/DashboardPreferences.cs">
public sealed class DashboardPreferences(IFeatureStateStore store, ILogger<DashboardPreferences> logger)
⋮----
public async Task<DashboardOrder> OrderOfAsync(string name, CancellationToken cancellationToken = default)
⋮----
var chosen = await store.GetAsync<string[]>(Collection, ConsoleRoles.Normalise(name), cancellationToken);
return new DashboardOrder(Arrange(chosen), Chosen: chosen is not null, Readable: true);
⋮----
logger.LogError(ex, "The dashboard order of {Name} could not be read; the overview is in the default order.", name);
return new DashboardOrder(Arrange(null), Chosen: false, Readable: false);
⋮----
public async Task<bool> SetAsync(string name, IReadOnlyList<string> order, CancellationToken cancellationToken = default)
⋮----
var key = ConsoleRoles.Normalise(name);
⋮----
if (held is not null && Arrange(held).SequenceEqual(arranged, StringComparer.Ordinal))
⋮----
await store.SetAsync(Collection, key, arranged.ToArray(), cancellationToken);
⋮----
public Task<bool> ResetAsync(string name, CancellationToken cancellationToken = default) =>
store.RemoveAsync(Collection, ConsoleRoles.Normalise(name), cancellationToken);
⋮----
public static IReadOnlyList<string> Arrange(IEnumerable<string>? chosen)
⋮----
.Where(key => OverviewArea.Find(key) is not null)
.Distinct(StringComparer.Ordinal)
.ToList();
⋮----
placed.AddRange(OverviewArea.All.Select(area => area.Key).Where(key => !placed.Contains(key, StringComparer.Ordinal)));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Preferences/OverviewAreas.cs">
public static OverviewArea? Find(string? key) => All.FirstOrDefault(area => area.Key == key);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Properties/launchSettings.json">
{
    "$schema": "https://json.schemastore.org/launchsettings.json",
    "profiles": {
        "https": {
            "commandName": "Project",
            "dotnetRunMessages": true,
            "launchBrowser": true,
            "applicationUrl": "https://localhost:7043;http://localhost:5043",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        }
    }
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Resources/ConsoleResource.cs">
public sealed class ConsoleResource
</file>

<file path="src/KnowledgeFabric.AdminConsole/Resources/ConsoleResource.it.resx">
<?xml version="1.0" encoding="utf-8"?>
<root>
  <!--
    The console's one shared resource (#102). Keys are dotted, by area and page; the Italian file
    beside this one holds exactly the same keys, and a test says so. docs/Localisation.md explains
    how to add a string or a language.
  -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="Binding.ValueMustNotBeNull" xml:space="preserve">
    <value>È richiesto un valore.</value>
  </data>
  <data name="Binding.MissingBindRequiredValue" xml:space="preserve">
    <value>È richiesto un valore per '{0}'.</value>
  </data>
  <data name="Binding.MissingKeyOrValue" xml:space="preserve">
    <value>È richiesto un valore.</value>
  </data>
  <data name="Binding.MissingRequestBodyRequiredValue" xml:space="preserve">
    <value>È richiesto un corpo della richiesta non vuoto.</value>
  </data>
  <data name="Binding.AttemptedValueIsInvalid" xml:space="preserve">
    <value>Il valore '{0}' non è valido per {1}.</value>
  </data>
  <data name="Binding.NonPropertyAttemptedValueIsInvalid" xml:space="preserve">
    <value>Il valore '{0}' non è valido.</value>
  </data>
  <data name="Binding.UnknownValueIsInvalid" xml:space="preserve">
    <value>Il valore fornito non è valido per {0}.</value>
  </data>
  <data name="Binding.NonPropertyUnknownValueIsInvalid" xml:space="preserve">
    <value>Il valore fornito non è valido.</value>
  </data>
  <data name="Binding.ValueIsInvalid" xml:space="preserve">
    <value>Il valore '{0}' non è valido.</value>
  </data>
  <data name="Binding.ValueMustBeANumber" xml:space="preserve">
    <value>Il campo {0} deve essere un numero.</value>
  </data>
  <data name="Binding.NonPropertyValueMustBeANumber" xml:space="preserve">
    <value>Il campo deve essere un numero.</value>
  </data>
  <data name="Shell.Language.Choose" xml:space="preserve">
    <value>Lingua</value>
... (8355 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Resources/ConsoleResource.resx">
<?xml version="1.0" encoding="utf-8"?>
<root>
  <!--
    The console's one shared resource (#102). Keys are dotted, by area and page; the Italian file
    beside this one holds exactly the same keys, and a test says so. docs/Localisation.md explains
    how to add a string or a language.
  -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="Binding.ValueMustNotBeNull" xml:space="preserve">
    <value>A value is required.</value>
  </data>
  <data name="Binding.MissingBindRequiredValue" xml:space="preserve">
    <value>A value for '{0}' is required.</value>
  </data>
  <data name="Binding.MissingKeyOrValue" xml:space="preserve">
    <value>A value is required.</value>
  </data>
  <data name="Binding.MissingRequestBodyRequiredValue" xml:space="preserve">
    <value>A non-empty request body is required.</value>
  </data>
  <data name="Binding.AttemptedValueIsInvalid" xml:space="preserve">
    <value>The value '{0}' is not valid for {1}.</value>
  </data>
  <data name="Binding.NonPropertyAttemptedValueIsInvalid" xml:space="preserve">
    <value>The value '{0}' is not valid.</value>
  </data>
  <data name="Binding.UnknownValueIsInvalid" xml:space="preserve">
    <value>The supplied value is invalid for {0}.</value>
  </data>
  <data name="Binding.NonPropertyUnknownValueIsInvalid" xml:space="preserve">
    <value>The supplied value is invalid.</value>
  </data>
  <data name="Binding.ValueIsInvalid" xml:space="preserve">
    <value>The value '{0}' is invalid.</value>
  </data>
  <data name="Binding.ValueMustBeANumber" xml:space="preserve">
    <value>The field {0} must be a number.</value>
  </data>
  <data name="Binding.NonPropertyValueMustBeANumber" xml:space="preserve">
    <value>The field must be a number.</value>
  </data>
  <data name="Shell.Language.Choose" xml:space="preserve">
    <value>Language</value>
... (8355 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/AuthenticationRegistration.cs">
public static class AuthenticationRegistration
⋮----
public static IServiceCollection AddConsoleAuthentication(
⋮----
configuration.GetSection(ConsoleAuthenticationOptions.SectionName));
⋮----
services.AddMemoryCache();
⋮----
.GetSection(ConsoleAuthenticationOptions.SectionName)
.Get<ConsoleAuthenticationOptions>()?.SessionLifetime ?? TimeSpan.FromHours(8);
⋮----
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
⋮----
public static IServiceCollection AddConsoleAuthorization(
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
⋮----
else if (environment.IsDevelopment())
⋮----
services.AddAuthorization(options =>
⋮----
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
⋮----
options.AddPolicy(ConsolePolicies.ViewConsole, policy => policy.RequireAuthenticatedUser());
⋮----
private static void AddRolePolicy(AuthorizationOptions options, string policy, params string[] roles) =>
options.AddPolicy(policy, builder => builder
⋮----
.AddRequirements(new RoleRequirement(roles)));
⋮----
private static async Task ValidateCredentialStillExistsAsync(CookieValidatePrincipalContext context)
⋮----
if (actor is null || options.PasswordFor(actor) is null)
⋮----
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsoleAuthenticationOptions.cs">
public sealed class ConsoleAuthenticationOptions
⋮----
public TimeSpan LockoutDuration { get; set; } = TimeSpan.FromMinutes(15);
⋮----
public TimeSpan SessionLifetime { get; set; } = TimeSpan.FromHours(8);
⋮----
.Where(user => !string.IsNullOrEmpty(user.Value) && !string.IsNullOrWhiteSpace(user.Key) && !IsReserved(user.Key.Trim()))
.Select(user => user.Key.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
⋮----
public string? PasswordFor(string name)
⋮----
if (string.Equals(configured.Trim(), name, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(password))
⋮----
private static bool IsReserved(string name) => ConsoleClaims.IsReserved(name);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsoleClaims.cs">
public static class ConsoleClaims
⋮----
public static bool IsReserved(string? actor) =>
string.Equals(actor, SharedCredentialActor, StringComparison.OrdinalIgnoreCase)
|| string.Equals(actor, GuestActor, StringComparison.OrdinalIgnoreCase);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsoleCredentials.cs">
public sealed class ConsoleCredentials
⋮----
public SignInOutcome Verify(string? name, string? password)
⋮----
_logger.LogError(
⋮----
return SignInOutcome.Refused("not-configured");
⋮----
if (string.IsNullOrEmpty(password))
⋮----
return SignInOutcome.Refused("no-password");
⋮----
var configured = name is null ? null : options.PasswordFor(name);
⋮----
return SignInOutcome.Refused(name is null ? "no-name" : "unknown-name");
⋮----
? SignInOutcome.Accepted(name!)
: SignInOutcome.Refused("wrong-password");
⋮----
private static bool Matches(string submitted, string configured)
⋮----
SHA256.HashData(Encoding.UTF8.GetBytes(submitted), submittedHash);
SHA256.HashData(Encoding.UTF8.GetBytes(configured), configuredHash);
⋮----
return CryptographicOperations.FixedTimeEquals(submittedHash, configuredHash);
⋮----
public static SignInOutcome Accepted(string actor) => new(true, actor, null);
⋮----
public static SignInOutcome Refused(string reason) => new(false, null, reason);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsolePeople.cs">
public sealed class ConsolePeople(IConsoleRoleStore store, IOptionsMonitor<ConsoleAuthenticationOptions> options)
⋮----
public Task<IReadOnlyList<string>> CrmAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<string>> BookingAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<string>> CompetitorsAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<string>> GatewayWritersAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<string>> GatewayAsync(CancellationToken cancellationToken = default) =>
⋮----
private async Task<IReadOnlyList<string>> HoldingAsync(IReadOnlyCollection<string> roles, CancellationToken cancellationToken)
⋮----
var grants = await store.AllAsync(cancellationToken);
⋮----
var configured = options.CurrentValue.Names.ToDictionary(ConsoleRoles.Normalise, name => name, StringComparer.Ordinal);
⋮----
.Where(grant => roles.Contains(grant.Role))
.Select(grant => grant.Name)
.Where(IsPerson)
.Distinct(StringComparer.Ordinal)
.Select(name => configured.GetValueOrDefault(name) ?? name)
.OrderBy(name => name, StringComparer.OrdinalIgnoreCase)
.ToList();
⋮----
public async Task<PeopleInitials> InitialsAsync(CancellationToken cancellationToken = default) =>
new((await store.InitialsAsync(cancellationToken))
.Where(row => IsPerson(row.Name))
.ToDictionary(row => row.Name, row => row.Initials, StringComparer.Ordinal));
⋮----
public static bool IsPerson(string? name) => !ConsoleRoles.IsAdmin(name);
⋮----
public static IReadOnlyList<string> OnlySignedIn(string signedInAs) => IsPerson(signedInAs) ? [signedInAs] : [];
⋮----
public sealed class PeopleInitials
⋮----
public static readonly PeopleInitials None = new(new Dictionary<string, string>(StringComparer.Ordinal));
⋮----
public string? Of(string? name) =>
string.IsNullOrWhiteSpace(name) ? null : _byName.GetValueOrDefault(ConsoleRoles.Normalise(name));
⋮----
public string Shown(string name) => Of(name) ?? name;
⋮----
public string Choice(string name) => Of(name) is { } initials ? $"{initials} — {name}" : name;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsolePolicies.cs">
public static class ConsolePolicies
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsoleRoles.cs">
public static class ConsoleRoles
⋮----
public static bool IsRole(string? role) => role is not null && All.Contains(role, StringComparer.Ordinal);
⋮----
public static bool IsAdmin(string? name) =>
string.Equals(name?.Trim(), AdminName, StringComparison.OrdinalIgnoreCase);
⋮----
public static string Normalise(string name) => name.Trim().ToLowerInvariant();
⋮----
public static (string Area, string? Verb) Keys(string role)
⋮----
var dot = role.IndexOf('.', StringComparison.Ordinal);
⋮----
public static string? IncludedBy(string role) => role switch
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/IConsoleRoleStore.cs">
public interface IConsoleRoleStore
⋮----
Task<IReadOnlySet<string>> RolesOfAsync(string name, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<RoleGrant>> AllAsync(CancellationToken cancellationToken = default);
⋮----
Task<bool> GrantAsync(string name, string role, string grantedBy, DateTimeOffset grantedAt, CancellationToken cancellationToken = default);
⋮----
Task<bool> RevokeAsync(string name, string role, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<PersonInitials>> InitialsAsync(CancellationToken cancellationToken = default);
⋮----
Task<bool> SetInitialsAsync(string name, string initials, string setBy, DateTimeOffset setAt, CancellationToken cancellationToken = default);
⋮----
public sealed class RoleGrant
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/InMemoryConsoleRoleStore.cs">
public sealed class InMemoryConsoleRoleStore : IConsoleRoleStore
⋮----
public Task<IReadOnlySet<string>> RolesOfAsync(string name, CancellationToken cancellationToken = default)
⋮----
var key = ConsoleRoles.Normalise(name);
⋮----
_grants.Where(grant => grant.Name == key).Select(grant => grant.Role).ToHashSet(StringComparer.Ordinal));
⋮----
public Task<IReadOnlyList<RoleGrant>> AllAsync(CancellationToken cancellationToken = default)
⋮----
_grants.OrderBy(grant => grant.Name, StringComparer.Ordinal).ThenBy(grant => grant.Role, StringComparer.Ordinal).ToList());
⋮----
public Task<bool> GrantAsync(string name, string role, string grantedBy, DateTimeOffset grantedAt, CancellationToken cancellationToken = default)
⋮----
if (_grants.Any(grant => grant.Name == key && grant.Role == role))
⋮----
return Task.FromResult(false);
⋮----
_grants.Add(new RoleGrant { Name = key, Role = role, GrantedBy = grantedBy, GrantedAt = grantedAt });
return Task.FromResult(true);
⋮----
public Task<bool> RevokeAsync(string name, string role, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(_grants.RemoveAll(grant => grant.Name == key && grant.Role == role) > 0);
⋮----
public Task<IReadOnlyList<PersonInitials>> InitialsAsync(CancellationToken cancellationToken = default)
⋮----
.OrderBy(row => row.Name, StringComparer.Ordinal)
.Select(row => new PersonInitials { Name = row.Name, Initials = row.Initials, SetBy = row.SetBy, SetAt = row.SetAt })
.ToList());
⋮----
public Task<bool> SetInitialsAsync(string name, string initials, string setBy, DateTimeOffset setAt, CancellationToken cancellationToken = default)
⋮----
var held = _initials.GetValueOrDefault(key)?.Initials ?? string.Empty;
⋮----
_initials.Remove(key);
⋮----
_initials[key] = new PersonInitials { Name = key, Initials = initials, SetBy = setBy, SetAt = setAt };
⋮----
public sealed class UnavailableConsoleRoleStore : IConsoleRoleStore
⋮----
public Task<IReadOnlySet<string>> RolesOfAsync(string name, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<RoleGrant>> AllAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<bool> GrantAsync(string name, string role, string grantedBy, DateTimeOffset grantedAt, CancellationToken cancellationToken = default) =>
throw new InvalidOperationException("Roles cannot be granted: the console has no database.");
⋮----
public Task<bool> RevokeAsync(string name, string role, CancellationToken cancellationToken = default) =>
Task.FromResult(false);
⋮----
public Task<IReadOnlyList<PersonInitials>> InitialsAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<bool> SetInitialsAsync(string name, string initials, string setBy, DateTimeOffset setAt, CancellationToken cancellationToken = default) =>
throw new InvalidOperationException("Initials cannot be set: the console has no database.");
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/LoginThrottle.cs">
public sealed class LoginThrottle
⋮----
private readonly IMemoryCache _cache;
⋮----
private static string CallerKey(string caller) => $"login-failures:caller:{caller}";
⋮----
private static string NameKey(string name) => $"login-failures:name:{name.ToLowerInvariant()}";
⋮----
private static IEnumerable<string> KeysFor(string caller, string? name)
⋮----
if (!string.IsNullOrWhiteSpace(name))
⋮----
yield return NameKey(name.Trim());
⋮----
public bool IsLockedOut(string caller, string? name, out TimeSpan retryAfter)
⋮----
if (!_cache.TryGetValue(key, out FailureRecord? record) || record is null)
⋮----
_cache.Remove(key);
⋮----
public void RecordFailure(string caller, string? name)
⋮----
var expiresAt = DateTimeOffset.UtcNow.Add(lockoutDuration);
⋮----
var record = _cache.TryGetValue(key, out FailureRecord? existing) && existing is not null
⋮----
: new FailureRecord(1, expiresAt);
⋮----
_cache.Set(key, record, expiresAt);
⋮----
public void Reset(string caller, string? name)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/PersonInitials.cs">
public sealed class PersonInitials
⋮----
public static string? Parse(string? typed)
⋮----
return said.Length <= Length && said.All(char.IsLetter) ? said.ToUpperInvariant() : null;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/PostgresConsoleRoleStore.cs">
public sealed class PostgresConsoleRoleStore(ConsoleDbContext db) : IConsoleRoleStore
⋮----
public async Task<IReadOnlySet<string>> RolesOfAsync(string name, CancellationToken cancellationToken = default)
⋮----
var key = ConsoleRoles.Normalise(name);
⋮----
var roles = await db.RoleGrants.AsNoTracking()
.Where(grant => grant.Name == key)
.Select(grant => grant.Role)
.ToListAsync(cancellationToken);
⋮----
return roles.ToHashSet(StringComparer.Ordinal);
⋮----
public async Task<IReadOnlyList<RoleGrant>> AllAsync(CancellationToken cancellationToken = default) =>
await db.RoleGrants.AsNoTracking()
.OrderBy(grant => grant.Name)
.ThenBy(grant => grant.Role)
⋮----
public async Task<bool> GrantAsync(string name, string role, string grantedBy, DateTimeOffset grantedAt, CancellationToken cancellationToken = default)
⋮----
var inserted = await db.Database.ExecuteSqlInterpolatedAsync(
⋮----
VALUES ({key}, {role}, {by}, {grantedAt.ToUniversalTime()})
⋮----
public async Task<bool> RevokeAsync(string name, string role, CancellationToken cancellationToken = default)
⋮----
.Where(grant => grant.Name == key && grant.Role == role)
.ExecuteDeleteAsync(cancellationToken) > 0;
⋮----
public async Task<IReadOnlyList<PersonInitials>> InitialsAsync(CancellationToken cancellationToken = default) =>
await db.Initials.AsNoTracking()
.OrderBy(row => row.Name)
⋮----
public async Task<bool> SetInitialsAsync(string name, string initials, string setBy, DateTimeOffset setAt, CancellationToken cancellationToken = default)
⋮----
return await db.Initials.Where(row => row.Name == key).ExecuteDeleteAsync(cancellationToken) > 0;
⋮----
var written = await db.Database.ExecuteSqlInterpolatedAsync(
⋮----
VALUES ({key}, {initials}, {by}, {setAt.ToUniversalTime()})
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/RetiredSharedPassword.cs">
public sealed class RetiredSharedPassword(IConfiguration configuration, ILogger<RetiredSharedPassword> logger) : IHostedService
⋮----
public Task StartAsync(CancellationToken cancellationToken)
⋮----
if (!string.IsNullOrEmpty(configuration[Key]))
⋮----
logger.LogWarning(
⋮----
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/RoleRequirement.cs">
public sealed class RoleRequirement(params string[] roles) : IAuthorizationRequirement
⋮----
public sealed class RoleAuthorizationHandler(SessionRoles sessionRoles) : AuthorizationHandler<RoleRequirement>
⋮----
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
⋮----
var held = await sessionRoles.OfAsync(context.User);
if (held.Satisfies(requirement.Roles))
⋮----
context.Succeed(requirement);
⋮----
public sealed class SessionRoles(IConsoleRoleStore store, ILogger<SessionRoles> logger)
⋮----
public async Task<HeldRoles> OfAsync(ClaimsPrincipal user, CancellationToken cancellationToken = default)
⋮----
private async Task<HeldRoles> ReadAsync(string? name, CancellationToken cancellationToken)
⋮----
return new HeldRoles(name, IsAdmin: false, HeldRoles.None, Unreadable: false);
⋮----
if (ConsoleRoles.IsAdmin(name))
⋮----
return new HeldRoles(name, IsAdmin: true, HeldRoles.None, Unreadable: false);
⋮----
return new HeldRoles(name, IsAdmin: false, await store.RolesOfAsync(name, cancellationToken), Unreadable: false);
⋮----
logger.LogError(ex, "The roles of {Name} could not be read; the session holds none until they can be.", name);
return new HeldRoles(name, IsAdmin: false, HeldRoles.None, Unreadable: true);
⋮----
public bool Satisfies(IEnumerable<string> roles) =>
IsAdmin || Roles.Contains(ConsoleRoles.Administrator) || roles.Any(Roles.Contains);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Storage/FeatureStateRegistration.cs">
public static class FeatureStateRegistration
⋮----
public static IServiceCollection AddFeatureState(this IServiceCollection services, IConfiguration configuration)
⋮----
var database = configuration.GetSection(DatabaseOptions.SectionName).Get<DatabaseOptions>() ?? new DatabaseOptions();
</file>

<file path="src/KnowledgeFabric.AdminConsole/Storage/IFeatureStateStore.cs">
public interface IFeatureStateStore
⋮----
Task<T?> GetAsync<T>(string collection, string key, CancellationToken cancellationToken = default);
⋮----
Task SetAsync<T>(string collection, string key, T value, CancellationToken cancellationToken = default);
⋮----
Task<bool> SetIfAsync<T>(string collection, string key, T? expected, T value, CancellationToken cancellationToken = default)
where T : class;
⋮----
Task<bool> RemoveAsync(string collection, string key, CancellationToken cancellationToken = default);
⋮----
Task<IReadOnlyList<string>> ListKeysAsync(string collection, CancellationToken cancellationToken = default);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Storage/InMemoryFeatureStateStore.cs">
public sealed class InMemoryFeatureStateStore : IFeatureStateStore
⋮----
private ConcurrentDictionary<string, string> Collection(string collection) =>
_collections.GetOrAdd(collection, _ => new ConcurrentDictionary<string, string>());
⋮----
public Task<T?> GetAsync<T>(string collection, string key, CancellationToken cancellationToken = default)
⋮----
if (!Collection(collection).TryGetValue(key, out var json))
⋮----
return Task.FromResult(JsonSerializer.Deserialize<T>(json));
⋮----
public Task SetAsync<T>(string collection, string key, T value, CancellationToken cancellationToken = default)
⋮----
Collection(collection)[key] = JsonSerializer.Serialize(value);
⋮----
public Task<bool> SetIfAsync<T>(string collection, string key, T? expected, T value, CancellationToken cancellationToken = default)
where T : class
⋮----
var json = JsonSerializer.Serialize(value);
⋮----
return Task.FromResult(expected is null
? documents.TryAdd(key, json)
: documents.TryUpdate(key, json, JsonSerializer.Serialize(expected)));
⋮----
public Task<bool> RemoveAsync(string collection, string key, CancellationToken cancellationToken = default) =>
Task.FromResult(Collection(collection).TryRemove(key, out _));
⋮----
public Task<IReadOnlyList<string>> ListKeysAsync(string collection, CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyList<string>>(Collection(collection).Keys.ToList());
</file>

<file path="src/KnowledgeFabric.AdminConsole/Storage/PostgresFeatureStateStore.cs">
public sealed class PostgresFeatureStateStore(ConsoleDbContext db, TimeProvider clock) : IFeatureStateStore
⋮----
public async Task<T?> GetAsync<T>(string collection, string key, CancellationToken cancellationToken = default)
⋮----
var json = await db.FeatureState.AsNoTracking()
.Where(row => row.Collection == collection && row.Key == key)
.Select(row => row.Value)
.FirstOrDefaultAsync(cancellationToken);
⋮----
public async Task SetAsync<T>(string collection, string key, T value, CancellationToken cancellationToken = default)
⋮----
var json = JsonSerializer.Serialize(value);
var at = clock.GetUtcNow().ToUniversalTime();
⋮----
await db.Database.ExecuteSqlInterpolatedAsync(
⋮----
public async Task<bool> SetIfAsync<T>(string collection, string key, T? expected, T value, CancellationToken cancellationToken = default)
where T : class
⋮----
return await db.Database.ExecuteSqlInterpolatedAsync(
⋮----
var held = JsonSerializer.Serialize(expected);
⋮----
public async Task<bool> RemoveAsync(string collection, string key, CancellationToken cancellationToken = default) =>
⋮----
.ExecuteDeleteAsync(cancellationToken) > 0;
⋮----
public async Task<IReadOnlyList<string>> ListKeysAsync(string collection, CancellationToken cancellationToken = default) =>
await db.FeatureState.AsNoTracking()
.Where(row => row.Collection == collection)
.OrderBy(row => row.Key)
.Select(row => row.Key)
.ToListAsync(cancellationToken);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Storage/StoredFeatureState.cs">
public sealed class StoredFeatureState
</file>

<file path="src/KnowledgeFabric.AdminConsole/ViewComponents/NotificationBellViewComponent.cs">
public sealed class NotificationBellViewComponent(INotificationStore store, ILogger<NotificationBellViewComponent> logger) : ViewComponent
⋮----
public async Task<IViewComponentResult> InvokeAsync()
⋮----
if (string.IsNullOrEmpty(name) || ConsoleRoles.IsAdmin(name))
⋮----
unread = await store.UnreadCountAsync(ConsoleRoles.Normalise(name), HttpContext.RequestAborted);
⋮----
logger.LogError(ex, "The unread notifications could not be counted; the bell shows no count.");
⋮----
return View(new NotificationBell(unread));
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Account/Login.cshtml">
@using System.Globalization
@model LoginModel
@{
    ViewData["title"] = T["Account.Login.Title"].Value;
    Layout = "_BlankLayout";
    // A launch signed out lands here, redirected from the start URL (Sections/_LaunchSplash).
    ViewData["launchSplash"] = true;
    var current = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
    var returnUrl = Context.Request.Path + Context.Request.QueryString;
}

<div class="authentication-wrapper">
    <div class="authentication-inner">

        <div class="card">
            <div class="card-body">

                <div class="app-brand justify-content-center mb-4">
                    <span class="app-brand-logo demo">
                        <img src="~/img/logo/kf-logo-icon-bg-transparent.png" asp-append-version="true" width="36" height="32" alt="" />
                    </span>
                    <span class="app-brand-text demo text-body fw-bold ms-2">@ConsoleBranding.AppName</span>
                </div>

                <p class="text-center text-body mb-4">@T["Account.Login.Lead"]</p>

                <form method="post" asp-controller="Account" asp-action="Login">
                    <input type="hidden" asp-for="ReturnUrl" />

                    @* Summary only: the model errors here are about the attempt as a whole - a wrong
                       password, or a lockout - rather than about one field being malformed. *@
                    <div asp-validation-summary="All" class="alert alert-danger @(ViewData.ModelState.IsValid ? "d-none" : "")" role="alert"></div>

                    @* Always a name (#68): nothing signs in without one since the shared password was retired (#89). *@
                    <div class="mb-3">
                        <label asp-for="Name" class="form-label"></label>
                        <input asp-for="Name" class="form-control" autocomplete="username" autofocus />
                        <div class="form-text">@T["Account.Login.NameHelp"]</div>
                    </div>

                    <div class="mb-3">
                        <label asp-for="Password" class="form-label"></label>
                        <input asp-for="Password" class="form-control" autocomplete="current-password" />
                    </div>

                    <button class="btn btn-primary d-grid w-100" type="submit">@T["Account.Login.Submit"]</button>
                </form>

            </div>
        </div>

        @* The language, before anyone has signed in (#102): the same cookie the navbar's switcher writes. *@
        <div class="d-flex justify-content-center gap-3 mt-3" id="login-language">
            @foreach (var culture in ConsoleCultures.Supported)
            {
                <form asp-controller="Culture" asp-action="Set" asp-area="" method="post">
                    <input type="hidden" name="culture" value="@culture" />
                    <input type="hidden" name="returnUrl" value="@returnUrl" />
                    <button type="submit" class="btn btn-link btn-sm p-0@(culture == current ? " fw-bold" : "")" lang="@culture" data-language="@culture">
                        @ConsoleCultures.NativeName(culture)
                    </button>
                </form>
            }
        </div>

    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Audit/Index.cshtml">
@using KnowledgeFabric.AdminConsole.Auditing
@using KnowledgeFabric.AdminConsole.Controllers
@model AuditLogPage
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss");

    var query = Model.Query;
    var results = Model.Results;
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Audit.Title"]</h5>
                <p class="text-body mb-0">@T["Audit.Intro"]</p>
                @if (Model.OwnEntriesOnly)
                {
                    <p id="own-entries-only" class="text-body mt-2 mb-0">@T["Audit.OwnEntriesOnly", query.Actor ?? ""]</p>
                }
            </div>
        </div>
    </div>
</div>

@if (Model.Storage == AuditStorage.LogsOnly)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Audit.NoDatabase.Title"]</h6>
        <p class="mb-2">@T["Audit.NoDatabase.Detail"]</p>
        <pre class="small mb-0"><code>traces | where message startswith "Audit:" | order by timestamp desc</code></pre>
    </div>
    return;
}

@if (Model.Storage == AuditStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Audit.Ephemeral"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Audit.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Audit.Unreadable.Detail"]</p>
    </div>
}

<div class="card mb-4">
    <div class="card-body">
        <form method="get" asp-action="Index" class="row g-3 align-items-end">
            <div class="col-12 col-md-5">
                <label for="kind" class="form-label">@T["Audit.Filter.Action"]</label>
                <select id="kind" name="kind" class="form-select">
                    <option value="">@T["Audit.Filter.EveryAction"]</option>
                    @foreach (var action in Model.Actions)
                    {
                        <option value="@action" selected="@(query.ActionFilter == action)">@action</option>
                    }
                </select>
            </div>
            <div class="col-12 col-md-4">
                <label for="target" class="form-label">@T["Audit.Filter.Target"]</label>
                <input type="search" id="target" name="target" value="@query.TargetFilter" class="form-control" placeholder="@T["Audit.Filter.TargetPlaceholder"].Value" />
            </div>
            <div class="col-12 col-md-3 d-flex gap-2">
                <button type="submit" class="btn btn-primary flex-fill">@T["Generic.Apply"]</button>
                <a asp-action="Index" class="btn btn-label-secondary flex-fill">@T["Generic.Clear"]</a>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">
            @if (Model.IsFiltered)
            {
                @(results.TotalCount == 1 ? T["Audit.Count.OneMatch"] : T["Audit.Count.ManyMatch", results.TotalCount])
            }
            else
            {
                @(results.TotalCount == 1 ? T["Audit.Count.One"] : T["Audit.Count.Many", results.TotalCount])
            }
        </h5>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th class="text-nowrap">@T["Audit.Column.When"]</th>
                    <th>@T["Audit.Column.Who"]</th>
                    <th>@T["Audit.Column.Action"]</th>
                    <th>@T["Audit.Column.Target"]</th>
                    <th>@T["Audit.Column.Details"]</th>
                </tr>
            </thead>
            <tbody>
                @if (results.Entries.Count == 0)
                {
... (77 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Home/Index.cshtml">
@using KnowledgeFabric.AdminConsole.Areas.Booking.ViewComponents
@using KnowledgeFabric.AdminConsole.Areas.Competitors.ViewComponents
@using KnowledgeFabric.AdminConsole.Areas.Crm.ViewComponents
@using KnowledgeFabric.AdminConsole.Areas.Gateway.ViewComponents
@using KnowledgeFabric.AdminConsole.Areas.Licensing.ViewComponents
@using KnowledgeFabric.AdminConsole.Preferences
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService Authorization
@inject SessionRoles SessionRoles
@inject DashboardPreferences Preferences
@{
    ViewData["title"] = T["Home.Title"].Value;
    // The installed app's start URL: a launch signed in lands here (Sections/_LaunchSplash).
    ViewData["launchSplash"] = true;

    // A session that may view no area sees one card instead of every feature's section (#88).
    var viewsAnArea = false;
    foreach (var policy in ConsolePolicies.AreaViews)
    {
        viewsAnArea |= (await Authorization.AuthorizeAsync(User, policy)).Succeeded;
    }
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start gap-3">
                    <h5 class="card-title mb-2">@ConsoleBranding.AppName</h5>
                    @if (viewsAnArea)
                    {
                        <a asp-area="" asp-controller="Preferences" asp-action="Dashboard" class="btn btn-sm btn-label-secondary text-nowrap" id="arrange-overview">
                            <i class="ti ti-arrows-sort me-1" aria-hidden="true"></i>@T["Home.Arrange"]
                        </a>
                    }
                </div>
                <p class="text-body mb-0">
                    @T["Home.Intro"]
                </p>
            </div>
        </div>
    </div>
</div>

@if (!viewsAnArea)
{
    var held = await SessionRoles.OfAsync(User);

    <div class="row g-4 mb-4">
        <div class="col-12">
            <div class="card" id="no-roles">
                <div class="card-body">
                    @if (held.Unreadable)
                    {
                        <h5 class="card-title mb-2">@T["Home.SignedInAs", held.Name ?? ""]</h5>
                        <p class="text-body mb-0">@T["Home.RolesUnreadable"]</p>
                    }
                    else
                    {
                        <h5 class="card-title mb-2">@T["Home.SignedInAs", held.Name ?? ""]</h5>
                        <p class="text-body mb-0">@T["Home.NoRoles"]</p>
                    }
                </div>
            </div>
        </div>
    </div>

    return;
}

@*
    Each feature draws its own part of the overview, and only for a session that may view its area;
    this page only places them (#37, #64, #88, #90, #176, #220), in the order the person chose on Dashboard
    preferences or the default one (#135).
*@
@foreach (var key in (await Preferences.OrderOfAsync(User.Identity!.Name!, Context.RequestAborted)).Areas)
{
    var component = key switch
    {
        OverviewArea.Licensing => typeof(LicensingOverviewViewComponent),
        OverviewArea.Gateway => typeof(GatewayOverviewViewComponent),
        OverviewArea.Crm => typeof(CrmOverviewViewComponent),
        OverviewArea.Booking => typeof(BookingOverviewViewComponent),
        OverviewArea.Competitors => typeof(CompetitorsOverviewViewComponent),
        _ => null,
    };

    // The component checks its policy too; asked here so an area the session cannot see leaves no trace.
    if (component is not null && (await Authorization.AuthorizeAsync(User, OverviewArea.Find(key)!.ViewPolicy)).Succeeded)
    {
        <div data-overview-area="@key">
            @await Component.InvokeAsync(component)
        </div>
    }
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Notifications/Index.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Controllers
@model NotificationsPage
@{
    var culture = CultureInfo.CurrentCulture;
    string When(DateTimeOffset at) =>
        $"{at.UtcDateTime.ToString("d MMM yyyy", culture)}, {at.UtcDateTime.ToString("HH:mm", CultureInfo.InvariantCulture)} UTC";
    var unread = Model.Rows.Count(row => !row.Read);
}

@* Each person's notifications (#209): said now from their subjects, in this page's language. *@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body d-flex flex-wrap align-items-start justify-content-between gap-3">
                <div>
                    <h5 class="card-title mb-2">@T["Notifications.Title"]</h5>
                    <p class="text-body mb-0">@T["Notifications.Intro"]</p>
                </div>
                <div class="d-flex flex-wrap gap-2">
                    <a asp-controller="NotificationSettings" asp-action="Index" class="btn btn-label-secondary" id="notifications-settings">
                        <i class="ti ti-settings ti-xs me-1" aria-hidden="true"></i>@T["Notifications.Settings.Link"]
                    </a>
                    @if (unread > 0)
                    {
                        <form asp-controller="Notifications" asp-action="MarkAllRead" method="post" class="d-inline">
                            <button type="submit" class="btn btn-label-primary" id="notifications-mark-all">
                                <i class="ti ti-checks ti-xs me-1" aria-hidden="true"></i>@T["Notifications.MarkAllRead"]
                            </button>
                        </form>
                    }
                </div>
            </div>
        </div>
    </div>
</div>

@if (Model.Gone)
{
    <div class="alert alert-info" role="status" id="notifications-gone">@T["Notifications.Gone"]</div>
}

@if (!Model.Readable)
{
    <div class="alert alert-warning" role="alert">@T["Notifications.Unreadable"]</div>
}

<div class="card">
    @if (Model.IsAdmin)
    {
        <div class="card-body">
            <p class="text-body mb-0" id="notifications-admin">@T["Notifications.Admin"]</p>
        </div>
    }
    else if (Model.Rows.Count == 0)
    {
        <div class="card-body">
            <p class="text-body mb-0" id="notifications-none">@T["Notifications.None"]</p>
        </div>
    }
    else
    {
        <ul class="list-group list-group-flush" id="notifications-list">
            @foreach (var row in Model.Rows)
            {
                <li class="list-group-item d-flex gap-3 align-items-start@(row.Read ? "" : " bg-label-primary")" data-notification="@row.Id" data-read="@(row.Read ? "true" : "false")">
                    <i class="ti @(row.Read ? "ti-bell" : "ti-bell-ringing") mt-1" aria-hidden="true"></i>
                    <div class="flex-grow-1">
                        @if (row.Content is { } content)
                        {
                            <a href="@Url.Content("~/" + KnowledgeFabric.AdminConsole.Notifications.NotificationRoutes.Open(row.Id))" class="fw-medium">@content.Title</a>
                            <div class="text-body">@content.Body</div>
                        }
                        else
                        {
                            <span class="fw-medium text-muted">@T["Notifications.Unavailable"]</span>
                        }
                        <div class="small text-muted">@When(row.CreatedAt)@(row.Read ? "" : " · " + S["Notifications.Unread"].Value)</div>
                    </div>
                </li>
            }
        </ul>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/NotificationSettings/Index.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Controllers
@using KnowledgeFabric.AdminConsole.Storage
@model NotificationSettingsPage
@{
    var culture = CultureInfo.CurrentCulture;
    string When(DateTimeOffset at) =>
        $"{at.UtcDateTime.ToString("d MMM yyyy", culture)}, {at.UtcDateTime.ToString("HH:mm", CultureInfo.InvariantCulture)} UTC";
}

@section PageScripts {
    @if (Model.Configured && !Model.IsAdmin)
    {
        <script src="~/js/notification-settings.js" asp-append-version="true"></script>
    }
}

@* User settings → Notifications (#209): the devices this person's notifications are pushed to. *@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Notifications.Settings.Title"]</h5>
                <p class="text-body mb-0">@T["Notifications.Settings.Intro"]</p>
            </div>
        </div>
    </div>
</div>

@if (Model.Done == "removed")
{
    <div class="alert alert-success" role="status" id="notifications-removed">@T["Notifications.Settings.Removed"]</div>
}
@if (Model.Done == "tested")
{
    <div class="alert alert-success" role="status" id="notifications-tested">@T["Notifications.Settings.Tested"]</div>
}

@if (Model.IsAdmin)
{
    <div class="card">
        <div class="card-body">
            <p class="text-body mb-0" id="notifications-settings-admin">@T["Notifications.Admin"]</p>
        </div>
    </div>
    return;
}

@if (!Model.Configured)
{
    <div class="alert alert-warning" role="alert" id="notifications-unconfigured">
        <h6 class="alert-heading mb-1">@T["Notifications.Settings.Unconfigured.Title"]</h6>
        <p class="mb-0">@T["Notifications.Settings.Unconfigured.Detail"]</p>
        @if (Model.Missing.Count > 0)
        {
            <p class="mb-0 mt-2 small">
                @T["Notifications.Settings.Unconfigured.Missing"]
                @foreach (var setting in Model.Missing)
                {
                    <code class="ms-1" data-missing>@setting</code>
                }
            </p>
        }
    </div>
}

@if (Model.Storage == FeatureStateStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Notifications.Settings.Ephemeral"]</div>
}

@if (!Model.Readable)
{
    <div class="alert alert-warning" role="alert">@T["Notifications.Settings.Unreadable"]</div>
}

@if (Model.Configured)
{
    @*
        This browser: what the script finds when it asks the browser, so the server never says whether
        a given browser is subscribed. Every state but one starts hidden; the script shows the one that holds.
    *@
    <div class="card mb-4" id="notifications-this-device"
         data-public-key="@Model.PublicKey"
         data-subscribe-url="@Url.Action("Add", "NotificationSettings")"
         data-remove-url="@Url.Content("~/Preferences/Notifications/Devices/")"
         data-devices="@string.Join(",", Model.Devices.Select(device => device.Id.ToString("D")))">
        <div class="card-header">
            <h5 class="card-title mb-1">@T["Notifications.Settings.ThisDevice"]</h5>
        </div>
        <div class="card-body">
            @Html.AntiForgeryToken()
            <p class="text-body" data-state="checking">@T["Notifications.Settings.Checking"]</p>
            <div class="d-none" data-state="unsupported">
                <p class="text-body mb-2">@T["Notifications.Settings.Unsupported"]</p>
                <p class="text-body small mb-0">@T["Notifications.Settings.Unsupported.Apple"]</p>
            </div>
            <p class="text-body d-none" data-state="denied">@T["Notifications.Settings.Denied"]</p>
            <div class="d-none" data-state="off">
                <p class="text-body">@T["Notifications.Settings.Off"]</p>
... (65 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Offline/Index.cshtml">
@using System.Globalization
@{
    Layout = null;
    var appName = ConsoleBranding.AppName;
}
<!DOCTYPE html>
@*
    The offline page (#166). Self-contained on purpose: no layout, no stylesheet, no script, no
    image file. The service worker shows it when the console cannot be reached, which is when
    nothing it would link to can be fetched either. The mark is inline, traced from
    wwwroot/img/logo/kf-logo-icon-bg-transparent.png, and the colours are the palette's by hand.
*@
<html lang="@CultureInfo.CurrentUICulture.TwoLetterISOLanguageName" dir="ltr">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="theme-color" content="@ConsoleBranding.ThemeColour" />
    <title>@ViewData["title"] | @appName</title>
    <style>
        html, body { height: 100%; margin: 0; }
        body {
            display: flex; align-items: center; justify-content: center;
            background: #f8f7fa; color: #5d596c;
            font-family: "Public Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
        }
        main { text-align: center; padding: 2rem 1rem; max-width: 28rem; }
        svg { width: 6rem; height: 6rem; color: @ConsoleBranding.ThemeColour; }
        h1 { font-size: 1.5rem; font-weight: 600; color: #433c50; margin: 1.5rem 0 0.5rem; }
        p { font-size: 0.9375rem; line-height: 1.5; margin: 0 0 1.5rem; }
        a {
            display: inline-block; padding: 0.6rem 1.5rem; border-radius: 0.375rem;
            background: @ConsoleBranding.ThemeColour; color: #fff; text-decoration: none; font-weight: 500;
        }
    </style>
</head>
<body>
    <main>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 107 107" role="img" aria-label="@appName">
            <path fill="currentColor" fill-rule="nonzero" d="M 42.00 95.31 C 40.06 93.37 40.01 91.82 41.83 89.34 C 43.04 87.69 44.98 87.34 56.08 86.83 C 70.91 86.14 75.81 84.31 83.07 76.71 C 90.31 69.14 91.93 64.88 91.93 53.38 C 91.93 44.82 91.59 42.73 89.57 38.88 C 86.37 32.75 79.95 26.25 73.93 23.04 L 68.93 20.38 L 39.33 19.88 C 7.86 19.35 6.43 19.11 6.43 14.45 C 6.43 10.01 7.32 9.88 36.95 9.88 C 66.67 9.88 70.52 10.34 79.82 15.08 C 84.99 17.72 93.02 25.32 96.01 30.42 C 106.75 48.76 103.77 70.93 88.65 85.07 C 79.41 93.72 70.22 96.88 54.32 96.88 C 45.88 96.88 43.23 96.54 42.00 95.31 Z M 16.85 80.11 C 14.92 78.79 14.55 76.15 16.00 74.07 C 17.35 72.14 18.63 72.02 40.84 71.71 L 64.26 71.38 L 68.59 68.36 C 79.33 60.88 79.33 45.88 68.59 38.40 L 64.26 35.38 L 33.61 35.06 C 14.06 34.86 2.51 34.36 1.70 33.69 C 0.00 32.28 0.08 28.41 1.84 26.95 C 2.88 26.09 11.92 25.85 35.62 26.08 L 67.98 26.38 L 72.95 29.57 C 78.95 33.43 84.07 39.83 85.55 45.33 C 86.16 47.56 86.43 52.43 86.17 56.16 C 85.77 61.78 85.10 63.81 82.31 67.92 C 78.64 73.31 72.90 77.89 67.53 79.72 C 63.74 81.01 18.67 81.36 16.85 80.11 Z M 24.00 64.31 C 22.05 62.36 22.01 60.82 23.84 58.32 C 25.13 56.56 26.92 56.33 43.09 55.88 C 60.41 55.39 60.94 55.31 61.23 53.22 C 61.47 51.54 60.79 50.82 58.09 49.93 C 54.14 48.63 52.99 45.95 55.09 42.94 C 59.29 36.95 71.43 44.71 71.43 53.38 C 71.43 57.17 67.87 62.84 64.40 64.60 C 62.69 65.46 56.28 65.85 43.75 65.86 C 28.54 65.87 25.31 65.62 24.00 64.31 Z M 33.63 49.68 C 32.08 48.13 32.08 44.62 33.63 43.08 C 35.18 41.52 44.67 41.52 46.23 43.08 C 47.77 44.62 47.77 48.13 46.23 49.68 C 45.57 50.34 42.73 50.88 39.93 50.88 C 37.12 50.88 34.29 50.34 33.63 49.68 Z" />
        </svg>
        <h1>@T["Offline.Title"]</h1>
        <p>@T["Offline.Detail"]</p>
        <a href="~/">@T["Offline.Retry"]</a>
    </main>
</body>
</html>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Preferences/Dashboard.cshtml">
@using KnowledgeFabric.AdminConsole.Controllers
@using KnowledgeFabric.AdminConsole.Storage
@model DashboardPreferencesPage

@section PageScripts {
    <script src="~/js/dashboard-preferences.js" asp-append-version="true"></script>
}

@* Dashboard preferences (#135): the order the overview places the areas this session may view in. *@
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Preferences.Dashboard.Title"]</h5>
                <p class="text-body mb-0">@T["Preferences.Dashboard.Intro"]</p>
            </div>
        </div>
    </div>
</div>

@if (Model.Saved)
{
    <div class="alert alert-success" role="status" id="dashboard-saved">
        @T["Preferences.Dashboard.Saved"]
        <a asp-area="" asp-controller="Home" asp-action="Index" class="alert-link">@T["Preferences.Dashboard.SeeOverview"]</a>
    </div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

@if (!Model.Readable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Preferences.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Preferences.Unreadable.Detail"]</p>
    </div>
}

@if (Model.Storage == FeatureStateStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Preferences.Ephemeral"]</div>
}

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-1">@T["Preferences.Dashboard.Order"]</h5>
        <p class="card-subtitle mb-0">
            @(Model.Chosen ? T["Preferences.Dashboard.Chosen"] : T["Preferences.Dashboard.Default"])
        </p>
    </div>
    <div class="card-body">
        @if (Model.Areas.Count == 0)
        {
            <p class="text-body mb-0" id="dashboard-no-areas">@T["Preferences.Dashboard.NoAreas"]</p>
        }
        else
        {
            <form method="post" asp-controller="Preferences" asp-action="Save">
                @*
                    The form posts the areas in the order the list has them: the hidden input travels
                    with its item when it is dragged or moved, so the script never builds a value.
                *@
                <ol class="list-group dashboard-order mb-4" id="dashboard-order" aria-describedby="dashboard-order-help">
                    @for (var i = 0; i < Model.Areas.Count; i++)
                    {
                        var area = Model.Areas[i];
                        var name = S[area.NameKey].Value;

                        <li class="list-group-item d-flex align-items-center gap-3" draggable="true" data-area="@area.Key">
                            <i class="ti ti-grip-vertical text-muted dashboard-order-handle" aria-hidden="true"></i>
                            <span class="badge bg-label-primary rounded-pill dashboard-order-position" data-position>@(i + 1)</span>
                            <i class="ti @area.Icon" aria-hidden="true"></i>
                            <span class="flex-grow-1 fw-medium">@name</span>
                            <button type="button" class="btn btn-icon btn-sm btn-text-secondary" data-move="up"
                                    aria-label="@S["Preferences.Dashboard.MoveUp", name]" title="@S["Preferences.Dashboard.MoveUp", name]">
                                <i class="ti ti-arrow-up" aria-hidden="true"></i>
                            </button>
                            <button type="button" class="btn btn-icon btn-sm btn-text-secondary" data-move="down"
                                    aria-label="@S["Preferences.Dashboard.MoveDown", name]" title="@S["Preferences.Dashboard.MoveDown", name]">
                                <i class="ti ti-arrow-down" aria-hidden="true"></i>
                            </button>
                            <input type="hidden" name="areas" value="@area.Key" />
                        </li>
                    }
                </ol>

                <p class="text-body small mb-4" id="dashboard-order-help">@T["Preferences.Dashboard.Help"]</p>

                <div class="d-flex flex-wrap gap-2">
                    <button type="submit" class="btn btn-primary">@T["Preferences.Dashboard.Save"]</button>
                    @if (Model.Chosen)
                    {
                        <button type="submit" class="btn btn-label-secondary" asp-controller="Preferences" asp-action="Reset">@T["Preferences.Dashboard.Reset"]</button>
                    }
                </div>
            </form>
        }
... (3 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Components/NotificationBell/Default.cshtml">
@using KnowledgeFabric.AdminConsole.ViewComponents
@model NotificationBell
@{
    var unread = Model.Unread ?? 0;
    var label = unread > 0 ? S["Notifications.Bell.Unread", unread].Value : S["Notifications.Bell.None"].Value;
    var shown = unread > 99 ? "99+" : unread.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
@*
    The bell (#209): the unread count, read on this page's load, leading to the inbox. The count sits on
    the icon, inside the button, as the template's own navbar badge does: the button clips what overhangs it.
*@
<a asp-area="" asp-controller="Notifications" asp-action="Index" id="notification-bell"
   class="nav-link btn btn-text-secondary btn-icon rounded-pill"
   aria-label="@label" title="@label" data-unread="@unread">
    <span class="position-relative">
        <i class="ti ti-bell ti-md" aria-hidden="true"></i>
        @if (unread > 0)
        {
            <span class="badge rounded-pill bg-danger badge-notifications" id="notification-bell-count">@shown</span>
        }
    </span>
</a>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/Footer/_Footer.cshtml">
@inject IWebHostEnvironment HostEnvironment
@inject IConfiguration Configuration
@{
    // Which environment is serving this request. An explicit label wins (set per stack by #7,
    // e.g. "Sandbox"); otherwise the hosting environment's own name.
    var environmentLabel = Configuration["EnvironmentLabel"];
    if (string.IsNullOrWhiteSpace(environmentLabel))
    {
        environmentLabel = HostEnvironment.EnvironmentName;
    }
}

<footer class="content-footer footer bg-footer-theme">
    <div class='@ViewData["containerNav"] d-flex align-items-center justify-content-between py-3 flex-md-row flex-column'>
        <div class="text-body">
            &copy; @DateTime.UtcNow.Year
            <a href="@ConsoleBranding.WebsiteUrl" target="_blank" rel="noopener" class="footer-link">@ConsoleBranding.AppName</a>
            @($"v{ConsoleBranding.Version}")
            @if (!string.IsNullOrWhiteSpace(environmentLabel))
            {
                <span class="badge bg-label-secondary ms-2" title="@T["Shell.Footer.Environment"].Value">@environmentLabel</span>
            }
        </div>
    </div>
</footer>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/Menu/_VerticalMenu.cshtml">
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService Authorization
@{
    var currentArea = ViewContext.RouteData.Values["area"] as string ?? "";
    var currentController = ViewContext.RouteData.Values["controller"] as string ?? "";
    var currentAction = ViewContext.RouteData.Values["action"] as string ?? "";
    var onHistory = currentArea == "Gateway" && currentController == "Usage" && currentAction.StartsWith("History", StringComparison.Ordinal);

    // Only what the session may view (#88): the menu asks the policies its pages ask, so an entry
    // is never offered that answers 403.
    var mayReadAudit = (await Authorization.AuthorizeAsync(User, ConsolePolicies.ReadAudit)).Succeeded;
    var mayManageRoles = (await Authorization.AuthorizeAsync(User, ConsolePolicies.ManageRoles)).Succeeded;
    var mayViewLicensing = (await Authorization.AuthorizeAsync(User, ConsolePolicies.LicensingView)).Succeeded;
    var mayViewGateway = (await Authorization.AuthorizeAsync(User, ConsolePolicies.GatewayView)).Succeeded;
    var mayViewCrm = (await Authorization.AuthorizeAsync(User, ConsolePolicies.CrmView)).Succeeded;
    var mayViewBooking = (await Authorization.AuthorizeAsync(User, ConsolePolicies.BookingView)).Succeeded;
    var mayConfigureBooking = mayViewBooking && (await Authorization.AuthorizeAsync(User, ConsolePolicies.BookingConfigure)).Succeeded;
    var mayViewCompetitors = (await Authorization.AuthorizeAsync(User, ConsolePolicies.CompetitorsView)).Succeeded;
    var mayConfigureCompetitors = mayViewCompetitors && (await Authorization.AuthorizeAsync(User, ConsolePolicies.CompetitorsConfigure)).Succeeded;
}

<aside id="layout-menu" class="layout-menu menu-vertical menu bg-menu-theme">

    <div class="app-brand demo">
        <a asp-area="" asp-controller="Home" asp-action="Index" class="app-brand-link">
            <span class="app-brand-logo demo">
                <img src="~/img/logo/kf-logo-icon-bg-transparent.png" asp-append-version="true" width="30" height="27" alt="" />
            </span>
            <span class="app-brand-text demo menu-text fw-bold ms-2">@ConsoleBranding.AppName</span>
        </a>

        <a href="javascript:void(0);" class="layout-menu-toggle menu-link text-large ms-auto">
            <i class="ti menu-toggle-icon d-none d-xl-block align-middle"></i>
            <i class="ti ti-x d-block d-xl-none ti-md align-middle"></i>
        </a>
    </div>

    <div class="menu-inner-shadow"></div>

    <ul class="menu-inner py-1">
        <li class='menu-item@(currentArea == "" && currentController == "Home" ? " active" : "")'>
            <a asp-area="" asp-controller="Home" asp-action="Index" class="menu-link">
                <i class="menu-icon tf-icons ti ti-layout-dashboard"></i>
                <div>@T["Menu.Overview"]</div>
            </a>
        </li>

        @if (mayReadAudit)
        {
            <li class='menu-item@(currentArea == "" && currentController == "Audit" ? " active" : "")'>
                <a asp-area="" asp-controller="Audit" asp-action="Index" class="menu-link">
                    <i class="menu-icon tf-icons ti ti-list-search"></i>
                    <div>@T["Menu.Audit"]</div>
                </a>
            </li>
        }

        @if (mayManageRoles)
        {
            <li class='menu-item@(currentArea == "" && currentController == "Users" ? " active" : "")'>
                <a asp-area="" asp-controller="Users" asp-action="Index" class="menu-link">
                    <i class="menu-icon tf-icons ti ti-users"></i>
                    <div>@T["Menu.Users"]</div>
                </a>
            </li>
        }

        @*
            Each area is a group that opens and closes (Vuexy's menu-toggle and menu-sub, started by
            site.js): the one the page is in is open when the page loads, and opening another closes
            it, so the menu stays as long as one area however many there are.
        *@
        @if (mayViewLicensing)
        {
            var inLicensing = currentArea == "Licensing";

            <li class='menu-item@(inLicensing ? " active open" : "")'>
                <a href="javascript:void(0);" class="menu-link menu-toggle">
                    <i class="menu-icon tf-icons ti ti-certificate"></i>
                    <div>@T["Menu.Licensing"]</div>
                </a>

                @*
                    This is where a feature attaches, and the whole of what adding one costs: an area, and
                    a group shaped like this one. No new project, no new login, no new pipeline - which is
                    the test #15 exists to pass.
                *@
                <ul class="menu-sub">
                    <li class='menu-item@(inLicensing && currentController == "Issue" ? " active" : "")'>
                        <a asp-area="Licensing" asp-controller="Issue" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Licensing.Issue"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(inLicensing && currentController == "Validate" ? " active" : "")'>
                        <a asp-area="Licensing" asp-controller="Validate" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Licensing.Validate"]</div>
                        </a>
                    </li>

... (203 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/Navbar/_LanguageSwitcher.cshtml">
@using System.Globalization
@{
    // One POST per language, so the global anti-forgery filter covers the switch; the return
    // address is the page as it is, query string included, because the filtered and paged pages
    // live in theirs (#102).
    var current = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
    var returnUrl = Context.Request.Path + Context.Request.QueryString;
}
<a class="nav-link btn btn-text-secondary btn-icon rounded-pill dropdown-toggle hide-arrow" href="javascript:void(0);"
   data-bs-toggle="dropdown" aria-label="@T["Shell.Language.Choose"].Value" title="@T["Shell.Language.Choose"].Value">
    <i class="ti ti-language rounded-circle ti-md"></i>
</a>
<ul class="dropdown-menu dropdown-menu-end">
    @foreach (var culture in ConsoleCultures.Supported)
    {
        <li>
            <form asp-controller="Culture" asp-action="Set" asp-area="" method="post">
                <input type="hidden" name="culture" value="@culture" />
                <input type="hidden" name="returnUrl" value="@returnUrl" />
                <button type="submit" class="dropdown-item@(culture == current ? " active" : "")" lang="@culture" data-language="@culture">
                    @ConsoleCultures.NativeName(culture)
                </button>
            </form>
        </li>
    }
</ul>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/Navbar/_Navbar.cshtml">
@{
    var actor = User.Identity?.Name ?? ConsoleClaims.SharedCredentialActor;
    var sharedCredential = actor == ConsoleClaims.SharedCredentialActor;
}

<nav class='layout-navbar @ViewData["navbarDetached"] @ViewData["containerNav"] navbar navbar-expand-xl align-items-center bg-navbar-theme'
     id="layout-navbar">

    <div class="layout-menu-toggle navbar-nav align-items-xl-center me-3 me-xl-0 d-xl-none">
        <a class="nav-item nav-link px-0 me-xl-4" href="javascript:void(0)">
            <i class="ti ti-menu-2 ti-sm"></i>
        </a>
    </div>

    <div class="navbar-nav-right d-flex align-items-center" id="navbar-collapse">

        <div class="navbar-nav align-items-center">
            <span class="fw-medium">@ViewData["title"]</span>
        </div>

        <ul class="navbar-nav flex-row align-items-center ms-auto">
            @* The language, chosen by cookie as kf-app does (#102); the page comes back with its query string. *@
            <li class="nav-item dropdown-language dropdown me-2">
                @await Html.PartialAsync("Sections/Navbar/_LanguageSwitcher")
            </li>
            @* The person's notifications (#209): the unread count, leading to the inbox. Nothing for admin. *@
            <li class="nav-item navbar-dropdown me-1 me-sm-2">
                @await Component.InvokeAsync("NotificationBell")
            </li>
            <li class="nav-item me-2 me-sm-3">
                @*
                    Named for what it is. While the console authenticates with a shared password
                    there is no person to greet, and a navbar that says "Administrator" would be
                    claiming an identity nobody supplied (#15).
                *@
                <span class="badge bg-label-secondary" title="@(sharedCredential ? T["Shell.Navbar.SharedCredential"].Value : T["Shell.Navbar.SignedIn"].Value)">
                    <i class="ti ti-user ti-xs me-1"></i>@actor
                </span>
            </li>
            <li class="nav-item">
                <form asp-controller="Account" asp-action="Logout" method="post" class="d-inline">
                    @* The icon alone on a phone, where the bell (#209) leaves no room for the words. *@
                    <button type="submit" class="btn btn-sm btn-outline-secondary" title="@T["Shell.Navbar.SignOut"].Value" aria-label="@T["Shell.Navbar.SignOut"].Value">
                        <i class="ti ti-logout ti-xs me-sm-1" aria-hidden="true"></i><span class="d-none d-sm-inline">@T["Shell.Navbar.SignOut"]</span>
                    </button>
                </form>
            </li>
        </ul>

    </div>
</nav>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/_LaunchSplash.cshtml">
@*
    The launch animation: what the installed app (#166) shows after the operating system's own
    start-up screen. The mark draws itself large in the middle, each stroke the way its line runs,
    then shrinks and moves left into the lockup as the wordmark fades and grows in beside it; then
    it all fades away to the page, which has been loading behind it the whole time. It delays
    nothing, and a tap or a key ends it at once.

    The operating system's screen cannot be animated: Android draws it from the manifest
    (background_color and an icon), and an iPhone shows a blank one. So this is the page's own first
    frame, on the manifest's white, and it plays only

      - in the installed app (display-mode: standalone, or navigator.standalone on an iPhone): a
        browser tab shows the page at once;
      - on a launch, which arrives with no referrer of the console's own (Android names the app as
        the referrer, an iPhone none): a page reached from another console page, the overview after
        signing in included, plays nothing;
      - once per session, so a reload plays nothing;
      - never when the person has asked for reduced motion.

    Rendered by the common layout on the two pages a launch lands on, the overview and the sign-in
    page (ViewData["launchSplash"]), first in the body: nothing of the page is parsed before the
    script below has decided, so nothing of it can paint first. Self-contained, styles and script
    inline and the lockup a vector: a launch fetches nothing more for it, the service worker needs
    no change, and it is in no cache.

    The lockup is the website's (kf-landing, www/assets/img/logo.png at 6bbdc6b): the mark beside
    "KnowledgeFabric" in its navy, in the mark's units, traced from img/icons/icon-512.png (99.5%
    the same pixels) and the wordmark from that logo (98%). The mark is four filled shapes, each
    revealed by a wide round stroke along its centre line inside a mask, the stroke's length beside
    it as --l. As the drawing ends the same four shapes, unmasked, take over, so an engine that does
    not repaint an animated mask still ends on the whole mark. The mark's blue is
    ConsoleBranding.ThemeColour, so it moves with the palette.

    The mark's moves are transforms in the lockup's own units (the UA's transform-origin for SVG is
    0 0): 903 is the distance from the middle of the lockup to the middle of the mark, and 249 256
    the mark's centre, about which it scales.
*@
<div id="kf-launch" class="kf-launch" aria-hidden="true">
    <style>
        .kf-launch { display: none; }
        .kf-launch.is-playing {
            position: fixed; inset: 0; z-index: 3000; display: flex; align-items: center; justify-content: center;
            background: #fff; touch-action: none; cursor: default; user-select: none; -webkit-user-select: none;
            animation: kf-launch-out 350ms cubic-bezier(.4, 0, .2, 1) 1850ms both;
        }
        .kf-launch.is-skipping { animation: kf-launch-out 180ms ease-out 0s both; }
        .kf-launch-lockup {
            display: block; width: min(82vw, 24rem); height: auto; margin-top: -4vh; overflow: visible;
            animation: kf-launch-recede 350ms cubic-bezier(.4, 0, .2, 1) 1850ms both;
        }
        .kf-launch-glyph { animation: kf-launch-settle 1260ms both; }
        .kf-launch-stroke {
            fill: none; stroke: #fff; stroke-width: 46; stroke-linecap: round; stroke-linejoin: round;
            stroke-dasharray: var(--l) 2000px; stroke-dashoffset: calc(var(--l) + 1px);
            animation: kf-launch-draw var(--t) cubic-bezier(.65, 0, .35, 1) var(--d) both;
        }
        .kf-launch-drawn { animation: kf-launch-hide 1ms linear 920ms both; }
        .kf-launch-whole { animation: kf-launch-show 1ms linear 920ms both; }
        .kf-launch-words { animation: kf-launch-rise 700ms cubic-bezier(.16, 1, .3, 1) 1100ms both; }
        @@keyframes kf-launch-draw { to { stroke-dashoffset: 0; } }
        @@keyframes kf-launch-hide { to { opacity: 0; } }
        @@keyframes kf-launch-show { from { opacity: 0; } to { opacity: 1; } }
        @@keyframes kf-launch-settle {
            0% { transform: translate(903px, 0) translate(249px, 256px) scale(1.62) translate(-249px, -256px); animation-timing-function: cubic-bezier(.16, 1, .3, 1); }
            62% { transform: translate(903px, 0) translate(249px, 256px) scale(1.75) translate(-249px, -256px); animation-timing-function: cubic-bezier(.65, 0, .35, 1); }
            100% { transform: translate(0, 0) translate(249px, 256px) scale(1) translate(-249px, -256px); }
        }
        @@keyframes kf-launch-rise { from { opacity: 0; transform: translate(504px, 250px) scale(.9) translate(-504px, -250px); } }
        @@keyframes kf-launch-out { to { opacity: 0; visibility: hidden; } }
        @@keyframes kf-launch-recede { to { transform: scale(1.04); } }
        @@media (prefers-reduced-motion: reduce) { .kf-launch.is-playing { display: none; } }
    </style>
    <svg class="kf-launch-lockup" viewBox="72 104 2160 304" width="2160" height="304" focusable="false">
        <defs>
            <path id="kf-launch-outer" d="M274.1 406C287.7 405.4 307.4 402.7 315.2 400.5C316.1 400.3 317.8 399.8 318.9 399.5C322.2 398.6 327.2 397 331.1 395.6C345.4 390.4 361.8 380.1 375.4 367.7C399.7 345.6 416.9 315.4 422.6 284.6C422.8 283.5 423.1 281.7 423.4 280.5C423.6 279.3 423.9 277.3 424 276C424.1 274.7 424.3 272.8 424.5 271.9C426.7 256 423.9 227.1 418.5 211.8C418.4 211.4 417.9 209.9 417.5 208.5C414.5 198.7 406.5 181.6 401.2 173.7C389.8 156.6 368.3 136.2 350.6 125.6C345.5 122.6 332.4 116.7 326.5 114.6C322.6 113.3 312.4 110.6 310 110.3C305.7 109.6 296.6 108.5 290.2 107.8C288 107.5 278.4 107 264.4 106.5C239.8 105.5 138 105.5 125 106.5C123.1 106.6 119.7 106.9 117.2 107C104.1 107.8 97.2 109.9 95 114C93.3 117.2 93.4 125.5 95.2 129C98.3 135 106.5 137 135.4 138.4C139.6 138.6 144.4 138.8 146 138.9C149.2 139 163.8 139.4 184.8 139.7C192.2 139.9 205.5 140.2 214.2 140.4C234.5 140.9 254.5 141.2 255 141.1C255.3 141 261.3 141.1 268.4 141.2C275.5 141.4 287.7 141.6 295.4 141.8L309.4 142L311.1 142.9C314.8 144.6 329.1 152.4 333.3 155.1C359 171.1 383 201.4 387.3 223.1C389.1 232.7 389.7 262.5 388.2 277.6C386.5 295.7 381.8 308 371.6 321.4C364.7 330.3 354.5 341.1 347.1 347.4C339.1 354.3 334 357.5 323.6 362.1C316.7 365.2 303.1 368.3 290.9 369.5C276.1 370.9 271.8 371.2 254.6 372C251.5 372.2 247.8 372.4 246.4 372.5C245 372.6 242.2 372.9 240.1 373C238.1 373.1 235.2 373.4 233.8 373.6C232.3 373.8 230.4 374 229.6 374.1C220.7 375.1 216.7 377.9 212.9 385.7C211 389.6 211.4 393.9 213.9 397.4C218.5 403.8 222.7 405.1 241.1 405.8C245.7 405.9 249.4 406.1 249.5 406.2C249.7 406.3 269.5 406.2 274.1 406Z" />
            <path id="kf-launch-middle" d="M249.4 350.4C259.6 350.2 270.7 349.8 274.2 349.6C277.8 349.4 282.4 349.2 284.6 349.1C289.7 348.9 300.5 347.9 303.1 347.3C309.4 346 320.3 340.2 329.6 333.4C346.8 320.7 362.2 300.6 366.3 285.5C370.2 271.4 370.6 240.6 367 228C361.6 209.1 344.8 187.8 324.8 174.6C318 170.1 307.9 163.7 306.9 163.2C305.4 162.6 252.2 162 159.9 161.6C103.3 161.4 82.6 162.2 78.4 164.7C72 168.7 71.8 184.8 78.1 188.2C81.4 189.9 107.8 191.4 145.6 192C153.9 192.1 166.5 192.4 173.7 192.5C180.9 192.7 197.1 192.9 209.7 193C222.3 193.1 246 193.3 262.2 193.5C278.5 193.7 292.3 193.8 292.9 193.9C294 194 305.5 201.8 311.5 206.5C317.7 211.3 324.1 218.7 328.3 225.9C336.3 239.8 338.4 257.3 334 272.8C330.3 285.8 321.8 297.7 310 306.6C305.4 310.1 294.2 317.8 293.5 318C292.8 318.2 272 318.5 214.8 319.3C141 320.2 132.1 320.9 127.8 326.1C122.8 332.2 122.8 341.2 127.8 346.3C131 349.6 134.4 349.9 166.8 350.5C174.1 350.6 180.1 350.8 180.2 350.9C180.5 351.2 229.9 350.8 249.4 350.4Z" />
            <path id="kf-launch-hook" d="M256.5 298.8C259.3 298.6 264.3 298.4 267.5 298.2C279 297.7 289.7 296.4 292.9 295.2C298.2 293.1 305.3 286.3 310.1 278.8C318 266.4 319.9 256.4 316.5 245.5C309.4 223.3 282.9 206.8 267.5 215C262.5 217.7 258.5 224.2 258.5 229.7C258.5 236.3 262.5 240.4 272.5 244.1C281.7 247.5 283.9 249.9 283 255.8C282 262.2 277.3 263.1 238.1 264.1C230.4 264.3 223.9 264.6 223.7 264.6C223.5 264.7 218 264.9 211.4 265C189 265.5 172.6 266.4 165.5 267.7C158.5 268.9 156 270.1 153.3 274.1C148.2 281.5 148.2 286.8 153.4 292.5C156 295.3 158 296.3 162.8 297.2C165.5 297.7 166 297.8 176.1 298.4C179.6 298.6 182.9 298.8 183.6 298.8C186.9 299 252 299 256.5 298.8Z" />
            <path id="kf-launch-dot" d="M216.8 247C224.3 246.5 230.2 244.6 232 242.2C236.6 235.9 236.1 225.2 231.1 220.6C225.1 215 193.2 215.1 187.7 220.8C183 225.7 182.6 236 187 242.1C189.8 246 201.7 248 216.8 247Z" />
            <mask id="kf-launch-outer-m" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512">
                <path class="kf-launch-stroke" style="--l: 652px; --t: 700ms; --d: 100ms" d="M100 121.5L288 123.5C354 125 406.5 183 406.5 256C406.5 329 354 386 288 388L218 390.5" />
            </mask>
            <mask id="kf-launch-middle-m" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512">
                <path class="kf-launch-stroke" style="--l: 587px; --t: 660ms; --d: 170ms" d="M80 176L298 178C330 194 352 222 352 256C352 290 330 318 298 334L130 335.5" />
            </mask>
            <mask id="kf-launch-hook-m" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512">
                <path class="kf-launch-stroke" style="--l: 203px; --t: 540ms; --d: 250ms" d="M268 229C291 229 301 243 301 256C301 271 290 281 266 281.5L160 283" />
            </mask>
            <mask id="kf-launch-dot-m" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512">
                <path class="kf-launch-stroke" style="--l: 21px; --t: 200ms; --d: 700ms" d="M199 231.5L220 231.5" />
            </mask>
        </defs>
        <g class="kf-launch-glyph" fill="@ConsoleBranding.ThemeColour">
            <g class="kf-launch-drawn">
                <use href="#kf-launch-outer" mask="url(#kf-launch-outer-m)" />
                <use href="#kf-launch-middle" mask="url(#kf-launch-middle-m)" />
                <use href="#kf-launch-hook" mask="url(#kf-launch-hook-m)" />
                <use href="#kf-launch-dot" mask="url(#kf-launch-dot-m)" />
            </g>
            <g class="kf-launch-whole">
                <use href="#kf-launch-outer" />
... (59 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/_Scripts.cshtml">
<script src="~/vendor/libs/jquery/jquery.js" asp-append-version="true"></script>
<script src="~/vendor/libs/popper/popper.js" asp-append-version="true"></script>
<script src="~/vendor/js/bootstrap.js" asp-append-version="true"></script>
<!-- `perfect-scrollbar` is required by the vertical menu -->
<script src="~/vendor/libs/perfect-scrollbar/perfect-scrollbar.js" asp-append-version="true"></script>
<!-- button click animation -->
<script src="~/vendor/libs/node-waves/node-waves.js" asp-append-version="true"></script>
<!-- swipe gesture, for the menu on small screens -->
<script src="~/vendor/libs/hammer/hammer.js" asp-append-version="true"></script>
<script src="~/vendor/js/menu.js" asp-append-version="true"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/_ScriptsIncludes.cshtml">
@* Template helpers and the global config (palette, layout defaults). Both must load before the
   page renders, or the menu and the theme flicker into place after first paint. *@
<script src="~/vendor/js/helpers.js" asp-append-version="true"></script>
<script src="~/js/config.js" asp-append-version="true"></script>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Sections/_Styles.cshtml">
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">

<!-- Icons -->
<link rel="stylesheet" href="~/vendor/fonts/tabler-icons.css" asp-append-version="true" />

@*
    Core CSS. theme-kfadmin is the console's own palette: the same Vuexy theme the product uses,
    compiled against a different primary. Both files are build output from src/scss - never edit
    them by hand, run `npm run build:css`.

    The template-customizer-* classes are how the template's customizer finds these links. It is
    switched off (see wwwroot/js/config.js), but the classes stay so that turning it on for a
    local look at an alternative theme does not need markup changes.
*@
<link rel="stylesheet" href="~/vendor/css/core.css" class="template-customizer-core-css" asp-append-version="true" />
<link rel="stylesheet" href="~/vendor/css/theme-kfadmin.css" class="template-customizer-theme-css" asp-append-version="true" />

<!-- `perfect-scrollbar` is required by the vertical menu -->
<link rel="stylesheet" href="~/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" asp-append-version="true" />
<link rel="stylesheet" href="~/vendor/libs/node-waves/node-waves.css" asp-append-version="true" />

<!-- Application stylesheet -->
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/_ApexCharts.cshtml">
@*
    The chart library, once a page however many sections ask for it (#158): the overview's licensing
    and CRM sections each draw charts, and either may be the only one a session sees, or the first.
    Deferred scripts run in order once the page is parsed, so a section's own script placed after
    this partial runs after the library, whichever section loaded it.
*@
@{
    const string Loaded = "kf:apexcharts";
}
@if (!Context.Items.ContainsKey(Loaded))
{
    Context.Items[Loaded] = true;
    <link rel="stylesheet" href="~/vendor/libs/apex-charts/apex-charts.css" asp-append-version="true" />
    <script src="~/vendor/libs/apex-charts/apexcharts.js" asp-append-version="true" defer></script>
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/_BlankLayout.cshtml">
@{
    Layout = "_CommonMasterLayout";
}

@section PageStyles { @RenderSection("PageStyles", required: false) }
@section PageScripts { @RenderSection("PageScripts", required: false) }
@section Scripts { @RenderSection("Scripts", required: false) }

@*
    No menu, no navbar, no footer. The login and error pages use this: a signed-out caller has
    nothing to navigate to, and a menu that leads only back to the login page is furniture.
*@
<div class="container-xxl">
    @RenderBody()
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/_CommonMasterLayout.cshtml">
@using System.Globalization
@inject ClientStrings ClientStrings
@{
    var title = ViewData["title"] as string ?? "";
    var appName = ConsoleBranding.AppName;
    var fullTitle = string.IsNullOrWhiteSpace(title) ? appName : $"{title} | {appName}";
}
<!DOCTYPE html>
@*
    light-style and the theme are fixed here rather than left to the template customizer, which is
    switched off. A console that renders the same way for everyone is one where a screenshot in a
    bug report means something.
*@
<html lang="@CultureInfo.CurrentUICulture.TwoLetterISOLanguageName"
      class='light-style @(ViewData["navbarType"] as string) @(ViewData["menuFixed"] as string) @(ViewData["contentType"] as string) customizer-hide'
      dir="ltr"
      data-theme="theme-kfadmin"
      data-assets-path='@(Context.Request.PathBase + "/")'
      data-template="vertical-menu-template">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@fullTitle</title>

    @* The KnowledgeFabric mark, copied from kf-app's wwwroot/img/favicon/ and logo/ (f881e3e). *@
    <link rel="icon" type="image/png" sizes="32x32" href="~/img/favicon/favicon-32x32.png" asp-append-version="true" />
    <link rel="icon" type="image/png" sizes="16x16" href="~/img/favicon/favicon-16x16.png" asp-append-version="true" />
    <link rel="icon" type="image/x-icon" href="~/favicon.ico" asp-append-version="true" />

    @*
        Installed as an app (#166). The manifest names the console and its icons and is read
        before sign-in, so it is a static file; its URL stays unversioned because an installed
        copy is tied to it. Safari reads the Apple metas and the 180-pixel icon rather than the
        manifest. The theme colour is the mark's blue, the same one the stylesheets and config.js
        hold (docs/Console-Shell.md, "The colour scheme").
    *@
    <link rel="manifest" href="~/manifest.webmanifest" />
    <meta name="theme-color" content="@ConsoleBranding.ThemeColour" />
    <link rel="apple-touch-icon" sizes="180x180" href="~/img/icons/apple-touch-icon.png" asp-append-version="true" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    <meta name="apple-mobile-web-app-title" content="@ConsoleBranding.ShortName" />

    @await Html.PartialAsync("Sections/_Styles")
    @RenderSection("PageStyles", required: false)
    @await Html.PartialAsync("Sections/_ScriptsIncludes")
</head>

<body>
    @*
        The launch animation (docs/Console-Shell.md, "Installed as an app"), on the two pages a
        launch of the installed app lands on, which ask for it. First in the body, so that it decides
        before anything of the page can paint; it removes itself everywhere it does not play.
    *@
    @if (ViewData["launchSplash"] is true)
    {
        @await Html.PartialAsync("Sections/_LaunchSplash")
    }

    @RenderBody()

    @*
        The page's language for its scripts (#102): the culture and every Js.* string, read by
        site.js into window.kfI18n. The one way a translation reaches JavaScript.
    *@
    <script id="kf-i18n" type="application/json">@Html.Raw(ClientStrings.ToJson())</script>

    @await Html.PartialAsync("Sections/_Scripts")
    @RenderSection("PageScripts", required: false)
    @RenderSection("Scripts", required: false)
</body>

</html>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/_ContentNavbarLayout.cshtml">
@{
    Layout = "_CommonMasterLayout";

    ViewData["isNavbar"] = ViewData["isNavbar"] ?? true;
    ViewData["isMenu"] = ViewData["isMenu"] ?? true;
    ViewData["isFooter"] = ViewData["isFooter"] ?? true;

    ViewData["menuFixed"] = ViewData["menuFixed"] ?? "layout-menu-fixed";
    ViewData["navbarType"] = ViewData["navbarType"] ?? "layout-navbar-fixed";
    ViewData["navbarDetached"] = ViewData["navbarDetached"] ?? "navbar-detached";

    @*
        Width is decided here and rendered into the HTML, rather than left for the customizer's
        JavaScript to set after first paint. kf-app learned this the hard way: a stored "compact"
        setting pinned the whole application to a centred column with no way left to undo it
        (kf-app#911). A page that wants the narrow measure sets both keys itself.
    *@
    ViewData["container"] = ViewData["container"] ?? "container-fluid";
    ViewData["containerNav"] = ViewData["containerNav"] ?? "container-fluid";

    var isMenu = Convert.ToBoolean(ViewData["isMenu"]);
}

@section PageStyles { @RenderSection("PageStyles", required: false) }
@section PageScripts { @RenderSection("PageScripts", required: false) }
@section Scripts { @RenderSection("Scripts", required: false) }

<div class='layout-wrapper layout-content-navbar @(isMenu ? "" : "layout-without-menu")'>
    <div class="layout-container">

        @if (isMenu)
        {
            @await Html.PartialAsync("Sections/Menu/_VerticalMenu")
        }

        <div class="layout-page">
            @if (Convert.ToBoolean(ViewData["isNavbar"]))
            {
                @await Html.PartialAsync("Sections/Navbar/_Navbar")
            }

            <div class="content-wrapper">
                <div class='@ViewData["container"] flex-grow-1 container-p-y'>
                    @RenderBody()
                </div>

                @if (Convert.ToBoolean(ViewData["isFooter"]))
                {
                    @await Html.PartialAsync("Sections/Footer/_Footer")
                }

                <div class="content-backdrop fade"></div>
            </div>
        </div>
    </div>

    @if (isMenu)
    {
        <div class="layout-overlay layout-menu-toggle"></div>
    }
    <div class="drag-target"></div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/_PublicLayout.cshtml">
@using System.Globalization
@using KnowledgeFabric.AdminConsole.Areas.Booking.Models
@using KnowledgeFabric.AdminConsole.Booking
@{
    // The public booking page's layout (#174): the template's stylesheet and the mark, and no
    // navbar, no menu, no link into the console, no service worker and no manifest. The only thing
    // it shares with the console's chrome is the language switcher, through the same cookie. The
    // page is reached by a link we hand out, not found: robots are told not to index it.
    var page = (PublicShell)Model;
    var title = ViewData["title"] as string ?? "";
    var appName = ConsoleBranding.AppName;
    var current = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
    var returnUrl = Context.Request.Path + Context.Request.QueryString;
    var zone = page.Zone;
}
<!DOCTYPE html>
<html lang="@current" class="light-style" dir="ltr" data-theme="theme-kfadmin" data-assets-path='@(Context.Request.PathBase + "/")'>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="robots" content="noindex" />
    <title>@title | @appName</title>

    <link rel="icon" type="image/png" sizes="32x32" href="~/img/favicon/favicon-32x32.png" asp-append-version="true" />
    <link rel="icon" type="image/png" sizes="16x16" href="~/img/favicon/favicon-16x16.png" asp-append-version="true" />
    <link rel="icon" type="image/x-icon" href="~/favicon.ico" asp-append-version="true" />
    <meta name="theme-color" content="@ConsoleBranding.ThemeColour" />

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="~/vendor/fonts/tabler-icons.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/vendor/css/core.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/vendor/css/theme-kfadmin.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>

<body>
    <div class="container-xxl container-p-y booking-public" data-booking-zone="@zone.Id" data-booking-zone-given="@(zone.Given ? "true" : "false")">
        <header class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
            <div class="d-flex align-items-center gap-2">
                <img src="~/img/logo/kf-logo-icon-bg-transparent.png" asp-append-version="true" width="36" height="32" alt="" />
                <span class="fw-bold text-body">@appName</span>
            </div>

            @* The language, by the same cookie the console's switcher writes (#102): the guest is addressed as tu. *@
            <div class="d-flex gap-3" id="public-language">
                @foreach (var culture in ConsoleCultures.Supported)
                {
                    <form asp-area="" asp-controller="Culture" asp-action="Set" method="post">
                        <input type="hidden" name="culture" value="@culture" />
                        <input type="hidden" name="returnUrl" value="@returnUrl" />
                        <button type="submit" class="btn btn-link btn-sm p-0@(culture == current ? " fw-bold" : "")" lang="@culture" data-language="@culture">
                            @ConsoleCultures.NativeName(culture)
                        </button>
                    </form>
                }
            </div>
        </header>

        <main class="booking-public-main">
            @RenderBody()
        </main>

        @*
            The zone the slots are shown in (#170, decision 6): the browser's, detected by the script
            below and sent as tz; or one the guest chooses here; or UTC, said out loud, without script.
        *@
        @if (page.ShowsZone)
        {
            <footer class="mt-4 pt-3 border-top">
                <form method="get" class="d-flex flex-wrap align-items-center gap-2" id="public-zone">
                    @foreach (var (name, values) in Context.Request.Query.Where(pair => pair.Key != "tz"))
                    {
                        <input type="hidden" name="@name" value="@values" />
                    }
                    <label for="public-tz" class="form-label mb-0 small">
                        @(zone.Given ? T["Booking.Public.Zone.Shown", zone.Id] : T["Booking.Public.Zone.Default", zone.Id])
                    </label>
                    <select id="public-tz" name="tz" class="form-select form-select-sm w-auto">
                        <option value="@PublicZone.Utc.Id" selected="@(zone.Id == PublicZone.Utc.Id)">@PublicZone.Utc.Id</option>
                        @foreach (var name in TimeZones.All)
                        {
                            <option value="@name" selected="@(name == zone.Id)">@name</option>
                        }
                    </select>
                    <button type="submit" class="btn btn-sm btn-label-secondary">@T["Booking.Public.Zone.Change"]</button>
                </form>
            </footer>
        }
    </div>

    <script src="~/js/booking-public.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>

</html>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Shared/Error.cshtml">
@model ErrorModel
@{
    ViewData["title"] = Model.Title;
    Layout = "_BlankLayout";
}

<div class="container-xxl container-p-y">
    <div class="misc-wrapper text-center">
        <h1 class="mb-2 mx-2 display-5 fw-bold">@Model.StatusCode</h1>
        <h4 class="mb-2">@Model.Title</h4>
        <p class="mb-4 mx-2">@Model.Detail</p>

        <a asp-area="" asp-controller="Home" asp-action="Index" class="btn btn-primary">@T["Error.Back"]</a>

        @if (!string.IsNullOrEmpty(Model.CorrelationId))
        {
            <p class="text-body mt-4 mb-0">
                <small>@T["Error.Reference", Html.Raw($"<code>{Html.Encode(Model.CorrelationId)}</code>")]</small>
            </p>
        }
    </div>
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Users/Index.cshtml">
@using KnowledgeFabric.AdminConsole.Controllers
@model UsersPage
@{
    static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm");

    var me = User.Identity?.Name;

    // The area roles under one heading each, so a column is "View" or "Write" rather than the role's whole name.
    var areas = ConsoleRoles.All
        .Where(role => role != ConsoleRoles.Administrator)
        .GroupBy(role => T.RoleArea(role), role => T.RoleVerb(role))
        .ToList();
}

<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title mb-2">@T["Users.Title"]</h5>
                <p class="text-body mb-2">@T["Users.Intro.Roles", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.Administrator))}</strong>")]</p>
                <p class="text-body mb-2">@T["Users.Intro.Names"]</p>
                <p class="text-body mb-0">@T["Users.Intro.Initials"]</p>
            </div>
        </div>
    </div>
</div>

@if (Model.Storage == RoleStorage.Unavailable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Users.NoDatabase.Title"]</h6>
        <p class="mb-0">@T["Users.NoDatabase.Detail"]</p>
    </div>
}
else if (Model.Storage == RoleStorage.Ephemeral)
{
    <div class="alert alert-info" role="alert">@T["Users.Ephemeral"]</div>
}

@if (Model.Unreadable)
{
    <div class="alert alert-warning" role="alert">
        <h6 class="alert-heading mb-1">@T["Users.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Users.Unreadable.Detail"]</p>
    </div>
}

@if (Model.Problem is { } problem)
{
    <div class="alert alert-danger" role="alert">@problem</div>
}

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">@(Model.Rows.Count == 1 ? T["Users.Count.One"] : T["Users.Count.Many", Model.Rows.Count])</h5>
    </div>
    <div class="table-responsive">
        <table class="table table-sm align-middle">
            <thead>
                <tr>
                    <th rowspan="2" class="align-bottom">@T["Users.Column.Name"]</th>
                    <th rowspan="2" class="align-bottom" title="@T["Users.Initials.Title"].Value">@T["Users.Column.Initials"]</th>
                    <th rowspan="2" class="text-center align-bottom">@T.Role(ConsoleRoles.Administrator)</th>
                    @foreach (var area in areas)
                    {
                        <th colspan="@area.Count()" class="text-center border-bottom-0 pb-0">@area.Key</th>
                    }
                </tr>
                <tr>
                    @foreach (var level in areas.SelectMany(area => area))
                    {
                        <th class="text-center">@level</th>
                    }
                </tr>
            </thead>
            <tbody>
                @foreach (var row in Model.Rows)
                {
                    <tr id="user-@ConsoleRoles.Normalise(row.Name)">
                        <td class="text-nowrap">
                            <span class="fw-medium">@row.Name</span>
                            @if (row.Name.Equals(me, StringComparison.OrdinalIgnoreCase))
                            {
                                <span class="text-body-secondary small">@T["Users.You"]</span>
                            }
                            @if (!row.HasSecret)
                            {
                                <div><span class="badge bg-label-warning" title="@S["Users.NoSecret.Title", row.Name].Value">@T["Users.NoSecret"]</span></div>
                            }
                            @if (row.HasNoRoles)
                            {
                                <div><span class="badge bg-label-secondary" title="@T["Users.NoRoles.Title"].Value">@T["Users.NoRoles"]</span></div>
                            }
                        </td>

                        @* Initials (#115): what the CRM's grid shows for the name. admin has none, being no one (#108). *@
                        <td class="text-nowrap">
                            @if (row.IsAdmin)
                            {
                                <span class="text-body-secondary" title="@T["Users.Initials.Admin.Title"].Value">—</span>
... (62 lines truncated)
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/_ViewImports.cshtml">
@using KnowledgeFabric.AdminConsole
@using KnowledgeFabric.AdminConsole.Models
@using KnowledgeFabric.AdminConsole.Security
@using Microsoft.AspNetCore.Mvc.Localization
@using KnowledgeFabric.AdminConsole.Localisation
@using KnowledgeFabric.AdminConsole.Resources
@using Microsoft.Extensions.Localization
@inject IHtmlLocalizer<ConsoleResource> T
@inject IStringLocalizer<ConsoleResource> S
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/_ViewStart.cshtml">
@{
    Layout = "_ContentNavbarLayout";
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/appsettings.Development.json">
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    }
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/appsettings.json">
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning",
            "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
        }
    },
    "AllowedHosts": "*",
    "Authentication": {
        "MaxFailedAttempts": 5,
        "LockoutDuration": "00:15:00",
        "SessionLifetime": "08:00:00"
    },
    "KeyVault": {
        "Uri": ""
    },
    "ApplicationInsights": {
        "ConnectionString": ""
    },
    "Gateway": {
        "BaseUrl": "https://ai.knowledgefabric.io",
        "Timeout": "00:00:05"
    },
    "Ollama": {
        "BaseUrl": "https://ollama.com",
        "Timeout": "00:01:00"
    },
    "Crm": {
        "BusinessCards": {
            "Model": "gemma4:31b",
            "Timeout": "00:01:00"
        },
        "Reminders": {
            "TimeZone": "Europe/Rome",
            "At": "08:00"
        }
    },
    "Booking": {
        "PublicBaseUrl": "https://admin.knowledgefabric.io",
        "Zoho": {
            "AccountsUrl": "https://accounts.zoho.eu",
            "BaseUrl": "https://calendar.zoho.eu",
            "CalendarUid": "c2f9ecd4355048ddbc2029f83d97cd04",
            "Timeout": "00:00:10"
        }
    },
    "Competitors": {
        "Model": "gpt-oss:120b",
        "Scan": {
            "TimeZone": "Europe/Rome",
            "At": "08:30",
            "MaxResults": 10,
            "LookBackDays": 3
        }
    },
    "Notifications": {
        "Vapid": {
            "Subject": "https://admin.knowledgefabric.io"
        }
    }
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/build-vendor.js">
function copy(target, source)
⋮----
function bundle(target, sources)
</file>

<file path="src/KnowledgeFabric.AdminConsole/package.json">
{
  "name": "knowledgefabric-adminconsole-assets",
  "version": "1.0.0",
  "private": true,
  "description": "Stylesheet build for the admin console. The Vuexy template is licensed commercially; see docs/Admin-Console.md.",
  "scripts": {
    "build:css": "sass --load-path=node_modules --no-source-map src/scss/core.scss:wwwroot/vendor/css/core.css src/scss/theme-kfadmin.scss:wwwroot/vendor/css/theme-kfadmin.css src/site.scss:wwwroot/css/site.css src/libs/apex-charts/apex-charts.scss:wwwroot/vendor/libs/apex-charts/apex-charts.css src/libs/datatables-bs5/datatables.bootstrap5.scss:wwwroot/vendor/libs/datatables-bs5/datatables.bootstrap5.css src/libs/datatables-fixedheader-bs5/fixedheader.bootstrap5.scss:wwwroot/vendor/libs/datatables-fixedheader-bs5/fixedheader.bootstrap5.css",
    "build:vendor": "node build-vendor.js",
    "watch:css": "npm run build:css -- --watch"
  },
  "dependencies": {
    "apexcharts-clevision": "3.28.5",
    "bootstrap": "5.3.3",
    "datatables.net": "1.13.11",
    "datatables.net-bs5": "1.13.11",
    "datatables.net-fixedheader": "3.4.0",
    "datatables.net-fixedheader-bs5": "3.4.0",
    "jsqr": "1.4.0"
  },
  "devDependencies": {
    "sass": "1.77.5"
  }
}
</file>

<file path="src/KnowledgeFabric.AdminConsole/Program.cs">
var builder = WebApplication.CreateBuilder(args);
⋮----
if (!string.IsNullOrWhiteSpace(keyVaultUri))
⋮----
builder.Configuration.AddAzureKeyVault(new Uri(keyVaultUri), new DefaultAzureCredential());
⋮----
if (!string.IsNullOrWhiteSpace(builder.Configuration["ApplicationInsights:ConnectionString"]))
⋮----
builder.Services.AddApplicationInsightsTelemetry();
⋮----
builder.Services.AddConsoleAuthentication(builder.Configuration);
⋮----
builder.Services.AddConsoleAuthorization(builder.Configuration, builder.Environment);
⋮----
builder.Services.AddConsoleAudit(builder.Configuration, builder.Environment);
⋮----
builder.Services.AddLicenceRegister(builder.Configuration, builder.Environment);
⋮----
builder.Services.AddCrmContacts(builder.Configuration, builder.Environment);
⋮----
builder.Services.AddOllama(builder.Configuration);
⋮----
builder.Services.AddBusinessCards(builder.Configuration);
⋮----
builder.Services.AddBookings(builder.Configuration, builder.Environment);
⋮----
builder.Services.AddZohoCalendar(builder.Configuration);
⋮----
builder.Services.AddCalendarFeeds();
⋮----
builder.Services.AddFeatureState(builder.Configuration);
⋮----
builder.Services.AddNotifications(builder.Configuration);
⋮----
builder.Services.AddCompetitors(builder.Configuration, builder.Environment);
⋮----
builder.Services.AddFollowUpReminders(builder.Configuration);
⋮----
builder.Services.AddGatewayWatch();
⋮----
builder.Services.AddLicenceIssuing(builder.Configuration);
⋮----
builder.Services.AddGatewayAdmin(builder.Configuration);
⋮----
builder.Services.AddControllersWithViews(options =>
⋮----
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
⋮----
.AddConsoleLocalisation();
⋮----
builder.Services.AddRateLimiter(options =>
⋮----
options.AddPolicy(RateLimitPolicies.Login, httpContext => PerAddress(httpContext, permitsPerMinute: 10));
options.AddPolicy(RateLimitPolicies.PublicBooking, httpContext => PerAddress(httpContext, permitsPerMinute: 10));
options.AddPolicy(RateLimitPolicies.PublicBrowsing, httpContext => PerAddress(httpContext, permitsPerMinute: 60));
⋮----
RateLimitPartition.GetFixedWindowLimiter(
⋮----
factory: _ => new FixedWindowRateLimiterOptions
⋮----
Window = TimeSpan.FromMinutes(1),
⋮----
builder.Services.AddHealthChecks();
⋮----
var app = builder.Build();
⋮----
if (!app.Environment.IsDevelopment())
⋮----
app.UseExceptionHandler("/error");
app.UseHsts();
⋮----
app.UseDeveloperExceptionPage();
⋮----
app.UseStatusCodePagesWithReExecute("/error/{0}");
⋮----
app.UseConsoleLocalisation();
⋮----
app.UseHttpsRedirection();
app.UseStaticFiles();
⋮----
app.UseRouting();
app.UseRateLimiter();
⋮----
app.UseAuthentication();
app.UseAuthorization();
⋮----
app.MapHealthChecks("/health").AllowAnonymous();
⋮----
app.MapControllerRoute(
⋮----
app.Run();
⋮----
public static class RateLimitPolicies
</file>

<file path="src/KnowledgeFabric.LicenseTool/Properties/launchSettings.json">
{
  "profiles": {
    "LicenseTool": {
      "commandName": "Project",
      "commandLineArgs": "gen-license --config \"%KF_LICENSE_CONFIG%\" --private-key \"%KF_LICENSE_PRIVATE_KEY%\" --passphrase \"%KF_LICENSE_PASSPHRASE%\" --output \"%KF_LICENSE_OUTPUT%\""
    }
  }
}
</file>

<file path="src/KnowledgeFabric.LicenseTool/ConfigLoader.cs">
namespace LicenseTool
⋮----
public static class ConfigLoader
⋮----
public static LicenseConfig Load(string configPath)
⋮----
if (!File.Exists(configPath))
⋮----
throw new FileNotFoundException($"License Configuration JSON file not found at path: {configPath}");
⋮----
string configJson = File.ReadAllText(configPath);
⋮----
throw new Exception("Configuration JSON is empty or malformed.");
⋮----
throw new Exception(
⋮----
throw new Exception("Invalid JSON - Formatting/Syntax errors found.", ex);
</file>

<file path="src/KnowledgeFabric.LicenseTool/ContractReader.cs">
namespace LicenseTool
⋮----
public sealed class ContractVerdict
⋮----
public static class ContractReader
⋮----
public static ContractVerdict Read(string licenseXml, string publicKey, DateTime evaluationInstantUtc)
⋮----
License license;
⋮----
license = License.Load(licenseXml);
⋮----
return new ContractVerdict
⋮----
var signatureValid = license.VerifySignature(publicKey);
⋮----
var trialShaped = attributes.ContainsKey(LicenseContract.Attributes.TrialDays);
⋮----
var entitlements = Entitlements.Read(new Dictionary<string, string>(attributes, StringComparer.Ordinal));
⋮----
.Where(name => !LicenseContract.Attributes.Known.Contains(name, StringComparer.Ordinal))
.OrderBy(name => name, StringComparer.Ordinal)
.ToList();
⋮----
Tier = attributes.TryGetValue(LicenseContract.Attributes.Tier, out var tier) ? tier : null,
AiTier = LicenseContract.Tiers.ForAi(tier),
Purpose = LicenseContract.Purposes.Of(new Dictionary<string, string>(attributes, StringComparer.Ordinal)),
Company = string.IsNullOrWhiteSpace(license.Customer?.Company) ? null : license.Customer.Company,
⋮----
public static string UnsupportedSchemaMessage(int declaredVersion) =>
$"This licence declares schema version {declaredVersion.ToString(CultureInfo.InvariantCulture)}, " +
$"which is newer than this build supports (version {LicenseContract.SupportedSchemaVersion.ToString(CultureInfo.InvariantCulture)}). " +
⋮----
private static string? FirstReason(bool signatureValid, bool schemaSupported, bool trialShaped, bool expired, bool inForce)
⋮----
private static bool TryReadSchemaVersion(IDictionary<string, string> attributes, out int schemaVersion)
⋮----
if (!attributes.TryGetValue(LicenseContract.Attributes.SchemaVersion, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out schemaVersion))
⋮----
private static DateTime? ReadValidFrom(IDictionary<string, string> attributes)
⋮----
if (!attributes.TryGetValue(LicenseContract.Attributes.ValidFrom, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
return DateTimeOffset.TryParse(raw, CultureInfo.InvariantCulture, styles, out var parsed)
⋮----
private static DateTime ToUtc(DateTime value) => value.Kind switch
⋮----
DateTimeKind.Local => value.ToUniversalTime(),
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc),
</file>

<file path="src/KnowledgeFabric.LicenseTool/Entitlements.cs">
namespace LicenseTool
⋮----
public sealed class Entitlements
⋮----
public static readonly Entitlements None = new();
⋮----
public long? Limit(string attribute) => attribute switch
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(attribute), attribute, "Not a limit."),
⋮----
public static Entitlements Read(IReadOnlyDictionary<string, string> attributes)
⋮----
return new Entitlements
⋮----
Reports = ReadNames(attributes, LicenseContract.Attributes.Reports, LicenseContract.Reports.All.Select(e => e.Name), ignored),
Features = ReadNames(attributes, LicenseContract.Attributes.Features, LicenseContract.Features.All.Select(e => e.Name), ignored),
⋮----
Ai = ReadNames(attributes, LicenseContract.Attributes.Ai, LicenseContract.Ai.All.Select(e => e.Name), ignored),
⋮----
public static string JoinList(IEnumerable<string> entries) => string.Join(",", entries);
⋮----
public static string FormatSource(string name, long? count) =>
count is null ? name : name + ":" + count.Value.ToString(CultureInfo.InvariantCulture);
⋮----
public static IEnumerable<string> SplitList(string raw) =>
raw.Split(',').Select(entry => entry.Trim()).Where(entry => entry.Length > 0);
⋮----
public static (string Name, string? Count) SplitSource(string entry)
⋮----
var colon = entry.IndexOf(':');
⋮----
? (entry.Trim(), null)
: (entry[..colon].Trim(), entry[(colon + 1)..].Trim());
⋮----
public static long? ParsePositive(string raw) =>
long.TryParse(raw, NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value > 0 ? value : null;
⋮----
private static IReadOnlyList<string> ReadNames(
⋮----
if (!attributes.TryGetValue(attribute, out var raw))
⋮----
var known = catalogue.ToList();
⋮----
if (known.Contains(name, StringComparer.Ordinal))
⋮----
granted.Add(name);
⋮----
return known.Where(granted.Contains).ToList();
⋮----
private static IReadOnlyList<SourceGrant> ReadSources(IReadOnlyDictionary<string, string> attributes, List<string> ignored)
⋮----
if (!attributes.TryGetValue(LicenseContract.Attributes.Sources, out var raw))
⋮----
var known = LicenseContract.Sources.All.Select(e => e.Name).ToList();
⋮----
if (!known.Contains(name, StringComparer.Ordinal))
⋮----
counts[name] = counts.TryGetValue(name, out var earlier) ? Lower(earlier, count) : count;
⋮----
.Where(counts.ContainsKey)
.Select(name => new SourceGrant(name, counts[name]))
.ToList();
⋮----
private static long? ReadLimit(IReadOnlyDictionary<string, string> attributes, string attribute)
⋮----
if (!attributes.TryGetValue(attribute, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
return ParsePositive(raw.Trim()) ?? 0;
⋮----
private static string? ReadPeriod(IReadOnlyDictionary<string, string> attributes, List<string> ignored)
⋮----
if (!attributes.TryGetValue(LicenseContract.Attributes.AiPeriod, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
var period = raw.Trim();
if (LicenseContract.AiPeriods.All.Contains(period, StringComparer.Ordinal))
⋮----
private static long? Lower(long? a, long? b) => a is null ? b : b is null ? a : Math.Min(a.Value, b.Value);
⋮----
private static void Ignore(List<string> ignored, string attribute, string name)
⋮----
if (!ignored.Contains(entry, StringComparer.Ordinal))
⋮----
ignored.Add(entry);
</file>

<file path="src/KnowledgeFabric.LicenseTool/FixtureGenerator.cs">
namespace LicenseTool
⋮----
public static class FixtureGenerator
⋮----
private static readonly JsonSerializerOptions ManifestJson = new()
⋮----
public static int Generate(string definitionPath, string outputDirectory)
⋮----
var definitionDirectory = Path.GetDirectoryName(Path.GetFullPath(definitionPath)) ?? ".";
⋮----
if (!definition.SigningKeys.TryGetValue("contract", out var contractKey))
⋮----
throw new Exception("The fixture set must define a signing key named 'contract' -- it is the key readers verify against.");
⋮----
Directory.CreateDirectory(outputDirectory);
⋮----
var contractPublicKey = File.ReadAllText(Resolve(definitionDirectory, contractKey.PublicKey)).Trim();
⋮----
File.WriteAllBytes(Path.Combine(outputDirectory, fileName), fileBytes);
⋮----
var verdict = ContractReader.Read(licenseXml, contractPublicKey, evaluationInstantUtc);
⋮----
failures.Add($"{fixture.Name}: {string.Join("; ", mismatches)}");
⋮----
entries.Add(new ManifestFixture
⋮----
Expect = new ManifestExpectation
⋮----
Reports = verdict.Entitlements.Reports.ToList(),
Features = verdict.Entitlements.Features.ToList(),
Sources = verdict.Entitlements.Sources.ToDictionary(grant => grant.Name, grant => grant.Count),
Ai = verdict.Entitlements.Ai.ToList(),
Limits = FixtureLimits.From(verdict.Entitlements),
IgnoredNames = verdict.Entitlements.IgnoredNames.ToList(),
UnknownAttributes = verdict.UnknownAttributes.ToList(),
⋮----
Console.WriteLine($"  [{status,8}] {fixture.Name,-30} {verdict.Reason ?? "(accepted)"}");
⋮----
File.Copy(source, Path.Combine(outputDirectory, Path.GetFileName(source)), overwrite: true);
⋮----
var manifest = new Manifest
⋮----
GeneratedFrom = Path.GetFileName(definitionPath),
GeneratedAtUtc = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
EvaluationInstant = definition.EvaluationInstant.UtcDateTime.ToString("o", CultureInfo.InvariantCulture),
PublicKeys = definition.SigningKeys.ToDictionary(k => k.Key, k => Path.GetFileName(k.Value.PublicKey)),
⋮----
File.WriteAllText(
Path.Combine(outputDirectory, "manifest.json"),
JsonSerializer.Serialize(manifest, ManifestJson) + Environment.NewLine);
⋮----
Console.Error.WriteLine();
Console.Error.WriteLine($"{failures.Count} fixture(s) do not behave as the set declares:");
⋮----
Console.Error.WriteLine("  - " + failure);
⋮----
private static FixtureSetDefinition LoadDefinition(string definitionPath)
⋮----
if (!File.Exists(definitionPath))
⋮----
throw new FileNotFoundException($"Fixture set definition not found at path: {definitionPath}");
⋮----
var definition = JsonSerializer.Deserialize<FixtureSetDefinition>(File.ReadAllText(definitionPath));
⋮----
throw new Exception("Fixture set definition is empty or malformed.");
⋮----
throw new Exception("The fixture set must declare an 'evaluationInstant' -- readers freeze their clock to it.");
⋮----
private static string Mint(FixtureCase fixture, FixtureSetDefinition definition, string definitionDirectory, DateTimeOffset issuedAt)
⋮----
throw new Exception($"Fixture '{fixture.Name}' has neither a 'license' config nor a 'literal'.");
⋮----
if (!definition.SigningKeys.TryGetValue(fixture.SignedWith, out var key))
⋮----
throw new Exception($"Fixture '{fixture.Name}' is signed with unknown key '{fixture.SignedWith}'.");
⋮----
LicenseTerms terms;
⋮----
throw new Exception($"Fixture '{fixture.Name}' sets productFeatures, which only a verbatim case may.");
⋮----
? LicenseTerms.Verbatim(fixture.License, issuedAt, fixture.ProductFeatures)
: LicenseTerms.Resolve(fixture.License, issuedAt);
⋮----
throw new Exception($"Fixture '{fixture.Name}': {ex.Message}", ex);
⋮----
var licenseXml = LicenseGenerator.Sign(
⋮----
if (!licenseXml.Contains(fixture.Tamper.Find, StringComparison.Ordinal))
⋮----
throw new Exception($"Fixture '{fixture.Name}' cannot be tampered: '{fixture.Tamper.Find}' is not in the signed document.");
⋮----
return licenseXml.Replace(fixture.Tamper.Find, fixture.Tamper.Replace, StringComparison.Ordinal);
⋮----
private static List<string> Compare(FixtureExpectation expected, ContractVerdict measured)
⋮----
mismatches.Add($"{field} expected {Describe(want)}, measured {Describe(got)}");
⋮----
var wanted = want.OrderBy(k => k, StringComparer.Ordinal).ToList();
var measuredNames = got.OrderBy(k => k, StringComparer.Ordinal).ToList();
if (!measuredNames.SequenceEqual(wanted, StringComparer.Ordinal))
... (35 lines truncated)
</file>

<file path="src/KnowledgeFabric.LicenseTool/FixtureSet.cs">
namespace LicenseTool
⋮----
public class FixtureSetDefinition
⋮----
public class FixtureSigningKey
⋮----
public class FixtureCase
⋮----
public class FixtureTamper
⋮----
public class FixtureExpectation
⋮----
public static FixtureLimits From(Entitlements entitlements) => new()
</file>

<file path="src/KnowledgeFabric.LicenseTool/KeyGenerator.cs">
namespace LicenseTool
⋮----
public static class KeyGenerator
⋮----
public static void GenerateKeys(string passphrase, string outputLocation)
⋮----
if (!string.IsNullOrEmpty(outputLocation) && !Directory.Exists(outputLocation))
⋮----
Directory.CreateDirectory(outputLocation);
⋮----
var privateKeyFilePath = Path.Combine(outputLocation, "private.key");
var publicKeyFilePath = Path.Combine(outputLocation, "public.key");
⋮----
if (File.Exists(privateKeyFilePath) || File.Exists(publicKeyFilePath))
⋮----
throw new InvalidOperationException(
⋮----
var keyGen = Standard.Licensing.Security.Cryptography.KeyGenerator.Create();
var keyPair = keyGen.GenerateKeyPair();
var publicKey = keyPair.ToPublicKeyString();
⋮----
var privateKey = KeyRekeyer.Encrypt(
KeyRekeyer.Decrypt(keyPair.ToEncryptedPrivateKeyString(passphrase), passphrase),
⋮----
File.WriteAllText(privateKeyFilePath, privateKey);
File.WriteAllText(publicKeyFilePath, publicKey);
⋮----
Console.WriteLine("Keys generated successfully:");
Console.WriteLine($"  Private Key: {privateKeyFilePath}");
Console.WriteLine($"  Public Key:  {publicKeyFilePath}");
</file>

<file path="src/KnowledgeFabric.LicenseTool/KeyRekeyer.cs">
namespace LicenseTool
⋮----
public static class KeyRekeyer
⋮----
public static string Rekey(
⋮----
if (!File.Exists(privateKeyPath))
⋮----
throw new FileNotFoundException($"Private key file not found at: {privateKeyPath}");
⋮----
if (string.IsNullOrEmpty(newPassphrase))
⋮----
throw new ArgumentException("The new passphrase must not be empty.", nameof(newPassphrase));
⋮----
throw new ArgumentException(
⋮----
var privateKey = Open(File.ReadAllText(privateKeyPath), currentPassphrase, privateKeyPath);
⋮----
throw new InvalidOperationException(
⋮----
var outputDirectory = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(outputDirectory) && !Directory.Exists(outputDirectory))
⋮----
Directory.CreateDirectory(outputDirectory);
⋮----
File.WriteAllText(outputPath, reencrypted);
⋮----
internal static AsymmetricKeyParameter Open(string encrypted, string passphrase, string privateKeyPath)
⋮----
encrypted = encrypted.Trim();
⋮----
der = Convert.FromBase64String(encrypted);
⋮----
internal static string Encrypt(AsymmetricKeyParameter privateKey, string passphrase)
⋮----
SecureRandom.GetInstance("SHA256PRNG", true).NextBytes(salt);
⋮----
return Convert.ToBase64String(
PrivateKeyFactory.EncryptKey(
⋮----
passphrase.ToCharArray(),
⋮----
internal static AsymmetricKeyParameter Decrypt(string blob, string passphrase)
⋮----
return PrivateKeyFactory.DecryptKey(passphrase.ToCharArray(), Convert.FromBase64String(blob));
⋮----
private static bool IsPublicKey(byte[] der)
⋮----
return !PublicKeyFactory.CreateKey(der).IsPrivate;
⋮----
private static string DerivePublicKeyString(AsymmetricKeyParameter privateKey)
⋮----
$"Expected an EC private key, found {privateKey.GetType().Name}. The licensing key pair is ECDSA.");
⋮----
var q = ec.Parameters.G.Multiply(ec.D).Normalize();
⋮----
? new ECPublicKeyParameters(ec.AlgorithmName, q, ec.PublicKeyParamSet)
: new ECPublicKeyParameters(ec.AlgorithmName, q, ec.Parameters);
⋮----
.CreateSubjectPublicKeyInfo(publicKey)
.ToAsn1Object()
.GetDerEncoded());
</file>

<file path="src/KnowledgeFabric.LicenseTool/LicenseConfig.cs">
namespace LicenseTool
⋮----
public class LicenseConfig
</file>

<file path="src/KnowledgeFabric.LicenseTool/LicenseContract.cs">
namespace LicenseTool
⋮----
public static class LicenseContract
⋮----
public static class Attributes
⋮----
new[] { SchemaVersion, IssuedAt, ValidFrom, Tier, Purpose, TrialDays }.Concat(Entitlements).ToArray();
⋮----
public static class Reports
⋮----
public static class Features
⋮----
public static class Sources
⋮----
public static class Ai
⋮----
public static class AiPeriods
⋮----
public static class Limits
⋮----
public static readonly LimitEntry SourcesMax = new(
⋮----
public static readonly LimitEntry Employees = new(
⋮----
public static readonly LimitEntry Assets = new(
⋮----
public static readonly LimitEntry History = new(
⋮----
public static readonly LimitEntry AiTokens = new(
⋮----
public static readonly LimitEntry AiRequestsPerMinute = new(
⋮----
public static class Presets
⋮----
public static long? SourcesMax(string? tier) =>
string.Equals(tier, Tiers.Standard, StringComparison.Ordinal) ? 10 : null;
⋮----
public static class Purposes
⋮----
public static string Of(IReadOnlyDictionary<string, string> attributes) =>
attributes.TryGetValue(Attributes.Purpose, out var purpose) && !string.IsNullOrWhiteSpace(purpose)
? purpose.Trim()
⋮----
public static class Tiers
⋮----
public static string ForAi(string? tier) =>
tier is not null && All.Contains(tier, StringComparer.Ordinal) ? tier : Standard;
⋮----
public static class Reasons
⋮----
public static bool IsWellFormedName(string name) =>
⋮----
&& name.All(c => c is >= 'a' and <= 'z' or >= '0' and <= '9');
⋮----
public static bool IsEntitlementAttributeName(string name) =>
Attributes.Entitlements.Contains(name, StringComparer.Ordinal)
|| Attributes.ReservedPrefixes.Any(prefix => name.StartsWith(prefix, StringComparison.Ordinal));
⋮----
public static bool IsReservedAttributeName(string name) =>
string.Equals(name, Attributes.TrialDays, StringComparison.Ordinal) || IsEntitlementAttributeName(name);
</file>

<file path="src/KnowledgeFabric.LicenseTool/LicenseGenerator.cs">
namespace LicenseTool
⋮----
public static class LicenseGenerator
⋮----
public static string Sign(LicenseTerms terms, string privateKeyPath, string passphrase)
⋮----
if (!File.Exists(privateKeyPath))
⋮----
throw new FileNotFoundException($"Private key file not found at: {privateKeyPath}");
⋮----
var privateKey = File.ReadAllText(privateKeyPath);
⋮----
return LicenseSigner.Sign(terms, privateKey, passphrase);
⋮----
KeyRekeyer.Open(privateKey, passphrase, privateKeyPath);
⋮----
public static string GenerateLicense(
⋮----
var terms = LicenseTerms.Resolve(config, DateTimeOffset.UtcNow, allowUnknownNames);
⋮----
Console.Error.WriteLine("Warning: " + warning);
⋮----
var outputDir = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir))
⋮----
Directory.CreateDirectory(outputDir);
⋮----
File.WriteAllText(outputPath, licenseText, Encoding.UTF8);
⋮----
Console.WriteLine($"License generated at: {outputPath}");
Console.WriteLine("\n=== Generated License ===\n");
Console.WriteLine(licenseText);
Console.WriteLine("\n=========================\n");
</file>

<file path="src/KnowledgeFabric.LicenseTool/LicenseSigner.cs">
namespace LicenseTool
⋮----
public static class LicenseSigner
⋮----
public static string Sign(LicenseTerms terms, string privateKey, string passphrase)
⋮----
var builder = License.New()
.WithUniqueIdentifier(terms.LicenseId)
.As(terms.LicenseType)
⋮----
.WithMaximumUtilization(1)
⋮----
.WithProductFeatures(productFeatures: new Dictionary<string, string>(terms.ProductFeatures))
.WithAdditionalAttributes(new Dictionary<string, string>(terms.Attributes));
⋮----
? builder.LicensedTo(terms.Name, terms.Email)
: builder.LicensedTo(terms.Name, terms.Email, customer => customer.Company = terms.Company);
⋮----
.ExpiresAt(terms.ExpirationUtc)
.CreateAndSignWithPrivateKey(privateKey, passphrase);
⋮----
return license.ToString();
</file>

<file path="src/KnowledgeFabric.LicenseTool/LicenseTerms.cs">
namespace LicenseTool
⋮----
public sealed class LicenseTerms
⋮----
private static readonly Regex InstantPattern = new(
⋮----
private static readonly Regex DurationPattern = new(
⋮----
public static LicenseTerms Resolve(LicenseConfig config, DateTimeOffset issuedAt, bool allowUnknownNames = false) =>
⋮----
public static LicenseTerms Verbatim(
⋮----
private static LicenseTerms Build(
⋮----
errors.Add(config.LicenseType == LicenseType.Trial
⋮----
var licenseId = Guid.NewGuid();
if (!string.IsNullOrWhiteSpace(config.LicenseId))
⋮----
if (!Guid.TryParse(config.LicenseId, out licenseId) || licenseId == Guid.Empty)
⋮----
errors.Add($"licenseId '{config.LicenseId}' is not a GUID. Leave it out to have one generated.");
⋮----
var hasExpiration = !string.IsNullOrWhiteSpace(config.Expiration);
var hasDuration = !string.IsNullOrWhiteSpace(config.Duration);
⋮----
errors.Add("Set either expiration or duration, not both.");
⋮----
errors.Add("Set either expiration (e.g. 2027-12-31T23:59:59Z) or duration (e.g. P1Y).");
⋮----
errors.Add($"validFrom {Format(validFrom.Value)} is not before the expiration {Format(expiration.Value)}.");
⋮----
warnings.Add($"The expiration {Format(expiration.Value)} has already passed. The product will refuse this licence on upload.");
⋮----
if (config.Tier is not null && !LicenseContract.Tiers.All.Contains(config.Tier, StringComparer.Ordinal))
⋮----
errors.Add($"tier '{config.Tier}' is not one of: {string.Join(", ", LicenseContract.Tiers.All)}. Leave it out to issue a licence with no tier.");
⋮----
LicenseContract.IssuedSchemaVersion.ToString(CultureInfo.InvariantCulture);
⋮----
if (LicenseContract.Purposes.All.Any(entry => entry.Name == purpose))
⋮----
errors.Add($"purpose '{purpose}' is not one of: {string.Join(", ", LicenseContract.Purposes.All.Select(entry => entry.Name))}. "
⋮----
var entitlements = new EntitlementWriter(attributes, errors, warnings, allowUnknownNames);
entitlements.Names(LicenseContract.Attributes.Reports, "report", config.Reports, LicenseContract.Reports.All.Select(e => e.Name));
entitlements.Names(LicenseContract.Attributes.Features, "feature", config.Features, LicenseContract.Features.All.Select(e => e.Name));
entitlements.Sources(config.Sources);
entitlements.Limit(LicenseContract.Attributes.SourcesMax, config.SourcesMax);
entitlements.Limit(LicenseContract.Attributes.AnalysisEmployees, config.AnalysisEmployees);
entitlements.Limit(LicenseContract.Attributes.AnalysisAssets, config.AnalysisAssets);
entitlements.Limit(LicenseContract.Attributes.AnalysisHistory, config.AnalysisHistory);
entitlements.Names(LicenseContract.Attributes.Ai, "AI capability", config.Ai, LicenseContract.Ai.All.Select(e => e.Name));
entitlements.Limit(LicenseContract.Attributes.AiTokens, config.AiTokens);
entitlements.Period(config.AiPeriod);
entitlements.Limit(LicenseContract.Attributes.AiRequestsPerMinute, config.AiRequestsPerMinute);
⋮----
warnings.Add("This licence grants no report, feature, connector or AI capability: it installs and unlocks nothing.");
⋮----
if (!verbatim && LicenseContract.IsReservedAttributeName(name))
⋮----
errors.Add(string.Equals(name, LicenseContract.Attributes.TrialDays, StringComparison.Ordinal)
⋮----
+ $"({string.Join(", ", LicenseContract.Attributes.Grants)}, and anything starting "
+ $"{string.Join(", ", LicenseContract.Attributes.ReservedPrefixes)}).");
⋮----
if (!verbatim && IssuerAttributes.TryGetValue(name, out var instead))
⋮----
errors.Add($"attributes may not contain '{name}': {instead}.");
⋮----
if (!attributes.TryAdd(name, value))
⋮----
errors.Add($"attribute '{name}' is set twice, by a top-level field and in attributes.");
⋮----
throw new LicenseConfigException(errors);
⋮----
return new LicenseTerms
⋮----
Company = string.IsNullOrWhiteSpace(config.Company) ? null : config.Company,
⋮----
private sealed class EntitlementWriter(
⋮----
public void Names(string attribute, string noun, IReadOnlyList<string>? names, IEnumerable<string> catalogue)
⋮----
accepted.Add(name);
⋮----
public void Sources(IReadOnlyList<string>? entries)
⋮----
var catalogue = LicenseContract.Sources.All.Select(e => e.Name).ToList();
⋮----
var (name, countText) = Entitlements.SplitSource(entry ?? string.Empty);
⋮----
count = Entitlements.ParsePositive(countText);
⋮----
errors.Add($"sources entry '{entry}' has a count that is not a positive whole number. "
⋮----
written[name] = Entitlements.FormatSource(name, count);
⋮----
Write(attribute, InCatalogueOrder(accepted, catalogue).Select(name => written[name]));
⋮----
... (78 lines truncated)
</file>

<file path="src/KnowledgeFabric.LicenseTool/Program.cs">
namespace LicenseTool
⋮----
class Program
⋮----
internal static int Main(string[] args)
⋮----
var rootCommand = new RootCommand("KnowledgeFabric License Tool CLI");
⋮----
var genKeysCommand = new Command("gen-keys", "Generates a new pair of keys (i.e. private and public key)");
⋮----
DefaultValueFactory = _ => Directory.GetCurrentDirectory()
⋮----
genKeysCommand.Options.Add(passphraseOption);
genKeysCommand.Options.Add(outputLocationOption);
⋮----
genKeysCommand.SetAction(parseResult =>
⋮----
var passphrase = parseResult.GetValue(passphraseOption)!;
var outputLocation = parseResult.GetValue(outputLocationOption)!;
⋮----
KeyGenerator.GenerateKeys(passphrase, outputLocation);
⋮----
Console.Error.WriteLine("Key generation failed! " + ex.Message);
⋮----
var licenseCommand = new Command("gen-license", "Generate a license using a configuration file.");
⋮----
DefaultValueFactory = _ => Path.Combine(Directory.GetCurrentDirectory(), "license.lic")
⋮----
licenseCommand.Options.Add(configPathOption);
licenseCommand.Options.Add(privateKeyOption);
licenseCommand.Options.Add(passphraseOption);
licenseCommand.Options.Add(outputOption);
licenseCommand.Options.Add(registerCsvOption);
licenseCommand.Options.Add(issuedByOption);
licenseCommand.Options.Add(allowUnknownNamesOption);
⋮----
licenseCommand.SetAction(parseResult =>
⋮----
var configPath = parseResult.GetValue(configPathOption)!;
var privateKey = parseResult.GetValue(privateKeyOption)!;
⋮----
var output = parseResult.GetValue(outputOption)!;
var registerCsv = parseResult.GetValue(registerCsvOption);
var issuedBy = parseResult.GetValue(issuedByOption);
var allowUnknownNames = parseResult.GetValue(allowUnknownNamesOption);
⋮----
var config = ConfigLoader.Load(configPath);
⋮----
licenseText = LicenseGenerator.GenerateLicense(config, privateKey, passphrase, output, allowUnknownNames);
⋮----
Console.Error.WriteLine("License Generation Failed! " + ex.Message);
⋮----
Console.Error.WriteLine(ex.InnerException.Message);
⋮----
if (string.IsNullOrWhiteSpace(registerCsv))
⋮----
var record = RegisterRecord.FromLicense(
⋮----
string.IsNullOrWhiteSpace(issuedBy) ? Environment.UserName : issuedBy,
⋮----
RegisterCsv.Append(registerCsv, record);
Console.WriteLine($"Register row appended to: {registerCsv}");
⋮----
Console.Error.WriteLine($"The licence was written to {output}, but recording it in {registerCsv} failed: {ex.Message}");
⋮----
var fixturesCommand = new Command(
⋮----
fixturesCommand.Options.Add(setOption);
fixturesCommand.Options.Add(fixturesOutputOption);
⋮----
fixturesCommand.SetAction(parseResult =>
⋮----
var definitionPath = parseResult.GetValue(setOption)!;
var outputDirectory = parseResult.GetValue(fixturesOutputOption)!;
⋮----
Console.WriteLine($"Generating the licence contract fixture set from {definitionPath}");
var failures = FixtureGenerator.Generate(definitionPath, outputDirectory);
⋮----
Console.WriteLine($"Fixture set written to {outputDirectory} -- every fixture verified.");
⋮----
Console.Error.WriteLine("Fixture generation failed! " + ex.Message);
Console.Error.WriteLine(ex.InnerException);
⋮----
var rekeyCommand = new Command(
⋮----
rekeyCommand.Options.Add(rekeyPrivateKeyOption);
rekeyCommand.Options.Add(currentPassphraseOption);
rekeyCommand.Options.Add(newPassphraseOption);
rekeyCommand.Options.Add(rekeyOutputOption);
⋮----
rekeyCommand.SetAction(parseResult =>
⋮----
var privateKeyPath = parseResult.GetValue(rekeyPrivateKeyOption)!;
var currentPassphrase = parseResult.GetValue(currentPassphraseOption)!;
var newPassphrase = parseResult.GetValue(newPassphraseOption)!;
var output = parseResult.GetValue(rekeyOutputOption);
⋮----
if (string.IsNullOrWhiteSpace(output))
⋮----
if (Path.GetFullPath(output) == Path.GetFullPath(privateKeyPath))
... (31 lines truncated)
</file>

<file path="src/KnowledgeFabric.LicenseTool/RegisterCsv.cs">
namespace LicenseTool
⋮----
public static class RegisterCsv
⋮----
public static void Append(string path, RegisterRecord record)
⋮----
var directory = Path.GetDirectoryName(Path.GetFullPath(path));
if (!string.IsNullOrEmpty(directory))
⋮----
Directory.CreateDirectory(directory);
⋮----
var lines = new StringBuilder();
if (!File.Exists(path) || new FileInfo(path).Length == 0)
⋮----
lines.Append(RegisterRecord.CsvLine(RegisterRecord.CsvColumns)).Append("\r\n");
⋮----
lines.Append(RegisterRecord.CsvLine(record.CsvFields())).Append("\r\n");
⋮----
File.AppendAllText(path, lines.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
</file>

<file path="src/KnowledgeFabric.LicenseTool/RegisterRecord.cs">
namespace LicenseTool
⋮----
public sealed class RegisterRecord
⋮----
public string Purpose => LicenseContract.Purposes.Of(Attributes);
⋮----
public Entitlements Entitlements => Entitlements.Read(Attributes);
⋮----
!Attributes.Keys.Any(name => LicenseContract.Attributes.Entitlements.Contains(name, StringComparer.Ordinal));
⋮----
.Where(pair => !LicenseContract.IsEntitlementAttributeName(pair.Key))
.OrderBy(pair => pair.Key, StringComparer.Ordinal);
⋮----
public static RegisterRecord FromLicense(string licenseXml, string issuedBy, string issuedByLogin, DateTime recordedAtUtc)
⋮----
var license = License.Load(licenseXml);
⋮----
return new RegisterRecord
⋮----
RecordId = Guid.NewGuid(),
⋮----
Company = string.IsNullOrWhiteSpace(license.Customer?.Company) ? null : license.Customer.Company,
LicenseType = license.Type.ToString(),
Tier = attributes.TryGetValue(LicenseContract.Attributes.Tier, out var tier) ? tier : null,
⋮----
public static byte[] FileBytes(string licenseXml) =>
Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(licenseXml)).ToArray();
⋮----
public static string Sha256Of(string licenseXml) =>
Convert.ToHexString(SHA256.HashData(FileBytes(licenseXml))).ToLowerInvariant();
⋮----
var customer = new string(CustomerName.Select(c => char.IsLetterOrDigit(c) ? c : '-').ToArray()).Trim('-');
⋮----
public IEnumerable<string> CsvFields()
⋮----
yield return LicenseId.ToString();
⋮----
yield return Attributes.TryGetValue(grant, out var list) ? string.Join(";", Entitlements.SplitList(list)) : string.Empty;
⋮----
yield return Pairs(Attributes.Where(pair =>
LicenseContract.IsEntitlementAttributeName(pair.Key)
&& !LicenseContract.Attributes.Grants.Contains(pair.Key, StringComparer.Ordinal)));
⋮----
public static string CsvLine(IEnumerable<string> fields) => string.Join(",", fields.Select(CsvField));
⋮----
private static string CsvField(string value)
⋮----
if (value.Length > 0 && "=+-@\t\r".Contains(value[0]))
⋮----
return value.IndexOfAny(new[] { ',', '"', '\r', '\n' }) >= 0
? "\"" + value.Replace("\"", "\"\"") + "\""
⋮----
private static string Pairs(IEnumerable<KeyValuePair<string, string>> pairs) =>
string.Join(";", pairs.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => $"{pair.Key}={pair.Value}"));
⋮----
private static string Iso(DateTime? value) =>
⋮----
private static int? ReadSchemaVersion(IDictionary<string, string> attributes)
⋮----
if (!attributes.TryGetValue(LicenseContract.Attributes.SchemaVersion, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
return int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var version) ? version : null;
⋮----
private static DateTime? ReadInstant(IDictionary<string, string> attributes, string name)
⋮----
if (!attributes.TryGetValue(name, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
return DateTimeOffset.TryParse(raw, CultureInfo.InvariantCulture, styles, out var parsed)
⋮----
private static DateTime ToUtc(DateTime value) => value.Kind switch
⋮----
DateTimeKind.Local => value.ToUniversalTime(),
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc),
</file>

<file path="CLAUDE.md">
# kf-admin

KnowledgeFabric's internal admin console. Licence issuing is its first tenant and, today, its only
one: everything in this repository is the CLI tool that mints the ECDSA signing keys and the signed
XML licence files used to unlock a KnowledgeFabric installation. .NET 8, `System.CommandLine` 2.0,
`Standard.Licensing` 1.2.1.

**The console shell exists, with five tenants: licensing, the AI gateway, the CRM, bookings, and competitors.** `src/KnowledgeFabric.AdminConsole/`
is an ASP.NET Core MVC application — sign-in, layout, `/health`, and the authorisation, audit and
storage seams — built for [#15](https://github.com/KnowledgeFabric/kf-admin/issues/15) on the Vuexy
template copied from kf-app and recoloured. Read [docs/Console-Shell.md](docs/Console-Shell.md)
before touching it. Sign-in is a name and a secret per person, `Authentication--Users--<name>` in
Key Vault ([#68](https://github.com/KnowledgeFabric/kf-admin/issues/68)), and nothing else: the
shared password is retired ([#89](https://github.com/KnowledgeFabric/kf-admin/issues/89)), a
configured one is ignored with a warning at startup, and `shared-credential`, the actor on every
entry written under it, stays only so those entries still read as unattributable.
**What a name may do is its roles** ([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)):
`Administrator`, and a view and a write role per area (licensing, gateway, CRM, bookings, competitors), rows of
`console_roles` in `kf_admin` granted on `/Users` and read per request, so a revoke counts at the
next request. The name `admin` holds every role by construction and nothing can touch it. Pages ask a policy (`ConsolePolicies`: `licensing:view`, `gateway:write`
and so on), never a role or the store: nothing outside `Security/`, `UsersController` and its view
knows where roles are held. `Authentication--Writers` is read by nothing. Its licensing area has the register of issued licences
([#8](https://github.com/KnowledgeFabric/kf-admin/issues/8), [docs/License-Register.md](docs/License-Register.md)),
on PostgreSQL (`kf_admin`, provisioned) and migrated at startup, and the issue form
([#6](https://github.com/KnowledgeFabric/kf-admin/issues/6)), which signs through the CLI's own
`LicenseTerms` and `LicenseSigner` — linked source files, not a project reference — and records every
licence before it can be downloaded, and the validate page, which reads a licence through
`ContractReader` and shows the product's and the gateway's verdicts, each as that reader behaves
today and as the contract requires. Each register row lists the installations the gateway holds
with its licence, through the console's read-only client for the gateway's `/admin`
([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). The overview, the console's landing page, is the register's
dashboard ([#37](https://github.com/KnowledgeFabric/kf-admin/issues/37)). It counts by licence
id, not by row, because a reissue keeps the id
([docs/License-Register.md](docs/License-Register.md#the-overview)). The "today" verdicts cite the kf-app and kf-ai-gateway commits
they were read at (`LicenceValidator`); when either reader changes, re-read it and move the commit.
kf-app's is read on `develop`, which can be ahead of its release (`ProductRelease`); where the
release differs, the page says so (#61). Its AI Gateway area
([#64](https://github.com/KnowledgeFabric/kf-admin/issues/64), the first page of
[#63](https://github.com/KnowledgeFabric/kf-admin/issues/63); [docs/Gateway-Management.md](docs/Gateway-Management.md))
shows what the gateway says of itself through `GET /admin/status`: version, the global brake and
the fleet, read with the gateway's read-only token through a thirty-second cache the home page's
card shares. Against a gateway from before kf-ai-gateway#37 it says the gateway does not report
status yet; the wire names it reads are in `Gateway/GatewayStatus.cs`, and a change to them is a
change there and nowhere else. Its installations ([#65](https://github.com/KnowledgeFabric/kf-admin/issues/65))
list the fleet, filtered, ordered and paged by the gateway (kf-ai-gateway#38, deployed at `241bf4a`),
and give each installation a page with its allowance and usage, in words that say whether each
number is its row's or its licence's, and the register's row for its licence. Their request names
are in `Gateway/InstallationQuery.cs` and the response's in `Gateway/GatewayInstallation.cs`. Its
usage by licence ([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)) joins every licence
in force, by the overview's rule (`RegisterSummary.InForce`), to the installations on the gateway's
two licence rows, in memory, and flags a licence served otherwise than the register's file says;
it assumes a fleet of hundreds, and says so when there are more. Its policy page
([#67](https://github.com/KnowledgeFabric/kf-admin/issues/67)) shows the gateway's allowance rows
and levers (kf-ai-gateway#39, deployed at `34e05ec`; wire names in `Gateway/GatewayPolicy.cs`),
read on every load and never cached, beside the register's licences in force on each licence row,
which the only-goes-up rule protects and the gateway cannot count. Each row and lever is changed
from it ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71), `PolicyChangeController`):
a form checked as the gateway checks it, then a review of the change whole, then the `PUT` under the
write token, audited `gateway:tier` or `gateway:policy` with the row before and after. **The
only-goes-up rule lives in the console** (`AllowanceRule`): the gateway accepts any lowering, so
the form refuses one on `standard` or `enterprise` while the register holds a licence in force on
it, or cannot be read.
Its usage history ([#70](https://github.com/KnowledgeFabric/kf-admin/issues/70)) reads the gateway's
daily usage ledger (kf-ai-gateway#41, deployed at `431701c`; wire names in `Gateway/GatewayUsage.cs`):
the fleet's last thirty days on the overview, an installation's on its page, last month beside this
period on usage by licence, and `/Gateway/Usage/History` for a range, its top installations and two
audited exports. A range is at most 366 UTC days, checked before it is sent.
**Where each installation calls from** ([#217](https://github.com/KnowledgeFabric/kf-admin/issues/217),
kf-ai-gateway#55, not deployed yet; built against `StubGateway`): `location` on a row (country,
network with its AS number, cloud and region, `located_at`; wire names in `Gateway/GatewayInstallation.cs`)
on the installation's page, a *Country* column on the list and a register row, and `by_country` and
`unlocated` on the status (`Gateway/GatewayStatus.cs`) as the overview's *Where the fleet is*, from the
same cached answer. **`"location": null` is *Not located yet* and no field at all is a gateway that does
not report locations** (`GatewayLocationConverter` tells them apart); informational, where traffic
leaves for the internet and not where the server sits, and the pages say so. No country filter: the
gateway has no parameter for one. A country is named from its code by `S.CountryName` (`Country.*`
keys from CLDR, **never `RegionInfo`**, which does not follow the UI culture), and every page showing
one carries DB-IP's attribution from one partial, `_LocationAttribution.cshtml`.
Revoking and restoring an installation ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)) is
its first write, under the write token; every audit entry is also a row in `audit_entries` beside
the register, listed at `/Audit` (`Auditing/AuditRegistration.cs`): everyone's to an Administrator
(`console:audit-all`), and to any other writer only their own ([#99](https://github.com/KnowledgeFabric/kf-admin/issues/99)). **A
`400` from the gateway is the console's bug**: since #38 it refuses a parameter it does not have or
cannot read, so never send one a page did not ask for, a cache-buster included, and check a typed
value before it is sent.
Its CRM area ([#87](https://github.com/KnowledgeFabric/kf-admin/issues/87), [docs/CRM.md](docs/CRM.md))
is the partners and ambassadors programme as records, behind `crm:view` and `crm:write`. Its
contacts grid ([#90](https://github.com/KnowledgeFabric/kf-admin/issues/90), `/Crm/Contacts`,
*Partnerships* in the menu and on the page since [#105](https://github.com/KnowledgeFabric/kf-admin/issues/105))
**looks like the sheet**: the sheet's columns in the sheet's order under the sheet's names, but for
*E*, headed *Engagement Level* (#105; its field, filter and export column are still `e` and
`engagement`), and with one column the sheet never had, *Presentation* after *With?*
([#126](https://github.com/KnowledgeFabric/kf-admin/issues/126): the codes of the presentations a
contact was shown, `C22,T51`, free text up to 200, trimmed and never re-cased; it costs the grid
its fit at 1366, by the team's choice), and in Italian the glossary's names for them ([#107](https://github.com/KnowledgeFabric/kf-admin/issues/107),
`Crm.Field.*`), DataTables for sorting and the frozen header, and cells edited in place by `wwwroot/js/crm-contacts.js` against
`ContactsController`: one `POST /Crm/Contacts/{id}/Cell` per cell save, carrying the row version
(`xmin`, `Contact.Version`), refused as `409` with the colleague's row when the version has moved,
and **nothing is ever merged silently**. **Individual or company is not a column**
([#146](https://github.com/KnowledgeFabric/kf-admin/issues/146)): `entity` on the row's details
... (807 lines truncated)
</file>

<file path="README.md">
# kf-admin

KnowledgeFabric's internal admin console. Licence issuing is its first tenant and, today, its only
one: what the repository actually holds is the command-line tool that mints the signing keys and the
signed licence files used to unlock a KnowledgeFabric installation, and the documentation for it.
The console is now here too — `src/KnowledgeFabric.AdminConsole/`, built for
[#15](https://github.com/KnowledgeFabric/kf-admin/issues/15) — and its licensing area issues a signed
licence from a form, through the same code as the CLI, records it in the register, and validates any
licence file against both readers
([#6](https://github.com/KnowledgeFabric/kf-admin/issues/6), [#8](https://github.com/KnowledgeFabric/kf-admin/issues/8)).
Its AI Gateway area shows what the gateway says of itself: its version, its global brake and its
fleet ([#64](https://github.com/KnowledgeFabric/kf-admin/issues/64), [docs/Gateway-Management.md](docs/Gateway-Management.md)),
its installations, each with what it is allowed, what it has used and the register's row for its
licence ([#65](https://github.com/KnowledgeFabric/kf-admin/issues/65)), every licence in force
beside what its installation has used ([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)),
its policy as it stands ([#67](https://github.com/KnowledgeFabric/kf-admin/issues/67)) and changing
it ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)), its usage history day by day
([#70](https://github.com/KnowledgeFabric/kf-admin/issues/70)), and revoking and restoring an
installation, audited ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)). Its CRM area
holds the partners and ambassadors programme as records: a contacts grid with the sheet's columns,
edited in place, each save attributed and version-checked
([#90](https://github.com/KnowledgeFabric/kf-admin/issues/90), [docs/CRM.md](docs/CRM.md)), and a
dated log of calls, meetings and messages on each contact, drawn into the grid's *Met?* and *With?*
([#91](https://github.com/KnowledgeFabric/kf-admin/issues/91)), with each contact's next action
beneath them, a follow-ups grid of what is due by whom, and the programme's counts on the overview
([#92](https://github.com/KnowledgeFabric/kf-admin/issues/92)), and the customers each partner
introduced as rows on the partner's page, each with a stage recorded as it moves
([#147](https://github.com/KnowledgeFabric/kf-admin/issues/147)).

A licence is a small XML document listing a customer, an expiry date and what it grants — reports,
features, connectors, analysis limits and AI limits — signed with an ECDSA private key held by
KnowledgeFabric. The product verifies that signature against the matching public key, refuses
anything expired or tampered with, and offers only what the licence names
([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38); kf-app does not read it yet).

- **What this repository is:** [docs/Admin-Console.md](docs/Admin-Console.md)
- **Running the console:** [docs/Console-Shell.md](docs/Console-Shell.md)
- **Hosting it, and running the hosted one:** [docs/Provisioning.md](docs/Provisioning.md) and
  [docs/Operations.md](docs/Operations.md)
- **Full documentation:** [`docs/`](docs/README.md)
- **Issuing a licence for a customer:** [docs/Issuing-A-License.md](docs/Issuing-A-License.md)
- **What a licence *means*, normatively:** [docs/License-Contract.md](docs/License-Contract.md),
  with the signed fixture set in [`contract/`](contract/README.md)

> [!IMPORTANT]
> **This is the only issuing code.** kf-app's copy of the tool was deleted by kf-app#982: kf-app
> verifies and interprets a licence and never mints one, and its tests read this repository's
> [signed fixtures](contract/README.md). Issue from the console, or offline with this CLI.
> See [Relationship to kf-app](docs/README.md#relationship-to-kf-app).

## Prerequisites

- **.NET 8 SDK** (`dotnet --version` → 8.x)
- **The signing private key and its passphrase**, for any licence that must work on a stock
  installation. See [Key custody](docs/Issuing-A-License.md#key-custody) — the key is not in this
  repository and must never be committed to it.

## Build

```bash
dotnet build KnowledgeFabricLicensing.sln -c Release
```

Output: `src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/`. Run via `dotnet LicenseTool.dll`, or
the `LicenseTool` / `LicenseTool.exe` apphost beside it. The build is warning-free.

```bash
dotnet test KnowledgeFabricLicensing.sln -c Release
```

Two test projects: the console's, and the CLI's own (`tests/KnowledgeFabric.LicenseTool.Tests`),
which covers config loading, `gen-keys`, `gen-license`'s exit codes and a generate → rekey → sign →
verify round trip. Both sign with `contract/test-keys/` and need no database and no secret.

The solution also builds the admin console, `src/KnowledgeFabric.AdminConsole/`. To run it you need
a sign-in password in user-secrets — see [docs/Console-Shell.md](docs/Console-Shell.md):

```bash
cd src/KnowledgeFabric.AdminConsole
dotnet user-secrets set "Authentication:Users:admin" "<pick something>"
dotnet run
```

Sign in as `admin`, which holds every role; anyone else you add as `Authentication:Users:<name>` is
granted roles on its Users page.

Its stylesheets are tracked build output; rebuilding them after a palette change needs `npm install
&& npm run build:css` in that directory, and nothing else.

## Quickstart

### Generate a keypair

Only when you genuinely need a new one — an ordinary customer licence is signed with the established
key, and a licence signed with a fresh key will not validate on a stock installation.

```bash
dotnet LicenseTool.dll gen-keys --passphrase "<passphrase>" --output ./keys
```

... (263 lines truncated)
</file>

</files>
