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, **/*.webmanifest, **/*.ico, **/*.key, **/*.lic, **/*.json, **/contract/**, **/contract/fixtures/**, **/contract/test-keys/**, **/wwwroot/**, **/src/**/src/libs/**
- 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>
docs/
  Admin-Console.md
  Branching.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
  Operations.md
  Provisioning.md
  README.md
src/
  KnowledgeFabric.AdminConsole/
    Areas/
      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
          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
            _InstallationLicence.cshtml
            _InstallationsUnavailable.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
    Controllers/
      AccountController.cs
      AuditController.cs
      CultureController.cs
      ErrorController.cs
      HomeController.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
      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
      GatewayInstallation.cs
      GatewayOptions.cs
      GatewayPolicy.cs
      GatewayRegistration.cs
      GatewayStatus.cs
      GatewayStatusCache.cs
      GatewayUsage.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
      InvariantFormValueProviderFactory.cs
      LocalisationRegistration.cs
      RoleNames.cs
    Models/
      ConsoleBranding.cs
      ErrorModel.cs
      LoginModel.cs
    Preferences/
      DashboardPreferences.cs
      OverviewAreas.cs
    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
    Views/
      Account/
        Login.cshtml
      Audit/
        Index.cshtml
      Home/
        Index.cshtml
      Offline/
        Index.cshtml
      Preferences/
        Dashboard.cshtml
      Shared/
        Sections/
          Footer/
            _Footer.cshtml
          Menu/
            _VerticalMenu.cshtml
          Navbar/
            _LanguageSwitcher.cshtml
            _Navbar.cshtml
          _Scripts.cshtml
          _ScriptsIncludes.cshtml
          _Styles.cshtml
        _ApexCharts.cshtml
        _BlankLayout.cshtml
        _CommonMasterLayout.cshtml
        _ContentNavbarLayout.cshtml
        Error.cshtml
      Users/
        Index.cshtml
      _ViewImports.cshtml
      _ViewStart.cshtml
    build-vendor.js
    Program.cs
  KnowledgeFabric.LicenseTool/
    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="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)).

## 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 | |
|---|---|---|
| `Gateway:BaseUrl` | `appsettings.json`: `https://ai.knowledgefabric.io` | The address installations enrol at, and not a secret. HTTPS only, or plain HTTP to a gateway on the same machine: the token does not cross a network in clear |
| `Gateway:AdminToken` | Key Vault, `Gateway--AdminToken` ([Provisioning B3](Provisioning.md#b3-load-the-secrets)) | The gateway's `Admin__ReadToken` for the same environment (kf-ai-gateway#40): accepted on `GET` alone, and sent on every read. Never rendered or logged |
| `Gateway:AdminWriteToken` | Key Vault, `Gateway--AdminWriteToken` ([Provisioning B3](Provisioning.md#the-write-token)) | The gateway's `Admin__Token` (#69): sent on writes alone. Absent, no write is attempted and every write control says why. Never rendered or logged |
| `Gateway:Timeout` | `appsettings.json`: five seconds | Short, because the overview every sign-in lands on waits for it |

**No token, no calls**, the same stance as the gateway, which maps no `/admin` without one. The
console still starts, and the pages that would show what the gateway knows say it is not configured.

**It reads with one token and writes with another.** Every read is a `GET` with the read token:

| Request | For |
|---|---|
| `/admin/installations?licence_id=<id>` | A register row: every installation holding that id, revoked or not, however old |
| `/admin/installations?shared=true&limit=500` | The overview: the installations whose id is held by more than one installation that has not been revoked |
| `/admin/status` | The AI Gateway area's overview and the home page's card: what the gateway says of itself ([#64](https://github.com/KnowledgeFabric/kf-admin/issues/64), [Gateway Management](Gateway-Management.md)). Read through `GatewayStatusCache`, once every thirty seconds at most |
| `/admin/installations?<filters>&limit=25&offset=<n>` | The installations list ([#65](https://github.com/KnowledgeFabric/kf-admin/issues/65), [Gateway Management](Gateway-Management.md#the-list)): only the filters the page asks for, built by `Gateway/InstallationQuery.cs` |
| `/admin/installations/<id>` | One installation's page, and a search for an id |
| `/admin/tiers`, `/admin/policy` | The policy page ([#67](https://github.com/KnowledgeFabric/kf-admin/issues/67), [Gateway Management](Gateway-Management.md#policy)): the allowance rows and the gateway levers, on every load, never cached. Their names are in `Gateway/GatewayPolicy.cs` |
| `/admin/installations?app_version_below=<version>&status=active&limit=1` | The policy page: how many active installations the minimum version would refuse, from `X-Total-Count` |
| `/admin/installations?app_version_below=<version>&status=active&limit=500&offset=<n>` | Changing the minimum version (#71): every active installation a new minimum would refuse, walked to the gateway's total, by version |
| `/admin/usage/daily?from=<date>&to=<date>[&installation_id=<id>]` | Usage history ([#70](https://github.com/KnowledgeFabric/kf-admin/issues/70), [Gateway Management](Gateway-Management.md#usage-history)): the fleet's days by row on the overview and the range page, one installation's on its page, zero-filled. Its names are in `Gateway/GatewayUsage.cs` |
| `/admin/usage/summary?from=<date>&to=<date>&limit=<n>` | The range page's totals, by row and top installations; usage by licence's last month |
| `PUT /admin/tiers/<tier>`, `PUT /admin/policy` | Changing policy ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71), [Gateway Management](Gateway-Management.md#changing-policy)), under the write token, with `X-KF-Operator`: a whole row, as written back by the gateway |
| `/admin/installations?row=standard&limit=500&offset=<n>`, and the same for `enterprise` | Usage by licence ([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66), [Gateway Management](Gateway-Management.md#usage-by-licence)): every installation on a licence row, walked to the gateway's total and matched to the register's licences in force by `licence_id` |

From each installation it reads `installation_id`, `app_version`, `tier`, `status`, `created_at`,
`last_seen_at`, `revoked_at` and `licence_id` — `AdminInstallation` in the gateway's
`Admin/AdminEndpoints.cs`, in its snake_case wire names — and, for the installations and usage
pages and a register row's installations, `licence_holders`, `licence` and `allowance` ([Gateway Management](Gateway-Management.md#what-they-read)).
The register's pages count the rows they are given rather than reading `licence_holders`, so a
row's page and the overview agree by construction; one installation's page, which has only its own
row, takes the gateway's count. From the status it reads what
[Gateway Management](Gateway-Management.md#what-it-reads) lists. `Gateway/GatewayInstallation.cs` and
`Gateway/GatewayStatus.cs` hold every wire name the console reads.

**The names are [kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35)'s
and [#38](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/38)'s, deployed on 2026-09-26
exactly as the client asks for them**: `licence_id` on the row, and `licence_id=` and `shared=true`
as the filters (#35); `allowance` on the row, the list's other filters, `sort=`, `offset=` and
`X-Total-Count`, and one installation by id (#38). The gateway's `docs/Admin.md` names kf-admin as
the client that depends on them, and kf-ai-gateway#36 makes `/admin` additive from here on. A change
to either side is a change to `Gateway/`: the request names are in `GatewayAdminClient` and
`InstallationQuery`, and the response names in `GatewayInstallation` and `GatewayStatus`, and
nowhere else.

**A filter is checked, not trusted.** A gateway from before kf-ai-gateway#38 ignores a query
parameter it does not know, so one from before #35 (a local build, or another environment) answers
a licence's request with its newest installations, none carrying a licence id. The client checks
every row against what it asked for, and reports such an answer as a gateway that does not record
licence ids yet rather than a list of strangers. #38's filters, order and page are checked by the
`X-Total-Count` that #38 added: an answer to any of them without it came from a gateway that
ignored them, and the page says the gateway does not filter its installations yet.

**A `400` is the console's bug, not an outage.** Since kf-ai-gateway#38 the gateway refuses a
parameter it does not have, or cannot read, with `400` and
`{"error":"unknown_parameter"|"invalid_parameter","parameter":…,"message":…}`, where an older one
ignored it. The console sends only the parameters a page asks for, never a cache-buster or anything
else, and checks each value first: the one an operator types, an application version, is read as
the gateway reads versions and refused on the page if it is not one. So a `400` means the console
asked something it should not have. It is logged as an error naming the parameter, shown as *The
gateway refused what the console asked* with the gateway's message, and never retried.

**It never throws at a page.** Not configured, unreachable, timed out, `400`, `401`, `404`, a gateway
that predates an endpoint (`404` for `/admin/status` while `/admin/installations` answers, or for
one installation while the list answers without `X-Total-Count`), or an answer that is not what the
console expects: each is an outcome the page states
([License Register](License-Register.md#installations),
[Gateway Management](Gateway-Management.md#when-the-gateway-cannot-answer)), and each but the first
is logged naming the request ([Operations](Operations.md#a-licences-installations-or-the-gateways-status-are-missing)).

**Its writes** ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)) are a `POST` with the
write token, naming the operator in `X-KF-Operator`, which the gateway logs with the change
(kf-ai-gateway#39):

| Request | For |
|---|---|
| `POST /admin/installations/<id>/revoke`, `/restore` | Revoking and restoring an installation, from its page or a register row's shared flag, behind a confirm step ([Gateway Management](Gateway-Management.md#revoke-and-restore)) |

A `403` on a write means the gateway knows the token and does not let it write: the write token
slot holds its read token. It is its own outcome, and the confirm step says so. The console never
retries a write, and writes its audit entry only once the gateway has confirmed one.

## Features are areas, never new projects

The test, stated plainly because it is the entire justification for the rename: **when the second
tool arrives it is an area in the existing application, not a second project in this repository.**

A second project means a second login, a second deploy and a second set of secrets — worse than two
repositories would have been, because it carries the coordination cost of sharing a repository with
none of the benefit. This is an acceptance criterion on
[#15](https://github.com/KnowledgeFabric/kf-admin/issues/15); it is repeated here because it is the
sentence that has to survive the first time it is inconvenient. The second tool arrived with
[#64](https://github.com/KnowledgeFabric/kf-admin/issues/64), as `Areas/Gateway/`, and passed it.
Since [#88](https://github.com/KnowledgeFabric/kf-admin/issues/88) an area also brings a view and a
write role of its own, so that the people who run one need not see another's: one login, and a role
per area granted on the Users page ([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).
The third tool, the CRM, arrived with [#90](https://github.com/KnowledgeFabric/kf-admin/issues/90)
as `Areas/Crm/`, behind the two roles that were waiting for it, and passed the test again.

## What does not belong here

| | Where it goes |
|---|---|
| Customer-facing pages | `kf-landing` |
| Product configuration screens | kf-app. What a licence grants in them is [License Entitlements](License-Entitlements.md) |
| Deployment dashboards | GitHub Actions, already |

## Not settled here

The shell's own decisions — authentication, storage, audit and layout — are
[#15](https://github.com/KnowledgeFabric/kf-admin/issues/15)'s. What that ticket has since settled
is in [Console Shell](Console-Shell.md); the shared-password versus Entra ID question was answered
for now by [#68](https://github.com/KnowledgeFabric/kf-admin/issues/68), a name and a secret per
person without a tenant, and Entra ID stays the end state.
This page does not pre-empt them. It is also deliberately not a roadmap:
candidate admin features were brainstormed only to test whether the name fits, and an aspirational
list of them in a charter would age badly.
</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/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` — the manifest, the worker and the offline page ([Installed as an app](#installed-as-an-app)) |

### 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
controller besides. If a change of scheme ever needs to touch a view, something has leaked out of
that seam and belongs back in it.

### Authorisation is roles per area, held in the database and granted on the Users page

Since [#88](https://github.com/KnowledgeFabric/kf-admin/issues/88), part of the CRM epic
([#87](https://github.com/KnowledgeFabric/kf-admin/issues/87)), a person may do what the roles held
by their name say, and nothing else. It replaced the writers list, `Authentication--Writers`, which
nothing reads any more.

**Seven roles.** `Administrator`, and a view and a write role for each area: `Licensing.View`,
`Licensing.Write`, `Gateway.View`, `Gateway.Write`, `Crm.View`, `Crm.Write` (`Security/ConsoleRoles.cs`;
the pages call them *Licensing: View* and so on). An area's write role includes its view role, and
`Administrator` includes every role and the Users page. The CRM's two exist before the CRM does, so
that its pages ask for them from the day they are written.

**The policies pages ask for** (`Security/ConsolePolicies.cs`), each decided by
`RoleAuthorizationHandler` from the roles the session's name holds:

| Policy | Needs | Asked by |
|---|---|---|
| `console:view` | Any signed-in session, roles or none | The overview and the account pages, and nothing else |
| `licensing:view` | `Licensing.View` or `Licensing.Write` | The register, the validate page, the issue form's page, the overview's licensing section, the menu's Licensing entries |
| `licensing:write` | `Licensing.Write` | Every `POST` of the issue form |
| `gateway:view` | `Gateway.View` or `Gateway.Write` | Every page of the AI Gateway area, its section of the overview and its menu entries |
| `gateway:write` | `Gateway.Write` | Revoke and restore, and every policy change |
| `crm:view`, `crm:write` | `Crm.View` or `Crm.Write`; `Crm.Write` | The CRM area ([#90](https://github.com/KnowledgeFabric/kf-admin/issues/90), [CRM](CRM.md)): the contacts grid, the follow-ups grid ([#92](https://github.com/KnowledgeFabric/kf-admin/issues/92)), a row's details, the confirm step's page and *Export CSV* ([#93](https://github.com/KnowledgeFabric/kf-admin/issues/93)); every cell save, the blank row, and the interactions and next action set from the panel |
| `crm:import` | `Administrator` | The CRM's import, `/Crm/Import` ([#93](https://github.com/KnowledgeFabric/kf-admin/issues/93)): a one-off that writes every contact at once, so not every writer's |
| `crm:delete` | `Administrator` | Deleting a contact, the confirm step's `POST`, and *Deleted contacts* with its *Restore* ([#119](https://github.com/KnowledgeFabric/kf-admin/issues/119)): a delete is soft, and a name once written stays, so not every writer's |
| `console:audit` | Any area's write role | The audit log: the session's own entries, unless it also meets `console:audit-all` |
| `console:audit-all` | `Administrator` | Everyone's entries in the audit log, not just one's own ([#99](https://github.com/KnowledgeFabric/kf-admin/issues/99)) |
| `console:roles` | `Administrator` | The Users page, and granting and revoking on it, and setting a person's initials |

Every policy but `console:view` is also met by `Administrator` and by the name `admin`.

**`admin` holds every role by construction.** The name `admin`, matched as names are (whatever its
case, trimmed), meets every policy with no row: there is no grant to revoke and no page that can
take one away, and the Users page refuses a grant or revoke that names it, whoever sends it. It
signs in like anyone, with `Authentication--Users--admin`, and is the one name that works on the
first start, before any role has been granted. An `Administrator` may do everything `admin` can,
granting `Administrator` to someone else included, except touch `admin`'s own.

**Held in `console_roles`, decided per request.** A row is a name and a role, with who granted it
and when, keyed on the two, the name kept lower-case so the key is case-insensitive in it. It lives
in `kf_admin` beside the register and the audit log, and is migrated at startup like them.
`SessionRoles` reads a session's roles the first time a request asks a policy and keeps them for
the rest of that request, so a role revoked on the Users page stops counting at that person's next
request, with no sign-out and no restart, and nothing about roles is ever written into the cookie.
Where roles are kept is chosen as the register's store is, by `Database:ConnectionString`:

- **Set:** `console_roles`.
- **Not set, in Development:** memory, as the register and the audit log are; this is what the tests
  run on.
- **Not set anywhere else:** nowhere. `admin` still holds every role, nobody else holds any, and the
  Users page says why.

A database that cannot be read is logged at error and read as no roles: the session sees the
overview, which says its roles could not be read, rather than an error page; `admin` is unaffected.

**The Users page**, `/Users` in the menu beside *Audit log*, behind `console:roles`. One row per name:
the names with a secret in `Authentication:Users` (what the sign-in reads), joined to `console_roles`,
with `admin`'s first, saying *every role, by construction*. A name holding roles but with no secret
shows *no secret*: it cannot sign in, and its roles stay until they are revoked; it can be granted
nothing more. A name with a secret and no roles shows *no roles*. Each role is granted or revoked by
the button in its cell, in one step: a role is undone by the button beside it, unlike a revoke on the
gateway. Each change is audited once the store has it, as `console:role-grant` or
`console:role-revoke`, with the name as target and the role in the details; a grant of a role already
held, or a revoke of one that is not, changes nothing and records nothing.

**Initials** ([#115](https://github.com/KnowledgeFabric/kf-admin/issues/115)) are the page's second
column: what the CRM's grid shows for a person, `VS` rather than `vera`, to fit the page as the
sheet's initials did ([CRM](CRM.md#people-by-their-initials)). An Administrator types them beside
the name and saves: one to four letters, kept upper-case, or blank to show the name again. They are
set, not derived, because a name does not yield them. Two people with the same initials are warned
about on both rows (*same as …*), never refused. `admin` has none, being no one (#108), and a set
naming it is refused as a grant is. Each change is audited as `console:initials`, with the name as
target and the new and previous initials in the details; setting what is held records nothing. They
are rows of `console_initials` in `kf_admin`, beside `console_roles`: the name, kept lower-case as a
role's is, the initials, and who set them when. A name keeps its row on the page while it has
initials, even with no secret and no role left, so they can be cleared. Nothing outside `Security/`,
`UsersController` and its view reads them but through `ConsolePeople`.

**What a session sees follows from its roles.** The menu shows only the areas, and the audit log and
Users entries, whose policies the session meets: `_VerticalMenu.cshtml` asks `IAuthorizationService`
the policy each page asks, so it never offers a link that answers 403. Each area is a group that
opens and closes, the template's own `menu-toggle` and `menu-sub` started by `site.js`: the group of
the page being shown is open when it loads, the others closed, and opening one closes the one that
was open, so the menu stays the length of one area however many there are. Each feature's section of the
overview checks its own area's view policy. A session that may view no area, a name with no roles
yet, sees one card instead: who it is signed in as, that it holds no roles,
and to ask an Administrator.

No page or controller outside `Security/`, `UsersController` and its view knows where roles are
held: a page asks a policy by name. **With Entra ID**, a group stands in for each role:
`SessionRoles` reads the token's groups instead of `console_roles`, the Users page goes, and no
policy, page or controller changes.

### Authorisation, audit and storage are seams before they are features

All three grant or do the simplest thing today. They exist anyway, because each is something that
cannot be retrofitted cheaply:

- **Authorisation** — pages ask for a policy by name, never for a role or a list, so the writers
  list (#68) and then the roles per area (#88, [above](#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page))
  each arrived as a change in `Security/` and to which policy a controller names, and in no page's
  logic. kf-app is the counter-example: it has no notion of an administrator and no seam to add one
  to (see #10).
- **Audit** — every mutating action is recorded because `AuditActionFilter` is global, not because
  someone remembered an attribute. An action that knows more than "this ran" writes its own entry
  and marks itself `[SelfAudited]`. Since [#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)
  every entry is a row in `audit_entries`, beside the register in `kf_admin`, as well as the log
  line it always was, and **Audit log** in the menu (`/Audit`) lists them, newest first, filtered by
  action and target. It was the change of registration this page promised
  (`Auditing/AuditRegistration.cs`): no caller of `IAuditLog` changed. Without a database, entries
  are log lines alone and the page says so; in Development without one, they are kept in memory. A
  row the database refuses is logged at error beside its line rather than thrown, so an action that
  has happened is never undone by its audit. An entry written under the shared password, before it
  was retired (#89), that a person named themselves in, a revoke or restore, keeps the typed name
  as `ClaimedActor` and stays unattributable.
- **Feature state** — `IFeatureStateStore` keeps the first feature's choice of store from becoming
  the platform's. The in-memory implementation is honest about surviving nothing. The first
  feature to need durable, queryable state — the register of issued licences,
  [#8](https://github.com/KnowledgeFabric/kf-admin/issues/8) — did not go behind it: it wanted
  search and a uniqueness rule, which this seam deliberately does not offer, so it has its own
  `ILicenceRegister` on PostgreSQL. That is the "decision worth making out loud" the interface
  asks for, and [License Register](License-Register.md) is where it was made. The first state that
  *is* a keyed document, each person's dashboard order ([#135](https://github.com/KnowledgeFabric/kf-admin/issues/135),
  [below](#user-settings)), made the seam durable: with a database, `PostgresFeatureStateStore`
  keeps a row per collection and key in `feature_state`, the value as `jsonb`, migrated with the
  register; without one, memory, and the page that sets it says so (`Storage/FeatureStateRegistration.cs`).
  It is still a document per key with no queries: a feature that wants to search its state wants
  its own table.

### Adding a feature

Add an area. `Areas/<Feature>/Controllers`, `Areas/<Feature>/Views`, and a group in
`Views/Shared/Sections/Menu/_VerticalMenu.cshtml` — which carries the licensing group and, since
[#64](https://github.com/KnowledgeFabric/kf-admin/issues/64), the AI Gateway's, which is exactly
that done a second time: a `menu-toggle` link with the area's name and icon, its pages under it in a
`menu-sub`, open when the page shown is one of the area's. The area route is already mapped. No new project, no new login, no new
pipeline.

Its controllers ask for the area's view policy, and its writes for its write policy; the menu group
sits inside the check of the same view policy. A new area is a view and a write role in
`ConsoleRoles`, two policies in `AddConsoleAuthorization`, and its view policy in
`ConsolePolicies.AreaViews`, which is how the overview tells a session that may see nothing from
one that may see something. The CRM's were there before the CRM was, and `Areas/Crm/` (#90) asks
for them and added nothing to `Security/` but the list of names its records may name.

If the feature has something to say on the overview, it adds a view component, a line to
`OverviewArea.All` (`Preferences/OverviewAreas.cs`: its key, view policy, name and icon) and a case
to the switch in `Views/Home/Index.cshtml` that places it, the way licensing's `LicensingOverview`
is ([License Register](License-Register.md#the-overview)). The component checks its area's view policy
and draws nothing without it. The overview page places each feature's section, in the order each
person chose ([below](#user-settings)); a new one comes last for anyone who chose before it existed.
It does not compute any of them.

### User settings

**User settings** in the menu ([#135](https://github.com/KnowledgeFabric/kf-admin/issues/135)) is
the person's own, for anyone signed in, and holds one page for now: **Dashboard preferences**
(`/Preferences/Dashboard`, `PreferencesController`), the order in which the overview places its
areas. Roberto puts the CRM first, Mark the licences.

- It lists only the areas the person may view, by the same policies the overview asks. Their roles
  decide what the overview shows; this decides only where. A person who may view nothing has
  nothing to order, and the page says so.
- An area is dragged into place, or moved with the arrows beside it, which do the same for a
  keyboard and for a phone, where a drag does not reach (`wwwroot/js/dashboard-preferences.js`, no
  library). Each item carries its own hidden input, so the form posts the order the list has;
  nothing is saved until *Save order*. *Back to the default order* forgets it.
- What is kept is a list of area codes, `licensing`, `gateway`, `crm`, never a translated name, per
  person by name as `ConsoleRoles.Normalise` has it, `admin` included, in the collection
  `dashboard-order` (`Preferences/DashboardPreferences.cs`). An area the list leaves out follows the
  ones it names in the default order: an area granted later, or added to the console later, comes
  last until it is placed. An area the person cannot see stays in their order, after the ones they
  placed, for the day they are granted it. A code that is no area is refused with `400`.
- A save that changes the order, and a reset that forgets one, is audited `console:dashboard`,
  targeting the person, with the order and the one it replaced as codes, or `default`. Saving the
  order already held writes nothing.
- An order that cannot be read is the default order, logged rather than thrown: the overview is
  the page every sign-in lands on.

### Installed as an app

The console is a progressive web app ([#166](https://github.com/KnowledgeFabric/kf-admin/issues/166)):
Chrome on Android and on a desktop offers to install it, Safari on an iPhone adds it to the home
screen from the share sheet, and installed it opens under the KnowledgeFabric mark, in its own
window, on the overview, and signs in once per session as a desktop tab does. Nothing the console
shows or does changes with it: the roles, the policies and every page are the same, and a browser
without service workers simply does not install it.

- **The manifest**, `wwwroot/manifest.webmanifest`, is a static file linked from the common
  layout, served by the static-files middleware ahead of authentication so that a browser can read
  it before anyone signs in, and it says nothing a signed-out caller may not see: the console's
  name and short name (`ConsoleBranding.AppName` and `ShortName`, which the test holds it equal to),
  the mark's blue as `theme_color`, and the icons. Its URLs are relative, so it is right under a
  path base too, and its own URL carries no version: an installed copy is tied to it.
- **The icons**, `wwwroot/img/icons/`, are the mark at 192 and 512 pixels on white, a maskable one
  in white on the mark's blue for Android launchers, and the 180-pixel `apple-touch-icon` the
  layout links for Safari, which reads that and the Apple metas rather than the manifest. They were
  traced from `img/logo/kf-logo-icon-bg-transparent.png` (124 pixels, which no icon can be scaled
  from) and are tracked images, not build output.
- **The service worker**, `wwwroot/sw.js`, is registered by `site.js` from the application root
  (`data-assets-path`, so its scope is the whole console) and **caches two things and nothing
  else**: the static assets the layout links with a version hash (`?v=`, under `vendor/`, `css/`,
  `js/`, `img/` and the favicon), cache first, and the offline page. Every other request goes to
  the network untouched: every page, every `POST`, every export, everything under `/Crm`, `/Audit`
  and `/Gateway`. The console shows personal data ([CRM](CRM.md), #87 decision 9) and live gateway
  state, and a CRM write carries a row version that is refused when it has moved, so a page served
  from a cache would be a page that lies and an edit queued for later one merged silently: no
  page or response is ever written to the phone's cache storage, and nothing is queued offline.
- **A deploy needs no change to the worker.** Each asset's new hash misses the cache and its old
  entry falls out of use; the worker's own file is fetched by the browser on its usual schedule.
  Change its cache name only when what it caches changes, which empties every installed copy's.
- **The offline page**, `/offline` (`OfflineController`, `Views/Offline/Index.cshtml`), is what the
  worker answers a page request with when the network is gone. It is anonymous, says only that the
  console cannot be reached, and carries no stylesheet, script or image file: when it is shown,
  nothing else can be fetched. It is a Razor view so that its words live in the one shared
  resource ([Localisation](Localisation.md)); the worker fetches it when it installs and again after
  each page the server answers, so the copy it holds is in the language the person last read the
  console in. `Cache-Control: no-store`, so the browser's own cache keeps no second copy.
- **Installing it**, step by step on Android, an iPhone and a desktop, is
  [Installing on a Phone](Installing-On-A-Phone.md).
- **Trying it**: Chrome's Lighthouse audit and its *Application* panel (manifest, service worker,
  cache storage) cover Android and a desktop; an iPhone needs a device or the Simulator, through
  Safari's share sheet. Airplane mode after a visit shows the offline page; the cache storage
  afterwards holds hashed assets and `/offline` and nothing else. `InstallableAppTests` checks what
  can be checked in process: the manifest, the icons at the sizes it names, the worker, the offline
  page in both languages and without dependencies, and the head of every page.

## The Vuexy template

The UI is [Vuexy](https://themeforest.net/item/vuexy-vuejs-html-laravel-admin-dashboard-template/23328599)
(PixInvent), the same commercial template kf-app uses, taken from kf-app's copy rather than from a
fresh download. It was treated as the same end product as kf-app, under kf-app's existing licence —
the decision is recorded on
[#15](https://github.com/KnowledgeFabric/kf-admin/issues/15#issuecomment-5781201697). The purchase
code is **not** copied into this repository; kf-app keeps it in a tracked file, which is not a
pattern to repeat here.

What was copied is a subset: the shell's own layouts, `src/scss/`, `src/libs/` (the template's lib
theming mixins) and the vendor assets the layout actually loads — jQuery, Popper, Bootstrap,
perfect-scrollbar, node-waves, hammer, typeahead, the Tabler icon font, and ApexCharts for the
overview's charts ([#37](https://github.com/KnowledgeFabric/kf-admin/issues/37)), and, since
[#90](https://github.com/KnowledgeFabric/kf-admin/issues/90), DataTables with its FixedHeader
extension for the CRM's contacts grid. kf-app's full `wwwroot/vendor/` is 40 MB; this is about
5 MB. A feature that needs select2 copies it across the same way and finds it already themed.

DataTables is how that copying went the first time something needed it. The library came from npm
rather than from kf-app's bundle, as ApexCharts did: `datatables.net-bs5` 1.13.11 and
`datatables.net-fixedheader-bs5` 3.4.0 (all MIT), pinned in `package.json` **with their cores,
`datatables.net` 1.13.11 and `datatables.net-fixedheader` 3.4.0, pinned beside them**: the
wrappers' own ranges are open at the top, and without the pins npm resolves a FixedHeader that
refuses to load against DataTables 1.13. They are bundled by `npm run build:vendor`
(`build-vendor.js`) into `wwwroot/vendor/libs/datatables-bs5/` and `datatables-fixedheader-bs5/`,
which are tracked. The template's styles for them were already here, in
`src/libs/datatables-bs5/` and `src/libs/datatables-fixedheader-bs5/`, themed against the console's
palette, and `npm run build:css` compiles them beside the others. Nothing of kf-app's DataTables
bundle, which drags in buttons, PDF export and checkboxes, was needed. The 1.13 line rather than
2.x, because the template's styles are written against its class names.

ApexCharts is `apexcharts-clevision` 3.28.5, PixInvent's MIT-licensed fork, and the package the
template's own `src/libs/apex-charts/` styles are written against. Upstream ApexCharts left the MIT
licence at 5.1.0, so do not swap in a current upstream package. It comes from npm rather than
from kf-app, and `npm run build:vendor` copies it into `wwwroot/vendor/libs/apex-charts/`. On the
overview, where more than one section draws charts, a section loads it through
`Views/Shared/_ApexCharts.cshtml`, which writes the library's tags once a request whichever
section asks first ([#158](https://github.com/KnowledgeFabric/kf-admin/issues/158)), and places its
own script after the partial.

jsQR is `jsqr` 1.4.0 (Apache-2.0), which decodes a QR code on a business card's photo where the
browser has no barcode detector of its own
([#163](https://github.com/KnowledgeFabric/kf-admin/issues/163)). It is not the template's, and has
no styles. `npm run build:vendor` copies its one build, unminified because the package ships no
other, with its licence into `wwwroot/vendor/libs/jsqr/`; only the business card page loads it.

What was deliberately left behind: kf-app's product navigation, its AI chat widget, its per-page
SCSS, and the template customizer. The customizer is a theme switcher for people evaluating the
template, and leaving it on lets a value in one browser's local storage change how the console
renders for that person alone — which is how kf-app ended up pinned to a narrow column by a setting
nobody could see (kf-app#911). The layout decides how the console looks, in markup, for everyone.

### The colour scheme

The KnowledgeFabric mark's blue, `#2c7be5`, not the product's purple. kf-app and this console are
routinely open side by side, and an admin tool that looks identical to the product is how someone
ends up doing the wrong thing in the wrong tab. It was deep teal, `#0f766e`, until the console took
the KnowledgeFabric mark as its favicon and the chrome moved to match it.

The favicon and the brand mark in the menu and on the sign-in page are kf-app's own
(`wwwroot/img/favicon/`, `wwwroot/favicon.ico` and `wwwroot/img/logo/`, copied from kf-app's
`wwwroot/img/favicon/` and `img/logo/` at `f881e3e`), so the two tabs carry the same icon and are
told apart by their titles and their chrome.

The palette lives in **three** places, and they have to move together:

| | File | Used by |
|---|---|---|
| SCSS | `src/scss/_custom-variables/_bootstrap-extended.scss` (`$primary`) | everything sass compiles — `core.css` and the theme |
| SCSS | `src/scss/theme-kfadmin.scss` (`$primary-color`) | the theme's own mixins — menu, navbar, footer |
| JS | `wwwroot/js/config.js` (`window.config.colors`) | anything that draws colours in script — charts, widgets |

Change one without the others and the chrome moves while the charts stay behind. The primary colour
is compiled into `core.css`, not only into the theme file, so recolouring is a rebuild rather than
an edit.

The installed app's chrome (#166) reads the same blue from a fourth place, `ConsoleBranding.ThemeColour`,
which the layout writes as the `theme-color` meta and the offline page draws with, and from the
manifest's `theme_color`. `InstallableAppTests` holds the manifest and the three files above to
that constant, so a palette change that forgets one fails the build rather than the look.

### Rebuilding the stylesheets

`wwwroot/vendor/css/*.css` and `wwwroot/css/site.css` are **build output** and are tracked, as
kf-app tracks them, so a deploy needs no Node step. Never edit them by hand:

```bash
cd src/KnowledgeFabric.AdminConsole
npm install
npm run build:css
```

Only `sass`, `bootstrap`, `apexcharts-clevision`, the four DataTables packages and `jsqr` are needed — not
kf-app's hundred-package gulp pipeline. `build:css` also compiles the template's ApexCharts and
DataTables styles. The chart and table scripts themselves are copied, not compiled, and are tracked
the same way. Refresh them with `npm run build:vendor` after changing a package's version. Custom
application CSS goes in `src/site.scss`, never inline in a `.cshtml`, following kf-app's convention.

## Acceptance, as checked

Against #15's acceptance criteria, on the running application:

- Without the credential, `/` and every unknown path redirect to `/account/login`; `/health` and
  the login page do not. Unmatched paths redirect rather than 404 for an anonymous caller, because
  the fallback policy applies to requests with no endpoint too — an anonymous caller does not get
  to learn which paths exist. Signed in, an unknown path renders the 404 page.
- `/health` returns 200 on a cold start with no configuration at all — no Key Vault URI, no
  Application Insights connection string, not even a password.
- Swapping the authentication scheme touches `Security/` and `AccountController`, and no page.
- Adding a feature means adding an area.
- Against #88's: `admin`, with an empty `console_roles`, sees every area, the audit log and the
  Users page; a name with `Licensing.Write` and `Gateway.View` issues a licence and lists the
  gateway's installations, and is refused every policy change; a name with `Crm.Write` alone sees
  no licensing or gateway entry in the menu and is refused `/Licensing/Register`. `admin` revoking
  the second's `Licensing.Write` refuses their next issue `POST` with no sign-out, and the audit
  log holds `console:role-revoke` with `admin` as actor (`RolesTests`). The migration, a grant, a
  repeated grant, a revoke and a refused grant to `admin` were also run by hand against PostgreSQL 16.
- Against #99's: a `Gateway.Write` name's audit log lists its own entries and none of anyone else's,
  whatever the query string asks, and its action filter names only its own actions; `admin` and an
  `Administrator` list everyone's; the name is matched whatever its case, so `GUS`, ` Gus ` and `gus`
  are one person's; and an Administrator who revokes their own `Administrator` sees their own alone at
  the next request (`AuditLogTests`). The PostgreSQL filter is `lower(btrim(actor))`, read from the
  query EF generates, not run against a server.
- Against #135's: the overview places its areas in the default order until a person saves another
  on Dashboard preferences, and in theirs from the next load; each person's is their own; a name
  with `Licensing.View` and `Crm.View` is offered those two and not the gateway, and when granted
  `Gateway.View` later finds it last on both pages; a name with no role has the page and nothing to
  order; a code that is no area is `400`; an order that cannot be read leaves the overview in the
  default order and a save says it changed nothing (`DashboardPreferencesTests`). The migration, a
  save, an overwrite, a restart that keeps the order and a reset were also run by hand against
  PostgreSQL 16, and the arrows and the drag in Chromium.
- Against #166's: signed out, the manifest, the worker, each icon and `/offline` answer `200`
  with their content types and no redirect to sign-in; the manifest names the console and icons
  that exist at the sizes it says; the offline page is in English, and in Italian once the switcher
  is used, with no stylesheet, script or image; and the sign-in page and the overview carry the
  manifest link, the theme colour and the touch icon (`InstallableAppTests`). In Chromium, against
  the console run in Development: the worker registers at the root and activates, after the
  Partnerships and Audit pages the one cache holds hashed assets under `vendor/`, `css/`, `js/`
  and `img/` and `/offline` and nothing else, a page asked for offline is the offline page, and
  after the switch to Italian and one page it is the Italian one. Android, an iPhone and the
  Lighthouse audit are the pull request's manual tests.
</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 `Crm--BusinessCards--ApiKey` in Key Vault ([Provisioning](Provisioning.md#the-business-card-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
colours are in `src/site.scss`, and nothing stored, filtered, exported or audited moves.

**Frozen header.** The header row stays in view as the page scrolls, as the sheet's freeze pane
did (its pane is A2): DataTables' FixedHeader, offset by the console's own navbar. The table says
so with `data-frozen-header`, not `data-fixed-header`: DataTables reads a table's `data-*`
attributes as options, over the script's, and took that one as `fixedHeader: true` with no offset,
which left the headings under the navbar until #113.

**It fits the page** ([#113](https://github.com/KnowledgeFabric/kf-admin/issues/113)) at about
1500 pixels and wider, in either language and with a classic scrollbar taking its 17 pixels: about
1100 pixels at its narrowest in English, 1125 in Italian. Until *Presentation* (#126) it fitted at
1366, about 990 and 1010 against a card of about 1010; the column, heading and sort arrows, is about
105 pixels more in English and 115 in Italian, which no other column had to give, so the team chose
to let the grid scroll inside its card at 1366 rather than shorten the heading or drop its sort.
It gets there with narrow gutters between columns, small minimum widths that the cells' own words
outgrow, filters as wide as their column, the
headings in the sheet's case rather than the template's capitals (*COINVOLGIMENTO* set its column's
width), *Met?*'s lines wrapping when the column is at its narrowest (*With?*'s, a few initials, never
do), and a word in *Notes* longer than the column, a pasted link, breaking rather than widening the
grid. Narrower than that, the grid scrolls sideways inside its card, never the page: DataTables'
`scrollX`, which FixedHeader follows, so the frozen header scrolls with the columns. `scrollX` draws
the headings as a table of their own, sized to the body's columns, so the script sizes them again
whenever the body's cells change (a save, an editor, a new row, a panel), and `autoWidth` stays on,
since without it FixedHeader clears those sizes each time the header docks. The widths are in
`src/site.scss`; a column added, or a heading or a filter's first choice made longer, is checked
against those numbers again in both languages.

**Current activity and Notes fold** ([#114](https://github.com/KnowledgeFabric/kf-admin/issues/114)),
since a pasted LinkedIn headline or a long note made the whole row tall: *Current activity* to its
first two lines and *Notes* to its first three, each ending in an ellipsis when cut. The whole text
is on hover (the cell's `title`), and a small *more* (*altro*) beneath a cut cell unfolds it in place,
*less* (*meno*) folding it again; the script shows the toggle only when the text is cut, measured
again as the columns change width. The toggle is a button, so it never opens the editor, and the
editor starts from the whole text without it. A cell saved is drawn folded. Only what is shown
changes: the cell sorts, and the search matches, by the whole text, and nothing stored, exported or
audited moves. The row's details show the current activity in full in their header.

**Sort by heading.** Click a heading to sort by it, again for the other way, as DataTables sorts:
among the rows on the page, which are all of them. A stage sorts in the order above, not
alphabetically; *Engagement Level* by number, with blanks first; *Met?* by the day of the latest interaction, so
the contact nobody has spoken to for longest comes first and one never contacted before every
other; the rest by text whatever its case. *With?* does not sort. The rows arrive by name, whatever
its case.

**A filter per column**, under the headings, as the sheet's autofilter: *Name* by [individual or
company](#individual-or-company), *By* by name, *Engagement Level* by "this warm or warmer" (`3+`),
*Met?* by *not contacted since*, and *Kind of partnership* and *Stage* by value. A choice reloads the
grid with the filter in the query string
(`?stage=Met&track=Ambassador&by=vera&e=3&since=Month&entity=Company`), so a filtered grid can be
linked to, which the [overview](#the-overview) does, and the filters combine. A value the console
does not know narrows nothing.

**Not contacted since** is the question the sheet could not answer: *Not in a week*, *Not in a
month*, *Not in 3 months* (`since=Week`, `Month`, `ThreeMonths`) keep the contacts with no
interaction on or after the day that long before the console's today, in UTC, those never
contacted included; *Never* (`since=Ever`) keeps only those with none at all. On PostgreSQL it is a
`NOT EXISTS` on `crm_interactions`, which the index on (`contact_id`, `occurred_on`) serves.

**The search box**, above the grid, matches any part of the name, the current activity, the
organisation or the presentation (`t51` finds every contact shown T51), ignoring case, as the register's does; on PostgreSQL `%` and `_` match themselves. It
keeps the column filters, and *Clear* drops everything.

**A name held by two contacts** is warned about, on both rows, and never refused: two people can
share a name.

## Editing in place

Click a cell to edit it. *Name*, *Current activity*, *Presentation* and *Notes* open as text: Enter or leaving the
cell saves, Escape cancels. *By*, *Engagement Level*, *Kind of partnership* and *Stage*, and the
details' *Individual or company* and *Why declined*, open as dropdowns, saved on choice (*E* was already a dropdown in the sheet, by data validation). A cell left as it was writes
nothing. A folded cell's editor holds its whole text, and its *more* is not a click on the cell.

**Each save is one request**, `POST /Crm/Contacts/{id}/Cell`, with the field, the value typed, the
row version the grid loaded and the page's anti-forgery token, through the same `IContactRegister` a
form would use. The value is checked before anything is written, as the gateway's policy form is
(`Areas/Crm/Models/ContactEdit.cs`): a name is required, *By* must be a name the dropdown offers, an
engagement is 1 to 5, a LinkedIn address starts with `https://`, and each text has the width of its
column. The request answers JSON with the row's every cell and its new version, and the script
(`wwwroot/js/crm-contacts.js`) redraws the row from it: the cell, its sort key, the *same name*
warning, and, on the details page, the header and the record card too.

| The answer | Means | The cell |
|---|---|---|
| `200` | Saved, under your name | Redrawn, and flashes |
| `400` with why | Refused: the value is not one the column takes. Nothing written | Keeps the editor, with why under it; fix it, or leave with Escape |
| `409` with the row and who | **Stale**: a colleague saved this contact after you loaded it. Nothing of yours written | Shows the colleague's value and who saved it when, with what you typed beside it to copy. The row now carries their version, so typing again saves |
| `404` | A colleague deleted the contact. Nothing written | The row is struck through, and the page says to reload |
| `403` | Your session no longer holds *CRM: Write*. Nothing written | The page says so |

**Nobody overwrites anybody** (#87, principle 5). The row version is PostgreSQL's own `xmin`, which
every write to a row moves: the grid carries it on each row, each save sends it, and the `UPDATE`
puts it in its `WHERE`, so a save over a colleague's later change finds no row to update and is
refused with the row as it is now. Two people editing different cells of one contact still
conflict: the version is the row's, not the cell's, and the second is shown the first's row and
types again. That is the cost of never merging silently, and it is a cost the sheet made the team
pay the other way round. A conflict between two cells of different contacts cannot happen.
[Interactions](#interactions) are rows of their own, so logging a call never conflicts with a cell,
and never makes a colleague's open cell stale.

**The blank row.** The grid's first row is blank, directly under the headings and filters, and it
stays first whatever the order ([#116](https://github.com/KnowledgeFabric/kf-admin/issues/116)):
the sheet's was its last, which with dozens of contacts meant scrolling to the end to add one. Type a
name and leave the cell: `POST /Crm/Contacts` creates the contact, with *By* the signed-in name
(chosen in the row, [for `admin`](#admin-is-no-one)), *Stage* *To contact* and *Kind of partnership*
*Undecided*, the row is filled from the answer and moved into the grid **directly beneath the blank
row**, not where the order would put it, so its other cells can be filled at once, and a fresh blank
row takes its place. It takes its place in the order at the next sort or reload. The other cells of
the blank row cannot be typed into before the name is. It is a `<tbody>` of its own, above the one
DataTables sorts: DataTables sorts only a table's first body, so the script takes the blank row's out
while DataTables starts and puts it back above.

**A `crm:view` session** gets the same grid, read-only: no editors, no blank row, and `403` from
every write.

### `admin` is no one

[#108](https://github.com/KnowledgeFabric/kf-admin/issues/108). `admin` holds every role, so it
reads and writes the CRM as *CRM: Write* does, creating and editing contacts and logging calls, but
it is the console's own name, not a person's, and a record names people: *By*, who took part in an
interaction, a next action's owner. It never met anyone. So:

- **No list offers it**: not *By*, not the panel's names, not a next action's owner, not the
  follow-ups' owner filter. Neither does the fallback when the role store cannot be read.
- **Nothing starts at it.** Signed in as `admin`, the add form ticks no one and a next action's owner
  starts blank, so a call is logged only once someone is chosen.
- **Typing it is refused**, whatever its case, with *admin is not a person*: a cell, a form, an
  import line.
- **Its blank row asks who brought them in.** A new contact's *By* is who is signed in, so for
  `admin` the row's *By* is a dropdown, *Who brought them in?*, chosen before the name is typed and
  sent with it as `by`; without one the create is refused. `admin` is still who created it. Anyone
  else's create ignores a `by` it sends.
- **A record that already names it keeps it**, as one naming someone who has since lost their CRM
  role does: an edit carries it through, and the form keeps it ticked or choosable until it is
  changed.

The audit trail, *Recorded by* and *saved by* still say `admin` when it was `admin`: those say who
did a thing, not who a record is about. The rule is `ConsolePeople.IsPerson`, in
`Security/ConsolePeople.cs`, and nowhere else. **`admin` has no initials** either
([below](#people-by-their-initials)): the Users page offers none for it and refuses a set naming it,
and initials stored for it some other way are never shown.

### People by their initials

[#115](https://github.com/KnowledgeFabric/kf-admin/issues/115), from the team's review: the sheet
wrote *VS*, *MM*, *RR*, and the grid fits the page better for it. #87's decision 5 stands, so this
changes **only what a cell shows**. What is stored, filtered on, exported and audited is the console
name.

- **Each person's initials are set by an Administrator** on the [Users page](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page),
  beside their roles: one to four letters, kept upper-case. They cannot be derived (`vera` does not
  yield *VS*). A person with none is shown by name, as before #115.
- **A cell shows the initials, with the name on hover**: *By*, each name on a *With?* line, and a
  next action's owner on *With?*'s last line, on Partnerships, Follow-ups and a row's details alike.
  *By* sorts by what it shows.
- **A choice names both**, so that choosing is unambiguous: *By*'s dropdown and filter, the blank
  row's *Who brought them in?*, the panel's checkboxes and a next action's owner, and the follow-ups'
  owner filter offer `VS — vera`, or the name for someone with none. Each sends the name: `?by=vera`,
  `?owner=rob`, a cell save's `value=vera`. Typing `VS` where a name is asked for is refused, as any
  other name nobody holds.
- **Everything else keeps the name**: the record, the audit log, the export, the panel's own lines
  (*with rob, vera*, *for rob*) and the import's preview.
- **Two people with the same initials** are warned about on the Users page, not refused; the grid
  tells them apart only on hover.

The initials are read through `Security/ConsolePeople.cs`, still the one place outside `Security/`
that knows who the people are, and written only by `UsersController`. When they cannot be read, the
grid shows names and the error is logged.

## From a business card

[#161](https://github.com/KnowledgeFabric/kf-admin/issues/161). **From a business card**, above the
grid beside *Export CSV*, opens `/Crm/Contacts/Card`: *Take a photo*, which opens the camera on a
phone, or *Choose a photo*. The photo is sent as soon as it is chosen, a vision model reads it, and
the page shows **the photo beside a form filled with what was read**: *Name*, *Current activity*
(the card's title), *Organisation*, *Email*, *Phone*, *LinkedIn* and *Notes*, which start with the
card's website and address, a line each, since neither is a field of the contact. **Reading writes
nothing.** The person checks each field against the card, corrects it, and saves, *Add the contact*;
only then is the contact made, and the page goes to its details.

- **The save is the blank row's**, with more cells filled: each field is checked as its cell is
  (`ContactEdit`), so an email without an `@` or a LinkedIn address without `https://` is refused
  under its field and nothing is written, and the contact starts at *To contact* and *Undecided*
  with *By* whoever saves it. `admin` is asked who brought them in, as its blank row asks
  ([`admin` is no one](#admin-is-no-one)); anyone else's form has no *By*, and one sent is ignored.
  It is audited `crm:contact-create`, as the blank row's is, with `from` `card`.
- **A name already in the CRM is warned about, never refused**, with a link to each contact holding
  it, as the grid warns of a [same name](#the-grid).
- **The cards are English and Italian, and nothing is translated.** Every field is read as printed,
  in the card's language, *Responsabile Commerciale* included, but the name, which the model gives
  given name first, in normal capitalisation and without a title: Italian cards print *Ing. Mario
  Rossi* or *ROSSI Mario*, and either read as printed would neither look like the CRM's names nor
  find the contact already holding it. The console's own language changes nothing of the reading.
- **The reading can be wrong, and the page says so.** The model is told to return only what is
  printed, never to guess, and an empty field where the card shows nothing; a LinkedIn address
  printed without its scheme is given `https://`, and anything else in that field is dropped. When
  the reading fails, or finds nothing, the form opens empty beside the photo, to be typed in from
  it, and the page says why ([Operations](Operations.md#a-business-card-is-not-read)).
- **The photo is a JPEG of at most 2,000 pixels a side** by the time it is sent: the page's script
  draws it on a canvas first, which makes a phone's several megabytes a few hundred kilobytes and
  an iPhone's HEIC a JPEG. Without the script the photo goes as taken; a JPEG or PNG of up to 10 MB
  is read, and anything else refused before it is sent.

**Where it is read.** Ollama Cloud's `/api/chat`, with an Ollama key of the console's own,
`Crm--BusinessCards--ApiKey` ([Provisioning](Provisioning.md#the-business-card-key)), and the model
in `Crm:BusinessCards:Model`, `gemma4:31b` until Ollama retires it, with the fields asked for as a
JSON schema in `format` (`Crm/BusinessCardReader.cs`). Not through kf-ai-gateway, though it fronts
Ollama too: the gateway serves one model behind its `knowledge-fabric-ai` alias, advertised without
`vision` and never named to its callers, to installations enrolled with a licence, and the console
is neither. Going through it would mean enrolling the console as an installation, and a change to
the gateway's contract with kf-app for an internal tool. The reader is an interface,
`IBusinessCardReader`, should that change.

**The photo is kept nowhere.** It is read from the request, sent to Ollama, shown back in the page
as a `data:` address, and dropped with the request: not in the database, not in a log line, not in
an audit entry, and not carried in the form, so a save refused for a field shows the form again
without it. Sending it is audited, `crm:card-read`, with the model and how the reading went, and
nothing of the card ([Audit](#audit)). A view-only session is refused the page, as it is every write.

### A QR code on the card

[#163](https://github.com/KnowledgeFabric/kf-admin/issues/163). **A QR code on the card is read with
it, and a link in one is followed.** The page's script looks for one on the canvas it shrinks the
photo on, with the browser's own barcode detector where it has one (Chrome on Android, macOS) and
with [jsQR](https://github.com/cozmo/jsQR) where it does not (iOS, Firefox, Chrome on Windows), and
sends what it says with the photo as `qr`. The model is then given it beside the photo
(`Crm/BusinessCardQr.cs`):

- **Text, a vCard most often, as it is.** The model reads the fields from it as it reads the card.
- **A link, with what its page says.** The console opens it (`Crm/LinkedPageReader.cs`) and gives
  the model the page as plain text: its title, the meta tags that describe a person or a business
  (`og:`, `profile:`, `description`), its structured data (JSON-LD), its `mailto:`, `tel:` and
  LinkedIn links, and its words without markup, at most 8,000 characters of it. A vCard or plain
  text behind the link is given as it is. A page drawn entirely by its own script says little:
  only its title and meta tags.

**What is printed comes first.** The model is told to take a field from the QR code only where the
card does not show it, and only when it is about the person on the card or their organisation, so a
link to a company's team page fills the website and not someone else's email. The QR code and its
page are data, not instructions, as the card is. **A LinkedIn profile in the QR code is the
contact's *LinkedIn*** when the card prints none, made `https://` and without the query a code
generator adds: LinkedIn shows a signed-out visitor nothing, so its page cannot say it. The form
says what came of the QR code above the photo, with its link as text, never as a link, and
everything in it is checked and saved as before.

**A link is followed to a public web page, and nowhere else.** A QR code is anyone's to print, and
the console sits beside its database, Key Vault and the platform's metadata endpoints, so:

- `http` or `https` only, on the default port, with no user name in it;
- every address the name resolves to must be public: not loopback, private, link-local (the
  metadata endpoints are `169.254.169.254`), carrier-grade NAT, multicast, reserved or
  documentation ranges, nor Azure's platform address `168.63.129.16`, and an IPv4 address carried
  in an IPv6 one is held to the same. The check is made as the connection is made, against what the
  name resolved to then, and the connection is to exactly those addresses
  (`Crm/PublicAddress.cs`), so a name that resolves elsewhere a second time gains nothing;
- redirects are followed by the console, at most five, each checked again;
- no proxy, cookie, credential or tracing header; ten seconds for the whole of it, redirects
  included; at most 512 KB of the answer read; and only a web page, a vCard or plain text read.

A link that fails any of these is not followed, and the card is read without it; the page says why
([Operations](Operations.md#a-business-cards-qr-code-is-not-followed)).

**A QR code is kept nowhere, as the photo is.** Its link can name a person
(`linkedin.com/in/ada-lovelace`), so neither it nor the page reaches a log line, the HTTP client
factory's own lines included, or Application Insights, which is told not to record the requests at
all. `crm:card-read` says only whether there was one, `qr` `link`, `text` or `none`, and how
following a link went, `link` ([Audit](#audit)). What the page says goes to Ollama beside the
photo, and opening the link tells its site that someone did, from the console's address.

Without the page's script there is no QR code: the photo goes as taken, and is read alone.

## Interactions

The sheet's *Met?* held a log, a status and a to-do in one cell, in the order they were typed
rather than by date ([#87](https://github.com/KnowledgeFabric/kf-admin/issues/87)). The log is now a
row per interaction ([#91](https://github.com/KnowledgeFabric/kf-admin/issues/91)): the day it
happened, since the sheet recorded days, not times; what kind it was, *Call*, *In person*,
*Message*, *Email* or *Event*; who from KnowledgeFabric took part, one or more of the names *By*
offers (#87, decision 5); and what was said, which is required. The status is the *Stage*; the to-do
is the [next action](#the-next-action).

**In the grid** *Met?* shows a line per interaction, by day, oldest first, as the sheet wrote them:
the kind and the day in the sheet's `dd.mm.yy`, which is the date format the team reads (`Call
23.09.26`, `In person 02.10.26`, `Event 12.09.26`). *With?* shows who took part in each, on the same
line (`rob, vera`). Neither is typed into.

**The panel.** A click on either cell, or Enter on it, opens the row's panel beneath it, DataTables'
child row, read from the console as it opens; a second click closes it. It starts with the
[next action](#the-next-action), then lists the interactions, each with its summary and who recorded
it when, and for a `crm:write` session *Edit* and *Delete* on each and a form to log one, starting at
today, *Call* and the signed-in name (no one, [for `admin`](#admin-is-no-one)), with what follows it beneath, [asked every time](#the-next-action) and saved in the same submit.
The next action's [*Done*](#done) sends the same request at once, as that action done.
A day after tomorrow is refused, because a planned meeting is a next action until it has happened; tomorrow is taken
because the console's today is UTC's and the team's is ahead of it. A day before 2000 is a mistyped
year. On the row's details the same panel is drawn in place, and a click on either cell goes to it.

| Request | |
|---|---|
| `GET /Crm/Contacts/{id}/Interactions` | The panel |
| `POST /Crm/Contacts/{id}/Interactions` | Log one: `occurredOn` (`yyyy-MM-dd`), `kind`, `participants` (one or more), `summary`; and, from the panel's form, `contactVersion` with the [next action](#the-next-action)'s three fields, and `nextActionChoice` (`clear` or `keep`) when they are left empty, or `done` from [*Done*](#done) |
| `POST /Crm/Contacts/{id}/NextAction` | Set, change or clear the next action: `nextAction`, `nextActionOwner`, `nextActionDue` and the contact's `version` the panel was drawn at |
| `POST /Crm/Contacts/{id}/Interactions/{interaction}` | Edit one: the same, and the `version` the panel was drawn at |
| `POST /Crm/Contacts/{id}/Interactions/{interaction}/Delete` | Delete one: the `version` the panel was drawn at |

Each answers the panel drawn again, as HTML, with the row's two cells in it, and the script
(`wwwroot/js/crm-contacts.js`) replaces the panel and redraws *Met?* and *With?* from that one
answer, without a reload. The form is checked before anything is written
(`Areas/Crm/Models/InteractionPanel.cs`), as a cell's value is.

| The answer | Means | The panel |
|---|---|---|
| `200` | Done, under your name | Redrawn, and the row's two cells flash |
| `400` | Refused: the form says why. Nothing written | The form shown again, with what you typed |
| `409` on an edit | **Stale**: a colleague edited it after the panel was drawn. Nothing of yours written | Theirs is shown, with your form open beside it, holding what you typed and now at their version: save it to replace theirs, knowingly, or cancel |
| `409` on an edit | A colleague deleted it. Nothing written | What you typed is moved to the add form, to log again if it should stay |
| `409` on a delete | A colleague edited it after the panel was drawn. Nothing deleted | It is shown as it is now: delete it again if it should still go |
| `200` on a delete | A colleague had already deleted it: the outcome asked for. Nothing recorded | Redrawn, saying so |
| `404`, JSON | The contact has been deleted | The row is struck through, as for a cell |
| `403` | Your session no longer holds *CRM: Write* | The page says so |

**An interaction never touches the contact row**: it is a row of its own. The next action logged
with it is the contact's, so since [#111](https://github.com/KnowledgeFabric/kf-admin/issues/111)
a logged call usually writes the contact too, setting or clearing what follows, and can be refused
as stale after a colleague's cell save ([below](#the-next-action)); one logged with the next action
kept, or already what the form says, does not. An interaction has its own row version,
its `xmin`, and an edit or a delete is checked against it as a cell save is checked against the
contact's: nothing is ever merged silently. On PostgreSQL the insert's foreign key locks the contact
row against a delete for the moment of the insert, and a row's locks are kept in its `xmax`, not its
`xmin`: the contact's version stays where it was, which was checked on PostgreSQL 16.

**A `crm:view` session** sees the lines and the panel, with no form and no *Edit* or *Delete*, and
`403` from every write.

## The next action

The sheet's to-dos were written after the calls in *Met?*: `DA CONTATTARE`, `IN ATTESA DI RISP`,
`FIX a meeting`, `Da risentire post email`, with no owner, no date and no page that listed them. The
*Stage* says where a contact stands; the next action says what is to be done next, by whom and by
when ([#92](https://github.com/KnowledgeFabric/kf-admin/issues/92)). **One per contact**, by design,
so it is three columns of the contact, not a table: its text, its owner (a console user, one of the
names *By* offers) and its due date, optional together.

**In the grid** it is the last line of *Met?*, after the interactions, as the sheet put `FIX a
meeting` after the calls: its text, and its due date in the sheet's `dd.mm.yy` when it has one
(`FIX a meeting by 15.10.26`), set apart from the dated lines above it by a rule and italics, and red
with an *overdue* badge once the date has passed. Its owner is the last line of *With?*. So the
sheet's `Call 09.09.26 / Da risentire post email` reads back as one dated line and a next action
beneath it, in the one cell the team looks in. *Met?* still sorts by the latest interaction.

**Its form's placeholder is a hint, not an action**: *Write the next action here*, *Scrivi qui la
prossima azione*, in italics and lighter than a value
([#112](https://github.com/KnowledgeFabric/kf-admin/issues/112)). It was the sheet's own `FIX a
meeting`, which was once taken for the action itself.

**Overdue** is due before the console's today, in UTC: due today is not overdue yet.

**Set, changed, cleared and done from the row's panel**, where it comes first: *Set* or *Change* opens its
form, *Clear* saves the three empty, without logging anything, for one that is no longer to be done,
and [*Done*](#done) logs it as done.

**Logging a call asks for it every time** ([#111](https://github.com/KnowledgeFabric/kf-admin/issues/111)),
because logging a call is the moment the next step is known: one *Add* records the call and replaces
what follows. The add form's next action **starts empty**, its text and due date blank and its owner
the signed-in name (no one for `admin`), while the next action as it stands is shown at the top of
the panel for reference. It used to start filled with the current one, and left so it wrote nothing:
after the call that settled *FIX a meeting*, *FIX a meeting* was still *Met?*'s last line, and it
looked as if nothing had been saved.

- **With its text**, the call is logged and the next action replaced: Met?'s last line is the new one,
  and only that one.
- **Left empty, it asks first: *No next action planned?*** (*Nessuna prossima azione prevista?*), in
  place of the *Add* button. *Yes: log it and clear the next action* logs the call and clears it,
  since the call is taken to have settled it. *Log it and keep the current one*, offered only when
  there is one, is for a call logged after the fact: the call is logged and the contact is not
  written. *No, I will write one* goes back to the field. The answer is sent as `nextActionChoice`,
  `clear` or `keep`; without one, the console draws the form again with the question open, `400`,
  and writes nothing.

The form (`Areas/Crm/Models/NextAction.cs`) is checked before anything is written:

- **The text decides.** Without it there is no next action, and the owner, which the form starts at
  the signed-in name, is not kept. A due date without the text is refused, since it was typed for
  something. The text is at most 500 characters: the rest belongs in an interaction's summary.
- **With the text, an owner is required**, one of the names *By* offers or the one it already names;
  **a due date is not**, because the sheet's to-dos often had none (`Call post California ??`). A day
  before 2000 is a mistyped year. A date in the past is taken: it is overdue.
- **Already what the contact holds, it writes nothing**, whatever version was sent: the outcome
  asked for. So a call logged with the next action kept, or typed as it stands, or cleared when
  there was none, never touches the contact row.

**It is part of the contact**, so its save is a contact save like a cell's. The panel is drawn with
the contact's version, its `xmin`, and the save carries it: over a colleague's later change to the
contact, whether to the next action or to any cell, it is `409` with the contact as it is now and what
was typed kept in the form, at the colleague's version, to save again knowingly. From the add form,
a stale next action refuses the call too: neither is written, and both are kept in the form. Since
the add form sets or clears the next action with almost every call (#111), this is the stale save a
logged call most often meets after a colleague's cell save; a cleared one is asked again, since the
colleague may have set a new one. The
version is the row's, not the field's, so a colleague's note can make a next action stale, and the
other way round; that is the cost [cell saves](#editing-in-place) already pay. On the page, the
script keeps the two in step: after a next action you saved, the row's cells take the new version
(the panel says which version it was saved from, and the next action is all that changed), and
after a cell you saved, the panel's forms do likewise; a version learnt any other way, a panel
opened after a colleague's save say, is never taken for the cells. A cell save answers the row's
next action too, so after a stale one the two lines are the colleague's.

| The answer | Means | The panel |
|---|---|---|
| `200` | Saved, under your name, or already so and nothing written | Redrawn, and the row's two cells redrawn and flashed |
| `400` | Refused: the form says why. Nothing written | The form open again, with what you typed |
| `409` | **Stale**: a colleague saved the contact after the panel was drawn. Nothing of yours written | Theirs is shown, with your form open, holding what you typed and now at their version |
| `404`, JSON | The contact has been deleted | The row is struck through |
| `403` | Your session no longer holds *CRM: Write* | The page says so |

Audited as `crm:contact-update`, with `field` naming the next-action fields the save changed
(`nextAction, nextActionOwner, nextActionDue`), and never what the next action says. Reminders by
mail or calendar, and more than one open action per contact, are not here (#92, not in scope).

### Done

*Clear* leaves nothing behind: the audit entry names the fields, never what they said, and the
contact leaves the follow-ups. **One that was done is *Done*** (*Fatta*,
[#133](https://github.com/KnowledgeFabric/kf-admin/issues/133)), beside *Change* and *Clear* for a
`crm:write` session on a contact that has one. **One click, and it is saved**, with nothing asked:

- **An interaction is logged**: a *Call*, today, its summary the next action's text as it stands,
  and its owner as taking part; when the owner cannot be named, `admin` ([#108](#admin-is-no-one))
  or a name no longer holding a CRM role, whoever pressed it.
- **The next action is cleared**, so the contact leaves `/Crm/FollowUps`.

What it logged is an ordinary interaction under *Met?*, in the name of whoever pressed it: a kind
other than *Call*, another day or more words are put right with its *Edit*. There is no kind for a
task, so a follow-up that was not contact with the person (`send the deck`) is changed to the kind
nearest to it, and no `Done:` is put before the summary: the interaction is the record that it was
done, and anything the console typed into the summary would be stored in the language of whoever
pressed the button. A next step is set afterwards with *Set*.

It is the add form's own `POST /Crm/Contacts/{id}/Interactions`, sent from a form of hidden fields
drawn with the panel, with the next action empty and `nextActionChoice=done`, which clears it without
asking *No next action planned?*. So the rules are a logged call's: the contact's version is checked,
and the answers and the audit entries are the same. Refused (`400`, `admin` pressing it with no one
to name, say), the add form is drawn with what it sent, headed *Log the next action as done*, to put
right and add, a next action typed there replacing the one done; *Cancel* turns it back into the form
for logging a call. Refused as stale (`409`), nothing is written and it is drawn as the add form,
since the colleague's next action may not be the one that was done: left empty, it asks again.

## Follow-ups

`/Crm/FollowUps`, **CRM → Follow-ups** in the menu: "what is due this week" is the question the
programme is run by. **The same grid as Partnerships**: the same columns, the same rows drawn by the same
`_ContactRow`, the same script and the same endpoints, so a row here is the row there, edited in
place, its panel opened from *Met?* or *With?*. What differs:

- **Only the contacts with a next action**, and no blank row, since a contact made here would have
  none.
- **Overdue first, then by due date**, which is one order: the earliest due date first, so the
  longest overdue leads; those with no date last, then by name. A heading sorts as on Partnerships;
  reloading gives this order back.
- **Filters above the grid**, in the query string so each can be linked to: **Mine**
  (`?mine=true`), the signed-in name's own, one link that means each person's own and wins over an
  owner; **owner** (`?owner=rob`), any name *By* offers; and **due** (`?due=Overdue`, or
  `?due=Week`, due today or in the six days after, whatever day today is). A value the console does
  not know narrows nothing.

The heading counts them and the overdue among them. The rows are read by
`IContactRegister.FollowUpsAsync`; on PostgreSQL the filter and the order are in SQL, over every
contact, since the programme is dozens of people.

## The overview

The CRM's section on `/`, placed by `Views/Home/Index.cshtml` as the other two areas' are and drawn
for a `crm:view` session only (`CrmOverviewViewComponent`):

| | Links to |
|---|---|
| **Contacts**, all of them | `/Crm/Contacts`, the *Partnerships* grid |
| **Follow-ups**: contacts with a next action, and how many have no date; *Yours* | `/Crm/FollowUps`, `?mine=true` |
| **Due within a week**: today and the six days after, in UTC | `/Crm/FollowUps?due=Week` |
| **Overdue**: due before today | `/Crm/FollowUps?due=Overdue` |
| **By stage**: every stage, in the order they are passed through, empty ones included | `/Crm/Contacts?stage=…` |
| **By kind of partnership**: every track | `/Crm/Contacts?track=…` |
| **By individual / company** (#156): *Individual*, *Company*, and *Not said* for every contact nobody has marked either way | `/Crm/Contacts?entity=…`, `NotSaid` for *Not said* ([*Name*'s filter](#individual-or-company)) |
| **Introductions by stage** (#147): every stage, the customers introduced above them | *Customers introduced* to `/Crm/Statistics#crm-introductions` (#150); the stages nowhere |
| **Interactions per week** (#158): a chart of the last twelve weeks, [below](#interactions-per-week) | Nowhere |

Counted in memory (`Crm/FollowUps.cs`, `CrmStatistics`) from `IContactRegister.SummariesAsync`,
each contact's stage, track, individual or company and next action's owner and due date and nothing
of the person, as the
register's statistics are: the programme is dozens of people, not thousands. A store it cannot read
is said on the card, not thrown: the overview is where every sign-in lands.

### Interactions per week

Beneath the tables ([#158](https://github.com/KnowledgeFabric/kf-admin/issues/158)), whether the
programme is being worked as well as where it stands: the interactions logged in each of the last
twelve weeks, stacked by kind, the current week last and partial, with the total and this week's
count above it and the same numbers as a table behind *Show as a table*. A week runs Monday to
Sunday in UTC, and an interaction counts in the week of the day it happened, not of when it was
entered, so a call logged after the fact, or imported from the sheet, goes back to its week. An
empty week is a week of zeros. Only live contacts' interactions count: a deleted contact's are
hidden with it.

**The team's, never a person's.** The chart has no split by participant, so it cannot read as a
league table. Nor does a week link anywhere: the grid has no filter by an interaction's day.

Read by `IContactRegister.InteractionSummariesAsync`, an interaction's day and kind and nothing else,
from the first day counted on, and counted in memory (`Crm/CrmActivity.cs`); drawn by
`wwwroot/js/crm-overview.js`. The five kinds take five hues in the kinds' order, the logo's blue
first, validated as a set for colour-blind readers on the card; three are below 3:1 against it,
which the table answers.

## Statistics

`/Crm/Statistics`, **CRM → Statistics** in the menu
([#120](https://github.com/KnowledgeFabric/kf-admin/issues/120)): the programme in numbers for the
go-to-market story, as Roberto set them out for devFest. One table, each line indented under the line
it divides, so the lines beneath a line add up to it:

| Line | Italian, Roberto's | Stages counted |
|---|---|---|
| **Contacts identified** | *Contatti identificati* | Every stage |
| To schedule | *Da pianificare* | *To contact*, *Contacted, awaiting reply* |
| To meet soon | *Da incontrare a breve* | *Meeting planned* |
| Met | *Incontrati* | *Met* and every stage after it |
| · Discussion ongoing | *Discussione in corso* | *Met* |
| · Discussion concluded | *Discussione conclusa* | The three lines below |
| · · **Accepted the proposal**, then by kind of partnership | *Proposta accettata* | *Pre-proposal agreed*, *Active* |
| · · **Decision deferred**, then by [why](#the-rows-details) | *Decisione rinviata* | *Declined or dormant* |
| · · **Not a fit to work with** | *Persona relazionalmente non idonea* | *Rejected* |

The three ways a discussion ends each carry their share of the concluded ones, `57%`, as the slide
did; with none concluded there is no share. *Accepted* lists partner and ambassador always and
*Undecided* only when an accepted contact has no track yet; *Decision deferred* lists every reason
and *No reason recorded* only when a deferred contact has none, so the lines still add up. A line of
one stage links to the grid filtered to it, today. Each line names the stages it counts, on a screen
wide enough, so a number can be checked against the grid.

**What it is not.** Counts only, never a name: a contact is personal data (#87, decision 9), and
the page is meant to be shown. Not conversion between stages or time spent in each: the
[change record](#the-change-record) holds what they need, and whether the page shows them is
Roberto's call. Nothing before the record began can be rebuilt: the audit log records that a stage
changed and never to what. Every live contact counts, a test one included: there is no flag for one,
and deleting it leaves it out.

Counted in memory (`Crm/CrmFunnel.cs`) from `IContactRegister.SummariesAsync`, as the overview is,
with each contact's decline reason added to the summary and still nothing of the person. A store it
cannot read is said on the page.

### What the partners produced

Beneath the partners' table, a second in the same form
([#150](https://github.com/KnowledgeFabric/kf-admin/issues/150)), *From introduction to contract*:
the partners' table counts the partners, this counts the [customers they introduced](#introductions).
Every line is a share of the customers introduced, and each group beneath the first line adds up to
it:

| Line | Italian | Stages counted |
|---|---|---|
| **Customers introduced** | *Clienti segnalati* | Every stage |
| · Not yet met | *Non ancora incontrati* | *Introduced* |
| · In discussion, Pilot | *In discussione*, *Pilota* | The stage of the name |
| · **Under contract** | *Sotto contratto* | *Under contract* |
| · Declined, Lapsed | *Ha rifiutato*, *Non rinnovato* | The stage of the name |
| *By the partner's kind of partnership*: business partner, ambassador, and undecided only when a partner has no track | *Per tipo di partnership di chi li ha segnalati* | |
| *How far they got, at any time*: **Reached a pilot** | *Arrivati a un pilota* | *Pilot*, *Under contract*, *Lapsed*, at any time |
| · **Reached a contract** | *Arrivati a un contratto* | *Under contract*, *Lapsed*, at any time |

**By the partner's track** as it stands today: the introductions' record keeps the stage and not the
track, and a track on a past day is the contacts' own record, which is not joined. On a day gone, a
partner deleted since counts by the track it had when it was deleted, its last change's
(`CrmHistory.Tracks`).

**How far they got** is read from the [introductions' change record](#the-introductions-change-record),
not from today's stage, which cannot say it once an introduction moves on, declines or lapses: an
introduction that stood at any time at the stage or one past it counts. A customer that signed
without a pilot got further than a pilot, and *Lapsed* is a contract that ended (#145, decision 3),
so *Reached a contract* is always within *Reached a pilot*. A pilot that declined still counts as a
pilot reached. Time spent in each stage is not built: Roberto's call, as it is for contacts.

**What it is not**, as the partners' table is not: never a name, neither the partner's nor the
customer's nor the contact person's (#87, decision 9; #145, decision 9); a partner's own
introductions are on the partner's page. No line links anywhere, since introductions have no grid
(#145, decision 12). Not which partner introduced the most, not why a customer declined (a reason
list first), and not revenue, which the console does not know (#145, decision 11).

Counted in memory (`Crm/IntroductionFunnel.cs`) from `IContactRegister.IntroductionSummariesAsync`,
joined by partner id to the contacts' summaries for the track, and from
`IContactRegister.IntroductionChangesAsync` for how far each got. Introductions that cannot be read
are said on their card, and the partners' table is shown regardless.

### On a day gone and over time

Since [#139](https://github.com/KnowledgeFabric/kf-admin/issues/139) the page answers for any day
since the [change record](#the-change-record) began, as well as today:

- **As of** a day, picked above the funnel and sent as `?asOf=2026-11-30`, read invariantly: the same
  table, every contact as it stood at the end of that day, UTC, those deleted by then left out. The
  lines do not link to the grid, which is today's, and the footnote names the day. *Back to today*
  drops it. A day that is not a date, has not come yet, or is before the record began is said on the
  page, which shows today instead; so does any day while the record cannot be read.
- **Over time**: contacts identified, met and accepted, the funnel's headline lines, at the end of
  each week (a Sunday, as an ISO week ends) from the day the record began to the day shown; once
  that is more than 26 weeks, at the end of each month. Three lines in one hue, light to dark as a
  contact goes further (`wwwroot/js/crm-statistics.js`, ApexCharts as the overview's charts are),
  each one's count where it ends, and the same numbers in a table beneath that folds open. A point,
  and each day in the table, opens the funnel as it stood that day. On the record's first day there
  is nothing to draw yet, and the page says so.

**The introductions** answer for the same day ([#150](https://github.com/KnowledgeFabric/kf-admin/issues/150),
`Crm/IntroductionHistory.cs`), replayed from `crm_introduction_changes` by the same rule, stopped at
the day's end, UTC: every introduction live then, those deleted by then left out, a partner's
deleted with it on the day the partner went. Their record has no baseline: it began with
`crm_introductions`' own migration, `AddCrmIntroductions`, on **22 October 2026**
(`IntroductionHistory.Created`), so a day from then to the first introduction counts none, and a day
before it shows nothing for them and says when it began, while the partners' table answers for the
day. Beneath the partners' chart a second, *Customers introduced over time*: the customers
introduced and those under contract at the end of each week, or month past 26 weeks, from 22 October
to the day shown, two lines at the two ends of the same ramp, and its table beneath; a point opens
the page as it stood that day.

Both of the partners' are `Crm/CrmHistory.cs`: the record read whole (`IContactRegister.ChangesAsync`), each contact's
changes taken in the order written and stopped at the first after the day, and the result counted by
`CrmFunnel`, unchanged. A past day's summaries have no next action, which the funnel does not read.
The ramp is worked out from the palette's primary (`window.config.colors`), so it moves with it; it
was checked as an ordinal ramp for the KnowledgeFabric blue, `#2c7be5`, and is to be checked again
if that changes.

### The change record

The statistics over time ([#139](https://github.com/KnowledgeFabric/kf-admin/issues/139)) are read
from changes, not snapshots. Every write that moves what the funnel counts, a contact's stage, track
or decline reason, or whether it is live, appends a row to `crm_contact_changes` holding those
values as they stand after it (`Crm/ContactChange.cs`), and so does one that moves whether the
contact is an [individual or a company](#individual-or-company) (#146), which the statistics do not count yet. How the programme stood on any day is each
contact's latest row on or before it, among those live on it, so nothing is saved daily and no day
has to have been asked about in advance.

| Kind | Written by | Who |
|---|---|---|
| `Baseline` | The `AddCrmContactChanges` migration, once: every contact, deleted ones included, as it stood when the migration ran | Nobody: `changed_by` is null |
| `Created` | The blank row | Who created it |
| `Imported` | [The import](#the-import), a row per contact | The Administrator who imported |
| `Updated` | A save that moved the stage, the track, the decline reason or the entity, from a cell or anywhere else | Who saved |
| `Deleted`, `Restored` | [Delete](#delete) and *Restore* | The Administrator. The row forgets who restored it, so this is the only place that says |

A save of any other field writes none: a name, a note, a next action, the contact save a logged call
makes. Neither does a value set to what it was, a stale save, a delete or a restore that finds
nothing to do, or an import refused. Each row is written in the same transaction as the write it
records, by the store (`IContactRegister`), not a database trigger: a restore leaves nothing on the
contact's row to say who made it, and the in-memory store the tests run on would have no trigger.

**Individual or company is recorded before the statistics count it** (#146): a count of accepted
partners by individual or company on a past day can be made only if the field was recorded from the
day it existed. The `AddCrmContactEntity` migration left it null on every change already written,
which is what it was, and wrote no baseline: a contact's first value is null.

**The record starts at the migration.** Nothing before it was kept, and nothing before it is
invented: [the statistics](#on-a-day-gone-and-over-time) say from which day it counts, and refuse a
day before it. It is read whole and replayed in memory
(`IContactRegister.ChangesAsync`): the programme is dozens of people, and the table grows only when
one of them moves.

**In the order written, not by time.** A contact's rows are numbered in the order their writes
committed: a delete or a restore numbers its row only once it holds the contact's, and a save that
would land out of turn fails its version check, so its number is never used. A replay takes them by
`id`. `changed_at`
is the console's clock read before the write, so it can run backwards by moments: a delete checks
no version and can land after a colleague's later-stamped save, and the baseline carries the
database's clock. It says which day a row counts from, never which of two rows is the later.

**It is not in the export.** [The import](#the-import) records each contact it writes as
`Imported`, today, at the stage the file gives, so a restore through export and import starts the
record again from that day. The server's point-in-time backups keep it, with everything else.

## The row's details

`/Crm/Contacts/{id}`, reached from the name: the same row on its own, with the fields that are not
columns. Not a second way to edit what the grid edits: the row is the same one-row grid, the same
cells, the same requests, and *Organisation*, *Individual or company*, *Email*, *Phone*, *LinkedIn*
and *Why declined* are cells of the same contact going to the same endpoint.

**Why declined** (#120, field `declineReason`) is a dropdown: *Awaiting more traction*, *Not looking
for new partners*, *Other*, or *Not said*. A list, as the stages are, so that the
[statistics](#statistics) count each reason rather than five spellings of one; a reason added is a
ticket. It is kept whatever the stage, so a contact who comes back keeps the reason they once gave,
and counted only while the stage is *Declined or dormant*. Not a column of the grid, to keep the
sheet's width.

What is to be done comes first ([#117](https://github.com/KnowledgeFabric/kf-admin/issues/117)):
directly under the row is the full timeline, the grid's panel drawn in place, with the next action
at its top, then every interaction and the form to log one. Below it, the
[*Customers introduced*](#introductions) card (#147); then the *Details* card, with those
six fields; then one line of small print, which is reference and not a card of its own: who
entered the contact and who last changed a cell, the contact's id, and a link to its audit entries,
its interactions among them. *Delete* is one button in a card at the foot of the page, which only an
Administrator sees ([#127](https://github.com/KnowledgeFabric/kf-admin/issues/127)).

### Individual or company

**Individual or company** ([#146](https://github.com/KnowledgeFabric/kf-admin/issues/146), field
`entity`), beside *Organisation*, says whether the partnership is with the person or with the
company they stand for: a dropdown of *Individual*, *Company* or *Not said* (blank). An ambassador is
a person; a business partner is usually a firm, and the row its representative. It says which the
partnership is with, not who the row is: the name stays the person's and the organisation the
firm's, and no rule ties it to *Organisation*, so a company contact with no organisation named is a
blank *Organisation*, as the sheet had them. Nullable, as *Engagement Level* and *Why declined* are,
so nobody's row says anything until someone does.

Not a column of the grid, which would cost the sheet's fit at 1366 (#126). Instead the *Name* cell
carries a building, `ti-building`, beside a company's name, with the organisation on hover, or
*Company* when none is named; the cell's value is still the bare name, so its editor starts from
that. *Name*'s filter asks for `?entity=Individual`, `Company`, or `NotSaid`, those nobody has
marked. The [overview](#the-overview) counts it as it stands today ([#156](https://github.com/KnowledgeFabric/kf-admin/issues/156)), *Not said* included; the
statistics do not yet: it is in the [change record](#the-change-record) so that they can, by a
ticket, when the customers ([#145](https://github.com/KnowledgeFabric/kf-admin/issues/145)) give
them a reason to. A column, should the team want one after seeing the mark, is a line in
`ContactFields.Columns`. `entity`, not `kind`: *Kind of partnership* is the sheet's name for the
track, and `kind` is an interaction's.

## Introductions

The CRM holds the partners and ambassadors; what they are for is the customers they introduce
([#145](https://github.com/KnowledgeFabric/kf-admin/issues/145)). An **introduction** is the
connection a partner made to a customer, as a record of its own
([#147](https://github.com/KnowledgeFabric/kf-admin/issues/147)) rather than a sentence in the
partner's *Notes*: who introduced whom, when, who at the customer we talk to, and how far it got.
It is **the partner's** (#145, decision 12): a card on the partner's page, *Customers introduced*
(*Clienti segnalati*; the Italian for an introduction is *segnalazione*, decision 13), and no page or
grid of its own. **Not a customers table** (decision 1): the customer is a name on the row until
Roberto's CRM brings customers into the console, when a nullable `customer_id` will join a row to
one. **Not a pipeline** (decision 7): the calls, meetings and demos with the customer are his CRM's,
so an introduction has no interactions and no next action; the partner's own calls with us stay on
the partner's row.

**The card**, below the timeline and above *Details*: one row per introduction, by the day it was
made, oldest first, and cells edited in place as the grid's are:

| Column | | Edited as |
|---|---|---|
| **Customer** | The customer's name, an organisation or a person. Required, at most 200 characters | Text |
| **Introduced on** | The day, in the sheet's `dd.mm.yy`. Required: the one date the register cannot know | A date |
| **Stage** | *Introduced*, *In discussion*, *Pilot*, *Under contract*, and the two exits, *Declined* and *Lapsed* | Dropdown |
| **Contact person** | Who at the customer we talk to. At most 200 | Text |
| **Notes** | Free text, with its line breaks, folded to its first lines ([#114](#the-grid)) | A block of text |

**The stages** (#145, decision 3): *Introduced → In discussion → Pilot → Under contract*, and two
ways out, *Declined*, a customer that stopped at any earlier stage, and *Lapsed*, a contract that
ended without renewal. Calls, meetings and demos are not a stage each: the stage is *In discussion*
while they happen. *Renewals* is not a stage: a renewed customer stays *Under contract*, the renewal
being a reissue of its licence. **The stage is set, not derived** (decision 4): a cell, as a
contact's is, and the [change record](#the-introductions-change-record) records every move. An
enum, `IntroductionStage` in `Crm/Introduction.cs`, changed by a ticket, as the contacts' stages
are. Neither exit has a reason list yet.

**The partner is not a cell** (decision 2): an introduction belongs to the partner who made it, which
is what the programme credits, and is set once. One entered on the wrong partner is deleted and
added on the right one; a second partner who helps later is a line in its notes.

**Each save is one request**, `POST /Crm/Contacts/{id}/Introductions/{introduction}/Cell`, with
the field, the value, the introduction's own row version (its `xmin`) and the page's token, checked
before anything is written (`Areas/Crm/Models/IntroductionCard.cs`, `IntroductionEdit`) and answered
as a contact's cell is: `200` with the row's cells, `400` with why, `409` with the row as a colleague
left it and who, nothing merged, `404` when the introduction or its partner has been deleted, `403`
without *CRM: Write*. The script (`wwwroot/js/crm-contacts.js`) is the grid's, generalised on its
endpoint: a row of the card is an introduction, its version its own, and a day opens as a date
input. The panel's *Email* and *Phone* (the second pull request) are cells of the same introduction,
saved the same way.

**The form**, at the foot of the card for a `crm:write` session: *Customer*, *Introduced on*,
starting at today, *Stage*, starting at *Introduced*, *Contact person* and *Notes*.
`POST /Crm/Contacts/{id}/Introductions`, each field checked as its cell is, and answered with the
card drawn again, which the script puts in place of it: `200` with the new row in its place and the
form empty, `400` with the form shown again, what was typed and why. **A day after tomorrow is
refused**, as the interactions form refuses it: an introduction is one that has been made, and one
that is planned is the partner's next action; tomorrow is taken because the console's today is UTC's
and the team's is ahead of it. A day before 2000 is a mistyped year.

**Adding one never touches the partner's row**: it is a row of its own, with its own version, so it
never makes a colleague's open cell save stale, and a colleague's cell save never makes it stale.

**With its partner** (#145, decision 10): an introduction goes where its partner goes, as the
partner's interactions do. It is hidden with a soft-deleted contact and back with a restore,
counted on the contact's [delete](#delete) confirm step beside the interactions, and erased with
an [erasure](Operations.md#erasing-a-contact) by the foreign key's cascade. Every read goes through
the store's live query: an introduction is read or written only while its partner is live and it is
not deleted itself.

**On the overview** the CRM section counts the customers introduced by stage, beside the contacts
by stage, from `IContactRegister.IntroductionSummariesAsync`: each introduction's id, its partner's
and its stage, and nothing else, counted in memory. The stages link nowhere, since an introduction
has no grid of its own; *Customers introduced* links to [their funnel](#what-the-partners-produced)
on the statistics page (#150).

**A `crm:view` session** sees the rows, with no form, and `403` from every write.

**The second pull request** (#147's, as the epic ordered the work): a click on the customer's name
opening the row's panel beneath it, with the contact person's *Email* and *Phone*, who entered the
introduction and who last changed it, and *Delete* for an Administrator; delete and restore, soft and
an Administrator's, with deleted introductions on *Deleted contacts*; the warning when two partners
name one customer, as two contacts sharing a name are warned (never refused: the team decides who
gets the credit); and `introductions.csv` in the export and the import. Its licences from the
register are [#149](https://github.com/KnowledgeFabric/kf-admin/issues/149), and its funnel on the
statistics page [#150](https://github.com/KnowledgeFabric/kf-admin/issues/150).

### The introductions' change record

`crm_introduction_changes` (`Crm/Introduction.cs`, `IntroductionChange`), the pattern of
[`crm_contact_changes`](#the-change-record): a row holding the introduction's stage and whether it
is live, as they stand after the write, appended in the same transaction as the write it records,
by the store and never a trigger, and never updated. One row on a create, an import, a save that
moves the stage, a delete and a restore, and **one per live introduction when its partner is
deleted or restored** (`Deleted`, `Restored`), since an introduction goes where its partner goes. A
save of anything else writes none: the customer's name, the contact person, a note, the day. Neither
does a stage set to what it was, or a stale save. **No baseline rows**: the table starts with the
introductions, so nothing before it is invented. `ContactChangeKind` is reused, less `Baseline`.
Read whole and replayed in memory by `IContactRegister.IntroductionChangesAsync`, in the order
written, for the introductions funnel over time (#150). Nothing of anyone in it: the introduction's
id, the partner's id (so a replay by partner needs no join), an enum, a time and a console name.

## Delete

From the row's details, behind a confirm step that says what it does and counts the interactions
and the [introductions](#introductions) that go with the contact. Audited as `crm:contact-delete` with the contact's id and name, and
nothing else of the row. Deleting what a colleague has already deleted changes nothing and records
nothing.

**Data never leaves the database** ([#119](https://github.com/KnowledgeFabric/kf-admin/issues/119)).
A delete is soft: the row stays in `crm_contacts` with `deleted_by` and `deleted_at` set, and its
interactions stay in `crm_interactions`. Every read leaves a deleted contact out (the grid, a
row's page, the follow-ups, the overview's counts, the same-name warning, *Export CSV*), so to
everyone it is gone, and a colleague with the grid open is told so on their next save of it, as
before. Every read goes through the store's `Live` query, spelled out rather than an EF Core global
filter, so that no query leaves rows out unseen.

**It is an Administrator's** (`crm:delete`), not every writer's, as the import is. Day to day, a
name once written stays: *CRM: Write* adds and edits contacts and logs, edits and deletes
interactions, and sees no *Delete* card, not a greyed-out button
([#127](https://github.com/KnowledgeFabric/kf-admin/issues/127)); the confirm step's page, reached by
its address, says it needs *Administrator*, and its `POST` is refused.

**The confirm step asks for the contact's name, typed.** It is compared as two contacts are found
to share a name: trimmed, case aside. Anything else, nothing typed included, deletes nothing and
records nothing, and the step says so.

**Deleted contacts** (`/Crm/Contacts/Deleted`, linked from the grid for an Administrator alone)
lists every deleted contact, the most recently deleted first, with who deleted it and when, a link to
its audit entries, and **Restore**, which brings it back as it was, its next action, its
interactions and its [introductions](#introductions) with it. Audited `crm:contact-restore` with the id and name. Restoring what a colleague
has already restored changes nothing and records nothing. A restore is `crm:delete` too: whoever
may take a contact away may bring it back.

**Erasing a person is an operator's.** When someone asks to be removed (#87, decision 9), nothing in
the console can do it: an Administrator deletes the contact, then an operator removes the row from
the database ([Operations](Operations.md#erasing-a-contact)), and the foreign keys' `ON DELETE CASCADE`
remove its interactions and its introductions with it. The audit log keeps the id and the name, as decision 9 allows for
every entry; whether an erasure reaches the audit log too is the team's call. An archive purged on a
schedule was considered and not built: the erasure is a deliberate act, by request.

**An import refuses a deleted contact's id**, since the row is still there: the preview says to
restore it instead, or leave it out of the file. A name only a deleted contact holds is free, as it
is for the blank row.

## Export and import

**Export CSV**, on the contacts grid, downloads every contact and every interaction, whatever the
grid is filtered to, but a [deleted](#delete) contact's, as `crm-export-yyyyMMdd-HHmm.zip` holding the two files below. Any `crm:view`
session may, as anyone who can read the register may export it, and every export is an audit entry,
`crm:export`, with the counts. **The zip is personal data**: keep it where the team keeps contacts,
never in a repository, and delete it when it has served.

**`/Crm/Import`** (*Import*, beside it, for an Administrator alone) reads the same two files back:
the sheet's one-off, and a [restore](Operations.md#restoring-the-crm-from-an-export). It is a
one-off in kind, so it is `crm:import`, an Administrator's, not every writer's.

### The format

Two files, `Crm/CrmCsv.cs`. RFC 4180: a value holding a comma, a quote or a line break is in double
quotes, its quotes doubled; UTF-8, a byte-order mark skipped if a spreadsheet wrote one. Read by the
header, so the columns may come in any order; a column the format does not have refuses the file
rather than being dropped, and one it has that a file leaves out reads as blank on every line.

`contacts.csv`, a line per contact, the columns of `crm_contacts` less the audit ones:

| Column | |
|---|---|
| `id` | The contact's id. Blank for a new contact; an export writes it, so that a restore keeps the ids the audit log names |
| `name` | Required |
| `headline`, `organisation`, `email`, `phone`, `linkedin_url` | As the details page takes them |
| `track` | `Ambassador`, `BusinessPartner`, `Undecided`; blank is `Undecided` |
| `stage` | By name: `ToContact`, `ContactedAwaitingReply`, `MeetingPlanned`, `Met`, `PreProposalAgreed`, `Active`, `DeclinedOrDormant`, `Rejected`; blank is `ToContact` |
| `engagement` | `1` to `5`, or blank |
| `originated_by` | Required: a console name holding a CRM role, never `admin` |
| `notes` | Line breaks and all |
| `next_action`, `next_action_owner`, `next_action_due` | The [next action](#the-next-action); the owner, when blank, is `originated_by`; the due date `yyyy-MM-dd` |
| `presentation` | The presentations shown, as the cell holds them (#126). An export from before it has no such column, and reads as blank |
| `decline_reason` | Why they declined, by name (#120): `AwaitingTraction`, `NotSeekingPartners`, `Other`, or blank. An export from before it has no such column, and reads as blank |
| `entity` | Individual or company, by name (#146): `Individual`, `Company`, or blank for *Not said*. An export from before it has no such column, and reads as blank |

`interactions.csv`, a line per interaction:

| Column | |
|---|---|
| `contact_id` | The contact's `id` in `contacts.csv`. Blank in a file prepared by hand; an export writes it, so that two contacts sharing a name stay apart |
| `contact` | The contact's name, as in `contacts.csv`, whatever its case. Needed when `contact_id` is blank |
| `occurred_on` | `yyyy-MM-dd`, not in the future: a planned meeting is a next action |
| `kind` | `Call`, `InPerson`, `Message`, `Email`, `Event` |
| `participants` | Console names holding a CRM role, never `admin`, separated by `;` |
| `summary` | What was said. Blank reads as *Imported from the sheet, which noted nothing more.*, since an interaction needs one |

**A value a spreadsheet would read as a formula** — one opening with `=`, `+`, `-`, `@` or a control
character — is written behind an apostrophe, as the register's export writes it, since an export is
opened in Excel and notes begin with a dash. So that an export reads back exactly, a value opening
with an apostrophe is written with a second one, and reading takes one leading apostrophe off every
value. A file prepared by hand therefore never starts a value with an apostrophe it means to keep.

### The import

Choose the two files and **Preview**: nothing is written. The preview lists what the files would
create, a contact a line with its stage, track, *By*, interactions and next action; or every problem
with the files, by file and line, the whole list at once so a file prepared by hand is mended in one
pass. Each value is checked by the parser of the page that edits it (`ContactEdit`, `NextActionEdit`,
`InteractionEdit`), so an imported contact is one the grid could have made: every name it names
holds a CRM role, no interaction is in the future, nothing is longer than its column. Two lines of
`contacts.csv` may share a name only when both have an `id`.

**A contact whose name is already in the CRM refuses the whole import**, whatever its case, and so
does an `id` already there. That is what keeps a one-off from running twice: the same files a
second time are refused at the preview. **Import** then reads the files again, carried in the
preview's form, checks them against the CRM as it is now, and writes every contact and interaction
in one transaction, holding a lock on `crm_contacts` across the check and the write; so a confirm
sent twice, or two Administrators at once, import once, and a failure halfway writes nothing.

Each contact is entered by whoever imports (`created_by`), with *By* (`originated_by`) as the file
says; each interaction is recorded by them too. Audited once, `crm:import`, with the counts of
contacts, interactions and next actions, and nothing of the files.

### The sheet's one-off

The sheet's 24 rows, with a free-text column in two languages and dates written three ways, are not
worth a parser (#93): they are prepared by hand into the two files, with the sheet open beside them,
**outside the repository**, since they name people (#87, decision 9), and handed to whoever imports.
The mapping, so that anyone can check it:

- *By* → `originated_by`, VS, RR and MM written as their console names; `VS/RR` → VS, with a note
  saying jointly.
- *E* → `engagement`.
- *Kind of partnership* → `track`; *Potential Ambassador* → `Ambassador`, at an early stage; blank →
  `Undecided`.
- *Proposed partnership* `Pre-proposal - Agreed` → `stage` `PreProposalAgreed`.
- *Met?*: a line of `interactions.csv` per dated line. `Call` → `Call`; `F2F` → `InPerson`; `Chat` →
  `Message`; `Pizz'n'meet` and `Napoli 16/17/18.10` → `Event` (one line, on the first day). The line
  of *With?* in the same position is its `participants`, and the line of *Notes* in the same position
  its `summary`, where the lines pair up. Dates `dd.mm.yy` read as 2026.
- *Met?*'s undated lines are the stage and the next action: `DA CONTATTARE` → `ToContact` with
  *Contact*; `IN ATTESA DI RISP` → `ContactedAwaitingReply` with *Chase for a reply*; `FIX a meeting`
  → `MeetingPlanned` with *Fix a meeting*; a future-dated line → `MeetingPlanned`, with that date as
  `next_action_due`. The owner is the originator unless *With?* names one person.
- A *Current Activity* that is only a company name (`ARENIA`) → `organisation`, not `headline`.

**On the day**: import on production; open three rows' pages beside the sheet and check them; then
make the sheet read-only in its share and put a note at its top pointing at the console. The date is
recorded on #93. Afterwards every one of the 24 has a page, those with dated lines in *Met?* have
them as interactions, those with `DA CONTATTARE` are at *To contact*, and **CRM → Follow-ups** lists
every `FIX a meeting` and every future date.

## Audit

Every write is an entry in the audit log, under the contact's id as its target and the name in its
details, written once the store has the change:

| Action | On | Details |
|---|---|---|
| `crm:contact-create` | The blank row's name, or a [business card](#from-a-business-card)'s form saved | `name`; from a card, `from` `card` too |
| `crm:card-read` | A [business card](#from-a-business-card)'s photo sent to be read, whatever came of it | `model`, `outcome` (`Read`, `Unreachable`, `KeyRefused`, `NotUnderstood`), `qr` (`link`, `text` or `none`) and, for a link, `link` (`Read`, `Refused`, `Unreachable`, `Unreadable`; [#163](#a-qr-code-on-the-card)). No target, and nothing of the card or its QR code: its name is not a contact's until the form is saved |
| `crm:contact-update` | One cell save, which is what a cell save is: one entry per cell; or a [next action](#the-next-action) saved, one entry naming the fields it changed | `name`, `field` (for a next action, those of `nextAction`, `nextActionOwner`, `nextActionDue` that changed, comma-separated) |
| `crm:contact-delete` | The confirm step, the contact's name typed | `name` |
| `crm:contact-restore` | *Restore*, on *Deleted contacts* | `name` |
| `crm:interaction-add` | An interaction logged from the panel | `name`, `interaction`, `date`, `kind` |
| `crm:interaction-update` | An interaction edited | The same, as it now reads |
| `crm:interaction-delete` | An interaction deleted | The same, as it read |
| `crm:introduction-create` | An [introduction](#introductions) added from the card's form | `name`, `introduction`, `customer` |
| `crm:introduction-update` | One cell of an introduction saved | The same, and `field` |
| `crm:export` | *Export CSV* | `contacts`, `interactions`: the counts. No target |
| `crm:import` | The import's confirm, once written | `contacts`, `interactions`, `nextActions`: the counts. No target, since it is every contact it made |

Never the old and the new text, never an interaction's summary, never what a next action says, and
never an introduction's contact person, their email or phone, or its notes (#145, decision 9): what
a note, a call or a to-do said is in the row, not in the log. An introduction's entries are under
the partner's id, as an interaction's are, with the introduction's id and the customer's name. A call logged with a next action
in one submit, or with it cleared, is two entries, the contact update first; with it kept, one. A
next action marked [*Done*](#done) is the same two. An interaction's entries are under the contact's id, so the details page's
*Audit log* link lists them with the contact's own.

## Personal data

The CRM holds business contacts by name, with what they said to us (#87, decision 9). So:

- **No log line of the console's own names a contact.** A store that cannot be read, a save that
  fails, a people list that cannot be read: each is logged, and none names a contact. A request's
  URL carries the contact's id and nothing else, so Application Insights' request telemetry holds
  ids.
- **An audit entry carries the id and the name**, and the field a cell save changed, or an
  interaction's id, day and kind, and nothing else: never a note, never a summary, never a next
  action's text. An audit entry is also a log line, by the shell's design (#69), so the name
  reaches Application Insights that way and no other; decision 9 allows exactly that much.
- **The [change record](#the-change-record) holds nothing of the person**: the contact's id,
  its stage, track, decline reason and entity, a time and a console name. Neither does the
  [introductions' record](#the-introductions-change-record).
- **An introduction is personal data where it names a person** (#145, decision 9): the contact
  person at the customer, their email and phone, and the partner it belongs to. The same rules.
- **A business card's photo is sent to Ollama Cloud, and kept nowhere** ([#161](#from-a-business-card)):
  not stored, logged or audited, and shown back only in the page that sent it. What Ollama does with
  it is [its own account](https://docs.ollama.com/cloud): processed to answer, and not trained on.
  It is the one way a contact's details leave the console other than an export, and it is audited,
  `crm:card-read`, as an export is. A QR code on the card goes with it, and the page its link leads
  to, which the console opens ([#163](#a-qr-code-on-the-card)): neither is logged or kept.
- **Nothing of it goes in a tracked file.** The tests make up their contacts; #93's prepared CSV is
  handed over outside the repository, and so is every export.
- **Delete exists**, above: an Administrator's, soft, and leaving out of every page and export a
  contact the database still holds. Erasing one is an operator's, by request
  ([Operations](Operations.md#erasing-a-contact)). Every [export](#export-and-import) is audited.
- Lawful basis, retention and a privacy notice are the team's call, not this console's.

## Storage

`crm_contacts`, `crm_interactions`, `crm_contact_changes`, `crm_introductions` and
`crm_introduction_changes` in `kf_admin`, beside the register,
the audit log and the roles, created by the `AddCrmContacts`, `AddCrmInteractions`, `AddCrmNextAction`,
`SoftDeleteCrmContacts`, `AddCrmPresentation`, `AddCrmDeclineReason`, `AddCrmContactChanges`,
`AddCrmContactEntity` and `AddCrmIntroductions` migrations at startup like them
([License Register](License-Register.md#changing-the-schema)). `crm_contacts`:

| Column | |
|---|---|
| `id` | uuid, the key |
| `name`, `headline`, `organisation`, `email`, `phone`, `linkedin_url` | The person. All but the name optional |
| `track`, `stage` | By name, as the ticket names them (`BusinessPartner`, `PreProposalAgreed`), so the table reads without the enum |
| `engagement` | 1 to 5, or null |
| `originated_by` | A console user's name, as the Users page spells it |
| `notes` | Text |
| `presentation` | The presentations shown (#126): text of at most 200 characters, though the grid is sized for a code or two. Nullable, so the migration that added it touched no row |
| `decline_reason` | Why they declined (#120), by name as `stage` is: `AwaitingTraction`, `NotSeekingPartners`, `Other`, or null. Nullable, so the migration that added it touched no row |
| `entity` | [Individual or company](#individual-or-company) (#146), by name as `stage` is: `Individual`, `Company`, or null when nobody has said. Text of at most 32 characters; nullable, so the migration that added it touched no row |
| `next_action`, `next_action_owner`, `next_action_due` | The [next action](#the-next-action) (#92): text of at most 500 characters, a console user's name, a date. Null together when there is none; nullable, so the migration that added them touched no row. No index: the follow-ups grid reads dozens of rows |
| `created_by`, `created_at`, `updated_by`, `updated_at` | Who, when, in UTC |
| `deleted_by`, `deleted_at` | Who [deleted](#delete) the contact and when (#119). Null together while it is live; nullable, so the migration that added them touched no row |
| `xmin` | The row version: PostgreSQL's system column, not one of the table's own. The migration lists it and Npgsql leaves it out of the `CREATE TABLE` |

An index on `name`, not unique. `crm_interactions` (`Crm/Interaction.cs`):

| Column | |
|---|---|
| `id` | uuid, the key |
| `contact_id` | The contact's `id`: a foreign key, `ON DELETE CASCADE`, which only an [erasure](#delete) uses |
| `occurred_on` | A date: the day it happened |
| `kind` | By name: `Call`, `InPerson`, `Message`, `Email`, `Event` |
| `participants` | `text[]`: console names, as the Users page spells them, one or more. An array, not a join table, since nothing asks which interactions a person took part in |
| `summary` | Text, required, at most 4,000 characters (the form's check) |
| `recorded_by`, `recorded_at`, `updated_by`, `updated_at` | Who, when, in UTC |
| `xmin` | The row version, as the contact's |

An index on (`contact_id`, `occurred_on`): the lines, the panel and the filter.
`crm_contact_changes` (`Crm/ContactChange.cs`, [the change record](#the-change-record)), appended to
and never updated by the console:

| Column | |
|---|---|
| `id` | bigint, an identity: the order the changes were written in, which a replay follows |
| `contact_id` | The contact's `id`: a foreign key, `ON DELETE CASCADE`, so an [erasure](Operations.md#erasing-a-contact) takes the contact's record with it |
| `changed_at` | When, in UTC |
| `kind` | By name: `Baseline`, `Created`, `Imported`, `Updated`, `Deleted`, `Restored` |
| `stage`, `track`, `decline_reason`, `entity` | The contact's, after the change, by name as on `crm_contacts`. `entity` (#146) is null on every row written before it existed |
| `live` | False from a delete until a restore |
| `changed_by` | A console name; null on a `Baseline` row |

An index on (`contact_id`, `changed_at`). `crm_introductions` (`Crm/Introduction.cs`, [the
introductions](#introductions)):

| Column | |
|---|---|
| `id` | uuid, the key |
| `contact_id` | The partner, `crm_contacts.id`: a foreign key, `ON DELETE CASCADE`, which only an [erasure](#delete) uses. Set once, never changed |
| `customer` | The customer's name: text of at most 200 characters, required |
| `introduced_on` | A date, required |
| `stage` | By name: `Introduced`, `InDiscussion`, `Pilot`, `UnderContract`, `Declined`, `Lapsed` |
| `contact_person`, `email`, `phone` | Who at the customer; optional, at most 200, 254 and 50 |
| `notes` | Text |
| `created_by`, `created_at`, `updated_by`, `updated_at` | Who, when, in UTC |
| `deleted_by`, `deleted_at` | Who deleted the introduction and when, soft as a contact's; null together while it is live. The columns are there from the first migration, the delete itself is the second pull request |
| `xmin` | The row version, as the contact's |

An index on `contact_id`. `crm_introduction_changes` ([the introductions' change record](#the-introductions-change-record)),
appended to and never updated by the console:

| Column | |
|---|---|
| `id` | bigint, an identity: the order the changes were written in |
| `introduction_id` | The introduction's `id`: a foreign key, `ON DELETE CASCADE` |
| `contact_id` | The partner's `id`, so a replay needs no join |
| `changed_at` | When, in UTC |
| `kind` | By name: `Created`, `Imported`, `Updated`, `Deleted`, `Restored` (`ContactChangeKind`, less `Baseline`) |
| `stage` | The introduction's, after the change, by name |
| `live` | False from a delete, its own or its partner's, until a restore |
| `changed_by` | A console name |

An index on (`introduction_id`, `changed_at`). The store is `Crm/IContactRegister.cs`, with a PostgreSQL
implementation and an in-memory one, chosen as the register's is
([How the console chooses a store](License-Register.md#how-the-console-chooses-a-store)): the
database when `Database:ConnectionString` is set, memory in Development without one, and otherwise
a store that holds nothing and refuses to write, which the grid says. It answers the follow-ups grid
(`FollowUpsAsync`) and the overview's and the statistics' counts (`SummariesAsync`,
`IntroductionSummariesAsync`) too. Its own interface rather than
`IFeatureStateStore`, for the reason the register has one ([Console Shell](Console-Shell.md#authorisation-audit-and-storage-are-seams-before-they-are-features)):
it wants search, ordering and a version check on every write. Interactions and introductions are in
the same store because they belong to a contact: the cascade and the filter read all three, and a
contact's delete and restore carry both. The introductions' methods are grouped under their own
heading in it. Reads and writes go through
`ConsoleDbContext`, and the names a contact may name come from `Security/ConsolePeople.cs`, which
reads the role store so that no page has to.

## Who may do what

| | `crm:view` (*CRM: View*) | `crm:write` (*CRM: Write*) |
|---|---|---|
| The grid, the follow-ups grid, the statistics, a row's details with its *Customers introduced* card, the confirm step's page, the panel with the next action | Yes | Yes |
| *Export CSV* | Yes | Yes |
| A contact from a [business card](#from-a-business-card), its page included | Refused | Yes |
| A cell save, the blank row; logging, editing or deleting an interaction; setting, changing or clearing a next action; adding an [introduction](#introductions) or saving a cell of one | `403` | Yes |
| Deleting a contact, *Deleted contacts* and *Restore* (`crm:delete`, [#119](https://github.com/KnowledgeFabric/kf-admin/issues/119)) | Refused | Refused: an Administrator's alone |
| The import, `/Crm/Import` (`crm:import`) | Refused | Refused: an Administrator's alone |
| The CRM in the menu and on the overview | Yes | Yes |

A session holding neither, a licensing operator say, is refused every `/Crm` route and sees no CRM
entry in the menu, and `admin` and an Administrator hold both. A `crm:write` session reads the audit
log as any write role does: its own entries, in every area, and everyone's only with *Administrator*
([#99](https://github.com/KnowledgeFabric/kf-admin/issues/99)).

## Not here

- Keyboard navigation across cells, range copy and paste, formulas, column widths that persist: a
  grid edited cell by cell, not a spreadsheet (#87, *Later*).
- Organisations as records, and a link from a contact to a customer in the licence register: the
  organisation is text until a programme needs to see one organisation's people together.
  [Individual or company](#individual-or-company) (#146) asks a contact a yes or no, not for a table.
  An [introduction](#introductions) (#147) names its customer and links to its licences by
  [#149](https://github.com/KnowledgeFabric/kf-admin/issues/149), still without a customers table.
- A grid or list of introductions across partners (#145, decision 12): a later ticket, read-only, if
  anyone asks; the overview counts them by stage meanwhile. Interactions and a next action on an
  introduction, invoices, payments and the reward, why a customer declined as a list, and moving an
  introduction to another partner: #145's *Later*.
- Individual or company as a column of the grid (#146): the mark on the name stands for it, and a
  column is a line in `ContactFields.Columns` if the team wants one.
- A general-purpose spreadsheet importer (#93, not in scope): the import reads the export format and
  nothing else, and the sheet was mapped into it by hand.
- Reminders of a next action by mail or calendar, and more than one open action per contact
  ([#92](https://github.com/KnowledgeFabric/kf-admin/issues/92), not in scope).
- A business card's photo kept on the contact, its back side read, or a stack of cards read at once
  (#161): one photo, one contact, and the photo dropped once read.
- More than one QR code on a card, the links on a QR code's page followed in turn, or a page drawn
  by its own script run to read it (#163): the first code, its one page, and what that page's
  markup says.
- Attachments on an interaction, and mail (#91, not in scope): a link to where a file lives is a
  sentence in the summary.
</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 |

## 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*).

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 |
| `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
arriving together share one request. Each page says when the answer it shows was fetched.

Thirty seconds is not longer, and not configurable, because the brake is what the page is for: a
longer cache is a promise about how out of date it may be, and nobody wants to take that decision
on the day the brake trips. A failure is held for the same time, so a gateway that is down does
not make every page wait the full timeout. The timeout itself is `Gateway:Timeout`'s five seconds
([Admin Console](Admin-Console.md#the-client)).

### When the gateway cannot answer

The page always renders, and says which of these it is:

| The page says | Because |
|---|---|
| The gateway is not configured | `Gateway--AdminToken` is not in Key Vault ([Provisioning B3](Provisioning.md#b3-load-the-secrets)), so the console does not ask |
| The gateway does not report status yet | It lists its installations but answers `404` for `/admin/status`: it predates kf-ai-gateway#37. The console tells this apart from no admin surface at all by asking for its installations after the `404` |
| The gateway refused the console's admin token | `401`: the token is neither of the gateway's. It should be the gateway's `Admin__ReadToken` |
| The gateway refused what the console asked | `400`, naming the parameter. **A fault in the console, not an outage**: since kf-ai-gateway#38 the gateway refuses a parameter it does not have or cannot read, where an older one ignored it, and the console checks everything it sends and sends nothing else. Logged as an error, never retried; report it |
| The gateway has no admin surface | `404` for `/admin/installations` too: the gateway has no `Admin__Token`, so it maps no `/admin`, or `Gateway:BaseUrl` is not the gateway |
| The console could not reach the gateway | No answer within five seconds, a network failure, an error status, or an answer that is not the status the console expects. The page gives the detail |

[Operations](Operations.md#a-licences-installations-or-the-gateways-status-are-missing) has what to
do about each.

## The home page's card

The console's overview carries one card for the gateway, after the register's figures: whether it
answers and at what version, the brake in one line (off, a percentage, or tripped), and how many
installations are active and were seen in the last day, with a link into the area. It is the
gateway area's `GatewayOverview` view component, so the shell's home page does not know there is a
gateway, the same way it does not know what a licence is
([Console Shell](Console-Shell.md#adding-a-feature)). When the gateway cannot answer, the card says
why, in the words above.

## Installations

**AI Gateway → Installations** (`/Gateway/Installations`, [#65](https://github.com/KnowledgeFabric/kf-admin/issues/65))
is the way from an installation id, off a support call, a kf-app log or the gateway's own log, to
what the gateway holds of it and the licence the register issued for it: the reverse of a register
row's *Installations* ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). Before it,
that took `curl` and a token, and the two numbers the call is about, what the installation is
allowed and what it has used, were on no page at all: kf-ai-gateway `docs/API.md`, *Self*, is the
installation's own view of them, which the customer sees and we do not.

### The list

Every installation the gateway has enrolled, 25 a page, newest first, **filtered, ordered and paged
by the gateway** (kf-ai-gateway#38): the console sends the question and shows the answer, and the
total comes from the gateway's `X-Total-Count`.

| Filter | Asks the gateway |
|---|---|
| Row: evaluation, standard, enterprise | `row=`: the allowance row it is served, not the wire tier |
| Status: active, revoked | `status=` |
| Last seen: in the last day, week or month | `seen_since=`, that long before now, in UTC with a `Z` |
| Last seen: longer ago than a month | Not a gateway filter, which has `seen_since` alone. Ordered by last seen, the installations seen in the last month come first, so the console counts them with `seen_since=…&limit=1` and pages past them with `offset=`. Always in order of last seen |
| App version below | `app_version_below=`: what the minimum-version lever would refuse at that version, read as the gateway reads versions. One that does not read as a version is said on the page and not sent |
| Installation id or licence id | An id, whole. Asked first as an installation's, `GET /admin/installations/{id}`, and opened when it is one; otherwise as a licence's, `licence_id=`, which lists every installation holding it, revoked or not, however old, whole and unpaged |
| Order: newest enrolled, last seen, tokens used | `sort=created`, `last_seen` or `tokens_used`, the three the gateway offers |

Each row has the installation id, short and linked to its page with a button that copies it whole;
its row; its status, with when it was revoked; app version; first enrolled; last seen; tokens used
against its limit as a bar; and its licence, which is one of:

- **The register's customer** for its licence id, from the latest file of that id, linked to it.
- ***Not in the register***: the gateway holds an id the register does not, a licence issued
  offline without `--register-csv` or by kf-app's copy of the tool before kf-app#982 deleted it (the
  reasons [#58](License-Register.md#installations) gives).
- ***Licensed, id not recorded***: on a licence tier with no id. It was licensed before
  kf-ai-gateway#35 recorded ids, and has one once kf-app sends its licence again. Calling it *No
  licence* would be wrong: it is served a licence row.
- ***No licence***: on evaluation.

### One installation

`/Gateway/Installations/{id}` reads `GET /admin/installations/{id}`, one installation with its
allowance, and says:

- **On the gateway**: the id, app version, the wire tier and the row it is served, status with when
  it was revoked, first enrolled and last seen. Not the credential: the gateway does not return it,
  and nothing here asks for it.
- **Allowance and usage**, the numbers the installation's own `GET /v1/installation` reports at the
  same instant, read by the same code, so they are what the customer's AI Manager screen shows.
  Requests a minute, as the limit, what remains of the window and when it next frees a request;
  tokens, as the limit, what the current period has used, as a bar, and when the period ends; and
  the longest reply. Each says whose it is, from `from_licence`: *"120 a minute, the standard
  row's"*, *"10,000,000 a calendar month, the standard row's"*, *"2,000,000 per 30 days, the
  licence's"*, or, when a licence set one and left the other to its row, *"2,000,000 a calendar
  month: the number the licence's, the period the standard row's"*. The request window is held in
  the gateway's memory, so a restart reads it full again. A limit of `0` from the licence is one it
  carried and the gateway could not read, which allows nothing, and the page says so.
- **Revoked is served nothing.** A revoked installation still reports an allowance, what it would
  be served if restored (kf-ai-gateway `docs/Admin.md`), and the page says above it that it is served
  nothing while revoked, and has been refused `403 installation_revoked` since when.
- **Its licence**: the register's latest file of its licence id, with customer, purpose, tier and
  expiry, linked to the register row and counting the files when a reissue made more than one;
  *Not in the register*, with the reasons above; *Licensed, id not recorded*; or *No licence*, with
  the gateway's `licence.reason` when it refused the licence it was last sent. When the gateway's
  `licence_holders` says more than one installation that has not been revoked holds the id, the
  section is flagged, and links to the list of them.
- **What to do about its allowance**: a customer's allowance changes by reissuing their licence
  with the numbers it should carry, with *Reissue* into the issue form
  ([#42](https://github.com/KnowledgeFabric/kf-admin/issues/42)) when the register has the row.
  Never an edit control: what a licence leaves out is its row's, which is policy, and a
  per-installation override is not a lever (kf-ai-gateway `docs/Admin.md`).
- **Revoke or restore**, one button, to [the confirm step](#revoke-and-restore) (#69). It is
  disabled, saying why, when the console has no write token or the session does not hold
  *Gateway: Write*. After a change the page says so and links to its audit entry.
- **Usage history** (#70): its last 90 days of tokens, and of requests split into answered, failed
  upstream and refused by each of its limits, with a choice of 30, 90, 180 or 365 days
  ([Usage history](#usage-history)).

**The row's period is not on the wire.** `from_licence.period` is the licence's, in the licence's
own words, `month` or `30d`, as kf-admin writes `ai.period`, not the gateway's `calendar_month` or
`rolling_30_days`. When the licence leaves it out, the period is its row's, which `/admin` does not
name, so `Areas/Gateway/Models/AllowanceWords.cs` reads it from `tokens.reset_at` by the two rules
kf-ai-gateway `docs/API.md` publishes, *Tiers and policy*: a calendar month is the UTC month, so it
ends at midnight on the 1st, and a rolling thirty days is counted from first enrolment in whole
periods. An instant both rules fit is *"a period"* rather than a guess. The gateway reports its
rows since kf-ai-gateway#39, which the [policy page](#policy) reads, so the row's period could be
read from `GET /admin/tiers` instead; the installation pages do not do that yet.

### What they read

`GET /admin/installations`, with only the parameters the page asks for and never anything else,
and `GET /admin/installations/{id}`, both with the read-only token. From each row, besides what the
register's pages read ([Admin Console](Admin-Console.md#the-client)), `licence_holders`, `licence`
and `allowance`, into `Gateway/GatewayInstallation.cs` in their snake_case wire names:

| Field | Shown as |
|---|---|
| `allowance.row` | The row it is served |
| `allowance.requests.limit`, `.remaining`, `.reset_at` | Requests a minute |
| `allowance.tokens.limit`, `.used`, `.reset_at` | Tokens a period, and the bar |
| `allowance.max_predict_tokens` | The longest reply |
| `allowance.from_licence.tokens`, `.period`, `.rpm` | Whose each number is |
| `licence.status`, `licence.reason` | Why an installation on evaluation has no licence |
| `licence_holders` | The shared flag on one installation's page |

Every field is optional and unknown fields are ignored, as for the status. **Paging uses the
gateway's `offset` and `X-Total-Count`**, with `limit=25`. A licence's installations are asked for
whole: `licence_id=` ignores `limit` and honours `offset`, so the console sends neither with it.

### Against an older gateway

The pages still render against a gateway from before kf-ai-gateway#38, which is told apart by the
`X-Total-Count` it does not send:

- **The list** shows its newest installations, unpaged, with the usage column saying it is not
  reported and the row column its wire tier. A filter, an order or a page it would have ignored is
  *The gateway does not filter its installations yet*, rather than its newest installations shown as
  though they matched. A licence id it has filtered since #35.
- **One installation** has no endpoint there, which answers `404` for every id. The console looks
  for it among the newest 500 the list returns instead, and its page says the gateway does not
  report usage yet.
- **Before kf-ai-gateway#35** no row has a licence id, so a licensed installation reads *Licensed, id
  not recorded*.

### When the gateway cannot answer about an installation

As for the overview, [above](#when-the-gateway-cannot-answer), and one more:

| The page says | Because |
|---|---|
| The gateway knows no installation with this id | `404` for one installation from a gateway that has the endpoint. It enrols on first use of AI, so one that never has is not there, and an id from another environment is on that environment's gateway |

[Operations](Operations.md#an-installation-you-expect-is-not-listed) has what to do when an
installation you expect is not listed at all.

## Usage by licence

**AI Gateway → Usage by licence** (`/Gateway/Usage`, [#66](https://github.com/KnowledgeFabric/kf-admin/issues/66))
puts every licence in force beside what its installation has used and has left. The register
knows what each licence *says*: its tier, its expiry and the `ai.tokens`, `ai.period` and `ai.rpm`
it carries or leaves to its row. The gateway knows what each installation is *served* and has
*spent*. Neither alone answers the questions this page is for:

- which customers are near their allowance;
- which use far less than they bought;
- which licence's installation has never enrolled;
- whether each licence is served what the register says it carries, and so whether raising the
  enterprise row will reach the customers it is meant for.

### The page

One row per licence id **in force** in the register, by the overview's rule: in force when any of
its files is, named by its latest file in force, and covered until the last of their expiry dates
(`RegisterSummary.InForce`, [License Register](License-Register.md#the-overview)). A reissue keeps
the id, so a renewed licence is one row. Beside it, every installation the gateway holds with that
id, one line each:

| Column | From |
|---|---|
| Customer, with its company, linked to the register row of its file in force | The register |
| Purpose, with the register's badges; a filter leaves internal and demo out | The register |
| Allowance: a filter keeps the licences whose tier chooses `standard` or `enterprise`, by rule 10 of [License Entitlements](License-Entitlements.md), so `standard` takes a tier of none or one the gateway does not know. The [policy page](#policy) links here for each licence row | The register |
| Tier and expiry | The register |
| Installation: its id, short and linked to its page, and when it was last seen. *Not enrolled* when the gateway holds none | The gateway |
| Tokens used this period against the limit, as a bar and a percentage, with whose each number is and when the period resets | The gateway's `allowance.tokens` and `from_licence`, in the words [One installation](#one-installation) uses |
| Tokens last month: what it spent in the calendar month before this one, in UTC, headed with the month's name, so a licence's trend shows beside this period | The gateway's daily usage ledger ([#70](#usage-history)) |
| Requests a minute, with whose it is | The gateway's `allowance.requests` |

Ordered by the share used, most first by default: a licence's share is the largest any installation
holding it has used. The other orders are least used first, where a licence no installation holds
comes first because "bought and never used" is what that order is for, expiring first, and by
customer.

Three flags, each counted in the table's heading:

- **At 80% or more** of its token budget this period.
- **On more than one installation** that has not been revoked: the rule is one
  ([#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)), and the register row's page says
  what to do.
- ***Served otherwise*** than the register's file in force says, with why beneath the installation:
  - It is served another row than the licence's tier chooses. That is how an Enterprise customer
    licensed before kf-ai-gateway#32 shows: served `standard` until their licence is sent again,
    and missed by a raise to the enterprise row.
  - It holds a file with another expiry. That is a renewal that has not reached the gateway.
  - With the same expiry, its licence's AI limits differ from the register's file. That is a
    correction that has not reached the gateway.

A revoked installation is listed, marked, and served nothing: it counts toward none of the three
flags, and a licence whose only installation is revoked is enrolled, not *Not enrolled*.

Beneath the table the page says, once, where the gateway sees less than the register. An
installation enrols on its first use of AI. kf-app 1.6.2 sends its licence only when it first
enrols, and kf-app#968, which sends it on every install, is in no release yet (#61). It also counts
the licensed installations the page cannot place: those with no licence id recorded, licensed
before kf-ai-gateway#35, and those holding an id with no licence in force in the register.

### The export

**Export CSV** writes the rows the page shows, in its order and under its filter, one line per
installation and one for a licence none holds:

```
licenseId,customerName,company,purpose,tier,expiration,installationId,status,lastSeenAt,tokensLimit,tokensUsed,tokensResetAt,requestsLimit,row,tokensLastMonth
```

The register's columns come first, named as its own export names them, with `expiration` the
licence's covered-until date. The gateway's follow. `status` is `active` or `revoked`, added to the
columns #66 lists so a revoked installation's line is not read as one being served.
`tokensLastMonth` came with #70, last so the columns before it stay where they were, and is empty
when the gateway keeps no history. Fields are
quoted, and guarded against spreadsheet formulas, as the register's export is. Each export writes
one audit entry, `gateway:usage-export`, with the filter and the number of licences and lines,
because every customer's name beside what they spend is worth a line even though it changes
nothing.

There is no export while the gateway cannot answer: without its columns every licence would read as
not enrolled. The button is not shown, and the address sends you back to the page, which says why.

### What it reads

- **The register**: every row's summary, one query with no XML, the attributes included because
  they carry `purpose` and the AI limits. The join is in memory: a register of a few hundred rows
  makes that cheap.
- **The gateway**: `GET /admin/installations?row=standard&limit=500` and `?row=enterprise&limit=500`,
  each walked with `offset=` until the gateway's `X-Total-Count`, matched to the register by
  `licence_id`. The `evaluation` row, most of the fleet, is not read: the gateway clears an
  installation's licence id when its licence lapses or is removed (kf-ai-gateway `docs/Admin.md`,
  *One licence on more than one installation*), so none there holds one. A fleet of hundreds is one
  request a row. The client stops at twenty pages a row, ten thousand installations, and the page
  says so rather than walking the gateway for a minute.
- **Last month**, from the ledger ([Usage history](#usage-history)): one
  `GET /admin/usage/summary` for the previous calendar month with `limit=50`. While fewer than fifty
  installations made a request that month, its top list is all of them, and one missing from it
  spent nothing. Past that, each listed installation missing from the top fifty is asked about on
  its own, `GET /admin/usage/daily?installation_id=`, four at a time and at most a hundred a page;
  the page says how many it did not ask about.

Against a gateway from before kf-ai-gateway#38, which would have ignored `row=`, the page lists
every licence with the register's columns and says the gateway does not report usage yet. Every
other failure is [the overview's](#when-the-gateway-cannot-answer), in the same words, and leaves
the register's columns filled.

### On a register row

A register row's *Installations* ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58),
[License Register](License-Register.md#installations)) gains the same numbers for each installation
holding the licence: the row it is served, tokens used this period against the limit with whose it
is and when it resets, and requests a minute. A customer's page answers "how much have they used"
without leaving it. It reads `licence_id=` as before, whose rows carry `allowance` since
kf-ai-gateway#38, so there is no extra request.


## Usage history

The rest of these pages say what is being spent now: the status this month, an installation this
period. Neither says what was spent before, because the gateway forgot each figure when its period
rolled. Its **daily usage ledger** keeps it ([kf-ai-gateway#41](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/41),
`docs/Admin.md`, *Usage history*): one row per installation per UTC day, with its tokens, its
requests, and, as parts of them, requests refused `429 rate_limited`, requests refused
`429 token_budget_exhausted`, and chats the provider failed. The console reads it
([#70](https://github.com/KnowledgeFabric/kf-admin/issues/70)) for the questions a month later: is
the fleet's spend growing, did this customer's usage fall off after a complaint, how often is anyone
hitting a `429`, is the upstream erroring more since the provider changed.

### Where it shows

- **The overview**: the fleet's last thirty days, tokens a day stacked by row, and refusals a day.
- **An installation's page**: its last 90 days, or 30, 180 or 365, of tokens, and of requests split
  into answered, failed upstream and refused by each limit, so the parts add up to the requests.
- **Usage by licence**: each installation's tokens in the calendar month before this one, beside
  this period's, and in the export.
- **AI Gateway → Usage history** (`/Gateway/Usage/History`): a chosen range, the last thirty days
  unless another is picked, typed or chosen from the presets (the last 7, 30, 90 and 365 days, this
  month and last month). The range's totals; tokens a day by row; the same totals by row, with each
  row's share of the tokens; and its top 10, 25 or 50 installations by tokens, each linked to its
  page and, for one on a licence row, to the register's row for the licence it holds.

The charts are ApexCharts, drawn by `wwwroot/js/gateway-usage.js` from numbers the server writes
beside each (`Areas/Gateway/Models/UsageChart.cs`), each series naming its colour in
`window.config.colors`, so the palette rule holds. A row has the colour the overview's cards give
it: `evaluation` secondary, `standard` success, `enterprise` warning.

### What the numbers are

- **UTC days, both ends included, today so far.** Tokens count on the day a chat ended, as it ends.
  Requests, refusals and upstream errors are counted in the gateway's memory and written once a
  minute, so the last minute is not there yet. A process that dies without shutting down loses up
  to a minute of them, never tokens.
- **A day with nothing counted is zero.** The gateway answers every day of a range; one it left out
  would be drawn at zero all the same (`GatewayUsageDailyAnswer.Fill`). Every day before the ledger
  existed, 2026-09-27 on the deployed gateway, is zero.
- **Rows are the rows installations are served now.** The ledger keeps counts, not rows, so an
  installation that bought a licence during a range counts under its licence's row from the first
  day of it. An installation deleted from the gateway by hand still counts in the totals and in no
  row: the range page lists it as *No longer on the gateway*.
- **At most 366 days a question**, a leap year whole. The range page says so of a longer range and
  never sends it, as it never sends a backwards one or a date it cannot read: the gateway would
  refuse each with a `400`, which would be the console's bug.

### The exports

The range page has two, each one audit entry, `gateway:usage-history-export`, with what was
exported, the range and the number of lines:

- **Days**, one line a day, oldest first:

  ```
  day,tokens,requests,refusalsRateLimited,refusalsBudgetExhausted,upstreamErrors,evaluationTokens,…,enterpriseUpstreamErrors
  ```

  the fleet's five counts, then the same five for each row.
- **Top installations**, in rank:

  ```
  rank,installationId,row,licenseId,customerName,tokens,requests,refusalsRateLimited,refusalsBudgetExhausted,upstreamErrors
  ```

  `licenseId` and `customerName` for one on a licence row whose licence the register holds.

### What it reads

- `GET /admin/usage/daily?from=<date>&to=<date>`, the fleet's days split by row, for the overview
  and the range page's chart; with `&installation_id=<id>`, one installation's.
- `GET /admin/usage/summary?from=<date>&to=<date>&limit=<n>`, for the range page and usage by
  licence's last month.
- For a top installation on a licence row, the licensed installations' list and the register's
  summaries, to name its licence, as usage by licence reads them.

All with the read-only token, and nothing else: no parameter the page did not ask for. The names
are in `Gateway/GatewayUsage.cs` and nowhere else.

**Against a gateway from before kf-ai-gateway#41**, which answers `404` for `/admin/usage` while its
installations answer, every place history shows says the gateway does not keep usage history yet,
and everything else on the page is as it was: the overview's status and fleet, an installation's
allowance, usage by licence's columns and its export, with *Tokens last month* empty. Every other
failure is [the overview's](#when-the-gateway-cannot-answer), in the same words.

## Policy

**AI Gateway → Policy** (`/Gateway/Policy`, [#67](https://github.com/KnowledgeFabric/kf-admin/issues/67))
is what the gateway is allowing now. Its policy lives in its database so that it can change without
a deploy, which also meant that what it allowed was known only to whoever last ran the `UPDATE`.
The page shows the rows as they stand, and beside each what it reaches. Each row and lever has a
**Change**, which [#71](https://github.com/KnowledgeFabric/kf-admin/issues/71) added
([below](#changing-policy)); without the write token, or for a session without *Gateway: Write*, it
is shown disabled and says why.

### Tier allowances

The three rows, `evaluation`, `standard` and `enterprise`, each with requests a window, the token
budget and its period, and the longest reply. Beside each are two counts:

- **Installations served**, the gateway's own count of active installations on the row, linked to
  the installations list filtered to them. It is whom a change reaches.
- **Licences in force**, for `standard` and `enterprise`, the register's count, linked to
  [usage by licence](#usage-by-licence) filtered to them. A licence is counted on the allowance its
  tier chooses, by rule 10 of [License Entitlements](License-Entitlements.md): `enterprise` for a
  tier of exactly that, and `standard` for any other, none included. Every purpose counts.

The licences in force are what the only-goes-up rule protects: while any licence on a tier is in
force, its allowance is raised and never lowered
([License Entitlements](License-Entitlements.md#the-ai-allowance-per-tier)). The gateway cannot
apply it, because it sees only the licences that enrolled, so the count comes from the register,
and the change form applies it ([below](#the-only-goes-up-rule)). Under the rows the page says so, and that the two licence rows
started equal, as copies of the gateway's single former licence row (kf-ai-gateway#32), until
`enterprise`'s numbers are decided. It also gives the status's count of licensed installations with
no licence tier recorded. Those are served `standard` whatever their licence says, so a raise to
`enterprise` does not reach an Enterprise customer among them until kf-app sends their licence again.

Each field carries a short explanation, taken from kf-ai-gateway `docs/Admin.md`, so the page says
what the `UPDATE` statements assumed an operator knew.

### Gateway levers

- **Minimum application version.** The oldest kf-app version that may enrol; below it, `426
  app_version_unsupported` at the next enrolment. Beside it, two counts of active installations,
  each the gateway's own answer to `app_version_below=`, linked to the installations list:
  - those below the minimum as it stands, which would be refused when next they enrol;
  - those below kf-app's current release (`LicenceValidator.ProductRelease`, 1.6.2), which is what
    raising the minimum to it would refuse. It is shown only while the minimum is below the release.

  #67 asked for the count below "the next version up"; the current release is the version a
  minimum is most often raised to, so that is the one asked. Any other version is the installations
  list's *App version below*. A minimum that does not read as a version admits everyone. Only
  `psql` can write one, and the page says so.
- **Enrolment velocity limit.** Off or armed, with its numbers, and kf-ai-gateway `docs/Admin.md`'s
  warning. The gateway reads the caller's address from what the App Service front end appends to
  `X-Forwarded-For`, which has never been checked against a real response. The evidence the warning
  asks for is on the page: the address the gateway attributed to the console's own request
  (`caller.address` on the status). It should be one of `app-kf-admin`'s outbound IP addresses,
  listed under the App Service's *Properties*. If it is the platform's front end, a private address
  or `unknown`, do not arm the limit.
- **Global token ceiling.** The number, or *No brake*, with this month's spend against it from the
  status and a banner when the brake is on. [The overview](#the-overview) has the brake in full.

### What it reads

- `GET /admin/tiers` and `GET /admin/policy` (kf-ai-gateway#39), with the read-only token, on
  every load and never cached, so a change made on the gateway shows on the next one. Their names
  are in `Gateway/GatewayPolicy.cs` and nowhere else.
- `GET /admin/status`, through the thirty-second cache the overview shares, for the brake and the
  caller's address.
- `GET /admin/installations?app_version_below=<version>&status=active&limit=1`, once or twice, for
  the version counts, read from `X-Total-Count`.
- The register's summaries, for the licences in force.

The status or the register failing leaves the rest of the page, and says what is missing. Against a
gateway from before kf-ai-gateway#39, which answers `404` for `/admin/tiers` while its installations
answer, the page says the gateway does not report policy yet. That is told apart from a gateway with
no admin surface as the status is. Every other failure is [the overview's](#when-the-gateway-cannot-answer),
in the same words.

## Revoke and restore

The console's first write to the gateway ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)).
Revoking is the one thing the gateway's `/admin` always did, and the one thing the register's shared
flag told an operator to do with `curl` and a token. It is now a button on an installation's page,
and beside each installation when a register row flags its licence as shared. It is kept to revoke
and restore so that what every later write reuses was reviewed on the smallest action: the write
token, the durable audit log and the confirm step. Policy edits ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71))
build on it.

### The confirm step

`/Gateway/Installations/{id}/Revoke` and `/Restore` show the installation as the gateway holds it
now, with its licence from the register, and what the change does, in the gateway's words:

- **Revoke**: every call it makes is refused `403 installation_revoked` from its next one, and
  re-enrolling does not get round it, because a new credential it enrols for is refused too. It
  stops counting as holding its licence, so a shared flag clears when it was the second holder.
  When it is the only installation holding a licence the register issued, the page says the
  customer's AI stops.
- **Restore**: it is served its row again from its next call, with the credential it has.

The form asks **why**, 3 to 500 characters, kept in the audit entry. **Who** comes from the sign-in:
a session under a name of its own (#68) is recorded, here and on the gateway, under that name. A
session under the shared password names no one, so before #88 the form asked for a name, recorded as
`ClaimedActor` on an entry that stayed unattributable and sent to the gateway as
`"<name> (shared password)"`. Since #88 such a session holds no role and reaches neither the page
nor the write, and since #89, which retired the shared password, there is no such session; the
entries written that way still read as they did.

The `POST` needs `gateway:write` (*Gateway: Write*, #88) and the form's anti-forgery token: a
bare `POST` is refused `400`. It reads the installation again before writing, and does not revoke
one already revoked, or restore one that is active. The page says so and offers the other.

### What it sends, and what it records

`POST /admin/installations/{id}/revoke` or `/restore`, with the write token, `Gateway--AdminWriteToken`
(the gateway's `Admin__Token`), and `X-KF-Operator` naming the operator, which the gateway's own
audit line records (kf-ai-gateway#39). Reads never carry the write token.

**The audit entry is written after the gateway confirms, with its answer:** `gateway:revoke` or
`gateway:restore`, the installation id as the target, and in the details its licence id, the
register's customer, the reason, the operator as sent, and the status and revocation instant the
gateway returned. A write that did not go through writes no entry.

| The confirm step says | Because |
|---|---|
| The console has no write token | `Gateway--AdminWriteToken` is not in Key Vault. Nothing is sent, and every write control on every page says the same |
| You can view this, not do it | The session's name holds *Gateway: View* and not *Gateway: Write* (#88) |
| The gateway refused the console's write token | `403`: it knows the token and does not let it write, so the slot holds its read token |
| The gateway refused the console's token | `401`: neither of its tokens |
| The gateway no longer knows this installation | `404` on the write |
| The gateway refused what the console sent | `400`, naming the field or header. A fault in the console |
| The console could not tell whether the gateway made the change | A timeout or another status. The change may have been made: the installation's page says its status |

[Operations](Operations.md#a-revoke-restore-or-policy-change-does-not-go-through) has what to do about each.

### The audit log

Every entry the console writes is now a row in `audit_entries`, beside the register, as well as the
log line it always was ([Console Shell](Console-Shell.md#authorisation-audit-and-storage-are-seams-before-they-are-features)).
**Audit log** in the menu (`/Audit`) lists them newest first, 50 a page, filtered by action and by
target, where part of an installation or licence id is enough: every person's to an Administrator,
and one's own to anyone else ([#99](https://github.com/KnowledgeFabric/kf-admin/issues/99)). The first revoke is therefore the
first durable write entry, not the first lost one.

## Changing policy

Every lever kf-ai-gateway `docs/Admin.md` used to change with an `UPDATE` in a Cloud Shell has a form
here ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)): raising `enterprise`'s
allowance for every Enterprise customer at once, retiring an application generation, arming the
enrolment brake, releasing the global one. Each has a rule the `UPDATE` could not enforce and a
consequence the operator had to know, and both are on the form. The `PUT`s are kf-ai-gateway#39's,
and the `psql` statements in its `docs/Admin.md` are now the fallback for a gateway without an admin
surface.

### Two steps

Each change is the pattern revoking an installation set (#69):

1. **The form** (`/Gateway/Policy/Tiers/{tier}`, `/MinimumVersion`, `/Velocity`, `/Ceiling`), with
   the lever as the gateway holds it now. What is typed is checked as the gateway checks it, so a
   refusal from the gateway is rare: every number whole and at least one, a period one of the
   gateway's two words, a minimum that reads as a version. Numbers may be typed with their thousands
   separated, `50,000,000`.
2. **The review**: the change whole, before and after, and whom it reaches. It asks **why**, and,
   under the shared password, **who**, exactly as the revoke step does, and only this step writes.

Before writing, the console reads the gateway again. If the lever changed there since the review was
shown, nothing is written and the review is shown again against the row as it stands, so a change
made with `curl` meanwhile is not written over. The `POST`s need `gateway:write` and the form's
anti-forgery token, and a failure is the confirm step's, in [the revoke table's](#what-it-sends-and-what-it-records)
words, with a `404` meaning a gateway from before kf-ai-gateway#39.

### The only-goes-up rule

The gateway does not refuse lowering `standard` or `enterprise`: it cannot tell whether a licence on
either is in force (kf-ai-gateway `docs/Admin.md`, *Raise a licence tier's allowance*). The register
can, so the console applies the rule
([License Entitlements](License-Entitlements.md#the-ai-allowance-per-tier)). While the register holds
a licence in force on a licence row, by rule 10, or cannot be read, the form refuses a change that
gives less, and says how many licences, linked to them in [usage by licence](#usage-by-licence).
Less is read lever by lever (`AllowanceRule`):

- **Requests are a rate**, what the tier's table promises a minute: fewer requests, or the same
  number over a longer window, is less. More over a proportionally longer window is not.
- **A smaller token budget** and **a shorter longest reply** are less.
- **The period is not moved at all.** A calendar month is longer than thirty days in some months and
  shorter in February, so neither word is more than the other, and the licences in force were issued
  against the one the row holds.

Raising is always allowed. `evaluation` is free, because no licence is served it, and so is a licence
row once no licence on it is in force: an expired licence, or a register with none on the tier, lets
a lowering through.

### Tier allowances

The form has the row's five levers: requests, the window they are counted over, the token budget,
its period and the longest reply. The review shows each before and after, the gateway's
`installations_served` for the row, and, on a licence row, the register's licences in force.
A change is felt on the next request: lowering the requests refuses an installation already past the
new number at once, and raising them releases one waiting at the old number.

### The minimum version

The review lists every active installation the new minimum would refuse the next time it enrols, by
the version it last reported, as the gateway counts them (`app_version_below=`, walked like the usage
by licence's rows). It is the lever's fleet in view, and the review is not offered without it: if the
gateway does not answer that question, the change waits until it does. A value that does not read as
a version is refused on the form; set with `psql`, it would admit everyone.

### The enrolment velocity limit

Off, or armed with an hourly number, a daily one or both, the hourly no higher than the daily. Arming
it from off needs a tick saying the address was checked, beside `caller.address`, the address the
gateway attributed to the console's own request, which is the check `docs/Admin.md` demands before
the limit is armed. Changing the numbers while it is armed, or turning it off, needs none.

### The global ceiling

A number of tokens a calendar month, or no brake. The form shows this month's spend and whether the
brake is on, read afresh from the status rather than through the cache, and the review says what the
new ceiling does to the brake: releases it, leaves it on because the spend is at or above the new
ceiling too, trips it because the spend already is, or leaves the headroom it gives. **Raising the
ceiling is the whole of releasing a tripped brake**, and the page says so. The month's spend is the
gateway's record of what was spent, not a lever: the form never offers it and the `PUT` never
carries it. After a change the status cache is dropped, so the overview's banner follows at once
rather than within thirty seconds.

### What it sends, and what it records

`PUT /admin/tiers/{tier}` with the row's five levers, or `PUT /admin/policy` with the whole
gateway row: the gateway refuses a missing field rather than reading it as null, because null turns a
lever off. Each policy form changes its own lever and sends the other three as the gateway holds them
at that moment. If one of those was written with `psql` and would not be taken back, such as a minimum
that is not a version, the form names it and sends nothing: change that lever first. The write token
and `X-KF-Operator` go as they do for a revoke; the names are in `Gateway/GatewayPolicy.cs`.

**The audit entry is written once the gateway confirms:** `gateway:tier` with the tier as its target,
or `gateway:policy` with `gateway`, the gateway's own target for the row. Its details hold the row
before and as written, in the gateway's wire names, the fields that moved, the reason and the
operator, and what the change reached: installations served and licences in force for a tier; the
lever, and for the minimum how many installations it refuses, for the ceiling the spend and whether
the brake was on, for the velocity limit the caller address and the tick.
</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.

## 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.
</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
  apply to every AI call the installation makes. Blank means the gateway's allowance for the
  licence's tier, or Standard's when it has none. Both tiers' allowances are the same until product
  management sets Enterprise's, which is raised at the gateway without reissuing anything
  ([#46](https://github.com/KnowledgeFabric/kf-admin/issues/46)). Type numbers only for a deal that
  includes more than its tier's.
- **The employee figure is an allowance, not a limit**
  ([#44](https://github.com/KnowledgeFabric/kf-admin/issues/44)). The product tells the customer's
  administrator when there are more employees, but refuses nothing and leaves nobody out of an
  analysis. Nothing reports the count back to us, so it is settled at renewal by asking.

> [!NOTE]
> **Both readers enforce the entitlement.** kf-app reads it since kf-app#985 (`c332de4`), and the
> AI Gateway applies its AI limits since kf-ai-gateway#28 (`ebb48b3`). A kf-app build from before
> kf-app#985 still gates each area on the five area keys #38 removed, so a licence issued now opens
> nothing there. kf-app 1.6.2, the current release, sends its licence to the gateway only when it
> first enrols, so there a licence uploaded after the installation first used AI does not change its
> AI allowance; kf-app#968, on `develop` and not yet released, sends it on every install. The
> validate page says what each reader will do with a licence.

Until a console-issued licence has been confirmed installing on a current kf-app build — #6's
acceptance — check the first few against [steps 5 and 6](#5-check-it-before-it-leaves) with
particular care.

## Before you start (the CLI)

This CLI is the only issuing code outside the console: kf-app's copy of the tool was deleted by
kf-app#982 ([Relationship to kf-app](README.md#relationship-to-kf-app)). Prefer the console, which
records what it issues; offline, add `--register-csv`.

You need:

1. **The .NET 8 SDK** — `dotnet --version` should report 8.x.
2. **The signing private key and its passphrase** — see [Key custody](#key-custody). For a licence
   that must work on a stock installation, this has to be the established KnowledgeFabric key, not a
   fresh one.
3. **A config file** for the licence — see [License Config Schema](License-Config-Schema.md).

## Key custody

> The private key is what makes a licence a licence. Anyone holding it and the passphrase can mint
> unlimited licences for any customer, for any duration, with every feature enabled. There is no
> revocation.

- **Never commit a private key or passphrase to this repository, or to any repository.**
- **Only the public key and the `.lic` file go to the customer.** Never the private key.
- The public half of the signing keypair is *not* a secret. It is compiled into the application
  image, committed in kf-app's `appsettings.Development.json`, and published in kf-app's docs.
- `gen-keys` refuses to overwrite existing key files, and says so rather than failing — a guard
  against silently replacing the keypair every issued licence depends on.

### Which key to sign with

A stock installation trusts the public keys **compiled into the image**
(`BundledLicensingSettings.PublicKeys` in kf-app's
`KnowledgeFabric.Logic/Services/Licensing/LicensingOptions.cs`, `c332de4`) — today a list of one,
the established key. This has a direct consequence:

- **Sign with the established private key** → the licence validates on any installation, with no
  configuration on the customer's side. This is the normal path.
- **Sign with a fresh `gen-keys` keypair** → the licence validates *only* where the customer also
  sets `LicensingSettings__PublicKey` to the matching public key. Use this only deliberately. That
  key is trusted *beside* the compiled ones, not instead of them (kf-app#983), so the installation
  still accepts licences signed with ours too.

Generating a new keypair does **not** invalidate existing licences — each is verified against the
keys the installation trusts, and those are unchanged. Rotating the *bundled* key is a release, not
an incident: ship a kf-app image and a gateway release trusting old and new, then sign with the
new. It is still not routine, because it is a release in two repositories and the gateway's must go
out first — see [Operations](Operations.md#rotating-the-key-pair).

## Step by step

### 1. Build

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

The tool lands at `src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/LicenseTool.dll`. Run it with
`dotnet <path>/LicenseTool.dll`, or use the `LicenseTool` / `LicenseTool.exe` apphost beside it.

The build is warning-free, so a warning is news.

### 2. Generate a keypair — only if you actually need a new one

Skip this for an ordinary customer licence; use the established key instead.

```bash
dotnet LicenseTool.dll gen-keys --passphrase "<passphrase>" --output ./keys
```

| Option | Required | Default |
|---|---|---|
| `--passphrase` | Yes | — |
| `--output` | No | current directory |

Writes `private.key` (passphrase-encrypted, PKCS#8) and `public.key` (base64 ECDSA P-256). If either
file already exists it writes neither, says `Key files already exist in …` on stderr and exits `1`.

### 3. Write the config

Copy `src/KnowledgeFabric.LicenseTool/config/license_config_template.json` and fill it in. Give
either an `expiration` with an explicit offset (`...T23:59:59Z`) or a `duration` (`P1Y`); set `tier`
if the customer bought a plan. The tool refuses a date with no offset, both or neither of
`expiration` and `duration`, an unknown tier and a reserved attribute name, all in one message. Every
field: [License Config Schema](License-Config-Schema.md).

One thing to get right, because it will not be flagged:

- **Check each entitlement field's name against [License Config Schema](License-Config-Schema.md#the-entitlement).**
  A misspelled *name inside* a list is refused, but a misspelled *field* — `"report"` for
  `"reports"` — is ignored, and that section grants nothing.

And one to know: **only the gateway enforces `validFrom`**, so a future-dated licence unlocks the
product as soon as it is installed, while the gateway keeps that installation on `evaluation` until
the licence is sent to it again after the date.

**To renew offline**, write the file the console's *Reissue* would ([above](#in-the-console)): set
`licenseId` to the licence's id, so the register counts it as the same licence, and `expiration` to
the old file's expiry day plus the term — `2027-11-30T23:59:59Z` to renew a licence expiring on
30 November 2026 for a year. **Leave `validFrom` out**: the gateway would refuse the file until
that day. Use
`expiration`, not `duration`: a `duration` counts from the moment of issue, so an early renewal
would lose however early it is.

### 4. Generate the licence

```bash
dotnet LicenseTool.dll gen-license \
  --config ./config/license_config.json \
  --private-key ./keys/private.key \
  --passphrase "<passphrase>" \
  --output ./license.lic \
  --register-csv ./issued-licences.csv \
  --issued-by "<your name>"
```

| Option | Required | Default |
|---|---|---|
| `--config` | Yes | — |
| `--private-key` | Yes | — |
| `--passphrase` | Yes | — |
| `--output` | No, despite being declared required | `./license.lic` |
| `--register-csv` | No | — no row is written |
| `--issued-by` | No | the operating-system user |

The licence is written to `--output` and echoed to stdout. Missing parent directories are created.
An existing file at that path **is overwritten without warning**.

`--register-csv` appends one row describing the licence to that file, in the columns of the
console's register export, and says `Register row appended to:` when it has. A licence issued here
never reaches the console's register, so this file is its record — keep it with the licence files.
See [License Register](License-Register.md#where-rows-come-from).

### Running from Visual Studio

`src/KnowledgeFabric.LicenseTool/Properties/launchSettings.json` carries a `LicenseTool` profile for
this step. It holds no passphrase and no machine-specific paths: every argument comes from an
environment variable that Visual Studio expands at launch.

| Variable | Supplies |
|---|---|
| `KF_LICENSE_CONFIG` | `--config` |
| `KF_LICENSE_PRIVATE_KEY` | `--private-key` |
| `KF_LICENSE_PASSPHRASE` | `--passphrase` |
| `KF_LICENSE_OUTPUT` | `--output` |

Set them in your user environment — Visual Studio reads the environment as it starts, so restart it
after changing them. **Do not put the passphrase back into the profile**; the file is committed, and
the last one that was left there has to be treated as compromised
([#3](https://github.com/KnowledgeFabric/kf-admin/issues/3)).

`dotnet run --launch-profile LicenseTool` does **not** expand `%VAR%` — it passes the literal text
and the tool fails on a path it cannot find. From the command line, pass the arguments yourself as
above.

### 5. Check it before it leaves

The tool will still mint a licence that cannot possibly work — a misspelled entitlement field,
signed with the wrong key — without a word of complaint, and one that has already expired or grants
nothing with only a warning. So read the XML back:

- `Expiration` — the right instant, in GMT? With a `duration`, is it counted from the start you
  meant?
- `reports`, `features`, `sources` and `ai` — everything the customer bought named, and nothing
  missing that they did? Anything not named is not granted.
- `LicenseAttributes` — **no `TrialDays`**, or the product will refuse the upload.
- `Customer` — name and email actually filled in?
- Any `Warning:` on stderr.

Or upload it to the console's *Licensing → Validate a licence*, which checks the signature against
the key every product image trusts and shows both readers' verdicts. Then upload it to a test
installation and confirm the licensed areas open: that is the only check that exercises the product
itself.

### 6. Deliver

Send the customer the `.lic` file, and the public key **only** if the licence was signed with a
non-bundled key. Never send the private key.

## Exit codes

Every command reports failure through its exit status (#3), so a script can depend on it. Measured:

| Situation | Exit code |
|---|---|
| Licence generated successfully | `0` |
| Wrong passphrase, or `--private-key` is not a private key | `1` |
| Config file not found | `1` |
| Invalid `licenseType` / malformed JSON | `1` |
| A config that breaks the rules — `The licence config is not valid:` | `1` |
| Licence written, but `--register-csv` could not be appended to | `2` |
| `gen-keys` declining to overwrite | `1` |
| Missing a required option (`--config`) | `1` |

`2` is apart from `1` because the remedy is the opposite: the licence exists, so record it in the
register by hand rather than mint a second one.

## Failure modes

### From the tool

All messages are prefixed `License Generation Failed! ` on stderr, with the underlying error's
message on the next line when there is one.

| Message | Cause | Fix |
|---|---|---|
| `Could not decrypt the private key: the passphrase is wrong, or the file is corrupt.` + `pad block corrupted` | Wrong passphrase, or a `private.key` that is corrupt | Check the passphrase. It never means the *config* is wrong. Before #3 this showed as `pad block corrupted` alone. |
| `… holds a public key, not a private one.` | `--private-key` names `public.key` | Pass `private.key`. |
| `… is not base64.` | `--private-key` names something other than a key file | Pass `private.key`. |
| `Invalid JSON - Formatting/Syntax errors found.` + `The JSON value could not be converted to Standard.Licensing.LicenseType` | `licenseType` is not a type `Standard.Licensing` has — commonly `Enterprise`, or empty | Use `Standard`. |
| `Invalid JSON - Formatting/Syntax errors found.` + `'/' is an invalid start of a property name` | A `//` comment in the config | Remove it; JSON has no comments. |
| `The licence config is not valid:` followed by a list | A `licenseType` other than `Standard`, a date with no offset, both or neither of `expiration` and `duration`, a bad `duration`, `validFrom` not before the expiry, an unknown `tier`, a `licenseId` that is not a GUID, or a reserved name in `attributes` | Fix each item listed; every problem in the file is reported at once. See [License Config Schema](License-Config-Schema.md). |
| `License Configuration JSON file not found at path: …` | Bad `--config` | Check the path; relative paths resolve from the working directory. |
| `Private key file not found at: …` | Bad `--private-key` | Check the path. |

Note that the config template shipped before these docs failed **twice over** — an empty
`licenseType` *and* a `//` comment. Fixing only the comment still leaves the first error.

### From the product, after delivery

| Symptom | Cause |
|---|---|
| Upload refused as `unverifiable`, log says the licence *"is not signed by any key this installation trusts"* | Signed with a key the installation does not trust — usually a fresh `gen-keys` keypair instead of the established one — or the file was edited after signing (any edit breaks the signature) |
| Upload refused as `expired` | The licence has already expired |
| Upload refused as `trial-licence` | The licence carries a `TrialDays` attribute |
| Upload refused as `unsupported-schema` | The licence declares a `schemaVersion` the build cannot read. Nothing issued today does: every licence is version 1 |
| Upload refused as `not-yet-valid`, naming a start date | Its `validFrom` is still ahead, or cannot be read. kf-app refuses it rather than store it to wait, because installing a licence replaces the one in force (kf-app#979, on `develop` and not yet released; kf-app 1.6.2 installs it, in force at once). A renewal needs no `validFrom`: *Reissue* runs the term on from the old expiry |
| Licence accepted, but every area redirects to the licence screen | The build is from before kf-app#985 and still gates on the five area keys, which a licence issued since does not carry — see [License Entitlements](License-Entitlements.md#what-the-readers-do-today) |
| Licence accepted, but one report or feature redirects to the licence screen, saying the licence does not include it | The licence does not name it. Anything not named is not granted — including anything added to the product after the licence was issued |
| Licence accepted, but the AI allowance is still the evaluation tier's | On kf-app 1.6.2, the licence reaches the AI Gateway only when the installation first enrols, so one that used AI before the licence was uploaded keeps the allowance it enrolled with. kf-app#968, not yet released, sends it on every install, and shows the gateway's answer on the AI Manager card |
| The licence screen says the licence cannot be read | A stored licence this build cannot verify or read: a `schemaVersion` it does not know, or signed by a key it no longer trusts. It grants nothing, and the screen offers the reset that falls back to the trial (kf-app#979, not yet released; kf-app 1.6.2 falls back to the trial by itself) |
| Whole product redirects to the licence screen | No licence uploaded, or the licence has expired. An expired uploaded licence does **not** fall back to the bundled trial |
| Startup fails with *"License validation failed because no licensing public key is available"* | A licence is stored but the installation trusts no key at all — the image carries none and no `LicensingSettings__PublicKey` is set. A stock image always carries one. A key that is set but unreadable does **not** cause this: it is skipped with a warning and the image's keys are still tried (kf-app `c332de4`, `LicenceSignature.cs`) |

## Who may issue

Partly decided. In the console, anyone whose name holds *Licensing: Write* can issue any licence
([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88); before it, anyone on #68's writers
list), as can `admin` and an Administrator, and so can anyone with the private key and passphrase;
*Licensing: View* sees the form and cannot issue from it. A licence cannot be revoked once
sent. What exists is the record: every licence the console issues is in the
[register](License-Register.md), with the name the issuer signed in under and the name they typed —
which, for a licence issued under the shared password before #88, is the only thing saying who that
was.

A licence minted offline with the CLI reaches the register only as a row in the CSV that
`--register-csv` writes. Keep that file with the licences it describes.
</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:

```
Trial    = 1
Standard = 2
```

There is **no `Enterprise`**, despite what the older kf-app wiki page says and what the template in
this repository used to suggest. Passing it fails with a `JsonException` naming
`$.licenseType`. The plan is `tier`, not `licenseType`.

**Only `Standard` is issued (#3).** `Trial` parses, and is then refused along with the config's other
problems, as is a config that leaves `licenseType` out. A `Trial`-typed file is too easily taken for
the product's trial, which is compiled in and never a file (kf-app#870), and the label grants nothing
the same licence typed `Standard` would not. For an evaluation, issue `Standard` with `"purpose":
"demo"` and a short `duration` — [the example below](#time-limited-evaluation-licence). Readers still
accept a `Trial`-typed licence issued before #3 and grant it what they would grant the same licence
typed `Standard`; kf-app's licence page shows it as "Trial" (kf-app `c332de4`).

Remember that `Type` gates nothing in the product — it is a label. Two licences differing only in
`licenseType` grant exactly the same access. See [License Format](License-Format.md#element-reference).

### `tier`

The product's own plan names, from kf-app's `LicenseController.GetUpgradePlans`. `trial` is not a
tier: the trial is a compiled constant, never a file. A licence with no `tier` says nothing about its
plan, and the tool does not guess one.

**The tier chooses the AI Gateway's defaults, and nothing else**
([#46](https://github.com/KnowledgeFabric/kf-admin/issues/46)). A licence that leaves out `ai.tokens`,
`ai.period` or `ai.rpm` gets its tier's allowance for it, and a licence with no `tier` gets
`standard`'s ([License Entitlements](License-Entitlements.md#how-a-reader-must-read-them), rule 10).
The allowances are the gateway's policy, not the licence's, so a plan's can be raised without
reissuing anything; a deal that includes more than its tier's allowance writes its numbers into the
licence instead. Both start at 120 requests a minute and 10,000,000 tokens a UTC calendar month:
[the AI allowance per tier](License-Entitlements.md#the-ai-allowance-per-tier).

Only the gateway reads `tier`, since kf-ai-gateway#32 (`c82878f`): it serves a licence whose `tier`
is exactly `enterprise` the `enterprise` allowance, and every other licence `standard`'s. kf-app does
not; its licence screen shows `Type` instead (kf-app `c332de4`). What the tiers mean commercially,
beyond the AI allowance, is not defined yet.

## Dates and timezones

`expiration` and `validFrom` must carry an offset: `Z`, or `+01:00` and the like. A value without
one — `2026-12-31T23:59:59`, or a date alone — is **refused**.

It used to be accepted and read as local time on the issuing machine, so the licence depended on
where it was minted. Measured before #4, minting the same config on three machines:

| `expiration` in config | Issuing machine TZ | `Expiration` in the licence |
|---|---|---|
| `2026-12-31T23:59:59` | UTC | `Thu, 31 Dec 2026 23:59:59 GMT` |
| `2026-12-31T23:59:59` | Europe/Malta (UTC+1) | `Thu, 31 Dec 2026 **22:59:59** GMT` |
| `2026-12-31T23:59:59` | America/New_York (UTC−5) | `Fri, **01 Jan 2027** 04:59:59 GMT` |
| `2026-12-31T23:59:59Z` | Europe/Malta | `Thu, 31 Dec 2026 23:59:59 GMT` ✅ |
| `2026-12-31T23:59:59+01:00` | Europe/Malta | `Thu, 31 Dec 2026 22:59:59 GMT` ✅ |

A date-only value was the sharpest edge: `"expiration": "2027-12-31"` became local midnight, so
issued from Malta it signed `Thu, 30 Dec 2027 23:00:00 GMT` and the licence died a day early.

> Use `...T23:59:59Z` when you mean end-of-day UTC, or an explicit offset like `+01:00` when you
> mean end-of-day in the customer's zone.

An expiration that has already passed is **not** refused — the tool prints a warning and mints it,
and the product refuses it on upload.

### `duration`

Instead of an `expiration`, a licence can state how long it lasts: `P1Y`, `P6M`, `P2W`, `P30D`, or
a combination such as `P1Y6M`. Exactly one of `expiration` and `duration` is set; both, or neither,
is refused.

- It is resolved **once, at issue time**, into an ordinary `Expiration`. Nothing in the file records
  the duration, and no reader needs to understand it.
- It counts from `validFrom` when the licence has one, and from the moment of issue otherwise. A
  `P1Y` licence starting next month runs a year from next month.
- It is calendar arithmetic, years then months then days: `P1Y` from `2026-06-01T00:00:00Z` is
  exactly `2027-06-01T00:00:00Z`, not 365 days later. A 29 February start plus `P1Y` lands on
  28 February.
- Only whole days or longer. A time part (`PT12H`) is refused, and so is a zero duration.

A duration counted from the moment of issue ends at that time of day, not at midnight. Where the
exact instant matters, give `validFrom` or write `expiration` out.

### `validFrom`

The instant the licence comes into force. Per the [contract](License-Contract.md#the-verification-algorithm)
a reader must refuse a licence before it, as `not-yet-valid`.

> [!WARNING]
> **kf-app's current release does not honour `validFrom`.** kf-app 1.6.2 checks expiry only, so a
> future-dated licence installs and unlocks the product **immediately**. kf-app#979, on `develop` at
> `5e9fb51` and not yet released, honours it: it **refuses** such a licence on upload as
> `not-yet-valid`, naming its start, rather than store it to wait, because installing a licence
> replaces the one in force. So a licence with a future `validFrom` cannot be installed ahead of
> time on a build with #979; the customer uploads it on or after the date.
>
> The gateway refuses it until that instant, reporting `unverifiable`, and keeps the installation on
> `evaluation` (kf-ai-gateway `ebb48b3`). It checks a licence only when one is sent: kf-app 1.6.2
> sends it only at enrolment, so an installation that sent it early stays on `evaluation`. From
> kf-app#968, also not yet released, kf-app sends it on every install.
>
> Don't sell a start date as enforced until kf-app has released #979, and don't use one for a
> renewal: *Reissue* runs the term on from the old expiry instead
> ([#42](https://github.com/KnowledgeFabric/kf-admin/issues/42)).

## Leniency you should know about

The tool refuses the date, duration, tier, id, entitlement and attribute-name problems above.
Everything else is still accepted:

- **Unknown fields are silently ignored.** `"seats": 50` is dropped without a word — and so is a
  misspelled entitlement field: `"report": ["map"]` for `reports` grants no report. The warning for a
  licence granting nothing catches the worst case of it.
- **Empty `name`/`email` are accepted**, producing a licence issued to nobody.
- **JSON comments are a hard error.** `System.Text.Json` rejects `//`, so a config cannot be
  annotated inline. Put the commentary in the commit message or here, not in the file.

Misspelled names inside the entitlement are no longer among them: before #38, `"Reporing": "true"`
was minted without complaint and matched no gate, and that exact typo was in the shipped template.
Now a name the catalogue does not have is refused. Still read back the XML the tool prints: a field
name it ignored leaves its section empty, and the licence grants less than you meant.

### Size

kf-app stores the licence in `ProductLicense.LicenseXml`, which is `nvarchar(max)` since kf-app#980
(migration `WidenProductLicenseXml`, kf-app `c332de4`), so no size a licence reaches is a problem.
It was `nvarchar(3000)` before, which is why `gen-license` used to warn above 2,500 bytes. Today's
licences are well under 1,000; the largest fixture is 1,206.

## Worked examples

Every example below was minted with `gen-license` against the contract test key.

### Standard customer licence, everything granted

Every report, feature, connector and the assistant, with the Standard plan's cap of ten knowledge
sources in total and no other limit.

```json
{
  "name": "Acme Corporation",
  "email": "it-ops@acme.example",
  "company": "Acme Corporation Ltd",
  "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"],
  "sources.max": 10,
  "ai": ["chat"],
  "attributes": {}
}
```

### Standard licence without the assistant, two reports and one connector

Knowledge Map, Workforce Report and Microsoft Teams are not named, so they are not granted — and
neither is anything the product adds later. Jira is limited to three sources. With `ai` left out,
the assistant is off; the installation still uses the AI Gateway for discovery, at the `standard`
allowance, since the licence names no `tier` and no AI limits.

```json
{
  "name": "Beta Industries Ltd",
  "email": "licensing@beta.example",
  "licenseType": "Standard",
  "expiration": "2027-03-31T23:59:59Z",
  "reports": ["insights", "resilience", "watch", "holders", "assets", "skills"],
  "features": ["offboarding", "actioncenter", "departure", "export"],
  "sources": ["git", "azureboards", "jira:3", "gcal", "outlook", "confluence", "shortcut", "onedrive", "publications", "github"],
  "attributes": {}
}
```

### Enterprise licence for one year from a start date, with limits

Expires `2027-01-01T00:00:00Z`: one calendar year after `validFrom`. It is sized for 500 employees,
analysis reads two years of history, and the AI Gateway allows 25 million tokens a calendar month.
Remember that only the gateway enforces the start date — see [`validFrom`](#validfrom) — and that the
500 is an allowance the product reports going over, not a limit
([License Entitlements](License-Entitlements.md#how-a-reader-must-read-them)).

```json
{
  "name": "Delta Logistics",
  "email": "licensing@delta.example",
  "licenseType": "Standard",
  "tier": "enterprise",
  "validFrom": "2026-01-01T00:00:00Z",
  "duration": "P1Y",
  "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"],
  "analysis.employees": 500,
  "analysis.history": 24,
  "ai": ["chat"],
  "ai.tokens": 25000000,
  "ai.period": "month",
  "attributes": {
    "orderRef": "PO-4471"
  }
}
```

### Time-limited evaluation licence

An evaluation licence from this tool is an ordinary `Standard` licence with a near expiry, marked
`demo` so the register leaves it out of its figures. It is *not* the duration-based bundled trial,
and it carries no `TrialDays` attribute (which would make the product refuse it). See
[License Entitlements](License-Entitlements.md#trialdays-and-why-this-repository-cannot-mint-a-trial).
The `duration` below does not change that: it becomes a fixed `Expiration` 30 days after the licence
is minted, not 30 days after it is installed. This example used `"licenseType": "Trial"` until #3,
which refuses it.

```json
{
  "name": "Gamma Group — Evaluation",
  "email": "evaluation@gamma.example",
  "licenseType": "Standard",
  "purpose": "demo",
  "duration": "P30D",
  "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": {}
}
```

## Files in this repository

- `src/KnowledgeFabric.LicenseTool/config/license_config_template.json` — a valid, fill-in-the-blanks
  starting point granting everything, with the Standard plan's cap of ten knowledge sources.
- `src/KnowledgeFabric.LicenseTool/config/license_config.json` — the developer sample, copied to the
  build output.
</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)).

| | Rule |
|---|---|
| Entitlement names | Lowercase letters and digits, case-sensitive: `insights` is not `Insights`. The catalogue is in [License Entitlements](License-Entitlements.md). A licence grants only what it names — there is no default-on. |
| Lists | Comma-separated, no spaces: `insights,map`. A connector may carry a count: `jira:3`. |
| Attribute names | Case-sensitive. Note the reserved name is `TrialDays`, capitalised. |
| Dates in attributes | ISO 8601 **with an offset** — `2026-12-01T00:00:00Z`. A bare local time is read as local to whatever machine parses it. |
| The `Expiration` element | RFC 1123 in UTC, written by `Standard.Licensing`. Not under the contract's control. |
| Numbers | `CultureInfo.InvariantCulture`, always. Limits and counts are positive whole numbers, digits only. |
| Reserved names | `TrialDays`, the entitlement's attributes (`reports`, `features`, `sources`, `ai`) and the `ai.`, `sources.` and `analysis.` prefixes. Free-form `attributes` must not use them. |

### Attribute names this contract defines

| Name | Meaning |
|---|---|
| `schemaVersion` | Integer, above. Absent means `1`. |
| `issuedAt` | When the licence was minted. Informational. |
| `validFrom` | The instant the licence comes into force. Optional. |
| `tier` | `standard` or `enterprise` — the product's own plan names. `trial` is never a file. It chooses the AI Gateway's default allowance, and nothing else: absent, or a value a reader does not know, reads as `standard` ([License Entitlements](License-Entitlements.md#how-a-reader-must-read-them), rule 10). |
| `purpose` | What the licence is for: `customer`, `internal` (our own development, staging and test installations) or `demo` (sales demos and partner installations). Written on every licence the tool issues; **absent reads as `customer`**. It grants nothing and restricts nothing: it is how the register leaves licences that are not a customer's out of its figures. A reader that does not know a value reports it as written. |
| `TrialDays` | **Reserved.** Its presence marks a file as a trial, and kf-app refuses to install one. A customer licence must never carry it. |
| `reports`, `features`, `sources`, `sources.max`, `analysis.employees`, `analysis.assets`, `analysis.history`, `ai`, `ai.tokens`, `ai.period`, `ai.rpm` | What the licence grants and limits. Defined, with how to read each, in [License Entitlements](License-Entitlements.md). |

## The verification algorithm

This is the twenty lines. Every reader implements it; the fixtures prove it did.

1. **Parse.** A document that will not parse is refused as `unverifiable`. Nothing about it can be
   trusted, so every other judgement is negative rather than left at a default.
2. **Verify the signature** against the public key, and check the **return value**.
   `VerifySignature` returns `false`; it does not throw. Catching an exception is not equivalent,
   and a reader that relies on one accepts every forged licence.
3. **Read `schemaVersion`.** Absent ⇒ `1`. Above what this reader knows, or unparseable ⇒ refuse as
   `unsupported-schema`, naming the version.
4. **Refuse a `TrialDays` attribute** on upload. A trial signs no calendar expiry, so storing one
   as an installed licence installs a licence that never lapses.
5. **Normalise `Expiration` to UTC**, then compare against the current instant. See below — this
   step is not optional.
6. **Honour `validFrom`** where present: a licence is not in force before that instant.
7. **Read the entitlement** by the rules in [License Entitlements](License-Entitlements.md#how-a-reader-must-read-them):
   a list grants only what it names, an unknown name is ignored, an absent limit is no limit, and a
   limit that is present but unreadable reads as 0. `ProductFeatures` is read for nothing.

**A malformed value fails closed, never open.** Where a reader cannot interpret an attribute that
would restrict the licence, it applies the restriction rather than discarding it. Specifically: an
unreadable `validFrom` leaves the licence **not in force**, because a start instant the reader
cannot establish has passed has not passed as far as that reader knows. Treating it as absent —
the natural result of a `TryParse` that returns null on failure — would put a licence in force on
the strength of a date nobody could read. The same principle makes an unparseable `schemaVersion`
unsupported rather than version 1.

An offset-less date should be read as UTC rather than local to whichever machine parses it. The
contract forbids emitting one (see [Names and encodings](#names-and-encodings)), but a reader may
still be handed one, and two readers disagreeing about it is worse than both being wrong the same
way.

Refusal reasons, in **precedence order** — a reader reports the first that applies:

| Reason | When | Status |
|---|---|---|
| `unverifiable` | Will not parse, or the signature does not verify against this reader's key | kf-ai-gateway's own word |
| `unsupported-schema` | `schemaVersion` above what the reader knows, or unparseable | **Proposed here**, and kf-app's word since kf-app#985. The gateway reports it as `unverifiable` |
| `trial-licence` | Carries `TrialDays` | **Proposed here**, and kf-app's word since kf-app#985. The gateway reports it as `unverifiable` |
| `expired` | `Expiration` precedes now | kf-ai-gateway's own word |
| `not-yet-valid` | `validFrom` follows now | **Proposed here**, and kf-app's word since kf-app#979, not yet released. The gateway reports it as `unverifiable` |

The gateway owns `expired` and `unverifiable`. The other three are named here so the fixture set
can be complete and so the words are on the record. kf-ai-gateway#7 closed without renaming them,
and without publishing them: the gateway's verifier names all three exactly as above
(`StandardLicenceEvaluator.Causes`), but its `docs/API.md` keeps two reasons, so on the wire all
three are `unverifiable` with `expires_at: null`. The contract's word survives as
`LicenceOutcome.Cause`, which the gateway logs and its own tests assert against every fixture (kf-ai-gateway `ebb48b3`, `docs/API.md` Enrolment
and `src/KnowledgeFabric.AiGateway/Licensing/StandardLicenceEvaluator.cs`).

### Normalising `Expiration` is not optional

`Standard.Licensing` parses the RFC 1123 expiry back as a `DateTimeKind.Local` value, and comparing
two `DateTime`s in .NET ignores their kind. Measured, loading one licence signed
`Fri, 31 Dec 2027 23:59:59 GMT` on three machines:

| Reader's timezone | `license.Expiration` | `Kind` | After `ToUniversalTime()` |
|---|---|---|---|
| UTC | `2027-12-31T23:59:59+00:00` | `Local` | `2027-12-31T23:59:59Z` |
| Europe/Malta | `2028-01-01T00:59:59+01:00` | `Local` | `2027-12-31T23:59:59Z` |
| America/New_York | `2027-12-31T18:59:59-05:00` | `Local` | `2027-12-31T23:59:59Z` |

A reader that compares the raw value against `DateTime.UtcNow` gives the customer extra hours east
of Greenwich and takes them away to the west — and in Malta reports the expiry as falling in
**January 2028**. kf-app already normalises, in its own `ToUtc`. Every reader must.

### `validFrom` is honoured by the gateway, and by kf-app from its next release

The gateway honours `validFrom` since kf-ai-gateway#7: a licence before its start, or with an
unreadable one, is refused — reported as `unverifiable`, above — and the installation stays on
`evaluation` (kf-ai-gateway `ebb48b3`).

kf-app honours it since kf-app#979, on `develop` at `5e9fb51` and not yet released. One rule,
`LicenceTerm.StandingAt`, judges a licence's dates for the upload path, the gate, the licence screen
and the expiry warnings, with this contract's precedence. On upload, a licence before its
`validFrom`, or with one it cannot read, is **refused** as `not-yet-valid`, naming its start, rather
than stored to wait: installing a licence replaces the one in force, so an early renewal stored to
wait would end the licence it renews (kf-app `docs/Architecture/Licence-Remit.md`, D4). This
contract says only that such a licence is not in force; refusing it on upload is kf-app's choice
within that. kf-app 1.6.2 (`c332de4`) checks expiry only, so there a future-dated licence works as
soon as it is installed.

The `valid-from-future` fixture records **both** facts: not in force per this contract, and accepted
on upload by kf-app before #979 (`acceptOnUpload`). kf-app's fixture test now refuses exactly where
the contract gives a reason, and allows `not-yet-valid` as the one difference from `acceptOnUpload`
(`LicenceContractFixtureTests`, `5e9fb51`), so the manifest needs no change for it.

## One licence, one installation

**A licence covers one installation**, decided on
[#47](https://github.com/KnowledgeFabric/kf-admin/issues/47). A customer that runs several (an
enterprise with one per team, say) holds one licence for each, each with its own id. This holds
whatever the licence's `purpose`: an `internal` licence covers one of our own installations, not our
development, staging and test installations between them, and a `demo` licence covers one demo or
partner installation.

- **The rule is on `Id`, not on `Quantity`.** `Quantity` is always `1` and read by nothing, and no
  reader may treat it as a count of installations or of seats. The file does not express the rule,
  so it needs no attribute, no new fixture and no new `schemaVersion`: nothing in a licence changes,
  and no reader refuses anything it accepted before.
- **kf-app cannot apply it.** It checks a licence offline and never learns of another installation,
  so the same file works wherever it is installed. That is how the product is built, not a gap in it.
- **The gateway watches for it and does not enforce it.** An installation enrols with the gateway to
  use AI, so the gateway is the one reader that can see a licence id on two installations. It must
  record the `Id` of the licence it accepts on each installation, and show an operator every id held
  by more than one. It must not refuse or downgrade an installation for it: the operator decides,
  with the revoke the gateway's `/admin` already has. Enforcing was considered and not chosen. A
  reinstalled installation enrols under a new installation id, so it would sit on `evaluation` until
  someone released the old one. Enforcing can be added later as a gateway change alone.
- **A reissue is the same licence.** A renewal keeps its id
  ([#42](https://github.com/KnowledgeFabric/kf-admin/issues/42)) and replaces the file on the
  installation it was issued for, so it is not a second installation. A replacement under a new id,
  such as a customer licence following a demo one, is a new licence, and the installation holds it
  instead of the old one.

What the gateway sees is narrower than the rule. An installation enrols on its first use of AI
(kf-ai-gateway `docs/API.md`, *Identity*), so one that never uses AI is invisible there. The id
recorded is the one the installation last sent. kf-app 1.6.2 (`c332de4`) sends its licence only
when it first enrols, so there a licence uploaded afterwards does not reach the gateway. kf-app#968,
on `develop` at `5e9fb51` and not yet released, sends it whenever a licence is installed, replaced
or removed.

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): `Installation.LicenceId`, written from an accepted licence only, kept across a renewal
and a re-enrolment, cleared when the licence lapses or is removed, and shown on
`/admin/installations` (`Admin/AdminEndpoints.cs`) as `licence_id` with a `licence_holders` count of
the installations holding it that have not been revoked. kf-admin's register shows it
([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). An installation licensed before that
deploy has no id until its licence is sent again.

## The fixture set

27 signed licences under [`contract/`](../contract/README.md), minted by the same code path that
signs a customer licence. Consumption, regeneration and the test-key arrangement are documented
there. The short version:

- Verify against the shipped `contract-test.public.key`, **not** the production key.
- Freeze your clock to the manifest's `evaluationInstant`, `2026-07-01T12:00:00Z`.
- `gen-fixtures` reads every fixture back and fails if it does not behave as the set declares, so
  the manifest's verdicts are measured rather than asserted.
- The set is **not byte-reproducible**: ECDSA signing uses a random nonce, so every regeneration
  rewrites every signature and every hash.

The cases cover the happy path (a licence granting everything, with no limits), a missing
`schemaVersion`, expiry, `validFrom`, an expiry resolved from a `duration` (from `validFrom`, and from
the moment of issue), `Customer/Company`, tampering, a foreign signature, trial shape, an
unknown attribute, an unsupported version, and a blob that is not a licence at all.

Seven cases cover the entitlement ([License Entitlements](License-Entitlements.md)): a licence
granting nothing, one carrying only the five area keys #38 removed (which grant nothing), a partial
grant, connector counts, analysis limits, AI limits, and names a reader does not know. One more,
`purpose-internal`, carries a `purpose` other than `customer`; every licence minted normally carries
`purpose=customer`, and the verbatim cases carry none, so both of those are covered too. Two cover
`tier`: `tier-enterprise`, whose missing AI limits come from the `enterprise` allowance, and
`tier-unknown`, whose tier no reader knows, so they come from `standard`'s. Every case states that
choice as `aiTier`.

Four further cases pin the fail-closed rule above, because a rule only prose enforces is a rule that
drifts: `malformed-valid-from` (unreadable start date ⇒ not in force), `negative-schema-version`
(a version below 1 ⇒ unsupported, where a naive "not newer than I support" test would accept it),
`malformed-connector-count` (an unreadable count ⇒ none of that connector) and `malformed-limits`
(an unreadable limit ⇒ 0, never unlimited).

## Normative and descriptive

The rest of `docs/` was written to describe what the code does, verified by building it and reading
kf-app at `075fa03`. Three of those pages are now **normative as well**, because a contract with no
shared binary needs a written source of truth:

| Page | Normative content |
|---|---|
| [License Format](License-Format.md) | The elements, which of them are acted on, and the validation paths. |
| [License Config Schema](License-Config-Schema.md) | The issuing-side config, and the offset rule on dates. |
| [License Entitlements](License-Entitlements.md) | The catalogue of reports, features, connectors and limits, how they are written, how a reader reads them, and the reserved attribute. |

Those pages still carry descriptive material — measured leniencies, sharp edges, kf-app's current
behaviour with citations. Where a page says what a reader *must* do, it is normative; where it
reports what the code *does* today, with a kf-app commit citation, it is descriptive. The
distinction matters most for `validFrom`, which the contract requires and kf-app's current
release does not implement (kf-app#979 does, on `develop`).

[Issuing a License](Issuing-A-License.md) and [Admin Console](Admin-Console.md) are operational and
descriptive throughout.

## Not settled

- **The three proposed reason words** — `unsupported-schema`, `trial-licence`, `not-yet-valid` —
  are still marked proposed. kf-app uses the first two as its own since kf-app#985, and shows them
  to an administrator whose upload it refuses (`LicenceUploadResult.Reasons`, kf-app `c332de4`),
  and the third since it honours `validFrom` (kf-app#979, `5e9fb51`). kf-ai-gateway#7 closed without
  renaming them, but reports all three as `unverifiable` (above), so its API does not carry them.
  Confirming them is [#22](https://github.com/KnowledgeFabric/kf-admin/issues/22).

Settled since: kf-app's narrowed remit — verify, interpret, handle unknown schema versions, never
mint — is its ADR `docs/Architecture/Licence-Remit.md` (kf-app#979), and kf-app#982 deleted kf-app's
copy of the tool with its CLI reference, which restated the format (both `5e9fb51`, on `develop`).
</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
   counts. A licence may name a report from a newer build of the product than the reader: that
   reader does not know it, so cannot offer it, and must not refuse the licence for it (the
   contract's first compatibility rule). A reader should report the names it ignored.
3. **An absent limit is no limit.** For `ai.tokens`, `ai.period` and `ai.rpm`, it is the licence's
   tier's default (rule 10).
4. **A limit or count that is present but cannot be read fails closed: it reads as 0 and allows
   nothing.** That covers words, zero, negative numbers, fractions and numbers with separators
   (`ten`, `0`, `-5`, `1.5`, `10,000,000`), in `sources.max`, `analysis.*`, `ai.tokens` and `ai.rpm`
   and in a `sources` count (`jira:x` allows no Jira). Treating it as absent would lift the limit on
   the strength of a value nobody could read. This is the rule that leaves a licence with an
   unreadable `validFrom` not in force ([License Contract](License-Contract.md#the-verification-algorithm)).
   For `analysis.employees` it is an allowance of 0, which every employee is over (rule 9).
5. **A connector listed twice gets the lower count**, for the same reason.
6. **An `ai.period` the reader does not know means its tier's default.** It is the one exception to
   rule 4: neither period is tighter than the other, so there is no restriction to fall back on.
7. **Both connector limits apply.** An installation may have at most a connector's count of that
   connector, and at most `sources.max` knowledge sources altogether. **A connector's count is of
   its sources, but for `github`, whose count is of repositories:** the repositories in scope,
   summed across every GitHub source on the installation, each with its issues and pull requests.
   A GitHub source is an organisation or a user account with the repositories it reads, so one
   source can hold forty. `sources.max` still counts each GitHub source as one source, whatever
   it holds. So under a `github` count a GitHub source must list its repositories, to be counted:
   reading *all repositories* of an account is open only to a licence whose `github` has no count.
   The name stayed `github` when it stopped meaning GitHub Issues sources, so every licence issued
   with `github` grants the connector that replaced them, and one with `github:N` allows N
   repositories ([#168](https://github.com/KnowledgeFabric/kf-admin/issues/168),
   kf-app#1030, decision D5).
8. **`ProductFeatures` is read for nothing.**
9. **`analysis.employees` is an allowance: a reader must not hold an analysis to it.** Every
   employee an analysis finds stays in it, however far over the allowance they are. A reader must
   not leave employees out to keep within it — an analysis of the first N employees is a wrong
   answer presented as a right one — and must not refuse or stop anything for going over, an upload
   or an analysis run included. It may count employees against the allowance and tell the customer;
   how is the reader's to decide (kf-app's is [below](#kf-app)). Decided on
   [#44](https://github.com/KnowledgeFabric/kf-admin/issues/44), after kf-app found nowhere refusing
   would mean anything: nobody adds an employee, an analysis finds them.
10. **The AI Gateway's defaults are the licence's tier's.** A licence whose `tier` is `enterprise`
    gets the `enterprise` allowance for each AI limit it leaves out. Any other licence gets the
    `standard` allowance: `tier` `standard`, no `tier` at all, and any value the reader does not
    know, so `premium` and `Enterprise` both read as `standard`. A tier is never a reason to refuse
    a licence. **It chooses those defaults and nothing else**: no reader may grant, withhold or size a
    report, feature, connector or any other limit by it. Decided on
    [#46](https://github.com/KnowledgeFabric/kf-admin/issues/46); what each allowance holds is
    [the gateway's policy](#the-ai-allowance-per-tier), not the licence's.

The fixtures pin each rule: `grants-nothing`, `legacy-area-keys`, `partial-grant`,
`connector-counts`, `analysis-limits`, `ai-limits`, `unknown-names`, `malformed-connector-count`,
`malformed-limits`, `tier-enterprise` and `tier-unknown` ([the fixture set](../contract/README.md)).
Rule 9 is about what a reader does with the number, which a fixture cannot show; `analysis-limits`
pins only how it is read. For rule 10 each fixture's `aiTier` is the allowance its missing AI limits
come from, which only the gateway asserts.

### The AI allowance per tier

What a tier's allowance holds is policy kept by the AI Gateway, not something a licence carries, so
that a plan's allowance can change for every customer on it without reissuing a licence. A deal that
includes more than its tier's allowance writes its numbers into the licence, which replace the
allowance's (rule 3).

| Tier | Requests a minute | Token budget | Budget period |
|---|---|---|---|
| `standard` | 120 | 10,000,000 | UTC calendar month |
| `enterprise` | 120 | 10,000,000 | UTC calendar month |

**The two are the same for now.** Both started as copies of the gateway's single `licensed` row
when it learned to read `tier` (kf-ai-gateway#32, [below](#kf-ai-gateway)), so that nothing any
installation was served changed. Enterprise's allowance is raised once product management sets it.

**A tier's allowance only goes up while a licence on that tier is in force.** Raising it reaches
every such licence at once, which is the point. Lowering it would shrink what a customer bought
under a licence that still says the same thing, so it is not done: a plan that needs a smaller
allowance is a new tier, or numbers written into the licences issued on it.

**The console enforces it, and nothing else does.** Whether a licence on a tier is in force is the
register's question: kf-ai-gateway sees only the licences that enrolled, and accepts any `PUT` or
`UPDATE` to its rows (kf-ai-gateway `docs/Admin.md`, *Raise a licence tier's allowance*). The
console's change form ([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71),
[Gateway Management](Gateway-Management.md#the-only-goes-up-rule)) refuses to lower `standard` or
`enterprise` while the register holds a licence in force on it by rule 10, or cannot be read. Requests
are compared as the rate this table gives, a minute; the budget and the longest reply may not fall;
and the period is not moved, since neither a calendar month nor thirty days is longer in every month.
A change made on the gateway without the console is the operator's to justify, and its audit line
there records who made it and what the row was before.

**A new tier reaches the gateway before any licence carries it.** A reader that does not know a tier
reads it as `standard` (rule 10), so a licence on a tier the gateway has not learned gets Standard's
allowance, whatever the tier was meant to hold. That is the same sequencing a new signing key
follows ([Operations](Operations.md#rotating-the-key-pair)).

## The catalogue

The issuing side's copy is `LicenseContract` in `src/KnowledgeFabric.LicenseTool/LicenseContract.cs`,
which the console's form is drawn from. kf-app and kf-ai-gateway keep their own copies of the names
they read. The fixtures, and a test on each side, keep the copies in step, because there is no
shared library to do it (#5).

### Reports

In the order kf-app's menu lists them (kf-app `c332de4`, `Views/Shared/Sections/Menu/_VerticalMenu.cshtml`).

| Name | Report | kf-app controller |
|---|---|---|
| `insights` | Insight Hub | `InsightHubController` |
| `resilience` | Risk Resilience Report | `RiskResilienceReportController` |
| `watch` | Knowledge Watch Report | `KnowledgeWatchReportController` |
| `holders` | Knowledge Holder Analysis | `KnowledgeHolderReportController` |
| `assets` | Knowledge Asset Analysis | `KnowledgeAssetReportController` |
| `map` | Knowledge Map | `KnowledgeMapReportController` |
| `skills` | Skills Matrix | `SkillMatrixReportController` |
| `workforce` | Workforce Report | `WorkforceContinuity/WorkforceController` |

"Advanced" and "Basic" reporting, which the product's plan descriptions promise
(`LicenseController.GetUpgradePlans`), are expressed by which reports a licence names, unless
product management wants a switch of its own.

### Features

| Name | Feature | What it is in kf-app |
|---|---|---|
| `offboarding` | Offboarding Planner | `WorkforceContinuity/OffboardingPlannerController`: a leaver's knowledge footprint and a suggested handover plan |
| `actioncenter` | Action Center | `ActionCenter/RiskController`: the risk register |
| `departure` | Departure Simulator | `DepartureSimulatorController`: the "what if this person leaves" panel inside the Risk Resilience Report and Knowledge Holder Analysis |
| `export` | Export | Downloading report data: today only the Skills Matrix's Excel export (`SkillMatrixReportController.ExportSkillMatrixExcel`) |

Not features, for now: AI asset discovery, Custom Signals and scheduled analysis.

### Connectors

The knowledge-source types a user can create. The product's name for a type is its
`KnowledgeSourceTypes` member (kf-app `c332de4`, `KnowledgeFabric.Common/Enums/KnowledgeSourceTypes.cs`),
never its number.

| Name | Connector | `KnowledgeSourceTypes` |
|---|---|---|
| `git` | Git | `GIT` |
| `azureboards` | Azure Boards | `AZURE_BOARDS` |
| `jira` | Jira | `JIRA` |
| `gcal` | Google Calendar | `GOOGLE_CALENDAR` |
| `outlook` | Outlook Calendar | `OUTLOOK_CALENDAR` |
| `confluence` | Confluence | `CONFLUENCE` |
| `shortcut` | Shortcut | `SHORTCUT` |
| `onedrive` | OneDrive | `ONEDRIVE` |
| `teams` | Microsoft Teams | `TEAMS` |
| `publications` | Publications | `PUBLICATIONS` |
| `github` | GitHub: source control, issues and pull requests. Its count is of repositories, not sources ([rule 7](#how-a-reader-must-read-them)) | `GITHUB`, from kf-app#1030, which replaces `GITHUB_ISSUES` |

**Custom Signals is not a connector,** although kf-app stores it as source type `CUSTOM_SIGNALS`
(999). It is manual entry with no integration behind it, and no user creates a source of that type.

### AI capabilities

| Name | Capability | What it is in kf-app |
|---|---|---|
| `chat` | AI assistant | `AI/AIChatController` and the chat widget, with the "Ask about this" button on reports |

The AI limits apply to every call the installation makes through the AI Gateway, whichever
capability makes it — asset discovery included — not only to the assistant.

### Limits

| Attribute | What it counts | Notes |
|---|---|---|
| `sources.max` | Knowledge sources, across every connector | On top of each connector's own count, and each GitHub source is one, however many repositories it reads. The Standard plan promises "Up to 10 Knowledge Sources"; the form's Standard preset is 10, still to be confirmed with product management. |
| `analysis.employees` | Knowledge holders currently employed, by their employment periods, and not suppressed | An allowance, not a limit ([rule 9](#how-a-reader-must-read-them)). kf-app creates a holder for every person an analysis finds, contractors and bot accounts included. The allowance counts the ones the customer recognises and controls: `IKnowledgeHolderRepository.GetEmployedHolderIdsAsync`, less suppressed holders (kf-app `c332de4`). |
| `analysis.assets` | Knowledge assets on the manifest | The manifest is what an analysis reads (`DefaultModeller`). |
| `analysis.history` | Months back an analysis reads | The plan copy promises "3 months / 1 year worth of data". kf-app holds it by leaving older signals out of the model ([below](#kf-app)). |
| `ai.tokens` | Input and output tokens together, per budget period | The gateway's `TierPolicy.TokenBudget`. |
| `ai.period` | `month`: a UTC calendar month. `30d`: 30 days rolling from the installation's enrolment | The gateway's `calendar_month` and `rolling_30_days`. |
| `ai.rpm` | Requests a minute | The gateway's `RequestsPerWindow`, over its one-minute window. |

Not limits, for now: analysis frequency (scheduled analysis runs at most once a day), the number of
manifests (the product runs one), and the maximum length of one AI reply, which the gateway clamps
at 4,096 tokens as a technical safeguard rather than something customers buy.

## What the readers do today

### kf-app

Measured at `c332de4`. **It reads the entitlement** by the rules above
(`KnowledgeFabric.Common/Licensing/LicenceEntitlement.cs`, since kf-app#985), and its tests hold it
to this repository's 26 fixtures, copied byte for byte from `1e25d1a`
(`KnowledgeFabric.Modeller.Tests/Licensing/Contract`). Its copy of the names is `LicenceContract`,
and `LicenceCatalogueTests` fails when the full grant names something its catalogue does not have,
or the other way round.

Everything is gated through `[LicenseValidation]` → `LicenseValidationFilter`:

| What | Opens when |
|---|---|
| Configuration and Administration | Any valid licence |
| Each report | The licence names it, on the controller in the [table above](#reports) |
| Each feature | The licence names it, on the controller or action in the [table above](#features). The Excel export needs `skills` and `export` both |
| The assistant | The licence names `chat`: the chat page, the widget and the "Ask about this" button |

A refusal redirects to the licence page and says why: expired, absent, or not included, and what
(kf-app#981). The menu leaves out what the licence does not name (kf-app#987), and so do the chat
widget, the Departure Simulator panel and the export button.

Limits are held where something changes, never part-way through an analysis (kf-app
`docs/Architecture/Licence-Entitlement.md`, D3):

| Limit | What reaching it does |
|---|---|
| A connector's count, `sources.max` | The next knowledge source is refused, naming the limit, from the Configuration screen and the Get-started checklist alike (`KnowledgeSourceService.CreateOrUpdateSource`). The add-source form offers only the connectors the licence names |
| `analysis.assets` | The next asset added to the manifest is refused |
| `analysis.history` | Older signals are left out of the model. Nothing is refused |
| `analysis.employees` | Nothing is refused. The administrator is told once, in the notification bell, and the analysis still covers everyone, as [rule 9](#how-a-reader-must-read-them) requires ([#44](https://github.com/KnowledgeFabric/kf-admin/issues/44)) |

**A `github` count is not yet read as repositories.** At `c332de4`, and on `develop` at `5e9fb51`,
`github` is the GitHub Issues connector (`GITHUB_ISSUES`) and its count, like every other, is of
sources. kf-app#1030 replaces that connector with GitHub, one source per account with its
repositories, and its T3 counts repositories by [rule 7](#how-a-reader-must-read-them), with
`connector-counts`' `github: 5` in the fixtures it copies. Until it merges, a licence with
`github:N` allows N GitHub Issues sources on an installation.

A renewal on narrower terms deletes nothing. Existing sources keep running and the next addition is
refused; a connector the licence no longer names has its sources skipped by analysis and discovery
until a licence names it again.

It reads `schemaVersion` as the contract requires: absent is 1, and anything unreadable or above 1
is refused as `unsupported-schema`, naming both versions. It reads `purpose` and marks an internal or
demo licence as such on its licence page; that grants nothing.

Since kf-app#979 it honours `validFrom`, refusing on upload a licence not yet in force, and a
stored licence it cannot read stands as unreadable and grants nothing. Since kf-app#968 it sends
every licence installed, replaced or removed to the gateway (below). Both are on kf-app `develop`
at `5e9fb51` and **in no release yet**: kf-app 1.6.2 (`c332de4`) installs a licence dated to start
later, in force at once, and sends the licence to the gateway only when it first enrols.

What it does not do:

- **Show `tier` or company** on its licence page, or `validFrom` except while a licence is not yet
  in force. It shows `<Type>`, which the console always writes as `Standard`, so an `enterprise`
  licence reads "Standard" there.

### kf-ai-gateway

Measured at `85ec7e4` (kf-ai-gateway#35 and #40, deployed 2026-09-26). It verifies a licence
(`StandardLicenceEvaluator`, since kf-ai-gateway#7) and reads three attributes of the entitlement:
`ai.tokens`, `ai.period` and `ai.rpm` (kf-ai-gateway#28). It also reads `tier`, which chooses the
row those three fall back on (kf-ai-gateway#32), and the licence's `Id`, which it records and never
refuses on (kf-ai-gateway#35). The reports, features, connectors and the `ai` switch are kf-app's to
enforce. It does not read `purpose`. Its limits come from `TierPolicies` rows, per installation:

| Row | Requests a minute | Token budget | Budget period |
|---|---|---|---|
| `evaluation` | 30 | 1,000,000 | 30 days, rolling from enrolment |
| `standard` | 120 | 10,000,000 | UTC calendar month |
| `enterprise` | 120 | 10,000,000 | UTC calendar month |

A licensed installation is served the row its licence's `tier` chooses, by
[rule 10](#how-a-reader-must-read-them). `enterprise` goes to a licence whose `tier` is exactly
`enterprise`, compared ordinally. `standard` goes to every other licence: `tier` `standard`, absent
or blank, and any value the gateway does not know, which it logs by the attribute's name and never
its value. A tier never refuses a licence (`StandardLicenceEvaluator.ReadTier`,
`PolicyStore.RowFor`). The licence's limits are laid over that row on every request where it names
them; any it leaves out are the row's. An unreadable value is 0 and refuses every request, as the
rules above say, and an unknown period is the row's. The licence's limits and its tier last as long
as it does: when it expires or is removed, the installation is back on `evaluation`.

Every row clamps one reply at 4,096 tokens, and a service-wide ceiling of 50,000,000 tokens a
calendar month pauses everyone when reached. There is no "unlimited": every limit is a number, and 0
refuses every request.

kf-ai-gateway#28 decided three things. The allowance is **per installation**, so two installations
carrying one licence each get all of it. There is no "unlimited" value: a licence that means it
carries a large number, and the service-wide ceiling still applies. The budget period stays `month`
or `30d` rather than following the licence's anniversary. A licence covers one installation all the
same ([License Contract](License-Contract.md#one-licence-one-installation),
[#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)). The gateway is to report a licence
on a second installation to an operator rather than refuse it, so each copy keeps the whole
allowance until the operator revokes one. It records the licence id since
[kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35) (`cb44c56`), which is
how kf-admin's register shows a licence on two installations (#58).

**The gateway reads `tier` since kf-ai-gateway#32**
([#46](https://github.com/KnowledgeFabric/kf-admin/issues/46)), deployed on 2026-09-25. It keeps the
licence's tier on the installation (`Installation.LicenceTier`), since it does not keep the licence.
Its migration (`LicenceTierAllowance`) inserted the `standard` and `enterprise` rows as copies of the
single `licensed` row they replace, so nothing any installation was served moved. `licensed` is left
in place and nothing reads it; a later gateway release deletes it (kf-ai-gateway `docs/Admin.md`).
The gateway's own `tier`, on the wire, stays `evaluation` or `licensed`, and so does `X-KF-Tier`: the
licence's tier chooses which row a `licensed` installation gets, and is not a third state an
installation can be in. The stub answers the same way (`StubLicences`, `StubState`). The gateway's
tests assert the `aiTier` of every fixture it accepts, in its copy of the 27 fixtures from
`f405b24`.

**An installation licensed before that deploy is served `standard`, whatever its licence says.** It
has no `LicenceTier`, and the gateway reads that as `standard` until a licence reaches it again. That
costs nothing while the two rows are equal. Before Enterprise's allowance is raised, find those
installations: the gateway's `docs/Admin.md` has the query. An Enterprise customer among them has to
send their licence again, which on kf-app 1.6.2 means enrolling again (kf-app#968, below).

**A 30-day period counts from enrolment, and the gateway's has since kf-ai-gateway#31**
([#45](https://github.com/KnowledgeFabric/kf-admin/issues/45)). At `e7cdff7`, deployed on
2026-09-25, a `30d` period is counted from the installation's first enrolment
(`Installation.CreatedAt`) in whole 30-day periods (`Quota/BudgetWindow.cs`): re-enrolling does not
move it, and neither does a spell on the calendar month. `BudgetPeriodStart` only records which
period the token count belongs to, and the ledger rolls it to the start of the period running
(`Forwarding/TokenLedger.cs`). Moving between `month` and `30d`, as an installation does when its
licence expires, can forgive once what was spent earlier in the new period; it never counts more
than was spent. The stub counts the same way (`StubState`), and advances a lapsed period to the next
whole one where it used to start it whenever it next heard from the installation. Before `e7cdff7`,
a 30-day period counted from `BudgetPeriodStart`, which the ledger moves to the 1st of the month on
a calendar month, so an installation whose licence had expired counted from the 1st of the last
month it spent tokens in. Its periods were still 30 days long; only the reset date was off
(`X-KF-Tokens-Reset`, `quota.tokens.reset_at`). kf-app shows that date as the gateway reports it, on
the AI Manager card and when the assistant is refused (`AiAllowanceViewModel`, `ChatErrorHandler`,
kf-app `d0f4b06`), so the fix needed no change there.

**The gateway sees a licence only when kf-app sends it.** kf-app 1.6.2 (`c332de4`) sends it once,
when the installation first enrols, and never calls `PUT /v1/installation/licence`. So there a
licence uploaded after the installation first used AI, a renewal included, does not move it to
`licensed` or change its limits or its tier's row. kf-app#968, on `develop` at `5e9fb51` and not
yet released, reports every install, replacement or removal with `PUT /v1/installation/licence`, or
by enrolling again when the gateway no longer knows the installation. One not using AI sends it on
its next use, and uploading the same licence again is how an administrator asks the gateway again.
The AI Manager card then shows the licence as the gateway reports it.

## `TrialDays`, and why this repository cannot mint a trial

The product reads one attribute outside the entitlement and the contract's own:

| Key | Read by | Effect |
|---|---|---|
| `TrialDays` | `LicenseService.UploadLicenseAsync` (kf-app `c332de4`), by the name in `TrialLicence.DurationDaysAttribute` | Its **presence marks the file as a trial**, whatever it holds, and the upload is **refused** as `trial-licence` |

> **Do not put `TrialDays` in the `attributes` of a customer licence.** The product will refuse the
> file at upload. Since kf-app#985 its licence page says why, where before the reason was only in
> the application log. `gen-license` refuses a config that tries (#4).

Free-form attributes other than the ones on this page and in the
[contract](License-Contract.md#attribute-names-this-contract-defines) are inert: carried in the
signed document, shown nowhere, read by nothing. They are safe for bookkeeping (an order reference,
say), but nothing in the product acts on them, and they cannot be changed later without reissuing
and re-signing.

The trial an installation runs under is **not a licence file at all** any more. Since kf-app #870 it
is a compiled constant (`BundledTrial`: 30 days), whose clock starts at the installation's first run
rather than at any signing date. It grants every report, feature, connector and AI capability with
no limits (`LicenceEntitlement.Everything`, kf-app `c332de4`), unless product management decides
otherwise, so a report added to the product reaches evaluators without a second edit.

The tool in *this* repository has no `trialDays` support and always signs a calendar `Expiration`,
so it cannot produce a duration-based trial; kf-app's copy could, until kf-app#982 deleted it. Its
`duration` field is not a trial
either: it is resolved into a fixed `Expiration` when the licence is minted, so the clock starts at
issue rather than at installation. Nor is a licence with `"licenseType": "Trial"`, which this
repository issued until #3 and now refuses: it carries no `TrialDays` attribute, so the product
treats it as an ordinary licence that happens to be labelled `Trial` and expires on the date signed
into it. One already issued uploads and validates normally.
</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,
   normalised to UTC, before now ⇒ `expired`; otherwise a `validFrom` still ahead, or one it cannot
   read ⇒ `not-yet-valid`, naming the start. Refused rather than stored to wait, because the next
   step replaces the licence in force (kf-app `docs/Architecture/Licence-Remit.md`, D4).
7. Store it, replacing any previously uploaded licence. A failure to store it is kf-app's own
   `not-saved`.

The licence page shows the reason. kf-app 1.6.2 does not read `validFrom`, so there a licence dated
to start later installs and is in force at once.

**On every subsequent load** (`EnsureLoadedAsync`) — signature and schema only:

1. Read the stored licence from the database.
2. No trusted key at all ⇒ throw; the installation cannot validate and does not silently continue.
3. `FindVerifyingKey` — each key's `VerifySignature` checked via its **return value**, not by
   catching an exception. No key verifies, the licence no longer parses, or it declares a
   `schemaVersion` this build cannot read ⇒ it stands as **unreadable**: it grants nothing, the gate
   redirects with the reason `unreadable`, and the licence screen says why and offers the reset that
   falls back to the trial. Only an older build could have installed a licence from a newer schema;
   the realistic cause is a key a later release stopped trusting. kf-app 1.6.2 does not honour such
   a licence either, but lets the bundled trial answer as if nothing had been uploaded.
4. The dates are *not* checked here. Each gated request judges them by the same rule as upload,
   so a future-dated licence an older build stored comes into force on its date with nothing
   re-read. kf-app 1.6.2 compares the expiry alone, in `IsLicenseValidAsync()`.

The licence is cached process-wide for the lifetime of the process, so a licence change requires an
upload (which refreshes the cache) or a restart.

### Which public keys are trusted

A list, not one key. `LicensingSettings.TrustedPublicKeys` in
`KnowledgeFabric.Logic/Services/Licensing/LicensingOptions.cs` (kf-app `c332de4`, kf-app#983):

```
TrustedPublicKeys = Bundled.PublicKeys + PublicKey, blank entries dropped, trimmed, de-duplicated
```

A licence is genuine if **any one** of them verifies it (`LicenceSignature.FindVerifyingKey`, same
directory and commit).

- `Bundled.PublicKeys` is **compiled into the application image** — the public halves of the keys
  KnowledgeFabric signs with (kf-app#870). An installation that configures nothing trusts exactly
  these. It is a list so the signing key can be rotated by releasing an image that trusts old and
  new together; see [Operations](Operations.md#rotating-the-key-pair).
- `LicensingSettings:PublicKey` (env: `LicensingSettings__PublicKey`) is trusted **beside** them,
  never instead of them, and is needed only where licences are signed with a key the published
  images do not carry. Before kf-app#983 it replaced the compiled key.

Blank entries are dropped deliberately: every shipped compose file passes the variable through, so a
fresh installation supplies an empty string, and trusting that would be trusting nothing. A key that
cannot be read is skipped with a warning rather than ending the search, so a malformed key pasted into
a deployment does not reject a licence the image's own key verifies.

**The practical consequence for issuing:** a licence signed with a *fresh* keypair from
`gen-keys` will **not** validate on a stock installation, because no key the image trusts verifies
it. Either sign with the established private key, or hand the customer the matching public key and
have them set `LicensingSettings__PublicKey`. See
[Issuing a License](Issuing-A-License.md#key-custody).

### Timezone normalisation on the reading side

`Standard.Licensing` parses the RFC 1123 expiry back as a `DateTimeKind.Local` value. kf-app
normalises it once, on read (`ToUtc` in `LicenseService.cs`), because comparing two `DateTime`s
ignores their kind — without that, a licence would last hours longer east of Greenwich and lapse
hours early west of it.

That fix is in the *product*. The issuing side has its own, separate timezone trap: see
[License Config Schema](License-Config-Schema.md#dates-and-timezones).

## What is not in the file

Worth stating plainly, because these are the levers people assume exist:

- **No seat, user or installation count.** `Quantity` is hard-coded to 1 and read by nothing. The
  closest the entitlement comes is `analysis.employees`, an allowance of employees rather than of the
  people who sign in, and not a limit: the product reports going over it and refuses nothing
  ([License Entitlements](License-Entitlements.md#how-a-reader-must-read-them),
  [#44](https://github.com/KnowledgeFabric/kf-admin/issues/44)).
- **No machine, domain or installation binding.** The same `.lic` validates on any installation
  holding the matching public key. A licence covers one installation all the same, but only the
  gateway can see a second one, and the contract has it report one rather than refuse it
  ([License Contract](License-Contract.md#one-licence-one-installation),
  [#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)).
- **No issuer.** Since #4 the file records *when* it was minted (`issuedAt`) and its
  `schemaVersion`, but not by whom — that is the [register](License-Register.md)'s job.
- **A start date only the next kf-app release enforces.** `validFrom` is written, and the gateway
  honours it (kf-ai-gateway `ebb48b3`). kf-app honours it since kf-app#979, which is not released: on
  kf-app 1.6.2 a future-dated licence unlocks the product as soon as it is installed.
- **No revocation.** Once issued, a licence is valid until its expiry; there is no way to withdraw
  it. Short expiries are the only lever.
</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
but the row could not be appended, it says so separately, so nobody mints a second licence thinking
the first failed. These rows do **not** reach the hosted register, which has no import. Keep the
file with the licence files it describes.

## The pages

- **List, search and filter**, newest first, 25 to a page. Each row gives the customer, with their
  email and the licence id, then the company in a column of its own
  ([#83](https://github.com/KnowledgeFabric/kf-admin/issues/83)), the tier, the expiry, and when
  and by whom it was issued. A licence that names no company shows `-`, as does its page. Search
  matches any part of the customer's name, email or company, or of the licence id, ignoring case.
  `%` and `_` match themselves. Three filters narrow the list further
  ([#85](https://github.com/KnowledgeFabric/kf-admin/issues/85)), each combining with the search
  and the others, and each judged on the row, the file, as the list shows it:
  - **Purpose**: customer, demo or internal. A licence issued before `purpose` existed is a
    customer's, as its row reads it.
  - **Tier**: standard, enterprise, or *No tier*, as the file writes it and the Tier column shows
    it. The gateway gives a licence with no tier the standard allowance, so
    [usage by licence](Gateway-Management.md#usage-by-licence), which filters by allowance, counts it
    under standard; here it is *No tier*.
  - **Status**: active, expired, or both, the default. A file is expired once its expiry has
    passed by the console's clock, as its row's badge says. A file not yet in force is active, as
    the overview shows it on its active tile. A reissue keeps the licence id, so a renewed
    licence's earlier file is listed as expired though the licence is not: the overview counts
    licences, not files.

  The filters are in the query string (`?q=…&purpose=demo&tier=none&status=expired`), so a
  filtered list can be linked to, and every page of it and its export keep them. A value the
  register does not know narrows nothing.
- **One licence**: every field above, the installations running it ([below](#installations)), and
  the XML.
- **Download**: the stored licence as `<customer>-<licenceId>.lic`, in the exact bytes the SHA-256
  was taken over.
- **CSV export** of what the list shows: its search and its filters. Columns: `licenseId, customerName, customerEmail, company,
  purpose, tier, licenseType, schemaVersion, validFrom, expiration, reports, features, sources, ai, limits,
  otherAttributes, issuedBy, issuedByLogin, issuedAt, sha256`. `reports`, `features`, `sources` and
  `ai` are the licence's lists as written, with `;` for `,` (`git;jira:3`); `limits` and
  `otherAttributes` are `name=value` pairs separated by `;`. A cell that would open with
  `=`, `+`, `-` or `@` gets a leading apostrophe, because customer names come from outside and the
  export is opened in a spreadsheet.

### The overview

The console's landing page is the register's dashboard
([#37](https://github.com/KnowledgeFabric/kf-admin/issues/37)): four counts, the files issued in
each of the last twelve months, the tiers of the licences in force, the licences expiring within a
month (each with *Reissue*), and the last five files issued. It is the licensing area's
`LicensingOverview` view component, so the shell's home page does not know what a licence is.

**It counts licences, not rows.** A reissue keeps the licence id and adds a row, so counting rows
would report every renewed customer as expired once the file it replaced lapsed. A licence id is
judged on all of its files together, by the code in `Licensing/Register/RegisterStatistics.cs`:

| | A licence id is counted here when |
|---|---|
| Licences issued | It has any row. The tile also gives the number of files, and how many were reissues |
| Active | Any of its files is in force now: not expired, and past its *valid from* if it has one |
| Expiring within a month | It is active, and the last expiry among its files is within one calendar month. An early renewal keeps it off this list. *Reissue* pre-fills one with no *valid from*, so it is in force from issue, expiring 12 months after the old file. Until the old file expires both are in force, and the licence still counts once |
| Expired | Every one of its files is past its expiry |
| Not yet in force | None of its files is in force yet, but one will be. Shown under *Active* when there are any |

Expired and in force are the contract's, as `ContractReader` applies them. kf-app 1.6.2, the
current release, does not honour *valid from*, so a licence counted as not yet in force installs
there today anyway; kf-app#979, not yet released, refuses it on upload until its date. The gateway
honours it, and keeps such an installation on `evaluation`. The tier chart
uses the tier of the file in force, so an upgrade counts under its new tier. The month chart counts
files by *issued at*, splitting a licence id's first file from its reissues.

The overview reads the register without the licence XML (`ILicenceRegister.SummariesAsync`) and
counts in memory, which suits a register that grows by a few hundred rows a year. If the register
cannot be read, the overview says so rather than failing, because it is the page every sign-in lands
on.

The overview's last card is the [licences on more than one installation](#installations), from the
gateway.

Download and export are GETs, which the global audit filter skips, so each writes its own entry:
`licence:redownload`, with the licence id, and `licence:register-export`, with the search, each
filter and the row count. Neither changes anything, but handing out a customer's file, or every customer's email at
once, is worth an audit line.

### Installations

A licence covers one installation, whatever its purpose
([#47](https://github.com/KnowledgeFabric/kf-admin/issues/47),
[License Contract](License-Contract.md#one-licence-one-installation)). kf-app cannot see other
installations, so the gateway watches for it, and the register is where an operator sees what the
gateway saw ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). The console asks the
gateway's `/admin` through its client ([Admin Console](Admin-Console.md#the-client)), and never its
database.

**A row's page** lists every installation the gateway holds with the row's licence id: installation
id, short and linked to the installation's own page in the AI Gateway area
([#65](https://github.com/KnowledgeFabric/kf-admin/issues/65),
[Gateway Management](Gateway-Management.md#one-installation)), app version, the row it is served,
status (with when it was revoked, if it was), first enrolled and last seen, and what it has used
([#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)): tokens this period against its
limit, with whose the limit is and when the period resets, and requests a minute. A revoked
installation is served nothing, and says so; against a gateway from before kf-ai-gateway#38 the
usage reads *Not reported*. A reissue keeps the id, so every file of a licence shows the same installations. When more
than one of them has not been revoked, the section is flagged, with what to do: ask the customer
which installation should have the licence, then revoke the other with *Revoke…* beside it
([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69),
[Gateway Management](Gateway-Management.md#revoke-and-restore)). Nothing is refused in the meantime,
and a revoked installation no longer counts, so revoking clears the flag.

**The overview** lists every licence id held by more than one installation that has not been revoked,
from the gateway's shared filter, whatever the licence's `purpose`: the rule covers internal and
demo licences too. Each is named by the register's latest row for that id, linked to it. An id the
register does not hold is still listed, marked *Not in the register*: it was issued offline without
`--register-csv`, or by kf-app's copy of the tool before kf-app#982 deleted it.

The console counts the rows the gateway returns rather than taking the gateway's own count, so the
overview and a row's page agree.

**What the gateway knows is narrower than the rule.** It holds the licence each installation last
sent it. kf-app 1.6.2, the current release, sends its licence only when it first enrols, so there a
licence installed afterwards does not reach the gateway;
[kf-app#968](https://github.com/KnowledgeFabric/kf-app/issues/968), not yet released, sends it on
every install. An installation that has never used AI has never enrolled at all. Both pages say so.

**The gateway never breaks a register page.** Each says why the installations are missing instead:

| The page says | Because |
|---|---|
| The gateway is not configured | `Gateway--AdminToken` is not in Key Vault ([Provisioning B3](Provisioning.md#b3-load-the-secrets)), so the console does not ask |
| The gateway does not record licence ids yet | It answered without them: it predates [kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35), deployed 2026-09-26, so `Gateway:BaseUrl` names an older gateway |
| The gateway refused the console's admin token | `401`: the token is neither of the gateway's. It should be its `Admin__ReadToken` (kf-ai-gateway#40) |
| The gateway refused what the console asked | `400`, naming the parameter: a fault in the console, not an outage ([Admin Console](Admin-Console.md#the-client)) |
| The gateway has no admin surface | `404`: the gateway has no `Admin__Token`, so it maps no `/admin` |
| The console could not reach the gateway | No answer within five seconds, a network failure, an error status, or an answer that is not a list of installations. The page gives the detail |

[Operations](Operations.md#a-licences-installations-or-the-gateways-status-are-missing) has what to do about each.

Revoking is here since [#69](https://github.com/KnowledgeFabric/kf-admin/issues/69): the console's
first write to the gateway, under its write token, behind a confirm step that asks why, and audited
once the gateway confirms it ([Gateway Management](Gateway-Management.md#revoke-and-restore)). The
audit entry names the licence id and the register's customer.

## How the console chooses a store

| `Database:ConnectionString` | Environment | Store |
|---|---|---|
| Set | Any | PostgreSQL, migrated at startup |
| Not set | Development | Memory. The page says it is lost on restart |
| Not set | Anything else | None. The page says so, reads are empty, and recording is refused |

A missing connection string does not stop the console starting, because the console was live before
its database existed. A connection string that is present but malformed, or a database that cannot
be reached or migrated, **does** stop it. The migration runs before Kestrel starts, the same as in
the gateway, so the deploy's readiness poll fails loudly rather than the console signing people in to
a register it cannot write. [Operations](Operations.md) has what to do when that happens.

### Changing the schema

Migrations are in `src/KnowledgeFabric.AdminConsole/Data/Migrations/`, and are applied at startup
under a PostgreSQL advisory lock so two overlapping instances cannot both apply one. To add one:

```bash
dotnet tool install --global dotnet-ef --version 8.0.11   # once
cd src/KnowledgeFabric.AdminConsole
dotnet ef migrations add <Name> --output-dir Data/Migrations
```

No database is needed to generate a migration: `DesignTimeConsoleDbContextFactory` supplies a
placeholder address that nothing connects to.

To run the console locally against a real database rather than memory, set
`Database__ConnectionString` in the environment or in user-secrets, never in `appsettings*.json`.
</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. |
| 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
  were invariant in MVC already. A test asserts no other form provider is registered.
- **Values written back into a form are written invariant**: the issue form's hidden copy of itself
  (`_HiddenForm.cshtml`), its number and date inputs, the validate page's `asOf`, the policy forms'
  pre-fills. A culture can never reach a value that round-trips.
- **The policy forms' typed numbers** are whole numbers read by `PolicyChange.TryWhole`: `50,000,000`,
  `50.000.000`, `50 000 000` and `50000000` are one number, in groups of three or none, and `1.5` is
  refused as it always was. What the gateway gets is digits (`PUT` bodies are JSON, and never a
  formatted string).
- **Requests to the gateway** build their query strings with `CultureInfo.InvariantCulture` and ISO
  formats (`Gateway/InstallationQuery.cs`, `UsageRange.Format`), and their bodies with
  `System.Text.Json`. A test asks the same pages in English and Italian and compares the requests
  the stub gateway received.
- **Signing** goes through the CLI's own `LicenseTerms` and `LicenseSigner`, which format every
  instant with the invariant culture, from a `LicenseConfig` the form built the same way
  (`IssueForm.Instant`). A test signs in Italian and reads the attributes back.
- **Audit entries** carry codes and invariant values: the action, the field, an ISO instant
  (`revokedAt`, `expiration`, an interaction's `date`), a number as digits. Never a translated word.
- **CSV export and import** (`Crm/CrmCsv.cs`, the register's `RegisterRecord`, the usage exports)
  write and read with the invariant culture and the enums' names. A test exports the same contacts
  from an English and an Italian session and compares the bytes.
- **Parsers** pass `NumberStyles.None, CultureInfo.InvariantCulture`: a row version, an engagement
  value, a CSV cell.
- **Log lines** are message templates, which `Microsoft.Extensions.Logging` renders invariantly, and
  carry no translated text.
- **Enum values** stay as stored and sent: CRM stages, tracks and engagement, `purpose`, `tier`, the
  gateway's rows and statuses. Only their labels are translated, where they are labels; a wire word
  shown as a code, `evaluation` or `revoked`, is shown as the code.

A new page follows the same lines: format what people read with the current culture or a key, and
everything else with `CultureInfo.InvariantCulture` or JSON. The default request culture is `en`, so
the existing tests, which assert English words and `1,234`-style numbers, hold on any machine; the
test project pins its own threads to English as well (`TestLocalizer`).

## Glossary

One Italian word for each term the console uses, so that every page says it the same way. ⚠ marks a
choice still to be reviewed by a native speaker; the rest follow kf-app's Italian or are plain.

| English | Italian | Note |
|---|---|---|
| licence | licenza | kf-app's word |
| issue (a licence), issued, reissue | emettere, emessa, riemissione | kf-app: *Piano emesso per* |
| licensee | licenziatario | |
| register (the licence register) | registro (delle licenze) | |
| audit log | registro di audit | ⚠ *log di audit* is also common |
| in force | in vigore | |
| expired, expiring, active, revoked | scaduta, in scadenza, attiva, revocata | agreeing with *licenza* |
| validate, validation | convalidare, convalida | ⚠ vs *verifica* |
| verdict | esito | ⚠ |
| entitlement, what a licence grants | ciò che la licenza concede | ⚠ no single noun chosen; the pages say *concede* |
| tier | livello | the codes `standard` and `enterprise` stay; ⚠ |
| allowance (the gateway's, per tier) | quota | ⚠ vs *dotazione* |
| limit | limite | |
| ceiling (the global token ceiling) | tetto | ⚠ vs *massimale* |
| velocity (enrolment rate limits) | velocità | ⚠ vs *frequenza* |
| brake (the global brake), tripped | freno, scattato | ⚠ |
| gateway, AI Gateway | gateway, Gateway IA | a product name; kf-app writes *IA* for AI |
| installation | installazione | |
| fleet | parco installazioni | ⚠ vs *flotta* |
| enrol, enrolment | registrarsi, registrazione | ⚠ overlaps *registro* |
| revoke, restore | revocare, ripristinare | |
| usage, usage ledger | utilizzo, registro degli utilizzi | ⚠ |
| overview | panoramica | kf-app's word |
| follow-up | follow-up | ⚠ the loanword, common in Italian business |
| next action | prossima azione | |
| No next action planned? (asked when a call is logged without one) | Nessuna prossima azione prevista? | #111 |
| done (a next action, logged as done) | fatta | agreeing with *azione*; the button *Fatta* (#133) |
| more, less (a folded cell's toggle) | altro, meno | ⚠ #114 |
| contact, interaction | contatto, interazione | |
| interactions per week (the overview's chart); week of; show as a table | interazioni per settimana; settimana del; mostra come tabella | #158; *interazioni*, not *attività*, which is *Current activity*'s |
| stage, track (kind of partnership), engagement | fase, tipo di partnership, coinvolgimento | |
| Rejected (a stage: the team decided not to go on) | Scartato | #120; ⚠ the statistics' line for it is Roberto's *Persona relazionalmente non idonea* |
| why declined; Awaiting more traction, Not looking for new partners | motivo del rifiuto; Attende maggior trazione, Non cerca nuovi partner | #120, the reasons in Roberto's words |
| individual or company; individual; company | persona o azienda; persona fisica; azienda | #146, from #145's glossary; ⚠ |
| customer (introduced by a partner) | cliente | #147; already there, as a licence's purpose |
| introduction (the connection a partner made) | segnalazione | #145, decision 13: the referral sense, *segnalare un cliente*; *presentazione* set aside |
| cannot be reached (the offline page: no connection, or the console not answering) | non raggiungibile | #166; ⚠ vs *offline*, the loanword |
| try again | riprova | #166 |
| Customers introduced (the card); introduced by, introduced on | Clienti segnalati; segnalato da, segnalato il | #147; ⚠ |
| the introduction stages: Introduced, In discussion, Pilot, Under contract, Declined, Lapsed | Segnalato, In discussione, Pilota, Sotto contratto, Ha rifiutato, Non rinnovato | #147; ⚠ |
| contact person (at the customer) | referente | #147; ⚠ |
| pilot, contract, renewal | pilota, contratto, rinnovo | #145 |
| not said (a value nobody has given yet) | non indicato | the dropdowns' and the filters' blank |
| QR code; links to | codice QR; rimanda a | #163 |
| Statistics (the CRM's page) | Statistiche | #120 |
| as of (a day), back to today | al, torna a oggi | #139; ⚠ *al* before the date field, as in *al 30 novembre* |
| the record of stage changes | lo storico delle fasi | #139; ⚠ *storico* rather than *registro*, which is the audit log's |
| over time, at the end of (a day, a week, a month) | nel tempo, alla fine di | #139 |
| the introductions' statistics (#150): From introduction to contract; Customers introduced, Not yet met; By the partner's kind of partnership; How far they got, at any time; Reached a pilot, Reached a contract; Customers introduced over time | Dalla segnalazione al contratto; Clienti segnalati, Non ancora incontrati; Per tipo di partnership di chi li ha segnalati; Fin dove sono arrivati, in qualsiasi momento; Arrivati a un pilota, Arrivati a un contratto; Clienti segnalati nel tempo | ⚠ Roberto's words if he has them; the other lines are the stages' names |
| the statistics' lines: Contacts identified, To schedule, To meet soon, Met, Discussion ongoing, Discussion concluded, Accepted the proposal, Decision deferred | Contatti identificati, Da pianificare, Da incontrare a breve, Incontrati, Discussione in corso, Discussione conclusa, Proposta accettata, Decisione rinviata | Roberto's words (#120), but for *Proposta accettata*, his *Accettato proposta* put in the form a heading takes; *Decision deferred* (*Decisione rinviata*) replaced *Declined the proposal* (*Proposta declinata*) |
| the grid's column headings: Name, By, Current activity, Engagement Level, Met?, With?, Presentation, Kind of partnership, Stage, Notes | Nome, Portato da, Attività attuale, Livello di coinvolgimento, Incontrato?, Con chi?, Presentazione, Tipo di partnership, Fase, Note | translated since #107, the sheet's names (#90), *Engagement Level* (#105) and *Presentation* (#126) in English; ⚠ *Portato da* for who brought a contact in, and *Incontrato?* in the masculine as a heading's generic; the fields behind them (`by`, `e`, `met`…) stay as they are |
| Partnerships (the CRM's grid, its page and menu item) | Partnership | ⚠ the loanword, invariant in the plural; the records on it stay *contatti* (#105) |
| overdue | in ritardo | ⚠ vs *scaduta*, already a licence's word |
| partner, ambassador | partner, ambassador | programme names ⚠ |
| purpose: customer, internal, demo | scopo: cliente, interna, demo | the codes stay; the adjectives agree with *licenza* |
| signing key, contract test key | chiave di firma, chiave di prova del contratto | |
| shared password | password condivisa | |
| sign in, sign out | accedi, esci | kf-app: *Accedi* |
| roles: Administrator, View, Write | Amministratore, Visualizzazione, Scrittura | |
| grant, revoke (a role) | concedere, revocare | |
| row (an allowance row) | riga | ⚠ |
| requests a minute, tokens, window | richieste al minuto, token, finestra | |
| budget period | periodo di budget | |
| knowledge source, connector | fonte di conoscenza, connettore | kf-app: *Fonti di Conoscenza* |
| repository (what a GitHub count counts), source control, issues, pull requests | repository, controllo del codice sorgente, issue, pull request | #168; ⚠ the loanwords, invariant in the plural, as GitHub's own Italian has them |
| knowledge asset, knowledge holder | risorsa di conoscenza, detentore di conoscenza | kf-app's words |
| reports, features | report, funzionalità | |
| Users (the page) | Utenti | |
| User settings (the menu's group), Dashboard preferences (its page) | Impostazioni utente, Preferenze della dashboard | #135; ⚠ *dashboard* the loanword, as the issue names the page, though the page it orders is the *panoramica* |
| order (of the overview's areas), default order | ordine, ordine predefinito | #135 |
| the preview, sign and record | l'anteprima, firma e registra | |
| unreadable (a value) | illeggibile | |
| sheet, grid, cell | foglio, griglia, cella | |
| log (an interaction), record | registrare | the audit sense is *registro di audit* |
| owner (of a next action) | responsabile | ⚠ |
| initials (a person's, as the CRM's grid shows them) | iniziali | the Users page's column (#115); the initials themselves, `VS`, are not translated |
| due date, due | data di scadenza, entro il | ⚠ *scadenza* is also a licence's expiry |
| summary (what was said) | riepilogo | |
| participant | partecipante | |
| same name (two contacts) | omonimo | |
| import, export, restore | importazione, esportazione, ripristino | |
| delete (a contact), deleted contacts | eliminare, contatti eliminati | a delete is soft (#119): *ripristinare* brings one back |
| personal data | dati personali | |
| business card; take a photo, choose a photo; read (a card) | biglietto da visita; scatta una foto, scegli una foto; leggere | #161; the button is *Da biglietto da visita* |
| engagement scale (1 Detached…) | unchanged | the sheet's own bilingual labels |
</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.

**Removing a person.** *Secrets → `Authentication--Users--<name>` → current version → Enabled: No*,
restart. Their session ends at its next request, not at the cookie's expiry, and a sign-in under the
name is refused and throttled like any wrong one. Then revoke their roles on the Users page, where
the name now shows *no secret*: a role on a name nobody can sign in under does nothing, but a secret
re-enabled later would bring it back. Disabled rather than deleted, because a deleted secret's name
stays reserved for 90 days ([Provisioning B3](Provisioning.md#b3-load-the-secrets)), and they may be
back.

**Rotating a person's password.** + New Version on their secret, restart, tell them. Their session
stays signed in; the cookie does not depend on the password.

**`admin`.** `Authentication--Users--admin` is a person's secret like any other, held by whoever
administers the console. The name holds every role by construction and nothing on the Users page can
change that, so its password is the one to rotate first if it may have leaked, and the one to keep
with the signing key's escrow copy. Grant *Administrator* to a second person, so that roles can be
managed when `admin`'s holder is away.

### From the writers list to roles

Once, when #88 deploys. On the first start after it, nobody but `admin` holds a role: everyone who
could write before, and everyone who could only view, sees the "no roles" card until granted one.
That is deliberate, and why `Authentication--Users--admin` must be in Key Vault, and the console
restarted, **before #88 merges** ([Provisioning B3](Provisioning.md#b3-load-the-secrets)).

1. Before the merge: load `Authentication--Users--admin` and restart. It signs in, and until the
   merge it is a name like any other on the writers list or off it.
2. After the deploy: sign in as `admin`, open **Users**, and grant each name what
   `Authentication--Writers` implied. A name that was on the list wrote in both areas, so
   *Licensing: Write* and *Gateway: Write*; everyone else viewed both, so *Licensing: View* and
   *Gateway: View*. Grant *Administrator* to a second person.
3. Delete nothing: *Secrets → `Authentication--Writers` → current version → Enabled: No*. Nothing
   reads it any more, and a disabled version records who it named.

---

## Rotating the passphrase

Also cheap, and worth doing whenever anyone has reason to think the passphrase has been seen. It
re-encrypts the **same private key** under a new passphrase. The key pair does not change, so every
licence ever issued keeps validating and no customer notices anything.

This is what the `rekey` command exists for, and it needs the private key in hand — which means a
developer machine and the offline copy, not the Portal.

> **Both passphrases go on the command line, so they land in shell history and in the process list
> of a shared machine.** On the one occasion this matters most, that is worth a moment's care: run
> it on a machine only you are on, prefix the command with a space if `HISTCONTROL` includes
> `ignorespace`, and clear the history afterwards. A passphrase recovered from `~/.bash_history` is
> exactly the failure this whole procedure is meant to end.

1. Fetch the current private key. It is the blob in `Licensing--PrivateKey`, or the offline copy.
2. Run `rekey`:

   ```bash
   dotnet src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/LicenseTool.dll rekey \
     --private-key ./private.key \
     --current-passphrase '<old>' \
     --new-passphrase '<new>' \
     --output ./private.key.rekeyed
   ```

   It decrypts the blob, re-encrypts it under the new passphrase, and reads the result back before
   writing anything. `--output` defaults to `<input>.rekeyed`; **it never writes over its input**,
   and refuses a path that already exists. The original is your fallback until step 6 says
   otherwise, so keep it.

   Like every command in the tool, `rekey` reports failure through its exit status, so a script can
   depend on it.

3. **Check the public key it prints.** This is the step that catches the mistake that matters.
   `rekey` derives the public half from the private key it just decrypted and prints it; it is the
   same value `gen-keys` wrote to `public.key`, and the same one compiled into every product image
   in `BundledLicensingSettings.PublicKeys` (kf-app#870, a list since kf-app#983). If those do not
   match, the wrong file was opened — stop, and replace nothing.

4. **Mint a licence with the new file and validate it**, before anything goes near Key Vault:

   ```bash
   dotnet src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/LicenseTool.dll gen-license \
     --config <a config> --private-key ./private.key.rekeyed --passphrase '<new>' \
     --output ./check.lic
   ```

   A non-zero exit means `check.lic` was not written, and stderr says why. Then verify the result
   against the **unchanged** public key — *Licensing → Validate a licence* shows both verdicts, and
   `ContractReader` is what it uses.

   Running `gen-fixtures` proves the *tool* works, not the re-encrypted key: it signs with
   `contract/test-keys/`, which `rekey` never touches.

5. *Key Vault →* new versions of **both** `Licensing--PrivateKey` and
   `Licensing--PrivateKeyPassphrase`. Both, in one sitting: a vault holding the new blob and the old
   passphrase signs nothing.
6. Restart the App Service, issue a test licence through the console, and validate it.
7. Update the offline copy in the safe, tell whoever holds the passphrase half of it, and destroy
   the old blob and the working files.

**This runbook has been run once, on the production key** (#3). The passphrase it replaced is
committed in this repository's history, in kf-app's `launchSettings.json` and in kf-app's docs, so
it was public. The key in Key Vault and in both escrowed copies has been under a passphrase that was
never public since. The old one still opens the original file on the machine the key was generated
on, until that is deleted ([Provisioning B3](Provisioning.md#b3-load-the-secrets)).

### What rekey changes about the file, beyond the passphrase

Both `rekey` and `gen-keys` write the private key behind **600,000** KDF iterations, against the
**10** that `Standard.Licensing` writes by default — four orders of magnitude short of protecting
anything, and no basis for a remedy to a leaked passphrase. The two commands share one definition of
the parameters (`KeyRekeyer.Encrypt`) so they cannot drift apart: a generated key and a re-encrypted
one are the same file protected the same way.

The count is stored in the `EncryptedPrivateKeyInfo` and read back from it, so no reader needs
changing: Standard.Licensing and #6's signing path both hand the blob to BouncyCastle, which takes
the parameters from the blob. The algorithm and salt length are unchanged
from what the library produces.

It costs about 450ms, paid once per licence signed — the key is decrypted at signing time and never
cached, because holding a decrypted private key in memory between signings is worse than paying the
KDF. It is not paid per request, and not in CI. If bulk signing ever appears — a batch reissue over
#8's register — that path should decrypt once and sign many rather than lower this number.

---

## Rotating the key pair

**Not as a remedy for a leaked passphrase.** Rotate the passphrase instead, above: it is minutes,
and it leaves every licence in the field untouched.

The situations that do justify it are the private key being **disclosed or lost** — the key, not the
passphrase. What that costs depends entirely on one property of the readers, so establish that
first.

### Which failure you are actually having

They are not equally bad, and the cheap remedy only fits one of them.

| What happened | Recoverable? |
|---|---|
| **The passphrase leaked** | Yes, cheaply — [rotate it](#rotating-the-passphrase). This is the case `rekey` exists for |
| **The passphrase was lost, the key file is intact** | **No.** The blob cannot be opened. Identical in effect to losing the key |
| **The key was lost** — no surviving copy | Yes, by rotating the pair — ordinary work, because both readers now accept a list of public keys; it would be a lock-step migration if they did not |
| **The key leaked** | Rotating stops it signing anything new, but does not un-trust what it already signed: whoever has it can mint licences every installation accepts until the old key leaves the readers' lists |

The second row is the one people do not expect. **The passphrase is exactly as load-bearing as the
key**, and an escrow scheme that keeps the two halves in separate places protects against theft
while *doubling* the chance of loss — either half going missing is fatal. Unless there is a specific
insider-threat model that justifies it, escrow two complete sealed copies in two locations rather
than splitting the halves between them. Availability is the likelier failure here, not
confidentiality.

### Who reads the public key

Three places, and the third is easy to forget:

1. **kf-app**, as the compiled list `BundledLicensingSettings.PublicKeys` (kf-app#870; a list
   since kf-app#983). `LicensingSettings.TrustedPublicKeys` is that list plus the deployment's own
   key, and `LicenseService.UploadLicenseAsync` accepts a licence if
   `LicenceSignature.FindVerifyingKey` finds any one of them that verifies it (kf-app `c332de4`,
   `KnowledgeFabric.Logic/Services/Licensing/LicensingOptions.cs` and `LicenseService.cs`).
2. **Any kf-app deployment that set `LicensingSettings:PublicKey` in configuration.** Before
   kf-app#983 that key replaced the compiled one and never picked up a new one, so such an
   installation broke silently across a rotation. It is now trusted *beside* the compiled list,
   never instead of it (`LicensingSettings.TrustedPublicKeys`, same file and commit), so it no longer
   blocks a rotation — but an installation still on an image from before #983 behaves the old way.
   Grep the deployment configs before rotating; it is a check, not a risk, as long as it is done.
3. **kf-ai-gateway**, as the compiled list `TrustedLicenceKeys.All` — kf-app's
   `BundledLicensingSettings.PublicKeys` key for key and in the same order, one key today.
   `Program.cs` registers `StandardLicenceEvaluator` over it, which accepts a licence if any key in
   the list verifies it (kf-ai-gateway#7; kf-ai-gateway `ebb48b3`,
   `src/KnowledgeFabric.AiGateway/Licensing/TrustedLicenceKeys.cs` and
   `StandardLicenceEvaluator.cs`). A licence no trusted key verifies enrols as `evaluation`,
   `unverifiable`. The list is compiled in, not configured, so adding a key is a gateway release.
   It evaluates licences at enrolment and at `PUT /v1/installation/licence`, so a rotation is a
   release across **two** repositories, not one.

### The property that decides the cost

**Keeping the old public key trusted does not require the old private key.** The public half is
already in the product; losing the private half does not take it away. So if the readers validate
against a **list** of public keys rather than one:

- Every licence already in the field keeps working, indefinitely and untouched. They verify against
  the old public key, which is still trusted.
- New and renewed licences are signed with the new key.
- **Nothing is lock-step.** Ship the multi-key release whenever, roll it out at leisure, and nothing
  breaks while it propagates.
- **Nothing is reissued.** Existing licences run to their natural expiry; a renewal simply happens
  to be signed with the new key.
- The old key leaves the list when no unexpired licence still uses it.

The only permanent loss is the ability to sign anything *new* with the old key — an existing licence
file can still be re-sent, but it can never be reissued with a corrected field under the key an old
image trusts. Once the new key is trusted everywhere, that stops mattering.

**Against that, single-key validation makes the same rotation a lock-step migration**: every
installation must take a new image and a reissued licence simultaneously, because a new image
with an old licence is broken and an old image with a new licence is broken. Its reissue step is
executable now — [#8](https://github.com/KnowledgeFabric/kf-admin/issues/8)'s register records who
holds which licence ([License Register](License-Register.md)) — but only for licences issued
through the console, or offline with `gen-license --register-csv`. Anything issued before the
register, or offline without that flag, has no record to reissue from.

**So the multi-key change is not a nicety to schedule for later. It is the first step of any
rotation**, and doing it first is what turns the rotation into an ordinary release. Where each
reader stands:

| Reader | Accepts a list? | As of |
|---|---|---|
| **kf-app** | **Yes** — `BundledLicensingSettings.PublicKeys`, with a deployment's own key trusted beside it (kf-app#983). Ready for a rotation; its own sequence is kf-app `docs/Licensing/Trial-Licence.md`, "Rotating the signing key" | `84afe1e` |
| **kf-ai-gateway** | **Yes** — `TrustedLicenceKeys.All`, verified by `StandardLicenceEvaluator` (kf-ai-gateway#7). Ready for a rotation; the new key goes into that list, after the old one, in a gateway release | `8e92f7d` |

Both readers are ready, so a rotation is now ordinary work: two releases, then new signatures. The
order is what matters. Nothing may be signed with a new key before **both** lists trust it — a
licence the gateway cannot verify enrols as `evaluation` with `unverifiable`, and
`PUT /v1/installation/licence` refuses it with `422 licence_rejected` — so the gateway release
carrying the new key goes out before the first licence signed with it.

### The order

1. `gen-keys` with a strong passphrase, on a clean machine. A key born with a good passphrase never
   needs `rekey`; that command remains for a future leak.
2. Escrow it — two complete sealed copies, both halves together, two locations — **before** it is
   used for anything. Then load it into Key Vault
   ([Provisioning B3](Provisioning.md#b3-load-the-secrets)).
3. Add the new public key to kf-app's `BundledLicensingSettings.PublicKeys`, after the old one.
   Release.
4. Add it to kf-ai-gateway's `TrustedLicenceKeys.All`, after the old one. Deploy.
5. Roll out. No deadline: old licences validate on old and new images alike.
6. Issue everything new with the new key.
7. Drop the old key from both lists once no unexpired licence uses it.

Steps 3 and 4 are a release across two repositories, which is why this is still not casual — but it
is a planned change rather than an incident, and no customer is ever in a broken state.

---

## When something fails

### The deploy fails

| Where it fails | Almost always |
|---|---|
| `Sign in to Azure` | The federated credential subject does not match. Both formats must exist ([Provisioning B6](Provisioning.md#b6-app-registration-and-federated-credentials)) and the environment name must match `production` character for character |
| `Deploy` | `AZURE_WEBAPP_NAME` or `AZURE_RESOURCE_GROUP` wrong or unset on the Environment — they are **variables**, not secrets, and an unset one deploys to an empty name |
| `Deploy`, with a permissions error | The app registration lost `Website Contributor` on the App Service, or it was assigned at the wrong scope |
| `Wait for /health` | The app is starting and failing. *App Service → Log stream* is the only thing that will tell you why; a missing required setting is the usual cause, and once the register has a database, a migration that could not be applied is the other ([below](#the-register-and-its-database)) |
| `Mint the fixture set` | A real contract break. The commit changed what a licence means without regenerating `contract/fixtures/`. Do not retry it — read the failure |

An interrupted deploy leaves the App Service holding half a package. The workflow's concurrency
group never cancels one in flight, so the way this happens is a runner dying: rerun the workflow.

### Nobody can sign in

The log line to look for, in *Log stream* or in Application Insights, is:

```
No sign-in credentials are configured. Set Authentication:Users:<name> for each person, ...
```

It means the console read no secret, and there are exactly three causes:

1. **The secret is misnamed.** It must be `Authentication--Users--<name>` — two hyphens, which the
   Key Vault configuration provider maps to the `:` a secret name cannot contain. A single hyphen binds to nothing and says nothing.
2. **`KeyVault__Uri` is not set**, or is set to the wrong vault. Without it the console never opens
   the vault at all — and still starts, and still answers `/health` 200, because it must.
3. **The managed identity cannot read.** *Key Vault → Access control (IAM)* should show the App
   Service's system-assigned identity with `Key Vault Secrets User`. Turning the identity off and on
   again creates a *new* principal and silently orphans the old assignment.

A green `/health` rules none of these out. It is anonymous and dependency-free by design, so it
answers before any secret has been read — that is what makes it useful to the deploy and useless
here.

### A secret cannot be recreated after deleting it

The Portal refuses the new secret because one "already exists", and the secret is nowhere in the
list. Soft delete is holding the name for 90 days, and purge protection — deliberately on
([Provisioning B1](Provisioning.md#b1-create-the-vault)) — forbids purging it early. This is the
control working, not a fault: it is what stops anyone destroying the signing key and emptying the
bin behind them.

*Key Vault → Secrets → **Manage deleted secrets** → Recover*, then **+ New Version** on the
recovered secret.

**So a correction is a new version, never a delete.** The superseded value stays in the version
history, unused, and can be disabled but not removed while purge protection is on — which is worth
knowing if what went in was not merely wrong but sensitive.

### One person cannot sign in

The lockout: 5 failed attempts locks that address out for 15 minutes, and the limiter refuses more
than 10 attempts a minute with a 429. Both are in-process and both are per-address. Wait it out;
restarting the App Service to clear it also clears it for everyone else, which is the wrong trade
for one person's typo.

### Someone signs in and sees nothing, or is told "Not allowed"

What a person sees is what their roles allow ([People](#people)). The overview's card says which of
two it is:

| The card says | Why | Do |
|---|---|---|
| You have no roles yet | The name holds no role: new, or every role revoked, or the first start after #88 | Grant what they need on **Users** |
| Your roles could not be read just now | The database did not answer: *"The roles of … could not be read"* is logged at error | As for [the register's database](#the-register-and-its-database); `admin` still gets in |

*Not allowed* on a page, or a menu without the area in it, means the name holds no role for that
area: *View* to read it, *Write* to change it. The Users page shows what each name holds.

### Issuing a licence fails

The issue form says why on the page, and writes `licence:issue-failed` to the audit log with the
exception's type — never the key, the passphrase or the customer's details. Nothing is recorded and
nothing is handed over, so there is nothing to undo. In order of likelihood:

1. **The two signing secrets do not open.** The page names which of these it is — it tries each
   without showing either value (`SigningKeyDiagnosis`):

   | The page says | Fix |
   |---|---|
   | `Licensing--PrivateKeyPassphrase` has a space or line break at its start or end | The Portal's *Secret value* box keeps a pasted trailing newline. Save a new version without it |
   | `Licensing--PrivateKeyPassphrase` does not open `Licensing--PrivateKey` | The two do not belong together: most often the `private.key` from *before* `rekey` with the new passphrase, or the reverse. Check both against the escrow copy — `gen-license` with them on a trusted machine is the test — and save whichever is wrong as a new version |
   | `Licensing--PrivateKey` is not base64 | Quotes, a PEM header or a truncated paste. The secret is exactly the one line `private.key` holds |
   | `Licensing--PrivateKey` holds the public key | `public.key` was loaded instead of `private.key` |

   **Then restart the App Service** — secrets are read at startup, so a corrected version does
   nothing until then. Never rotate the key pair to fix any of these.
2. **The key opens but is not the one the product trusts.** Every licence is read back against the
   key compiled into every product image (`TrustedKeys.Product`, mirroring kf-app's
   `BundledLicensingSettings.PublicKeys`) before it is recorded, and refused if that key does not
   verify it. It means `Licensing--PrivateKey` holds some other key — the wrong file loaded in B3.
   Load the right one as a new version; never rotate the pair to fix it.
3. **The console cannot read the vault at all**, which is the three causes above.
4. **The licence is refused by the product rather than by us.** That is a contract question, not an
   infrastructure one: [License Contract](License-Contract.md) is normative, `contract/` holds the
   fixtures, and *Licensing → Validate a licence* shows both readers' verdicts side by side.

`gen-license` exits `1` when it wrote no licence and `2` when it wrote one but could not append its
`--register-csv` row (#3); [Issuing a licence](Issuing-A-License.md#exit-codes) has the table.

### The register and its database

**The register page says it has no database.** `Database--ConnectionString` is not in the vault, or
the App Service has not restarted since it was added. Nothing is recorded and #6 refuses to issue
until it is there — which is the point of saying so.

**The console will not start, and the log names the database.** Once the connection string is set,
the console migrates before it serves, and exits rather than serve on a database it cannot use. In
*Log stream*:

| The log says | Almost always |
|---|---|
| `Database:ConnectionString must be a PostgreSQL connection string naming a host and a database` | The secret's value is malformed — a missing `Host=` or `Database=`, or a stray `;`. Nothing is echoed, because the value carries the password |
| `password authentication failed for user "kf_admin_app"` | The password in the secret is not the role's. Fix whichever is wrong; there is no need to recreate the role |
| `permission denied for database kf_admin` | `GRANT CONNECT` was skipped, or run after the database changed hands ([Part C](Provisioning.md#c1-the-database-and-its-login)) |
| `42501: permission denied for schema public` | The schema was not handed to `kf_admin_app` before the database was |
| A timeout, or no route to the host | The server's *Allow public access from any Azure service* was switched off, or the server is stopped |

To restore service while you investigate, **disable** the secret — not delete it; see
[A secret cannot be recreated after deleting it](#a-secret-cannot-be-recreated-after-deleting-it) —
and restart: the console comes back without a register, which refuses to record rather than losing
anything.

**Two instances starting at once** — an overlapping deploy — do not both migrate: each takes the
same PostgreSQL advisory lock first, and the second finds the schema current.

### Restoring the CRM from an export

The CRM's tables are in `kf_admin`, so **the server's backups are the first remedy**: 35 days of
point-in-time restore, which give back contacts, interactions and their audit trail exactly. It acts
on the whole shared server, so it is restored to a new server and `kf_admin` moved, as for the
register ([License Register](License-Register.md#storage-a-database-on-the-gateways-postgresql-server)). An export
([CRM](CRM.md#export-and-import), *CRM → Contacts → Export CSV*) is for what a backup cannot do:
moving the CRM to another environment, or putting it back into a database rebuilt from nothing.
A contact deleted by mistake needs neither: a delete is soft, and an Administrator restores it from
*CRM → Partnerships → Deleted contacts* ([CRM](CRM.md#delete)).

1. **Make sure the people exist.** Every *By*, next-action owner and participant in the export must
   hold a CRM role in the console restored into, or the preview says which line names whom. Grant
   *CRM: View* on the Users page to anyone missing; it can be revoked after.
2. **Unzip** the export: `contacts.csv` and `interactions.csv`.
3. Signed in as an **Administrator**, *CRM → Contacts → Import*, choose both, **Preview**.
4. The preview refuses the whole import if any contact's name or id is already in the CRM: a restore
   is into an empty CRM. To restore only what was lost, delete those lines from both files, matching
   `contacts.csv`'s `id` to `interactions.csv`'s `contact_id`, and preview again.
5. **Import.** It is one transaction: all of it, or none of it.

What comes back: every contact under its old id, so the audit log's entries still find their
contact's page, with every field the grid and the details page edit and its next action; every
interaction, with its participants and summary. What does not: who entered each contact and when,
and who recorded each interaction: they are now whoever restored, and the time of the restore. The
audit log is its own table and is not in the export. An interaction gets a new id, which nothing
outside the CRM refers to.

The export is personal data ([CRM](CRM.md#personal-data)): restore from where it was kept, and
delete the copy you unzipped when you are done.

### Erasing a contact

A contact's delete in the console is soft ([CRM](CRM.md#delete)): the row, its interactions and its
introductions ([CRM](CRM.md#introductions), #147) stay in `kf_admin`. When a person asks to be removed (#87, decision 9), that is not enough, and the row
must go from the database. This is the only way it goes.

1. **An Administrator deletes the contact in the console**, if it is not deleted already, so the
   audit log records who and when, and copies its id from *Deleted contacts* (the *Audit log* link
   beside it carries the id in its address).
2. **Get a `psql` prompt on `kf_admin`** ([Provisioning](Provisioning.md#c1-the-database-and-its-login),
   with `PGDATABASE=kf_admin`).
3. **Erase it**, in a transaction, checking the count before committing:

   ```sql
   BEGIN;
   DELETE FROM crm_contacts WHERE id = '<the id>' AND deleted_at IS NOT NULL;
   -- DELETE 1: the contact, and its interactions, its change record, its introductions and their change record by ON DELETE CASCADE. DELETE 0: wrong id, or not deleted in the console yet.
   COMMIT;
   ```

   `AND deleted_at IS NOT NULL` is the guard: a mistyped id cannot erase a live contact.
4. **Record the erasure** where the team records the request: the date and the id, never the name.

The audit log's entries for the contact keep its id and name (#87, decision 9 allows that much in
every entry); whether an erasure request reaches them too is the team's call, and nothing here
removes them. The point-in-time backups still hold the contact until they age out, 35 days after
the erasure.

### A licence's installations, or the gateway's status, are missing

A register row's *Installations* section and the overview's *Licences on more than one
installation* (#58, [License Register](License-Register.md#installations)), the AI Gateway
area's overview and its card on the console's overview (#64,
[Gateway Management](Gateway-Management.md)), its installations and each installation's page
(#65, [Gateway Management](Gateway-Management.md#installations)), the usage by licence (#66,
[Gateway Management](Gateway-Management.md#usage-by-licence)), and the policy page and its change
forms (#67, #71, [Gateway Management](Gateway-Management.md#policy)), and the usage history (#70,
[Gateway Management](Gateway-Management.md#usage-history)), all come from the gateway's `/admin`. The gateway never breaks a page: each says why it has nothing to show, and the log says
more.

| The page says | The log | Do |
|---|---|---|
| The gateway is not configured | Nothing: the console did not ask | Add `Gateway--AdminToken` ([Provisioning B3](Provisioning.md#b3-load-the-secrets)) and restart |
| The gateway does not record licence ids yet | Nothing: the gateway answered | `Gateway:BaseUrl` names a gateway from before [kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35), deployed 2026-09-26: a local build, or another environment. Point it at the right one |
| The gateway does not report status yet | `The gateway answered 404 for admin/status but lists its installations`, as information | Nothing here. The gateway predates [kf-ai-gateway#37](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/37); this clears when it is deployed. The register's pages are unaffected |
| The gateway does not filter its installations yet | `… without X-Total-Count: it predates kf-ai-gateway#38 and ignored its filters`, as information | `Gateway:BaseUrl` names a gateway from before [kf-ai-gateway#38](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/38), deployed 2026-09-26 at `241bf4a`. Clear the filters to see its newest installations; its pages say it does not report usage yet |
| The gateway does not report usage yet | `… without X-Total-Count: it predates kf-ai-gateway#38 and ignored its filters`, as information | On the usage by licence: as the row above. Its register columns are filled meanwhile, and there is no export |
| The gateway does not keep usage history yet | `The gateway answered 404 for admin/usage/daily but lists its installations: it predates kf-ai-gateway#41`, as information | Nothing here. `Gateway:BaseUrl` names a gateway from before [kf-ai-gateway#41](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/41), deployed 2026-09-27 at `431701c`; every other part of each page is unaffected, and this clears when it is deployed |
| The gateway does not report policy yet | `The gateway answered 404 for admin/tiers but lists its installations: it predates kf-ai-gateway#39`, as information | Nothing here. `Gateway:BaseUrl` names a gateway from before [kf-ai-gateway#39](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/39), deployed 2026-09-26 at `34e05ec`; this clears when it is deployed |
| The gateway knows no installation with this id | Nothing: the gateway answered | The id is not on this gateway: see [below](#an-installation-you-expect-is-not-listed) |
| The gateway refused what the console asked | `The gateway refused the console's request for … This is a fault in the console, not the gateway`, as an **error**, naming the parameter | A bug in the console, not an outage, and nothing to wait out: since #38 the gateway refuses a parameter it does not have or cannot read. Raise an issue with the logged parameter and the page's address. Most likely the console was deployed against a gateway older than a filter it sends, or a filter's value is built wrong |
| The gateway refused the console's admin token | `The gateway refused the console's admin token`, as a warning | The token is neither of the gateway's. Set a new version of `Gateway--AdminToken` to the gateway's `Admin__ReadToken` (kf-ai-gateway#40) — never delete it ([why](#a-secret-cannot-be-recreated-after-deleting-it)) — and restart |
| The gateway has no admin surface | `The gateway answered 404 … it maps no /admin`, as a warning | The gateway has no `Admin__Token`, or `Gateway:BaseUrl` is not the gateway. Give the gateway a token (Provisioning B3) |
| The console could not reach the gateway | `The gateway's /admin did not answer`, with the exception or status, as a warning | The page gives the detail. A timeout is five seconds without an answer; a `5xx` is the gateway's own failure, and its Application Insights (`app-stg-ai-gw`) has why. The register itself is unaffected. On the usage by licence, a detail saying the gateway lists more than 10,000 installations on a row is logged as an error: the page was written for a fleet of hundreds, and reading more is a change to it, not to the gateway |

The status is asked for once every thirty seconds at most and the answer shared between the two
pages that show it ([Gateway Management](Gateway-Management.md#once-every-thirty-seconds)), so a
change on the gateway, the brake tripping or releasing, takes up to half a minute to show, and a
failure is shown for as long once the gateway is back.

**A licence is flagged on more than one installation.** Ask the customer which installation should
have it, then revoke the other with *Revoke…* beside it on the licence's page (#69). Nothing is
refused while it is flagged, and revoking clears the flag.

### A revoke, restore or policy change does not go through

The confirm step says which of these it is, and writes no audit entry for a change that was not
made. A policy change (#71) says the same, and three things of its own, after the table.

| The page says | Do |
|---|---|
| The console has no write token | `Gateway--AdminWriteToken` is not in Key Vault ([Provisioning](Provisioning.md#the-write-token)) |
| The gateway refused the console's write token | `403`: the slot holds the gateway's read token. Set a new version of `Gateway--AdminWriteToken` to its `Admin__Token`, and restart |
| The gateway refused the console's token | `401`: it is neither of the gateway's tokens, usually one side rotated without the other |
| You can view this, not do it | The session's name does not hold *Gateway: Write*: an Administrator grants it on the Users page ([People](#people)) |
| The console could not tell whether the gateway made the change | A timeout or a `5xx`: the change may have been made. Open the installation's page, or the policy page, and read what it says before trying again |

- **The allowance only goes up while a licence on it is in force.** Not a fault: the register holds
  a licence in force on `standard` or `enterprise`, and the change would give it less. Raise instead,
  or leave the lever as it is. A plan that needs less is a new tier
  ([License Entitlements](License-Entitlements.md#the-ai-allowance-per-tier)). If the page says the
  register could not be read, the rule holds until it can: [the register's own
  table](#the-register-and-its-database) has why.
- **The gateway's row holds a value it will not take back.** A lever was set with `psql`, which checks
  nothing, to something the gateway's `PUT` refuses, such as a minimum that is not a version. Change
  that lever first, from its own form; the page names it.
- **The gateway's row changed since you reviewed this.** Someone changed the same lever on the
  gateway meanwhile. Nothing was written; read the review again against the row as it now stands.

**The brake is on.** Every chat is refused `503 service_paused`. Raise the ceiling: **AI Gateway →
Policy → Global token ceiling → Change**, or the link in the overview's banner. The review says
whether the new ceiling releases it. A restart does not, and the month's spend is not to be touched.

### A business card is not read

Adding a contact from a business card ([#161](https://github.com/KnowledgeFabric/kf-admin/issues/161))
never loses anything when the card is not read: the form opens empty beside the photo, to be typed
in. The page says why, and `crm:card-read` in the audit log has the same as its `outcome`. The
console's log has Ollama's status and its own error, which names a model or a plan and never the card.

| The page says | `outcome` | Do |
|---|---|---|
| Reading business cards is not configured | none: nothing was sent | `Crm--BusinessCards--ApiKey` is not in Key Vault ([Provisioning](Provisioning.md#the-business-card-key)) |
| Ollama refused the console's key | `KeyRefused` | `401` or `403`: the key was revoked or mistyped, or the account's plan does not cover the model. Make a new key, set it as a new version of the secret, and restart |
| Ollama could not be reached, or did not answer in time | `Unreachable` | A network failure, a `5xx`, a `429`, or no answer in `Crm:BusinessCards:Timeout` (a minute). Try again in a while; the console retries nothing by itself |
| Ollama's answer was not a reading of the card | `NotUnderstood` | Usually a model Ollama has retired, whose `404` the log names. Set `Crm__BusinessCards__Model` to a model with `vision` ([Provisioning](Provisioning.md#the-business-card-key)) |
| Nothing could be read from the photo | `Read` | Not a fault: the photo was too blurred, dark or far away. Take it again, closer and flat |
| That is not a JPEG or PNG photo | none | The page's script makes every photo a JPEG; without it, a HEIC from an iPhone is refused. Reload the page, or choose a JPEG |

### A business card's QR code is not followed

A QR code on the card ([#163](https://github.com/KnowledgeFabric/kf-admin/issues/163)) that links
somewhere is followed by the console, and when that fails the card is read without it: nothing is
lost but what the page would have added. The page says why, above the photo, and `crm:card-read`
has it as `link`. The console's log says which, by status or failure, and never the link.

| The page says | `link` | Do |
|---|---|---|
| …which is not a public web page, so the console did not open it | `Refused` | Not a fault: the link, or a redirect from it, is not `http` or `https` on its default port, carries a user name, or names an address that is not public ([CRM](CRM.md#a-qr-code-on-the-card)). Open it on a phone if it matters |
| …which did not answer in time or answered with an error | `Unreachable` | The site was down, answered `4xx` or `5xx`, redirected more than five times, or took more than ten seconds. LinkedIn always answers so, signed out: its profile is put in the form all the same. If every link fails, check the App Service's outbound access |
| …which is not a page or a contact the console can read | `Unreadable` | The link leads to an image, a PDF or an empty page. Open it on a phone and type in what it says |

### The audit log

Every audited action is a row in `audit_entries` in `kf_admin` (#69) and a log line starting
`Audit:` in Application Insights; **Audit log** in the menu lists the rows, for anyone holding a
write role in any area, or *Administrator* (#88): every person's to an *Administrator* and to `admin`,
and to anyone else only the rows under their own name, matched whatever its case, failed sign-ins
under it included (#99). An operator who needs to see who else did something asks an Administrator. Granting and revoking a role are there too, as
`console:role-grant` and `console:role-revoke`, and setting a person's initials as `console:initials`. The table is appended to
and never changed by the console, and its backups are the server's, as the register's are
([Provisioning Part C](Provisioning.md#part-c--the-registers-database)). A row the database refused
is still a line, next to an error reading *"The audit entry … could not be written to the
database"*, which is where to look when the page seems to be missing an entry.

### An installation you expect is not listed

On a register row, on the installations list, or by searching its id.

- **It has never used AI.** An installation enrols with the gateway the first time it uses AI, not
  when it is installed or licensed. Until then the gateway has never heard of it, and *The gateway
  knows no installation with this id* is the truth.
- **It is on another gateway.** `Gateway:BaseUrl` is `https://ai.knowledgefabric.io`. A kf-app
  configured for another, a local build or kf-ai-gateway's stub, enrolled there instead.
- **It is listed, but not with this licence.** The gateway holds the licence each installation
  last sent it. kf-app 1.6.2 (`c332de4`), the current release, sends it only when the installation
  first enrols, so a licence installed there afterwards never reaches the gateway, and the
  installation stays on evaluation or on its old licence;
  [kf-app#968](https://github.com/KnowledgeFabric/kf-app/issues/968), on kf-app `develop` at
  `5e9fb51` and in no release yet (#61), sends it on every install. Search its installation id
  instead: its page says which licence the gateway holds, or *No licence*.
- **It reads *Licensed, id not recorded*.** It was licensed before kf-ai-gateway#35's deploy on
  2026-09-26 recorded licence ids, so a search by licence id does not find it. It has an id once its
  licence is sent again: on a kf-app with #968, by uploading it again.
- **The search was part of an id.** The gateway looks ids up whole; the list shows them short, and
  the button beside each copies the whole one.

The usage by licence shows the same from the other side: a licence in force with none of these
installations reads *Not enrolled*, and one whose installation holds an earlier file, or is served
another row than its tier chooses, reads *Served otherwise*, with which.

### No telemetry in Application Insights

`ApplicationInsights__ConnectionString`, with a double underscore, is the setting the console reads.
The one the App Service writes for you, `APPLICATIONINSIGHTS_CONNECTION_STRING`, does not bind to a
nested configuration key and leaves telemetry off with every appearance of being on. See
[Provisioning B4](Provisioning.md#b4-application-settings).

Floods of `/health` rows are the opposite problem: agent-based collection is still enabled, and the
two settings to delete are in [B5](Provisioning.md#b5-application-insights).

---

## Who can reach what

| | Can deploy code | Can read the signing key |
|---|---|---|
| The GitHub workflow (`kf-admin-deploy-production`) | Yes, to one App Service | **No** |
| The App Service's managed identity | — | Yes, read only |
| A person with `Key Vault Secrets Officer` | — | Yes |
| A subscription Owner | Yes | **Not without granting themselves a data-plane role first**, which is an auditable act |

This is the property the design rests on, and the one to preserve when changing any of it: a
workflow run can replace the console's code but has never had a path to the value it signs with.

**When someone leaves**, in this order: remove their Key Vault role assignment, rotate the shared
password, and rotate the passphrase if they ever held it. The first is immediate; the other two are
the runbooks above.

**Access restrictions are deliberately not in place** — see
[Who can reach the console](Provisioning.md#who-can-reach-the-console) for what that means and the
two upgrades that close it.
</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
watch.

**What this costs, and what it does not.** App Service bills per **plan**, not per app: the plan is
the rented compute and apps are processes on it, so a `P0v3` running one app and a `P0v3` running
two bill identically. Joining the gateway's plan adds **nothing** to the App Service line, which is
the whole reason to do it for something idle most of the week.

What still costs something, all small but none of them zero: Key Vault bills per operation (the
console reads its secrets at startup and then not again), and Application Insights bills on data
ingested against a monthly free grant that the gateway is already drawing on. The resource group,
the custom domain binding and the App Service Managed Certificate are free. Microsoft Defender for
App Service is not, and is billed per app — see the create blade's *Monitor + secure* tab above.

What is being spent instead of money is headroom. A `P0v3` is **1 vCPU and 4 GB**, fixed rather than
burstable, and **Always On** — which A1 turns on — keeps the console resident whether or not anyone
is signed in. An idle ASP.NET Core MVC application is a couple of hundred megabytes. Comfortable
beside the gateway; not free of consequence.

The €0 therefore holds until the plan has to grow. If the two applications together outgrow
`P0v3`, moving to `P1v3` is a real increase and it lands on the gateway's bill as much as on this
one — so the cost of the console is coupled to the gateway's growth, not only to its own. Scaling
*out* would multiply the plan cost outright, which is one more reason the single instance below is
not merely a correctness constraint.

**Tell the gateway's owner what is now on their plan.** `rg-kf-staging-weu-01` is a staging group
and `P0v3` is where risky gateway work happens — scaling it, changing its tier, deleting it. Those
act on every application on the plan, and one of them is now the only place KnowledgeFabric licences
are issued from. The console's resources are all in `rg-kf-admin-weu-01`, so nothing done *in* the
staging group touches them; the plan is the one shared object, and it belongs in the runbook beside
the instance-count alert.

### Current state

**The console is deployed, serving and signed into**, as of 2026-09-24. The first deploy ran green
end to end in under two minutes and `/health` answered 200 forty-three seconds after the package
landed; the secrets went in the following day, once `rekey` existed.

Signing in is what proved the Key Vault chain — the system-assigned identity, the
`Key Vault Secrets User` assignment, `KeyVault__Uri` and the `--` mapping had all been configured
and none of them had ever been exercised. `Licensing--PrivateKey` and
`Licensing--PrivateKeyPassphrase` arrive through the same mechanism and are read by
[#6](https://github.com/KnowledgeFabric/kf-admin/issues/6)'s issue form, only at the moment it signs.

The register's database ([Part C](#part-c--the-registers-database), specified by
[#8](https://github.com/KnowledgeFabric/kf-admin/issues/8)) went in on 2026-09-24: the first start
against it applied `CreateIssuedLicences` and logged `Database schema is current.` What remains is
the access restriction and the required reviewer, the dated decisions below.

| Resource | Status |
|---|---|
| App Service `app-kf-admin` on the existing `P0v3` | **Done** — 2026-09-23 |
| `admin.knowledgefabric.io`, certificate bound | **Done** — 2026-09-23, verified serving `CN=admin.knowledgefabric.io` |
| Key Vault `kv-kf-admin-weu`, RBAC, purge protection | **Done** — 2026-09-23, identity and both role assignments in place |
| The three secrets loaded (B3) | **Done** — 2026-09-24, after `rekey`; sign-in confirmed end to end |
| Offline escrow copies of the key and passphrase | **Done** — confirmed 2026-09-24 |
| The key deleted from the machine it was generated on | **Requested 2026-09-24, not yet confirmed** |
| Application Insights on its own workspace | **Done** — 2026-09-23, `log-kfadmin-weu-1`, 30-day retention, agent collection removed |
| App registration, federated credentials, role assignment | **Done** — 2026-09-23, both subject formats |
| GitHub Environment `production` and its secrets | **Done** — 2026-09-23, no required reviewer yet (see above) |
| The register's database (Part C) | **Done** — 2026-09-24, `kf_admin` on `pgsql-aigw-stg-weu-1`; migrated on startup and serving the register |
| `Gateway--AdminToken` (B3), for the register's installations ([#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)) and the AI Gateway area ([#64](https://github.com/KnowledgeFabric/kf-admin/issues/64)) | **Done** — 2026-09-26, holding the gateway's `Admin__ReadToken` ([kf-ai-gateway#40](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/40)), the same day [kf-ai-gateway#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35) and #40 were deployed. The register's installations show |
| Per-person secrets and the writers list (B3, [#68](https://github.com/KnowledgeFabric/kf-admin/issues/68)) | **Done** — 2026-09-26, the per-person `Authentication--Users--<name>` secrets loaded in `kv-kf-admin-weu`. [Operations](Operations.md#people) has adding and removing a person. The writers list is read by nothing since #88 |
| `Authentication--Users--admin` (B3), and roles per area ([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)) | **Must be done before #88 merges**: on the first start after it, nobody but `admin` holds a role. The roles' table, `console_roles`, is created by the migration at that start, beside the register's in `kf_admin`; then `admin` grants what the writers list implied ([Operations](Operations.md#from-the-writers-list-to-roles)) |
| `Authentication--SharedPassword` disabled (B3, [#89](https://github.com/KnowledgeFabric/kf-admin/issues/89)) | **Must be done before #89 merges**: every operator still on the shared password gets a secret of their own ([Operations](Operations.md#people)); then *Secrets → `Authentication--SharedPassword` → current version → Enabled: No*, restart, and check the login page no longer signs in without a name. The day goes on #89. Disabled rather than deleted, so that its versions stay as the record of it |
| `Gateway--AdminWriteToken` (B3), for revoking and restoring installations ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)) | **Not yet done.** Load it once #69 is deployed, and only then; the steps are [below](#the-write-token) |
| `Crm--BusinessCards--ApiKey` (B3), for adding a contact from a business card ([#161](https://github.com/KnowledgeFabric/kf-admin/issues/161)) | **Not yet done.** An Ollama API key of the console's own, loaded once #161 is deployed; the steps are [below](#the-business-card-key). Until then the page says reading a card is not configured |
| The audit log's table (Part C, [#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)) | Created by the migration at the first start after #69 deploys, beside the register's, in `kf_admin`. Nothing to do by hand |
| Access restrictions | **Deliberately not done** — see [Who can reach the console](#who-can-reach-the-console) |

---

## Before you start

- A subscription, and **`rg-kf-admin-weu-01`** — create it if it does not exist; every resource in
  this document goes in it. The one thing that does not is the App Service **plan**, which is the
  gateway's existing `P0v3` in `rg-kf-staging-weu-01`: an application and its plan are allowed to
  live in different resource groups, and this is what keeps "delete the group and the console is
  gone" true without moving something the gateway owns. The Portal has defaulted these create blades
  to West US 3 in the past, and the group's name says `weu`: check the region on every one of them
  regardless of what the group is called.
- Permission to create an app registration in Microsoft Entra ID, and to assign roles on the App
  Service and on the Key Vault. These are usually different people's rights; find out before you
  begin rather than halfway through.
- Access to DNS for `knowledgefabric.io`.
- Admin of this GitHub repository, to create the Environment and its secrets.
- **The private key, its new passphrase, and `admin`'s password**, in hand, before you
  start Part B. Read [Part B](#part-b--key-vault-and-the-signing-key) first: getting the key into
  Key Vault is the one step in this document that cannot be undone by deleting a resource and
  starting again.

---

## Part A — The App Service

### A1. Create it

*Create a resource → Web App.* The blade has seven tabs and the defaults are wrong on three of
them, so this goes tab by tab rather than listing only the Basics.

**Basics:**

| Setting | Value | Why |
|---|---|---|
| Resource group | `rg-kf-admin-weu-01` | |
| Name | `app-kf-admin` | |
| Publish | **Code** | Not Container. There is no image; the deploy is a `dotnet publish` package |
| Runtime stack | .NET 8 (LTS) | |
| Operating System | Linux | |
| Region | West Europe | Beside the gateway and the Key Vault |
| Pricing plan | **Existing → `P0v3`** | Pick it rather than creating one. It lives in `rg-kf-staging-weu-01` and the dropdown offers plans from other resource groups, which is what makes the shared-plan decision possible. See above |

**Database: none.** This blade offers to create a database and wire its connection string for you.
The register's database is a new database on the gateway's existing PostgreSQL server
([Part C](#part-c--the-registers-database)), not a new server — what this blade offers would bill
for a second one.

**Deployment:**

| Setting | Value | Why |
|---|---|---|
| Continuous deployment | **Disable** | **The important one.** *Enable* makes the Portal commit its own workflow file to the repository — a generic build-and-deploy that knows nothing about the fixture-set check and publishes the whole solution rather than the console. It would race this repository's `deploy.yml` on every push to `main`. The OIDC trust is set up by hand in [B6](#b6-app-registration-and-federated-credentials) instead, scoped to one App Service |
| Basic authentication | **Disable** | The same setting as *SCM Basic Auth Publishing*, and better set here than turned off afterwards. The deploy authenticates with OIDC; a publish profile is a long-lived credential this project has no use for, and the repository is deliberately rid of the one it had — the `LicenseTool.csproj.user` that #7 flagged was untracked in [#3](https://github.com/KnowledgeFabric/kf-admin/issues/3) |

**Networking:** defaults. Public access enabled, no VNet integration. Access restrictions are a
deviation taken deliberately — [Who can reach the console](#who-can-reach-the-console).

**Monitor + secure:**

| Setting | Value | Why |
|---|---|---|
| Application Insights | **Yes**, West Europe | Leaving it on makes [B5](#b5-application-insights) three checks and one deletion rather than a create |
| Microsoft Defender for App Service | **Off** | Billed per app. It is the one thing on this blade that turns the marginal cost of joining an existing plan from nothing into a monthly line item, and it defaults on in some subscriptions. Price it deliberately rather than accepting it |

**Tags:** whatever the organisation uses. Cheap now, tedious to backfill.

Then, on the created App Service:

- **Settings → Configuration → General settings → Always On = On.** The console is idle most of the
  time, which is exactly the case the platform idles the process out for. Without this, the first
  sign-in of the day pays a cold start, and — worse — the deploy's `/health` poll can time out
  against an app the platform has not bothered to start.
- **Health check** tab: path **`/health`**. The endpoint is anonymous and dependency-free on purpose
  (`Program.cs`): it answers on a cold start before any secret has been read. That is what lets the
  platform, and the deploy, tell "not started yet" from "started and broken". It is also why a green
  `/health` does **not** mean the console can reach Key Vault.
- **HTTPS Only = On**, and **Minimum Inbound TLS Version = 1.2**.
- **FTP state = Disabled.** SCM basic auth was already turned off on the Deployment tab above; this
  is the other publishing path, and it is no more wanted than that one. If the app was created
  without setting basic auth, turn it off here too: *General settings → SCM Basic Auth Publishing*.
- **Scale out: one instance, no autoscale rule.** See [Sharing the gateway's plan](#sharing-the-gateways-plan).
- **Deployment slots: none.** The plan has them, and the gateway wants one for key rotation. The
  console does not: its secrets are in Key Vault and are re-read on restart, so a rotation here is a
  restart, and a restart of an idle console costs one person one page reload. Adding one as a
  stand-in for the absent staging tier is a scheduled decision, with its two traps, under
  [Two consequences to schedule](#two-consequences-to-schedule).

### A2. DNS and the managed certificate

1. On the App Service, **Settings → Custom domains → Add custom domain**. The dialog opens with
   **Domain provider = App Service Domain**, which is the wrong branch: that means a domain bought
   through Azure as a resource in the subscription, and it reports *"No App Service Domain was found
   in the current subscription"* because there is none. Choose **All other domain services**.
   `knowledgefabric.io` is registered elsewhere.

   Leave the other two as they come: **App Service Managed Certificate** and **SNI SSL**.

   Enter `admin.knowledgefabric.io` and read the two values the dialog then shows: the App Service
   default hostname, and the **custom domain verification ID**.
2. At the DNS provider, create both records for `admin.knowledgefabric.io`:
   - `CNAME` → `app-kf-admin.azurewebsites.net`
   - `TXT` on `asuid.admin` → the verification ID

   **Validation fails until these exist**, so the first click on *Validate* is expected to fail and
   is not a sign anything is wrong.

   **On Cloudflare, the record must be DNS-only** — grey cloud, not orange. Managed certificate
   issuance fails against a proxied record and the error does not say that is why.
3. Back in the Portal, validate and add the domain.
4. **Add a free App Service Managed Certificate**, then bind it (SNI SSL).

   **SNI, never IP-based.** IP-based SSL allocates a dedicated inbound address so the app can serve
   a certificate to clients that do not send SNI, which no client this console will ever see still
   fails to do. It is billed, it consumes one of the shared plan's dedicated addresses — which is
   the gateway's capacity as much as this app's — and it changes the inbound IP, which is a poor
   thing to do to a DNS record that was just validated. The gateway's two hostnames are SNI for the
   same reasons.

   **These are two steps even though the dialog presents them as one.** Selecting *App Service
   Managed Certificate* while adding the domain can still leave the domain listed as **No
   binding** — the certificate is issued but nothing binds it to the hostname. Use the *Add
   binding* link against that row: certificate for this hostname, TLS/SSL type **SNI SSL**.

   **Then give it a few minutes.** Until the binding reaches App Service's front ends the hostname
   is served the platform's own `CN=*.azurewebsites.net` certificate, and `curl` fails with *no
   alternative certificate subject name matches target host name* — which reads like a
   misconfiguration and is only impatience. It is right when *Custom domains* shows **Secured** and:

   ```bash
   curl -i https://admin.knowledgefabric.io/health
   curl -vI https://admin.knowledgefabric.io/health 2>&1 | grep -i 'subject:'
   ```

   name the hostname rather than `*.azurewebsites.net`. Before the first deploy the status codes are
   **200 on `/` and 404 on `/health`** — the placeholder page App Service serves for an app with no
   content. `/health` answers 200 from the first deploy onwards, and it is the deploy that changes
   it, not anything here.

   A correct result looks like this, and is what this environment returned on 2026-09-23:

   ```
   subject:  CN=admin.knowledgefabric.io
   issuer:   DigiCert / GeoTrust TLS RSA CA G1
   verify:   ok
   http://   301 → https://          (HTTPS Only)
   ```

   The certificate renews itself, so there is nothing to diarise for its expiry.

If validation fails, it is almost always a record that has not propagated yet — wait rather than
changing anything.

---

## Part B — Key Vault and the signing key

**This is where this document stops following the gateway's.** The gateway keeps its provider key in
an App Service application setting, and that is a defensible choice there: a leaked provider key is
revoked in the provider's console and rotated through a slot swap, and by the next morning it is a
non-event.

The licensing private key is not like that. Its public half is compiled into every product image
and read by kf-ai-gateway too, so **it cannot be rotated in an afternoon**. kf-app trusts a list of
public keys (`BundledLicensingSettings.PublicKeys` in
`KnowledgeFabric.Logic/Services/Licensing/LicensingOptions.cs`, kf-app `c332de4`, kf-app#983), so on
its side a rotation is a release trusting old and new, with no licence reissued. kf-ai-gateway
trusts the same list (`TrustedLicenceKeys.All`, verified by `StandardLicenceEvaluator`,
kf-ai-gateway `ebb48b3`, kf-ai-gateway#7), so a rotation is a release of each, in the order
[Operations](Operations.md#rotating-the-key-pair) gives. And even a clean rotation does not revoke: a
leaked key keeps signing licences every installation accepts until a release drops it from the
list. The key gets a Key Vault, RBAC, purge protection, and an identity that the deploy pipeline does
not have.

### B1. Create the vault

*Create a resource → Key Vault*, in `rg-kf-admin-weu-01`, **West Europe**.

| Setting | Value | Why |
|---|---|---|
| Name | `kv-kf-admin-weu` | Named for the console, not for licensing — see the rule in [B3](#b3-load-the-secrets). Globally unique across Azure; if it is taken, suffix it and use the real name everywhere below |
| Pricing tier | Standard | HSM-backed keys are the Premium feature. The private key is stored as a *secret* — an opaque blob — not as a Key Vault *key*, because signing happens in-process through Standard.Licensing and BouncyCastle |
| Permission model | **Azure role-based access control** | Not the legacy access policies. RBAC is what `Key Vault Secrets User` in B2 assigns, and it is auditable next to every other role assignment in the subscription |
| Soft-delete retention | 90 days | A deleted secret is recoverable for this long. On by default and not removable |
| **Purge protection** | **Enabled** | **Create-time is the sensible time, and it cannot be turned off again.** With it, nobody — including an owner, including a compromised credential — can hard-delete a secret before its retention expires. Given that the key cannot be rotated, "somebody deleted it and emptied the bin" must not be a reachable state |
| Public network access | Enabled | Private endpoints are the tidier end state and need more network than this estate has. Access is by RBAC and Entra ID, not by address |

### B2. The Web App's identity, and who may read

1. **App Service → Settings → Identity → System assigned → On.** This creates a service principal
   that exists only as long as the App Service does and has no credential anyone can copy.
2. **Key Vault → Access control (IAM) → Add role assignment → `Key Vault Secrets User` →** assign to
   that managed identity. *Secrets User* reads secret values; it cannot write, list versions'
   metadata for other purposes, or delete. The console never writes a secret.
3. Give the people who will load the secrets in B3 **`Key Vault Secrets Officer`**, scoped to this
   vault, for as long as that takes. Owner of the subscription does **not** grant data-plane access
   under the RBAC permission model — this is the step that surprises people, usually at the moment
   they are trying to upload the key.

   **Officer, not User.** The two roles sit next to each other in the picker and only one of them
   can write: `Key Vault Secrets User` is get and list, so a person holding it can read every secret
   here and still be refused at B3's first *Generate/Import*. `Key Vault Secrets Officer` adds set,
   delete, recover and restore. If both end up assigned to the same person, remove the User one —
   Officer already includes reading, and on this vault a role list that reads clean at a glance is
   worth the ten seconds.

When it is right, the vault's *Access control (IAM) → Role assignments* shows exactly two
assignments at **This resource** scope, and the Type column is what distinguishes them:

| Principal | Type | Role |
|---|---|---|
| `app-kf-admin` | **Managed identity** | `Key Vault Secrets User` |
| Whoever loads the secrets | User | `Key Vault Secrets Officer` |

Everything else in that list is inherited from the subscription — Owner, Contributor, Reader and
the rest. Those are management-plane roles and none of them reads a secret, which is the whole
point of the permission model chosen in B1. It is worth being clear-eyed about the limit of that,
though: a subscription Owner can assign themselves `Key Vault Secrets Officer`, and a Contributor
can switch the vault back to access policies and grant themselves one. Neither is silent — both
are role or configuration changes on the resource, and both show in the Activity log — but the
separation this document builds is *auditable*, not absolute. Who holds Owner and Contributor on
this subscription is therefore part of who can reach the signing key.

**The deploy pipeline is not in this list and must never be.** Its app registration (B6) gets
`Website Contributor` on the App Service and nothing on the vault. That is the property the whole
design rests on: a GitHub workflow can replace the console's code, but cannot read the key the
console signs with, and no workflow run has ever had a path to that value.

### B3. Load the secrets

**This is the one-time, witnessed operation.** Do it with a second person present, and read all of
it before starting.

The private key exists on one developer machine and nowhere else. Once it is in Key Vault, Key Vault
is one of only two copies. **Before you upload, make the offline copy** — encrypted, on removable
media, in a safe. Purge protection stops the vault losing it; it does not stop the subscription
being lost, and the recovery story for "the key is gone" is that there is none.

**Two complete copies, not two halves.** Splitting the key and its passphrase between locations
protects against one being stolen and *doubles* the chance of loss, because either half going
missing is equally fatal — a passphrase lost with the file intact is the same outcome as losing the
file. Availability is the likelier failure here, so unless a specific insider-threat model says
otherwise, seal the key and its passphrase together and put a complete copy in each of two places.
[Operations](Operations.md#which-failure-you-are-actually-having) sets out why.

**Then close the loop on the machine it came from.** The copy this key was generated on is still a
working private key, and until `rekey` it was protected by a passphrase anyone with repository
access could recover. Deleting it — and any backup of the folder holding it — is part of this step,
not an afterthought, and it is not done until whoever holds that machine confirms it.

**#3's `rekey` came first, and has been done.** The passphrase that encrypted the private key until
then is committed in this repository's history, in kf-app's `launchSettings.json`, and in kf-app's
docs — loading the key under it would have moved a known secret into a good vault. `rekey`
re-encrypted the *same private key* under a new passphrase; the key pair and every licence ever
issued are untouched. The new passphrase is what goes in below, and never the old one.

*Key Vault → Objects → Secrets → + Generate/Import*, once for each:

| Secret name | Value | Read by |
|---|---|---|
| `Licensing--PrivateKey` | The contents of `private.key` — one base64 blob, exactly as the file holds it | #6's signing path |
| `Licensing--PrivateKeyPassphrase` | The **new** passphrase from `rekey` | #6's signing path |
| `Authentication--SharedPassword` | **Retired** ([#89](https://github.com/KnowledgeFabric/kf-admin/issues/89)): the console's shared sign-in password, with no name, from #15 until every operator had a name of their own. Disabled, never deleted, and not loaded into a new vault | Nothing. A value still configured is ignored, with a warning at startup (`RetiredSharedPassword`) |
| `Authentication--Users--<name>` | One per person: the password they sign in with under `<name>`, which is letters, digits and single hyphens. Added later, one at a time, as people join; what each may do is the roles granted to the name on the Users page ([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)) | `ConsoleCredentials` |
| `Authentication--Users--admin` | The password of the name `admin`, which holds every role by construction and grants everyone else theirs ([#88](https://github.com/KnowledgeFabric/kf-admin/issues/88)). **It must exist, and the console have restarted, before the first deploy of #88**: from that start nobody but `admin` holds a role until `admin` grants one ([Operations](Operations.md#from-the-writers-list-to-roles)) | `ConsoleCredentials`, and `SessionRoles` by name |
| `Gateway--AdminToken` | The gateway's `Admin__ReadToken` — see below | The register's installations (#58) and the AI Gateway area (#64), through `GatewayAdminClient`, on every read |
| `Gateway--AdminWriteToken` | The gateway's `Admin__Token` — see [the write token](#the-write-token). Added with #69, and not before | Revoke and restore (#69), through `GatewayAdminClient`, on writes alone |
| `Crm--BusinessCards--ApiKey` | An Ollama API key of the console's own — see [the business card key](#the-business-card-key). Added with #161 | Reading a business card into a new contact (#161), through `OllamaBusinessCardReader` |

**`Gateway--AdminToken` is not part of the witnessed operation**, and was added later, alone, on
2026-09-26. It is the **read-only** bearer token of the gateway's operator surface (kf-ai-gateway
`docs/Admin.md`, *The tokens*; [kf-ai-gateway#40](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/40)),
which the console reads to show which installations run each licence
([License Register](License-Register.md#installations)) and what the gateway says of itself
([Gateway Management](Gateway-Management.md)). Without it the console starts, and those pages say
the gateway is not configured.

1. **Give the gateway its tokens, or read them.** They are the `Admin__Token` and `Admin__ReadToken`
   application settings on `app-stg-ai-gw`, the App Service behind `ai.knowledgefabric.io`.
   `Admin__Token` maps `/admin` and is accepted on every method; `Admin__ReadToken` is accepted on
   `GET` alone. If the gateway has neither, generate both with `openssl rand -base64 32`, distinct
   (the gateway refuses either shorter than 32 characters, and refuses to start with the two equal),
   and set them in one *Apply*, which restarts the gateway and drops any chat streaming at the time.
2. **Add the read token here** as `Gateway--AdminToken`, then restart the console. The write token
   is a separate secret, below, added only once the console writes.
3. **Check** a register row's *Installations* section, or *AI Gateway* in the menu. The section lists
   installations, or says none has enrolled with the licence; the area says the gateway does not
   report status yet until kf-ai-gateway#37 is deployed. Anything else is in
   [Operations](Operations.md#a-licences-installations-or-the-gateways-status-are-missing).

It sits next to the signing key because it is this application's configuration, per the rule below.
It is the read token, so a console that leaked it would leak a dashboard and not a revoke button;
that is what the gateway has two tokens for. Rotate it on the gateway and here together, and a
mismatch shows as a refused token rather than anything worse. **When `ai.knowledgefabric.io` moves
to a production gateway**, this must become that
gateway's token; `Gateway:BaseUrl` stays as it is, because the hostname moves with it.

#### The write token

**`Gateway--AdminWriteToken` is the gateway's `Admin__Token`**, the one it accepts on every method,
and the console's first credential that can change the gateway: it revokes and restores
installations ([#69](https://github.com/KnowledgeFabric/kf-admin/issues/69)) and changes policy
([#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)). The console sends
it on writes alone; every read keeps the read token. Without it the console reads the gateway and
changes nothing: every write control is disabled and says why, and no write is attempted.

It is a separate secret, and was added only when the writes shipped, so that for as long as the
console only read, a leak of what it held was a dashboard and not a revoke button.

1. **Before loading it, check who holds *Gateway: Write*** on the console's Users page
   ([Operations](Operations.md#people)): they, `admin` and any Administrator are who can use it.
   Since #88 nobody else can.
2. **Copy the gateway's `Admin__Token`**: `app-stg-ai-gw` → *Settings* → *Environment variables*, its
   value. Not `Admin__ReadToken`: that one the gateway refuses on a write, and the console says so.
3. **Add it here** as `Gateway--AdminWriteToken` (*+ Generate/Import*), then restart `app-kf-admin`.
4. **Check** an installation's page (*AI Gateway* → *Installations*, then one of them): it offers
   *Revoke…* instead of saying the console has no write token. Revoking is real; to check without
   changing anything, open the confirm step and cancel.

Rotate it on the gateway and here together, as the read token. A mismatch shows on the confirm step
as the gateway refusing the console's token, and changes nothing.

#### The business card key

**`Crm--BusinessCards--ApiKey` is an Ollama API key**, sent as a bearer token to Ollama Cloud's
`/api/chat` when someone adds a contact from a photo of a business card
([#161](https://github.com/KnowledgeFabric/kf-admin/issues/161), [CRM](CRM.md#from-a-business-card)).
Without it the console starts, and the page says reading a card is not configured.

**The console's own key, not the gateway's.** kf-ai-gateway holds an Ollama key too
(`AI_GATEWAY_OLLAMA_API_KEY` on `app-stg-ai-gw`), for the model behind its alias; reusing it would
put the console's card reads on the bill and in the limits of the customers' AI, and a rotation of
either would break the other. A key of its own is revoked, rotated and watched alone.

1. **Create the key** at [ollama.com/settings/keys](https://ollama.com/settings/keys), signed in as
   the team's Ollama account, named for the console (`kf-admin business cards`).
2. **Add it here** as `Crm--BusinessCards--ApiKey` (*+ Generate/Import*), then restart `app-kf-admin`.
3. **Check** *CRM → Partnerships → From a business card*: it offers *Take a photo* instead of saying
   reading is not configured. Read a card you hold; nothing is added until the form is saved.

**The model is an application setting, not a secret.** `appsettings.json` names `gemma4:31b`, a model
Ollama Cloud lists with the `vision` capability. Ollama retires cloud models with notice
([its usage settings](https://ollama.com/settings) list the dates); when it does, set
`Crm__BusinessCards__Model` on `app-kf-admin` (*Settings → Environment variables*) to another model
`curl https://ollama.com/api/tags` lists with `vision`, and restart. A retired model shows on the
page as an answer that was not a reading of the card ([Operations](Operations.md#a-business-card-is-not-read)).

**What leaves the console.** The photo of the card, what a QR code on it says and, when that is a
link, what the page it leads to says (#163), and nothing else: Ollama processes it to answer and,
by [its own account](https://docs.ollama.com/cloud), does not train on it. The console keeps none of
it. Following the link is a request from the console to whatever site the card names, to a public
address only ([CRM](CRM.md#a-qr-code-on-the-card)); it needs nothing configured, only the outbound
access the App Service already has. Whether that suits the programme's privacy notice is the team's call, as the
lawful basis for the CRM is ([CRM](CRM.md#personal-data)).

**The double hyphen is not decoration.** The console loads the whole vault as configuration
(`AddAzureKeyVault` in `Program.cs`), and the Key Vault configuration provider maps `--` to `:`
because a secret name cannot contain a colon. `Licensing--PrivateKey` arrives as
`Licensing:PrivateKey`. A secret named with a single hyphen, or with a colon, does not bind to
anything and fails silently.

Two consequences of loading the whole vault, both worth holding onto:

- **Every secret in this vault becomes the console's configuration**, which is why it is named for
  the console rather than for licensing: `Licensing--PrivateKey` sits beside
  `Authentication--Users--<name>` today, and beside whatever the console's second feature needs
  tomorrow. The rule is therefore sharper than "put nothing else in it" — put nothing in it that is
  not *this application's* configuration. The day a feature wants a secret that should not sit next
  to the signing key, that is a second vault and a second `AddAzureKeyVault` call, not another
  secret in here.
- **Configuration is read at startup.** A changed secret reaches the console on its next restart,
  not before. That is what makes [rotating the passphrase](Operations.md) a restart, and it is the
  first thing to check when a secret you have just set does not appear to have taken effect.

> **A secret in this vault cannot be deleted and recreated.** Getting a value wrong and reaching
> for delete-then-add-it-again is the obvious move, and it fails: the deleted secret sits in the
> soft-deleted state for 90 days, purge protection ([B1](#b1-create-the-vault)) forbids purging it,
> and the name stays reserved — so the Portal refuses the new secret because one "already exists".
> That is purge protection doing its job rather than a fault.
>
> The fix is *Secrets → **Manage deleted secrets** → Recover*, then **+ New Version** on the
> recovered secret. The new version becomes current, which is what the console reads; the wrong
> value stays in the version history, unused. `Key Vault Secrets Officer` includes recover, so
> whoever loaded the secrets can do it.
>
> **A correction is therefore a new version, never a delete.** Worth knowing before a value needs
> fixing rather than during — and worth knowing that a wrong value can be superseded and disabled
> but never removed, so a secret pasted into the wrong field is in the vault's history for good.

> **Each `Authentication--Users--<name>` holds the password, not a hash of it.** #7 described it as "the login password hash"; the shell built in #15 compares
> SHA-256 digests of the submitted and configured *passwords* so the comparison runs in constant
> time (`ConsoleCredentials`), which needs the password itself. Storing a hash here would make the
> hash the password. This is worth knowing rather than fixing: per-person identity through Entra ID
> retires every password here
> altogether, and is the answer #15 already names.

### B4. Application settings

**Settings → Environment variables → App settings**, then *+ Add*. (Not *Configuration*, which now
holds only platform settings — the Portal moved these out of it.) They are set here, by hand, and
**the deploy never writes them**: it ships code only.

| Setting | Value | Why |
|---|---|---|
| `KeyVault__Uri` | `https://kv-kf-admin-weu.vault.azure.net/` | The only thing pointing at the vault. Absent, the console starts without it — which is the normal local case, and is why `/health` answers on a cold start |
| `ApplicationInsights__ConnectionString` | The connection string from B5 | See the warning below |
| `ApplicationInsights__EnableAdaptiveSampling` | `false` | |
| `ASPNETCORE_ENVIRONMENT` | `Production` | The default, but stated: it is what turns the developer exception page off |

`Gateway:BaseUrl` is not in this table: `appsettings.json` carries it, as `https://ai.knowledgefabric.io`,
because it is the address every installation enrols at rather than something this environment
chooses. A `Gateway__BaseUrl` setting here would override it; there is no reason to add one.

**No secret value appears in this table, and none ever should.** `KeyVault__Uri` is a URL; the
things it reaches are the secrets. Key Vault *references*
(`@Microsoft.KeyVault(SecretUri=...)` in an app setting) are the other way of doing this and the
console does not use them — it reads the vault itself through its managed identity, so there is one
mechanism rather than two, and an app setting holding a resolved secret value is never a state this
App Service can be in.

> **`APPLICATIONINSIGHTS_CONNECTION_STRING` is not the setting this application reads.** The App
> Service writes that one for you when it creates the Application Insights resource, and it looks
> like the job is done. It is not: `Program.cs` gates telemetry on
> `ApplicationInsights:ConnectionString`, and an environment variable with underscores does not bind
> to a nested configuration key. Set `ApplicationInsights__ConnectionString` — double underscore —
> or telemetry stays off with every sign that it is on. Leaving the auto-created one in place as
> well is harmless.

**Sampling is off, by decision.** Adaptive sampling drops what it judges repetitive, and on an
application whose whole telemetry volume is a few hundred requests a week the thing it would drop is
a failed sign-in in a run of them. The audit trail is the point of this application having telemetry
at all. Volume is not a cost worth managing here.

**A setting is not live until you confirm it.** The blade stages your edits, *Apply* opens a
confirmation, and only then does the App Service restart and the process see them. Skipping that
dialog leaves the old value in force.

### B5. Application Insights

**There is probably one already**, created with the App Service in A1 and named after it — so
`app-kf-admin` is *two* resources of different types. Tell them apart by the type column in the
resource group, or by the left nav: *Deployment Center* and *Environment variables* is the App
Service, *Logs* and *Live Metrics* is Application Insights.

**Delete the agent settings.** On the **App Service**, *Settings → Environment variables → App
settings*, remove:

```
ApplicationInsightsAgent_EXTENSION_VERSION
XDT_MicrosoftApplicationInsights_Mode
```

These turn on agent-based ("codeless") collection, which the App Service enables when it creates the
resource for you. The console instruments itself through `Microsoft.ApplicationInsights.AspNetCore`,
and an agent attached on top of that reports every request twice. Apply, and confirm the dialog.

**Give it a workspace of its own.** The auto-created resource points at the subscription default
workspace, `DefaultWorkspace-<subscription-id>-WEU`. Create `log-kfadmin-weu-1` in
`rg-kf-admin-weu-01`, West Europe, and move it: *Application Insights → Configure → Properties →
Change Workspace*.

> **Create a "Log Analytics workspace", and check you got one.** The marketplace offers several
> things called *workspace* and the search results sit next to each other — **Azure Monitor
> workspace** (`Microsoft.Monitor/accounts`, which is for Prometheus metrics) is the one that gets
> picked by mistake. It cannot hold Application Insights data and never appears in the *Change
> Workspace* picker, so the symptom is the workspace you just created not being in the list.
>
> Confirm before going further, because the two are hard to tell apart on the Overview blade: the
> resource group's **Type** column should read **Log Analytics workspace**, and the resource's own
> subtitle says the same rather than just *Workspace*. A working one shows **Workspace ID**,
> **Pricing tier** and **Retention** in Essentials, and carries *Logs*, *Tables* and *Usage and
> estimated costs* in its left nav — that last is where retention is set below, so a resource
> without it would have blocked the next step anyway. Delete the wrong one; nothing is using it. Retention is a workspace setting, so the 30 days below would otherwise re-set retention
for everything else writing to the default workspace; and read access is a workspace grant, which
matters here because **this workspace records who signed in to the licence issuing console and
when**. The connection string belongs to the Application Insights resource rather than to the
workspace, so nothing needs redeploying; telemetry already ingested stays in the old workspace and
is not migrated, so do this before there is anything worth keeping.

**Set retention.** On the workspace, *Usage and estimated costs → Data Retention*: **30 days**. A new
workspace usually defaults to 30 already — check it rather than assuming, because the default has
moved between Portal releases and nothing announces it when it does.

**What is in here.** Request telemetry for an internal console: URLs, status codes, timings, and the
audit entries `LoggingAuditLog` writes through `ILogger`. Not in here: the private key, the
passphrase, anyone's password, or any licence's contents — the audit seam records the outcome of
an action rather than its payload (`AuditActionFilter`), and nothing enables request-body capture.
Whoever can query this workspace can see that a licence was issued and by which session; not what
was in it. The register (#8) is what holds that, deliberately.

### B6. App registration and federated credentials

1. *Microsoft Entra ID → App registrations → New registration.* Name it `kf-admin-deploy-production`.
   No redirect URI.
2. *Certificates & secrets → **Federated credentials** tab → Add credential.* Choose the **GitHub
   Actions deploying Azure resources** scenario:
   - Organization `KnowledgeFabric`, Repository `kf-admin`
   - **Organization ID** `142328979`, **Repository ID** `1254144758` — the form asks for GitHub's
     numeric ids, which are awkward to find for a private repository. They come from
     `api.github.com/orgs/<org>` and `api.github.com/repos/<org>/<repo>`.
   - Entity type **Environment**, environment name **exactly** `production`

   **Create this credential twice, with both subject formats.** The blade builds a subject in
   GitHub's *immutable claims* form, which embeds those numeric ids:

   ```
   repo:KnowledgeFabric@142328979/kf-admin@1254144758:environment:production
   ```

   GitHub only sends that form if the organisation has opted into immutable OIDC claims. Otherwise
   it sends the classic one:

   ```
   repo:KnowledgeFabric/kf-admin:environment:production
   ```

   For the second credential, use the *Edit (optional)* link beside **Subject identifier** and type
   the classic form. Whichever GitHub actually sends then matches one of them. Two credentials cost
   nothing — each is the same narrow statement about one repository and one environment — and a
   mismatch otherwise surfaces as an unhelpful `azure/login` failure at the very end of a deploy,
   after the publish has already happened. Issuer and audience are correct as they come.
3. **Do not create a client secret.** The point of OIDC is that there is no stored credential.
   Client secrets live on a different tab of the same blade; the federated one is the other.
4. On the **App Service** — not the resource group, and not the subscription:
   *Access control (IAM) → Add role assignment → **Website Contributor** →* assign to this app
   registration. Scoping to the one App Service is what keeps the blast radius to one application.
   **Assign nothing on the Key Vault** (B2).
5. Record from the registration's Overview: **Application (client) ID** and **Directory (tenant)
   ID**. Take the **Subscription ID** from the subscription blade.

### B7. GitHub Environment and its secrets

*Repository → Settings → Environments → New environment*, named **exactly** `production`.

**Secrets:**

| Secret | From |
|---|---|
| `AZURE_CLIENT_ID` | B6 step 5 |
| `AZURE_TENANT_ID` | B6 step 5 |
| `AZURE_SUBSCRIPTION_ID` | B6 step 5 |

**Variables** — not secrets, because masking them would blank the deployed URL out of exactly the
log a failed deploy needs to show:

| Variable | Value |
|---|---|
| `AZURE_WEBAPP_NAME` | `app-kf-admin` |
| `AZURE_RESOURCE_GROUP` | `rg-kf-admin-weu-01` |

**Nothing here is a credential for the console itself.** What these grant is the right to deploy
code to one App Service. The secrets the console uses are in Key Vault, reachable only by the App
Service's own identity, so a workflow log has nothing to leak — that is a property of the design
rather than a promise about masking.

**No required reviewer yet, and that is a dated decision.** `production` is the only Environment, so
a reviewer on it gates every deploy — friction worth paying once the console can issue a licence and
not before. Add it at #6: *Settings → Environments → production → Required reviewers*.

---

## Part C — The register's database

The register of issued licences ([License Register](License-Register.md)) is a PostgreSQL database,
`kf_admin`, on **the gateway's existing Flexible Server**, `pgsql-aigw-stg-weu-1`. [#8](https://github.com/KnowledgeFabric/kf-admin/issues/8)
chose that on 2026-09-24; the reasons, and what sharing the server costs, are on that page.

**Until this part is done the console runs without it**: the register page says it has no database,
reads are empty, and recording is refused — so issuing (#6) cannot hand out a licence the register
has not recorded. Nothing else changes.

> **#8's database is a precondition on #6, not a parallel ticket.** Without a register, the only
> trace of an issued licence is `LoggingAuditLog`'s line in Application Insights — on a workspace
> this document sets to **30-day retention** (B5), after which there is nothing at all. And by
> design an audit entry records the *outcome* of an action rather than its payload
> (`AuditActionFilter`), so even inside those 30 days it shows that a licence was issued and by
> which session, never what was in it. Do this part before the first licence is issued from the
> console, not after.

**Done on 2026-09-24**, after a rehearsal the same day against a local PostgreSQL 16 set up the same
way. On Azure the database and login were first created under the old names below and renamed.

**Created under the old names?** An earlier version of this page said `kf_licensing` /
`kf_licensing_app`. Rename rather than recreate, connected to `postgres`, with nobody connected to
the database: `ALTER DATABASE kf_licensing RENAME TO kf_admin;` then
`ALTER ROLE kf_licensing_app RENAME TO kf_admin_app;`. A SCRAM password survives the rename; if
PostgreSQL reports that it cleared an MD5 one, set it again with `ALTER ROLE kf_admin_app PASSWORD '…';`.

### C1. The database and its login

This is section A2 of
[the gateway's doc](https://github.com/KnowledgeFabric/kf-ai-gateway/blob/main/docs/Provisioning-Environments.md)
once more. Read its **What sharing costs** first. Its note on the `\l` that breaks in Cloud Shell
applies here too.

The database and its login are named after the console, `kf_admin` / `kf_admin_app`, the way the
gateway's are named after the gateway — not after licensing, which is only the console's first
feature. A second feature's tables go in the same database.

**Getting a `psql` prompt — as yourself, with no password.** The server accepts Microsoft Entra
sign-in as well as PostgreSQL passwords, and an Entra administrator of the server has the same rights
as the password admin. So there is no admin password to find: open **Cloud Shell** from the Portal's
top bar (the `>_` icon), choose **Bash**, and paste what the server's *Connect* blade shows:

```bash
export PGHOST=pgsql-aigw-stg-weu-1.postgres.database.azure.com
export PGUSER=<your Entra sign-in, e.g. name@example.org>
export PGPORT=5432
export PGDATABASE=postgres
export PGPASSWORD="$(az account get-access-token --resource https://ossrdbms-aad.database.windows.net --query accessToken --output tsv)"
psql
```

Cloud Shell is already signed in to Azure, and it runs inside Azure, so the Azure-services firewall
rule admits it. The token lasts about an hour; if `psql` later reports `password authentication
failed`, re-run the `PGPASSWORD` line and start `psql` again. If your sign-in is not an Entra
administrator of the server, the server's *Authentication* blade is where one is added.

The applications' own logins are unaffected by any of this: `kf_gateway_app` and `kf_admin_app` are
ordinary password logins, because an App Service needs a connection string it can hold.

Generate the password from a password manager: **40 characters of letters and digits, no symbols**
— it has to survive Npgsql's connection-string parser, where `;` ends a field.

```sql
CREATE ROLE kf_admin_app LOGIN PASSWORD '...';

CREATE DATABASE kf_admin;
REVOKE CONNECT ON DATABASE kf_admin FROM PUBLIC;
GRANT  CONNECT ON DATABASE kf_admin TO kf_admin_app;
```
```
\c kf_admin
```
```sql
ALTER SCHEMA public OWNER TO kf_admin_app;
```
```
\c postgres
```
```sql
ALTER DATABASE kf_admin OWNER TO kf_admin_app;
```

**The order is the whole trick**, and the gateway's doc says why: roles first, `REVOKE`/`GRANT` while
the admin still owns the database, the schema before the database. The console's migration creates
its table in `public`, and fails with `42501: permission denied for schema public` if the schema
was not handed over.

**Check it**, reading the catalogue directly:

```sql
SELECT datname, pg_get_userbyid(datdba) AS owner, datacl
FROM   pg_database
WHERE  datname = 'kf_admin';
```

The owner is `kf_admin_app` and the ACL is
`{=T/kf_admin_app,kf_admin_app=CTc/kf_admin_app}` — PUBLIC holds `T` and not `c`.

**Then prove the isolation in both directions**, because a database on a shared server is only
acceptable if its login can reach nothing else. Still connected as yourself:

```sql
SELECT datname, pg_get_userbyid(datdba) AS owner, datacl
FROM   pg_database
WHERE  datname LIKE 'kf_%';
```

`kf_admin_app` must appear on the `kf_admin` row and no other, no gateway login may appear on the
`kf_admin` row, and every row's ACL must open `=T/` — never `=Tc/`, which is CONNECT for everyone.
If any of that is not so, stop.

Do not prove it with `\c kf_gateway kf_admin_app` from the same session. `PGPASSWORD` holds your
Entra token, and `psql` offers it as the password for whichever login you name, so the attempt fails
on authentication before it ever reaches the permission being tested — a refusal that proves nothing.
To see the refusal itself, leave `psql` and connect with the app login's own password:

```bash
PGPASSWORD='<kf_admin_app password>' psql "host=pgsql-aigw-stg-weu-1.postgres.database.azure.com dbname=kf_gateway user=kf_admin_app sslmode=require"
```

It must be refused with `permission denied for database`.

**If you are locked out of the database** because the steps ran out of order, the gateway doc's
`SET ROLE` rescue works as yourself too — quote the Entra name, which contains `@` and `.`:
`GRANT CONNECT ON DATABASE kf_admin TO "name@example.org";`

### C2. The connection string, in Key Vault

As one line:

```
Host=pgsql-aigw-stg-weu-1.postgres.database.azure.com;Database=kf_admin;Username=kf_admin_app;Password=...;SslMode=Require
```

It goes in `kv-kf-admin-weu` as the secret **`Database--ConnectionString`**, beside the others from
B3 — not in an application setting. It is as much a secret as the passphrase, and the vault is
already there. The console reads it as `Database:ConnectionString` through the same `--` mapping.

No firewall change is needed: the server already allows *public access from any Azure service
within Azure* (gateway A1), which admits the console's App Service.

### C3. Restart and read the log

*App Service → Overview → Restart.* On the way up the console migrates the schema before it
serves anything. In *Log stream*, look for `Applying migration '…_CreateIssuedLicences'`, then
`Database schema is current.`, then `Now listening on`.

If the process instead exits, the log says why, and nothing in it contains the password. A console
that will not start is the designed answer to a database it cannot use —
[Operations](Operations.md#the-register-and-its-database) has the cases. To back out, **disable**
the secret (*Secrets → Database--ConnectionString → current version → Enabled: No*) and restart: the
console returns to running without a register. Disable rather than delete — a deleted secret's name
stays reserved until it is purged ([Operations](Operations.md#a-secret-cannot-be-recreated-after-deleting-it)).

Then open **Licensing → Licence register**. The "no database" warning is gone and the list is empty.

## Who can reach the console

**Today: anyone who can resolve `admin.knowledgefabric.io`.** There are no access restrictions, and
a password plus the sign-in rate limiter are the whole of the control. That is a deliberate
choice, taken on 2026-09-22 and reaffirmed on 2026-09-23, and it is a deviation from #7's task list,
which asks for access restrictions to office and VPN ranges "at minimum".

What the console does have: HTTPS only, a session cookie that is `Secure`, `HttpOnly` and eight
hours long, a fixed-window limiter of 10 sign-in attempts per minute per address, a lockout after
5 failed attempts for 15 minutes per address and per name — and an audit entry for every mutating
action. Since [#68](https://github.com/KnowledgeFabric/kf-admin/issues/68) it also has names, a
secret per person, so the audit trail can say who, and since [#89](https://github.com/KnowledgeFabric/kf-admin/issues/89)
nothing else signs in: the shared password is retired
([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) roles per area, so a name
reaches only the areas it was granted
([Console Shell](Console-Shell.md#authorisation-is-roles-per-area-held-in-the-database-and-granted-on-the-users-page)).
What it still does not have is any control on where a sign-in comes from: behind whichever
credential is the key that signs every KnowledgeFabric licence.

Two upgrades, either of which closes that, in the order they are cheap:

1. **App Service access restrictions.** *Settings → Networking → Access restriction* on the App
   Service: allow the office and VPN ranges, deny all else. Minutes of work, no code. Remember
   `scm` has its own rule set on the same blade, and that the deploy reaches the app through Azure's
   control plane rather than through the site, so restricting the site does not break it.
2. **Entra ID authentication.** Either "Easy Auth" (*Settings → Authentication*) in front of the
   app, or the OpenID Connect handler inside it — `AuthenticationRegistration.AddConsoleAuthentication`
   is the seam #15 built for exactly this, and swapping it changes no page, no controller and no
   policy. It replaces the per-person secrets with the tenant's identities and each role with a
   group, once a tenant KnowledgeFabric controls exists.

Both were considered again on 2026-09-26 and deferred as too early
([#63](https://github.com/KnowledgeFabric/kf-admin/issues/63), decision 4). The day to revisit is
the first customer installation, or the first person leaving who held a password.

### The hostname is not a secret, and cannot be made into one

Considered on 2026-09-23 and rejected: naming the host something unguessable rather than `admin`,
so that it is not found in the first place.

It does not work, for a reason that has nothing to do with how good the name is. **Every
publicly-trusted certificate is published to Certificate Transparency logs** — including the free
App Service Managed Certificate bound in [A2](#a2-dns-and-the-managed-certificate). CT is mandatory
for trusted CAs and there is no opt-out, so a query for `%.knowledgefabric.io` at `crt.sh` returns
every hostname this organisation has ever certified, usually within minutes of issuance. Scanners
read those logs as a discovery feed. An obscure name is public the moment step A2 completes.

Two things follow that are worth stating plainly, because the instinct behind the idea is sound even
though the mechanism is not:

- **The default hostname stays reachable regardless.** `app-kf-admin.azurewebsites.net` is bound and
  serving whatever the custom domain says, and those are enumerable without CT at all.
- **What obscurity does buy is quieter logs, not less risk.** Dictionary subdomain scanning does try
  `admin`, `portal`, `vpn`; a different name avoids some of that noise. The rate limiter and the
  lockout already handle noise. It buys nothing against anyone who read the log.

So the memorable name is kept, on the understanding that it was never the control. The control is
the access restriction above — which does not hide the console from a scanner but makes it
unreachable by one, and a hostname in a CT log is useless to someone whose packets get a 403 at the
front door. If this question comes round again, it is that blade it should be settled on, not DNS.

---

## Verifying the whole thing

In order, because each one answers a question the one before it cannot:

```bash
# 1. The platform is serving, and the certificate is the right one.
curl -sI https://admin.knowledgefabric.io/health | head -1
curl -vI https://admin.knowledgefabric.io/health 2>&1 | grep -i 'subject:'

# 2. The application started. /health is anonymous and dependency-free, so this passes even
#    when the console cannot read a single secret.
curl -s -o /dev/null -w '%{http_code}\n' https://admin.knowledgefabric.io/health   # 200

# 3. An anonymous request for a real page is redirected to sign-in rather than served.
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://admin.knowledgefabric.io/   # 302 .../account/login
```

4. **Sign in as `admin`.** This is the first step that proves Key Vault works, because
   it is the first thing that reads a secret. If it fails, [Operations](Operations.md) has the three
   causes.

5. **Telemetry is arriving.** In *Logs*:

   ```kusto
   requests | where timestamp > ago(15m) | project timestamp, name, url, resultCode
   ```

   The sign-in should be there. `/health` rows appearing in bulk mean agent-based collection is still
   on — the deletion in B5 did not take, or was not confirmed. Nothing at all means
   `ApplicationInsights__ConnectionString` is not set under that exact name (B4).

---

## What is deliberately not here

- **The private key's value and the passphrase.** They exist on removable
  media in a safe and in Key Vault. Nowhere else, ever — not in this repository, not in an
  application setting, not in a workflow log.
- **Rotating anything.** [Operations](Operations.md) has the runbooks, and the difference between
  rotating the passphrase (cheap) and rotating the key pair (a release of kf-app plus reissuing every
  licence in the field) is the most important thing in them.
- **A container image.** The console deploys as a `dotnet publish` package, like the gateway.
- **Bicep or Terraform.** #7 made it optional and the doc mandatory. One environment built once, by
  hand, following this page, does not repay a template — and a template nobody re-runs rots quietly
  where a doc someone follows does not. That argument gets weaker the moment there is a second
  environment to keep identical, which is another reason the decision above is worth holding to.
- **A staging or sandbox environment.** Not deferred — declined, on 2026-09-23. What replaces it is
  the fixture set and #6's validate page, and the reasoning is under
  [Why one is enough](#why-one-is-enough-and-what-it-costs).
</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.
- [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.
- [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
[License Entitlements](License-Entitlements.md). Where one of those says what a reader **must** do, an
implementation that disagrees is wrong; where it reports today's behaviour with a kf-app citation,
it is descriptive. The executable half of the same contract is the signed fixture set in
[`contract/`](../contract/README.md).

> **This repository holds the only issuing code.** kf-app's copy of the tool is deleted. See
> [Relationship to kf-app](#relationship-to-kf-app).

## Relationship to kf-app

**kf-admin mints licences; kf-app verifies and interprets them, and never mints one.** That is the
direction taken on [#1](https://github.com/KnowledgeFabric/kf-admin/issues/1#issuecomment-5750795917),
revising the mechanism of [#13](https://github.com/KnowledgeFabric/kf-admin/issues/13), and kf-app
records its half in its ADR `docs/Architecture/Licence-Remit.md` (kf-app#979). There is no shared
library or package between them: `schemaVersion`, the normative pages here and the
[signed fixtures](../contract/README.md) carry the contract.

kf-app used to carry its own, diverged copy of this tool, `KnowledgeFabric.LicenseTool/`, with a
`trialDays` field for minting a duration-based trial. kf-app#982 deleted it (kf-app `5e9fb51`, on
`develop`) once its tests read this repository's fixtures instead: a verbatim copy in
`KnowledgeFabric.Modeller.Tests/Licensing/Contract`, taken from `1e25d1a`. Before that its tests
signed their own licences through it. So:

- **Issue from the console** ([#6](https://github.com/KnowledgeFabric/kf-admin/issues/6)), which
  records what it issues, **or offline with this repository's CLI.** There is nothing else.
- **A licence the old copy issued is in no register here.** The overview marks one found on the
  gateway as *Not in the register*.
- **A trial is not a file.** The product's trial is a compiled constant (kf-app#870), and kf-app
  refuses any licence carrying `TrialDays`.
- **When the fixture set is regenerated, kf-app and kf-ai-gateway copy it again**, replacing the
  whole directory.

This repository has CI of its own — `.github/workflows/build.yml` builds the
solution, runs the console's and the CLI's tests, mints and verifies the
[contract fixture set](../contract/README.md), and checks that the committed fixtures are current.
The CLI's tests came with [#3](https://github.com/KnowledgeFabric/kf-admin/issues/3).
</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));
⋮----
public async Task<IActionResult> Restore(Guid id, CancellationToken cancellationToken)
⋮----
restored = await contacts.RestoreAsync(id, SignedInAs, clock.GetUtcNow(), CancellationToken.None);
⋮----
logger.LogError(ex, "A contact could not be restored; nothing changed.");
return View("Deleted", new DeletedContacts(
contacts.Storage, await contacts.DeletedAsync(cancellationToken), Restored: null, Unreadable: false, Problem: text["Crm.Deleted.NotRestored"]));
⋮----
private async Task<IActionResult> ConfirmDeleteAsync(Guid id, string? problem, CancellationToken cancellationToken)
⋮----
var interactions = (await contacts.InteractionsAsync([id], cancellationToken)).Count;
var introductions = (await contacts.IntroductionsAsync([id], cancellationToken)).Count;
return View("Delete", new ContactDeletion(contact, interactions, introductions, await MayDeleteAsync(), SignedInAs, problem));
⋮----
private async Task<object> AnswerAsync(Contact contact, CancellationToken cancellationToken)
⋮----
shared = (await contacts.SharedNamesAsync(cancellationToken)).Contains(Contact.NormaliseName(contact.Name));
⋮----
logger.LogError(ex, "The shared names could not be read after a save; the row is drawn without the warning.");
⋮----
version = contact.Version.ToString(CultureInfo.InvariantCulture),
⋮----
cells = ContactCells.Of(contact, text, initials),
next = NextActionLine.Of(contact, Today)?.Answer(text, initials),
⋮----
private Task AuditAsync(string action, Contact contact, string? field)
⋮----
return auditLog.RecordAsync(
⋮----
Target: contact.Id.ToString(),
OccurredAt: clock.GetUtcNow(),
⋮----
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 async Task<PeopleInitials> InitialsAsync(CancellationToken cancellationToken)
⋮----
return await people.InitialsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The people's initials could not be read; the grid shows their names.");
⋮----
private async Task<bool> MayWriteAsync() =>
(await authorization.AuthorizeAsync(User, ConsolePolicies.CrmWrite)).Succeeded;
⋮----
private async Task<bool> MayDeleteAsync() =>
(await authorization.AuthorizeAsync(User, ConsolePolicies.CrmDelete)).Succeeded;
⋮----
private DateOnly Today => DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
⋮----
private IActionResult Refused(string problem) =>
⋮----
private IActionResult Problem(string problem) =>
</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)
⋮----
private static InteractionForm Typed(Guid? id, string? version, string? occurredOn, string? kind, string[]? participants, string? summary) =>
⋮----
private static NextActionForm TypedNext(string? version, string? text, string? owner, string? due) =>
⋮----
private Task AuditNextActionAsync(Contact contact, IReadOnlyList<string> changed) =>
auditLog.RecordAsync(
new AuditEntry(
⋮----
Target: contact.Id.ToString(),
OccurredAt: clock.GetUtcNow(),
⋮----
Details: new Dictionary<string, string?> { ["name"] = contact.Name, ["field"] = string.Join(", ", changed) }),
⋮----
private Task AuditAsync(string action, Contact contact, Interaction interaction) =>
⋮----
["interaction"] = interaction.Id.ToString(),
["date"] = InteractionPanel.Iso(interaction.OccurredOn),
["kind"] = interaction.Kind.ToString(),
⋮----
private async Task<PeopleInitials> InitialsAsync(CancellationToken cancellationToken)
⋮----
return await people.InitialsAsync(cancellationToken);
⋮----
logger.LogError(ex, "The people's initials could not be read; the panel shows their names.");
⋮----
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 async Task<bool> MayWriteAsync() =>
(await authorization.AuthorizeAsync(User, ConsolePolicies.CrmWrite)).Succeeded;
⋮----
private DateOnly Today => DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
⋮----
private static string Instant(DateTimeOffset value) => value.UtcDateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC";
⋮----
private ObjectResult Gone() =>
</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(),
⋮----
interactions.Add(interaction);
⋮----
public int InteractionsOf(Contact contact) => Import?.Interactions.Count(interaction => interaction.ContactId == contact.Id) ?? 0;
</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:
            <div class="alert alert-warning" role="alert">@T["Crm.Card.Unreachable"]</div>
            break;
        case BusinessCardOutcome.KeyRefused:
            <div class="alert alert-warning" role="alert">@T["Crm.Card.KeyRefused"]</div>
            break;
        case BusinessCardOutcome.NotUnderstood:
            <div class="alert alert-warning" role="alert">@T["Crm.Card.NotUnderstood"]</div>
            break;
    }

    @if (Model.Qr is { } qr)
    {
        @* The link as text, never a link: it is a stranger's, and the console has already followed it. *@
        <div class="alert alert-@(Model.Link is null or { Outcome: LinkedPageOutcome.Read } ? "info" : "warning") text-break" role="status" data-qr="@(Model.Link?.Outcome.ToString() ?? "Text")">
            @switch (Model.Link?.Outcome)
            {
                case null:
                    @T["Crm.Card.Qr.Text"]
                    break;
                case LinkedPageOutcome.Read:
                    @T["Crm.Card.Qr.Read", qr.Text]
                    break;
                case LinkedPageOutcome.Refused:
                    @T["Crm.Card.Qr.Refused", qr.Text]
                    break;
                case LinkedPageOutcome.Unreachable:
                    @T["Crm.Card.Qr.Unreachable", qr.Text]
                    break;
                case LinkedPageOutcome.Unreadable:
                    @T["Crm.Card.Qr.Unreadable", qr.Text]
                    break;
            }
        </div>
    }

    @if (Model.SameName is { Count: > 0 } same)
    {
        <div class="alert alert-warning" role="alert" data-same-name>
            @T["Crm.Card.SameName"]
            @for (var i = 0; i < same.Count; i++)
            {
                <a asp-controller="Contacts" asp-action="Details" asp-route-id="@same[i].Id" target="_blank" rel="noopener">@same[i].Name@(same[i].Organisation is { } organisation ? $" ({organisation})" : "")</a>@(i < same.Count - 1 ? ", " : ".")
            }
        </div>
    }

    <div class="row g-4">
        @if (Model.Photo is { } photo)
        {
            <div class="col-12 col-lg-5">
                <div class="card">
                    <div class="card-body">
                        <img src="@photo" alt="@T["Crm.Card.Photo"].Value" class="img-fluid rounded w-100" />
                    </div>
                </div>
            </div>
        }
        <div class="col-12 @(Model.Photo is null ? "col-lg-8" : "col-lg-7")">
            <div class="card">
                <div class="card-body">
                    <form method="post" asp-action="Create" novalidate>
                        @if (Model.AsksBy)
                        {
                            <div class="mb-3">
                                <label class="form-label" for="crm-card-by">@T["Crm.Field.By"]</label>
                                <select class="form-select@(Invalid(ContactFields.By))" id="crm-card-by" name="By">
                                    <option value="">@T["Crm.Contacts.ChooseBy"]</option>
                                    @foreach (var person in Model.People ?? [])
                                    {
                                        <option value="@person" selected="@(string.Equals(person, form.By, StringComparison.OrdinalIgnoreCase))">@((Model.Initials ?? PeopleInitials.None).Choice(person))</option>
                                    }
                                </select>
                                <div class="invalid-feedback">@Model.ProblemOf(ContactFields.By)</div>
                            </div>
                        }
                        <div class="mb-3">
                            <label class="form-label" for="crm-card-name">@T["Crm.Field.Name"]</label>
                            <input class="form-control@(Invalid(ContactFields.Name))" id="crm-card-name" name="Name" value="@form.Name" required autocomplete="off" />
                            <div class="invalid-feedback">@Model.ProblemOf(ContactFields.Name)</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="crm-card-headline">@T["Crm.Field.Headline"]</label>
                            <input class="form-control@(Invalid(ContactFields.Headline))" id="crm-card-headline" name="Headline" value="@form.Headline" autocomplete="off" />
                            <div class="invalid-feedback">@Model.ProblemOf(ContactFields.Headline)</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="crm-card-organisation">@T["Crm.Field.Organisation"]</label>
                            <input class="form-control@(Invalid(ContactFields.Organisation))" id="crm-card-organisation" name="Organisation" value="@form.Organisation" autocomplete="off" />
                            <div class="invalid-feedback">@Model.ProblemOf(ContactFields.Organisation)</div>
                        </div>
                        <div class="row g-3 mb-3">
                            <div class="col-12 col-md-6">
                                <label class="form-label" for="crm-card-email">@T["Crm.Field.Email"]</label>
                                <input class="form-control@(Invalid(ContactFields.Email))" id="crm-card-email" name="Email" value="@form.Email" type="email" autocomplete="off" />
                                <div class="invalid-feedback">@Model.ProblemOf(ContactFields.Email)</div>
                            </div>
                            <div class="col-12 col-md-6">
                                <label class="form-label" for="crm-card-phone">@T["Crm.Field.Phone"]</label>
                                <input class="form-control@(Invalid(ContactFields.Phone))" id="crm-card-phone" name="Phone" value="@form.Phone" type="tel" autocomplete="off" />
                                <div class="invalid-feedback">@Model.ProblemOf(ContactFields.Phone)</div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="crm-card-linkedin">LinkedIn</label>
                            <input class="form-control@(Invalid(ContactFields.LinkedIn))" id="crm-card-linkedin" name="LinkedIn" value="@form.LinkedIn" type="url" autocomplete="off" />
                            <div class="invalid-feedback">@Model.ProblemOf(ContactFields.LinkedIn)</div>
                        </div>
                        <div class="mb-4">
                            <label class="form-label" for="crm-card-notes">@T["Crm.Field.Notes"]</label>
                            <textarea class="form-control@(Invalid(ContactFields.Notes))" id="crm-card-notes" name="Notes" rows="3">@form.Notes</textarea>
                            <div class="form-text">@T["Crm.Card.Notes.Hint"]</div>
                            <div class="invalid-feedback">@Model.ProblemOf(ContactFields.Notes)</div>
                        </div>
                        <p class="small text-body-secondary">@T["Crm.Card.StartsAs", ContactStage.ToContact.DisplayName(S), ContactTrack.Undecided.DisplayName(S)]</p>
                        <div class="d-flex flex-wrap gap-2">
                            <button type="submit" class="btn btn-primary" disabled="@(!Model.CanAdd)">@T["Crm.Card.Add"]</button>
                            @if (Model.Configured)
                            {
                                <a asp-action="Index" class="btn btn-label-secondary">@T["Crm.Card.Another"]</a>
                            }
                            <a asp-controller="Contacts" asp-action="Index" 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/_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>
            </div>
            <div class="card-body">
                <dl class="row mb-0" data-contact="@contact.Id" data-version="@contact.Version">
                    <dt class="col-sm-4">@T["Crm.Field.Organisation"]</dt>
                    <dd class="col-sm-8 crm-cell crm-field" data-field="@ContactFields.Organisation" data-value="@cells[ContactFields.Organisation].Value" data-order="">@cells[ContactFields.Organisation].Display</dd>

                    @* Whom the partnership is with (#146): the name stays the person's, the organisation the firm's.
                       Its label wraps beside a narrow card, so it keeps the gap beneath it that a dd keeps. *@
                    <dt class="col-sm-4 mb-2">@T["Crm.Field.Entity"]</dt>
                    <dd class="col-sm-8 crm-cell crm-field" data-field="@ContactFields.Entity" data-value="@cells[ContactFields.Entity].Value" data-order="">@cells[ContactFields.Entity].Display</dd>

                    <dt class="col-sm-4">@T["Crm.Field.Email"]</dt>
                    <dd class="col-sm-8 crm-cell crm-field" data-field="@ContactFields.Email" data-value="@cells[ContactFields.Email].Value" data-order="">@cells[ContactFields.Email].Display</dd>

                    <dt class="col-sm-4">@T["Crm.Field.Phone"]</dt>
                    <dd class="col-sm-8 crm-cell crm-field" data-field="@ContactFields.Phone" data-value="@cells[ContactFields.Phone].Value" data-order="">@cells[ContactFields.Phone].Display</dd>

                    <dt class="col-sm-4">LinkedIn</dt>
                    <dd class="col-sm-8 crm-cell crm-field text-break" data-field="@ContactFields.LinkedIn" data-value="@cells[ContactFields.LinkedIn].Value" data-order="">
                        @if (contact.LinkedInUrl is { } url)
                        {
                            <a href="@url" target="_blank" rel="noopener">@url</a>
                        }
                    </dd>

                    @* Why they declined (#120), counted on the statistics page while the stage is Declined or dormant. *@
                    <dt class="col-sm-4" title="@T["Crm.Field.DeclineReason.Title"].Value">@T["Crm.Field.DeclineReason"]</dt>
                    <dd class="col-sm-8 crm-cell crm-field mb-0" data-field="@ContactFields.DeclineReason" data-value="@cells[ContactFields.DeclineReason].Value" data-order="">@cells[ContactFields.DeclineReason].Display</dd>
                </dl>
            </div>
        </div>
    </div>
</div>

<p class="small text-body-secondary mb-4">
    @T["Crm.Details.EnteredBy"] @contact.CreatedBy, @Instant(contact.CreatedAt)
    · @T["Crm.Details.LastChangedBy"] <span data-updated="@contact.Id">@contact.UpdatedBy, @Instant(contact.UpdatedAt)</span>
    · Id <code>@contact.Id</code>
    <a asp-area="" asp-controller="Audit" asp-action="Index" asp-route-target="@contact.Id" class="ms-1">@T["Menu.Audit"]</a>
</p>

@* Only a session that may delete sees the card at all (#127): a greyed-out button offers what it cannot do. *@
@if (Model.MayDelete)
{
    <div class="row g-4">
        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-1">@T["Crm.Delete"]</h5>
                </div>
                <div class="card-body">
                    <p class="mb-3">@T["Crm.Details.Delete.Lead"]</p>
                    <a asp-action="Delete" asp-route-id="@contact.Id" class="btn btn-outline-danger">@T["Crm.Delete"]…</a>
                </div>
            </div>
        </div>
    </div>
}

<partial name="_ContactConfig" model="Model" />
</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>
            }
            @* Every contact whatever the filter, with every interaction: an export is what a restore reads. *@
            <a asp-action="Export" class="btn btn-label-secondary" title="@T["Crm.Contacts.Export.Title"].Value">
                <i class="ti ti-download me-1"></i>@T["Generic.ExportCsv"]
            </a>
            @if (mayImport)
            {
                <a asp-controller="Import" asp-action="Index" class="btn btn-label-secondary" title="@T["Crm.Contacts.Import.Title"].Value">
                    <i class="ti ti-upload me-1"></i>@T["Crm.Contacts.Import"]
                </a>
            }
            @if (mayDelete)
            {
                <a asp-action="DeletedContacts" class="btn btn-label-secondary" title="@T["Crm.Deleted.Lead.Short"].Value">
                    <i class="ti ti-trash me-1"></i>@T["Crm.Deleted.Title"]
                </a>
            }
        </form>
    </div>

    @* The headings are the sheet's in English and the glossary's in Italian (#90, #107). *@
    <table id="crm-contacts" class="table table-sm table-hover crm-grid mb-0" data-frozen-header="true"
           data-empty="@(query.IsFiltered ? T["Crm.Contacts.Empty.Filtered"].Value : T["Crm.Contacts.Empty"].Value)">
        <thead>
            <tr>
                @foreach (var (field, headingKey) in ContactFields.Columns)
                {
                    <th class="@(field == ContactFields.With ? "crm-unsortable" : "")" data-column="@field"
                        title="@(field == ContactFields.Met ? T["Crm.Contacts.MetSorts"].Value : null)">@T[headingKey]</th>
                }
            </tr>
            @* A filter per column, as the sheet's autofilter: a choice reloads the grid with the filter in the query string. *@
            <tr class="crm-filters">
                @* Individual or company (#146) is not a column: its filter is Name's, as its mark is. *@
                <th>
                    <select class="form-select form-select-sm" data-filter="entity" aria-label="@T["Crm.Contacts.Filter.Entity"].Value">
                        <option value="">@T["Generic.Any"]</option>
                        @foreach (var entity in CrmWords.Entities)
                        {
                            <option value="@entity" selected="@(query.Entity == entity)">@entity.DisplayName(S)</option>
                        }
                        <option value="@ContactQuery.NotSaid" selected="@query.EntityNotSaid">@T["Crm.Entity.NotSaid"]</option>
                    </select>
                </th>
                <th>
                    <select class="form-select form-select-sm" data-filter="by" aria-label="@T["Crm.Contacts.Filter.By"].Value">
                        <option value="">@T["Crm.Contacts.Anyone"]</option>
                        @if (!byKnown)
                        {
                            <option value="@query.OriginatedBy" selected="selected">@query.OriginatedBy</option>
                        }
                        @foreach (var person in Model.People)
                        {
                            <option value="@person" selected="@string.Equals(person, query.OriginatedBy, StringComparison.OrdinalIgnoreCase)">@Model.Initials.Choice(person)</option>
                        }
                    </select>
                </th>
                <th></th>
                <th>
                    <select class="form-select form-select-sm" data-filter="e" aria-label="@T["Crm.Contacts.Filter.Engagement"].Value">
                        <option value="">@T["Generic.Any"]</option>
                        @foreach (var engagement in CrmWords.Engagements)
                        {
                            <option value="@((int)engagement)" selected="@(query.EngagementAtLeast == engagement)" title="@S["Crm.Contacts.OrWarmer", engagement.DisplayName(S)].Value">@((int)engagement)+</option>
                        }
                    </select>
                </th>
                <th>
                    <select class="form-select form-select-sm" data-filter="since" aria-label="@T["Crm.Contacts.Filter.Since"].Value">
                        <option value="">@T["Generic.Any"]</option>
                        @foreach (var silence in CrmWords.Silences)
                        {
                            <option value="@silence" selected="@(query.NotContactedSince == silence)">@silence.DisplayName(S)</option>
                        }
                    </select>
                </th>
                <th></th>
                <th></th>
                <th>
                    <select class="form-select form-select-sm" data-filter="track" aria-label="@T["Crm.Contacts.Filter.Track"].Value">
                        <option value="">@T["Generic.Any"]</option>
                        @foreach (var track in CrmWords.Tracks)
                        {
                            <option value="@track" selected="@(query.Track == track)">@track.DisplayName(S)</option>
                        }
                    </select>
                </th>
                <th>
                    <select class="form-select form-select-sm" data-filter="stage" aria-label="@T["Crm.Contacts.Filter.Stage"].Value">
                        <option value="">@T["Generic.Any"]</option>
                        @foreach (var stage in CrmWords.Stages)
                        {
                            <option value="@stage" selected="@(query.Stage == stage)">@stage.DisplayName(S)</option>
                        }
                    </select>
                </th>
                <th></th>
            </tr>
        </thead>
        @* The blank row heads the body whatever the order (#116): a body of its own, which DataTables does not sort. *@
        @if (Model.CanEdit)
        {
            <tbody class="crm-new-body">
                <partial name="_NewContactRow" model="(Model.SignedInAs, Model.People, Model.Initials)" />
            </tbody>
        }
        <tbody class="crm-rows">
            @foreach (var contact in Model.Rows)
            {
                <partial name="_ContactRow" model="Model.RowOf(contact)" />
            }
        </tbody>
    </table>
</div>

@if (Model.CanEdit)
{
    <template id="crm-new-row">
        <partial name="_NewContactRow" model="(Model.SignedInAs, Model.People, Model.Initials)" />
    </template>
}

<partial name="_ContactConfig" model="Model" />
</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)
                {
                    <option value="@query.Owner" selected="selected">@query.Owner</option>
                }
                @foreach (var person in Model.People)
                {
                    <option value="@person" selected="@string.Equals(person, query.Owner, StringComparison.OrdinalIgnoreCase)">@Model.Initials.Choice(person)</option>
                }
            </select>
            <select class="form-select form-select-sm w-auto" data-filter="due" aria-label="@T["Crm.FollowUps.Filter.Due"].Value">
                <option value="">@T["Generic.AnyTime"]</option>
                @foreach (var due in CrmWords.Dues)
                {
                    <option value="@due" selected="@(query.Due == due)">@due.DisplayName(S)</option>
                }
            </select>
            @if (query.IsFiltered)
            {
                <a asp-action="Index" class="btn btn-sm btn-label-secondary">@T["Generic.Clear"]</a>
            }
        </div>
    </div>

    @* The headings are the sheet's in English and the glossary's in Italian (#90, #107). *@
    <table id="crm-contacts" class="table table-sm table-hover crm-grid mb-0" data-frozen-header="true"
           data-empty="@(query.IsFiltered ? T["Crm.FollowUps.Empty.Filtered"].Value : T["Crm.FollowUps.Empty"].Value)">
        <thead>
            <tr>
                @foreach (var (field, headingKey) in ContactFields.Columns)
                {
                    <th class="@(field == ContactFields.With ? "crm-unsortable" : "")" data-column="@field"
                        title="@(field == ContactFields.Met ? T["Crm.Contacts.MetSorts"].Value : null)">@T[headingKey]</th>
                }
            </tr>
        </thead>
        <tbody>
            @foreach (var contact in Model.Rows)
            {
                <partial name="_ContactRow" model="Model.RowOf(contact)" />
            }
        </tbody>
    </table>
</div>

<partial name="_ContactConfig" model="Model" />
</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>
                <form method="post" asp-action="Confirm">
                    <input type="hidden" name="contactsFile" value="@Model.ContactsFile" />
                    <input type="hidden" name="interactionsFile" value="@Model.InteractionsFile" />
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary" disabled="@(Model.Storage == ContactStorage.Unavailable)">@T["Crm.Contacts.Import"]</button>
                        <a asp-action="Index" class="btn btn-label-secondary">@T["Crm.Import.ChooseOthers"]</a>
                    </div>
                </form>
            </div>
        </div>
    }
}

@if (import is { Contacts.Count: > 0 })
{
    @* The grid's column headings (#90, #105, #107). *@
    <div class="card">
        <div class="table-responsive text-nowrap">
            <table class="table table-sm">
                <thead>
                    <tr>
                        <th>@T["Crm.Field.Name"]</th>
                        <th>@T["Crm.Field.By"]</th>
                        <th>@T["Crm.Field.Track"]</th>
                        <th>@T["Crm.Field.Stage"]</th>
                        <th>@T["Crm.Field.Engagement"]</th>
                        <th class="text-end">@T["Crm.Interactions"]</th>
                        <th>@T["Crm.Next"]</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var contact in import.Contacts)
                    {
                        <tr>
                            <td>@contact.Name</td>
                            <td>@contact.OriginatedBy</td>
                            <td>@contact.Track.DisplayName(S)</td>
                            <td>@contact.Stage.DisplayName(S)</td>
                            <td>@(contact.Engagement is { } e ? ((int)e).ToString() : "")</td>
                            <td class="text-end">@Model.InteractionsOf(contact)</td>
                            <td>
                                @if (CrmWords.NextLine(contact, S) is { } next)
                                {
                                    <span>@next</span><span class="text-body-secondary">, @contact.NextActionOwner</span>
                                }
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
}
</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>
                            </table>
                        </div>
                        <div class="col-md-4">
                            <h6 class="mb-2" title="@T["Crm.Overview.IntroductionsByStage.Title"].Value">@T["Crm.Overview.IntroductionsByStage"]</h6>
                            <table class="table table-sm mb-0" data-crm-counts="introduction-stage">
                                <tbody>
                                    <tr>
                                        <td><a asp-area="Crm" asp-controller="Statistics" asp-action="Index" asp-fragment="crm-introductions">@T["Crm.Overview.Introductions"]</a></td>
                                        <td class="text-end" data-crm-count="introductions">@stats.Introductions</td>
                                    </tr>
                                    @foreach (var (stage, count) in stats.IntroductionsByStage)
                                    {
                                        <tr>
                                            <td class="ps-4">@stage.DisplayName(S)</td>
                                            <td class="text-end" data-introduction-stage="@stage">@count</td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                    </div>

                    @if (activity is not null)
                    {
                        <div class="mt-4" data-crm-activity>
                            <div class="d-flex flex-wrap justify-content-between align-items-baseline gap-2 mb-2">
                                <h6 class="mb-0">@T["Crm.Overview.Activity"]</h6>
                                <small class="text-body">@T["Crm.Overview.Activity.Lead", activity.Total, CrmActivity.WeekCount, activity.Weeks[^1].Total]</small>
                            </div>
                            <div id="crm-activity-chart" role="img" aria-label="@T["Crm.Overview.Activity"].Value"></div>
                            <details class="mt-2">
                                <summary class="small">@T["Crm.Overview.Activity.Table"]</summary>
                                <div class="table-responsive mt-2">
                                    <table class="table table-sm mb-0" data-crm-counts="activity">
                                        <thead>
                                            <tr>
                                                <th>@T["Crm.Overview.Activity.WeekColumn"]</th>
                                                @foreach (var kind in CrmWords.Kinds)
                                                {
                                                    <th class="text-end">@kind.DisplayName(S)</th>
                                                }
                                                <th class="text-end">@T["Crm.Overview.Activity.Total"]</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach (var week in activity.Weeks)
                                            {
                                                <tr data-week="@week.Starts.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)">
                                                    <td>@CrmWords.SheetDate(week.Starts) – @CrmWords.SheetDate(week.Ends)</td>
                                                    @foreach (var (kind, count) in week.ByKind)
                                                    {
                                                        <td class="text-end" data-kind="@kind">@count</td>
                                                    }
                                                    <td class="text-end" data-kind="total">@week.Total</td>
                                                </tr>
                                            }
                                        </tbody>
                                    </table>
                                </div>
                            </details>
                        </div>
                    }
                }
            </div>
        </div>
    </div>
</div>

@if (activity is not null)
{
    @*
        The chart's numbers, as the server counted them, its words in the page's culture; the table
        above holds the same. wwwroot/js/crm-overview.js only draws them.
    *@
    <script type="application/json" id="crm-activity-data">@Json.Serialize(new
    {
        labels = activity.Weeks.Select(week => week.Starts.ToString("d MMM", culture)),
        titles = activity.Weeks.Select(week => S["Crm.Overview.Activity.Week", week.Starts.ToString("d MMMM yyyy", culture)].Value),
        series = CrmWords.Kinds.Select((kind, i) => new
        {
            name = kind.DisplayName(S),
            data = activity.Weeks.Select(week => week.ByKind[i].Count),
        }),
    })</script>
    <partial name="~/Views/Shared/_ApexCharts.cshtml" />
    <script src="~/js/crm-overview.js" asp-append-version="true" defer></script>
}
</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>
                    <button type="button" class="btn btn-sm btn-label-secondary" data-interaction-action="next-cancel">@T["Generic.Cancel"]</button>
                </div>
            </form>
        }
    </div>

    @if (Model.Interactions.Count == 0)
    {
        <p class="text-body-secondary mb-3">@T["Crm.Interactions.None"]</p>
    }
    else
    {
        <ol class="list-unstyled crm-interactions mb-3">
            @foreach (var interaction in Model.Interactions)
            {
                var changed = interaction.UpdatedAt != interaction.RecordedAt || !string.Equals(interaction.UpdatedBy, interaction.RecordedBy, StringComparison.Ordinal);

                <li class="crm-interaction" data-interaction="@interaction.Id">
                    <div class="d-flex flex-wrap align-items-baseline gap-2">
                        <span class="fw-medium" title="@InteractionPanel.Iso(interaction.OccurredOn)">@CrmWords.MetLine(interaction, S)</span>
                        <span class="text-body-secondary">@T["Crm.Interactions.With", CrmWords.WithLine(interaction)]</span>
                        @if (Model.CanEdit)
                        {
                            <span class="ms-auto text-nowrap">
                                <button type="button" class="btn btn-sm btn-text-primary" data-interaction-action="edit">@T["Generic.Edit"]</button>
                                <button type="button" class="btn btn-sm btn-text-danger" data-interaction-action="delete">@T["Crm.Delete"]</button>
                            </span>
                        }
                    </div>
                    <div class="crm-summary">@interaction.Summary</div>
                    <div class="small text-body-secondary">
                        @T["Crm.Interactions.RecordedBy", interaction.RecordedBy, Instant(interaction.RecordedAt)]@(changed ? S["Crm.Interactions.ChangedBy", interaction.UpdatedBy, Instant(interaction.UpdatedAt)].Value : "")
                    </div>

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

                    @if (Model.CanEdit)
                    {
                        var form = Model.EditForm(interaction);

                        <form method="post" asp-area="Crm" asp-controller="Interactions" asp-action="Update"
                              asp-route-contactId="@Model.ContactId" asp-route-id="@interaction.Id"
                              class="crm-interaction-form mt-2@(Model.IsEditing(interaction) ? "" : " d-none")" data-interaction-form="edit">
                            <input type="hidden" name="version" value="@form.Version" />
                            <partial name="_InteractionFields" model="(Model, form)" />
                            <div class="d-flex gap-2 mt-2">
                                <button type="submit" class="btn btn-sm btn-primary">@T["Generic.Save"]</button>
                                <button type="button" class="btn btn-sm btn-label-secondary" data-interaction-action="cancel">@T["Generic.Cancel"]</button>
                            </div>
                        </form>

                        <form method="post" asp-area="Crm" asp-controller="Interactions" asp-action="Delete"
                              asp-route-contactId="@Model.ContactId" asp-route-id="@interaction.Id"
                              class="crm-interaction-form crm-interaction-confirm mt-2 d-none" data-interaction-form="delete">
                            <input type="hidden" name="version" value="@interaction.Version" />
                            <div class="d-flex flex-wrap align-items-center gap-2">
                                <span>@T["Crm.Interactions.DeleteConfirm"]</span>
                                <button type="submit" class="btn btn-sm btn-danger">@T["Crm.Delete"]</button>
                                <button type="button" class="btn btn-sm btn-label-secondary" data-interaction-action="keep">@T["Crm.Interactions.Keep"]</button>
                            </div>
                        </form>
                    }
                </li>
            }
        </ol>
    }

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

        <form method="post" asp-area="Crm" asp-controller="Interactions" asp-action="Add" asp-route-contactId="@Model.ContactId"
              class="crm-interaction-form crm-interaction-add" data-interaction-form="add" data-done="@(add.Done ? "true" : "false")">
            @*
                Two headings and two labels below, one of each shown: as the form is for logging a call, and as
                the console draws it again when a Done (#133) is refused, with what Done sent, to put right and
                add. Its Cancel turns it back into the form for logging a call.
            *@
            <h6 class="mb-2@(add.Done ? " d-none" : "")" data-log-only>@T["Crm.Interactions.Log"]</h6>
            <h6 class="mb-2@(add.Done ? "" : " d-none")" data-done-only>@T["Crm.Interactions.Done"]</h6>
            <partial name="_InteractionFields" model="(Model, add)" />
            @*
                What follows, set in the same submit: logging a call is the moment the next step is known
                (#92), so the fields start empty and ask for it every time (#111), the next action as it
                stands being at the top of the panel. Sent empty, the script asks No next action planned?
                and nextActionChoice carries the answer: clear it, since the call settled it, or keep the
                current one, for a call logged after the fact. The console asks again, drawing the
                question open, when it gets no answer.
            *@
            <div class="crm-next-fields mt-2">
                <span class="form-label small d-block mb-1@(add.Done ? " d-none" : "")" data-log-only>@T["Crm.Interactions.AndNext"]</span>
                <span class="form-label small d-block mb-1@(add.Done ? "" : " d-none")" data-done-only>@T["Crm.Interactions.Done.AndNext"]</span>
                <input type="hidden" name="contactVersion" value="@Model.AddNextForm.Version" data-contact-version />
                <input type="hidden" name="nextActionChoice" value="@(add.Done ? NoNextAction.Done : "")" data-next-choice />
                <partial name="_NextActionFields" model="(Model, Model.AddNextForm, addNextKey)" />
            </div>
            <div class="crm-next-confirm bg-label-warning rounded px-3 py-2 mt-2@(add.AskNoNext ? "" : " d-none")" tabindex="-1" role="group" aria-label="@T["Crm.Interactions.NoNext.Ask"].Value" data-next-confirm>
                <div class="d-flex flex-wrap align-items-center gap-2">
                    <span class="fw-medium">@T["Crm.Interactions.NoNext.Ask"]</span>
                    <button type="button" class="btn btn-sm btn-primary" data-interaction-action="no-next" data-choice="@NoNextAction.Clear">@T["Crm.Interactions.NoNext.Yes"]</button>
                    @if (Model.Next is not null)
                    {
                        <button type="button" class="btn btn-sm btn-label-primary" data-interaction-action="no-next" data-choice="@NoNextAction.Keep">@T["Crm.Interactions.NoNext.Keep"]</button>
                    }
                    <button type="button" class="btn btn-sm btn-label-secondary" data-interaction-action="no-next-back">@T["Crm.Interactions.NoNext.Back"]</button>
                </div>
            </div>
            <div class="d-flex gap-2 mt-2@(add.AskNoNext ? " d-none" : "")" data-add-submit>
                <button type="submit" class="btn btn-sm btn-primary">@T["Crm.Interactions.Add"]</button>
                <button type="button" class="btn btn-sm btn-label-secondary@(add.Done ? "" : " d-none")" data-done-only data-interaction-action="done-cancel">@T["Generic.Cancel"]</button>
            </div>
        </form>
    }
    else
    {
        <p class="small text-body-secondary mb-0">@T["Crm.Interactions.ViewOnly", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.CrmWrite))}</strong>")]</p>
    }
</div>
</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>
            }
            <div class="d-flex gap-2 mt-2">
                <button type="submit" class="btn btn-sm btn-primary">@T["Crm.Introductions.Add"]</button>
            </div>
        </form>
    }
    else
    {
        <p class="small text-body-secondary mb-0">@T["Crm.Introductions.ViewOnly", Html.Raw($"<strong>{Html.Encode(T.Role(ConsoleRoles.CrmWrite))}</strong>")]</p>
    }
</div>
</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.
    Beneath the partners' table, what they produced (#150): the customers introduced, in the same
    form, on the same day, from the introductions' own record; and a second chart.
*@

<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.Statistics"]</h5>
                <p class="text-body mb-0">@T["Crm.Statistics.Lead"]</p>

                @if (Model.Began is { } began)
                {
                    <form method="get" asp-action="Index" class="d-flex flex-wrap align-items-end gap-2 mt-4" id="crm-as-of">
                        <div>
                            <label for="asOf" class="form-label">@T["Crm.Statistics.AsOf"]</label>
                            <input type="date" id="asOf" name="asOf" class="form-control" value="@CrmStatisticsPage.Iso(Model.Day)"
                                   min="@CrmStatisticsPage.Iso(began)" max="@CrmStatisticsPage.Iso(Model.Today)" aria-describedby="asOf-hint" />
                        </div>
                        <button type="submit" class="btn btn-primary">@T["Crm.Statistics.AsOf.Show"]</button>
                        @if (Model.AsOf is not null)
                        {
                            <a asp-action="Index" class="btn btn-label-secondary">@T["Crm.Statistics.AsOf.Today"]</a>
                        }
                        <div id="asOf-hint" class="form-text w-100 mb-0">@T["Crm.Statistics.AsOf.Hint", CrmStatisticsPage.LongDay(began)]</div>
                    </form>
                }
            </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.Overview.NoDatabase"]</p>
    </div>
}
else if (funnel is null)
{
    <div class="alert alert-danger" role="alert">
        <h6 class="alert-heading mb-1">@T["Crm.Unreadable.Title"]</h6>
        <p class="mb-0">@T["Crm.Statistics.Unreadable.Detail"]</p>
    </div>
}
else
{
    @if (Model.Storage == ContactStorage.Ephemeral)
    {
        <div class="alert alert-info" role="alert">@T["Crm.Ephemeral"]</div>
    }

    @if (Model.AsOfProblem is { } problem)
    {
        <div class="alert alert-warning" role="alert" id="crm-as-of-problem">@problem</div>
    }

    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-1">@T["Crm.Statistics.Funnel"]</h5>
            <p class="card-subtitle mb-0">
                @T["Crm.Statistics.Funnel.Subtitle"]
                @if (Model.AsOf is { } asOf)
                {
                    <strong data-as-of="@CrmStatisticsPage.Iso(asOf)">@T["Crm.Statistics.Funnel.AsOf", CrmStatisticsPage.LongDay(asOf)]</strong>
                }
            </p>
        </div>
        <div class="table-responsive">
            <table class="table mb-0 crm-funnel" id="crm-funnel">
                <thead>
                    <tr>
                        <th></th>
                        <th class="text-end">@T["Crm.Statistics.Contacts"]</th>
                        <th class="text-end">@T["Crm.Statistics.OfConcluded"]</th>
                        <th class="d-none d-md-table-cell">@T["Crm.Statistics.Stages"]</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var line in lines)
                    {
                        var share = line.Level == 3 && funnel.OfConcluded(line.Count) is { } fraction ? fraction.ToString("P0", CultureInfo.CurrentCulture) : null;

                        <tr data-funnel="@line.Key" class="crm-funnel-level-@line.Level">
                            <td class="@line.Emphasis">
                                @if (linked && line.Link is { } stage)
                                {
                                    <a asp-controller="Contacts" asp-action="Index" asp-route-stage="@stage" class="@line.Emphasis">@line.Label</a>
                                }
                                else
                                {
                                    @line.Label
                                }
                            </td>
                            <td class="text-end @line.Emphasis" data-count>@line.Count</td>
                            <td class="text-end @line.Emphasis" data-share>@share</td>
                            <td class="small text-body-secondary d-none d-md-table-cell">@line.Stages</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
        <div class="card-body">
            <p class="small text-body-secondary mb-0">
                @if (Model.AsOf is { } day)
                {
                    @T["Crm.Statistics.Footnote.AsOf", CrmStatisticsPage.LongDay(day)]
                }
                else
                {
                    @T["Crm.Statistics.Footnote"]
                }
            </p>
        </div>
    </div>


    <div class="card mb-4" id="crm-introductions">
        <div class="card-header">
            <h5 class="card-title mb-1">@T["Crm.Statistics.Introductions"]</h5>
            <p class="card-subtitle mb-0">
                @T["Crm.Statistics.Introductions.Subtitle"]
                @if (Model.AsOf is { } introducedAsOf)
                {
                    <strong>@T["Crm.Statistics.Funnel.AsOf", CrmStatisticsPage.LongDay(introducedAsOf)]</strong>
                }
            </p>
        </div>
        @if (introductions is null)
        {
            <div class="card-body">
                <p class="mb-0 text-body-secondary">@T["Crm.Statistics.Introductions.Unreadable"]</p>
            </div>
        }
        else if (produced is null)
        {
            <div class="card-body">
                <p class="mb-0 text-body-secondary" id="crm-introductions-before">@T["Crm.Statistics.Introductions.BeforeRecord", CrmStatisticsPage.LongDay(introductions.Began), CrmStatisticsPage.LongDay(Model.Day)]</p>
            </div>
        }
        else
        {
            <div class="table-responsive">
                <table class="table mb-0 crm-funnel" id="crm-introduction-funnel">
                    <thead>
                        <tr>
                            <th></th>
                            <th class="text-end">@T["Crm.Statistics.Customers"]</th>
                            <th class="text-end">@T["Crm.Statistics.OfIntroduced"]</th>
                            <th class="d-none d-md-table-cell">@T["Crm.Statistics.Stages"]</th>
                        </tr>
                    </thead>
                    @foreach (var (heading, group) in new[] { ((string?)null, byStage), (S["Crm.Statistics.ByPartnerTrack"].Value, byTrack), (S["Crm.Statistics.HowFar"].Value, reached) })
                    {
                        <tbody>
                            @if (heading is not null)
                            {
                                <tr class="crm-funnel-section">
                                    <th colspan="4" scope="rowgroup" class="small text-body-secondary pt-4">@heading</th>
                                </tr>
                            }
                            @foreach (var line in group)
                            {
                                <tr data-introductions="@line.Key" class="crm-funnel-level-@line.Level">
                                    <td class="@line.Emphasis">@line.Label</td>
                                    <td class="text-end @line.Emphasis" data-count>@line.Count</td>
                                    <td class="text-end @line.Emphasis" data-share>@line.Share</td>
                                    <td class="small text-body-secondary d-none d-md-table-cell">@line.Stages</td>
                                </tr>
                            }
                        </tbody>
                    }
                </table>
            </div>
            <div class="card-body">
                <p class="small text-body-secondary mb-0">
                    @if (Model.AsOf is { } introducedOn)
                    {
                        @T["Crm.Statistics.Introductions.Footnote.AsOf", CrmStatisticsPage.LongDay(introducedOn)]
                    }
                    else
                    {
                        @T["Crm.Statistics.Introductions.Footnote"]
                    }
                </p>
            </div>
        }
    </div>

    <div class="card mb-4" id="crm-over-time">
        <div class="card-header">
            <h5 class="card-title mb-1">@T["Crm.Statistics.OverTime"]</h5>
            @if (Model.Began is { } start && series.Count >= 2)
            {
                <p class="card-subtitle mb-0">@T[Model.Weekly ? "Crm.Statistics.OverTime.Weekly" : "Crm.Statistics.OverTime.Monthly", CrmStatisticsPage.LongDay(start)]</p>
            }
        </div>
        <div class="card-body">
            @if (Model.Series is null)
            {
                <p class="mb-0 text-body-secondary">@T["Crm.Statistics.OverTime.Unreadable"]</p>
            }
            else if (Model.Began is not { } recorded)
            {
                <p class="mb-0 text-body-secondary">@T["Crm.Statistics.OverTime.Nothing"]</p>
            }
            else if (series.Count < 2)
            {
                <p class="mb-0 text-body-secondary">@T["Crm.Statistics.OverTime.TooShort", CrmStatisticsPage.LongDay(recorded)]</p>
            }
            else
            {
                <div data-crm-history-chart="crm-history-data" style="min-height: 280px"></div>
                <script type="application/json" id="crm-history-data">@Json.Serialize(chart)</script>

                <details class="mt-3">
                    <summary>@T["Crm.Statistics.OverTime.Numbers"]</summary>
                    <div class="table-responsive mt-2">
                        <table class="table table-sm mb-0" id="crm-history">
                            <thead>
                                <tr>
                                    <th>@T["Crm.Statistics.OverTime.EndOf"]</th>
                                    <th class="text-end">@T["Crm.Statistics.Identified"]</th>
                                    <th class="text-end">@T["Crm.Statistics.Met"]</th>
                                    <th class="text-end">@T["Crm.Statistics.Accepted"]</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var point in series)
                                {
                                    <tr data-day="@CrmStatisticsPage.Iso(point.Day)">
                                        <td><a href="@PointLink(point.Day)">@CrmStatisticsPage.LongDay(point.Day)</a></td>
                                        <td class="text-end" data-identified>@point.Funnel.Identified</td>
                                        <td class="text-end" data-met>@point.Funnel.Met</td>
                                        <td class="text-end" data-accepted>@point.Funnel.Accepted</td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                </details>
            }
        </div>
    </div>

    @if (produced is not null)
    {
        <div class="card mb-4" id="crm-introductions-over-time">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Crm.Statistics.Introductions.OverTime"]</h5>
                @if (introductionSeries.Count >= 2)
                {
                    <p class="card-subtitle mb-0">@T[introductions!.Weekly ? "Crm.Statistics.Introductions.OverTime.Weekly" : "Crm.Statistics.Introductions.OverTime.Monthly", CrmStatisticsPage.LongDay(introductions.Began)]</p>
                }
            </div>
            <div class="card-body">
                @if (introductionSeries.Count < 2)
                {
                    <p class="mb-0 text-body-secondary">@T["Crm.Statistics.Introductions.OverTime.TooShort", CrmStatisticsPage.LongDay(introductions!.Began)]</p>
                }
                else
                {
                    <div data-crm-history-chart="crm-introductions-history-data" style="min-height: 280px"></div>
                    <script type="application/json" id="crm-introductions-history-data">@Json.Serialize(introductionChart)</script>

                    <details class="mt-3">
                        <summary>@T["Crm.Statistics.OverTime.Numbers"]</summary>
                        <div class="table-responsive mt-2">
                            <table class="table table-sm mb-0" id="crm-introductions-history">
                                <thead>
                                    <tr>
                                        <th>@T["Crm.Statistics.OverTime.EndOf"]</th>
                                        <th class="text-end">@T["Crm.Statistics.Introduced"]</th>
                                        <th class="text-end">@T["Crm.IntroductionStage.UnderContract"]</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var point in introductionSeries)
                                    {
                                        <tr data-introductions-day="@CrmStatisticsPage.Iso(point.Day)">
                                            <td><a href="@PointLink(point.Day)">@CrmStatisticsPage.LongDay(point.Day)</a></td>
                                            <td class="text-end" data-introduced>@point.Introduced</td>
                                            <td class="text-end" data-under-contract>@point.UnderContract</td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                    </details>
                }
            </div>
        </div>
    }

    @if (charted)
    {
        @* 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/crm-statistics.js" asp-append-version="true" defer></script>
    }
}

@functions {
    /// <summary>
    /// One line of the funnel: its level of indent, its label and count, how it is emphasised as on
    /// Roberto's slide, the stages it counts, the one stage it links to when it counts only one, and
    /// its share, where the introductions' table (#150) gives one.
    /// </summary>
    private sealed record FunnelLine(string Key, int Level, string Label, int Count, string? Emphasis = null, string? Stages = null, ContactStage? Link = null, string? Share = null);
}
</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);
var beforeFields = JsonSerializer.SerializeToElement(before, Wire);
var afterFields = JsonSerializer.SerializeToElement(after, Wire);
⋮----
var changed = afterFields.EnumerateObject()
.Where(field => !beforeFields.TryGetProperty(field.Name, out var was) || was.GetRawText() != field.Value.GetRawText())
.Select(field => $"{field.Name}: {(beforeFields.TryGetProperty(field.Name, out var was) ? was.GetRawText() : "-")} → {field.Value.GetRawText()}");
⋮----
details["before"] = beforeFields.GetRawText();
details["after"] = afterFields.GetRawText();
details["changed"] = string.Join("; ", changed);
details["reason"] = form.Reason!.Trim();
⋮----
foreach (var unset in details.Where(detail => detail.Value is null).Select(detail => detail.Key).ToList())
⋮----
details.Remove(unset);
⋮----
await auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
⋮----
ClaimedActor: shared ? form.Name!.Trim() : null),
⋮----
private async Task<TierChange> TierChangeAsync(InstallationRow row, PolicyChangeStep step, TierChangeForm? form, CancellationToken cancellationToken)
⋮----
var policy = gateway.PolicyAsync(cancellationToken);
⋮----
form ??= current.Tiers.FirstOrDefault(tier => tier.Tier == row.ToString().ToLowerInvariant()) is { } stands
? TierChangeForm.Of(stands.Levers)
: new TierChangeForm();
⋮----
return new TierChange(step, current, await WriterAsync(), row, form, licences, read);
⋮----
private async Task<VelocityChange> VelocityChangeAsync(PolicyChangeStep step, GatewayPolicyAnswer current, VelocityForm form, CancellationToken cancellationToken)
⋮----
var status = await cache.GetAsync(gateway.StatusAsync, cancellationToken);
return new VelocityChange(step, current, await WriterAsync(), form, status.Answer, status.AskedAt);
⋮----
private async Task<(int? Count, bool Read)> LicencesInForceAsync(InstallationRow row, CancellationToken cancellationToken)
⋮----
if (!AllowanceRule.IsLicenceRow(row))
⋮----
var counts = PolicyPage.CountByAllowance(await register.SummariesAsync(cancellationToken), clock.GetUtcNow().UtcDateTime);
return (counts.GetValueOrDefault(row.ToString().ToLowerInvariant()), true);
⋮----
logger.LogError(ex, "The policy form could not read the licence register.");
⋮----
private async Task<PolicyWriter> WriterAsync() => new(
⋮----
MayWrite: (await authorization.AuthorizeAsync(User, ConsolePolicies.GatewayWrite)).Succeeded,
NeedsName: GatewayOperator.IsShared(User),
⋮----
private static InstallationRow? RowOf(string tier) => tier switch
</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/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;
⋮----
public static IReadOnlyList<string> Lowerings(GatewayTierLevers before, GatewayTierLevers after, IStringLocalizer<ConsoleResource> text)
⋮----
lowerings.Add(text["Gateway.Tier.Lowering.Requests", PolicyPage.Requests(before.RequestsPerWindow, before.RequestWindowSeconds, text), PolicyPage.Requests(after.RequestsPerWindow, after.RequestWindowSeconds, text)]);
⋮----
lowerings.Add(text["Gateway.Tier.Lowering.Budget", PolicyPage.N(before.TokenBudget), PolicyPage.N(after.TokenBudget)]);
⋮----
lowerings.Add(text["Gateway.Tier.Lowering.Period", PolicyPage.PeriodName(before.BudgetPeriod, text), PolicyPage.PeriodName(after.BudgetPeriod, text)]);
⋮----
lowerings.Add(text["Gateway.Tier.Lowering.LongestReply", PolicyPage.N(before.MaxPredictTokens), PolicyPage.N(after.MaxPredictTokens)]);
⋮----
internal static readonly JsonSerializerOptions Wire = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
⋮----
public static IReadOnlyList<string> Problems(GatewayPolicy row, IStringLocalizer<ConsoleResource> text)
⋮----
if (!InstallationQuery.IsVersion(row.MinimumAppVersion) || row.MinimumAppVersion!.Trim().Length > MinimumVersionForm.MaxLength)
⋮----
problems.Add(text["Gateway.Change.RowProblem.Version", row.MinimumAppVersion ?? ""]);
⋮----
problems.Add(text["Gateway.Change.RowProblem.Hourly", row.EnrolmentsPerHour]);
⋮----
problems.Add(text["Gateway.Change.RowProblem.Daily", row.EnrolmentsPerDay]);
⋮----
problems.Add(text["Gateway.Change.RowProblem.HourlyAboveDaily"]);
⋮----
problems.Add(text["Gateway.Change.RowProblem.Ceiling", row.GlobalTokenCeiling]);
⋮----
public string Tier => Row.ToString().ToLowerInvariant();
⋮----
public GatewayTier? CurrentRow => Current.Tiers.FirstOrDefault(tier => tier.Tier == Tier);
⋮----
public bool IsLicenceRow => AllowanceRule.IsLicenceRow(Row);
⋮----
.GroupBy(installation => installation.AppVersion ?? "")
.Select(version => new VersionTally(version.Key, version.Count()))
.OrderByDescending(tally => Numeric(tally.Version) is not null)
.ThenByDescending(tally => Numeric(tally.Version))
.ThenBy(tally => tally.Version, StringComparer.Ordinal)
.ToList()
⋮----
/// <summary>Whether the review can be confirmed: the gateway said whom the minimum would refuse.</summary>
⋮----
private static Version? Numeric(string value) =>
InstallationQuery.IsVersion(value) ? Version.Parse(value.Trim().Split('-', '+')[0]) : null;
⋮----
/// <summary>How many installations reported one application version.</summary>
/// <param name="Version">As the installation reported it; empty when it reported none.</param>
</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);
⋮----
static string Day(DateTime value) => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
⋮----
public bool CustomersOnly => string.Equals(Purpose, CustomerPurpose, StringComparison.OrdinalIgnoreCase);
⋮----
public string? Allowance => LicenseContract.Tiers.All.FirstOrDefault(tier => string.Equals(tier, Tier, StringComparison.Ordinal));
⋮----
public UsageSort SortOrder => Sorts.Where(sort => sort.Value == Sort).Select(sort => sort.Sort).DefaultIfEmpty(UsageSort.MostUsed).First();
⋮----
public Dictionary<string, string> RouteValues()
⋮----
values["sort"] = Sorts.First(sort => sort.Sort == SortOrder).Value;
</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";

                    if (brake.Tripped)
                    {
                        <div class="alert alert-danger" role="alert">
                            <h6 class="alert-heading mb-1">@T["Gateway.Brake.On.Title"]</h6>
                            <p class="mb-0">
                                @T["Gateway.Brake.On.Detail"]
                                <a asp-controller="PolicyChange" asp-action="Ceiling">@T["Gateway.Brake.ChangeCeiling"]</a>.
                            </p>
                        </div>
                    }

                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-heading fw-medium">@T["Gateway.Brake.OfTokens", N(brake.Used), N(brake.Ceiling!.Value)]</span>
                        <span class="text-body">@percent%</span>
                    </div>
                    <div class="progress mb-3" role="progressbar" aria-label="@T["Gateway.Brake.Aria"].Value"
                         aria-valuenow="@percent" aria-valuemin="0" aria-valuemax="100">
                        <div class="progress-bar @bar" style="width: @percent%"></div>
                    </div>
                    <p class="text-body mb-0">
                        @T["Gateway.Brake.PeriodEnds", Day(brake.PeriodEnd)]
                        @if (!brake.Tripped && percent >= 80)
                        {
                            <span>@T["Gateway.Brake.Close"]</span>
                        }
                    </p>
                }
            </div>
        </div>
    </div>
</div>

@if (Model.Usage is { } usage)
{
    <div class="row g-4 mb-4">
        @if (!usage.Answered)
        {
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-1">@T["Gateway.Overview.LastDays", usage.Range.Days]</h5>
                        <p class="card-subtitle mb-0">@T["Gateway.Overview.LastDays.Lead"]</p>
                    </div>
                    <div class="card-body">
                        <partial name="_UsageUnavailable" model="(usage.Outcome, usage.Detail)" />
                    </div>
                </div>
            </div>
        }
        else
        {
            var total = usage.Total;
            var tokensChart = (UsageChart.TokensByRow(usage.Days, S), "usage-tokens", 280);
            var refusalsChart = (UsageChart.Refusals(usage.Days, S), "usage-refusals", 280);
            <div class="col-xl-8">
                <div class="card h-100">
                    <div class="card-header d-flex justify-content-between align-items-start gap-2">
                        <div>
                            <h5 class="card-title mb-1">@T["Gateway.Usage.TokensADay"]</h5>
                            <p class="card-subtitle mb-0">@T["Gateway.Overview.TokensADay.Lead", usage.Range.Days, N(total.Tokens)]</p>
                        </div>
                        <a asp-controller="Usage" asp-action="History" class="btn btn-sm btn-label-primary text-nowrap">@T["Menu.Gateway.UsageHistory"]</a>
                    </div>
                    <div class="card-body">
                        <partial name="_UsageChart" model="tokensChart" />
                    </div>
                </div>
            </div>
            <div class="col-xl-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h5 class="card-title mb-1">@T["Gateway.Overview.RefusalsADay"]</h5>
                        <p class="card-subtitle mb-0">@T["Gateway.Usage.Totals", N(total.Requests), N(total.RefusalsRateLimited), N(total.RefusalsBudgetExhausted), N(total.UpstreamErrors)]</p>
                    </div>
                    <div class="card-body">
                        <partial name="_UsageChart" model="refusalsChart" />
                    </div>
                </div>
            </div>
            <div class="col-12">
                <p class="small text-body-secondary mb-0">@T["Gateway.Overview.Usage.Footnote"]</p>
            </div>
            <partial name="_UsageChartScripts" />
        }
    </div>
}

@if (fleet is null)
{
    <div class="row g-4">
        <div class="col-12">
            <div class="card"><div class="card-body"><p class="text-body mb-0">@T["Gateway.Overview.NoFleet"]</p></div></div>
        </div>
    </div>
    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>
                    <a asp-controller="Installations" asp-action="Index" class="text-heading">@T["Menu.Gateway.Installations"]</a>
                    <h4 class="mb-1 mt-1">@fleet.Total</h4>
                    <small class="text-body">@T["Gateway.Overview.ActiveRevoked", fleet.Active, fleet.Revoked]</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-primary"><i class="ti ti-server 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["Gateway.Row.evaluation"]</span>
                    <h4 class="mb-1 mt-1">@(fleet.ByRow?.Evaluation.ToString() ?? "-")</h4>
                    <small class="text-body">@T["Gateway.Overview.Row.evaluation"]</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-secondary"><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">
                <div>
                    <span class="text-heading">@T["Gateway.Row.standard"]</span>
                    <h4 class="mb-1 mt-1">@(fleet.ByRow?.Standard.ToString() ?? "-")</h4>
                    <small class="text-body">@T["Gateway.Overview.Row.standard"]</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-success"><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["Gateway.Row.enterprise"]</span>
                    <h4 class="mb-1 mt-1">@(fleet.ByRow?.Enterprise.ToString() ?? "-")</h4>
                    <small class="text-body">@T["Gateway.Overview.Row.enterprise"]</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-warning"><i class="ti ti-certificate ti-26px"></i></span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-8">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Overview.SeenRecently"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Overview.SeenRecently.Lead"]</p>
            </div>
            <div class="card-body">
                <div class="row g-4">
                    <div class="col-sm-4">
                        <span class="text-heading">@T["Gateway.Overview.Last24h"]</span>
                        <h4 class="mb-0 mt-1">@fleet.SeenLast24h</h4>
                    </div>
                    <div class="col-sm-4">
                        <span class="text-heading">@T["Gateway.Overview.Last7d"]</span>
                        <h4 class="mb-0 mt-1">@fleet.SeenLast7d</h4>
                    </div>
                    <div class="col-sm-4">
                        <span class="text-heading">@T["Gateway.Overview.Last30d"]</span>
                        <h4 class="mb-0 mt-1">@fleet.SeenLast30d</h4>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @* The rows kf-ai-gateway docs/Admin.md says to look for before enterprise's allowance is raised (#32). *@
    <div class="col-xl-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Overview.TierNotRecorded"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Overview.TierNotRecorded.Lead"]</p>
            </div>
            <div class="card-body">
                @if (fleet.LicensedWithoutLicenceTier == 0)
                {
                    <h4 class="mb-1">0</h4>
                    <p class="text-body mb-0">@T["Gateway.Overview.TierNotRecorded.None"]</p>
                }
                else
                {
                    <h4 class="mb-1 text-warning">@fleet.LicensedWithoutLicenceTier</h4>
                    <p class="text-body mb-0">
                        @(fleet.LicensedWithoutLicenceTier == 1 ? T["Gateway.Overview.TierNotRecorded.Some.One"] : T["Gateway.Overview.TierNotRecorded.Some.Many", fleet.LicensedWithoutLicenceTier])
                    </p>
                }
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <p class="small text-body-secondary mb-0">
                    @T["Gateway.Overview.Footnote"]
                    @if (status.Caller?.Address is { } address)
                    {
                        <span>@T["Gateway.Overview.Footnote.Caller", Html.Raw($"<code>{Html.Encode(address)}</code>")]</span>
                    }
                </p>
            </div>
        </div>
    </div>
</div>
</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>
                        }
                    </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[Model.IsRevoke ? "Gateway.Change.WhatRevokeDoes" : "Gateway.Change.WhatRestoreDoes"]</h6>
            </div>
            <div class="card-body">
                @if (Model.IsRevoke)
                {
                    <p>@T["Gateway.Change.Revoke.Detail"]</p>
                    @if (Model.IsOnlyHolder)
                    {
                        <div class="alert alert-warning mb-3" role="alert">@T["Gateway.Change.OnlyHolder", Html.Raw($"<strong>{Html.Encode(Model.LicenceRow!.CustomerName)}</strong>")]</div>
                    }
                }
                else
                {
                    <p>@T["Gateway.Change.Restore.Detail"]</p>
                }

                @if (Model.AlreadyDone)
                {
                    <div class="alert alert-secondary mb-0" role="status">
                        @if (Model.IsRevoke)
                        {
                            <span>@T["Gateway.Change.AlreadyRevoked", Instant(installation.RevokedAt)]</span>
                            <a asp-action="Restore" asp-route-id="@Model.InstallationId">@T["Gateway.Change.RestoreIt"]</a><span> @T["Gateway.Change.Instead"]</span>
                        }
                        else
                        {
                            <span>@T["Gateway.Change.NotRevoked"]</span>
                            <a asp-action="Revoke" asp-route-id="@Model.InstallationId">@T["Gateway.Change.RevokeIt"]</a><span> @T["Gateway.Change.Instead"]</span>
                        }
                    </div>
                }
                else 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>
                }
                else
                {
                    <form method="post" asp-action="@action" asp-route-id="@Model.InstallationId">
                        <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="@(Model.IsRevoke ? T["Gateway.Change.Revoke.Placeholder"].Value : T["Gateway.Change.Restore.Placeholder"].Value)">@Model.Form.Reason</textarea>
                            @if (ViewData.ModelState[nameof(InstallationChangeForm.Reason)]?.Errors is { Count: > 0 } reasonErrors)
                            {
                                <div class="text-danger small mt-1">@reasonErrors[0].ErrorMessage</div>
                            }
                        </div>
                        @if (Model.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 (ViewData.ModelState[nameof(InstallationChangeForm.Name)]?.Errors is { Count: > 0 } nameErrors)
                                {
                                    <div class="text-danger small mt-1">@nameErrors[0].ErrorMessage</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(Model.SignedInAs)}</strong>")]</p>
                        }
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn @(Model.IsRevoke ? "btn-danger" : "btn-primary")">@T[Model.IsRevoke ? "Gateway.Change.Revoke.Submit" : "Gateway.Change.Restore.Submit"]</button>
                            <a asp-action="Details" asp-route-id="@Model.InstallationId" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                        </div>
                    </form>
                }
            </div>
        </div>
    </div>
</div>
</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>

                    <dt class="col-sm-5">@T["Licensing.Installations.Column.Status"]</dt>
                    <dd class="col-sm-7">
                        @(installation.Status ?? (installation.IsRevoked ? "revoked" : "active"))
                        @if (installation.IsRevoked)
                        {
                            <div class="small text-body">@T["Gateway.Installation.RevokedAt", Instant(installation.RevokedAt)]</div>
                        }
                    </dd>

                    <dt class="col-sm-5">@T["Gateway.Installation.FirstEnrolled"]</dt>
                    <dd class="col-sm-7">@Instant(installation.CreatedAt)</dd>

                    <dt class="col-sm-5">@T["Licensing.Installations.Column.LastSeen"]</dt>
                    <dd class="col-sm-7 mb-0">@Instant(installation.LastSeenAt)</dd>
                </dl>
            </div>
        </div>
    </div>

    @* The two numbers a support call is about: what it is allowed, and what it has used. *@
    <div class="col-xl-7">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Installation.Allowance"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Installation.Allowance.Lead"]</p>
            </div>
            <div class="card-body">
                @if (installation.IsRevoked)
                {
                    <div class="alert alert-secondary" role="status">
                        <h6 class="alert-heading mb-1">@T["Gateway.Installation.ServedNothing.Title"]</h6>
                        <p class="mb-0">
                            @T["Gateway.Installation.ServedNothing.Detail", Instant(installation.RevokedAt)]
                            @if (allowance is not null)
                            {
                                <span>@T["Gateway.Installation.ServedNothing.IfRestored"]</span>
                            }
                        </p>
                    </div>
                }

                @if (allowance is null)
                {
                    <div class="alert alert-secondary mb-0" role="status">
                        <h6 class="alert-heading mb-1">@T["Gateway.NoUsageYet.Title"]</h6>
                        <p class="mb-0">@T["Gateway.Installation.NoUsageYet.Detail"]</p>
                    </div>
                }
                else
                {
                    <dl class="row mb-0">
                        <dt class="col-sm-4">@T["Gateway.Installation.Requests"]</dt>
                        <dd class="col-sm-8">
                            @if (allowance.Requests is { } requests)
                            {
                                <div class="text-heading fw-medium">@AllowanceWords.Requests(allowance, S)</div>
                                <div>@T["Gateway.Installation.Requests.Remaining", AllowanceWords.N(requests.Remaining), AllowanceWords.N(requests.Limit), Seconds(requests.ResetAt)]</div>
                                <div class="small text-body-secondary">@T["Gateway.Installation.Requests.InMemory"]</div>
                            }
                            else
                            {
                                <span>@T["Gateway.NotReported"]</span>
                            }
                        </dd>

                        <dt class="col-sm-4">@T["Gateway.Installation.Tokens"]</dt>
                        <dd class="col-sm-8">
                            @if (allowance.Tokens is { } tokens)
                            {
                                var bar = installation.IsRevoked ? "bg-secondary" : tokens.Percent >= 100 ? "bg-danger" : tokens.Percent >= 80 ? "bg-warning" : "bg-primary";
                                <div class="text-heading fw-medium">@AllowanceWords.Tokens(allowance, installation.CreatedAt, S)</div>
                                <div class="d-flex justify-content-between">
                                    <span>@T["Gateway.Installation.Tokens.UsedOf", AllowanceWords.N(tokens.Used), AllowanceWords.N(tokens.Limit)]</span>
                                    <span class="text-body">@tokens.Percent%</span>
                                </div>
                                <div class="progress my-1" 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">@T["Gateway.Installation.Tokens.PeriodEnds", Instant(tokens.ResetAt)]</div>
                            }
                            else
                            {
                                <span>@T["Gateway.NotReported"]</span>
                            }
                        </dd>

                        <dt class="col-sm-4">@T["Gateway.Installation.LongestReply"]</dt>
                        <dd class="col-sm-8 mb-0">
                            @if (allowance.MaxPredictTokens is { } longest)
                            {
                                <span>@T["Gateway.Installation.LongestReply.Detail", AllowanceWords.N(longest), AllowanceWords.RowOwner(allowance, S)]</span>
                            }
                            else
                            {
                                <span>@T["Gateway.NotReported"]</span>
                            }
                        </dd>
                    </dl>

                    @if (AllowanceWords.HasUnreadableLimit(allowance))
                    {
                        <div class="alert alert-warning mt-3 mb-0" role="alert">
                            <h6 class="alert-heading mb-1">@T["Gateway.Installation.ZeroLimit.Title"]</h6>
                            <p class="mb-0">@T["Gateway.Installation.ZeroLimit.Detail"]</p>
                        </div>
                    }
                }
            </div>
        </div>
    </div>
</div>

@if (Model.Usage is { } usage)
{
    <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-2">
                    <div>
                        <h5 class="card-title mb-1">@T["Menu.Gateway.UsageHistory"]</h5>
                        <p class="card-subtitle mb-0">
                            @T["Gateway.Installation.History.Lead", usage.Range.Days]
                            @if (usage.Answered)
                            {
                                var total = usage.Total;
                                <span>@T["Gateway.Installation.History.Totals", AllowanceWords.N(total.Tokens), AllowanceWords.N(total.Requests), AllowanceWords.N(total.RefusalsRateLimited), AllowanceWords.N(total.RefusalsBudgetExhausted), AllowanceWords.N(total.UpstreamErrors)]</span>
                            }
                        </p>
                    </div>
                    <div class="btn-group btn-group-sm" role="group" aria-label="@T["Gateway.Installation.HowManyDays"].Value">
                        @foreach (var range in InstallationDetails.UsageRanges)
                        {
                            <a asp-action="Details" asp-route-id="@Model.InstallationId" asp-route-days="@(range == InstallationDetails.DefaultUsageDays ? null : range)"
                               class="btn @(range == usage.Range.Days ? "btn-primary" : "btn-label-primary")">@T["Gateway.Days", range]</a>
                        }
                    </div>
                </div>
                <div class="card-body">
                    @if (!usage.Answered)
                    {
                        <partial name="_UsageUnavailable" model="(usage.Outcome, usage.Detail)" />
                    }
                    else
                    {
                        var tokensChart = (UsageChart.Tokens(usage.Days, S), "installation-tokens", 240);
                        var requestsChart = (UsageChart.Requests(usage.Days, S), "installation-requests", 240);
                        <div class="row g-4">
                            <div class="col-xl-6">
                                <h6 class="mb-2">@T["Gateway.Usage.TokensADay"]</h6>
                                <partial name="_UsageChart" model="tokensChart" />
                            </div>
                            <div class="col-xl-6">
                                <h6 class="mb-2">@T["Gateway.Usage.RequestsADay"]</h6>
                                <partial name="_UsageChart" model="requestsChart" />
                            </div>
                        </div>
                        <p class="small text-body-secondary mt-3 mb-0">@T["Gateway.Installation.History.Footnote"]</p>
                        <partial name="_UsageChartScripts" />
                    }
                </div>
            </div>
        </div>
    </div>
}

<div class="row g-4 mb-4">
    <div class="col-xl-7">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Gateway.Installation.ItsLicence"]</h5>
                <p class="card-subtitle mb-0">@T["Gateway.Installation.ItsLicence.Lead"]</p>
            </div>
            <div class="card-body">
                @if (Model.IsShared)
                {
                    <div class="alert alert-warning" role="alert">
                        <h6 class="alert-heading mb-1">@T["Licensing.Installations.Shared.Title", installation.LicenceHolders ?? 0]</h6>
                        <p class="mb-0">
                            @T["Gateway.Installation.Shared.Detail"]
                            <a asp-action="Index" asp-route-q="@installation.LicenceId">@T["Gateway.Installation.Shared.SeeAll"]</a>.
                        </p>
                    </div>
                }

                @switch (Model.LicenceState)
                {
                    case InstallationLicenceState.InRegister:
                        var file = licenceRow!;
                        <dl class="row mb-0">
                            <dt class="col-sm-4">@T["Licensing.Column.Customer"]</dt>
                            <dd class="col-sm-8">
                                <a asp-area="Licensing" asp-controller="Register" asp-action="Details" asp-route-id="@file.RecordId" class="fw-medium">@file.CustomerName</a>
                                <div class="small text-body">@file.CustomerEmail@(file.Company is null ? "" : " · " + file.Company)</div>
                            </dd>

                            <dt class="col-sm-4">@T["Licensing.Purpose"]</dt>
                            <dd class="col-sm-8"><partial name="~/Areas/Licensing/Views/Shared/_Purpose.cshtml" model="file.Purpose" /></dd>

                            <dt class="col-sm-4">@T["Licensing.Tier"]</dt>
                            <dd class="col-sm-8">@(file.Tier ?? "-")</dd>

                            <dt class="col-sm-4">@T["Licensing.Column.Expires"]</dt>
                            <dd class="col-sm-8">
                                @Day(file.ExpirationUtc)
                                @if (file.ExpirationUtc < DateTime.UtcNow)
                                {
                                    <span class="badge bg-label-secondary ms-1">@T["Licensing.Badge.Expired"]</span>
                                }
                            </dd>

                            <dt class="col-sm-4">@T["Licensing.LicenceId"]</dt>
                            <dd class="col-sm-8 mb-0">
                                <code>@installation.LicenceId</code>
                                @if (Model.LicenceFiles > 1)
                                {
                                    <div class="small text-body">@T["Gateway.Installation.LicenceFiles", Model.LicenceFiles]</div>
                                }
                            </dd>
                        </dl>
                        break;

                    case InstallationLicenceState.NotInRegister:
                        <div class="alert alert-warning mb-3" role="status">
                            <h6 class="alert-heading mb-1">@T["Licensing.Overview.Shared.NotInRegister"]</h6>
                            <p class="mb-0">@T["Gateway.Installation.NotInRegister.Detail"]</p>
                        </div>
                        <p class="mb-0">@T["Gateway.Installation.LicenceIdIs", Html.Raw($"<code>{installation.LicenceId}</code>")]</p>
                        break;

                    case InstallationLicenceState.RegisterUnread:
                        <div class="alert alert-secondary mb-3" role="status">
                            <h6 class="alert-heading mb-1">@T["Licensing.Overview.Unreadable.Title"]</h6>
                            <p class="mb-0">@T["Gateway.Installation.RegisterUnread.Detail"]</p>
                        </div>
                        <p class="mb-0">@T["Gateway.Installation.LicenceIdIs", Html.Raw($"<code>{installation.LicenceId}</code>")]</p>
                        break;

                    case InstallationLicenceState.IdNotRecorded:
                        <p class="mb-0">@T["Gateway.Installation.IdNotRecorded.Detail"]</p>
                        break;

                    default:
                        <h6 class="mb-1">@T["Gateway.Licence.None"]</h6>
                        <p class="mb-0">
                            @T["Gateway.Installation.OnEvaluation"]
                            @if (installation.Licence is { IsRejected: true, Reason: { } reason })
                            {
                                <span>@T["Gateway.Installation.Refused.Reason", Html.Raw($"<code>{Html.Encode(reason)}</code>")]</span>
                            }
                            else if (installation.Licence is { IsRejected: true })
                            {
                                <span>@T["Gateway.Installation.Refused"]</span>
                            }
                            else
                            {
                                <span>@T["Gateway.Installation.NoneSent"]</span>
                            }
                        </p>
                        break;
                }
            </div>
        </div>
    </div>

    <div class="col-xl-5">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">@T["Gateway.Installation.WhatToDo"]</h5>
            </div>
            <div class="card-body">
                <p class="mb-3">@T["Gateway.Installation.WhatToDo.Detail"]</p>
                @if (licenceRow is not null)
                {
                    <a asp-area="Licensing" asp-controller="Issue" asp-action="Index" asp-route-from="@licenceRow.RecordId" class="btn btn-label-secondary">
                        <i class="ti ti-refresh me-1"></i> @T["Licensing.Reissue"]
                    </a>
                }
            </div>
        </div>

        @* Revoke and restore (#69): under the write token, behind a confirm step, through the audit seam. *@
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">@(installation.IsRevoked ? T["Gateway.Restore"] : T["Gateway.Revoke"])</h5>
            </div>
            <div class="card-body">
                <p class="mb-3">
                    @if (installation.IsRevoked)
                    {
                        <span>@T["Gateway.Installation.Restore.Lead"]</span>
                    }
                    else
                    {
                        <span>@T["Gateway.Installation.Revoke.Lead"]</span>
                    }
                </p>
                @if (!Model.CanWrite)
                {
                    <button type="button" class="btn btn-label-secondary" disabled>@(installation.IsRevoked ? T["Gateway.Restore"] : T["Gateway.Revoke"])</button>
                    <p class="small text-body-secondary mt-2 mb-0">@T["Gateway.NoWriteToken.Short"]</p>
                }
                else if (!Model.MayWrite)
                {
                    <button type="button" class="btn btn-label-secondary" disabled>@(installation.IsRevoked ? T["Gateway.Restore"] : T["Gateway.Revoke"])</button>
                    <p class="small text-body-secondary mt-2 mb-0">@T["Gateway.Installation.ViewOnly", T.Role(ConsoleRoles.GatewayWrite)]</p>
                }
                else if (installation.IsRevoked)
                {
                    <a asp-action="Restore" asp-route-id="@Model.InstallationId" class="btn btn-primary">@T["Gateway.Restore"]…</a>
                }
                else
                {
                    <a asp-action="Revoke" asp-route-id="@Model.InstallationId" class="btn btn-outline-danger">@T["Gateway.Revoke"]…</a>
                }
            </div>
        </div>
    </div>
</div>
</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)
{
    <partial name="_InstallationsUnavailable" model="(answer.Outcome, answer.Detail)" />
    return;
}

<div class="card">
    <div class="card-header">
        @if (Model.SearchedLicence is { } searched)
        {
            <h5 class="card-title mb-1">@T["Gateway.Installations.HoldingLicence", Html.Raw($"<code>{searched}</code>")]</h5>
            <p class="card-subtitle mb-0">
                @T["Gateway.Installations.HoldingLicence.Lead"]
                @if (Model.Register.TryGetValue(searched, out var licenceRow))
                {
                    <span>@T["Gateway.Installations.HoldingLicence.Row", Html.ActionLink(licenceRow.CustomerName, "Details", "Register", new { area = "Licensing", id = licenceRow.RecordId })]</span>
                }
            </p>
        }
        else
        {
            var total = answer.Total ?? answer.Installations.Count;
            <h5 class="card-title mb-1">
                @if (filter.IsFiltered)
                {
                    @(total == 1 ? T["Gateway.Installations.Count.OneMatch"] : T["Gateway.Installations.Count.ManyMatch", total])
                }
                else
                {
                    @(total == 1 ? T["Gateway.Installations.Count.One"] : T["Gateway.Installations.Count.Many", total])
                }
            </h5>
            <p class="card-subtitle mb-0">@T["Gateway.Installations.OrderLead", T[InstallationFilter.Sorts.First(sort => sort.Sort == filter.SortOrder).Label].Value]</p>
        }
    </div>

    @if (!Model.ReportsUsage)
    {
        <div class="card-body pt-0">
            <div class="alert alert-secondary mb-0" role="status">
                <h6 class="alert-heading mb-1">@T["Gateway.NoUsageYet.Title"]</h6>
                <p class="mb-0">@T["Gateway.Installations.NoUsageYet.Detail"]</p>
            </div>
        </div>
    }

    <div class="table-responsive">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>@T["Licensing.Installations.Column.Installation"]</th>
                    <th>@T["Licensing.Installations.Column.Row"]</th>
                    <th>@T["Licensing.Installations.Column.Status"]</th>
                    <th>@T["Licensing.Installations.Column.Version"]</th>
                    <th>@T["Licensing.Installations.Column.Enrolled"]</th>
                    <th class="text-nowrap">@T["Gateway.Installations.Column.LastSeenUtc"]</th>
                    <th class="text-nowrap">@T["Licensing.Installations.Column.TokensUsed"]</th>
                    <th>@T["Gateway.Installations.Column.Licence"]</th>
                </tr>
            </thead>
            <tbody>
                @if (answer.Installations.Count == 0)
                {
                    <tr>
                        <td colspan="8" class="text-center text-body py-4">
                            @if (Model.SearchedLicence is not null)
                            {
                                <span>@T["Gateway.Installations.Empty.Searched"]</span>
                            }
                            else if (filter.IsFiltered)
                            {
                                <span>@T["Gateway.Installations.Empty.Filtered"]</span>
                            }
                            else
                            {
                                <span>@T["Gateway.Installations.Empty"]</span>
                            }
                        </td>
                    </tr>
                }
                @foreach (var installation in answer.Installations)
                {
                    var tokens = installation.Allowance?.Tokens;
                    <tr>
                        <td class="text-nowrap">
                            <a 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>
                        </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" title="@Instant(installation.RevokedAt)">@Day(installation.RevokedAt!.Value)</div>
                            }
                        </td>
                        <td>@(installation.AppVersion ?? "-")</td>
                        <td class="text-nowrap" title="@Instant(installation.CreatedAt)">@Day(installation.CreatedAt)</td>
                        <td class="text-nowrap">@Minute(installation.LastSeenAt)</td>
                        <td style="min-width: 8rem">
                            @if (tokens is null)
                            {
                                <span class="small text-body-secondary">@T["Licensing.Installations.NotReported"]</span>
                            }
                            else
                            {
                                var bar = installation.IsRevoked ? "bg-secondary" : tokens.Percent >= 100 ? "bg-danger" : tokens.Percent >= 80 ? "bg-warning" : "bg-primary";
                                <div class="small text-nowrap">
                                    @AllowanceWords.N(tokens.Used) <span class="text-body-secondary">@T["Gateway.Of", AllowanceWords.N(tokens.Limit)]</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>
                            }
                        </td>
                        <td>
                            <partial name="_InstallationLicence" model="Model.LicenceOf(installation)" />
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

    @if (Model.PageCount is > 1 and var pages)
    {
        <div class="card-footer d-flex justify-content-between align-items-center">
            <span class="text-body">@T["Generic.PageOf", Model.Page, pages]</span>
            <div class="d-flex gap-2">
                @if (Model.Page > 1)
                {
                    <a asp-action="Index" asp-all-route-data="@filter.RouteValues(Model.Page - 1)" class="btn btn-sm btn-label-secondary">@T["Generic.Previous"]</a>
                }
                @if (Model.Page < pages)
                {
                    <a asp-action="Index" asp-all-route-data="@filter.RouteValues(Model.Page + 1)" class="btn btn-sm btn-label-secondary">@T["Generic.Next"]</a>
                }
            </div>
        </div>
    }
</div>
</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>
                        <td class="text-nowrap">@PolicyPage.Requests(tier, S)</td>
                        <td>@N(tier.TokenBudget) <div class="small text-body-secondary">@PolicyPage.Period(tier.BudgetPeriod, S)</div></td>
                        <td class="text-nowrap">@T["Gateway.Tokens", N(tier.MaxPredictTokens)]</td>
                        <td>
                            <a asp-controller="Installations" asp-action="Index" asp-route-row="@tier.Tier" asp-route-status="active">@N(tier.InstallationsServed)</a>
                        </td>
                        <td>
                            @if (!isLicenceRow)
                            {
                                <span class="text-body-secondary" title="@T["Gateway.Policy.NoLicenceRow"].Value">-</span>
                            }
                            else if (Model.LicencesInForce is null)
                            {
                                <span class="small text-body-secondary">@T["Gateway.Policy.RegisterNotRead"]</span>
                            }
                            else
                            {
                                var count = Model.LicencesInForce.GetValueOrDefault(tier.Tier);
                                <a asp-controller="Usage" asp-action="Index" asp-route-tier="@tier.Tier">@(count == 1 ? T["Licensing.Register.Count.One"] : T["Licensing.Register.Count.Many", N(count)])</a>
                            }
                        </td>
                        <td class="text-end">
                            @if (mayChange)
                            {
                                <a asp-controller="PolicyChange" asp-action="Tier" asp-route-tier="@tier.Tier" class="btn btn-sm btn-label-primary">@T["Gateway.Policy.Change"]</a>
                            }
                            else
                            {
                                <span class="btn btn-sm btn-label-secondary disabled" title="@cannotChange">@T["Gateway.Policy.Change"]</span>
                            }
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
    <div class="card-body">
        <dl class="row small mb-3">
            <dt class="col-sm-3">@T["Gateway.Installation.Requests"]</dt>
            <dd class="col-sm-9">@T["Gateway.Policy.Requests.Help"]</dd>
            <dt class="col-sm-3">@T["Gateway.Policy.TokenBudget"]</dt>
            <dd class="col-sm-9">@T["Gateway.Policy.TokenBudget.Help"]</dd>
            <dt class="col-sm-3">@T["Gateway.Installation.LongestReply"]</dt>
            <dd class="col-sm-9">@T["Gateway.Policy.LongestReply.Help"]</dd>
            <dt class="col-sm-3">@T["Gateway.Policy.Whose"]</dt>
            <dd class="col-sm-9 mb-0">@T["Gateway.Policy.Whose.Help"]</dd>
        </dl>
        <div class="alert alert-info mb-0" role="note">
            <h6 class="alert-heading mb-1">@T["Gateway.Policy.OnlyUp.Title"]</h6>
            <p class="mb-2">@T["Gateway.Policy.OnlyUp.Detail"]</p>
            @if (status is { Installations: { } fleet })
            {
                <p class="mb-0">@(fleet.LicensedWithoutLicenceTier == 1 ? T["Gateway.Policy.NoTier.One"] : T["Gateway.Policy.NoTier.Many", N(fleet.LicensedWithoutLicenceTier)])</p>
            }
        </div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-1">@T["Gateway.Policy.Levers"]</h5>
        <p class="card-subtitle mb-0">@T["Gateway.Policy.Levers.Lead"]</p>
    </div>
    <div class="card-body">

        @* The minimum application version. *@
        <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <h6 class="mb-0">@T["Gateway.Policy.Minimum"]</h6>
                @if (mayChange)
                {
                    <a asp-controller="PolicyChange" asp-action="MinimumVersion" class="btn btn-sm btn-label-primary">@T["Gateway.Policy.Change"]</a>
                }
                else
                {
                    <span class="btn btn-sm btn-label-secondary disabled" title="@cannotChange">@T["Gateway.Policy.Change"]</span>
                }
            </div>
            <p class="mb-2">
                <span class="fs-5 fw-medium"><code>@(levers!.MinimumAppVersion ?? "-")</code></span>
                @if (levers.MinimumAppVersion?.Trim() == "0.0.0")
                {
                    <span class="text-body-secondary ms-2">@T["Gateway.Policy.Minimum.Seeded"]</span>
                }
            </p>
            <p class="small text-body mb-2">@T["Gateway.Policy.Minimum.Help"]</p>
            @if (!InstallationQuery.IsVersion(levers.MinimumAppVersion))
            {
                <div class="alert alert-warning small mb-2" role="alert">@T["Gateway.Policy.Minimum.NotAVersion"]</div>
            }
            <ul class="small mb-0">
                @if (Model.BelowMinimum is { } belowMinimum)
                {
                    <li>
                        @T["Gateway.Policy.Minimum.Below", Html.Raw($"<code>{Html.Encode(belowMinimum.Version)}</code>")]
                        @if (belowMinimum.Answered)
                        {
                            <text>@T["Gateway.Policy.Minimum.Below.Refused", Html.ActionLink(Installations(belowMinimum.Count!.Value), "Index", "Installations", new { below = belowMinimum.Version, status = "active" })]</text>
                        }
                        else
                        {
                            <span class="text-body-secondary">@Unanswered(belowMinimum)</span>
                        }
                    </li>
                }
                @if (Model.BelowRelease is { } belowRelease)
                {
                    <li>
                        @T["Gateway.Policy.Minimum.BelowRelease", Html.Raw($"<code>{Html.Encode(belowRelease.Version)}</code>")]
                        @if (belowRelease.Answered)
                        {
                            <text>@T["Gateway.Policy.Minimum.BelowRelease.WouldRefuse", Html.ActionLink(Installations(belowRelease.Count!.Value), "Index", "Installations", new { below = belowRelease.Version, status = "active" })]</text>
                        }
                        else
                        {
                            <span class="text-body-secondary">@Unanswered(belowRelease)</span>
                        }
                    </li>
                }
                <li>@T["Gateway.Policy.Minimum.AnyOther", Html.ActionLink(S["Gateway.Policy.InstallationsList"].Value, "Index", "Installations", new { status = "active" })]</li>
            </ul>
        </div>

        @* The enrolment velocity limit. *@
        <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <h6 class="mb-0">@T["Gateway.Policy.Velocity"]</h6>
                @if (mayChange)
                {
                    <a asp-controller="PolicyChange" asp-action="Velocity" class="btn btn-sm btn-label-primary">@T["Gateway.Policy.Change"]</a>
                }
                else
                {
                    <span class="btn btn-sm btn-label-secondary disabled" title="@cannotChange">@T["Gateway.Policy.Change"]</span>
                }
            </div>
            <p class="mb-2">
                @if (levers.VelocityArmed)
                {
                    <span class="badge bg-label-warning me-2">@T["Gateway.Policy.Velocity.Armed"]</span>
                    <span>@T["Gateway.Policy.Velocity.Limits", levers.EnrolmentsPerHour is { } hourly ? S["Gateway.Policy.Velocity.AnHour", N(hourly)].Value : S["Gateway.Policy.Velocity.NoHourly"].Value, levers.EnrolmentsPerDay is { } daily ? S["Gateway.Policy.Velocity.ADay", N(daily)].Value : S["Gateway.Policy.Velocity.NoDaily"].Value]</span>
                }
                else
                {
                    <span class="badge bg-label-secondary me-2">@T["Gateway.Policy.Off"]</span>
                    <span>@T["Gateway.Policy.Velocity.OffDetail"]</span>
                }
            </p>
            <p class="small text-body mb-2">@T["Gateway.Policy.Velocity.Help"]</p>
            <div class="alert alert-warning small mb-0" role="alert">
                <h6 class="alert-heading mb-1">@T["Gateway.Policy.Velocity.CheckAddress.Title"]</h6>
                <p class="mb-2">@T["Gateway.Policy.Velocity.CheckAddress.Detail"]</p>
                <p class="mb-0">
                    @if (status?.Caller?.Address is { } address)
                    {
                        <span>@T["Gateway.Policy.Velocity.CallerSeen", Minute(Model.Status.AskedAt), Html.Raw($"<code>{Html.Encode(address)}</code>")]</span>
                    }
                    else
                    {
                        <span>@T["Gateway.Policy.Velocity.CallerUnknown"]</span>
                    }
                </p>
            </div>
        </div>

        @* The global token ceiling. *@
        <div>
            <div class="d-flex justify-content-between align-items-center mb-1">
                <h6 class="mb-0">@T["Gateway.Policy.Ceiling"]</h6>
                @if (mayChange)
                {
                    <a asp-controller="PolicyChange" asp-action="Ceiling" class="btn btn-sm btn-label-primary">@T["Gateway.Policy.Change"]</a>
                }
                else
                {
                    <span class="btn btn-sm btn-label-secondary disabled" title="@cannotChange">@T["Gateway.Policy.Change"]</span>
                }
            </div>
            <p class="mb-2">
                @if (levers.GlobalTokenCeiling is { } ceiling)
                {
                    <span class="fs-5 fw-medium">@N(ceiling)</span>
                    <span class="text-body-secondary ms-1">@T["Gateway.Policy.Ceiling.Unit"]</span>
                }
                else
                {
                    <span class="badge bg-label-secondary me-2">@T["Gateway.Policy.NoBrake"]</span>
                    <span>@T["Gateway.Policy.NoBrake.Detail"]</span>
                }
            </p>
            @if (status?.Brake is { } brake && levers.GlobalTokenCeiling is not null)
            {
                @if (brake.Tripped)
                {
                    <div class="alert alert-danger small mb-2" role="alert">@T["Gateway.Policy.BrakeOn"]</div>
                }
                <p class="small mb-2">
                    @T["Gateway.Policy.SpentThisMonth", N(brake.Used)]@(brake.Percent is { } percent ? S["Gateway.Policy.SpentPercent", percent].Value : "")@(brake.PeriodEnd is { } end ? S["Gateway.Policy.SpentUntil", Minute(end)].Value : "").
                    @T["Gateway.Policy.OverviewHasBrake", Html.ActionLink(S["Gateway.Policy.TheOverview"].Value, "Index", "Home")]
                </p>
            }
            else if (status is null)
            {
                <p class="small text-body-secondary mb-2">@T["Gateway.Policy.BrakeUnknown"]</p>
            }
            <p class="small text-body mb-0">@T["Gateway.Policy.Ceiling.Help"]</p>
        </div>
    </div>
</div>
</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">
                            <button type="submit" name="Step" value="@PolicyChangeForm.ReviewStep" class="btn btn-primary" disabled="@(!Model.Writer.CanSubmit)">@T["Gateway.Change.Review"]</button>
                            <a asp-controller="Policy" asp-action="Index" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                        </div>
                    </form>
                }
            </div>
        </div>
    </div>

    <div class="col-12 col-lg-5">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Gateway.Ceiling.TheBrake"]</h6>
            </div>
            <div class="card-body small">
                @if (brake is null)
                {
                    <p class="text-body-secondary">@T["Gateway.Policy.BrakeUnknown"]</p>
                }
                else
                {
                    @if (brake.Tripped)
                    {
                        <div class="alert alert-danger mb-3" role="alert">@T["Gateway.Ceiling.BrakeOn"]</div>
                    }
                    <dl class="row mb-3">
                        <dt class="col-6">@T["Gateway.Ceiling.SpentThisMonth"]</dt>
                        <dd class="col-6">@N(brake.Used)@(brake.Percent is { } percent ? $", {percent}%" : "")</dd>
                        <dt class="col-6">@T["Gateway.Ceiling.MonthEnds"]</dt>
                        <dd class="col-6 mb-0">@(brake.PeriodEnd is { } end ? $"{Minute(end)} UTC" : "-")</dd>
                    </dl>
                }
                <p>@T["Gateway.Ceiling.About.1"]</p>
                <p>@T["Gateway.Ceiling.About.2"]</p>
                <p class="mb-0">@T["Gateway.Ceiling.About.3"]</p>
            </div>
        </div>
    </div>
</div>
</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
                {
                    <form method="post" asp-action="MinimumVersion">
                        <div class="mb-3">
                            <label for="MinimumAppVersion" class="form-label">@T["Gateway.Policy.Minimum"]</label>
                            <input type="text" id="MinimumAppVersion" name="MinimumAppVersion" value="@form.MinimumAppVersion" class="form-control"
                                   maxlength="@MinimumVersionForm.MaxLength" placeholder="1.7.0" autocomplete="off" />
                            <div class="form-text">@T["Gateway.Change.NowValue", Html.Raw($"<code>{Html.Encode(now ?? "-")}</code>")]@(now?.Trim() == "0.0.0" ? S["Gateway.Minimum.Seeded.Suffix"].Value : "")</div>
                            @if (Error(nameof(MinimumVersionForm.MinimumAppVersion)) is { } versionError)
                            {
                                <div class="text-danger small mt-1">@versionError</div>
                            }
                        </div>
                        @if (!Model.Writer.CanSubmit)
                        {
                            <div class="mb-3"><partial name="_PolicyWriteBlocked" model="Model.Writer" /></div>
                        }
                        <div class="d-flex gap-2">
                            <button type="submit" name="Step" value="@PolicyChangeForm.ReviewStep" class="btn btn-primary" disabled="@(!Model.Writer.CanSubmit)">@T["Gateway.Minimum.SeeWhom"]</button>
                            <a asp-controller="Policy" asp-action="Index" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                        </div>
                    </form>
                }
            </div>
        </div>
    </div>

    <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.WhatItDoes"]</h6>
            </div>
            <div class="card-body small">
                <p>@T["Gateway.Minimum.WhatItDoes.1"]</p>
                <p>@T["Gateway.Minimum.WhatItDoes.2"]</p>
                <p class="mb-0">@T["Gateway.Minimum.CurrentRelease", Html.Raw($"<code>{KnowledgeFabric.AdminConsole.Licensing.Validation.LicenceValidator.ProductRelease}</code>")]</p>
            </div>
        </div>
    </div>
</div>
</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" />
                        <input type="hidden" name="RequestWindowSeconds" value="@form.RequestWindowSeconds" />
                        <input type="hidden" name="TokenBudget" value="@form.TokenBudget" />
                        <input type="hidden" name="BudgetPeriod" value="@form.BudgetPeriod" />
                        <input type="hidden" name="MaxPredictTokens" value="@form.MaxPredictTokens" />
                        <partial name="_PolicyConfirm" model="confirm" />
                    </form>
                </div>
            }
            else
            {
                <div class="card-body">
                    <form method="post" asp-action="Tier" asp-route-tier="@tier">
                        <div class="row g-3 mb-3">
                            <div class="col-sm-6">
                                <label for="RequestsPerWindow" class="form-label">@T["Gateway.Installation.Requests"]</label>
                                <input type="text" inputmode="numeric" id="RequestsPerWindow" name="RequestsPerWindow" value="@form.RequestsPerWindow" class="form-control" />
                                <div class="form-text">@T["Gateway.Change.NowValue", N(current.RequestsPerWindow)]</div>
                                @if (Error(nameof(TierChangeForm.RequestsPerWindow)) is { } requestsError)
                                {
                                    <div class="text-danger small mt-1">@requestsError</div>
                                }
                            </div>
                            <div class="col-sm-6">
                                <label for="RequestWindowSeconds" class="form-label">@T["Gateway.Tier.Window"]</label>
                                <input type="text" inputmode="numeric" id="RequestWindowSeconds" name="RequestWindowSeconds" value="@form.RequestWindowSeconds" class="form-control" />
                                <div class="form-text">@T["Gateway.Tier.Window.Now", N(current.RequestWindowSeconds)]</div>
                                @if (Error(nameof(TierChangeForm.RequestWindowSeconds)) is { } windowError)
                                {
                                    <div class="text-danger small mt-1">@windowError</div>
                                }
                            </div>
                            <div class="col-sm-6">
                                <label for="TokenBudget" class="form-label">@T["Gateway.Policy.TokenBudget"]</label>
                                <input type="text" inputmode="numeric" id="TokenBudget" name="TokenBudget" value="@form.TokenBudget" class="form-control" />
                                <div class="form-text">@T["Gateway.Change.NowValue", N(current.TokenBudget)]</div>
                                @if (Error(nameof(TierChangeForm.TokenBudget)) is { } budgetError)
                                {
                                    <div class="text-danger small mt-1">@budgetError</div>
                                }
                            </div>
                            <div class="col-sm-6">
                                <label for="BudgetPeriod" class="form-label">@T["Gateway.Tier.PerPeriod"]</label>
                                <select id="BudgetPeriod" name="BudgetPeriod" class="form-select">
                                    @foreach (var period in BudgetPeriods.All)
                                    {
                                        <option value="@period" selected="@(form.BudgetPeriod == period)">@PolicyPage.PeriodName(period, S)</option>
                                    }
                                </select>
                                <div class="form-text">@T["Gateway.Change.NowValue", PolicyPage.PeriodName(current.BudgetPeriod, S)]</div>
                                @if (Error(nameof(TierChangeForm.BudgetPeriod)) is { } periodError)
                                {
                                    <div class="text-danger small mt-1">@periodError</div>
                                }
                            </div>
                            <div class="col-sm-6">
                                <label for="MaxPredictTokens" class="form-label">@T["Gateway.Tier.LongestReplyTokens"]</label>
                                <input type="text" inputmode="numeric" id="MaxPredictTokens" name="MaxPredictTokens" value="@form.MaxPredictTokens" class="form-control" />
                                <div class="form-text">@T["Gateway.Change.NowValue", N(current.MaxPredictTokens)]</div>
                                @if (Error(nameof(TierChangeForm.MaxPredictTokens)) is { } predictError)
                                {
                                    <div class="text-danger small mt-1">@predictError</div>
                                }
                            </div>
                        </div>
                        @if (!Model.Writer.CanSubmit)
                        {
                            <div class="mb-3"><partial name="_PolicyWriteBlocked" model="Model.Writer" /></div>
                        }
                        <div class="d-flex gap-2">
                            <button type="submit" name="Step" value="@PolicyChangeForm.ReviewStep" class="btn btn-primary" disabled="@(!Model.Writer.CanSubmit)">@T["Gateway.Change.Review"]</button>
                            <a asp-controller="Policy" asp-action="Index" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                        </div>
                    </form>
                </div>
            }
        </div>
    </div>

    <div class="col-12 col-lg-5">
        <div class="card h-100">
            <div class="card-header">
                <h6 class="card-title mb-0">@T["Gateway.Tier.WhomItReaches"]</h6>
            </div>
            <div class="card-body">
                <dl class="row mb-3">
                    <dt class="col-7">@T["Gateway.Policy.InstallationsServed"]</dt>
                    <dd class="col-5">
                        <a asp-controller="Installations" asp-action="Index" asp-route-row="@tier" asp-route-status="active">@N(current.InstallationsServed)</a>
                    </dd>
                    @if (Model.IsLicenceRow)
                    {
                        <dt class="col-7">@T["Gateway.Policy.LicencesInForce"]</dt>
                        <dd class="col-5 mb-0">
                            @if (Model.RegisterRead)
                            {
                                <a asp-controller="Usage" asp-action="Index" asp-route-tier="@tier">@N(licences)</a>
                            }
                            else
                            {
                                <span class="text-body-secondary">@T["Gateway.Policy.RegisterNotRead"]</span>
                            }
                        </dd>
                    }
                </dl>
                <p class="small mb-3">@T["Gateway.Tier.Reaches.Detail"]</p>
                @if (!Model.IsLicenceRow)
                {
                    <p class="small mb-0">@T["Gateway.Tier.Evaluation"]</p>
                }
                else if (Model.RuleHolds)
                {
                    <div class="alert alert-info small mb-0" role="note">@T["Gateway.Tier.RuleHolds"]</div>
                }
                else
                {
                    <p class="small mb-0">@T["Gateway.Tier.RuleFree"]</p>
                }
            </div>
        </div>
    </div>
</div>
</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)
                                {
                                    <div class="text-danger small mt-1">@dayError</div>
                                }
                            </div>
                        </div>

                        @if (!Model.WasArmed)
                        {
                            <div class="alert alert-warning small mb-3" role="alert">
                                <h6 class="alert-heading mb-1">@T["Gateway.Policy.Velocity.CheckAddress.Title"]</h6>
                                <p class="mb-2">@T["Gateway.Velocity.CheckAddress.Counts"]</p>
                                <p class="mb-2">
                                    @if (address is not null)
                                    {
                                        <span>@T["Gateway.Policy.Velocity.CallerSeen", Model.AskedAt.UtcDateTime.ToString("yyyy-MM-dd HH:mm"), Html.Raw($"<code>{Html.Encode(address)}</code>")]</span>
                                    }
                                    else
                                    {
                                        <span>@T["Gateway.Velocity.CallerUnknownHere"]</span>
                                    }
                                </p>
                                <div class="form-check mb-0">
                                    <input class="form-check-input" type="checkbox" name="AddressChecked" id="AddressChecked" value="true" checked="@form.AddressChecked" />
                                    <label class="form-check-label" for="AddressChecked">@T["Gateway.Velocity.AddressChecked"]</label>
                                </div>
                                @if (Error(nameof(VelocityForm.AddressChecked)) is { } checkError)
                                {
                                    <div class="text-danger mt-1">@checkError</div>
                                }
                            </div>
                        }

                        @if (!Model.Writer.CanSubmit)
                        {
                            <div class="mb-3"><partial name="_PolicyWriteBlocked" model="Model.Writer" /></div>
                        }
                        <div class="d-flex gap-2">
                            <button type="submit" name="Step" value="@PolicyChangeForm.ReviewStep" class="btn btn-primary" disabled="@(!Model.Writer.CanSubmit)">@T["Gateway.Change.Review"]</button>
                            <a asp-controller="Policy" asp-action="Index" class="btn btn-label-secondary">@T["Generic.Cancel"]</a>
                        </div>
                    </form>
                }
            </div>
        </div>
    </div>

    <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.WhatItDoes"]</h6>
            </div>
            <div class="card-body small">
                <p>@T["Gateway.Velocity.WhatItDoes.1"]</p>
                <p class="mb-0">@T["Gateway.Velocity.WhatItDoes.2"]</p>
            </div>
        </div>
    </div>
</div>
</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/_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/_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>
                </div>
            </div>
        </div>
    }
</div>

<div class="card mb-4">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-start gap-2">
        <div>
            <h5 class="card-title mb-1">@T["Gateway.Usage.TokensADay"]</h5>
            <p class="card-subtitle mb-0">@T["Gateway.History.Chart.Lead", LongDay(range.From), LongDay(range.To), range.Days == 1 ? S["Gateway.Days.One"].Value : S["Gateway.Days", range.Days].Value]</p>
        </div>
        @if (Model.Daily?.Outcome == GatewayOutcome.Answered)
        {
            <a asp-action="HistoryExport" asp-all-route-data="daysExport" class="btn btn-sm btn-label-primary text-nowrap"><i class="ti ti-download me-1"></i>@T["Gateway.History.DaysCsv"]</a>
        }
    </div>
    <div class="card-body">
        @if (Model.Daily is { Outcome: GatewayOutcome.Answered } daily)
        {
            var tokensChart = (UsageChart.TokensByRow(daily.Days, S), "history-tokens", 300);
            <partial name="_UsageChart" model="tokensChart" />
            <partial name="_UsageChartScripts" />
        }
        else if (Model.Daily is { } failed)
        {
            <partial name="_UsageUnavailable" model="(failed.Outcome, failed.Detail)" />
        }
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-1">@T["Gateway.History.ByRow"]</h5>
        <p class="card-subtitle mb-0">@T["Gateway.History.ByRow.Lead"]</p>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>@T["Licensing.Installations.Column.Row"]</th>
                    <th class="text-end">@T["Gateway.History.Tokens"]</th>
                    <th class="text-end">@T["Gateway.History.Share"]</th>
                    <th class="text-end">@T["Gateway.History.Requests"]</th>
                    <th class="text-end" title="@T["Gateway.History.Refused.Title"].Value">@T["Gateway.History.Refused"]</th>
                    <th class="text-end text-nowrap">@T["Gateway.History.UpstreamErrors"]</th>
                    <th class="text-end">@T["Licensing.Installations"]</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var row in UsageHistory.Rows)
                {
                    var counts = Model.Row(row);
                    <tr>
                        <td class="fw-medium">
                            <a asp-controller="Installations" asp-action="Index" asp-route-row="@row">@row</a>
                        </td>
                        <td class="text-end">@N(counts.Tokens)</td>
                        <td class="text-end">@(Model.Share(counts.Tokens) is { } share ? $"{share}%" : "-")</td>
                        <td class="text-end">@N(counts.Requests)</td>
                        <td class="text-end" title="@Refusals(counts.RefusalsRateLimited, counts.RefusalsBudgetExhausted)">@N(counts.RefusalsRateLimited + counts.RefusalsBudgetExhausted)</td>
                        <td class="text-end">@N(counts.UpstreamErrors)</td>
                        <td class="text-end">@N(counts.Installations)</td>
                    </tr>
                }
                @if (unrowed is not null)
                {
                    <tr>
                        <td class="text-body-secondary" title="@T["Gateway.History.Unrowed.Title"].Value">@T["Gateway.History.Unrowed"]</td>
                        <td class="text-end">@N(unrowed.Tokens)</td>
                        <td class="text-end">@(Model.Share(unrowed.Tokens) is { } share ? $"{share}%" : "-")</td>
                        <td class="text-end">@N(unrowed.Requests)</td>
                        <td class="text-end" title="@Refusals(unrowed.RefusalsRateLimited, unrowed.RefusalsBudgetExhausted)">@N(unrowed.RefusalsRateLimited + unrowed.RefusalsBudgetExhausted)</td>
                        <td class="text-end">@N(unrowed.UpstreamErrors)</td>
                        <td class="text-end">@N(unrowed.Installations)</td>
                    </tr>
                }
                <tr class="fw-medium">
                    <td>@T["Gateway.History.All"]</td>
                    <td class="text-end">@N(totals.Tokens)</td>
                    <td class="text-end">@(totals.Tokens > 0 ? "100%" : "-")</td>
                    <td class="text-end">@N(totals.Requests)</td>
                    <td class="text-end" title="@Refusals(totals.RefusalsRateLimited, totals.RefusalsBudgetExhausted)">@N(totals.RefusalsRateLimited + totals.RefusalsBudgetExhausted)</td>
                    <td class="text-end">@N(totals.UpstreamErrors)</td>
                    <td class="text-end">@N(totals.Installations)</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-start gap-2">
        <div>
            <h5 class="card-title mb-1">@T["Gateway.History.TopInstallations"]</h5>
            <p class="card-subtitle mb-0">
                @T["Gateway.History.Top.Lead", request.Top]
                @if (summary.ListsEveryone)
                {
                    <span>@T["Gateway.History.Top.Everyone"]</span>
                }
                else
                {
                    <span>@T["Gateway.History.Top.Some", N(totals.Installations)]</span>
                }
            </p>
        </div>
        @if (Model.Top.Count > 0)
        {
            <a asp-action="HistoryExport" asp-all-route-data="topExport" class="btn btn-sm btn-label-primary text-nowrap"><i class="ti ti-download me-1"></i>@T["Gateway.History.TopCsv"]</a>
        }
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>@T["Licensing.Installations.Column.Installation"]</th>
                    <th>@T["Licensing.Installations.Column.Row"]</th>
                    <th>@T["Gateway.Installations.Column.Licence"]</th>
                    <th class="text-end">@T["Gateway.History.Tokens"]</th>
                    <th class="text-end">@T["Gateway.History.Share"]</th>
                    <th class="text-end">@T["Gateway.History.Requests"]</th>
                    <th class="text-end">@T["Gateway.History.Refused"]</th>
                    <th class="text-end text-nowrap">@T["Gateway.History.UpstreamErrors"]</th>
                </tr>
            </thead>
            <tbody>
                @if (Model.Top.Count == 0)
                {
                    <tr>
                        <td colspan="9" class="text-center text-body py-4">@T["Gateway.History.Top.Empty"]</td>
                    </tr>
                }
                @foreach (var top in Model.Top)
                {
                    var usage = top.Usage;
                    <tr>
                        <td class="text-body-secondary">@top.Rank</td>
                        <td class="text-nowrap">
                            <a asp-controller="Installations" asp-action="Details" asp-route-id="@usage.InstallationId" title="@usage.InstallationId"><code>@Short(usage.InstallationId)</code></a>
                            <button type="button" class="btn btn-sm btn-icon btn-text-secondary" data-copy="@usage.InstallationId"
                                    title="@T["Gateway.CopyWholeId"].Value" aria-label="@S["Gateway.CopyId.Aria", usage.InstallationId].Value">
                                <i class="ti ti-copy"></i>
                            </button>
                        </td>
                        <td>@(usage.Row ?? T["Gateway.History.Unrowed.Lower"].Value)</td>
                        <td>
                            @if (top.Licence is { } licence)
                            {
                                <a asp-area="Licensing" asp-controller="Register" asp-action="Details" asp-route-id="@licence.RecordId">@licence.CustomerName</a>
                            }
                            else if (top.LicenceId is { } licenceId)
                            {
                                <code title="@licenceId">@Short(licenceId)</code> <span class="small text-body-secondary">@T["Gateway.History.NotInRegister.Lower"]</span>
                            }
                            else
                            {
                                <span class="text-body-secondary">-</span>
                            }
                        </td>
                        <td class="text-end">@N(usage.Tokens)</td>
                        <td class="text-end">@(Model.Share(usage.Tokens) is { } share ? $"{share}%" : "-")</td>
                        <td class="text-end">@N(usage.Requests)</td>
                        <td class="text-end" title="@Refusals(usage.RefusalsRateLimited, usage.RefusalsBudgetExhausted)">@N(usage.RefusalsRateLimited + usage.RefusalsBudgetExhausted)</td>
                        <td class="text-end">@N(usage.UpstreamErrors)</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
    <div class="card-body">
        <p class="small text-body-secondary mb-0">@T["Gateway.History.Footnote"]</p>
    </div>
</div>
</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)
        {
            <div class="alert alert-secondary mb-0" role="status">
                <h6 class="alert-heading mb-1">@T["Gateway.NoUsageYet.Title"]</h6>
                <p class="mb-0">@T["Gateway.Usage.NoUsageYet.Detail"]</p>
            </div>
        }
        else
        {
            <partial name="_InstallationsUnavailable" model="(Model.Gateway.Outcome, Model.Gateway.Detail)" />
        }
    </div>
}

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-1">
            @(Model.Licences.Count == 1 ? T["Gateway.Usage.Count.One"] : T["Gateway.Usage.Count.Many", Model.Licences.Count])
            @if (filter.Allowance is { } allowance)
            {
                <text>@T["Gateway.Usage.OnAllowance", allowance]</text>
            }
        </h5>
        <p class="card-subtitle mb-0">
            @T[UsageFilter.Sorts.First(sort => sort.Sort == filter.SortOrder).Label].
            @if (Model.Hidden > 0)
            {
                <span>@(Model.Hidden == 1 ? T["Gateway.Usage.Hidden.One"] : T["Gateway.Usage.Hidden.Many", Model.Hidden])</span>
            }
            @if (Model.GatewayAnswered)
            {
                <span>
                    @T["Gateway.Usage.Enrolled", Model.Enrolled, Model.NotEnrolled]
                    @if (Model.NearLimit > 0)
                    {
                        <span class="badge bg-label-warning">@T["Gateway.Usage.NearLimit", Model.NearLimit, UsageByLicence.NearLimitPercent]</span>
                    }
                    @if (Model.Shared > 0)
                    {
                        <span class="badge bg-label-warning">@T["Gateway.Usage.SharedCount", Model.Shared]</span>
                    }
                    @if (Model.ServedOtherwise > 0)
                    {
                        <span class="badge bg-label-danger">@T["Gateway.Usage.ServedOtherwiseCount", Model.ServedOtherwise]</span>
                    }
                </span>
            }
        </p>
    </div>

    @if (lastMonth is { Outcome: not GatewayOutcome.Answered } unread)
    {
        <div class="card-body pt-0">
            <p class="small text-body-secondary mb-0">
                @(unread.Outcome == GatewayOutcome.NotReported
                    ? T["Gateway.Usage.LastMonth.NoLedger"]
                    : T["Gateway.Usage.LastMonth.Failed", unread.Detail ?? ""])
            </p>
        </div>
    }
    else if (lastMonth is { Unread: > 0 } partial)
    {
        <div class="card-body pt-0">
            <p class="small text-body-secondary mb-0">@T["Gateway.Usage.LastMonth.Partial", partial.Unread]</p>
        </div>
    }

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>@T["Licensing.Column.Customer"]</th>
                    <th>@T["Licensing.Purpose"]</th>
                    <th>@T["Licensing.Tier"]</th>
                    <th>@T["Licensing.Column.Expires"]</th>
                    <th>@T["Licensing.Installations.Column.Installation"]</th>
                    <th class="text-nowrap">@T["Gateway.Usage.TokensThisPeriod"]</th>
                    <th style="width: 6.5rem" title="@T["Gateway.Usage.LastMonth.Title"].Value">@lastMonthHeading</th>
                    <th style="width: 7rem">@T["Licensing.Installations.Column.RequestsAMinute"]</th>
                </tr>
            </thead>
            <tbody>
                @if (Model.Licences.Count == 0)
                {
                    <tr>
                        <td colspan="8" class="text-center text-body py-4">
                            @if (Model.Hidden > 0)
                            {
                                <span>@T["Gateway.Usage.Empty.Customers"]</span>
                            }
                            else if (filter.Allowance is not null)
                            {
                                <span>@T["Gateway.Usage.Empty.Allowance"]</span>
                            }
                            else
                            {
                                <span>@T["Gateway.Usage.Empty"]</span>
                            }
                        </td>
                    </tr>
                }
                @foreach (var licence in Model.Licences)
                {
                    var current = licence.Current;
                    var span = Math.Max(1, licence.Installations.Count);
                    var first = licence.Installations.FirstOrDefault();

                    <tr class="border-top">
                        <td rowspan="@span">
                            <a asp-area="Licensing" asp-controller="Register" asp-action="Details" asp-route-id="@current.RecordId" class="fw-medium">@current.CustomerName</a>
                            <div class="small text-body">@current.Company</div>
                            <div class="d-flex flex-wrap gap-1 mt-1">
                                @if (licence.IsNearLimit)
                                {
                                    <span class="badge bg-label-warning" title="@S["Gateway.Usage.NearLimit.Title", UsageByLicence.NearLimitPercent].Value">@T["Gateway.Usage.PercentUsed", licence.Percent ?? 0]</span>
                                }
                                @if (licence.IsShared)
                                {
                                    <span class="badge bg-label-warning" title="@T["Gateway.Usage.Shared.Title"].Value">@T["Licensing.Installations.Shared.Title", licence.Holding.Count()]</span>
                                }
                                @if (licence.IsServedOtherwise)
                                {
                                    <span class="badge bg-label-danger">@T["Gateway.Usage.ServedOtherwise"]</span>
                                }
                            </div>
                        </td>
                        <td rowspan="@span"><partial name="~/Areas/Licensing/Views/Shared/_Purpose.cshtml" model="current.Purpose" /></td>
                        <td rowspan="@span">@(current.Tier ?? "-")</td>
                        <td rowspan="@span" class="text-nowrap" title="@(licence.Licence.Files == 1 ? S["Gateway.Usage.OneFile"].Value : S["Gateway.Usage.Files", licence.Licence.Files].Value)">@Day(licence.CoveredUntilUtc)</td>

                        @if (!Model.GatewayAnswered)
                        {
                            <td colspan="4" class="small text-body-secondary">@unanswered</td>
                        }
                        else if (first is null)
                        {
                            <td><span class="badge bg-label-secondary" title="@T["Gateway.Usage.NotEnrolled.Title"].Value">@T["Gateway.Usage.NotEnrolled"]</span></td>
                            <td class="text-body-secondary">-</td>
                            <td class="text-body-secondary">-</td>
                            <td class="text-body-secondary">-</td>
                        }
                        else
                        {
                            <partial name="_InstallationUsage" model="(first, Model)" />
                        }
                    </tr>

                    @foreach (var usage in licence.Installations.Skip(1))
                    {
                        <tr>
                            <partial name="_InstallationUsage" model="(usage, Model)" />
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>

    <div class="card-body">
        <h6 class="mb-2">@T["Gateway.Usage.LessThanRegister.Title"]</h6>
        <p class="small text-body mb-2">@T["Gateway.Usage.LessThanRegister.Detail", LicenceValidator.ProductRelease]</p>
        @if (Model.GatewayAnswered && (Model.WithoutLicenceId > 0 || Model.HoldingOtherIds > 0))
        {
            <p class="small text-body mb-0">
                @if (Model.WithoutLicenceId > 0)
                {
                    <span>@(Model.WithoutLicenceId == 1 ? T["Gateway.Usage.WithoutId.One"] : T["Gateway.Usage.WithoutId.Many", Model.WithoutLicenceId])</span>
                }
                @if (Model.HoldingOtherIds > 0)
                {
                    <span>@(Model.HoldingOtherIds == 1 ? T["Gateway.Usage.OtherIds.One"] : T["Gateway.Usage.OtherIds.Many", Model.HoldingOtherIds])</span>
                }
                @T["Gateway.Usage.ListHasThemAll", Html.ActionLink(S["Gateway.Usage.TheInstallationsList"].Value, "Index", "Installations")]
            </p>
        }
    </div>
</div>
</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();
form.Sources = entitlements.Sources.Select(grant => grant.Name).ToList();
⋮----
.Where(grant => grant.Count is not null)
.ToDictionary(grant => grant.Name, grant => grant.Count, StringComparer.Ordinal);
⋮----
form.Ai = entitlements.Ai.ToList();
⋮----
private Task Audit(string action, string? target, IReadOnlyDictionary<string, string?> details) =>
auditLog.RecordAsync(
new AuditEntry(
⋮----
OccurredAt: clock.GetUtcNow(),
</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>
                                    </div>
                                }
                            </div>
                            <div class="form-text">@T["Licensing.Issue.PurposeHelp"]</div>
                        </div>
                        <div class="col-md-6">
                            <label asp-for="Company" class="form-label">@T["Licensing.Issue.Form.Company"] <span class="text-body-secondary">@T["Generic.Optional"]</span></label>
                            <input asp-for="Company" class="form-control" autocomplete="off" />
                        </div>
                        <div class="col-md-6">
                            <label asp-for="Tier" class="form-label">@T["Licensing.Issue.Form.Tier"] <span class="text-body-secondary">@T["Generic.Optional"]</span></label>
                            <select asp-for="Tier" class="form-select">
                                <option value="" data-sources-max="">@S.TierName(null)</option>
                                @foreach (var tier in LicenseContract.Tiers.All)
                                {
                                    <option value="@tier" data-sources-max="@LicenseContract.Presets.SourcesMax(tier)">@tier</option>
                                }
                            </select>
                            <div class="form-text">@T["Licensing.Issue.TierHelp"]</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header"><h6 class="card-title mb-0">@T["Licensing.Issue.Term"]</h6></div>
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="ValidFrom" class="form-label">@T["Licensing.Issue.Form.ValidFrom"] <span class="text-body-secondary">@T["Generic.Optional"]</span></label>
                            @* ISO, invariant: the value a date input takes whatever the language (#102). *@
                            <input type="date" id="ValidFrom" name="ValidFrom" value='@Model.ValidFrom?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)' class="form-control" />
                            <div class="form-text">@T["Licensing.Issue.ValidFromHelp"]</div>
                        </div>
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" asp-for="Term" id="TermDuration" value="@LicenceTermKind.Duration" />
                                <label class="form-check-label" for="TermDuration">@T["Licensing.Issue.Form.LastsFor"]</label>
                            </div>
                            <div class="ms-4 mt-2">
                                <div class="d-flex flex-wrap gap-2 mb-2" role="group" aria-label="@T["Licensing.Issue.CommonTerms"].Value">
                                    @foreach (var (amount, unit, label) in termPresets)
                                    {
                                        <button type="button" class="btn btn-sm btn-label-primary" data-term-amount="@amount" data-term-unit="@unit">@label</button>
                                    }
                                </div>
                                <div class="input-group term-length">
                                    <input asp-for="DurationAmount" type="number" min="1" step="1" class="form-control" aria-label="@T["Licensing.Issue.HowMany"].Value" />
                                    <select asp-for="DurationUnit" class="form-select" aria-label="@T["Licensing.Issue.Units"].Value">
                                        @foreach (var unit in Enum.GetValues<LicenceTermUnit>())
                                        {
                                            <option value="@unit">@T["Licensing.Issue.Unit." + unit]</option>
                                        }
                                    </select>
                                </div>
                                <div class="form-text">@T["Licensing.Issue.DurationHelp"]</div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" asp-for="Term" id="TermExpiration" value="@LicenceTermKind.Expiration" />
                                <label class="form-check-label" for="TermExpiration">@T["Licensing.Issue.ExpiresOn"]</label>
                            </div>
                            <div class="ms-4 mt-2 col-md-5">
                                <input type="date" id="Expiration" name="Expiration" value='@Model.Expiration?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)' class="form-control" aria-label="@T["Licensing.Issue.ExpiryDate"].Value" />
                                <div class="form-text">@T["Licensing.Issue.ExpiryHelp"]</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-5">
            <h6 class="mb-1">@T["Licensing.Issue.Grants.Title"]</h6>
            <p class="small text-body mb-3">@T["Licensing.Issue.Grants.Lead"]</p>

            <div class="accordion mb-4" id="entitlement">
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#section-reports"
                                aria-expanded="false" aria-controls="section-reports">
                            <span class="flex-grow-1">@T["Licensing.Section." + EntitlementSummary.Reports]</span>
                            <span class="small text-body-secondary me-2" data-summary="reports">@summary[EntitlementSummary.Reports]</span>
                        </button>
                    </h2>
                    <div id="section-reports" class="accordion-collapse collapse" data-section="reports">
                        <div class="accordion-body">
                            <partial name="_Switches" model='("Reports", "report", LicenseContract.Reports.All.Select(entry => (entry.Name, S.ReportName(entry), S.ReportDescription(entry))).ToList(), Model.Reports)' />
                        </div>
                    </div>
                </div>

                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#section-features"
                                aria-expanded="false" aria-controls="section-features">
                            <span class="flex-grow-1">@T["Licensing.Section." + EntitlementSummary.Features]</span>
                            <span class="small text-body-secondary me-2" data-summary="features">@summary[EntitlementSummary.Features]</span>
                        </button>
                    </h2>
                    <div id="section-features" class="accordion-collapse collapse" data-section="features">
                        <div class="accordion-body">
                            <partial name="_Switches" model='("Features", "feature", LicenseContract.Features.All.Select(entry => (entry.Name, S.FeatureName(entry), S.FeatureDescription(entry))).ToList(), Model.Features)' />
                        </div>
                    </div>
                </div>

                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#section-sources"
                                aria-expanded="false" aria-controls="section-sources">
                            <span class="flex-grow-1">@T["Licensing.Section." + EntitlementSummary.Connectors]</span>
                            <span class="small text-body-secondary me-2" data-summary="sources">@summary[EntitlementSummary.Connectors]</span>
                        </button>
                    </h2>
                    <div id="section-sources" class="accordion-collapse collapse" data-section="sources">
                        <div class="accordion-body">
                            <div class="d-flex gap-3 small mb-2">
                                <button type="button" class="btn btn-link p-0" data-select="Sources" data-select-value="true">@T["Licensing.Issue.AllOn"]</button>
                                <button type="button" class="btn btn-link p-0" data-select="Sources" data-select-value="false">@T["Licensing.Issue.AllOff"]</button>
                            </div>
                            <table class="table table-sm table-borderless align-middle mb-3">
                                <thead>
                                    <tr class="small text-body-secondary">
                                        <th scope="col" class="ps-0 fw-normal">@T["Licensing.Issue.Connector"]</th>
                                        <th scope="col" class="fw-normal">@T["Licensing.Issue.HowMany"]</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var source in LicenseContract.Sources.All)
                                    {
                                        var on = Model.Sources.Contains(source.Name);
                                        <tr>
                                            <td class="ps-0">
                                                <div class="form-check form-switch mb-0">
                                                    <input class="form-check-input" type="checkbox" name="Sources" value="@source.Name" id="source-@source.Name"
                                                           data-count="count-@source.Name" @(on ? "checked" : "") />
                                                    <label class="form-check-label" for="source-@source.Name">
                                                        @S.SourceName(source) <span class="small text-body-secondary">@S.SourceDescription(source)</span>
                                                    </label>
                                                </div>
                                            </td>
                                            <td class="source-count">
                                                @* The unit says what the count counts: sources, but repositories for GitHub (#168). *@
                                                <div class="input-group input-group-sm">
                                                    <input type="number" min="1" step="1" class="form-control" id="count-@source.Name"
                                                           name="SourceCounts[@source.Name]" value="@Model.Count(source.Name)?.ToString(System.Globalization.CultureInfo.InvariantCulture)" placeholder="@T["Licensing.Issue.NoLimitPlaceholder"].Value"
                                                           aria-label="@S["Licensing.Issue.HowManySources", S.SourceName(source), S.SourceUnit(source)].Value" @(on ? "" : "disabled") />
                                                    <span class="input-group-text" data-source-unit="@source.Name">@S.SourceUnit(source)</span>
                                                </div>
                                            </td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                            <partial name="_Limit" model='(LicenseContract.Limits.SourcesMax, "SourcesMax", Model.SourcesMax)' />
                        </div>
                    </div>
                </div>

                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#section-analysis"
                                aria-expanded="false" aria-controls="section-analysis">
                            <span class="flex-grow-1">@T["Licensing.Section." + EntitlementSummary.Analysis]</span>
                            <span class="small text-body-secondary me-2" data-summary="analysis">@summary[EntitlementSummary.Analysis]</span>
                        </button>
                    </h2>
                    <div id="section-analysis" class="accordion-collapse collapse" data-section="analysis">
                        <div class="accordion-body d-flex flex-column gap-3">
                            <partial name="_Limit" model='(LicenseContract.Limits.Employees, "AnalysisEmployees", Model.AnalysisEmployees)' />
                            <partial name="_Limit" model='(LicenseContract.Limits.Assets, "AnalysisAssets", Model.AnalysisAssets)' />
                            <partial name="_Limit" model='(LicenseContract.Limits.History, "AnalysisHistory", Model.AnalysisHistory)' />
                        </div>
                    </div>
                </div>

                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#section-ai"
                                aria-expanded="false" aria-controls="section-ai">
                            <span class="flex-grow-1">@T["Licensing.Section." + EntitlementSummary.Ai]</span>
                            <span class="small text-body-secondary me-2" data-summary="ai">@summary[EntitlementSummary.Ai]</span>
                        </button>
                    </h2>
                    <div id="section-ai" class="accordion-collapse collapse" data-section="ai">
                        <div class="accordion-body d-flex flex-column gap-3">
                            @foreach (var capability in LicenseContract.Ai.All)
                            {
                                <div class="form-check form-switch mb-0">
                                    <input class="form-check-input" type="checkbox" name="Ai" value="@capability.Name" id="ai-@capability.Name"
                                           @(Model.Ai.Contains(capability.Name) ? "checked" : "") />
                                    <label class="form-check-label" for="ai-@capability.Name">
                                        @S.AiName(capability)
                                        <span class="d-block small text-body-secondary">@S.AiDescription(capability)</span>
                                    </label>
                                </div>
                            }
                            <partial name="_Limit" model='(LicenseContract.Limits.AiTokens, "AiTokens", Model.AiTokens)' />
                            <div>
                                <label for="AiPeriod" class="form-label">@T["Licensing.Issue.AiPeriod"]</label>
                                <select id="AiPeriod" name="AiPeriod" class="form-select" data-limit>
                                    <option value="" selected="@(string.IsNullOrEmpty(Model.AiPeriod))">@S.AiPeriodName(null)</option>
                                    <option value="@LicenseContract.AiPeriods.Month" selected="@(Model.AiPeriod == LicenseContract.AiPeriods.Month)">@S.AiPeriodName(LicenseContract.AiPeriods.Month)</option>
                                    <option value="@LicenseContract.AiPeriods.Rolling30Days" selected="@(Model.AiPeriod == LicenseContract.AiPeriods.Rolling30Days)">@S.AiPeriodName(LicenseContract.AiPeriods.Rolling30Days)</option>
                                </select>
                            </div>
                            <partial name="_Limit" model='(LicenseContract.Limits.AiRequestsPerMinute, "AiRequestsPerMinute", Model.AiRequestsPerMinute)' />
                            <div class="form-text mt-0">@T["Licensing.Issue.AiHelp"]</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header"><h6 class="card-title mb-0">@T["Licensing.OtherAttributes"] <span class="text-body-secondary fw-normal">@T["Generic.Optional"]</span></h6></div>
                <div class="card-body">
                    <textarea asp-for="Attributes" class="form-control font-monospace" rows="4" placeholder="purchaseOrder=PO-1234" aria-label="@T["Licensing.OtherAttributes"].Value"></textarea>
                    <div class="form-text">@T["Licensing.Issue.AttributesHelp"]</div>
                </div>
            </div>

            <div class="card">
                <div class="card-body">
                    <label asp-for="IssuedBy" class="form-label"></label>
                    <input asp-for="IssuedBy" class="form-control" placeholder="@T["Licensing.Issue.YourName"].Value" />
                    <span asp-validation-for="IssuedBy" class="text-danger small"></span>
                    <div class="form-text mb-3">@T["Licensing.Issue.IssuedByHelp"]</div>
                    <button type="submit" class="btn btn-primary w-100" disabled="@(!mayIssue)">
                        <i class="ti ti-eye me-1"></i> @T["Licensing.Issue.Preview"]
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>
</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>
                    <dd class="col-sm-7"><code>@Model.IssuedByLogin</code></dd>

                    <dt class="col-sm-5">@T["Licensing.Register.Recorded"]</dt>
                    <dd class="col-sm-7">@Instant(Model.RecordedAtUtc)</dd>

                    <dt class="col-sm-5">SHA-256</dt>
                    <dd class="col-sm-7 mb-0"><code class="text-break">@Model.Sha256</code></dd>
                </dl>
            </div>
        </div>
    </div>

    <div class="col-12">
        @await Component.InvokeAsync(typeof(LicenceInstallationsViewComponent), new { licenceId = Model.LicenseId })
    </div>

    <div class="col-12">
        <div class="card">
            <div class="card-header"><h6 class="card-title mb-0">@T["Licensing.LicenceXml"]</h6></div>
            <div class="card-body">
                <pre class="mb-0"><code>@Model.LicenseXml</code></pre>
            </div>
        </div>
    </div>
</div>
</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)
                {
                    var expired = query.IsExpired(row);
                    <tr>
                        <td>
                            <a asp-action="Details" asp-route-id="@row.RecordId" class="fw-medium">@row.CustomerName</a>
                            @if (!row.IsCustomer)
                            {
                                <partial name="_Purpose" model="row.Purpose" />
                            }
                            <div class="small text-body">@row.CustomerEmail</div>
                            <code class="small">@row.LicenseId</code>
                        </td>
                        <td>@(row.Company ?? "-")</td>
                        <td>@(row.Tier ?? "-")</td>
                        <td>
                            @row.ExpirationUtc.ToString("yyyy-MM-dd")
                            @if (expired)
                            {
                                <span class="badge bg-label-secondary ms-1">@T["Licensing.Badge.Expired"]</span>
                            }
                        </td>
                        <td>@row.IssuedAtUtc.ToString("yyyy-MM-dd HH:mm") UTC</td>
                        <td>@row.IssuedBy</td>
                        <td class="text-end">
                            <a asp-action="Download" asp-route-id="@row.RecordId" class="btn btn-sm btn-icon btn-text-secondary"
                               title="@T["Licensing.Register.Download.Title"].Value" aria-label="@S["Licensing.Register.Download.For", row.CustomerName].Value">
                                <i class="ti ti-file-download"></i>
                            </a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

    @if (results.PageCount > 1)
    {
        <div class="card-footer d-flex justify-content-between align-items-center">
            <span class="text-body">@T["Generic.PageOf", results.Page, results.PageCount]</span>
            <div class="d-flex gap-2">
                @if (results.Page > 1)
                {
                    <a asp-action="Index" asp-all-route-data="@Model.RouteValues(results.Page - 1)" class="btn btn-sm btn-label-secondary">@T["Generic.Previous"]</a>
                }
                @if (results.Page < results.PageCount)
                {
                    <a asp-action="Index" asp-all-route-data="@Model.RouteValues(results.Page + 1)" class="btn btn-sm btn-label-secondary">@T["Generic.Next"]</a>
                }
            </div>
        </div>
    }
</div>
</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["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>
                                <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
                                {
                                    <td style="min-width: 13rem">
                                        @if (allowance.Tokens is { } tokens)
                                        {
                                            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", Instant(tokens.ResetAt)]</div>
                                        }
                                        else
                                        {
                                            <span class="small text-body-secondary">@T["Licensing.Installations.NotReported"]</span>
                                        }
                                    </td>
                                    <td class="small">@(AllowanceWords.Requests(allowance, S) ?? "-")</td>
                                }
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        }

        <div class="card-body @(Model.Answer.Installations.Count == 0 ? "pt-0" : "")">
            <p class="small text-body-secondary mb-0">@T["Licensing.Installations.Footnote"]</p>
        </div>
    }
</div>
</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">
                <div>
                    <span class="text-heading">@T["Licensing.Overview.Expired"]</span>
                    <h4 class="mb-1 mt-1">@stats.Expired</h4>
                    <small class="text-body">@T["Licensing.Overview.EveryFilePastExpiry"]</small>
                </div>
                <div class="avatar">
                    <span class="avatar-initial rounded bg-label-danger"><i class="ti ti-calendar-x ti-26px"></i></span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-8">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Licensing.Overview.IssuedPerMonth"]</h5>
                <p class="card-subtitle mb-0">@T["Licensing.Overview.IssuedPerMonth.Lead", RegisterStatistics.Months]</p>
            </div>
            <div class="card-body">
                <div id="licences-by-month" role="img"
                     aria-label="@S["Licensing.Overview.IssuedPerMonth.Aria", Count(stats.IssuedByMonth.Sum(month => month.New), "Licensing.Overview.NewLicences"), Count(stats.IssuedByMonth.Sum(month => month.Reissued), "Licensing.Overview.Reissues"), RegisterStatistics.Months].Value"></div>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Licensing.Overview.TiersInForce"]</h5>
                <p class="card-subtitle mb-0">@T["Licensing.Overview.TiersInForce.Lead"]</p>
            </div>
            <div class="card-body">
                @if (stats.Active == 0)
                {
                    <p class="text-body mb-0">@T["Licensing.Overview.NoTiers"]</p>
                }
                else
                {
                    <div id="licences-by-tier" role="img"
                         aria-label="@string.Join(", ", stats.ActiveByTier.Select(tier => $"{S.TierName(tier.Label == RegisterStatistics.NoTier ? null : tier.Label)}: {tier.Count}"))"></div>
                }
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Licensing.Overview.ExpiringWithinMonth"]</h5>
                <p class="card-subtitle mb-0">@T["Licensing.Overview.Expiring.Lead", stats.ExpiringByUtc.ToString("yyyy-MM-dd")]</p>
            </div>
            @if (stats.Expiring.Count == 0)
            {
                <div class="card-body">
                    <p class="text-body mb-0">@T["Licensing.Overview.NothingExpires", stats.ExpiringByUtc.ToString("yyyy-MM-dd")]</p>
                </div>
            }
            else
            {
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>@T["Licensing.Column.Customer"]</th>
                                <th class="d-none d-md-table-cell">@T["Licensing.Tier"]</th>
                                <th>@T["Licensing.Column.Expires"]</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var licence in stats.Expiring)
                            {
                                var row = licence.Current;
                                <tr>
                                    <td>
                                        <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<span class="d-md-none">@(row.Company is null ? "" : " · ")@(row.Tier ?? S.TierName(null).ToLowerInvariant())</span>
                                        </div>
                                    </td>
                                    <td class="d-none d-md-table-cell">@(row.Tier ?? "-")</td>
                                    <td class="text-nowrap">
                                        @licence.CoveredUntilUtc.ToString("yyyy-MM-dd")
                                        <div class="small text-body">@DaysLeft(licence.CoveredUntilUtc)</div>
                                    </td>
                                    <td class="text-end text-nowrap">
                                        <a asp-area="Licensing" asp-controller="Issue" asp-action="Index" asp-route-from="@row.RecordId"
                                           class="btn btn-sm btn-label-primary" aria-label="@S["Licensing.Overview.ReissueFor", row.CustomerName].Value">
                                            <i class="ti ti-refresh"></i><span class="d-none d-sm-inline ms-1">@T["Licensing.Reissue"]</span>
                                        </a>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }
        </div>
    </div>

    <div class="col-xl-6">
        <div class="card h-100">
            <div class="card-header d-flex justify-content-between align-items-start gap-3">
                <div>
                    <h5 class="card-title mb-1">@T["Licensing.Overview.RecentlyIssued"]</h5>
                    <p class="card-subtitle mb-0">@T["Licensing.Overview.RecentlyIssued.Lead", RegisterStatistics.RecentCount]</p>
                </div>
                <a asp-area="Licensing" asp-controller="Register" asp-action="Index" class="btn btn-sm btn-label-secondary">@T["Licensing.Overview.RegisterLink"]</a>
            </div>
            @if (stats.RecentlyIssued.Count == 0)
            {
                <div class="card-body">
                    <p class="text-body mb-3">@T["Licensing.Register.Empty"]</p>
                    <a asp-area="Licensing" asp-controller="Issue" asp-action="Index" class="btn btn-primary">
                        <i class="ti ti-file-plus me-1"></i> @T["Menu.Licensing.Issue"]
                    </a>
                </div>
            }
            else
            {
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>@T["Licensing.Column.Customer"]</th>
                                <th class="d-none d-md-table-cell">@T["Licensing.Tier"]</th>
                                <th>@T["Licensing.Column.Issued"]</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var issue in stats.RecentlyIssued)
                            {
                                var row = issue.Row;
                                <tr>
                                    <td>
                                        <a asp-area="Licensing" asp-controller="Register" asp-action="Details" asp-route-id="@row.RecordId" class="fw-medium">@row.CustomerName</a>
                                        @if (issue.IsReissue)
                                        {
                                            <span class="badge bg-label-info ms-1">@T["Licensing.Badge.Reissue"]</span>
                                        }
                                        <div class="small text-body">@T["Licensing.Overview.By", row.IssuedBy]<span class="d-md-none"> · @(row.Tier ?? S.TierName(null).ToLowerInvariant())</span></div>
                                    </td>
                                    <td class="d-none d-md-table-cell">@(row.Tier ?? "-")</td>
                                    <td class="text-nowrap">@row.IssuedAtUtc.ToString("yyyy-MM-dd")</td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }
        </div>
    </div>
</div>

@* A licence covers one installation (#47); the gateway watches for one on more (#58). *@
<div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-1">@T["Licensing.Overview.Shared.Title"]</h5>
                <p class="card-subtitle mb-0">@T["Licensing.Overview.Shared.Lead"]</p>
            </div>
            @if (Model.Gateway.Outcome != GatewayOutcome.Answered)
            {
                <div class="card-body">
                    <partial name="~/Areas/Licensing/Views/Shared/_GatewayUnavailable.cshtml" model="Model.Gateway" />
                </div>
            }
            else if (Model.Shared.Count == 0)
            {
                <div class="card-body">
                    <p class="text-body mb-0">@T["Licensing.Overview.Shared.None"]</p>
                </div>
            }
            else
            {
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>@T["Licensing.Column.Customer"]</th>
                                <th class="d-none d-md-table-cell">@T["Licensing.LicenceId"]</th>
                                <th class="text-end">@T["Licensing.Installations"]</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var licence in Model.Shared)
                            {
                                <tr>
                                    <td>
                                        @if (licence.Row is { } 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>
                                        }
                                        else
                                        {
                                            <span class="badge bg-label-warning">@T["Licensing.Overview.Shared.NotInRegister"]</span>
                                            <div class="small text-body">@T["Licensing.Overview.Shared.NotInRegister.Detail"]</div>
                                        }
                                        <code class="small d-md-none">@licence.LicenceId</code>
                                    </td>
                                    <td class="d-none d-md-table-cell"><code>@licence.LicenceId</code></td>
                                    <td class="text-end">@licence.Holding</td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
                <div class="card-body pt-3">
                    <p class="small text-body-secondary mb-0">@T["Licensing.Overview.Shared.Remedy"]</p>
                </div>
            }
        </div>
    </div>
</div>

@*
    The charts' numbers, as the server counted them; wwwroot/js/licensing-overview.js only draws
    them. The chart library is loaded here rather than by the overview page, which does not know
    what licensing draws, through _ApexCharts, once a page, since the CRM's section draws a chart too
    (#158). Deferred scripts run in order once the page is parsed.
*@
<script type="application/json" id="licensing-overview-data">@Json.Serialize(new
{
    months = stats.IssuedByMonth.Select(month => month.Month.ToString("MMMM yyyy", culture)),
    monthLabels = stats.IssuedByMonth.Select((month, i) => i == 0 || month.Month.Month == 1
        ? new[] { month.Month.ToString("MMM", culture), month.Month.ToString("yyyy", CultureInfo.InvariantCulture) }
        : new[] { month.Month.ToString("MMM", culture) }),
    issuedNew = stats.IssuedByMonth.Select(month => month.New),
    issuedReissued = stats.IssuedByMonth.Select(month => month.Reissued),
    tiers = stats.ActiveByTier.Select(tier => S.TierName(tier.Label == RegisterStatistics.NoTier ? null : tier.Label)),
    tierCounts = stats.ActiveByTier.Select(tier => tier.Count),
    tierColours = stats.ActiveByTier.Select(tier => TierColour(tier.Label)),
    active = stats.Active,
})</script>
<partial name="~/Views/Shared/_ApexCharts.cshtml" />
<script src="~/js/licensing-overview.js" asp-append-version="true" defer></script>
</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>

                        <dt class="col-sm-4">@T["Licensing.Purpose"]</dt>
                        <dd class="col-sm-8">@if (contract.Loaded) { <partial name="_Purpose" model="contract.Purpose" /> } else { <span>-</span> }</dd>

                        <dt class="col-sm-4">@T["Licensing.Tier"]</dt>
                        <dd class="col-sm-8">@(contract.Tier ?? "-")</dd>

                        <dt class="col-sm-4">@T["Licensing.Column.Company"]</dt>
                        <dd class="col-sm-8">@(contract.Company ?? "-")</dd>

                        <dt class="col-sm-4">@T["Licensing.ValidFrom"]</dt>
                        <dd class="col-sm-8">
                            @(contract.ValidFromUtc is null ? "-" : Instant(contract.ValidFromUtc))
                            @if (contract.Loaded && !contract.InForce && contract.SignatureValid && !contract.Expired)
                            {
                                <span class="badge bg-label-warning ms-1">@T["Licensing.Badge.NotYetInForce"]</span>
                            }
                        </dd>

                        <dt class="col-sm-4">@T["Licensing.Column.Expires"]</dt>
                        <dd class="col-sm-8">
                            @Instant(contract.ExpirationUtc)
                            @if (contract.Expired)
                            {
                                <span class="badge bg-label-danger ms-1">@T["Licensing.Badge.Expired"]</span>
                            }
                        </dd>

                        @if (contract.Loaded)
                        {
                            <partial name="_Entitlement" model="(EntitlementSummary.Describe(contract.Entitlements, S), 4)" />
                        }

                        @if (contract.Entitlements.IgnoredNames.Count > 0)
                        {
                            <dt class="col-sm-4">@T["Licensing.Validate.NamesNotKnown"]</dt>
                            <dd class="col-sm-8">
                                @string.Join(", ", contract.Entitlements.IgnoredNames)
                                <div class="small text-body">@T["Licensing.Validate.NamesNotKnown.Detail"]</div>
                            </dd>
                        }

                        @if (contract.ProductFeatures.Count > 0)
                        {
                            <dt class="col-sm-4">@T["Licensing.AreaKeys"]</dt>
                            <dd class="col-sm-8">
                                @foreach (var feature in contract.ProductFeatures.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.Validate.AreaKeys.Detail", LicenceValidator.ProductCommit]</div>
                            </dd>
                        }

                        <dt class="col-sm-4">@T["Licensing.Validate.UnknownAttributes"]</dt>
                        <dd class="col-sm-8">
                            @(contract.UnknownAttributes.Count == 0 ? "-" : string.Join(", ", contract.UnknownAttributes))
                            @if (contract.UnknownAttributes.Count > 0)
                            {
                                <div class="small text-body">@T["Licensing.Validate.UnknownAttributes.Detail"]</div>
                            }
                        </dd>

                        <dt class="col-sm-4">@T["Licensing.Validate.Register"]</dt>
                        <dd class="col-sm-8 mb-0">
                            @if (Model.RegisterRecord is { } row)
                            {
                                <a asp-controller="Register" asp-action="Details" asp-route-id="@row.RecordId">@T["Licensing.Validate.Register.ThisFile"]</a>
                                <span>@T["Licensing.Validate.Register.IssuedBy", row.IssuedAtUtc.ToString("yyyy-MM-dd"), row.IssuedBy]</span>
                            }
                            else if (Model.RegisterAvailability == RegisterAvailability.Unavailable)
                            {
                                <span>@T["Licensing.Validate.Register.NotChecked"]</span>
                            }
                            else if (Model.RegisterRowsWithSameId > 0)
                            {
                                <span>@T["Licensing.Validate.Register.NotThisFile"] </span>
                                <a asp-controller="Register" asp-action="Index" asp-route-q="@Model.LicenseId">
                                    @(Model.RegisterRowsWithSameId == 1 ? T["Licensing.Validate.Register.SameId.One"] : T["Licensing.Validate.Register.SameId.Many", Model.RegisterRowsWithSameId])
                                </a>
                                <span> @T["Licensing.Validate.Register.SameId.Detail"]</span>
                            }
                            else
                            {
                                <span>@T["Licensing.Validate.Register.NotInRegister"]</span>
                            }
                        </dd>
                    </dl>
                </div>
            </div>

            <div class="row g-4 mb-4">
                <div class="col-md-6">
                    <div class="card h-100">
                        <div class="card-header">
                            <h6 class="card-title mb-1">@T["Licensing.Validate.Product.Title"]</h6>
                            <p class="small text-body mb-0">@T["Licensing.Validate.Product.Lead"]</p>
                        </div>
                        <div class="card-body">
                            <partial name="_Verdict" model='(S["Licensing.Validate.Today"].Value, productToday, report.ProductToday)' />
                            <hr />
                            <partial name="_Verdict" model='(S["Licensing.Validate.PerContract"].Value, "docs/License-Contract.md", report.ProductPerContract)' />
                            @if (report.ProductToday.Accepts != report.ProductPerContract.Accepts || report.ProductToday.Reason != report.ProductPerContract.Reason)
                            {
                                <p class="small text-body mt-3 mb-0">@T["Licensing.Validate.Product.Differ"]</p>
                            }
                            @if (contract.Reason == LicenseContract.Reasons.NotYetValid)
                            {
                                <p class="small text-body mt-3 mb-0">@T["Licensing.Validate.Product.Release", LicenceValidator.ProductRelease, Html.Raw($"<code>{LicenceValidator.ProductReleaseCommit}</code>")]</p>
                            }
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card h-100">
                        <div class="card-header">
                            <h6 class="card-title mb-1">@T["Licensing.Validate.Gateway.Title"]</h6>
                            <p class="small text-body mb-0">@T["Licensing.Validate.Gateway.Lead"]</p>
                        </div>
                        <div class="card-body">
                            <partial name="_GatewayVerdict" model='(S["Licensing.Validate.Today"].Value, gatewayToday, report.GatewayToday)' />
                            <hr />
                            <partial name="_GatewayVerdict" model='(S["Licensing.Validate.PerContract"].Value, "docs/License-Contract.md", report.GatewayPerContract)' />
                            @if (report.GatewayToday.Reason != report.GatewayPerContract.Reason)
                            {
                                <p class="small text-body mt-3 mb-0">@T["Licensing.Validate.Gateway.Words"]</p>
                            }
                            @if (contract.Reason == LicenseContract.Reasons.NotYetValid)
                            {
                                <p class="small text-body mt-3 mb-0">@T["Licensing.Validate.Gateway.NotYetValid", LicenceValidator.ProductRelease]</p>
                            }
                            @if (report.GatewayToday.Allowance is not null && contract.AiTier == LicenseContract.Tiers.Enterprise)
                            {
                                <p class="small text-body mt-3 mb-0">@T["Licensing.Validate.Gateway.EnterpriseBeforeTier"]</p>
                            }
                            <p class="small text-body mt-3 mb-0">@T["Licensing.Validate.Gateway.WhenSent", Html.Raw($"<code>{LicenceValidator.ProductCommit}</code>"), LicenceValidator.ProductRelease]</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header"><h6 class="card-title mb-0">@T["Licensing.LicenceXml"]</h6></div>
                <div class="card-body">
                    <pre class="mb-0"><code>@Model.LicenseXml</code></pre>
                </div>
            </div>
        }
    </div>
</div>
</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/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/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);
⋮----
!string.IsNullOrWhiteSpace(ApiKey) && !string.IsNullOrWhiteSpace(Model) && BaseAddress is not null;
⋮----
if (string.IsNullOrWhiteSpace(BaseUrl)
|| !Uri.TryCreate(BaseUrl.Trim().TrimEnd('/') + "/", UriKind.Absolute, out var address))
</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(HttpClient http, IOptions<BusinessCardOptions> options, ILogger<OllamaBusinessCardReader> logger)
: IBusinessCardReader
⋮----
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(settings.BaseAddress!, ChatPath))
⋮----
Content = new StringContent(Body(settings.Model!.Trim(), image, qrCode).ToJsonString(), Encoding.UTF8, "application/json"),
⋮----
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", settings.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 JsonObject { ["role"] = "system", ["content"] = Instructions },
new JsonObject
⋮----
["images"] = new JsonArray(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));
⋮----
.RedactLoggedHeaders(["Authorization"]);
⋮----
http.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; KnowledgeFabricAdmin/1.0; +business card)");
⋮----
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
⋮----
ConnectTimeout = TimeSpan.FromSeconds(5),
⋮----
ActivityHeadersPropagator = DistributedContextPropagator.CreateNoOutputPropagator(),
⋮----
.RemoveAllLoggers();
</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/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);
⋮----
private void RecordWithPartner(Guid contactId, ContactChangeKind kind, bool live, string by, DateTimeOffset at)
⋮----
foreach (var introduction in _introductions.Values.Where(row => row.ContactId == contactId && row.DeletedAt is null).OrderBy(row => row.CreatedAt))
⋮----
Record(IntroductionChange.Of(introduction, kind, live, by, at));
⋮----
public Task<IReadOnlySet<string>> SharedNamesAsync(CancellationToken cancellationToken = default)
⋮----
.GroupBy(row => Contact.NormaliseName(row.Name), StringComparer.Ordinal)
.Where(group => group.Count() > 1)
.Select(group => group.Key)
.ToHashSet(StringComparer.Ordinal));
⋮----
public Task<IReadOnlyList<Interaction>> InteractionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default)
⋮----
var wanted = contactIds.Where(id => LiveRow(id) is not null).ToHashSet();
⋮----
.Where(interaction => wanted.Contains(interaction.ContactId))
.OrderBy(interaction => interaction.OccurredOn)
.ThenBy(interaction => interaction.RecordedAt)
.Select(interaction => interaction.Copy())
⋮----
public Task<IReadOnlyList<InteractionSummary>> InteractionSummariesAsync(DateOnly from, CancellationToken cancellationToken = default)
⋮----
.Where(interaction => interaction.OccurredOn >= from && LiveRow(interaction.ContactId) is not null)
.Select(InteractionSummary.Of)
⋮----
public Task<InteractionSave> AddInteractionAsync(Interaction interaction, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(InteractionSave.NotFound);
⋮----
return Task.FromResult(InteractionSave.Saved(stored.Copy()));
⋮----
public Task<InteractionSave> SaveInteractionAsync(
⋮----
if (!_interactions.TryGetValue(id, out var row) || row.ContactId != contactId || LiveRow(contactId) is null)
⋮----
return Task.FromResult(InteractionSave.Stale(row.Copy()));
⋮----
return Task.FromResult(InteractionSave.Saved(changed.Copy()));
⋮----
public Task<InteractionSave> DeleteInteractionAsync(Guid contactId, Guid id, uint version, CancellationToken cancellationToken = default)
⋮----
_interactions.Remove(id);
return Task.FromResult(InteractionSave.Saved(row.Copy()));
⋮----
private IEnumerable<Introduction> LiveIntroductions => _introductions.Values.Where(row => row.DeletedAt is null && LiveRow(row.ContactId) is not null);
⋮----
public Task<IReadOnlyList<Introduction>> IntroductionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default)
⋮----
var wanted = contactIds.ToHashSet();
⋮----
.Where(introduction => wanted.Contains(introduction.ContactId))
.OrderBy(introduction => introduction.IntroducedOn)
.ThenBy(introduction => introduction.CreatedAt)
.Select(introduction => introduction.Copy())
⋮----
public Task<IReadOnlyList<IntroductionSummary>> IntroductionSummariesAsync(CancellationToken cancellationToken = default)
⋮----
return Task.FromResult<IReadOnlyList<IntroductionSummary>>(LiveIntroductions.Select(IntroductionSummary.Of).ToList());
⋮----
public Task<IntroductionSave> AddIntroductionAsync(Introduction introduction, CancellationToken cancellationToken = default)
⋮----
return Task.FromResult(IntroductionSave.NotFound);
⋮----
var stored = introduction.Copy();
⋮----
Record(IntroductionChange.Of(stored, ContactChangeKind.Created, live: true, stored.CreatedBy, stored.CreatedAt));
return Task.FromResult(IntroductionSave.Saved(stored.Copy()));
⋮----
public Task<IntroductionSave> SaveIntroductionAsync(
⋮----
if (!_introductions.TryGetValue(id, out var row) || row.ContactId != contactId || row.DeletedAt is not null || LiveRow(contactId) is null)
⋮----
return Task.FromResult(IntroductionSave.Stale(row.Copy()));
⋮----
Record(IntroductionChange.Of(changed, ContactChangeKind.Updated, live: true, by, at));
⋮----
return Task.FromResult(IntroductionSave.Saved(changed.Copy()));
⋮----
public Task<IReadOnlyList<IntroductionChange>> IntroductionChangesAsync(CancellationToken cancellationToken = default)
⋮----
public sealed class UnconfiguredContactRegister : IContactRegister
⋮----
public Task<IReadOnlyList<Contact>> SearchAsync(ContactQuery query, CancellationToken cancellationToken = default) =>
⋮----
public Task<Contact?> FindAsync(Guid id, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<Contact>> FollowUpsAsync(FollowUpQuery query, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<ContactSummary>> SummariesAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<Contact> AddAsync(Contact contact, CancellationToken cancellationToken = default) =>
throw new ContactRegisterUnavailableException();
⋮----
public Task<ContactSave> SaveAsync(Guid id, uint version, Action<Contact> change, string by, DateTimeOffset at, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<string>> ImportAsync(IReadOnlyList<Contact> contacts, IReadOnlyList<Interaction> interactions, CancellationToken cancellationToken = default) =>
⋮----
public Task<bool> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<Contact>> DeletedAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<Contact?> RestoreAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<ContactChange>> ChangesAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlySet<string>> SharedNamesAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<Interaction>> InteractionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<InteractionSummary>> InteractionSummariesAsync(DateOnly from, CancellationToken cancellationToken = default) =>
⋮----
public Task<InteractionSave> AddInteractionAsync(Interaction interaction, CancellationToken cancellationToken = default) =>
⋮----
public Task<InteractionSave> DeleteInteractionAsync(Guid contactId, Guid id, uint version, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<Introduction>> IntroductionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<IntroductionSummary>> IntroductionSummariesAsync(CancellationToken cancellationToken = default) =>
⋮----
public Task<IntroductionSave> AddIntroductionAsync(Introduction introduction, CancellationToken cancellationToken = default) =>
⋮----
public Task<IReadOnlyList<IntroductionChange>> IntroductionChangesAsync(CancellationToken cancellationToken = default) =>
</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)
⋮----
said.Append(label).Append(": ").Append(value).Append('\n');
⋮----
private static string? Attribute(string tag, string name)
⋮----
foreach (Match attribute in Attributes().Matches(tag))
⋮----
if (attribute.Groups[1].Value.Equals(name, StringComparison.OrdinalIgnoreCase))
⋮----
private static string Decode(string text) => WebUtility.HtmlDecode(text);
⋮----
private static string OneLine(string text) => Whitespace().Replace(text, " ").Trim();
⋮----
private static string Lines(string text)
⋮----
foreach (var line in text.Split('\n'))
⋮----
lines.Add(one);
⋮----
return string.Join("\n", lines);
⋮----
private static partial Regex Title();
⋮----
private static partial Regex Meta();
⋮----
private static partial Regex Attributes();
⋮----
private static partial Regex StructuredData();
⋮----
private static partial Regex Links();
⋮----
private static partial Regex Hidden();
⋮----
private static partial Regex Breaks();
⋮----
private static partial Regex Tags();
⋮----
private static partial Regex Whitespace();
</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);
⋮----
.Where(c => ids.Contains(c.Id) || (c.DeletedAt == null && names.Contains(c.Name.Trim().ToLower())))
.Select(c => new { c.Id, c.Name, Deleted = c.DeletedAt != null })
⋮----
var heldIds = held.Select(row => row.Id).ToHashSet();
var heldNames = held.Where(row => !row.Deleted).Select(row => Contact.NormaliseName(row.Name)).ToHashSet(StringComparer.Ordinal);
⋮----
.Where(contact => heldIds.Contains(contact.Id) || heldNames.Contains(Contact.NormaliseName(contact.Name)))
.Select(contact => contact.Name)
.ToList();
⋮----
db.Contacts.AddRange(contacts);
db.Interactions.AddRange(interactions);
db.ContactChanges.AddRange(contacts.Select(contact =>
ContactChange.Of(contact, ContactChangeKind.Imported, contact.CreatedBy, contact.CreatedAt)));
⋮----
await transaction.CommitAsync(cancellationToken);
⋮----
public async Task<bool> DeleteAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default) =>
⋮----
Live.Where(c => c.Id == id),
set => set.SetProperty(c => c.DeletedBy, by).SetProperty(c => c.DeletedAt, at),
⋮----
public async Task<IReadOnlyList<Contact>> DeletedAsync(CancellationToken cancellationToken = default) =>
await db.Contacts.AsNoTracking()
.Where(c => c.DeletedAt != null)
.OrderByDescending(c => c.DeletedAt)
⋮----
public Task<Contact?> RestoreAsync(Guid id, string by, DateTimeOffset at, CancellationToken cancellationToken = default) =>
⋮----
db.Contacts.Where(c => c.Id == id && c.DeletedAt != null),
set => set.SetProperty(c => c.DeletedBy, (string?)null).SetProperty(c => c.DeletedAt, (DateTimeOffset?)null),
⋮----
public async Task<IReadOnlyList<ContactChange>> ChangesAsync(CancellationToken cancellationToken = default) =>
await db.ContactChanges.AsNoTracking()
.OrderBy(c => c.Id)
⋮----
private Task<Contact?> MarkAsync(
⋮----
db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
⋮----
if (await target.ExecuteUpdateAsync(marks, cancellationToken) == 0)
⋮----
var contact = await db.Contacts.AsNoTracking().SingleAsync(c => c.Id == id, cancellationToken);
db.ContactChanges.Add(ContactChange.Of(contact, kind, by, at));
⋮----
var introductions = await db.Introductions.AsNoTracking()
.Where(i => i.ContactId == id && i.DeletedAt == null)
.OrderBy(i => i.CreatedAt)
⋮----
db.IntroductionChanges.AddRange(introductions.Select(introduction =>
IntroductionChange.Of(introduction, kind, live: kind == ContactChangeKind.Restored, by, at)));
⋮----
private void Forget(ContactChange? change)
⋮----
db.Entry(change).State = EntityState.Detached;
⋮----
public async Task<IReadOnlySet<string>> SharedNamesAsync(CancellationToken cancellationToken = default)
⋮----
var names = await Live.AsNoTracking()
.GroupBy(c => c.Name.ToLower())
.Where(group => group.Count() > 1)
.Select(group => group.Key)
⋮----
return names.Select(Contact.NormaliseName).ToHashSet(StringComparer.Ordinal);
⋮----
public async Task<IReadOnlyList<Interaction>> InteractionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default)
⋮----
var ids = contactIds.ToArray();
⋮----
return await LiveInteractions.AsNoTracking()
.Where(i => ids.Contains(i.ContactId))
.OrderBy(i => i.OccurredOn)
.ThenBy(i => i.RecordedAt)
⋮----
public async Task<IReadOnlyList<InteractionSummary>> InteractionSummariesAsync(DateOnly from, CancellationToken cancellationToken = default) =>
⋮----
.Where(i => i.OccurredOn >= from)
.Select(i => new InteractionSummary(i.OccurredOn, i.Kind))
⋮----
public async Task<InteractionSave> AddInteractionAsync(Interaction interaction, CancellationToken cancellationToken = default)
⋮----
if (!await Live.AnyAsync(c => c.Id == interaction.ContactId, cancellationToken))
⋮----
db.Interactions.Add(interaction);
⋮----
db.Entry(interaction).State = EntityState.Detached;
⋮----
return InteractionSave.Saved(interaction);
⋮----
public async Task<InteractionSave> SaveInteractionAsync(
⋮----
var row = await LiveInteractions.SingleOrDefaultAsync(i => i.Id == id && i.ContactId == contactId, cancellationToken);
⋮----
return InteractionSave.Stale(row);
⋮----
return InteractionSave.Saved(row);
⋮----
public async Task<InteractionSave> DeleteInteractionAsync(Guid contactId, Guid id, uint version, CancellationToken cancellationToken = default)
⋮----
db.Interactions.Remove(row);
⋮----
private async Task<InteractionSave> CurrentAsync(Guid contactId, Guid id, CancellationToken cancellationToken)
⋮----
var current = await LiveInteractions.AsNoTracking().SingleOrDefaultAsync(i => i.Id == id && i.ContactId == contactId, cancellationToken);
return current is null ? InteractionSave.NotFound : InteractionSave.Stale(current);
⋮----
public async Task<IReadOnlyList<Introduction>> IntroductionsAsync(IReadOnlyCollection<Guid> contactIds, CancellationToken cancellationToken = default)
⋮----
return await LiveIntroductions.AsNoTracking()
⋮----
.OrderBy(i => i.IntroducedOn)
.ThenBy(i => i.CreatedAt)
⋮----
public async Task<IReadOnlyList<IntroductionSummary>> IntroductionSummariesAsync(CancellationToken cancellationToken = default) =>
⋮----
.Select(i => new IntroductionSummary(i.Id, i.ContactId, i.Stage))
⋮----
public async Task<IntroductionSave> AddIntroductionAsync(Introduction introduction, CancellationToken cancellationToken = default)
⋮----
if (!await Live.AnyAsync(c => c.Id == introduction.ContactId, cancellationToken))
⋮----
var created = IntroductionChange.Of(introduction, ContactChangeKind.Created, live: true, introduction.CreatedBy, introduction.CreatedAt);
db.Introductions.Add(introduction);
db.IntroductionChanges.Add(created);
⋮----
db.Entry(introduction).State = EntityState.Detached;
db.Entry(created).State = EntityState.Detached;
⋮----
return IntroductionSave.Saved(introduction);
⋮----
public async Task<IntroductionSave> SaveIntroductionAsync(
⋮----
var row = await LiveIntroductions.SingleOrDefaultAsync(i => i.Id == id && i.ContactId == contactId, cancellationToken);
⋮----
return IntroductionSave.Stale(row);
⋮----
var updated = row.Stage == before ? null : IntroductionChange.Of(row, ContactChangeKind.Updated, live: true, by, at);
⋮----
db.IntroductionChanges.Add(updated);
⋮----
var current = await LiveIntroductions.AsNoTracking().SingleOrDefaultAsync(i => i.Id == id && i.ContactId == contactId, cancellationToken);
return current is null ? IntroductionSave.NotFound : IntroductionSave.Stale(current);
⋮----
db.Entry(updated).State = EntityState.Detached;
⋮----
return IntroductionSave.Saved(row);
⋮----
public async Task<IReadOnlyList<IntroductionChange>> IntroductionChangesAsync(CancellationToken cancellationToken = default) =>
await db.IntroductionChanges.AsNoTracking()
</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");
⋮----
contact.Property(c => c.Version)
.HasColumnName("xmin")
.HasColumnType("xid")
.ValueGeneratedOnAddOrUpdate()
.IsConcurrencyToken();
⋮----
contact.HasIndex(c => c.Name).HasDatabaseName("ix_crm_contacts_name");
⋮----
interaction.ToTable("crm_interactions");
interaction.HasKey(i => i.Id);
⋮----
interaction.Property(i => i.Id).HasColumnName("id");
interaction.Property(i => i.ContactId).HasColumnName("contact_id");
interaction.Property(i => i.OccurredOn).HasColumnName("occurred_on");
⋮----
interaction.Property(i => i.Kind).HasColumnName("kind").HasConversion<string>().HasMaxLength(32);
⋮----
interaction.Property(i => i.Participants).HasColumnName("participants");
⋮----
interaction.Property(i => i.Summary).HasColumnName("summary");
interaction.Property(i => i.RecordedBy).HasColumnName("recorded_by").HasMaxLength(Contact.PersonLength);
interaction.Property(i => i.RecordedAt).HasColumnName("recorded_at");
interaction.Property(i => i.UpdatedBy).HasColumnName("updated_by").HasMaxLength(Contact.PersonLength);
interaction.Property(i => i.UpdatedAt).HasColumnName("updated_at");
⋮----
interaction.Property(i => i.Version)
⋮----
.WithMany()
.HasForeignKey(i => i.ContactId)
.HasConstraintName("fk_crm_interactions_contact")
.OnDelete(DeleteBehavior.Cascade);
⋮----
interaction.HasIndex(i => new { i.ContactId, i.OccurredOn }).HasDatabaseName("ix_crm_interactions_contact_occurred_on");
⋮----
change.ToTable("crm_contact_changes");
change.HasKey(c => c.Id);
⋮----
change.Property(c => c.Id).HasColumnName("id").UseIdentityAlwaysColumn();
change.Property(c => c.ContactId).HasColumnName("contact_id");
change.Property(c => c.ChangedAt).HasColumnName("changed_at");
⋮----
change.Property(c => c.Kind).HasColumnName("kind").HasConversion<string>().HasMaxLength(32);
change.Property(c => c.Stage).HasColumnName("stage").HasConversion<string>().HasMaxLength(32);
change.Property(c => c.Track).HasColumnName("track").HasConversion<string>().HasMaxLength(32);
change.Property(c => c.DeclineReason).HasColumnName("decline_reason").HasConversion<string>().HasMaxLength(32);
change.Property(c => c.Entity).HasColumnName("entity").HasConversion<string>().HasMaxLength(32);
⋮----
change.Property(c => c.Live).HasColumnName("live");
change.Property(c => c.ChangedBy).HasColumnName("changed_by").HasMaxLength(Contact.PersonLength);
⋮----
.HasForeignKey(c => c.ContactId)
.HasConstraintName("fk_crm_contact_changes_contact")
⋮----
change.HasIndex(c => new { c.ContactId, c.ChangedAt }).HasDatabaseName("ix_crm_contact_changes_contact_changed_at");
⋮----
introduction.ToTable("crm_introductions");
introduction.HasKey(i => i.Id);
⋮----
introduction.Property(i => i.Id).HasColumnName("id");
introduction.Property(i => i.ContactId).HasColumnName("contact_id");
introduction.Property(i => i.Customer).HasColumnName("customer").HasMaxLength(Introduction.CustomerLength);
introduction.Property(i => i.IntroducedOn).HasColumnName("introduced_on");
⋮----
introduction.Property(i => i.Stage).HasColumnName("stage").HasConversion<string>().HasMaxLength(32);
⋮----
introduction.Property(i => i.ContactPerson).HasColumnName("contact_person").HasMaxLength(Introduction.ContactPersonLength);
introduction.Property(i => i.Email).HasColumnName("email").HasMaxLength(Introduction.EmailLength);
introduction.Property(i => i.Phone).HasColumnName("phone").HasMaxLength(Introduction.PhoneLength);
introduction.Property(i => i.Notes).HasColumnName("notes");
introduction.Property(i => i.CreatedBy).HasColumnName("created_by").HasMaxLength(Contact.PersonLength);
introduction.Property(i => i.CreatedAt).HasColumnName("created_at");
introduction.Property(i => i.UpdatedBy).HasColumnName("updated_by").HasMaxLength(Contact.PersonLength);
introduction.Property(i => i.UpdatedAt).HasColumnName("updated_at");
⋮----
introduction.Property(i => i.DeletedBy).HasColumnName("deleted_by").HasMaxLength(Contact.PersonLength);
introduction.Property(i => i.DeletedAt).HasColumnName("deleted_at");
⋮----
introduction.Property(i => i.Version)
⋮----
.HasConstraintName("fk_crm_introductions_contact")
⋮----
introduction.HasIndex(i => i.ContactId).HasDatabaseName("ix_crm_introductions_contact");
⋮----
introductionChange.ToTable("crm_introduction_changes");
introductionChange.HasKey(c => c.Id);
⋮----
introductionChange.Property(c => c.Id).HasColumnName("id").UseIdentityAlwaysColumn();
introductionChange.Property(c => c.IntroductionId).HasColumnName("introduction_id");
introductionChange.Property(c => c.ContactId).HasColumnName("contact_id");
introductionChange.Property(c => c.ChangedAt).HasColumnName("changed_at");
introductionChange.Property(c => c.Kind).HasColumnName("kind").HasConversion<string>().HasMaxLength(32);
introductionChange.Property(c => c.Stage).HasColumnName("stage").HasConversion<string>().HasMaxLength(32);
introductionChange.Property(c => c.Live).HasColumnName("live");
introductionChange.Property(c => c.ChangedBy).HasColumnName("changed_by").HasMaxLength(Contact.PersonLength);
⋮----
.HasForeignKey(c => c.IntroductionId)
.HasConstraintName("fk_crm_introduction_changes_introduction")
⋮----
introductionChange.HasIndex(c => new { c.IntroductionId, c.ChangedAt }).HasDatabaseName("ix_crm_introduction_changes_introduction_changed_at");
⋮----
state.ToTable("feature_state");
state.HasKey(s => new { s.Collection, s.Key });
⋮----
state.Property(s => s.Collection).HasColumnName("collection").HasMaxLength(StoredFeatureState.CollectionLength);
state.Property(s => s.Key).HasColumnName("key").HasMaxLength(StoredFeatureState.KeyLength);
state.Property(s => s.Value).HasColumnName("value").HasColumnType("jsonb");
state.Property(s => s.UpdatedAt).HasColumnName("updated_at");
⋮----
private static class DetailsAsJson
⋮----
value => JsonSerializer.Serialize(value, (JsonSerializerOptions?)null),
⋮----
(left, right) => left != null && right != null && left.Count == right.Count && !left.Except(right).Any(),
value => value.Aggregate(0, (hash, pair) => HashCode.Combine(hash, pair.Key, pair.Value)),
⋮----
private static class DictionaryAsJson
</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);
⋮----
? GatewayWriteAnswer<GatewayTier>.Of(GatewayOutcome.Unreachable, text["Gateway.Client.ChangedNotAllowanceRow"])
⋮----
private async Task<Reply> PutAsync<T>(string path, T body, string operatorName, CancellationToken cancellationToken)
⋮----
return Reply.Of(GatewayOutcome.RequestRefused, text["Gateway.Client.OperatorName", MaxOperatorLength]);
⋮----
var content = new StringContent(JsonSerializer.Serialize(body, Wire), Encoding.UTF8, "application/json");
⋮----
logger.LogWarning("The gateway answered 404 for PUT {Path}: it predates kf-ai-gateway#39.", path);
return Reply.Of(GatewayOutcome.NotReported);
⋮----
public async Task<GatewayUsageDailyAnswer> UsageDailyAsync(UsageRange range, Guid? installationId = null, CancellationToken cancellationToken = default)
⋮----
return GatewayUsageDailyAnswer.Of(GatewayOutcome.RequestRefused, range, $"{range} is not a range the gateway answers: at most {UsageRange.MaxDays} days, in order.");
⋮----
var query = $"from={UsageRange.Format(range.From)}&to={UsageRange.Format(range.To)}";
⋮----
return GatewayUsageDailyAnswer.Of(outcome, range, detail);
⋮----
return GatewayUsageDailyAnswer.Of(reply.Outcome, range, reply.Detail);
⋮----
? GatewayUsageDailyAnswer.Of(GatewayOutcome.Unreachable, range, text["Gateway.Client.NotUsageDays"])
: new GatewayUsageDailyAnswer(
⋮----
GatewayUsageDailyAnswer.Fill(range, days.Where(day => day.Day >= range.From && day.Day <= range.To), byRow: installationId is null),
⋮----
public async Task<GatewayUsageSummaryAnswer> UsageSummaryAsync(UsageRange range, int top = 10, CancellationToken cancellationToken = default)
⋮----
return GatewayUsageSummaryAnswer.Of(GatewayOutcome.RequestRefused, $"{range} is not a range the gateway answers: at most {UsageRange.MaxDays} days, in order.");
⋮----
var limit = Math.Clamp(top, 1, MaxUsageTop);
⋮----
$"{UsageSummaryPath}?from={UsageRange.Format(range.From)}&to={UsageRange.Format(range.To)}&limit={limit}",
⋮----
return GatewayUsageSummaryAnswer.Of(outcome, detail);
⋮----
return GatewayUsageSummaryAnswer.Of(reply.Outcome, reply.Detail);
⋮----
? GatewayUsageSummaryAnswer.Of(GatewayOutcome.Unreachable, text["Gateway.Client.NotUsageSummary"])
: new GatewayUsageSummaryAnswer(GatewayOutcome.Answered, summary, Detail: null);
⋮----
public async Task<GatewayUsageTokensAnswer> TokensInAsync(UsageRange range, IReadOnlyCollection<Guid> installations, CancellationToken cancellationToken = default)
⋮----
return GatewayUsageTokensAnswer.Of(summary.Outcome, range, summary.Detail);
⋮----
.GroupBy(installation => installation.InstallationId)
.ToDictionary(group => group.Key, group => group.First().Tokens);
⋮----
var tokens = installations.Distinct().ToDictionary(id => id, id => listed.GetValueOrDefault(id));
⋮----
return new GatewayUsageTokensAnswer(GatewayOutcome.Answered, range, tokens, Unread: 0, Detail: null);
⋮----
var missing = tokens.Keys.Where(id => !listed.ContainsKey(id)).ToList();
var asked = missing.Take(MaxTokensAskedOneByOne).ToList();
⋮----
logger.LogWarning(
⋮----
using var gate = new SemaphoreSlim(4);
var answers = await Task.WhenAll(asked.Select(async id =>
⋮----
await gate.WaitAsync(cancellationToken);
⋮----
gate.Release();
⋮----
if (answers.FirstOrDefault(answer => !answer.Answer.Answered) is { Answer: { } failed })
⋮----
return GatewayUsageTokensAnswer.Of(failed.Outcome, range, failed.Detail);
⋮----
foreach (var id in missing.Skip(asked.Count))
⋮----
tokens.Remove(id);
⋮----
return new GatewayUsageTokensAnswer(GatewayOutcome.Answered, range, tokens, Unread: missing.Count - asked.Count, Detail: null);
⋮----
private async Task<(GatewayOutcome Outcome, string? Detail)> NotFoundOnNewerEndpointAsync(string path, string ticket, CancellationToken cancellationToken)
⋮----
logger.LogInformation("The gateway answered 404 for {Path} but lists its installations: it predates {Ticket}.", path, ticket);
⋮----
logger.LogWarning("The gateway answered 404 for {Path}: it maps no /admin.", path);
⋮----
private async Task<GatewayAnswer> ListAsync(string path, CancellationToken cancellationToken)
⋮----
return GatewayAnswer.Of(reply.Outcome, reply.Detail);
⋮----
? GatewayAnswer.Of(GatewayOutcome.Unreachable, text["Gateway.Client.NotInstallations"])
: new GatewayAnswer(GatewayOutcome.Answered, installations, Detail: null) { Total = reply.Total };
⋮----
private async Task<GatewayAnswer> NotSeenSinceAsync(InstallationQuery query, DateTimeOffset before, CancellationToken cancellationToken)
⋮----
var older = answer.Installations.Where(installation => installation.LastSeenAt < before).ToList();
⋮----
Total = seenSince is { } seen && answer.Total is { } total ? Math.Max(0, total - seen) : older.Count,
⋮----
private async Task<GatewayInstallationAnswer> NotFoundAsync(Guid installationId, CancellationToken cancellationToken)
⋮----
return GatewayInstallationAnswer.Of(probe.Outcome, probe.Detail);
⋮----
logger.LogInformation("The gateway answered 404 for one installation but lists them: it predates kf-ai-gateway#38.");
⋮----
return GatewayInstallationAnswer.Of(newest.Outcome, newest.Detail);
⋮----
if (newest.Installations.FirstOrDefault(installation => installation.InstallationId == installationId) is { } found)
⋮----
return new GatewayInstallationAnswer(GatewayOutcome.Answered, found, Detail: null);
⋮----
return GatewayInstallationAnswer.Of(newest.Installations.Count < MaxLimit ? GatewayOutcome.UnknownInstallation : GatewayOutcome.NotReported);
⋮----
private Task<Reply> GetAsync(string path, CancellationToken cancellationToken) =>
⋮----
private async Task<Reply> SendAsync(HttpMethod method, string path, string? operatorName, HttpContent? content, CancellationToken cancellationToken)
⋮----
return Reply.Of(GatewayOutcome.NotConfigured);
⋮----
return Reply.Of(GatewayOutcome.WritesNotConfigured);
⋮----
using var request = new HttpRequestMessage(method, new Uri(settings.BaseAddress!, path)) { Content = content };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", (writes ? settings.AdminWriteToken! : settings.AdminToken!).Trim());
⋮----
request.Headers.TryAddWithoutValidation(OperatorHeader, operatorName);
⋮----
using var response = await http.SendAsync(request, cancellationToken);
⋮----
logger.LogWarning("The gateway refused the console's admin token for {Path}.", path);
return Reply.Of(GatewayOutcome.TokenRefused);
⋮----
logger.LogError("The gateway refused the console's write token for {Method} {Path}: it is the gateway's read token.", method, path);
return Reply.Of(GatewayOutcome.WriteRefused);
⋮----
return Reply.Of(GatewayOutcome.NoAdminSurface);
⋮----
return Refused(path, await response.Content.ReadAsStringAsync(cancellationToken));
⋮----
logger.LogWarning("The gateway's /admin did not answer {Path}: HTTP {Status}.", path, (int)status);
return Reply.Of(GatewayOutcome.Unreachable, text["Gateway.Client.Http", (int)status]);
⋮----
return Reply.Answered(await response.Content.ReadAsStringAsync(cancellationToken), TotalOf(response));
⋮----
? text["Gateway.Client.Timeout", http.Timeout.TotalSeconds.ToString("0.#", CultureInfo.CurrentCulture)].Value
⋮----
logger.LogWarning(ex, "The gateway's /admin did not answer {Path}.", path);
return Reply.Of(GatewayOutcome.Unreachable, detail);
⋮----
private Reply Refused(string path, string body)
⋮----
return Reply.Of(GatewayOutcome.RequestRefused, detail);
⋮----
private static int? TotalOf(HttpResponseMessage response) =>
response.Headers.TryGetValues(TotalHeader, out var values)
&& int.TryParse(values.FirstOrDefault(), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var total)
⋮----
private T? Read<T>(string body, string path, string expected, LogLevel level = LogLevel.Warning) where T : class
⋮----
logger.Log(level, ex, "The gateway's answer to {Path} was not {Expected}.", path, expected);
⋮----
public static Reply Of(GatewayOutcome outcome, string? detail = null) => new(outcome, detail, null, null);
⋮----
public static Reply Answered(string body, int? total) => new(GatewayOutcome.Answered, null, body, total);
⋮----
public static GatewayAnswer Of(GatewayOutcome outcome, string? detail = null) => new(outcome, [], detail);
⋮----
public static GatewayInstallationAnswer Of(GatewayOutcome outcome, string? detail = null) => new(outcome, null, detail);
⋮----
public static GatewayStatusAnswer Of(GatewayOutcome outcome, string? detail = null) => new(outcome, null, detail);
</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;
</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;
</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/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/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/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/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>
  </data>
  <data name="Shell.Navbar.SignedIn" xml:space="preserve">
    <value>Accesso effettuato</value>
  </data>
  <data name="Shell.Navbar.SharedCredential" xml:space="preserve">
    <value>Questa sessione è stata autenticata con la password condivisa della console, quindi le azioni sono registrate a nome della credenziale e non di una persona.</value>
  </data>
  <data name="Shell.Navbar.SignOut" xml:space="preserve">
    <value>Esci</value>
  </data>
  <data name="Shell.Footer.Environment" xml:space="preserve">
    <value>Ambiente che serve questa richiesta</value>
  </data>
  <data name="Account.Login.Title" xml:space="preserve">
    <value>Accedi</value>
  </data>
  <data name="Account.Login.Lead" xml:space="preserve">
    <value>Accedi alla console di amministrazione.</value>
  </data>
  <data name="Account.Login.NameHelp" xml:space="preserve">
    <value>Il tuo nome, com'è in Key Vault.</value>
  </data>
  <data name="Account.Login.Submit" xml:space="preserve">
    <value>Accedi</value>
  </data>
  <data name="Account.Login.Name" xml:space="preserve">
    <value>Nome</value>
  </data>
  <data name="Account.Login.Password" xml:space="preserve">
    <value>Password</value>
  </data>
  <data name="Account.Login.NameTooLong" xml:space="preserve">
    <value>Un nome ha al massimo 64 caratteri.</value>
  </data>
  <data name="Account.Login.PasswordRequired" xml:space="preserve">
    <value>Inserisci la password.</value>
  </data>
  <data name="Account.Login.EnterName" xml:space="preserve">
    <value>Inserisci il tuo nome.</value>
  </data>
  <data name="Account.Login.NotAccepted" xml:space="preserve">
    <value>Nome e password non sono stati accettati.</value>
  </data>
  <data name="Account.Login.LockedOut.One" xml:space="preserve">
    <value>Troppi tentativi falliti. Riprova tra 1 minuto.</value>
  </data>
  <data name="Account.Login.LockedOut.Many" xml:space="preserve">
    <value>Troppi tentativi falliti. Riprova tra {0} minuti.</value>
  </data>
  <data name="Error.Back" xml:space="preserve">
    <value>Torna alla console</value>
  </data>
  <data name="Error.Reference" xml:space="preserve">
    <value>Riferimento {0}: citalo quando segnali il problema.</value>
  </data>
  <data name="Error.NotFound.Title" xml:space="preserve">
    <value>Pagina non trovata</value>
  </data>
  <data name="Error.NotFound.Detail" xml:space="preserve">
    <value>Questo indirizzo non esiste in questa console.</value>
  </data>
  <data name="Error.Forbidden.Title" xml:space="preserve">
    <value>Non consentito</value>
  </data>
  <data name="Error.Forbidden.Detail" xml:space="preserve">
    <value>La tua sessione è autenticata, ma nessuno dei suoi ruoli lo consente. Un Amministratore concede i ruoli nella pagina Utenti della console.</value>
  </data>
  <data name="Error.TooManyRequests.Title" xml:space="preserve">
    <value>Troppe richieste</value>
  </data>
  <data name="Error.TooManyRequests.Detail" xml:space="preserve">
    <value>Troppi tentativi in poco tempo. Attendi un minuto e riprova.</value>
  </data>
  <data name="Error.Unexpected.Title" xml:space="preserve">
    <value>Qualcosa è andato storto</value>
  </data>
  <data name="Error.Unexpected.Detail" xml:space="preserve">
    <value>La console non è riuscita a completare la richiesta.</value>
  </data>
  <data name="Menu.Overview" xml:space="preserve">
    <value>Panoramica</value>
  </data>
  <data name="Menu.Audit" xml:space="preserve">
    <value>Registro di audit</value>
  </data>
  <data name="Menu.Users" xml:space="preserve">
    <value>Utenti</value>
  </data>
  <data name="Menu.Licensing" xml:space="preserve">
    <value>Licenze</value>
  </data>
  <data name="Menu.Licensing.Issue" xml:space="preserve">
    <value>Emetti una licenza</value>
  </data>
  <data name="Menu.Licensing.Validate" xml:space="preserve">
    <value>Convalida una licenza</value>
  </data>
  <data name="Menu.Licensing.Register" xml:space="preserve">
    <value>Registro delle licenze</value>
  </data>
  <data name="Menu.Gateway" xml:space="preserve">
    <value>Gateway IA</value>
  </data>
  <data name="Menu.Gateway.Overview" xml:space="preserve">
    <value>Panoramica</value>
  </data>
  <data name="Menu.Gateway.Installations" xml:space="preserve">
    <value>Installazioni</value>
  </data>
  <data name="Menu.Gateway.UsageByLicence" xml:space="preserve">
    <value>Utilizzo per licenza</value>
  </data>
  <data name="Menu.Gateway.UsageHistory" xml:space="preserve">
    <value>Cronologia utilizzo</value>
  </data>
  <data name="Menu.Gateway.Policy" xml:space="preserve">
    <value>Policy</value>
  </data>
  <data name="Menu.Crm" xml:space="preserve">
    <value>CRM</value>
  </data>
  <data name="Menu.Crm.Contacts" xml:space="preserve">
    <value>Partnership</value>
  </data>
  <data name="Menu.Crm.FollowUps" xml:space="preserve">
    <value>Follow-up</value>
  </data>
  <data name="Menu.Crm.Statistics" xml:space="preserve">
    <value>Statistiche</value>
  </data>
  <data name="Home.Title" xml:space="preserve">
    <value>Panoramica</value>
  </data>
  <data name="Home.Intro" xml:space="preserve">
    <value>La console di amministrazione interna. Le funzionalità si aggiungono come aree: l'emissione delle licenze è la prima, il gateway IA la seconda e il CRM la terza, ciascuna con una propria area anziché una propria applicazione.</value>
  </data>
  <data name="Home.SignedInAs" xml:space="preserve">
    <value>Accesso effettuato come {0}</value>
  </data>
  <data name="Home.RolesUnreadable" xml:space="preserve">
    <value>Non è stato possibile leggere i tuoi ruoli in questo momento, quindi la console non ti mostra nulla finché non sarà possibile. Il motivo è nel log della console; riprova tra poco.</value>
  </data>
  <data name="Home.NoRoles" xml:space="preserve">
    <value>Non hai ancora alcun ruolo, quindi qui non c'è nulla che tu possa vedere. Chiedi a un Amministratore di concederti i ruoli di cui hai bisogno: ogni area ha un ruolo di visualizzazione e uno di scrittura.</value>
  </data>
  <data name="Role.Administrator" xml:space="preserve">
    <value>Amministratore</value>
  </data>
  <data name="Role.Area.Licensing" xml:space="preserve">
    <value>Licenze</value>
  </data>
  <data name="Role.Area.Gateway" xml:space="preserve">
    <value>Gateway</value>
  </data>
  <data name="Role.Area.Crm" xml:space="preserve">
    <value>CRM</value>
  </data>
  <data name="Role.Verb.View" xml:space="preserve">
    <value>Visualizzazione</value>
  </data>
  <data name="Role.Verb.Write" xml:space="preserve">
    <value>Scrittura</value>
  </data>
  <data name="Role.Display" xml:space="preserve">
    <value>{0}: {1}</value>
  </data>
  <data name="Generic.Apply" xml:space="preserve">
    <value>Applica</value>
  </data>
  <data name="Generic.Clear" xml:space="preserve">
    <value>Azzera</value>
  </data>
  <data name="Generic.PageOf" xml:space="preserve">
    <value>Pagina {0} di {1}</value>
  </data>
  <data name="Audit.Title" xml:space="preserve">
    <value>Registro di audit</value>
  </data>
  <data name="Audit.Intro" xml:space="preserve">
    <value>Cosa è stato fatto tramite questa console e da chi, dal più recente: ogni modifica, ogni licenza emessa, scaricata o convalidata, ogni esportazione, ogni accesso, ogni revoca o ripristino di un'installazione sul gateway e ogni modifica alla sua policy. Una voce sotto un nome proprio è attribuibile; una sotto la password condivisa dice chi l'operatore ha dichiarato di essere, e non prova nulla. Le voci vengono aggiunte e mai modificate.</value>
  </data>
  <data name="Audit.OwnEntriesOnly" xml:space="preserve">
    <value>Queste sono le tue voci: ciò che è stato fatto sotto il nome &lt;strong&gt;{0}&lt;/strong&gt;, accessi compresi. Le voci di tutti può leggerle un Amministratore.</value>
  </data>
  <data name="Audit.NoDatabase.Title" xml:space="preserve">
    <value>La console non ha un database</value>
  </data>
  <data name="Audit.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; non è in Key Vault, quindi le voci di audit sono soltanto righe di log in Application Insights e qui non c'è nulla da elencare. Sono le tracce il cui messaggio inizia con &lt;code&gt;Audit:&lt;/code&gt;.</value>
  </data>
  <data name="Audit.Ephemeral" xml:space="preserve">
    <value>Registro di audit di sviluppo, tenuto in memoria: tutto ciò che è qui va perso al riavvio della console.</value>
  </data>
  <data name="Audit.Unreadable.Title" xml:space="preserve">
    <value>Non è stato possibile leggere il registro di audit</value>
  </data>
  <data name="Audit.Unreadable.Detail" xml:space="preserve">
    <value>Il motivo è nel log della console, sotto "The audit page could not read the audit log". Le voci continuano a essere scritte come righe di log in Application Insights.</value>
  </data>
  <data name="Audit.Filter.Action" xml:space="preserve">
    <value>Azione</value>
  </data>
  <data name="Audit.Filter.EveryAction" xml:space="preserve">
    <value>Tutte le azioni</value>
  </data>
  <data name="Audit.Filter.Target" xml:space="preserve">
    <value>Oggetto</value>
  </data>
  <data name="Audit.Filter.TargetPlaceholder" xml:space="preserve">
    <value>Un id di installazione o di licenza, o una sua parte</value>
  </data>
  <data name="Audit.Count.One" xml:space="preserve">
    <value>1 voce</value>
  </data>
  <data name="Audit.Count.Many" xml:space="preserve">
    <value>{0} voci</value>
  </data>
  <data name="Audit.Count.OneMatch" xml:space="preserve">
    <value>1 voce corrisponde</value>
  </data>
  <data name="Audit.Count.ManyMatch" xml:space="preserve">
    <value>{0} voci corrispondono</value>
  </data>
  <data name="Audit.Column.When" xml:space="preserve">
    <value>Quando, UTC</value>
  </data>
  <data name="Audit.Column.Who" xml:space="preserve">
    <value>Chi</value>
  </data>
  <data name="Audit.Column.Action" xml:space="preserve">
    <value>Azione</value>
  </data>
  <data name="Audit.Column.Target" xml:space="preserve">
    <value>Oggetto</value>
  </data>
  <data name="Audit.Column.Details" xml:space="preserve">
    <value>Dettagli</value>
  </data>
  <data name="Audit.Empty.Filtered" xml:space="preserve">
    <value>Nessuna voce corrisponde a questi filtri.</value>
  </data>
  <data name="Audit.Empty.Own" xml:space="preserve">
    <value>Non è ancora stato registrato nulla sotto il tuo nome.</value>
  </data>
  <data name="Audit.Empty.All" xml:space="preserve">
    <value>Non è ancora stato registrato nulla.</value>
  </data>
  <data name="Audit.SharedPassword" xml:space="preserve">
    <value>password condivisa</value>
  </data>
  <data name="Audit.SharedPassword.Title" xml:space="preserve">
    <value>Accesso con la password condivisa: non si sa chi fosse</value>
  </data>
  <data name="Audit.ClaimedAs" xml:space="preserve">
    <value>come "{0}"</value>
  </data>
  <data name="Audit.Correlation.Title" xml:space="preserve">
    <value>L'identificativo di traccia della richiesta, per trovarne i log</value>
  </data>
  <data name="Audit.Newer" xml:space="preserve">
    <value>Più recenti</value>
  </data>
  <data name="Audit.Older" xml:space="preserve">
    <value>Meno recenti</value>
  </data>
  <data name="Users.Title" xml:space="preserve">
    <value>Utenti</value>
  </data>
  <data name="Users.Intro.Roles" xml:space="preserve">
    <value>Chi può fare cosa nella console. Ogni area ha un ruolo di visualizzazione e uno di scrittura, e quello di scrittura comprende la visualizzazione; {0} comprende ogni ruolo e questa pagina. Una concessione o una revoca ha effetto alla richiesta successiva di quella persona, senza disconnessione, ed è registrata nel registro di audit.</value>
  </data>
  <data name="Users.Intro.Names" xml:space="preserve">
    <value>Un nome è elencato quando può accedere, con un segreto proprio, &lt;code&gt;Authentication--Users--&amp;lt;nome&amp;gt;&lt;/code&gt; in Key Vault, caricato da un operatore con i diritti su Key Vault (&lt;code&gt;docs/Operations.md&lt;/code&gt;, &lt;em&gt;People&lt;/em&gt;), oppure finché detiene ancora un ruolo. &lt;strong&gt;admin&lt;/strong&gt; detiene ogni ruolo per costruzione: non c'è nulla da concedergli né nulla che gli si possa revocare.</value>
  </data>
  <data name="Users.NoDatabase.Title" xml:space="preserve">
    <value>La console non ha un database</value>
  </data>
  <data name="Users.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; non è in Key Vault, quindi non c'è dove conservare un ruolo: &lt;strong&gt;admin&lt;/strong&gt; detiene ogni ruolo per costruzione e nessun altro ne detiene alcuno. Non si può concedere nulla finché il database non è configurato (&lt;code&gt;docs/Provisioning.md&lt;/code&gt;, parte C).</value>
  </data>
  <data name="Users.Ephemeral" xml:space="preserve">
    <value>Ruoli di sviluppo, tenuti in memoria: ogni concessione va persa al riavvio della console.</value>
  </data>
  <data name="Users.Unreadable.Title" xml:space="preserve">
    <value>Non è stato possibile leggere i ruoli</value>
  </data>
  <data name="Users.Unreadable.Detail" xml:space="preserve">
    <value>Il motivo è nel log della console, sotto "The Users page could not read the roles". Finché non si potranno leggere, nessuno tranne &lt;strong&gt;admin&lt;/strong&gt; detiene un ruolo.</value>
  </data>
  <data name="Users.Problem.NoDatabase" xml:space="preserve">
    <value>Nulla è cambiato: la console non ha un database, quindi nessun ruolo può essere concesso o revocato.</value>
  </data>
  <data name="Users.Problem.NotGranted" xml:space="preserve">
    <value>Nulla è cambiato: non è stato possibile concedere {0} a {1}. Il motivo è nel log della console.</value>
  </data>
  <data name="Users.Problem.NotRevoked" xml:space="preserve">
    <value>Nulla è cambiato: non è stato possibile revocare {0} a {1}. Il motivo è nel log della console.</value>
  </data>
  <data name="Users.Count.One" xml:space="preserve">
    <value>1 nome</value>
  </data>
  <data name="Users.Count.Many" xml:space="preserve">
    <value>{0} nomi</value>
  </data>
  <data name="Users.Column.Name" xml:space="preserve">
    <value>Nome</value>
  </data>
  <data name="Users.You" xml:space="preserve">
    <value>(tu)</value>
  </data>
  <data name="Users.NoSecret" xml:space="preserve">
    <value>nessun segreto</value>
  </data>
  <data name="Users.NoSecret.Title" xml:space="preserve">
    <value>Nessun segreto Authentication--Users--{0}, quindi questo nome non può accedere. I suoi ruoli restano finché non vengono revocati.</value>
  </data>
  <data name="Users.NoRoles" xml:space="preserve">
    <value>nessun ruolo</value>
  </data>
  <data name="Users.NoRoles.Title" xml:space="preserve">
    <value>Accede e vede solo la panoramica, che dice di rivolgersi a un Amministratore.</value>
  </data>
  <data name="Users.EveryRole" xml:space="preserve">
    <value>Ogni ruolo, per costruzione</value>
  </data>
  <data name="Users.Held" xml:space="preserve">
    <value>Detenuto</value>
  </data>
  <data name="Users.Held.Title" xml:space="preserve">
    <value>Detenuto: concesso da {0}, {1} UTC</value>
  </data>
  <data name="Users.Revoke" xml:space="preserve">
    <value>Revoca</value>
  </data>
  <data name="Users.Revoke.Title" xml:space="preserve">
    <value>Revoca {0} a {1}</value>
  </data>
  <data name="Users.Grant" xml:space="preserve">
    <value>Concedi</value>
  </data>
  <data name="Users.Grant.Title" xml:space="preserve">
    <value>Concedi {0} a {1}</value>
  </data>
  <data name="Users.Through" xml:space="preserve">
    <value>tramite {0}</value>
  </data>
  <data name="Users.Intro.Initials" xml:space="preserve">
    <value>Le iniziali, dove impostate, sono ciò che la griglia del CRM mostra per una persona, VS invece di vera, con il nome al passaggio del mouse; il record, i suoi filtri, la sua esportazione e il registro di audit conservano il nome. Vuote, si mostra il nome. admin non ne ha.</value>
  </data>
  <data name="Users.Column.Initials" xml:space="preserve">
    <value>Iniziali</value>
  </data>
  <data name="Users.Initials.Title" xml:space="preserve">
    <value>Mostrate nella griglia del CRM al posto del nome, che resta ciò che ogni record contiene. Da una a quattro lettere; vuote, si mostra il nome.</value>
  </data>
  <data name="Users.Initials.Label" xml:space="preserve">
    <value>Iniziali di {0}</value>
  </data>
  <data name="Users.Initials.Admin.Title" xml:space="preserve">
    <value>admin non è una persona, quindi non ha iniziali.</value>
  </data>
  <data name="Users.Initials.Same" xml:space="preserve">
    <value>uguali a {0}</value>
  </data>
  <data name="Users.Initials.Same.Title" xml:space="preserve">
    <value>Due persone con le stesse iniziali si leggono come una sola nella griglia del CRM, finché il passaggio del mouse non mostra il nome. Consentito, ma conviene cambiarle.</value>
  </data>
  <data name="Users.Problem.NotInitials" xml:space="preserve">
    <value>Nulla è cambiato: “{0}” non sono iniziali. Scrivi da una a {1} lettere, oppure lascia vuoto per mostrare il nome.</value>
  </data>
  <data name="Users.Problem.NoDatabaseInitials" xml:space="preserve">
    <value>Nulla è cambiato: la console non ha un database, quindi non si possono impostare iniziali.</value>
  </data>
  <data name="Users.Problem.InitialsNotSet" xml:space="preserve">
    <value>Nulla è cambiato: non è stato possibile salvare le iniziali di {0}. Il motivo è nel log della console.</value>
  </data>
  <data name="Generic.Search" xml:space="preserve">
    <value>Cerca</value>
  </data>
  <data name="Generic.Optional" xml:space="preserve">
    <value>(facoltativo)</value>
  </data>
  <data name="Generic.Edit" xml:space="preserve">
    <value>Modifica</value>
  </data>
  <data name="Generic.Previous" xml:space="preserve">
    <value>Precedente</value>
  </data>
  <data name="Generic.Next" xml:space="preserve">
    <value>Successiva</value>
  </data>
  <data name="Licensing.Purpose" xml:space="preserve">
    <value>Scopo</value>
  </data>
  <data name="Licensing.Tier" xml:space="preserve">
    <value>Livello</value>
  </data>
  <data name="Licensing.LicenceId" xml:space="preserve">
    <value>Id licenza</value>
  </data>
  <data name="Licensing.Type" xml:space="preserve">
    <value>Tipo</value>
  </data>
  <data name="Licensing.SchemaVersion" xml:space="preserve">
    <value>Versione dello schema</value>
  </data>
  <data name="Licensing.Unreadable" xml:space="preserve">
    <value>illeggibile</value>
  </data>
  <data name="Licensing.ValidFrom" xml:space="preserve">
    <value>Valida dal</value>
  </data>
  <data name="Licensing.AreaKeys" xml:space="preserve">
    <value>Chiavi di area</value>
  </data>
  <data name="Licensing.OtherAttributes" xml:space="preserve">
    <value>Altri attributi</value>
  </data>
  <data name="Licensing.LicenceXml" xml:space="preserve">
    <value>XML della licenza</value>
  </data>
  <data name="Licensing.Reissue" xml:space="preserve">
    <value>Riemetti</value>
  </data>
  <data name="Licensing.Installations" xml:space="preserve">
    <value>Installazioni</value>
  </data>
  <data name="Licensing.Column.Customer" xml:space="preserve">
    <value>Cliente</value>
  </data>
  <data name="Licensing.Column.Company" xml:space="preserve">
    <value>Azienda</value>
  </data>
  <data name="Licensing.Column.Expires" xml:space="preserve">
    <value>Scade</value>
  </data>
  <data name="Licensing.Column.Issued" xml:space="preserve">
    <value>Emessa</value>
  </data>
  <data name="Licensing.Column.IssuedBy" xml:space="preserve">
    <value>Emessa da</value>
  </data>
  <data name="Licensing.Badge.Expired" xml:space="preserve">
    <value>scaduta</value>
  </data>
  <data name="Licensing.Badge.Custom" xml:space="preserve">
    <value>personalizzato</value>
  </data>
  <data name="Licensing.Badge.NotYetInForce" xml:space="preserve">
    <value>non ancora in vigore</value>
  </data>
  <data name="Licensing.Badge.Reissue" xml:space="preserve">
    <value>riemissione</value>
  </data>
  <data name="Licensing.Section.Reports" xml:space="preserve">
    <value>Report</value>
  </data>
  <data name="Licensing.Section.Features" xml:space="preserve">
    <value>Funzionalità</value>
  </data>
  <data name="Licensing.Section.Connectors" xml:space="preserve">
    <value>Connettori</value>
  </data>
  <data name="Licensing.Section.Analysis" xml:space="preserve">
    <value>Analisi</value>
  </data>
  <data name="Licensing.Section.AI" xml:space="preserve">
    <value>IA</value>
  </data>
  <data name="Licensing.Register.Title" xml:space="preserve">
    <value>Registro delle licenze</value>
  </data>
  <data name="Licensing.Register.Lead" xml:space="preserve">
    <value>Ogni licenza emessa dalla console.</value>
  </data>
  <data name="Licensing.Register.Count.One" xml:space="preserve">
    <value>1 licenza</value>
  </data>
  <data name="Licensing.Register.Count.Many" xml:space="preserve">
    <value>{0} licenze</value>
  </data>
  <data name="Licensing.Register.Count.OneMatch" xml:space="preserve">
    <value>1 licenza corrisponde</value>
  </data>
  <data name="Licensing.Register.Count.ManyMatch" xml:space="preserve">
    <value>{0} licenze corrispondono</value>
  </data>
  <data name="Licensing.Register.Issue" xml:space="preserve">
    <value>Emetti</value>
  </data>
  <data name="Licensing.Register.SearchPlaceholder" xml:space="preserve">
    <value>Cliente, azienda o id licenza</value>
  </data>
  <data name="Licensing.Register.EveryPurpose" xml:space="preserve">
    <value>Tutti gli scopi</value>
  </data>
  <data name="Licensing.Register.EveryTier" xml:space="preserve">
    <value>Tutti i livelli</value>
  </data>
  <data name="Licensing.Register.Status" xml:space="preserve">
    <value>Stato</value>
  </data>
  <data name="Licensing.Register.Status.Both" xml:space="preserve">
    <value>Attive e scadute</value>
  </data>
  <data name="Licensing.Register.Status.Active" xml:space="preserve">
    <value>Attive</value>
  </data>
  <data name="Licensing.Register.Status.Expired" xml:space="preserve">
    <value>Scadute</value>
  </data>
  <data name="Licensing.Register.Empty" xml:space="preserve">
    <value>Non è ancora stata registrata alcuna licenza.</value>
  </data>
  <data name="Licensing.Register.Empty.Filtered" xml:space="preserve">
    <value>Nessuna licenza corrisponde.</value>
  </data>
  <data name="Licensing.Register.Download.Title" xml:space="preserve">
    <value>Scarica il file .lic</value>
  </data>
  <data name="Licensing.Register.Download.For" xml:space="preserve">
    <value>Scarica il file di licenza di {0}</value>
  </data>
  <data name="Licensing.Register.DownloadLic" xml:space="preserve">
    <value>Scarica .lic</value>
  </data>
  <data name="Licensing.Register.OnInstallation" xml:space="preserve">
    <value>All'installazione</value>
  </data>
  <data name="Licensing.Register.NotKnownHere" xml:space="preserve">
    <value>Sconosciuti qui</value>
  </data>
  <data name="Licensing.Register.NotKnownHere.Detail" xml:space="preserve">
    <value>Emessi prima che il catalogo di questa build li conoscesse. I lettori che non li conoscono li ignorano.</value>
  </data>
  <data name="Licensing.Register.AreaKeys.Detail" xml:space="preserve">
    <value>Emessa prima della #38. Queste chiavi ora non concedono nulla; riemetti la licenza per concedere ciò che dovrebbe.</value>
  </data>
  <data name="Licensing.Register.SignedInAs" xml:space="preserve">
    <value>Accesso come</value>
  </data>
  <data name="Licensing.Register.Recorded" xml:space="preserve">
    <value>Registrata</value>
  </data>
  <data name="Licensing.Register.NoDatabase.Title" xml:space="preserve">
    <value>Il registro non ha un database</value>
  </data>
  <data name="Licensing.Register.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; non è in Key Vault, quindi qui non si può registrare nulla e non si può emettere nulla. Il provisioning è la parte C di &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Licensing.Register.Ephemeral" xml:space="preserve">
    <value>Registro di sviluppo, tenuto in memoria: tutto ciò che è qui va perso al riavvio della console.</value>
  </data>
  <data name="Licensing.Gateway.NotConfigured.Title" xml:space="preserve">
    <value>Il gateway non è configurato</value>
  </data>
  <data name="Licensing.Gateway.NotConfigured.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminToken&lt;/code&gt; non è in Key Vault, quindi la console non chiede al gateway quali installazioni usano una licenza. Caricarlo è il punto B3 di &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Licensing.Gateway.NoLicenceIds.Title" xml:space="preserve">
    <value>Il gateway non registra ancora gli id delle licenze</value>
  </data>
  <data name="Licensing.Gateway.NoLicenceIds.Detail" xml:space="preserve">
    <value>Ha risposto senza, quindi è anteriore a kf-ai-gateway#35, distribuita il 2026-09-26: verifica che &lt;code&gt;Gateway:BaseUrl&lt;/code&gt; indichi il gateway presso cui le installazioni si registrano e che sia stato distribuito da allora.</value>
  </data>
  <data name="Licensing.Gateway.RequestRefused.Title" xml:space="preserve">
    <value>Il gateway ha rifiutato la richiesta della console</value>
  </data>
  <data name="Licensing.Gateway.RequestRefused.Detail" xml:space="preserve">
    <value>Ha risposto 400, che è un difetto della console e non un'interruzione: la console controlla ciò che invia, e ha inviato qualcosa che il gateway non accetta. È nel log della console, sotto "The gateway refused the console's request"; segnalalo anziché riprovare.</value>
  </data>
  <data name="Licensing.Gateway.TokenRefused.Title" xml:space="preserve">
    <value>Il gateway ha rifiutato il token di amministrazione della console</value>
  </data>
  <data name="Licensing.Gateway.TokenRefused.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminToken&lt;/code&gt; deve essere uno dei token del gateway per lo stesso ambiente: il suo &lt;code&gt;Admin__ReadToken&lt;/code&gt; (kf-ai-gateway#40). &lt;code&gt;docs/Operations.md&lt;/code&gt; dice cosa controllare.</value>
  </data>
  <data name="Licensing.Gateway.NoAdminSurface.Title" xml:space="preserve">
    <value>Il gateway non espone l'amministrazione</value>
  </data>
  <data name="Licensing.Gateway.NoAdminSurface.Detail" xml:space="preserve">
    <value>Ha risposto 404 a &lt;code&gt;/admin/installations&lt;/code&gt;, come fa quando non ha un &lt;code&gt;Admin__Token&lt;/code&gt; impostato o quando &lt;code&gt;Gateway:BaseUrl&lt;/code&gt; non è il gateway. &lt;code&gt;docs/Operations.md&lt;/code&gt; dice cosa controllare.</value>
  </data>
  <data name="Licensing.Gateway.Unreachable.Title" xml:space="preserve">
    <value>La console non è riuscita a raggiungere il gateway</value>
  </data>
  <data name="Licensing.Gateway.Unreachable.Detail" xml:space="preserve">
    <value>Il motivo è nel log della console, sotto "The gateway's /admin did not answer"; &lt;code&gt;docs/Operations.md&lt;/code&gt; dice cosa controllare.</value>
  </data>
  <data name="Licensing.Issue.Title" xml:space="preserve">
    <value>Emetti una licenza</value>
  </data>
  <data name="Licensing.Issue.ReissueTitle" xml:space="preserve">
    <value>Riemetti una licenza</value>
  </data>
  <data name="Licensing.Issue.PreviewTitle" xml:space="preserve">
    <value>Anteprima della licenza</value>
  </data>
  <data name="Licensing.Issue.IssuedTitle" xml:space="preserve">
    <value>Licenza emessa</value>
  </data>
  <data name="Licensing.Issue.Term.Months" xml:space="preserve">
    <value>{0} mesi</value>
  </data>
  <data name="Licensing.Issue.Term.OneYear" xml:space="preserve">
    <value>1 anno</value>
  </data>
  <data name="Licensing.Issue.Term.Years" xml:space="preserve">
    <value>{0} anni</value>
  </data>
  <data name="Licensing.Issue.ViewOnly.Title" xml:space="preserve">
    <value>Puoi vedere questo modulo ma non emettere da qui</value>
  </data>
  <data name="Licensing.Issue.ViewOnly.Detail" xml:space="preserve">
    <value>Emettere richiede il ruolo {0}, e {1} non lo detiene. Un Amministratore lo concede nella pagina Utenti.</value>
  </data>
  <data name="Licensing.Issue.Dropped" xml:space="preserve">
    <value>La licenza da riemettere contiene {0}, che questa build non conosce e il modulo non può scrivere. La nuova licenza non li conterrà.</value>
  </data>
  <data name="Licensing.Issue.Predates" xml:space="preserve">
    <value>La licenza da riemettere è anteriore a ciò che una licenza concede oggi (#38): contiene le vecchie chiavi di area, che non concedono nulla. Il modulo parte con tutto attivo e senza limiti. Controlla ogni sezione prima dell'anteprima.</value>
  </data>
  <data name="Licensing.Issue.ReissueLead" xml:space="preserve">
    <value>Un rinnovo mantiene l'id della licenza, {0}, così il registro la conta come la stessa licenza.</value>
  </data>
  <data name="Licensing.Issue.Lead" xml:space="preserve">
    <value>Una licenza Standard. Nulla viene firmato finché non hai visto l'anteprima.</value>
  </data>
  <data name="Licensing.Issue.PurposeLabel" xml:space="preserve">
    <value>A cosa serve</value>
  </data>
  <data name="Licensing.Issue.PurposeHelp" xml:space="preserve">
    <value>Scritto nell'attributo &lt;code&gt;purpose&lt;/code&gt;. Non concede nulla; è il modo in cui il registro tiene le licenze interne e demo fuori dalle sue cifre. Qualunque sia lo scopo, una licenza copre una sola installazione: emettine una per ciascuna.</value>
  </data>
  <data name="Licensing.Issue.Form.Company" xml:space="preserve">
    <value>Azienda</value>
  </data>
  <data name="Licensing.Issue.Form.Tier" xml:space="preserve">
    <value>Livello</value>
  </data>
  <data name="Licensing.Issue.TierHelp" xml:space="preserve">
    <value>Scritto nell'attributo &lt;code&gt;tier&lt;/code&gt;. Nessun lettore vi agisce; sceglierne uno compila il suo tetto di connettori.</value>
  </data>
  <data name="Licensing.Issue.Term" xml:space="preserve">
    <value>Durata</value>
  </data>
  <data name="Licensing.Issue.Form.ValidFrom" xml:space="preserve">
    <value>Valida dal</value>
  </data>
  <data name="Licensing.Issue.ValidFromHelp" xml:space="preserve">
    <value>Dalle 00:00 UTC di quel giorno. Vuoto: in vigore dall'emissione; lascialo vuoto per un rinnovo. Una data futura significa che il file va installato quel giorno o dopo: il Gateway IA lo rifiuta prima di allora e non conserva nulla da attivare in seguito, e kf-app rifiuta di installarlo prima di allora dalla sua prossima release (kf-app#979). kf-app 1.6.2 lo installa, subito in vigore.</value>
  </data>
  <data name="Licensing.Issue.Form.LastsFor" xml:space="preserve">
    <value>Dura</value>
  </data>
  <data name="Licensing.Issue.CommonTerms" xml:space="preserve">
    <value>Durate comuni</value>
  </data>
  <data name="Licensing.Issue.HowMany" xml:space="preserve">
    <value>Quanti</value>
  </data>
  <data name="Licensing.Issue.Units" xml:space="preserve">
    <value>Giorni, settimane, mesi o anni</value>
  </data>
  <data name="Licensing.Issue.Unit.Days" xml:space="preserve">
    <value>giorni</value>
  </data>
  <data name="Licensing.Issue.Unit.Weeks" xml:space="preserve">
    <value>settimane</value>
  </data>
  <data name="Licensing.Issue.Unit.Months" xml:space="preserve">
    <value>mesi</value>
  </data>
  <data name="Licensing.Issue.Unit.Years" xml:space="preserve">
    <value>anni</value>
  </data>
  <data name="Licensing.Issue.DurationHelp" xml:space="preserve">
    <value>Contati da &lt;em&gt;valida dal&lt;/em&gt;, o dall'emissione, secondo il calendario: 12 mesi dal 15 marzo finiscono il 15 marzo.</value>
  </data>
  <data name="Licensing.Issue.ExpiresOn" xml:space="preserve">
    <value>Scade il</value>
  </data>
  <data name="Licensing.Issue.ExpiryDate" xml:space="preserve">
    <value>Data di scadenza</value>
  </data>
  <data name="Licensing.Issue.ExpiryHelp" xml:space="preserve">
    <value>Funziona fino alle 23:59:59 UTC di quel giorno.</value>
  </data>
  <data name="Licensing.Issue.Grants.Title" xml:space="preserve">
    <value>Cosa concede la licenza</value>
  </data>
  <data name="Licensing.Issue.Grants.Lead" xml:space="preserve">
    <value>Tutto parte attivo e senza limiti. Una licenza concede solo ciò che nomina, quindi ciò che viene disattivato qui, e ciò che il prodotto aggiungerà in futuro, non è concesso.</value>
  </data>
  <data name="Licensing.Issue.AllOn" xml:space="preserve">
    <value>Tutti attivi</value>
  </data>
  <data name="Licensing.Issue.AllOff" xml:space="preserve">
    <value>Tutti disattivi</value>
  </data>
  <data name="Licensing.Issue.Connector" xml:space="preserve">
    <value>Connettore</value>
  </data>
  <data name="Licensing.Issue.NoLimitPlaceholder" xml:space="preserve">
    <value>Nessun limite</value>
  </data>
  <data name="Licensing.Issue.HowManySources" xml:space="preserve">
    <value>Numero di {1} {0}</value>
  </data>
  <data name="Licensing.Issue.AiPeriod" xml:space="preserve">
    <value>Periodo del budget IA</value>
  </data>
  <data name="Licensing.Issue.AiHelp" xml:space="preserve">
    <value>Vuoto significa la quota del Gateway IA per il livello della licenza, o quella di Standard quando non ne ha: 10.000.000 di token per mese di calendario e 120 richieste al minuto per entrambi i livelli finché quella di Enterprise non verrà alzata, cosa che raggiunge ogni licenza Enterprise senza riemetterla (#46). Inserisci numeri solo per un accordo che include più del suo livello. Valgono per ogni chiamata IA fatta dall'installazione, non solo per quelle dell'assistente.</value>
  </data>
  <data name="Licensing.Issue.AttributesHelp" xml:space="preserve">
    <value>Un &lt;code&gt;nome=valore&lt;/code&gt; per riga. Inerti nel prodotto. &lt;code&gt;TrialDays&lt;/code&gt;, i nomi che il modulo imposta da sé e tutto ciò che inizia con &lt;code&gt;ai.&lt;/code&gt;, &lt;code&gt;sources.&lt;/code&gt; o &lt;code&gt;analysis.&lt;/code&gt; sono rifiutati.</value>
  </data>
  <data name="Licensing.Issue.YourName" xml:space="preserve">
    <value>Il tuo nome</value>
  </data>
  <data name="Licensing.Issue.IssuedByHelp" xml:space="preserve">
    <value>Registrato nel registro accanto al nome con cui hai effettuato l'accesso. Con la password condivisa questa casella è l'unica traccia di chi ha emesso la licenza.</value>
  </data>
  <data name="Licensing.Issue.Preview" xml:space="preserve">
    <value>Anteprima</value>
  </data>
  <data name="Licensing.Issue.Form.IssuedBy" xml:space="preserve">
    <value>Emessa da</value>
  </data>
  <data name="Licensing.Issue.Form.IssuedByRequired" xml:space="preserve">
    <value>Indica chi emette questa licenza.</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerName" xml:space="preserve">
    <value>Nome del licenziatario</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerNameRequired" xml:space="preserve">
    <value>Il nome del licenziatario è obbligatorio.</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerEmail" xml:space="preserve">
    <value>Email del licenziatario</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerEmailRequired" xml:space="preserve">
    <value>L'email del licenziatario è obbligatoria.</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerEmailInvalid" xml:space="preserve">
    <value>Questo non è un indirizzo email.</value>
  </data>
  <data name="Licensing.Issue.Form.TooLong" xml:space="preserve">
    <value>{0} è troppo lungo: al massimo {1} caratteri.</value>
  </data>
  <data name="Licensing.Issue.Form.Attributes" xml:space="preserve">
    <value>Altri attributi</value>
  </data>
  <data name="Licensing.Issue.Problem.CountAtLeastOne" xml:space="preserve">
    <value>{0}: il numero deve essere almeno 1. Lascialo vuoto per nessun limite, oppure disattiva il connettore.</value>
  </data>
  <data name="Licensing.Issue.Problem.LimitAtLeastOne" xml:space="preserve">
    <value>{0} deve essere almeno 1. Lascialo vuoto per {1}.</value>
  </data>
  <data name="Licensing.Issue.Problem.DurationRequired" xml:space="preserve">
    <value>Indica quanto dura la licenza: un numero intero di giorni, settimane, mesi o anni, almeno 1.</value>
  </data>
  <data name="Licensing.Issue.Problem.DurationUnit" xml:space="preserve">
    <value>Scegli giorni, settimane, mesi o anni per la durata della licenza.</value>
  </data>
  <data name="Licensing.Issue.Problem.AttributeLine" xml:space="preserve">
    <value>Attributi, riga {0}: scrivila come nome=valore.</value>
  </data>
  <data name="Licensing.Issue.Problem.AttributeTwice" xml:space="preserve">
    <value>Attributi, riga {0}: '{1}' è impostato più di una volta.</value>
  </data>
  <data name="Licensing.Issue.Failure.PreviewExpired" xml:space="preserve">
    <value>L'anteprima è scaduta o non è leggibile. Controlla la licenza e genera di nuovo l'anteprima.</value>
  </data>
  <data name="Licensing.Issue.Failure.NoDatabase" xml:space="preserve">
    <value>Non si può emettere nulla: il registro delle licenze non ha un database, e una licenza non viene mai consegnata senza essere registrata.</value>
  </data>
  <data name="Licensing.Issue.Failure.AlreadySigning" xml:space="preserve">
    <value>Questa licenza è già in corso di firma. Controlla il registro prima di riprovare.</value>
  </data>
  <data name="Licensing.Issue.Failure.TestKeyRefused" xml:space="preserve">
    <value>Non emessa: la chiave di firma configurata è una chiave di prova del contratto, e nulla di ciò che firma è valido su un'installazione cliente.</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyNotConfigured" xml:space="preserve">
    <value>Non emessa: la chiave di firma non è configurata (Licensing--PrivateKey e Licensing--PrivateKeyPassphrase in Key Vault).</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyNotBase64" xml:space="preserve">
    <value>Non emessa: Licensing--PrivateKey non è una chiave, non è base64. Il segreto deve essere esattamente il contenuto di private.key: una riga, senza virgolette, senza intestazione. Salva una nuova versione corretta, poi riavvia l'App Service.</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyIsPublic" xml:space="preserve">
    <value>Non emessa: Licensing--PrivateKey contiene la chiave pubblica (public.key), non quella privata. Salva il contenuto di private.key come nuova versione, poi riavvia l'App Service.</value>
  </data>
  <data name="Licensing.Issue.Failure.PassphraseHasWhitespace" xml:space="preserve">
    <value>Non emessa: Licensing--PrivateKeyPassphrase ha uno spazio o un a capo all'inizio o alla fine. Senza di esso, la passphrase apre la chiave. Salva una nuova versione del segreto senza, poi riavvia l'App Service.</value>
  </data>
  <data name="Licensing.Issue.Failure.PassphraseDoesNotOpenKey" xml:space="preserve">
    <value>Non emessa: Licensing--PrivateKeyPassphrase non apre Licensing--PrivateKey. I due segreti non vanno insieme: di solito la chiave di prima del rekey con la nuova passphrase, o il contrario. Controllali entrambi con la copia in deposito; vedi Operations, 'Issuing a licence fails'.</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyNotTrusted" xml:space="preserve">
    <value>Non emessa: la chiave di firma configurata non è una di quelle di cui il prodotto si fida, quindi nulla di ciò che firma si installerebbe. Verifica che Licensing--PrivateKey in Key Vault sia la chiave di Knowledge Fabric; vedi Operations, 'Issuing a licence fails'.</value>
  </data>
  <data name="Licensing.Issue.Failure.SigningFailed" xml:space="preserve">
    <value>Non emessa: la chiave di firma si è aperta, ma la firma non è riuscita. L'eccezione è nel log della console, sotto 'Issuing licence ... failed'.</value>
  </data>
  <data name="Licensing.Issue.Failure.Config" xml:space="preserve">
    <value>Non emessa: {0}</value>
  </data>
  <data name="Licensing.Issue.Failure.NotRecorded" xml:space="preserve">
    <value>Non emessa: non è stato possibile registrare la licenza nel registro, quindi non è stata consegnata. Non c'è nulla da annullare; riprova quando il registro sarà raggiungibile.</value>
  </data>
  <data name="Licensing.Issue.SignerSays" xml:space="preserve">
    <value>Il firmatario segnala:</value>
  </data>
  <data name="Licensing.Issue.OnIssue" xml:space="preserve">
    <value>All'emissione</value>
  </data>
  <data name="Licensing.Issue.Size" xml:space="preserve">
    <value>Dimensione</value>
  </data>
  <data name="Licensing.Issue.BytesSigned" xml:space="preserve">
    <value>Circa {0} byte firmati</value>
  </data>
  <data name="Licensing.Issue.SignAndRecord" xml:space="preserve">
    <value>Firma e registra</value>
  </data>
  <data name="Licensing.Issue.SigningHelp" xml:space="preserve">
    <value>La firma registra la licenza nel registro prima che il file possa essere scaricato. Questa anteprima può essere firmata per {0} minuti.</value>
  </data>
  <data name="Licensing.Issue.XmlLead" xml:space="preserve">
    <value>Come verrà firmato. La firma viene aggiunta quando premi Firma.</value>
  </data>
  <data name="Licensing.Issued.Title" xml:space="preserve">
    <value>Licenza emessa a {0}</value>
  </data>
  <data name="Licensing.Issued.Expires" xml:space="preserve">
    <value>Scade il {0} · id licenza {1}</value>
  </data>
  <data name="Licensing.Issued.Recorded" xml:space="preserve">
    <value>Registrata nel registro. Scaricala e inviala al cliente.</value>
  </data>
  <data name="Licensing.Issued.Download" xml:space="preserve">
    <value>Scarica {0}</value>
  </data>
  <data name="Licensing.Issued.ViewInRegister" xml:space="preserve">
    <value>Vedi nel registro</value>
  </data>
  <data name="Licensing.Issued.IssueAnother" xml:space="preserve">
    <value>Emetti un'altra</value>
  </data>
  <data name="Licensing.Signing.NoKey.Title" xml:space="preserve">
    <value>Nessuna chiave di firma</value>
  </data>
  <data name="Licensing.Signing.NoKey.Detail" xml:space="preserve">
    <value>&lt;code&gt;Licensing--PrivateKey&lt;/code&gt; e &lt;code&gt;Licensing--PrivateKeyPassphrase&lt;/code&gt; non sono entrambi configurati, quindi qui si può vedere l'anteprima delle licenze ma non firmarle. Vanno in Key Vault (parte B di &lt;code&gt;docs/Provisioning.md&lt;/code&gt;) e raggiungono la console al suo prossimo riavvio.</value>
  </data>
  <data name="Licensing.Signing.TestKeyRefused.Title" xml:space="preserve">
    <value>La chiave di firma è una chiave di prova del contratto</value>
  </data>
  <data name="Licensing.Signing.TestKeyRefused.Detail" xml:space="preserve">
    <value>È una delle chiavi usa e getta in &lt;code&gt;contract/test-keys/&lt;/code&gt;, la cui metà pubblica non è in alcuna immagine del prodotto. Nulla di ciò che firma è valido su un'installazione cliente, quindi la console qui non firma con essa.</value>
  </data>
  <data name="Licensing.Signing.TestKey" xml:space="preserve">
    <value>Sviluppo: firma con una chiave di prova del contratto. Ciò che firma è valido solo nei test delle fixture del contratto.</value>
  </data>
  <data name="Licensing.Signing.NoDatabase.Detail" xml:space="preserve">
    <value>Una licenza non viene mai consegnata senza essere registrata, e &lt;code&gt;Database--ConnectionString&lt;/code&gt; non è configurato, quindi non si può emettere nulla. Il provisioning è la parte C di &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Licensing.Signing.Ephemeral" xml:space="preserve">
    <value>Registro di sviluppo, tenuto in memoria: una licenza emessa qui resta registrata fino al riavvio della console.</value>
  </data>
  <data name="Licensing.Validate.Title" xml:space="preserve">
    <value>Convalida una licenza</value>
  </data>
  <data name="Licensing.Validate.Lead" xml:space="preserve">
    <value>Cosa faranno il prodotto e il Gateway IA di un file &lt;code&gt;.lic&lt;/code&gt;. Nulla viene modificato o registrato, a parte una riga di audit.</value>
  </data>
  <data name="Licensing.Validate.File" xml:space="preserve">
    <value>File di licenza</value>
  </data>
  <data name="Licensing.Validate.OrPaste" xml:space="preserve">
    <value>oppure incolla l'XML</value>
  </data>
  <data name="Licensing.Validate.AsOf" xml:space="preserve">
    <value>Alla data</value>
  </data>
  <data name="Licensing.Validate.AsOf.Optional" xml:space="preserve">
    <value>(facoltativa, UTC)</value>
  </data>
  <data name="Licensing.Validate.AsOf.Help" xml:space="preserve">
    <value>Vuoto: adesso. Imposta una data per sapere se funzionerà ancora allora.</value>
  </data>
  <data name="Licensing.Validate.TrustTestKey" xml:space="preserve">
    <value>Fidati anche della chiave di prova del contratto</value>
  </data>
  <data name="Licensing.Validate.TrustTestKey.Help" xml:space="preserve">
    <value>Per controllare le fixture. Nessuna immagine del prodotto se ne fida.</value>
  </data>
  <data name="Licensing.Validate.Submit" xml:space="preserve">
    <value>Convalida</value>
  </data>
  <data name="Licensing.Validate.Explainer.Readers" xml:space="preserve">
    <value>Ogni lettore è mostrato due volte: come si comporta &lt;strong&gt;oggi&lt;/strong&gt;, letto dal suo codice al commit indicato, e come richiede il &lt;strong&gt;contratto di licenza&lt;/strong&gt; (&lt;code&gt;docs/License-Contract.md&lt;/code&gt;). Dove differiscono, si tratta di una differenza nota del lettore, spiegata sotto i suoi esiti, non di un problema della licenza.</value>
  </data>
  <data name="Licensing.Validate.Explainer.Keys" xml:space="preserve">
    <value>Le firme sono verificate con la chiave di cui si fida ogni immagine del prodotto (kf-app &lt;code&gt;BundledLicensingSettings.PublicKeys&lt;/code&gt;), che è anche l'elenco di cui si fida il gateway.</value>
  </data>
  <data name="Licensing.Validate.PastedLicence" xml:space="preserve">
    <value>Licenza incollata</value>
  </data>
  <data name="Licensing.Validate.EvaluatedAsOf" xml:space="preserve">
    <value>Valutata alla data {0}</value>
  </data>
  <data name="Licensing.Validate.Signature" xml:space="preserve">
    <value>Firma</value>
  </data>
  <data name="Licensing.Validate.Signature.Valid" xml:space="preserve">
    <value>valida</value>
  </data>
  <data name="Licensing.Validate.Signature.NotVerified" xml:space="preserve">
    <value>non verificata</value>
  </data>
  <data name="Licensing.Validate.Signature.By" xml:space="preserve">
    <value>con la {0}</value>
  </data>
  <data name="Licensing.Validate.Key.Product" xml:space="preserve">
    <value>chiave di firma Knowledge Fabric</value>
  </data>
  <data name="Licensing.Validate.Key.ContractTest" xml:space="preserve">
    <value>chiave di prova del contratto (contract/test-keys)</value>
  </data>
  <data name="Licensing.Validate.Signature.TestKey" xml:space="preserve">
    <value>chiave di prova: non valida su alcuna installazione cliente</value>
  </data>
  <data name="Licensing.Validate.Signature.NoTrustedKey" xml:space="preserve">
    <value>con nessuna chiave fidata: modificata dopo la firma, o firmata con un'altra chiave</value>
  </data>
  <data name="Licensing.Validate.Unsupported" xml:space="preserve">
    <value>non supportata</value>
  </data>
  <data name="Licensing.Validate.NamesNotKnown" xml:space="preserve">
    <value>Nomi sconosciuti</value>
  </data>
  <data name="Licensing.Validate.NamesNotKnown.Detail" xml:space="preserve">
    <value>Ignorati da un lettore che non li conosce: forse scritti male, o più recenti di questa build.</value>
  </data>
  <data name="Licensing.Validate.AreaKeys.Detail" xml:space="preserve">
    <value>Le chiavi rimosse dalla #38. Nessun lettore le legge più: kf-app ha smesso a {0}, quindi non concedono nulla.</value>
  </data>
  <data name="Licensing.Validate.UnknownAttributes" xml:space="preserve">
    <value>Attributi sconosciuti</value>
  </data>
  <data name="Licensing.Validate.UnknownAttributes.Detail" xml:space="preserve">
    <value>Trasportati e ignorati da ogni lettore.</value>
  </data>
  <data name="Licensing.Validate.Register" xml:space="preserve">
    <value>Registro</value>
  </data>
  <data name="Licensing.Validate.Register.ThisFile" xml:space="preserve">
    <value>Esattamente questo file</value>
  </data>
  <data name="Licensing.Validate.Register.IssuedBy" xml:space="preserve">
    <value>, emesso il {0} da {1}</value>
  </data>
  <data name="Licensing.Validate.Register.NotChecked" xml:space="preserve">
    <value>Non verificato: il registro non ha un database.</value>
  </data>
  <data name="Licensing.Validate.Register.NotThisFile" xml:space="preserve">
    <value>Non questo file, ma</value>
  </data>
  <data name="Licensing.Validate.Register.SameId.One" xml:space="preserve">
    <value>1 licenza con questo id</value>
  </data>
  <data name="Licensing.Validate.Register.SameId.Many" xml:space="preserve">
    <value>{0} licenze con questo id</value>
  </data>
  <data name="Licensing.Validate.Register.SameId.Detail" xml:space="preserve">
    <value>: un rinnovo, o un file modificato dopo l'emissione.</value>
  </data>
  <data name="Licensing.Validate.Register.NotInRegister" xml:space="preserve">
    <value>Non nel registro: emessa offline, o altrove.</value>
  </data>
  <data name="Licensing.Validate.Product.Title" xml:space="preserve">
    <value>Il prodotto</value>
  </data>
  <data name="Licensing.Validate.Product.Lead" xml:space="preserve">
    <value>Caricandola nella pagina della licenza</value>
  </data>
  <data name="Licensing.Validate.Today" xml:space="preserve">
    <value>Oggi</value>
  </data>
  <data name="Licensing.Validate.PerContract" xml:space="preserve">
    <value>Secondo il contratto</value>
  </data>
  <data name="Licensing.Validate.Source.ProductToday" xml:space="preserve">
    <value>kf-app {0} su develop, LicenseService.UploadLicenseAsync</value>
  </data>
  <data name="Licensing.Validate.Source.GatewayToday" xml:space="preserve">
    <value>kf-ai-gateway {0}, StandardLicenceEvaluator</value>
  </data>
  <data name="Licensing.Validate.Product.Differ" xml:space="preserve">
    <value>Differiscono solo sul fatto che venga conservata. Il contratto dice che non è in vigore prima del suo &lt;code&gt;validFrom&lt;/code&gt;; kf-app la rifiuta al caricamento anziché tenerla in attesa, perché installare una licenza sostituisce quella in vigore (kf-app &lt;code&gt;docs/Architecture/Licence-Remit.md&lt;/code&gt;, D4).</value>
  </data>
  <data name="Licensing.Validate.Product.Release" xml:space="preserve">
    <value>kf-app {0}, la release attuale ({1}), non rispetta &lt;code&gt;validFrom&lt;/code&gt;: installa questa licenza, subito in vigore. kf-app#979 lo cambia dalla prossima release.</value>
  </data>
  <data name="Licensing.Validate.Gateway.Title" xml:space="preserve">
    <value>Il Gateway IA</value>
  </data>
  <data name="Licensing.Validate.Gateway.Lead" xml:space="preserve">
    <value>Alla registrazione, e &lt;code&gt;PUT /v1/installation/licence&lt;/code&gt;</value>
  </data>
  <data name="Licensing.Validate.Gateway.Words" xml:space="preserve">
    <value>Il livello è lo stesso; le parole differiscono. L'API del gateway pubblica due motivi, quindi riporta &lt;code&gt;unsupported-schema&lt;/code&gt;, &lt;code&gt;trial-licence&lt;/code&gt; e &lt;code&gt;not-yet-valid&lt;/code&gt; del contratto come &lt;code&gt;unverifiable&lt;/code&gt; senza &lt;code&gt;expires_at&lt;/code&gt;, e registra nel log soltanto la parola del contratto.</value>
  </data>
  <data name="Licensing.Validate.Gateway.NotYetValid" xml:space="preserve">
    <value>Il gateway controlla una licenza solo quando viene inviata, quindi un'installazione che invia questa prima del suo &lt;code&gt;validFrom&lt;/code&gt; resta su &lt;code&gt;evaluation&lt;/code&gt; finché non la invia di nuovo dopo quella data. kf-app {0} può farlo; da kf-app#979, kf-app la rifiuta al caricamento, quindi non la invia mai in anticipo. Un rinnovo non ha bisogno di &lt;code&gt;validFrom&lt;/code&gt;: &lt;em&gt;Riemetti&lt;/em&gt; fa invece partire la durata dalla vecchia scadenza (#42).</value>
  </data>
  <data name="Licensing.Validate.Gateway.EnterpriseBeforeTier" xml:space="preserve">
    <value>Un'installazione che ha inviato la licenza prima che il gateway leggesse &lt;code&gt;tier&lt;/code&gt; (kf-ai-gateway#32, distribuita il 2026-09-25) non ha alcun livello di licenza registrato lì, e riceve la quota di &lt;code&gt;standard&lt;/code&gt; finché non invia di nuovo una licenza.</value>
  </data>
  <data name="Licensing.Validate.Gateway.WhenSent" xml:space="preserve">
    <value>kf-app a {0} invia la licenza alla prima registrazione, e di nuovo ogni volta che una licenza viene installata, sostituita o rimossa: subito se l'installazione usa l'IA, altrimenti al suo prossimo utilizzo (kf-app#968). kf-app {1} la invia solo alla prima registrazione, quindi lì una licenza caricata dopo il primo utilizzo dell'IA, rinnovo compreso, non raggiunge il gateway.</value>
  </data>
  <data name="Licensing.Validate.Gateway.LoggedAs" xml:space="preserve">
    <value>Registrato nel log come {0}, la parola del contratto.</value>
  </data>
  <data name="Licensing.Validate.Verdict.Refused" xml:space="preserve">
    <value>rifiutata</value>
  </data>
  <data name="Licensing.Validate.Verdict.AcceptedGrantsNothing" xml:space="preserve">
    <value>accettata, non concede nulla</value>
  </data>
  <data name="Licensing.Validate.Verdict.Accepted" xml:space="preserve">
    <value>accettata</value>
  </data>
  <data name="Licensing.Validate.FileTooLarge" xml:space="preserve">
    <value>Quel file supera {0} KB, cosa che nessuna licenza fa.</value>
  </data>
  <data name="Licensing.Validate.NothingToRead" xml:space="preserve">
    <value>Scegli un file .lic, oppure incolla l'XML della licenza.</value>
  </data>
  <data name="Licensing.Validate.Verdict.Installs" xml:space="preserve">
    <value>Si installa, e apre ciò che nomina.</value>
  </data>
  <data name="Licensing.Validate.Verdict.InstallsInForce" xml:space="preserve">
    <value>Si installa ed è in vigore.</value>
  </data>
  <data name="Licensing.Validate.Verdict.InstallsNotYetInForce" xml:space="preserve">
    <value>Si installa, ma non è in vigore fino al suo validFrom.</value>
  </data>
  <data name="Licensing.Validate.Verdict.GrantsNothing" xml:space="preserve">
    <value>Non nomina alcun report, funzionalità, connettore o capacità IA, quindi si aprono solo Configurazione e Amministrazione.</value>
  </data>
  <data name="Licensing.Validate.Allowance.TokensUnreadable" xml:space="preserve">
    <value>0 token, che rifiuta ogni richiesta</value>
  </data>
  <data name="Licensing.Validate.Allowance.Tokens" xml:space="preserve">
    <value>{0} token per periodo di budget</value>
  </data>
  <data name="Licensing.Validate.Allowance.PeriodMonth" xml:space="preserve">
    <value>un mese di calendario UTC come periodo di budget</value>
  </data>
  <data name="Licensing.Validate.Allowance.Period30d" xml:space="preserve">
    <value>30 giorni come periodo di budget</value>
  </data>
  <data name="Licensing.Validate.Allowance.RequestsUnreadable" xml:space="preserve">
    <value>0 richieste al minuto, che rifiuta ogni richiesta</value>
  </data>
  <data name="Licensing.Validate.Allowance.Requests" xml:space="preserve">
    <value>{0} richieste al minuto</value>
  </data>
  <data name="Licensing.Validate.Allowance.None" xml:space="preserve">
    <value>Non nomina limiti IA, quindi vale la quota propria del livello {0}.</value>
  </data>
  <data name="Licensing.Validate.Allowance.Replaces" xml:space="preserve">
    <value>I suoi limiti IA sostituiscono quelli del livello {0}: {1}. Quelli che omette restano del livello.</value>
  </data>
  <data name="Licensing.Validate.Explain.NotALicence" xml:space="preserve">
    <value>Non è una licenza: non si riesce a leggerla.</value>
  </data>
  <data name="Licensing.Validate.Explain.Unverifiable" xml:space="preserve">
    <value>Nessuna chiave fidata verifica la sua firma: è stata modificata dopo la firma, o firmata con un'altra chiave.</value>
  </data>
  <data name="Licensing.Validate.Explain.UnsupportedSchema" xml:space="preserve">
    <value>Questa licenza dichiara la versione di schema {0}, più recente di quella supportata da questa build (versione {1}). Aggiorna l'applicazione per installarla.</value>
  </data>
  <data name="Licensing.Validate.Explain.Trial" xml:space="preserve">
    <value>Contiene TrialDays, che indica una prova.</value>
  </data>
  <data name="Licensing.Validate.Explain.Expired" xml:space="preserve">
    <value>È scaduta.</value>
  </data>
  <data name="Licensing.Validate.Explain.ValidFromUnreadable" xml:space="preserve">
    <value>Il suo validFrom non è leggibile, quindi non è in vigore, e kf-app la rifiuta anziché conservarla.</value>
  </data>
  <data name="Licensing.Validate.Explain.NotYetValid" xml:space="preserve">
    <value>Non è in vigore fino alle {0} UTC, e kf-app la rifiuta anziché conservarla in attesa.</value>
  </data>
  <data name="Licensing.Validate.Explain.Refused" xml:space="preserve">
    <value>Rifiutata.</value>
  </data>
  <data name="Licensing.Overview.Today" xml:space="preserve">
    <value>oggi</value>
  </data>
  <data name="Licensing.Overview.Tomorrow" xml:space="preserve">
    <value>domani</value>
  </data>
  <data name="Licensing.Overview.InDays" xml:space="preserve">
    <value>tra {0} giorni</value>
  </data>
  <data name="Licensing.Overview.Unreadable.Title" xml:space="preserve">
    <value>Non è stato possibile leggere il registro</value>
  </data>
  <data name="Licensing.Overview.Unreadable.Detail" xml:space="preserve">
    <value>Non ci sono cifre sulle licenze finché non sarà possibile. L'eccezione è nel log della console, sotto "The overview could not read the licence register"; &lt;code&gt;docs/Operations.md&lt;/code&gt; tratta il caso di un database scomparso.</value>
  </data>
  <data name="Licensing.Overview.LicencesIssued" xml:space="preserve">
    <value>Licenze emesse</value>
  </data>
  <data name="Licensing.Overview.Files.One" xml:space="preserve">
    <value>1 file</value>
  </data>
  <data name="Licensing.Overview.Files.Many" xml:space="preserve">
    <value>{0} file</value>
  </data>
  <data name="Licensing.Overview.Reissues.One" xml:space="preserve">
    <value>1 riemissione</value>
  </data>
  <data name="Licensing.Overview.Reissues.Many" xml:space="preserve">
    <value>{0} riemissioni</value>
  </data>
  <data name="Licensing.Overview.Active" xml:space="preserve">
    <value>Attive</value>
  </data>
  <data name="Licensing.Overview.InForceToday" xml:space="preserve">
    <value>In vigore oggi</value>
  </data>
  <data name="Licensing.Overview.MoreNotYetInForce" xml:space="preserve">
    <value>; altre {0} non ancora in vigore</value>
  </data>
  <data name="Licensing.Overview.ExpiringWithinMonth" xml:space="preserve">
    <value>In scadenza entro un mese</value>
  </data>
  <data name="Licensing.Overview.ByUnlessReissued" xml:space="preserve">
    <value>Entro il {0}, salvo riemissione</value>
  </data>
  <data name="Licensing.Overview.Expired" xml:space="preserve">
    <value>Scadute</value>
  </data>
  <data name="Licensing.Overview.EveryFilePastExpiry" xml:space="preserve">
    <value>Ogni file oltre la sua scadenza</value>
  </data>
  <data name="Licensing.Overview.IssuedPerMonth" xml:space="preserve">
    <value>Emesse per mese</value>
  </data>
  <data name="Licensing.Overview.IssuedPerMonth.Lead" xml:space="preserve">
    <value>File emessi in ciascuno degli ultimi {0} mesi (UTC). Una riemissione mantiene il suo id di licenza.</value>
  </data>
  <data name="Licensing.Overview.IssuedPerMonth.Aria" xml:space="preserve">
    <value>{0} e {1} negli ultimi {2} mesi</value>
  </data>
  <data name="Licensing.Overview.NewLicences.One" xml:space="preserve">
    <value>1 nuova licenza</value>
  </data>
  <data name="Licensing.Overview.NewLicences.Many" xml:space="preserve">
    <value>{0} nuove licenze</value>
  </data>
  <data name="Licensing.Overview.TiersInForce" xml:space="preserve">
    <value>Livelli in vigore</value>
  </data>
  <data name="Licensing.Overview.TiersInForce.Lead" xml:space="preserve">
    <value>Licenze attive per l'attributo &lt;code&gt;tier&lt;/code&gt; del file in vigore.</value>
  </data>
  <data name="Licensing.Overview.NoTiers" xml:space="preserve">
    <value>Nessuna licenza è in vigore, quindi non ci sono livelli da mostrare.</value>
  </data>
  <data name="Licensing.Overview.Expiring.Lead" xml:space="preserve">
    <value>Licenze in vigore senza alcun file che duri oltre il {0}. Riemettine una per rinnovarla.</value>
  </data>
  <data name="Licensing.Overview.NothingExpires" xml:space="preserve">
    <value>Nulla scade prima del {0}.</value>
  </data>
  <data name="Licensing.Overview.ReissueFor" xml:space="preserve">
    <value>Riemetti la licenza di {0}</value>
  </data>
  <data name="Licensing.Overview.RecentlyIssued" xml:space="preserve">
    <value>Emesse di recente</value>
  </data>
  <data name="Licensing.Overview.RecentlyIssued.Lead" xml:space="preserve">
    <value>Gli ultimi {0} file, dal più recente.</value>
  </data>
  <data name="Licensing.Overview.RegisterLink" xml:space="preserve">
    <value>Registro</value>
  </data>
  <data name="Licensing.Overview.By" xml:space="preserve">
    <value>da {0}</value>
  </data>
  <data name="Licensing.Overview.Shared.Title" xml:space="preserve">
    <value>Licenze su più di un'installazione</value>
  </data>
  <data name="Licensing.Overview.Shared.Lead" xml:space="preserve">
    <value>Dal gateway: id di licenza detenuti da più di un'installazione non revocata, qualunque sia lo scopo della licenza. Una licenza copre una sola installazione.</value>
  </data>
  <data name="Licensing.Overview.Shared.None" xml:space="preserve">
    <value>Nessuna licenza è su più di un'installazione.</value>
  </data>
  <data name="Licensing.Overview.Shared.NotInRegister" xml:space="preserve">
    <value>Non nel registro</value>
  </data>
  <data name="Licensing.Overview.Shared.NotInRegister.Detail" xml:space="preserve">
    <value>Emessa offline senza &lt;code&gt;--register-csv&lt;/code&gt;, o dalla vecchia copia dello strumento in kf-app</value>
  </data>
  <data name="Licensing.Overview.Shared.Remedy" xml:space="preserve">
    <value>Chiedi al cliente quale installazione debba avere la licenza, poi revoca l'altra dalla pagina della licenza, che elenca le sue installazioni.</value>
  </data>
  <data name="Licensing.Installations.Lead" xml:space="preserve">
    <value>Ogni installazione che il gateway tiene con l'id di licenza {0}, con quanto ha usato in questo periodo e quanto le è consentito (#66). Una riemissione mantiene l'id, quindi ogni file di questa licenza mostra le stesse.</value>
  </data>
  <data name="Licensing.Installations.Shared.Title" xml:space="preserve">
    <value>Su {0} installazioni</value>
  </data>
  <data name="Licensing.Installations.Shared.Detail" xml:space="preserve">
    <value>Una licenza copre una sola installazione. Chiedi al cliente quale di queste debba averla, poi revoca l'altra con &lt;em&gt;Revoca&lt;/em&gt; qui sotto accanto a essa. Nel frattempo nulla viene rifiutato per questo.</value>
  </data>
  <data name="Licensing.Installations.None" xml:space="preserve">
    <value>Nessuna installazione nota al gateway detiene questa licenza.</value>
  </data>
  <data name="Licensing.Installations.Column.Installation" xml:space="preserve">
    <value>Installazione</value>
  </data>
  <data name="Licensing.Installations.Column.Version" xml:space="preserve">
    <value>Versione</value>
  </data>
  <data name="Licensing.Installations.Column.Row" xml:space="preserve">
    <value>Riga</value>
  </data>
  <data name="Licensing.Installations.Column.Status" xml:space="preserve">
    <value>Stato</value>
  </data>
  <data name="Licensing.Installations.Column.Enrolled" xml:space="preserve">
    <value>Registrata</value>
  </data>
  <data name="Licensing.Installations.Column.LastSeen" xml:space="preserve">
    <value>Ultimo contatto</value>
  </data>
  <data name="Licensing.Installations.Column.TokensUsed" xml:space="preserve">
    <value>Token usati</value>
  </data>
  <data name="Licensing.Installations.Column.RequestsAMinute" xml:space="preserve">
    <value>Richieste al minuto</value>
  </data>
  <data name="Licensing.Installations.Revoke" xml:space="preserve">
    <value>Revoca…</value>
  </data>
  <data name="Licensing.Installations.WireTier" xml:space="preserve">
    <value>Il livello sul filo: il gateway non riporta la riga che serve</value>
  </data>
  <data name="Licensing.Installations.ServedNothing" xml:space="preserve">
    <value>Non servita finché revocata.</value>
  </data>
  <data name="Licensing.Installations.NotReported" xml:space="preserve">
    <value>Non riportato</value>
  </data>
  <data name="Licensing.Installations.NotReported.Title" xml:space="preserve">
    <value>Il gateway è anteriore a kf-ai-gateway#38</value>
  </data>
  <data name="Licensing.Installations.OfLimit" xml:space="preserve">
    <value>di {0}, {1}%</value>
  </data>
  <data name="Licensing.Installations.TokensAgainstLimit" xml:space="preserve">
    <value>Token usati rispetto al limite</value>
  </data>
  <data name="Licensing.Installations.Resets" xml:space="preserve">
    <value>Si azzera {0}</value>
  </data>
  <data name="Licensing.Installations.Footnote" xml:space="preserve">
    <value>Il gateway tiene la licenza che ogni installazione gli ha inviato per ultima. kf-app ne invia una a ogni installazione da kf-app#968, non ancora in una release; kf-app 1.6.2 la invia solo alla prima registrazione, quindi una licenza installata lì in seguito non raggiunge il gateway. Un'installazione che non ha mai usato l'IA non si è mai registrata, quindi non è elencata.</value>
  </data>
  <data name="Catalogue.Report.insights" xml:space="preserve">
    <value>Hub delle Informazioni</value>
  </data>
  <data name="Catalogue.Report.insights.Description" xml:space="preserve">
    <value>La dashboard iniziale: il verdetto, l'istantanea della conoscenza, l'indice di resilienza e la copertura delle evidenze.</value>
  </data>
  <data name="Catalogue.Report.resilience" xml:space="preserve">
    <value>Report Resilienza al Rischio</value>
  </data>
  <data name="Catalogue.Report.resilience.Description" xml:space="preserve">
    <value>L'indice di resilienza, cosa lo abbassa, la copertura rispetto all'obiettivo e l'esposizione al rischio per risorsa.</value>
  </data>
  <data name="Catalogue.Report.watch" xml:space="preserve">
    <value>Report Monitoraggio Conoscenza</value>
  </data>
  <data name="Catalogue.Report.watch.Description" xml:space="preserve">
    <value>I movimenti principali di risorse e detentori di conoscenza.</value>
  </data>
  <data name="Catalogue.Report.holders" xml:space="preserve">
    <value>Analisi Detentore di Conoscenza</value>
  </data>
  <data name="Catalogue.Report.holders.Description" xml:space="preserve">
    <value>Il profilo di conoscenza e di rischio di ogni detentore di conoscenza.</value>
  </data>
  <data name="Catalogue.Report.assets" xml:space="preserve">
    <value>Analisi Risorsa di Conoscenza</value>
  </data>
  <data name="Catalogue.Report.assets.Description" xml:space="preserve">
    <value>Il profilo e il profilo di rischio di ogni risorsa di conoscenza.</value>
  </data>
  <data name="Catalogue.Report.map" xml:space="preserve">
    <value>Mappa della Conoscenza</value>
  </data>
  <data name="Catalogue.Report.map.Description" xml:space="preserve">
    <value>Chi sa cosa, come mappa.</value>
  </data>
  <data name="Catalogue.Report.skills" xml:space="preserve">
    <value>Matrice delle Competenze</value>
  </data>
  <data name="Catalogue.Report.skills.Description" xml:space="preserve">
    <value>Detentori di conoscenza rispetto alle risorse di conoscenza, come matrice.</value>
  </data>
  <data name="Catalogue.Report.workforce" xml:space="preserve">
    <value>Report Forza Lavoro</value>
  </data>
  <data name="Catalogue.Report.workforce.Description" xml:space="preserve">
    <value>L'elenco della forza lavoro, nell'area Forza Lavoro.</value>
  </data>
  <data name="Catalogue.Feature.offboarding" xml:space="preserve">
    <value>Pianificatore di Offboarding</value>
  </data>
  <data name="Catalogue.Feature.offboarding.Description" xml:space="preserve">
    <value>L'impronta di conoscenza di chi lascia e un piano di passaggio suggerito, registrabile come rischio.</value>
  </data>
  <data name="Catalogue.Feature.actioncenter" xml:space="preserve">
    <value>Centro Operativo</value>
  </data>
  <data name="Catalogue.Feature.actioncenter.Description" xml:space="preserve">
    <value>Il registro dei rischi: i rischi, il loro ciclo di vita e i loro obiettivi.</value>
  </data>
  <data name="Catalogue.Feature.departure" xml:space="preserve">
    <value>Simulatore di uscita</value>
  </data>
  <data name="Catalogue.Feature.departure.Description" xml:space="preserve">
    <value>E se questa persona se ne andasse: un pannello nel Report Resilienza al Rischio e nell'Analisi Detentore di Conoscenza.</value>
  </data>
  <data name="Catalogue.Feature.export" xml:space="preserve">
    <value>Esportazione</value>
  </data>
  <data name="Catalogue.Feature.export.Description" xml:space="preserve">
    <value>Il download dei dati dei report. Oggi è l'esportazione Excel della Matrice delle Competenze.</value>
  </data>
  <data name="Catalogue.Source.git" xml:space="preserve">
    <value>Git</value>
  </data>
  <data name="Catalogue.Source.git.Description" xml:space="preserve">
    <value>Controllo del codice sorgente</value>
  </data>
  <data name="Catalogue.Source.git.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.azureboards" xml:space="preserve">
    <value>Azure Boards</value>
  </data>
  <data name="Catalogue.Source.azureboards.Description" xml:space="preserve">
    <value>Gestione progetti</value>
  </data>
  <data name="Catalogue.Source.azureboards.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.jira" xml:space="preserve">
    <value>Jira</value>
  </data>
  <data name="Catalogue.Source.jira.Description" xml:space="preserve">
    <value>Gestione progetti</value>
  </data>
  <data name="Catalogue.Source.jira.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.gcal" xml:space="preserve">
    <value>Google Calendar</value>
  </data>
  <data name="Catalogue.Source.gcal.Description" xml:space="preserve">
    <value>Calendario</value>
  </data>
  <data name="Catalogue.Source.gcal.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.outlook" xml:space="preserve">
    <value>Outlook Calendar</value>
  </data>
  <data name="Catalogue.Source.outlook.Description" xml:space="preserve">
    <value>Calendario</value>
  </data>
  <data name="Catalogue.Source.outlook.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.confluence" xml:space="preserve">
    <value>Confluence</value>
  </data>
  <data name="Catalogue.Source.confluence.Description" xml:space="preserve">
    <value>Documentazione</value>
  </data>
  <data name="Catalogue.Source.confluence.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.shortcut" xml:space="preserve">
    <value>Shortcut</value>
  </data>
  <data name="Catalogue.Source.shortcut.Description" xml:space="preserve">
    <value>Gestione progetti</value>
  </data>
  <data name="Catalogue.Source.shortcut.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.onedrive" xml:space="preserve">
    <value>OneDrive</value>
  </data>
  <data name="Catalogue.Source.onedrive.Description" xml:space="preserve">
    <value>Documentazione</value>
  </data>
  <data name="Catalogue.Source.onedrive.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.teams" xml:space="preserve">
    <value>Microsoft Teams</value>
  </data>
  <data name="Catalogue.Source.teams.Description" xml:space="preserve">
    <value>Comunicazione</value>
  </data>
  <data name="Catalogue.Source.teams.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.publications" xml:space="preserve">
    <value>Publications</value>
  </data>
  <data name="Catalogue.Source.publications.Description" xml:space="preserve">
    <value>Documentazione</value>
  </data>
  <data name="Catalogue.Source.publications.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Source.github" xml:space="preserve">
    <value>GitHub</value>
  </data>
  <data name="Catalogue.Source.github.Description" xml:space="preserve">
    <value>Controllo del codice sorgente, issue e pull request</value>
  </data>
  <data name="Catalogue.Source.github.Unit" xml:space="preserve">
    <value>repository</value>
  </data>
  <data name="Catalogue.Ai.chat" xml:space="preserve">
    <value>Assistente IA</value>
  </data>
  <data name="Catalogue.Ai.chat.Description" xml:space="preserve">
    <value>L'assistente in chat, e il pulsante Chiedi su questo nei report.</value>
  </data>
  <data name="Catalogue.Limit.sources.max" xml:space="preserve">
    <value>Fonti di conoscenza in totale</value>
  </data>
  <data name="Catalogue.Limit.sources.max.Description" xml:space="preserve">
    <value>Su tutti i connettori, oltre al numero proprio di ciascun connettore.</value>
  </data>
  <data name="Catalogue.Limit.sources.max.Unit" xml:space="preserve">
    <value>fonti</value>
  </data>
  <data name="Catalogue.Limit.sources.max.AbsentMeans" xml:space="preserve">
    <value>Nessun limite.</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees" xml:space="preserve">
    <value>Quota dipendenti</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees.Description" xml:space="preserve">
    <value>Detentori di conoscenza attualmente impiegati, secondo i loro periodi di impiego, e non esclusi. Il prodotto avvisa il cliente quando ce ne sono di più; non rifiuta nulla e non lascia nessuno fuori da un'analisi.</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees.Unit" xml:space="preserve">
    <value>dipendenti</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees.AbsentMeans" xml:space="preserve">
    <value>Nessuna quota.</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets" xml:space="preserve">
    <value>Risorse di conoscenza</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets.Description" xml:space="preserve">
    <value>Le risorse nel manifesto, che è ciò che un'analisi legge.</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets.Unit" xml:space="preserve">
    <value>risorse</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets.AbsentMeans" xml:space="preserve">
    <value>Nessun limite.</value>
  </data>
  <data name="Catalogue.Limit.analysis.history" xml:space="preserve">
    <value>Storico dei dati</value>
  </data>
  <data name="Catalogue.Limit.analysis.history.Description" xml:space="preserve">
    <value>Quanto indietro legge un'analisi.</value>
  </data>
  <data name="Catalogue.Limit.analysis.history.Unit" xml:space="preserve">
    <value>mesi</value>
  </data>
  <data name="Catalogue.Limit.analysis.history.AbsentMeans" xml:space="preserve">
    <value>Nessun limite.</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens" xml:space="preserve">
    <value>Budget di token IA</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens.Description" xml:space="preserve">
    <value>Token in ingresso e in uscita insieme, per periodo di budget, al Gateway IA.</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens.Unit" xml:space="preserve">
    <value>token</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens.AbsentMeans" xml:space="preserve">
    <value>Il valore predefinito del livello.</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm" xml:space="preserve">
    <value>Richieste IA al minuto</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm.Description" xml:space="preserve">
    <value>Richieste al minuto al Gateway IA.</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm.Unit" xml:space="preserve">
    <value>richieste al minuto</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm.AbsentMeans" xml:space="preserve">
    <value>Il valore predefinito del livello.</value>
  </data>
  <data name="Catalogue.Purpose.customer" xml:space="preserve">
    <value>Cliente</value>
  </data>
  <data name="Catalogue.Purpose.customer.Description" xml:space="preserve">
    <value>Venduta a un cliente.</value>
  </data>
  <data name="Catalogue.Purpose.demo" xml:space="preserve">
    <value>Demo</value>
  </data>
  <data name="Catalogue.Purpose.demo.Description" xml:space="preserve">
    <value>Per mostrare il prodotto: demo commerciali e installazioni dei partner.</value>
  </data>
  <data name="Catalogue.Purpose.internal" xml:space="preserve">
    <value>Interna</value>
  </data>
  <data name="Catalogue.Purpose.internal.Description" xml:space="preserve">
    <value>Le nostre: installazioni di sviluppo, staging e test.</value>
  </data>
  <data name="Catalogue.Tier.standard" xml:space="preserve">
    <value>Standard</value>
  </data>
  <data name="Catalogue.Tier.enterprise" xml:space="preserve">
    <value>Enterprise</value>
  </data>
  <data name="Catalogue.Tier.none" xml:space="preserve">
    <value>Nessun livello</value>
  </data>
  <data name="Catalogue.Tier.other" xml:space="preserve">
    <value>Altro</value>
  </data>
  <data name="Catalogue.AiPeriod.none" xml:space="preserve">
    <value>Il valore predefinito del livello</value>
  </data>
  <data name="Catalogue.AiPeriod.month" xml:space="preserve">
    <value>Un mese di calendario (UTC)</value>
  </data>
  <data name="Catalogue.AiPeriod.30d" xml:space="preserve">
    <value>30 giorni, a scorrere dalla registrazione</value>
  </data>
  <data name="Js.Summary.All" xml:space="preserve">
    <value>Tutti {0}</value>
  </data>
  <data name="Js.Summary.None" xml:space="preserve">
    <value>Nessuno</value>
  </data>
  <data name="Js.Summary.Of" xml:space="preserve">
    <value>{0} di {1}</value>
  </data>
  <data name="Js.Summary.Named" xml:space="preserve">
    <value>{0}: {1}</value>
  </data>
  <data name="Js.Summary.NamedOff" xml:space="preserve">
    <value>{0} - disattivi: {1}</value>
  </data>
  <data name="Js.Summary.WithCount" xml:space="preserve">
    <value>{0} con un numero</value>
  </data>
  <data name="Js.Summary.InTotal" xml:space="preserve">
    <value>{0} in totale</value>
  </data>
  <data name="Js.Summary.InTotalUnreadable" xml:space="preserve">
    <value>nessuna in totale (limite illeggibile)</value>
  </data>
  <data name="Js.Summary.NoLimit" xml:space="preserve">
    <value>{0}, nessun limite</value>
  </data>
  <data name="Js.Summary.Employees" xml:space="preserve">
    <value>{0} dipendenti (quota)</value>
  </data>
  <data name="Js.Summary.EmployeesUnreadable" xml:space="preserve">
    <value>0 dipendenti (quota illeggibile)</value>
  </data>
  <data name="Js.Summary.Assets" xml:space="preserve">
    <value>{0} risorse di conoscenza</value>
  </data>
  <data name="Js.Summary.AssetsUnreadable" xml:space="preserve">
    <value>nessuna risorsa di conoscenza (limite illeggibile)</value>
  </data>
  <data name="Js.Summary.History" xml:space="preserve">
    <value>{0} mesi di storico</value>
  </data>
  <data name="Js.Summary.HistoryUnreadable" xml:space="preserve">
    <value>nessun mese di storico (limite illeggibile)</value>
  </data>
  <data name="Js.Summary.NoLimits" xml:space="preserve">
    <value>Nessun limite</value>
  </data>
  <data name="Js.Summary.AssistantOn" xml:space="preserve">
    <value>Assistente attivo</value>
  </data>
  <data name="Js.Summary.AssistantOff" xml:space="preserve">
    <value>Assistente disattivo</value>
  </data>
  <data name="Js.Summary.PeriodMonth" xml:space="preserve">
    <value>un mese di calendario</value>
  </data>
  <data name="Js.Summary.Period30d" xml:space="preserve">
    <value>30 giorni</value>
  </data>
  <data name="Js.Summary.TokensUnreadable" xml:space="preserve">
    <value>nessun token (limite illeggibile)</value>
  </data>
  <data name="Js.Summary.TokensAPeriod" xml:space="preserve">
    <value>{0} token a periodo</value>
  </data>
  <data name="Js.Summary.TokensPer" xml:space="preserve">
    <value>{0} token per {1}</value>
  </data>
  <data name="Js.Summary.TierBudgetPer" xml:space="preserve">
    <value>il budget del livello per {0}</value>
  </data>
  <data name="Js.Summary.RequestsUnreadable" xml:space="preserve">
    <value>nessuna richiesta (limite illeggibile)</value>
  </data>
  <data name="Js.Summary.Requests" xml:space="preserve">
    <value>{0} richieste al minuto</value>
  </data>
  <data name="Js.Summary.TierDefaults" xml:space="preserve">
    <value>valori predefiniti del livello</value>
  </data>
  <data name="Js.Summary.UpTo" xml:space="preserve">
    <value>{0} fino a {1} {2}</value>
  </data>
  <data name="Js.Summary.UpToUnreadable" xml:space="preserve">
    <value>{0} nessuna (numero illeggibile)</value>
  </data>
  <data name="Js.Overview.New" xml:space="preserve">
    <value>Nuove</value>
  </data>
  <data name="Js.Overview.Reissued" xml:space="preserve">
    <value>Riemesse</value>
  </data>
  <data name="Js.Overview.Active" xml:space="preserve">
    <value>Attive</value>
  </data>
  <data name="Generic.Any" xml:space="preserve">
    <value>Qualsiasi</value>
  </data>
  <data name="Generic.AnyTime" xml:space="preserve">
    <value>In qualsiasi momento</value>
  </data>
  <data name="Generic.Cancel" xml:space="preserve">
    <value>Annulla</value>
  </data>
  <data name="Generic.ExportCsv" xml:space="preserve">
    <value>Esporta CSV</value>
  </data>
  <data name="Js.Usage.Billions" xml:space="preserve">
    <value>{0} mld</value>
  </data>
  <data name="Js.Usage.Millions" xml:space="preserve">
    <value>{0} mln</value>
  </data>
  <data name="Js.Usage.Thousands" xml:space="preserve">
    <value>{0} k</value>
  </data>
  <data name="Gateway.At" xml:space="preserve">
    <value>su</value>
  </data>
  <data name="Gateway.NotReported" xml:space="preserve">
    <value>Non riportato</value>
  </data>
  <data name="Gateway.NotReported.Lower" xml:space="preserve">
    <value>non riportato</value>
  </data>
  <data name="Gateway.Of" xml:space="preserve">
    <value>di {0}</value>
  </data>
  <data name="Gateway.Tokens" xml:space="preserve">
    <value>{0} token</value>
  </data>
  <data name="Gateway.Days" xml:space="preserve">
    <value>{0} giorni</value>
  </data>
  <data name="Gateway.Days.One" xml:space="preserve">
    <value>1 giorno</value>
  </data>
  <data name="Gateway.Since" xml:space="preserve">
    <value>dal {0}</value>
  </data>
  <data name="Gateway.Revoke" xml:space="preserve">
    <value>Revoca</value>
  </data>
  <data name="Gateway.Restore" xml:space="preserve">
    <value>Ripristina</value>
  </data>
  <data name="Gateway.Reason" xml:space="preserve">
    <value>Motivo</value>
  </data>
  <data name="Gateway.Reason.Required" xml:space="preserve">
    <value>Indica il motivo: il registro di audit lo conserva.</value>
  </data>
  <data name="Gateway.Reason.Length" xml:space="preserve">
    <value>Un motivo è lungo da 3 a 500 caratteri.</value>
  </data>
  <data name="Gateway.YourName" xml:space="preserve">
    <value>Il tuo nome</value>
  </data>
  <data name="Gateway.YourName.Required" xml:space="preserve">
    <value>Inserisci il tuo nome: con la password condivisa è l'unica traccia di chi ha fatto questo.</value>
  </data>
  <data name="Gateway.YourName.Length" xml:space="preserve">
    <value>Un nome ha al massimo 100 caratteri.</value>
  </data>
  <data name="Gateway.SharedPassword.NameHelp" xml:space="preserve">
    <value>Hai effettuato l'accesso con la password condivisa, che non identifica nessuno. Il registro di audit registra questo come chi hai detto di essere, e non prova nulla.</value>
  </data>
  <data name="Gateway.RecordedAs" xml:space="preserve">
    <value>Registrato come {0}, qui e nel log del gateway.</value>
  </data>
  <data name="Gateway.CopyId" xml:space="preserve">
    <value>Copia l'id</value>
  </data>
  <data name="Gateway.CopyWholeId" xml:space="preserve">
    <value>Copia l'id completo</value>
  </data>
  <data name="Gateway.CopyId.Aria" xml:space="preserve">
    <value>Copia l'id di installazione {0}</value>
  </data>
  <data name="Gateway.Row.evaluation" xml:space="preserve">
    <value>Valutazione</value>
  </data>
  <data name="Gateway.Row.standard" xml:space="preserve">
    <value>Standard</value>
  </data>
  <data name="Gateway.Row.enterprise" xml:space="preserve">
    <value>Enterprise</value>
  </data>
  <data name="Gateway.Status.active" xml:space="preserve">
    <value>Attiva</value>
  </data>
  <data name="Gateway.Status.revoked" xml:space="preserve">
    <value>Revocata</value>
  </data>
  <data name="Gateway.Status.revoked.Lower" xml:space="preserve">
    <value>revocata</value>
  </data>
  <data name="Gateway.Seen.day" xml:space="preserve">
    <value>Nell'ultimo giorno</value>
  </data>
  <data name="Gateway.Seen.week" xml:space="preserve">
    <value>Nell'ultima settimana</value>
  </data>
  <data name="Gateway.Seen.month" xml:space="preserve">
    <value>Nell'ultimo mese</value>
  </data>
  <data name="Gateway.Seen.longer" xml:space="preserve">
    <value>Da più di un mese</value>
  </data>
  <data name="Gateway.Sort.created" xml:space="preserve">
    <value>Registrate più di recente</value>
  </data>
  <data name="Gateway.Sort.last_seen" xml:space="preserve">
    <value>Ultimo contatto</value>
  </data>
  <data name="Gateway.Sort.tokens_used" xml:space="preserve">
    <value>Token usati</value>
  </data>
  <data name="Gateway.NoUsageYet.Title" xml:space="preserve">
    <value>Il gateway non riporta ancora l'utilizzo</value>
  </data>
  <data name="Gateway.NoWriteToken.Title" xml:space="preserve">
    <value>La console non ha un token di scrittura</value>
  </data>
  <data name="Gateway.NoWriteToken.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt;, l'&lt;code&gt;Admin__Token&lt;/code&gt; del gateway, non è in Key Vault, quindi la console legge il gateway e non lo modifica. Caricarlo è il punto B3 di &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.NoWriteToken.Short" xml:space="preserve">
    <value>La console non ha un token di scrittura: &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; non è in Key Vault, quindi legge il gateway e non lo modifica.</value>
  </data>
  <data name="Gateway.ViewNotDo.Title" xml:space="preserve">
    <value>Puoi vederlo, non farlo</value>
  </data>
  <data name="Gateway.ViewNotDo.Detail" xml:space="preserve">
    <value>Hai effettuato l'accesso come {0}, che non detiene {1}. Un Amministratore lo concede nella pagina Utenti.</value>
  </data>
  <data name="Gateway.Write.WriteRefused.Title" xml:space="preserve">
    <value>Il gateway ha rifiutato il token di scrittura della console</value>
  </data>
  <data name="Gateway.Write.WriteRefused.Detail" xml:space="preserve">
    <value>Ha risposto 403: conosce il token e non gli permette di scrivere. &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; contiene il token di lettura del gateway; deve essere il suo &lt;code&gt;Admin__Token&lt;/code&gt;. Nulla è stato modificato.</value>
  </data>
  <data name="Gateway.Write.TokenRefused.Title" xml:space="preserve">
    <value>Il gateway ha rifiutato il token della console</value>
  </data>
  <data name="Gateway.Write.TokenRefused.Detail" xml:space="preserve">
    <value>Ha risposto 401: &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; non è nessuno dei suoi token. Deve essere l'&lt;code&gt;Admin__Token&lt;/code&gt; del gateway per lo stesso ambiente. Nulla è stato modificato.</value>
  </data>
  <data name="Gateway.Write.NotConfigured.Detail" xml:space="preserve">
    <value>Nulla è stato inviato. &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; non è in Key Vault.</value>
  </data>
  <data name="Gateway.Write.RequestRefused.Title" xml:space="preserve">
    <value>Il gateway ha rifiutato ciò che la console ha inviato</value>
  </data>
  <data name="Gateway.Write.RequestRefused.Detail" xml:space="preserve">
    <value>Ha risposto 400, un difetto della console e non un'interruzione; nulla è stato modificato.</value>
  </data>
  <data name="Gateway.Requests.AMinute" xml:space="preserve">
    <value>{0} al minuto</value>
  </data>
  <data name="Gateway.Requests.PerSeconds" xml:space="preserve">
    <value>{0} ogni {1} secondi</value>
  </data>
  <data name="Gateway.Period.Month" xml:space="preserve">
    <value>al mese di calendario, UTC</value>
  </data>
  <data name="Gateway.Period.Rolling" xml:space="preserve">
    <value>ogni 30 giorni, a scorrere dalla registrazione</value>
  </data>
  <data name="Gateway.Period.Other" xml:space="preserve">
    <value>per "{0}"</value>
  </data>
  <data name="Gateway.PeriodName.Month" xml:space="preserve">
    <value>un mese di calendario</value>
  </data>
  <data name="Gateway.PeriodName.Rolling" xml:space="preserve">
    <value>trenta giorni a scorrere</value>
  </data>
  <data name="Gateway.Range.Unbounded" xml:space="preserve">
    <value>un numero intero, 1 o più</value>
  </data>
  <data name="Gateway.Range.UpTo" xml:space="preserve">
    <value>un numero intero da 1 a {0}</value>
  </data>
  <data name="Gateway.Allowance.ItsRows" xml:space="preserve">
    <value>della sua riga</value>
  </data>
  <data name="Gateway.Allowance.TheRows" xml:space="preserve">
    <value>della riga {0}</value>
  </data>
  <data name="Gateway.Allowance.TheLicences" xml:space="preserve">
    <value>della licenza</value>
  </data>
  <data name="Gateway.Allowance.AMinute" xml:space="preserve">
    <value>{0} al minuto, {1}</value>
  </data>
  <data name="Gateway.Allowance.TokensOwner" xml:space="preserve">
    <value>{0} {1}, {2}</value>
  </data>
  <data name="Gateway.Allowance.TokensOwners" xml:space="preserve">
    <value>{0} {1}: il numero {2}, il periodo {3}</value>
  </data>
  <data name="Gateway.Allowance.Period.Month" xml:space="preserve">
    <value>al mese di calendario</value>
  </data>
  <data name="Gateway.Allowance.Period.30d" xml:space="preserve">
    <value>ogni 30 giorni</value>
  </data>
  <data name="Gateway.Allowance.Period.APeriod" xml:space="preserve">
    <value>a periodo</value>
  </data>
  <data name="Gateway.Allowance.Period.Other" xml:space="preserve">
    <value>per periodo "{0}"</value>
  </data>
  <data name="Gateway.Unavailable.NotConfigured.Title" xml:space="preserve">
    <value>Il gateway non è configurato</value>
  </data>
  <data name="Gateway.Unavailable.NotConfigured.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminToken&lt;/code&gt; non è in Key Vault, quindi la console non chiede nulla al gateway. Caricarlo è il punto B3 di &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Unavailable.NoStatus.Title" xml:space="preserve">
    <value>Il gateway non riporta ancora lo stato</value>
  </data>
  <data name="Gateway.Unavailable.NoStatus.Detail" xml:space="preserve">
    <value>Elenca le sue installazioni ma risponde 404 a &lt;code&gt;/admin/status&lt;/code&gt;: è anteriore a kf-ai-gateway#37. Non c'è nulla da mostrare qui finché non sarà distribuita. Le pagine del registro non ne risentono.</value>
  </data>
  <data name="Gateway.Unavailable.NoFilters.Title" xml:space="preserve">
    <value>Il gateway non filtra ancora le sue installazioni</value>
  </data>
  <data name="Gateway.Unavailable.NoFilters.Detail" xml:space="preserve">
    <value>Ha risposto senza i filtri, l'ordine o la pagina richiesti: è anteriore a kf-ai-gateway#38, e avrebbe elencato le sue installazioni più recenti come se li avesse applicati. Azzera i filtri per vederle.</value>
  </data>
  <data name="Gateway.Unavailable.Unknown.Title" xml:space="preserve">
    <value>Il gateway non conosce alcuna installazione con questo id</value>
  </data>
  <data name="Gateway.Unavailable.Unknown.Detail" xml:space="preserve">
    <value>Un'installazione si registra la prima volta che usa l'IA, quindi una che non l'ha mai fatto non è sul gateway, e un id di un altro ambiente è sul gateway di quell'ambiente. &lt;code&gt;docs/Operations.md&lt;/code&gt; dice cosa controllare.</value>
  </data>
  <data name="Gateway.Overview.Lead" xml:space="preserve">
    <value>Cosa dice di sé il gateway{0}, dal suo &lt;code&gt;GET /admin/status&lt;/code&gt;: cosa è distribuito, cosa ha speso l'intero servizio rispetto al suo tetto, e il parco installazioni in cifre; e, dal suo registro giornaliero degli utilizzi, gli ultimi trenta giorni del parco. Letto con il token di sola lettura; nulla in questa pagina modifica il gateway.</value>
  </data>
  <data name="Gateway.Overview.Status" xml:space="preserve">
    <value>Stato</value>
  </data>
  <data name="Gateway.Overview.Status.AsOf" xml:space="preserve">
    <value>Alle {0} UTC. La console chiede al massimo ogni {1} secondi.</value>
  </data>
  <data name="Gateway.Overview.Version" xml:space="preserve">
    <value>Versione</value>
  </data>
  <data name="Gateway.Overview.Started" xml:space="preserve">
    <value>Avviato</value>
  </data>
  <data name="Gateway.Overview.Up" xml:space="preserve">
    <value>Attivo da {0}</value>
  </data>
  <data name="Gateway.Overview.Up.Days" xml:space="preserve">
    <value>{0} giorni</value>
  </data>
  <data name="Gateway.Overview.Up.Hours" xml:space="preserve">
    <value>{0} ore</value>
  </data>
  <data name="Gateway.Overview.Up.UnderAnHour" xml:space="preserve">
    <value>meno di un'ora</value>
  </data>
  <data name="Gateway.Overview.Telemetry" xml:space="preserve">
    <value>Telemetria</value>
  </data>
  <data name="Gateway.Overview.Telemetry.Connected" xml:space="preserve">
    <value>Application Insights collegato</value>
  </data>
  <data name="Gateway.Overview.Telemetry.None" xml:space="preserve">
    <value>Nessuna destinazione di telemetria</value>
  </data>
  <data name="Gateway.Overview.Telemetry.None.Detail" xml:space="preserve">
    <value>Nulla raggiunge Application Insights; gli avvisi del gateway non vedono nulla.</value>
  </data>
  <data name="Gateway.Brake.Title" xml:space="preserve">
    <value>Il freno globale</value>
  </data>
  <data name="Gateway.Brake.Lead" xml:space="preserve">
    <value>I token spesi dall'intero servizio in questo mese di calendario, rispetto al tetto che mette tutti in pausa.</value>
  </data>
  <data name="Gateway.Brake.NotReported" xml:space="preserve">
    <value>Il gateway non ha riportato il freno.</value>
  </data>
  <data name="Gateway.Brake.Off.Title" xml:space="preserve">
    <value>Il freno globale è disattivato</value>
  </data>
  <data name="Gateway.Brake.Off.Detail" xml:space="preserve">
    <value>Non è impostato alcun tetto, quindi dietro il servizio c'è solo il limite del fornitore. Impostarne uno è &lt;code&gt;GlobalTokenCeiling&lt;/code&gt; nella riga di policy del gateway (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Brake.SpentSince" xml:space="preserve">
    <value>Spesi dal {0}: {1} token.</value>
  </data>
  <data name="Gateway.Brake.On.Title" xml:space="preserve">
    <value>Il freno globale è attivo</value>
  </data>
  <data name="Gateway.Brake.On.Detail" xml:space="preserve">
    <value>Ogni chat di ogni installazione è rifiutata con &lt;code&gt;503 service_paused&lt;/code&gt; finché il tetto non viene alzato. Un riavvio non lo rilascia, e il contatore della spesa non è modificabile dall'operatore: alzare il tetto è tutto il rilascio, dalla chat successiva.</value>
  </data>
  <data name="Gateway.Brake.ChangeCeiling" xml:space="preserve">
    <value>Cambia il tetto globale</value>
  </data>
  <data name="Gateway.Brake.OfTokens" xml:space="preserve">
    <value>{0} di {1} token</value>
  </data>
  <data name="Gateway.Brake.Aria" xml:space="preserve">
    <value>Token spesi rispetto al tetto</value>
  </data>
  <data name="Gateway.Brake.PeriodEnds" xml:space="preserve">
    <value>Il periodo termina il {0}, quando il contatore riparte.</value>
  </data>
  <data name="Gateway.Brake.Close" xml:space="preserve">
    <value>Vicino al tetto: il freno scatta per tutti quando viene raggiunto.</value>
  </data>
  <data name="Gateway.Overview.LastDays" xml:space="preserve">
    <value>Gli ultimi {0} giorni</value>
  </data>
  <data name="Gateway.Overview.LastDays.Lead" xml:space="preserve">
    <value>Token, richieste e rifiuti al giorno, dal registro giornaliero degli utilizzi del gateway.</value>
  </data>
  <data name="Gateway.Usage.TokensADay" xml:space="preserve">
    <value>Token al giorno</value>
  </data>
  <data name="Gateway.Usage.RequestsADay" xml:space="preserve">
    <value>Richieste al giorno</value>
  </data>
  <data name="Gateway.Overview.TokensADay.Lead" xml:space="preserve">
    <value>Gli ultimi {0} giorni di tutto il parco, per la riga servita ora a ciascuna installazione: {1} token in totale.</value>
  </data>
  <data name="Gateway.Overview.RefusalsADay" xml:space="preserve">
    <value>Rifiuti al giorno</value>
  </data>
  <data name="Gateway.Usage.Totals" xml:space="preserve">
    <value>Di {0} richieste, {1} rifiutate per limite di velocità, {2} per budget esaurito e {3} fallite a monte.</value>
  </data>
  <data name="Gateway.Overview.Usage.Footnote" xml:space="preserve">
    <value>Giorni in UTC, oggi finora. I token si contano al termine di ogni chat; richieste, rifiuti ed errori a monte raggiungono il registro del gateway una volta al minuto. Un'installazione conta sotto la riga che le è servita ora, per tutto l'intervallo. I giorni precedenti alla tenuta del registro da parte del gateway (kf-ai-gateway#41) sono a zero.</value>
  </data>
  <data name="Gateway.Overview.NoFleet" xml:space="preserve">
    <value>Il gateway non ha riportato il suo parco installazioni.</value>
  </data>
  <data name="Gateway.Overview.ActiveRevoked" xml:space="preserve">
    <value>{0} attive, {1} revocate</value>
  </data>
  <data name="Gateway.Overview.Row.evaluation" xml:space="preserve">
    <value>Sulla riga di valutazione: nessuna licenza, o una decaduta</value>
  </data>
  <data name="Gateway.Overview.Row.standard" xml:space="preserve">
    <value>Con licenza, servite dalla riga standard</value>
  </data>
  <data name="Gateway.Overview.Row.enterprise" xml:space="preserve">
    <value>Con licenza, servite dalla riga enterprise</value>
  </data>
  <data name="Gateway.Overview.SeenRecently" xml:space="preserve">
    <value>Viste di recente</value>
  </data>
  <data name="Gateway.Overview.SeenRecently.Lead" xml:space="preserve">
    <value>Installazioni che hanno fatto una chiamata autenticata al gateway. Un'installazione che non usa mai l'IA non si registra mai, quindi non è in nessuna di queste.</value>
  </data>
  <data name="Gateway.Overview.Last24h" xml:space="preserve">
    <value>Ultime 24 ore</value>
  </data>
  <data name="Gateway.Overview.Last7d" xml:space="preserve">
    <value>Ultimi 7 giorni</value>
  </data>
  <data name="Gateway.Overview.Last30d" xml:space="preserve">
    <value>Ultimi 30 giorni</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded" xml:space="preserve">
    <value>Livello della licenza non registrato</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.Lead" xml:space="preserve">
    <value>Installazioni con licenza la cui licenza è arrivata prima che il gateway leggesse &lt;code&gt;tier&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.None" xml:space="preserve">
    <value>Ogni installazione con licenza ha il livello della licenza registrato.</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.Some.One" xml:space="preserve">
    <value>1 installazione è servita dalla riga standard qualunque cosa dica la licenza, finché kf-app non invia di nuovo la licenza. Cerca un cliente Enterprise tra queste prima di alzare la quota di &lt;code&gt;enterprise&lt;/code&gt; (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.Some.Many" xml:space="preserve">
    <value>{0} installazioni sono servite dalla riga standard qualunque cosa dica la licenza, finché kf-app non invia di nuovo la licenza. Cerca un cliente Enterprise tra queste prima di alzare la quota di &lt;code&gt;enterprise&lt;/code&gt; (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Overview.Footnote" xml:space="preserve">
    <value>Le righe sono la quota servita a ciascuna installazione, non il livello sul filo, che chiama entrambe le righe con licenza &lt;code&gt;licensed&lt;/code&gt;. Questi sono i conteggi del gateway; quelli del registro sono nella Panoramica, e i due differiscono ovunque una licenza non sia mai stata installata su un'installazione che usa l'IA.</value>
  </data>
  <data name="Gateway.Overview.Footnote.Caller" xml:space="preserve">
    <value>Il gateway ha attribuito la richiesta di questa console a {0}, che è la verifica da fare prima di armare il limite di velocità di registrazione.</value>
  </data>
  <data name="Gateway.Card.Lead" xml:space="preserve">
    <value>Cosa dice di sé {0}, alle {1} UTC.</value>
  </data>
  <data name="Gateway.Card.Lead.NoHost" xml:space="preserve">
    <value>Il gateway, come la console l'ha visto l'ultima volta.</value>
  </data>
  <data name="Gateway.Card.Gateway" xml:space="preserve">
    <value>Gateway</value>
  </data>
  <data name="Gateway.Card.Answering" xml:space="preserve">
    <value>Risponde</value>
  </data>
  <data name="Gateway.Card.Version" xml:space="preserve">
    <value>Versione {0}</value>
  </data>
  <data name="Gateway.Card.Brake" xml:space="preserve">
    <value>Freno globale</value>
  </data>
  <data name="Gateway.Card.Brake.Off" xml:space="preserve">
    <value>Disattivato</value>
  </data>
  <data name="Gateway.Card.Brake.Off.Detail" xml:space="preserve">
    <value>{0} token spesi questo mese, nessun tetto</value>
  </data>
  <data name="Gateway.Card.Brake.Tripped" xml:space="preserve">
    <value>Scattato</value>
  </data>
  <data name="Gateway.Card.Brake.Tripped.Detail" xml:space="preserve">
    <value>Ogni chat è rifiutata finché il tetto non viene alzato</value>
  </data>
  <data name="Gateway.Card.Brake.Used" xml:space="preserve">
    <value>{0} di {1} token questo mese</value>
  </data>
  <data name="Gateway.Card.Active" xml:space="preserve">
    <value>{0} attive</value>
  </data>
  <data name="Gateway.Card.Seen" xml:space="preserve">
    <value>{0} viste nell'ultimo giorno, {1} revocate</value>
  </data>
  <data name="Gateway.Installations.Lead" xml:space="preserve">
    <value>Ogni installazione che il gateway{0} ha registrato, filtrata, ordinata e impaginata dal gateway stesso, con quanto ciascuna ha usato della sua quota e il cliente del registro per la licenza che detiene. Un'installazione si registra la prima volta che usa l'IA. Letto con il token di sola lettura; nulla in questa pagina modifica il gateway.</value>
  </data>
  <data name="Gateway.Installations.Search" xml:space="preserve">
    <value>Id di installazione o id di licenza</value>
  </data>
  <data name="Gateway.Installations.Search.Placeholder" xml:space="preserve">
    <value>L'id completo</value>
  </data>
  <data name="Gateway.Installations.Order" xml:space="preserve">
    <value>Ordine</value>
  </data>
  <data name="Gateway.Installations.Row" xml:space="preserve">
    <value>Riga</value>
  </data>
  <data name="Gateway.Installations.Status" xml:space="preserve">
    <value>Stato</value>
  </data>
  <data name="Gateway.Installations.LastSeen" xml:space="preserve">
    <value>Ultimo contatto</value>
  </data>
  <data name="Gateway.Installations.Below" xml:space="preserve">
    <value>Versione app inferiore a</value>
  </data>
  <data name="Gateway.Installations.LongGone" xml:space="preserve">
    <value>Da più di un mese è in ordine di ultimo contatto, dal più recente: il gateway filtra solo su visto-dal, quindi la console elenca ciò che viene dopo le installazioni viste nell'ultimo mese.</value>
  </data>
  <data name="Gateway.Installations.NotAsked" xml:space="preserve">
    <value>Il gateway non è stato interrogato</value>
  </data>
  <data name="Gateway.Installations.Problem.Version" xml:space="preserve">
    <value>"{0}" non è una versione dell'applicazione. Scrivine una come 1.7.0; una prerelease conta come la sua release.</value>
  </data>
  <data name="Gateway.Installations.Problem.Search" xml:space="preserve">
    <value>La ricerca accetta un id di installazione o di licenza, completo: il gateway cerca gli id esattamente, non per parte.</value>
  </data>
  <data name="Gateway.Installations.HoldingLicence" xml:space="preserve">
    <value>Con l'id di licenza {0}</value>
  </data>
  <data name="Gateway.Installations.HoldingLicence.Lead" xml:space="preserve">
    <value>Nessuna installazione ha questo id, quindi è letto come id di licenza: ogni installazione che lo detiene, revocata o no, per quanto vecchia.</value>
  </data>
  <data name="Gateway.Installations.HoldingLicence.Row" xml:space="preserve">
    <value>La sua riga nel registro è {0}.</value>
  </data>
  <data name="Gateway.Installations.Count.One" xml:space="preserve">
    <value>1 installazione</value>
  </data>
  <data name="Gateway.Installations.Count.Many" xml:space="preserve">
    <value>{0} installazioni</value>
  </data>
  <data name="Gateway.Installations.Count.OneMatch" xml:space="preserve">
    <value>1 installazione corrisponde</value>
  </data>
  <data name="Gateway.Installations.Count.ManyMatch" xml:space="preserve">
    <value>{0} installazioni corrispondono</value>
  </data>
  <data name="Gateway.Installations.OrderLead" xml:space="preserve">
    <value>{0} per prime. La riga è la quota servita a ciascuna, non il livello sul filo, che chiama entrambe le righe con licenza &lt;code&gt;licensed&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Installations.NoUsageYet.Detail" xml:space="preserve">
    <value>Ha risposto senza una quota o un totale: è anteriore a kf-ai-gateway#38. Queste sono le più recenti che elenca, non impaginate, e la riga è il suo livello sul filo.</value>
  </data>
  <data name="Gateway.Installations.Column.LastSeenUtc" xml:space="preserve">
    <value>Ultimo contatto, UTC</value>
  </data>
  <data name="Gateway.Installations.Column.Licence" xml:space="preserve">
    <value>Licenza</value>
  </data>
  <data name="Gateway.Installations.Empty.Searched" xml:space="preserve">
    <value>Nessuna installazione ha questo id, e nessuna lo detiene come licenza.</value>
  </data>
  <data name="Gateway.Installations.Empty.Filtered" xml:space="preserve">
    <value>Nessuna installazione corrisponde a questi filtri.</value>
  </data>
  <data name="Gateway.Installations.Empty" xml:space="preserve">
    <value>Il gateway non ha ancora installazioni.</value>
  </data>
  <data name="Gateway.Licence.NotInRegister.Title" xml:space="preserve">
    <value>Emessa offline senza --register-csv, o dalla vecchia copia dello strumento in kf-app</value>
  </data>
  <data name="Gateway.Licence.RegisterUnread" xml:space="preserve">
    <value>Registro non letto</value>
  </data>
  <data name="Gateway.Licence.RegisterUnread.Title" xml:space="preserve">
    <value>Il registro non ha un database, o non è stato possibile leggerlo</value>
  </data>
  <data name="Gateway.Licence.IdNotRecorded" xml:space="preserve">
    <value>Con licenza, id non registrato</value>
  </data>
  <data name="Gateway.Licence.IdNotRecorded.Title" xml:space="preserve">
    <value>Con licenza da prima che kf-ai-gateway#35 registrasse gli id di licenza; ne ha uno quando kf-app invia di nuovo la licenza</value>
  </data>
  <data name="Gateway.Licence.None" xml:space="preserve">
    <value>Nessuna licenza</value>
  </data>
  <data name="Gateway.Installation.Title" xml:space="preserve">
    <value>Installazione</value>
  </data>
  <data name="Gateway.Installation.Changed.Revoked" xml:space="preserve">
    <value>&lt;strong&gt;Revocata.&lt;/strong&gt; Da ora il gateway rifiuta ogni sua chiamata. La voce è nel registro di audit.</value>
  </data>
  <data name="Gateway.Installation.Changed.Restored" xml:space="preserve">
    <value>&lt;strong&gt;Ripristinata.&lt;/strong&gt; Dalla sua prossima chiamata il gateway le serve di nuovo la sua riga. La voce è nel registro di audit.</value>
  </data>
  <data name="Gateway.Installation.Changed.SeeIt" xml:space="preserve">
    <value>Vedila</value>
  </data>
  <data name="Gateway.Installation.NoLookup.Title" xml:space="preserve">
    <value>Il gateway non cerca ancora le installazioni per id</value>
  </data>
  <data name="Gateway.Installation.NoLookup.Detail" xml:space="preserve">
    <value>È anteriore a kf-ai-gateway#38, quindi la console ha cercato tra le 500 installazioni più recenti che elenca, e questa non è tra quelle.</value>
  </data>
  <data name="Gateway.Installation.OnGateway" xml:space="preserve">
    <value>Sul gateway</value>
  </data>
  <data name="Gateway.Installation.OnGateway.Lead" xml:space="preserve">
    <value>Cosa ne conserva il gateway{0}. Non la sua credenziale, che il gateway non restituisce.</value>
  </data>
  <data name="Gateway.Installation.AppVersion" xml:space="preserve">
    <value>Versione app</value>
  </data>
  <data name="Gateway.Installation.ServedRow" xml:space="preserve">
    <value>Servita dalla riga {0}</value>
  </data>
  <data name="Gateway.Installation.RevokedAt" xml:space="preserve">
    <value>Revocata il {0}</value>
  </data>
  <data name="Gateway.Installation.FirstEnrolled" xml:space="preserve">
    <value>Prima registrazione</value>
  </data>
  <data name="Gateway.Installation.Allowance" xml:space="preserve">
    <value>Quota e utilizzo</value>
  </data>
  <data name="Gateway.Installation.Allowance.Lead" xml:space="preserve">
    <value>I numeri che il suo &lt;code&gt;GET /v1/installation&lt;/code&gt; riporta, letti dallo stesso codice, quindi sono ciò che mostra la schermata AI Manager del cliente.</value>
  </data>
  <data name="Gateway.Installation.ServedNothing.Title" xml:space="preserve">
    <value>Non servita finché revocata</value>
  </data>
  <data name="Gateway.Installation.ServedNothing.Detail" xml:space="preserve">
    <value>Ogni sua chiamata è rifiutata con &lt;code&gt;403 installation_revoked&lt;/code&gt; dal {0}, compresa una fatta dopo che si registra di nuovo.</value>
  </data>
  <data name="Gateway.Installation.ServedNothing.IfRestored" xml:space="preserve">
    <value>Quanto segue è ciò che le verrebbe servito se fosse ripristinata.</value>
  </data>
  <data name="Gateway.Installation.NoUsageYet.Detail" xml:space="preserve">
    <value>Ha risposto senza una quota: è anteriore a kf-ai-gateway#38. Finché non sarà distribuita, i numeri sono solo nel &lt;code&gt;GET /v1/installation&lt;/code&gt; dell'installazione, che il cliente vede e la console no.</value>
  </data>
  <data name="Gateway.Installation.Requests" xml:space="preserve">
    <value>Richieste</value>
  </data>
  <data name="Gateway.Installation.Requests.Remaining" xml:space="preserve">
    <value>{0} di {1} rimanenti; una richiesta si libera alle {2}</value>
  </data>
  <data name="Gateway.Installation.Requests.InMemory" xml:space="preserve">
    <value>Contate nella memoria del gateway, quindi un riavvio le legge di nuovo piene: la panoramica del gateway dice quando è stato avviato l'ultima volta.</value>
  </data>
  <data name="Gateway.Installation.Tokens" xml:space="preserve">
    <value>Token</value>
  </data>
  <data name="Gateway.Installation.Tokens.UsedOf" xml:space="preserve">
    <value>{0} usati di {1}</value>
  </data>
  <data name="Gateway.Installation.Tokens.PeriodEnds" xml:space="preserve">
    <value>Questo periodo termina il {0}, quando il conteggio riparte. I giorni precedenti sono nella sua cronologia utilizzo, sotto.</value>
  </data>
  <data name="Gateway.Installation.LongestReply" xml:space="preserve">
    <value>Risposta più lunga</value>
  </data>
  <data name="Gateway.Installation.LongestReply.Detail" xml:space="preserve">
    <value>{0} token, {1}. Una licenza non la imposta mai.</value>
  </data>
  <data name="Gateway.Installation.ZeroLimit.Title" xml:space="preserve">
    <value>Un limite di 0 non consente nulla</value>
  </data>
  <data name="Gateway.Installation.ZeroLimit.Detail" xml:space="preserve">
    <value>La licenza conteneva un &lt;code&gt;ai.tokens&lt;/code&gt; o &lt;code&gt;ai.rpm&lt;/code&gt; che il gateway non ha potuto leggere, e lo serve come 0. Riemetti la licenza con un numero che possa leggere.</value>
  </data>
  <data name="Gateway.Installation.History.Lead" xml:space="preserve">
    <value>I suoi ultimi {0} giorni dal registro giornaliero degli utilizzi del gateway, in giorni UTC, oggi finora.</value>
  </data>
  <data name="Gateway.Installation.History.Totals" xml:space="preserve">
    <value>{0} token e {1} richieste: {2} rifiutate per limite di velocità, {3} per budget esaurito e {4} fallite a monte.</value>
  </data>
  <data name="Gateway.Installation.HowManyDays" xml:space="preserve">
    <value>Quanti giorni</value>
  </data>
  <data name="Gateway.Installation.History.Footnote" xml:space="preserve">
    <value>I token si contano al termine di ogni chat; richieste, rifiuti ed errori a monte raggiungono il registro una volta al minuto. Un giorno senza richieste è a zero, come ogni giorno precedente alla tenuta del registro da parte del gateway (kf-ai-gateway#41).</value>
  </data>
  <data name="Gateway.Installation.ItsLicence" xml:space="preserve">
    <value>La sua licenza</value>
  </data>
  <data name="Gateway.Installation.ItsLicence.Lead" xml:space="preserve">
    <value>La licenza che il gateway ha accettato per essa, come il registro l'ha emessa.</value>
  </data>
  <data name="Gateway.Installation.Shared.Detail" xml:space="preserve">
    <value>Il gateway dice che questo id di licenza è detenuto da più di un'installazione non revocata. Una licenza copre una sola installazione: chiedi al cliente quale debba averla, poi revoca l'altra.</value>
  </data>
  <data name="Gateway.Installation.Shared.SeeAll" xml:space="preserve">
    <value>Vedile tutte</value>
  </data>
  <data name="Gateway.Installation.LicenceFiles" xml:space="preserve">
    <value>{0} file nel registro: una riemissione mantiene l'id, e questo è il più recente.</value>
  </data>
  <data name="Gateway.Installation.NotInRegister.Detail" xml:space="preserve">
    <value>Il gateway ha accettato una licenza che il registro non ha: emessa offline senza &lt;code class="text-nowrap"&gt;--register-csv&lt;/code&gt;, o dalla copia dello strumento in kf-app prima che kf-app#982 la eliminasse.</value>
  </data>
  <data name="Gateway.Installation.LicenceIdIs" xml:space="preserve">
    <value>Id licenza {0}</value>
  </data>
  <data name="Gateway.Installation.RegisterUnread.Detail" xml:space="preserve">
    <value>Non ha un database, o non ha risposto: il motivo è nel log della console.</value>
  </data>
  <data name="Gateway.Installation.IdNotRecorded.Detail" xml:space="preserve">
    <value>Con licenza, ma il gateway non ne conserva l'id: ha ricevuto la licenza prima che kf-ai-gateway#35 registrasse gli id, il 2026-09-26, e non ne ha finché kf-app non invia di nuovo la licenza. Su un kf-app con kf-app#968 basta caricarla di nuovo; kf-app 1.6.2 la invia solo alla prima registrazione.</value>
  </data>
  <data name="Gateway.Installation.OnEvaluation" xml:space="preserve">
    <value>In valutazione.</value>
  </data>
  <data name="Gateway.Installation.Refused.Reason" xml:space="preserve">
    <value>Il gateway ha rifiutato l'ultima licenza ricevuta: {0}.</value>
  </data>
  <data name="Gateway.Installation.Refused" xml:space="preserve">
    <value>Il gateway ha rifiutato l'ultima licenza ricevuta.</value>
  </data>
  <data name="Gateway.Installation.NoneSent" xml:space="preserve">
    <value>Non ha inviato al gateway una licenza che detiene ora: nessuna, o una decaduta o rimossa.</value>
  </data>
  <data name="Gateway.Installation.WhatToDo" xml:space="preserve">
    <value>Cosa fare per la sua quota</value>
  </data>
  <data name="Gateway.Installation.WhatToDo.Detail" xml:space="preserve">
    <value>La quota di un cliente cambia riemettendo la sua licenza con i numeri che deve contenere, installata da kf-app. Ciò che una licenza omette è della sua riga, che è policy e muove insieme ogni installazione su di essa. Non c'è alcuna deroga per una singola installazione, e mai qui (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Installation.Restore.Lead" xml:space="preserve">
    <value>Il ripristino le serve di nuovo la sua riga dalla sua prossima chiamata. Indichi il motivo nella pagina successiva, ed è registrato nell'audit.</value>
  </data>
  <data name="Gateway.Installation.Revoke.Lead" xml:space="preserve">
    <value>La revoca rifiuta ogni sua chiamata con &lt;code&gt;403 installation_revoked&lt;/code&gt;, nuova registrazione compresa, finché non viene ripristinata. Indichi il motivo nella pagina successiva, ed è registrato nell'audit.</value>
  </data>
  <data name="Gateway.Installation.ViewOnly" xml:space="preserve">
    <value>Puoi vedere questa installazione, non modificarla: serve {0}.</value>
  </data>
  <data name="Gateway.Change.Revoke.PageTitle" xml:space="preserve">
    <value>Revoca un'installazione</value>
  </data>
  <data name="Gateway.Change.Restore.PageTitle" xml:space="preserve">
    <value>Ripristina un'installazione</value>
  </data>
  <data name="Gateway.Change.Revoke.Title" xml:space="preserve">
    <value>Revoca l'installazione {0}</value>
  </data>
  <data name="Gateway.Change.Restore.Title" xml:space="preserve">
    <value>Ripristina l'installazione {0}</value>
  </data>
  <data name="Gateway.Change.Lead" xml:space="preserve">
    <value>Una modifica sul gateway{0} con il token di scrittura della console. È registrata nel registro di audit, con il tuo motivo, una volta che il gateway la conferma, e il gateway la registra nel proprio log sotto lo stesso nome.</value>
  </data>
  <data name="Gateway.Change.Unknown.Title" xml:space="preserve">
    <value>Il gateway non conosce più questa installazione</value>
  </data>
  <data name="Gateway.Change.Unknown.Detail" xml:space="preserve">
    <value>Ha risposto 404. Nulla è stato modificato.</value>
  </data>
  <data name="Gateway.Change.Unsure.Title" xml:space="preserve">
    <value>La console non ha potuto stabilire se il gateway abbia fatto la modifica</value>
  </data>
  <data name="Gateway.Change.Unsure.Detail" xml:space="preserve">
    <value>Apri la pagina dell'installazione per vederne lo stato prima di riprovare. Nessuna voce di audit è stata scritta.</value>
  </data>
  <data name="Gateway.Change.TheInstallation" xml:space="preserve">
    <value>L'installazione</value>
  </data>
  <data name="Gateway.Change.HeldBy" xml:space="preserve">
    <value>Detenuta da {0} installazioni</value>
  </data>
  <data name="Gateway.Change.WhatRevokeDoes" xml:space="preserve">
    <value>Cosa fa la revoca</value>
  </data>
  <data name="Gateway.Change.WhatRestoreDoes" xml:space="preserve">
    <value>Cosa fa il ripristino</value>
  </data>
  <data name="Gateway.Change.Revoke.Detail" xml:space="preserve">
    <value>Ogni sua chiamata è rifiutata con &lt;code&gt;403 installation_revoked&lt;/code&gt; dalla prossima: l'IA, la quota che legge, tutto. &lt;strong&gt;Registrarsi di nuovo non la aggira&lt;/strong&gt;: anche una nuova credenziale per cui si registra è rifiutata. Smette di contare come detentrice della sua licenza, quindi una licenza segnalata su due installazioni non è più segnalata se questa era la seconda. Il ripristino annulla tutto questo.</value>
  </data>
  <data name="Gateway.Change.OnlyHolder" xml:space="preserve">
    <value>Questa è l'unica installazione non revocata che detiene la licenza di {0}. La loro IA si ferma finché non viene ripristinata.</value>
  </data>
  <data name="Gateway.Change.Restore.Detail" xml:space="preserve">
    <value>Le è servita di nuovo la sua riga dalla sua prossima chiamata, e conta di nuovo come detentrice della sua licenza, quindi una licenza che condivide è segnalata di nuovo. La credenziale che ha continua a funzionare; non deve registrarsi di nuovo.</value>
  </data>
  <data name="Gateway.Change.AlreadyRevoked" xml:space="preserve">
    <value>È già revocata, dal {0}.</value>
  </data>
  <data name="Gateway.Change.RestoreIt" xml:space="preserve">
    <value>Ripristinala</value>
  </data>
  <data name="Gateway.Change.NotRevoked" xml:space="preserve">
    <value>Non è revocata.</value>
  </data>
  <data name="Gateway.Change.RevokeIt" xml:space="preserve">
    <value>Revocala</value>
  </data>
  <data name="Gateway.Change.Instead" xml:space="preserve">
    <value>invece.</value>
  </data>
  <data name="Gateway.Change.Revoke.Placeholder" xml:space="preserve">
    <value>Reinstallata; il cliente dice che il vecchio server non c'è più</value>
  </data>
  <data name="Gateway.Change.Restore.Placeholder" xml:space="preserve">
    <value>Revocata per errore</value>
  </data>
  <data name="Gateway.Change.Revoke.Submit" xml:space="preserve">
    <value>Revoca l'installazione</value>
  </data>
  <data name="Gateway.Change.Restore.Submit" xml:space="preserve">
    <value>Ripristina l'installazione</value>
  </data>
  <data name="Gateway.Usage.Lead" xml:space="preserve">
    <value>Ogni licenza in vigore nel registro, accanto a quanto il gateway{0} dice che la sua installazione ha usato in questo periodo e le resta, e ha speso nel mese di calendario precedente, dal suo registro giornaliero degli utilizzi. Il registro dice cosa contiene ogni licenza; il gateway dice cosa le è servito e cosa ha speso. Letto alle {1} UTC con il token di sola lettura; nulla in questa pagina modifica l'uno o l'altro.</value>
  </data>
  <data name="Gateway.Usage.RegisterUnread.Detail" xml:space="preserve">
    <value>Ogni riga di questa pagina è una licenza nel registro, quindi non c'è nulla da elencare. Il motivo è nel log della console, sotto "The usage by licence could not read the licence register".</value>
  </data>
  <data name="Gateway.Usage.Allowance" xml:space="preserve">
    <value>Quota</value>
  </data>
  <data name="Gateway.Usage.Allowance.standard" xml:space="preserve">
    <value>Standard: livello standard, nessuno o sconosciuto</value>
  </data>
  <data name="Gateway.Usage.Allowance.enterprise" xml:space="preserve">
    <value>Enterprise</value>
  </data>
  <data name="Gateway.Usage.EveryLicence" xml:space="preserve">
    <value>Tutte le licenze</value>
  </data>
  <data name="Gateway.Usage.CustomersOnly" xml:space="preserve">
    <value>Solo clienti, senza interne e demo</value>
  </data>
  <data name="Gateway.Usage.Sort.used" xml:space="preserve">
    <value>Più usate per prime</value>
  </data>
  <data name="Gateway.Usage.Sort.least" xml:space="preserve">
    <value>Meno usate per prime</value>
  </data>
  <data name="Gateway.Usage.Sort.expiry" xml:space="preserve">
    <value>In scadenza per prime</value>
  </data>
  <data name="Gateway.Usage.Sort.customer" xml:space="preserve">
    <value>Cliente</value>
  </data>
  <data name="Gateway.Usage.NoUsageYet.Detail" xml:space="preserve">
    <value>Ha risposto senza una quota o un totale: è anteriore a kf-ai-gateway#38, che riporta cosa è consentito e usato da ogni installazione. Le colonne del registro sono sotto; quelle del gateway si riempiono quando sarà distribuita.</value>
  </data>
  <data name="Gateway.Usage.Count.One" xml:space="preserve">
    <value>1 licenza in vigore</value>
  </data>
  <data name="Gateway.Usage.Count.Many" xml:space="preserve">
    <value>{0} licenze in vigore</value>
  </data>
  <data name="Gateway.Usage.OnAllowance" xml:space="preserve">
    <value>sulla quota {0}</value>
  </data>
  <data name="Gateway.Usage.Hidden.One" xml:space="preserve">
    <value>1 licenza interna o demo è esclusa.</value>
  </data>
  <data name="Gateway.Usage.Hidden.Many" xml:space="preserve">
    <value>{0} licenze interne o demo sono escluse.</value>
  </data>
  <data name="Gateway.Usage.Enrolled" xml:space="preserve">
    <value>{0} registrate, {1} non registrate.</value>
  </data>
  <data name="Gateway.Usage.NearLimit" xml:space="preserve">
    <value>{0} al {1}% o più</value>
  </data>
  <data name="Gateway.Usage.SharedCount" xml:space="preserve">
    <value>{0} su più di un'installazione</value>
  </data>
  <data name="Gateway.Usage.ServedOtherwiseCount" xml:space="preserve">
    <value>{0} servite diversamente da quanto dice il registro</value>
  </data>
  <data name="Gateway.Usage.LastMonth.NoLedger" xml:space="preserve">
    <value>I token del mese scorso non sono mostrati: il gateway non tiene ancora la cronologia degli utilizzi, essendo anteriore a kf-ai-gateway#41.</value>
  </data>
  <data name="Gateway.Usage.LastMonth.Failed" xml:space="preserve">
    <value>I token del mese scorso non sono mostrati: il gateway non ha risposto per la sua cronologia degli utilizzi. {0}</value>
  </data>
  <data name="Gateway.Usage.LastMonth.Partial" xml:space="preserve">
    <value>I token del mese scorso non sono mostrati per {0} installazioni: più di quante la console chieda una alla volta per una pagina hanno speso meno delle prime cinquanta del gateway.</value>
  </data>
  <data name="Gateway.Usage.LastMonth.NotRead" xml:space="preserve">
    <value>Non letto</value>
  </data>
  <data name="Gateway.Usage.LastMonth.TooMany" xml:space="preserve">
    <value>Non letto: più installazioni di quante la console chieda una alla volta</value>
  </data>
  <data name="Gateway.Usage.LastMonth.NoAnswer" xml:space="preserve">
    <value>Il gateway non ha risposto</value>
  </data>
  <data name="Gateway.Usage.LastMonth.Title" xml:space="preserve">
    <value>Il mese di calendario precedente a questo, in UTC, dal registro giornaliero degli utilizzi del gateway</value>
  </data>
  <data name="Gateway.Usage.TokensIn" xml:space="preserve">
    <value>Token a {0}</value>
  </data>
  <data name="Gateway.Usage.TokensLastMonth" xml:space="preserve">
    <value>Token il mese scorso</value>
  </data>
  <data name="Gateway.Usage.TokensThisPeriod" xml:space="preserve">
    <value>Token usati in questo periodo</value>
  </data>
  <data name="Gateway.Usage.Empty.Customers" xml:space="preserve">
    <value>Nessuna licenza cliente è in vigore.</value>
  </data>
  <data name="Gateway.Usage.Empty.Allowance" xml:space="preserve">
    <value>Nessuna licenza in vigore è su questa quota.</value>
  </data>
  <data name="Gateway.Usage.Empty" xml:space="preserve">
    <value>Nessuna licenza nel registro è in vigore.</value>
  </data>
  <data name="Gateway.Usage.NearLimit.Title" xml:space="preserve">
    <value>Un'installazione che la detiene ha usato il {0}% o più del suo budget di token in questo periodo</value>
  </data>
  <data name="Gateway.Usage.PercentUsed" xml:space="preserve">
    <value>{0}% usato</value>
  </data>
  <data name="Gateway.Usage.Shared.Title" xml:space="preserve">
    <value>Una licenza copre una sola installazione: la pagina della riga del registro dice cosa fare</value>
  </data>
  <data name="Gateway.Usage.ServedOtherwise" xml:space="preserve">
    <value>Servita diversamente</value>
  </data>
  <data name="Gateway.Usage.OneFile" xml:space="preserve">
    <value>Un file</value>
  </data>
  <data name="Gateway.Usage.Files" xml:space="preserve">
    <value>{0} file: una riemissione mantiene l'id</value>
  </data>
  <data name="Gateway.Usage.NotEnrolled" xml:space="preserve">
    <value>Non registrata</value>
  </data>
  <data name="Gateway.Usage.NotEnrolled.Title" xml:space="preserve">
    <value>Nessuna installazione nota al gateway detiene questo id di licenza</value>
  </data>
  <data name="Gateway.Usage.Unanswered.NotConfigured" xml:space="preserve">
    <value>Non configurato</value>
  </data>
  <data name="Gateway.Usage.Unanswered.NotReported" xml:space="preserve">
    <value>Non ancora riportato</value>
  </data>
  <data name="Gateway.Usage.Unanswered.NoAnswer" xml:space="preserve">
    <value>Nessuna risposta</value>
  </data>
  <data name="Gateway.Usage.LastCall" xml:space="preserve">
    <value>La sua ultima chiamata autenticata</value>
  </data>
  <data name="Gateway.Usage.Seen" xml:space="preserve">
    <value>Vista il {0} UTC</value>
  </data>
  <data name="Gateway.Usage.LessThanRegister.Title" xml:space="preserve">
    <value>Dove il gateway vede meno del registro</value>
  </data>
  <data name="Gateway.Usage.LessThanRegister.Detail" xml:space="preserve">
    <value>Un'installazione si registra la prima volta che usa l'IA, quindi una licenza la cui installazione non l'ha mai fatto è &lt;em&gt;Non registrata&lt;/em&gt;. Il gateway tiene la licenza che ogni installazione gli ha inviato per ultima: kf-app ne invia una a ogni installazione da kf-app#968, unita su &lt;code&gt;develop&lt;/code&gt; e in nessuna release ancora; kf-app {0} la invia solo alla prima registrazione, quindi una licenza installata lì in seguito, rinnovo compreso, non raggiunge il gateway. È questo che &lt;em&gt;Servita diversamente&lt;/em&gt; significa più spesso: l'installazione detiene un file precedente, e le è servito ciò che dice quel file.</value>
  </data>
  <data name="Gateway.Usage.WithoutId.One" xml:space="preserve">
    <value>1 installazione con licenza non ha l'id di licenza registrato: con licenza da prima che il gateway registrasse gli id (kf-ai-gateway#35), ne avrà uno quando kf-app invierà di nuovo la licenza, e fino ad allora la licenza che usa può risultare qui come non registrata.</value>
  </data>
  <data name="Gateway.Usage.WithoutId.Many" xml:space="preserve">
    <value>{0} installazioni con licenza non hanno l'id di licenza registrato: con licenza da prima che il gateway registrasse gli id (kf-ai-gateway#35), ciascuna ne avrà uno quando kf-app invierà di nuovo la licenza, e fino ad allora la licenza che usa può risultare qui come non registrata.</value>
  </data>
  <data name="Gateway.Usage.OtherIds.One" xml:space="preserve">
    <value>1 installazione con licenza detiene un id di licenza per cui il registro non ha alcuna licenza in vigore: una non nel registro, o una lì scaduta di cui il gateway non si è accorto, perché l'installazione non ha più chiamato.</value>
  </data>
  <data name="Gateway.Usage.OtherIds.Many" xml:space="preserve">
    <value>{0} installazioni con licenza detengono un id di licenza per cui il registro non ha alcuna licenza in vigore: una non nel registro, o una lì scaduta di cui il gateway non si è accorto, perché l'installazione non ha più chiamato.</value>
  </data>
  <data name="Gateway.Usage.ListHasThemAll" xml:space="preserve">
    <value>{0} le ha tutte.</value>
  </data>
  <data name="Gateway.Usage.TheInstallationsList" xml:space="preserve">
    <value>L'elenco delle installazioni</value>
  </data>
  <data name="Gateway.Usage.Differs" xml:space="preserve">
    <value>Servita {0}, dove il file del registro {1}.</value>
  </data>
  <data name="Gateway.Usage.Differs.Row" xml:space="preserve">
    <value>Servita dalla riga {0}, dove il livello della licenza sceglie {1}.</value>
  </data>
  <data name="Gateway.Usage.Differs.Expiry" xml:space="preserve">
    <value>Detiene un file che scade il {0}, dove il file in vigore del registro scade il {1}.</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.Tokens" xml:space="preserve">
    <value>{0} token a periodo dalla sua licenza</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.RowBudget" xml:space="preserve">
    <value>il budget di token della sua riga</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.Period" xml:space="preserve">
    <value>{0} dalla sua licenza</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.RowPeriod" xml:space="preserve">
    <value>il periodo di budget della sua riga</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.Rpm" xml:space="preserve">
    <value>{0} richieste al minuto dalla sua licenza</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.RowRpm" xml:space="preserve">
    <value>le richieste al minuto della sua riga</value>
  </data>
  <data name="Gateway.Usage.Differs.Sets" xml:space="preserve">
    <value>imposta {0}</value>
  </data>
  <data name="Gateway.Usage.Differs.LeavesBudget" xml:space="preserve">
    <value>lascia il budget alla sua riga</value>
  </data>
  <data name="Gateway.Usage.Differs.LeavesPeriod" xml:space="preserve">
    <value>lascia il periodo alla sua riga</value>
  </data>
  <data name="Gateway.Usage.Differs.LeavesRpm" xml:space="preserve">
    <value>le lascia alla sua riga</value>
  </data>
  <data name="Gateway.Usage.Period.Months" xml:space="preserve">
    <value>mesi di calendario</value>
  </data>
  <data name="Gateway.Usage.Period.Rolling" xml:space="preserve">
    <value>30 giorni a scorrere</value>
  </data>
  <data name="Gateway.Usage.Period.Other" xml:space="preserve">
    <value>periodo "{0}"</value>
  </data>
  <data name="Gateway.Usage.NoLedger.Title" xml:space="preserve">
    <value>Il gateway non tiene ancora la cronologia degli utilizzi</value>
  </data>
  <data name="Gateway.Usage.NoLedger.Detail" xml:space="preserve">
    <value>Risponde 404 a &lt;code&gt;/admin/usage&lt;/code&gt; mentre le sue installazioni rispondono: è anteriore a kf-ai-gateway#41, che tiene il registro giornaliero degli utilizzi. Quanto ogni installazione ha usato in questo periodo è ancora nella sua pagina.</value>
  </data>
  <data name="Gateway.Usage.Unit.tokens" xml:space="preserve">
    <value>token</value>
  </data>
  <data name="Gateway.Usage.Unit.requests" xml:space="preserve">
    <value>richieste</value>
  </data>
  <data name="Gateway.Usage.Series.Answered" xml:space="preserve">
    <value>Risposte</value>
  </data>
  <data name="Gateway.Usage.Series.Upstream" xml:space="preserve">
    <value>Errori a monte</value>
  </data>
  <data name="Gateway.Usage.Series.RateLimited" xml:space="preserve">
    <value>Rifiutate, limite di velocità</value>
  </data>
  <data name="Gateway.Usage.Series.BudgetSpent" xml:space="preserve">
    <value>Rifiutate, budget esaurito</value>
  </data>
  <data name="Gateway.History.Lead" xml:space="preserve">
    <value>Cosa ha speso il parco installazioni in un intervallo di giorni, dal registro giornaliero degli utilizzi del gateway{0}: i totali, gli stessi per la riga servita ora a ciascuna installazione, un grafico dei giorni, e le installazioni che hanno speso di più. Giorni UTC, estremi compresi, oggi finora. Letto con il token di sola lettura.</value>
  </data>
  <data name="Gateway.History.From" xml:space="preserve">
    <value>Dal</value>
  </data>
  <data name="Gateway.History.To" xml:space="preserve">
    <value>Al, compreso</value>
  </data>
  <data name="Gateway.History.TopInstallations" xml:space="preserve">
    <value>Installazioni principali</value>
  </data>
  <data name="Gateway.History.Show" xml:space="preserve">
    <value>Mostra</value>
  </data>
  <data name="Gateway.History.Preset.Last7" xml:space="preserve">
    <value>Ultimi 7 giorni</value>
  </data>
  <data name="Gateway.History.Preset.Last30" xml:space="preserve">
    <value>Ultimi 30 giorni</value>
  </data>
  <data name="Gateway.History.Preset.ThisMonth" xml:space="preserve">
    <value>Questo mese</value>
  </data>
  <data name="Gateway.History.Preset.LastMonth" xml:space="preserve">
    <value>Mese scorso</value>
  </data>
  <data name="Gateway.History.Preset.Last90" xml:space="preserve">
    <value>Ultimi 90 giorni</value>
  </data>
  <data name="Gateway.History.Preset.Last365" xml:space="preserve">
    <value>Ultimi 365 giorni</value>
  </data>
  <data name="Gateway.History.NotARange" xml:space="preserve">
    <value>Non è un intervallo a cui il gateway risponde</value>
  </data>
  <data name="Gateway.History.Problem.NotADate" xml:space="preserve">
    <value>"{0}" non è una data: scrivila come {1}.</value>
  </data>
  <data name="Gateway.History.Problem.Backwards" xml:space="preserve">
    <value>L'ultimo giorno è prima del primo.</value>
  </data>
  <data name="Gateway.History.Problem.TooLong" xml:space="preserve">
    <value>Sono {0} giorni. Il gateway risponde al massimo per {1} alla volta, un anno bisestile intero: chiedi un intervallo più lungo in parti.</value>
  </data>
  <data name="Gateway.History.Tokens" xml:space="preserve">
    <value>Token</value>
  </data>
  <data name="Gateway.History.Tokens.Note" xml:space="preserve">
    <value>Quanto il fornitore ha detto che sono costate le chat</value>
  </data>
  <data name="Gateway.History.Requests" xml:space="preserve">
    <value>Richieste</value>
  </data>
  <data name="Gateway.History.Requests.Note" xml:space="preserve">
    <value>Ogni richiesta, ammessa o rifiutata</value>
  </data>
  <data name="Gateway.History.Refused" xml:space="preserve">
    <value>Rifiutate</value>
  </data>
  <data name="Gateway.History.Refused.Title" xml:space="preserve">
    <value>Rifiutate per limite di velocità, e per budget esaurito</value>
  </data>
  <data name="Gateway.History.RefusedDetail" xml:space="preserve">
    <value>{0} per limite di velocità, {1} per budget esaurito</value>
  </data>
  <data name="Gateway.History.UpstreamErrors" xml:space="preserve">
    <value>Errori a monte</value>
  </data>
  <data name="Gateway.History.UpstreamErrors.Note" xml:space="preserve">
    <value>Chat fallite dal fornitore</value>
  </data>
  <data name="Gateway.History.Installations.Note" xml:space="preserve">
    <value>Che hanno fatto una richiesta nell'intervallo</value>
  </data>
  <data name="Gateway.History.Chart.Lead" xml:space="preserve">
    <value>Dal {0} al {1}, {2}, per la riga servita ora a ciascuna installazione.</value>
  </data>
  <data name="Gateway.History.DaysCsv" xml:space="preserve">
    <value>Giorni (CSV)</value>
  </data>
  <data name="Gateway.History.ByRow" xml:space="preserve">
    <value>Per riga</value>
  </data>
  <data name="Gateway.History.ByRow.Lead" xml:space="preserve">
    <value>La riga servita ora a ciascuna installazione, per tutto l'intervallo: una che ha acquistato una licenza durante l'intervallo conta sotto la riga della sua licenza dal primo giorno.</value>
  </data>
  <data name="Gateway.History.Share" xml:space="preserve">
    <value>Quota parte</value>
  </data>
  <data name="Gateway.History.Unrowed" xml:space="preserve">
    <value>Non più sul gateway</value>
  </data>
  <data name="Gateway.History.Unrowed.Lower" xml:space="preserve">
    <value>non più sul gateway</value>
  </data>
  <data name="Gateway.History.Unrowed.Title" xml:space="preserve">
    <value>Eliminate dal gateway a mano: hanno speso ciò che hanno speso, e non è servita loro alcuna riga</value>
  </data>
  <data name="Gateway.History.All" xml:space="preserve">
    <value>Tutte</value>
  </data>
  <data name="Gateway.History.Top.Lead" xml:space="preserve">
    <value>Le {0} che hanno speso più token nell'intervallo, ciascuna con la licenza del registro dove ne detiene una.</value>
  </data>
  <data name="Gateway.History.Top.Everyone" xml:space="preserve">
    <value>Sono tutte le installazioni che vi hanno fatto una richiesta.</value>
  </data>
  <data name="Gateway.History.Top.Some" xml:space="preserve">
    <value>{0} vi hanno fatto una richiesta.</value>
  </data>
  <data name="Gateway.History.TopCsv" xml:space="preserve">
    <value>Installazioni principali (CSV)</value>
  </data>
  <data name="Gateway.History.Top.Empty" xml:space="preserve">
    <value>Nessuna installazione ha fatto una richiesta in questo intervallo.</value>
  </data>
  <data name="Gateway.History.NotInRegister.Lower" xml:space="preserve">
    <value>non nel registro</value>
  </data>
  <data name="Gateway.History.Footnote" xml:space="preserve">
    <value>I token si contano al termine di ogni chat; richieste, rifiuti ed errori a monte raggiungono il registro una volta al minuto, quindi l'ultimo minuto non è ancora qui. I giorni precedenti alla tenuta del registro da parte del gateway (kf-ai-gateway#41) sono a zero. Ogni esportazione è registrata nel registro di audit.</value>
  </data>
  <data name="Gateway.Policy.NoWriteToken" xml:space="preserve">
    <value>La console non ha un token di scrittura: Gateway--AdminWriteToken non è in Key Vault.</value>
  </data>
  <data name="Gateway.Policy.ViewOnly" xml:space="preserve">
    <value>Puoi vedere la policy, non modificarla: serve {0}.</value>
  </data>
  <data name="Gateway.Policy.Count.NotReported" xml:space="preserve">
    <value>non riportato da questo gateway</value>
  </data>
  <data name="Gateway.Policy.Count.NoAnswer" xml:space="preserve">
    <value>non disponibile: il gateway non ha risposto</value>
  </data>
  <data name="Gateway.Policy.ActiveInstallations.One" xml:space="preserve">
    <value>1 installazione attiva</value>
  </data>
  <data name="Gateway.Policy.ActiveInstallations.Many" xml:space="preserve">
    <value>{0} installazioni attive</value>
  </data>
  <data name="Gateway.Policy.Lead" xml:space="preserve">
    <value>Cosa consente ora il gateway{0}: le sue tre righe di quota e le sue leve a livello di gateway, come le conserva il suo database, rilette a ogni caricamento alle {1} UTC con il token di sola lettura. La policy vive nel database del gateway così può cambiare senza un deploy, e una modifica si fa sentire alla richiesta successiva del gateway.</value>
  </data>
  <data name="Gateway.Policy.Lead.Change" xml:space="preserve">
    <value>Ogni riga e leva ha il proprio &lt;strong&gt;Modifica&lt;/strong&gt;: un modulo controllato come lo controlla il gateway, poi la modifica mostrata per intero, con chi raggiunge, prima di essere fatta con il token di scrittura. Ogni modifica è {0}, con il suo motivo e la riga prima e dopo.</value>
  </data>
  <data name="Gateway.Policy.TheAuditLog" xml:space="preserve">
    <value>nel registro di audit</value>
  </data>
  <data name="Gateway.Policy.Changed.Minimum" xml:space="preserve">
    <value>La versione minima dell'applicazione</value>
  </data>
  <data name="Gateway.Policy.Changed.Velocity" xml:space="preserve">
    <value>Il limite di velocità di registrazione</value>
  </data>
  <data name="Gateway.Policy.Changed.Ceiling" xml:space="preserve">
    <value>Il tetto globale di token</value>
  </data>
  <data name="Gateway.Policy.Changed.Tier" xml:space="preserve">
    <value>La quota {0}</value>
  </data>
  <data name="Gateway.Policy.Changed" xml:space="preserve">
    <value>{0} è stata modificata sul gateway, e si fa sentire alla sua richiesta successiva.</value>
  </data>
  <data name="Gateway.Policy.Changed.AuditLink" xml:space="preserve">
    <value>Il registro di audit</value>
  </data>
  <data name="Gateway.Policy.Changed.HasEntry" xml:space="preserve">
    <value>ha la voce.</value>
  </data>
  <data name="Gateway.Policy.NotReported.Title" xml:space="preserve">
    <value>Il gateway non riporta ancora la policy</value>
  </data>
  <data name="Gateway.Policy.NotReported.Detail" xml:space="preserve">
    <value>Elenca le sue installazioni ma risponde 404 a &lt;code&gt;/admin/tiers&lt;/code&gt;: è anteriore a kf-ai-gateway#39, che legge e scrive le righe di policy. Finché non sarà distribuita, le righe si leggono con &lt;code&gt;psql&lt;/code&gt;, come dice il suo &lt;code&gt;docs/Admin.md&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Policy.Tiers" xml:space="preserve">
    <value>Quote per livello</value>
  </data>
  <data name="Gateway.Policy.Tiers.Lead" xml:space="preserve">
    <value>Cosa è servito a un'installazione su ciascuna riga, a meno che la sua licenza non imposti il numero da sé. Le installazioni servite sono il conteggio del gateway di quelle attive; le licenze in vigore sono del registro.</value>
  </data>
  <data name="Gateway.Policy.TokenBudget" xml:space="preserve">
    <value>Budget di token</value>
  </data>
  <data name="Gateway.Policy.InstallationsServed" xml:space="preserve">
    <value>Installazioni servite</value>
  </data>
  <data name="Gateway.Policy.LicencesInForce" xml:space="preserve">
    <value>Licenze in vigore</value>
  </data>
  <data name="Gateway.Policy.NoLicenceRow" xml:space="preserve">
    <value>Nessuna licenza è servita da questa riga: è delle installazioni senza licenza</value>
  </data>
  <data name="Gateway.Policy.RegisterNotRead" xml:space="preserve">
    <value>Il registro non è stato letto</value>
  </data>
  <data name="Gateway.Policy.Change" xml:space="preserve">
    <value>Modifica</value>
  </data>
  <data name="Gateway.Policy.Requests.Help" xml:space="preserve">
    <value>Le richieste che un'installazione può fare nella finestra, un minuto su ogni riga oggi. Abbassarle rifiuta un'installazione già oltre il nuovo numero alla sua richiesta immediatamente successiva; alzarle libera una in attesa al vecchio. La finestra è tenuta nella memoria del gateway, quindi un riavvio fa ripartire da capo quella di ogni installazione.</value>
  </data>
  <data name="Gateway.Policy.TokenBudget.Help" xml:space="preserve">
    <value>I token che un'installazione può spendere in un periodo, prompt e risposta insieme: un mese di calendario in UTC, o trenta giorni a scorrere da dove è iniziato il suo periodo. La spesa è nel database del gateway, quindi un riavvio non la tocca.</value>
  </data>
  <data name="Gateway.Policy.LongestReply.Help" xml:space="preserve">
    <value>Il massimo di token che il gateway lascia scrivere al modello in una risposta: un'installazione che ne chiede di più è tenuta a questo. Una licenza non la imposta mai.</value>
  </data>
  <data name="Gateway.Policy.Whose" xml:space="preserve">
    <value>Di chi è il numero</value>
  </data>
  <data name="Gateway.Policy.Whose.Help" xml:space="preserve">
    <value>&lt;code&gt;evaluation&lt;/code&gt; serve ogni installazione senza licenza. &lt;code&gt;standard&lt;/code&gt; ed &lt;code&gt;enterprise&lt;/code&gt; servono le installazioni con licenza, secondo il livello della licenza: esattamente &lt;code&gt;enterprise&lt;/code&gt; prende la riga enterprise, e ogni altro livello, o nessuno, la riga standard. Una licenza che imposta &lt;code&gt;ai.tokens&lt;/code&gt;, &lt;code&gt;ai.period&lt;/code&gt; o &lt;code&gt;ai.rpm&lt;/code&gt; mantiene i propri numeri, e la sua riga fornisce solo ciò che la licenza omette.</value>
  </data>
  <data name="Gateway.Policy.OnlyUp.Title" xml:space="preserve">
    <value>La quota di un livello di licenza va solo verso l'alto</value>
  </data>
  <data name="Gateway.Policy.OnlyUp.Detail" xml:space="preserve">
    <value>&lt;code&gt;standard&lt;/code&gt; ed &lt;code&gt;enterprise&lt;/code&gt; sono partite uguali, come copie dell'unica vecchia riga con licenza del gateway (kf-ai-gateway#32), così che nulla di ciò che era servito a un'installazione cambiasse; &lt;code&gt;enterprise&lt;/code&gt; sarà alzata una volta decisi i suoi numeri. Finché una qualsiasi licenza su un livello è in vigore, la quota di quel livello viene alzata e mai abbassata (&lt;code&gt;License-Entitlements.md&lt;/code&gt;, &lt;em&gt;The AI allowance per tier&lt;/em&gt;): abbassarla ridurrebbe ciò che un cliente ha acquistato con una licenza che dice ancora la stessa cosa. Il conteggio del registro delle licenze in vigore è ciò che la regola protegge, e &lt;strong&gt;Modifica&lt;/strong&gt; rifiuta un abbassamento finché una è in vigore. Il gateway non lo controlla: vede solo le licenze che si sono registrate.</value>
  </data>
  <data name="Gateway.Policy.NoTier.One" xml:space="preserve">
    <value>1 installazione con licenza non ha il livello della licenza registrato: con licenza da prima che il gateway leggesse i livelli, le è servito &lt;code&gt;standard&lt;/code&gt; qualunque cosa dica la sua licenza, e un aumento di &lt;code&gt;enterprise&lt;/code&gt; non raggiunge un cliente Enterprise tra queste finché kf-app non invia di nuovo la sua licenza.</value>
  </data>
  <data name="Gateway.Policy.NoTier.Many" xml:space="preserve">
    <value>{0} installazioni con licenza non hanno il livello della licenza registrato: con licenza da prima che il gateway leggesse i livelli, è servito loro &lt;code&gt;standard&lt;/code&gt; qualunque cosa dica la loro licenza, e un aumento di &lt;code&gt;enterprise&lt;/code&gt; non raggiunge un cliente Enterprise tra queste finché kf-app non invia di nuovo la sua licenza.</value>
  </data>
  <data name="Gateway.Policy.Levers" xml:space="preserve">
    <value>Leve del gateway</value>
  </data>
  <data name="Gateway.Policy.Levers.Lead" xml:space="preserve">
    <value>Una riga di impostazioni a livello di gateway, ciascuna raggiunge insieme ogni installazione.</value>
  </data>
  <data name="Gateway.Policy.Minimum" xml:space="preserve">
    <value>Versione minima dell'applicazione</value>
  </data>
  <data name="Gateway.Policy.Minimum.Seeded" xml:space="preserve">
    <value>come inizializzato: ogni versione può registrarsi</value>
  </data>
  <data name="Gateway.Policy.Minimum.Help" xml:space="preserve">
    <value>La versione più vecchia di kf-app che può registrarsi. Un'installazione inferiore è rifiutata con &lt;code&gt;426 app_version_unsupported&lt;/code&gt; alla sua prossima registrazione; una già registrata continua a funzionare fino ad allora. Ritira una generazione dell'applicazione, quindi chiediti prima cosa costerebbe: i conteggi sotto sono del gateway, letti come la leva legge le versioni, e una prerelease conta come la sua release.</value>
  </data>
  <data name="Gateway.Policy.Minimum.NotAVersion" xml:space="preserve">
    <value>Non si legge come una versione, quindi ammette tutti: un valore così può essere stato scritto solo con &lt;code&gt;psql&lt;/code&gt;, che non controlla nulla. Il &lt;code&gt;PUT&lt;/code&gt; del gateway lo rifiuta.</value>
  </data>
  <data name="Gateway.Policy.Minimum.Below" xml:space="preserve">
    <value>Sotto {0}, il minimo:</value>
  </data>
  <data name="Gateway.Policy.Minimum.Below.Refused" xml:space="preserve">
    <value>{0}, rifiutate alla loro prossima registrazione.</value>
  </data>
  <data name="Gateway.Policy.Minimum.BelowRelease" xml:space="preserve">
    <value>Sotto {0}, la release attuale di kf-app:</value>
  </data>
  <data name="Gateway.Policy.Minimum.BelowRelease.WouldRefuse" xml:space="preserve">
    <value>{0}, ciò che alzare il minimo a quella rifiuterebbe.</value>
  </data>
  <data name="Gateway.Policy.Minimum.AnyOther" xml:space="preserve">
    <value>Qualsiasi altra versione: &lt;em&gt;Versione app inferiore a&lt;/em&gt; {0} pone al gateway la stessa domanda.</value>
  </data>
  <data name="Gateway.Policy.Velocity" xml:space="preserve">
    <value>Limite di velocità di registrazione</value>
  </data>
  <data name="Gateway.Policy.Velocity.Armed" xml:space="preserve">
    <value>Armato</value>
  </data>
  <data name="Gateway.Policy.Off" xml:space="preserve">
    <value>Disattivato</value>
  </data>
  <data name="Gateway.Policy.Velocity.Limits" xml:space="preserve">
    <value>{0}, {1}, da un solo indirizzo.</value>
  </data>
  <data name="Gateway.Policy.Velocity.Limits.Short" xml:space="preserve">
    <value>{0}, {1}</value>
  </data>
  <data name="Gateway.Policy.Velocity.AnHour" xml:space="preserve">
    <value>{0} all'ora</value>
  </data>
  <data name="Gateway.Policy.Velocity.ADay" xml:space="preserve">
    <value>{0} al giorno</value>
  </data>
  <data name="Gateway.Policy.Velocity.NoHourly" xml:space="preserve">
    <value>nessun limite orario</value>
  </data>
  <data name="Gateway.Policy.Velocity.NoDaily" xml:space="preserve">
    <value>nessun limite giornaliero</value>
  </data>
  <data name="Gateway.Policy.Velocity.OffDetail" xml:space="preserve">
    <value>Nessuna registrazione è contata e nessun indirizzo è registrato, come inizializzato.</value>
  </data>
  <data name="Gateway.Policy.Velocity.Help" xml:space="preserve">
    <value>Quante registrazioni può fare un indirizzo in un'ora e in un giorno prima che la successiva sia rifiutata con &lt;code&gt;429 enrolment_rate_limited&lt;/code&gt;. La registrazione è l'unico endpoint che non richiede credenziali, quindi questa è la leva per il giorno in cui qualcuno ne abusa; è disattivata per decisione, perché voler installare il prodotto troppe volte è un problema migliore che rifiutare un rollout legittimo. Armato, il conteggio parte da zero.</value>
  </data>
  <data name="Gateway.Policy.Velocity.CheckAddress.Title" xml:space="preserve">
    <value>Verifica l'indirizzo prima di armarlo</value>
  </data>
  <data name="Gateway.Policy.Velocity.CheckAddress.Detail" xml:space="preserve">
    <value>Dietro App Service il gateway legge l'indirizzo che il front end della piattaforma aggiunge a &lt;code&gt;X-Forwarded-For&lt;/code&gt;, e questo non è mai stato verificato con una risposta reale. Armato sull'indirizzo sbagliato, il limite conta ogni installazione su un solo indirizzo e rifiuta tutti.</value>
  </data>
  <data name="Gateway.Policy.Velocity.CallerSeen" xml:space="preserve">
    <value>Il gateway ha visto la richiesta di questa console, alle {0} UTC, come proveniente da {1}. Dovrebbe essere uno degli indirizzi IP in uscita di &lt;code&gt;app-kf-admin&lt;/code&gt; (App Service, &lt;em&gt;Properties&lt;/em&gt;). Se è il front end della piattaforma, un indirizzo privato o &lt;code&gt;unknown&lt;/code&gt;, non armare il limite.</value>
  </data>
  <data name="Gateway.Policy.Velocity.CallerUnknown" xml:space="preserve">
    <value>L'indirizzo da cui il gateway ha visto chiamare questa console non è disponibile: viene dallo stato del gateway, che non ha risposto. Verificalo prima di armare il limite.</value>
  </data>
  <data name="Gateway.Policy.Ceiling" xml:space="preserve">
    <value>Tetto globale di token</value>
  </data>
  <data name="Gateway.Policy.Ceiling.Unit" xml:space="preserve">
    <value>token al mese di calendario, l'intero servizio</value>
  </data>
  <data name="Gateway.Policy.NoBrake" xml:space="preserve">
    <value>Nessun freno</value>
  </data>
  <data name="Gateway.Policy.NoBrake.Detail" xml:space="preserve">
    <value>Dietro il gateway c'è solo il limite del fornitore.</value>
  </data>
  <data name="Gateway.Policy.BrakeOn" xml:space="preserve">
    <value>&lt;strong&gt;Il freno è attivo.&lt;/strong&gt; Ogni chat è rifiutata con &lt;code&gt;503 service_paused&lt;/code&gt; finché il tetto non viene alzato o il mese non finisce.</value>
  </data>
  <data name="Gateway.Policy.SpentThisMonth" xml:space="preserve">
    <value>Spesi questo mese: {0}</value>
  </data>
  <data name="Gateway.Policy.SpentPercent" xml:space="preserve">
    <value>, {0}% del tetto</value>
  </data>
  <data name="Gateway.Policy.SpentUntil" xml:space="preserve">
    <value>, fino alle {0} UTC</value>
  </data>
  <data name="Gateway.Policy.OverviewHasBrake" xml:space="preserve">
    <value>{0} ha il freno per intero.</value>
  </data>
  <data name="Gateway.Policy.TheOverview" xml:space="preserve">
    <value>La panoramica</value>
  </data>
  <data name="Gateway.Policy.BrakeUnknown" xml:space="preserve">
    <value>Lo stato del freno non è disponibile: lo stato del gateway non ha risposto.</value>
  </data>
  <data name="Gateway.Policy.Ceiling.Help" xml:space="preserve">
    <value>I token che l'intero servizio può spendere in un mese di calendario prima che ogni chat, per tutti, sia rifiutata con &lt;code&gt;503 service_paused&lt;/code&gt;: un rilevatore di fughe, non un secondo limite di velocità, inizializzato generosamente a 50.000.000. Alzarlo è tutto il rilascio del freno, e un riavvio non lo rilascia. Nessun tetto è nessun freno, non un freno a zero.</value>
  </data>
  <data name="Gateway.Change.Policy.Lead" xml:space="preserve">
    <value>Una modifica al gateway{0} con il token di scrittura della console, {1}, che si fa sentire alla richiesta successiva del gateway. È registrata nel registro di audit, con il tuo motivo, una volta che il gateway la conferma, e il gateway la registra nel proprio log sotto lo stesso nome.</value>
  </data>
  <data name="Gateway.Change.Stale.Title" xml:space="preserve">
    <value>La riga del gateway è cambiata da quando l'hai rivista</value>
  </data>
  <data name="Gateway.Change.Stale.Detail" xml:space="preserve">
    <value>Nulla è stato scritto. La modifica è mostrata di nuovo rispetto alla riga com'è ora: rivedila, e conferma se è ancora ciò che intendi.</value>
  </data>
  <data name="Gateway.Change.NoPolicyWrites.Title" xml:space="preserve">
    <value>Il gateway non accetta modifiche alla policy</value>
  </data>
  <data name="Gateway.Change.NoPolicyWrites.Detail" xml:space="preserve">
    <value>Ha risposto 404 alla modifica: è anteriore a kf-ai-gateway#39. Nulla è stato modificato.</value>
  </data>
  <data name="Gateway.Change.Policy.RequestRefused.Detail" xml:space="preserve">
    <value>Ha risposto 400, un difetto della console e non un'interruzione; la riga è com'era.</value>
  </data>
  <data name="Gateway.Change.Policy.Unsure.Detail" xml:space="preserve">
    <value>Apri {0} per vedere la riga com'è prima di riprovare. Nessuna voce di audit è stata scritta.</value>
  </data>
  <data name="Gateway.Change.ThePolicyPage" xml:space="preserve">
    <value>la pagina della policy</value>
  </data>
  <data name="Gateway.Change.RowProblems.Title" xml:space="preserve">
    <value>La riga del gateway contiene un valore che non riaccetterà</value>
  </data>
  <data name="Gateway.Change.RowProblems.Detail" xml:space="preserve">
    <value>Una modifica scrive l'intera riga, e la riga contiene {0}: scritto senza la console, con &lt;code&gt;psql&lt;/code&gt;, che non controlla nulla. Il gateway rifiuta una riga che lo contiene, quindi cambia prima quello.</value>
  </data>
  <data name="Gateway.Change.RowProblems.And" xml:space="preserve">
    <value>, e </value>
  </data>
  <data name="Gateway.Change.RowProblems.Minimum" xml:space="preserve">
    <value>Versione minima</value>
  </data>
  <data name="Gateway.Change.RowProblems.Velocity" xml:space="preserve">
    <value>Velocità di registrazione</value>
  </data>
  <data name="Gateway.Change.RowProblems.Ceiling" xml:space="preserve">
    <value>Tetto globale</value>
  </data>
  <data name="Gateway.Change.RowProblem.Version" xml:space="preserve">
    <value>una versione minima, "{0}", che non si legge come una versione</value>
  </data>
  <data name="Gateway.Change.RowProblem.Hourly" xml:space="preserve">
    <value>un limite orario di registrazione di {0}, che rifiuta ogni registrazione</value>
  </data>
  <data name="Gateway.Change.RowProblem.Daily" xml:space="preserve">
    <value>un limite giornaliero di registrazione di {0}, che rifiuta ogni registrazione</value>
  </data>
  <data name="Gateway.Change.RowProblem.HourlyAboveDaily" xml:space="preserve">
    <value>un limite orario di registrazione superiore a quello giornaliero</value>
  </data>
  <data name="Gateway.Change.RowProblem.Ceiling" xml:space="preserve">
    <value>un tetto globale di token di {0}, che mette in pausa il servizio per tutti</value>
  </data>
  <data name="Gateway.Change.Reason.Placeholder" xml:space="preserve">
    <value>Il perché, per chi leggerà il registro di audit</value>
  </data>
  <data name="Gateway.Change.TheChange" xml:space="preserve">
    <value>La modifica</value>
  </data>
  <data name="Gateway.Change.Now" xml:space="preserve">
    <value>Ora</value>
  </data>
  <data name="Gateway.Change.After" xml:space="preserve">
    <value>Dopo</value>
  </data>
  <data name="Gateway.Change.NowValue" xml:space="preserve">
    <value>Ora {0}</value>
  </data>
  <data name="Gateway.Change.Unchanged" xml:space="preserve">
    <value>invariato</value>
  </data>
  <data name="Gateway.Change.Review" xml:space="preserve">
    <value>Rivedi la modifica</value>
  </data>
  <data name="Gateway.Change.WhatItDoes" xml:space="preserve">
    <value>Cosa fa</value>
  </data>
  <data name="Gateway.Tier.Title" xml:space="preserve">
    <value>Cambia la quota {0}</value>
  </data>
  <data name="Gateway.Tier.Title.Html" xml:space="preserve">
    <value>Cambia la quota {0}</value>
  </data>
  <data name="Gateway.Tier.NoRow" xml:space="preserve">
    <value>Il gateway non elenca una riga {0}.</value>
  </data>
  <data name="Gateway.Tier.InForce.One" xml:space="preserve">
    <value>1 licenza in vigore</value>
  </data>
  <data name="Gateway.Tier.InForce.Many" xml:space="preserve">
    <value>{0} licenze in vigore</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Title" xml:space="preserve">
    <value>La quota {0} va solo verso l'alto finché una licenza su di essa è in vigore</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Holds" xml:space="preserve">
    <value>Il registro ha {0} su questa riga, e questa modifica darebbe loro di meno:</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Unread" xml:space="preserve">
    <value>Non è stato possibile leggere il registro, quindi la console non può dire se una licenza su questa riga sia in vigore, e finché non potrà la riga viene solo alzata. Questa modifica darebbe di meno:</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Why" xml:space="preserve">
    <value>Abbassarla ridurrebbe ciò che quei clienti hanno acquistato con licenze che dicono ancora la stessa cosa. Un piano che ha bisogno di meno è un nuovo livello, o numeri scritti nelle licenze emesse su di esso (&lt;code&gt;License-Entitlements.md&lt;/code&gt;, &lt;em&gt;The AI allowance per tier&lt;/em&gt;).</value>
  </data>
  <data name="Gateway.Tier.TheRow" xml:space="preserve">
    <value>La riga</value>
  </data>
  <data name="Gateway.Tier.Window" xml:space="preserve">
    <value>Per finestra di, in secondi</value>
  </data>
  <data name="Gateway.Tier.Window.Now" xml:space="preserve">
    <value>Ora {0}, un minuto su ogni riga come inizializzato</value>
  </data>
  <data name="Gateway.Tier.PerPeriod" xml:space="preserve">
    <value>Per periodo</value>
  </data>
  <data name="Gateway.Tier.LongestReplyTokens" xml:space="preserve">
    <value>Risposta più lunga, in token</value>
  </data>
  <data name="Gateway.Tier.WhomItReaches" xml:space="preserve">
    <value>Chi raggiunge</value>
  </data>
  <data name="Gateway.Tier.Reaches.Detail" xml:space="preserve">
    <value>Le installazioni servite sono il conteggio del gateway di quelle attive sulla riga: una modifica raggiunge ognuna di esse alla sua prossima richiesta. Abbassare le richieste rifiuta subito un'installazione già oltre il nuovo numero; alzarle libera una in attesa al vecchio numero. Una licenza che imposta &lt;code&gt;ai.tokens&lt;/code&gt;, &lt;code&gt;ai.period&lt;/code&gt; o &lt;code&gt;ai.rpm&lt;/code&gt; mantiene i propri numeri, e la riga fornisce solo ciò che la licenza omette.</value>
  </data>
  <data name="Gateway.Tier.Evaluation" xml:space="preserve">
    <value>&lt;code&gt;evaluation&lt;/code&gt; serve ogni installazione senza licenza. Nessuna licenza ne è servita, quindi va verso il basso come verso l'alto.</value>
  </data>
  <data name="Gateway.Tier.RuleHolds" xml:space="preserve">
    <value>&lt;strong&gt;Va solo verso l'alto.&lt;/strong&gt; Finché una licenza su questa riga è in vigore, viene alzata e mai abbassata: meno richieste al minuto, un budget minore, un altro periodo o una risposta più corta sono rifiutati qui. Alzare raggiunge insieme ogni tale licenza. Il gateway non lo controlla; lo fa la console, dal registro.</value>
  </data>
  <data name="Gateway.Tier.RuleFree" xml:space="preserve">
    <value>Nessuna licenza su questa riga è in vigore, quindi la regola del solo-verso-l'alto non la vincola, e va verso il basso come verso l'alto. Una licenza emessa su di essa in seguito è tenuta ai numeri che avrà allora.</value>
  </data>
  <data name="Gateway.Tier.NoChange" xml:space="preserve">
    <value>Questi sono i numeri che la riga ha già: nulla cambierebbe.</value>
  </data>
  <data name="Gateway.Tier.Field.Requests" xml:space="preserve">
    <value>Le richieste</value>
  </data>
  <data name="Gateway.Tier.Field.Window" xml:space="preserve">
    <value>La finestra</value>
  </data>
  <data name="Gateway.Tier.Field.Budget" xml:space="preserve">
    <value>Il budget di token</value>
  </data>
  <data name="Gateway.Tier.Field.LongestReply" xml:space="preserve">
    <value>La risposta più lunga</value>
  </data>
  <data name="Gateway.Tier.Problem.MustBe" xml:space="preserve">
    <value>{0} deve essere {1}.</value>
  </data>
  <data name="Gateway.Tier.Problem.Period" xml:space="preserve">
    <value>Il periodo deve essere un mese di calendario o trenta giorni a scorrere: il gateway non ne conosce altri.</value>
  </data>
  <data name="Gateway.Tier.Lowering.Requests" xml:space="preserve">
    <value>meno richieste: {0} diventerebbe {1}</value>
  </data>
  <data name="Gateway.Tier.Lowering.Budget" xml:space="preserve">
    <value>un budget di token minore: {0} diventerebbe {1}</value>
  </data>
  <data name="Gateway.Tier.Lowering.Period" xml:space="preserve">
    <value>un altro periodo: {0} diventerebbe {1}, e nessuno dei due è più lungo dell'altro in ogni mese</value>
  </data>
  <data name="Gateway.Tier.Lowering.LongestReply" xml:space="preserve">
    <value>una risposta più lunga più corta: {0} token diventerebbero {1}</value>
  </data>
  <data name="Gateway.Velocity.Title" xml:space="preserve">
    <value>Cambia il limite di velocità di registrazione</value>
  </data>
  <data name="Gateway.Velocity.TheLimit" xml:space="preserve">
    <value>Il limite</value>
  </data>
  <data name="Gateway.Velocity.Review.Off" xml:space="preserve">
    <value>Disattivato: nessuna registrazione è contata e nessun indirizzo è registrato, come inizializzato.</value>
  </data>
  <data name="Gateway.Velocity.Review.PastIt" xml:space="preserve">
    <value>Oltre il limite, la registrazione da quell'indirizzo è rifiutata con &lt;code&gt;429 enrolment_rate_limited&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Velocity.Review.StartsEmpty" xml:space="preserve">
    <value>Il conteggio parte da zero: la finestra si riempie nell'ora successiva anziché risalire a registrazioni che nessuno ha registrato.</value>
  </data>
  <data name="Gateway.Velocity.Review.Ticked" xml:space="preserve">
    <value>Hai spuntato di aver verificato l'indirizzo da cui il gateway vede i chiamanti: {0}. Armato sull'indirizzo sbagliato, il limite rifiuta tutti.</value>
  </data>
  <data name="Gateway.Velocity.NotAvailableHere" xml:space="preserve">
    <value>non disponibile qui</value>
  </data>
  <data name="Gateway.Velocity.Arm" xml:space="preserve">
    <value>Arma il limite</value>
  </data>
  <data name="Gateway.Velocity.TurnOff" xml:space="preserve">
    <value>Disattiva il limite</value>
  </data>
  <data name="Gateway.Velocity.ChangeLimit" xml:space="preserve">
    <value>Cambia il limite</value>
  </data>
  <data name="Gateway.Velocity.OffOption" xml:space="preserve">
    <value>Disattivato: nulla contato, nessun indirizzo registrato</value>
  </data>
  <data name="Gateway.Velocity.ArmedOption" xml:space="preserve">
    <value>Armato, da un solo indirizzo:</value>
  </data>
  <data name="Gateway.Velocity.PerHour" xml:space="preserve">
    <value>Registrazioni all'ora</value>
  </data>
  <data name="Gateway.Velocity.PerHour.Now" xml:space="preserve">
    <value>Ora {0}. Vuoto per nessun limite orario.</value>
  </data>
  <data name="Gateway.Velocity.PerDay" xml:space="preserve">
    <value>Registrazioni al giorno</value>
  </data>
  <data name="Gateway.Velocity.PerDay.Now" xml:space="preserve">
    <value>Ora {0}. Vuoto per nessun limite giornaliero.</value>
  </data>
  <data name="Gateway.Velocity.None" xml:space="preserve">
    <value>nessuno</value>
  </data>
  <data name="Gateway.Velocity.CheckAddress.Counts" xml:space="preserve">
    <value>Dietro App Service il gateway conta l'indirizzo che il front end della piattaforma aggiunge a &lt;code&gt;X-Forwarded-For&lt;/code&gt;, e questo non è mai stato verificato con una risposta reale. Armato sull'indirizzo sbagliato, il limite conta ogni installazione su un solo indirizzo e rifiuta tutti.</value>
  </data>
  <data name="Gateway.Velocity.CallerUnknownHere" xml:space="preserve">
    <value>L'indirizzo che il gateway vede non è disponibile qui: viene dallo stato del gateway, che non ha risposto. Verificalo come dice kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt; prima di armare il limite.</value>
  </data>
  <data name="Gateway.Velocity.AddressChecked" xml:space="preserve">
    <value>Ho verificato l'indirizzo da cui il gateway vede i chiamanti</value>
  </data>
  <data name="Gateway.Velocity.NoChange" xml:space="preserve">
    <value>Questi sono i limiti che il gateway ha già: nulla cambierebbe.</value>
  </data>
  <data name="Gateway.Velocity.NoChange.Off" xml:space="preserve">
    <value>Il limite è già disattivato: nulla cambierebbe.</value>
  </data>
  <data name="Gateway.Velocity.Problem.Hourly" xml:space="preserve">
    <value>Un limite orario è {0}, o vuoto per nessuno.</value>
  </data>
  <data name="Gateway.Velocity.Problem.Daily" xml:space="preserve">
    <value>Un limite giornaliero è {0}, o vuoto per nessuno.</value>
  </data>
  <data name="Gateway.Velocity.Problem.None" xml:space="preserve">
    <value>Armare richiede un limite orario, uno giornaliero, o entrambi. Per disattivare il limite, scegli Disattivato.</value>
  </data>
  <data name="Gateway.Velocity.Problem.HourlyAboveDaily" xml:space="preserve">
    <value>Il limite orario non deve essere superiore a quello giornaliero, che rifiuterebbe sempre per primo.</value>
  </data>
  <data name="Gateway.Velocity.Problem.Unchecked" xml:space="preserve">
    <value>Spunta questo dopo aver verificato l'indirizzo: armato su quello sbagliato, il limite rifiuta tutti.</value>
  </data>
  <data name="Gateway.Velocity.WhatItDoes.1" xml:space="preserve">
    <value>Quante registrazioni può fare un indirizzo in un'ora e in un giorno prima che la successiva sia rifiutata. La registrazione è l'unico endpoint che non richiede credenziali, quindi questa è la leva per il giorno in cui qualcuno ne abusa.</value>
  </data>
  <data name="Gateway.Velocity.WhatItDoes.2" xml:space="preserve">
    <value>È disattivato per decisione (kf-ai-gateway#4): voler installare il prodotto troppe volte è un problema migliore che rifiutare un rollout legittimo. Il limite orario non è superiore a quello giornaliero, che rifiuterebbe sempre per primo. Disattivalo prima di puntare il gateway a un database ripristinato, e riattivalo quando il parco si sarà stabilizzato.</value>
  </data>
  <data name="Gateway.Ceiling.Title" xml:space="preserve">
    <value>Cambia il tetto globale di token</value>
  </data>
  <data name="Gateway.Ceiling.TheCeiling" xml:space="preserve">
    <value>Il tetto</value>
  </data>
  <data name="Gateway.Ceiling.TokensAMonth" xml:space="preserve">
    <value>{0} token al mese di calendario</value>
  </data>
  <data name="Gateway.Ceiling.Releases" xml:space="preserve">
    <value>&lt;strong&gt;Questo rilascia il freno.&lt;/strong&gt; La prossima chat è ammessa: {0} token sono stati spesi questo mese, {1}.</value>
  </data>
  <data name="Gateway.Ceiling.Releases.NoCeiling" xml:space="preserve">
    <value>e dopo non c'è alcun tetto</value>
  </data>
  <data name="Gateway.Ceiling.Releases.Below" xml:space="preserve">
    <value>sotto il nuovo tetto</value>
  </data>
  <data name="Gateway.Ceiling.StaysOn" xml:space="preserve">
    <value>&lt;strong&gt;Il freno resta attivo.&lt;/strong&gt; {0} token sono stati spesi questo mese, pari o superiori anche al nuovo tetto, quindi ogni chat è ancora rifiutata con &lt;code&gt;503 service_paused&lt;/code&gt;. Alzalo sopra quanto speso per rilasciarlo.</value>
  </data>
  <data name="Gateway.Ceiling.Trips" xml:space="preserve">
    <value>&lt;strong&gt;Questo fa scattare il freno.&lt;/strong&gt; {0} token sono stati spesi questo mese, già pari o superiori al nuovo tetto, quindi ogni chat, per tutti, è rifiutata con &lt;code&gt;503 service_paused&lt;/code&gt; dalla prossima, finché il tetto non viene alzato o il mese non finisce.</value>
  </data>
  <data name="Gateway.Ceiling.Headroom" xml:space="preserve">
    <value>{0} token sono stati spesi questo mese, quindi altri {1} possono essere spesi prima che il freno scatti</value>
  </data>
  <data name="Gateway.Ceiling.Headroom.Until" xml:space="preserve">
    <value>, finché il mese finisce alle {0} UTC</value>
  </data>
  <data name="Gateway.Ceiling.Off" xml:space="preserve">
    <value>Nessun freno: il gateway spende finché il limite del fornitore non lo ferma. Nulla scatta per una fuga fino ad allora.</value>
  </data>
  <data name="Gateway.Ceiling.TurnOff" xml:space="preserve">
    <value>Disattiva il freno</value>
  </data>
  <data name="Gateway.Ceiling.ChangeCeiling" xml:space="preserve">
    <value>Cambia il tetto</value>
  </data>
  <data name="Gateway.Ceiling.Option.Ceiling" xml:space="preserve">
    <value>Un tetto, in token al mese di calendario, l'intero servizio:</value>
  </data>
  <data name="Gateway.Ceiling.Aria" xml:space="preserve">
    <value>Token al mese di calendario</value>
  </data>
  <data name="Gateway.Ceiling.Option.NoBrake" xml:space="preserve">
    <value>Nessun freno: dietro il gateway c'è solo il limite del fornitore</value>
  </data>
  <data name="Gateway.Ceiling.TheBrake" xml:space="preserve">
    <value>Il freno</value>
  </data>
  <data name="Gateway.Ceiling.BrakeOn" xml:space="preserve">
    <value>&lt;strong&gt;Il freno è attivo.&lt;/strong&gt; Ogni chat è rifiutata con &lt;code&gt;503 service_paused&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Ceiling.SpentThisMonth" xml:space="preserve">
    <value>Spesi questo mese</value>
  </data>
  <data name="Gateway.Ceiling.MonthEnds" xml:space="preserve">
    <value>Fine del mese</value>
  </data>
  <data name="Gateway.Ceiling.About.1" xml:space="preserve">
    <value>&lt;strong&gt;Alzare il tetto è tutto il rilascio di un freno scattato&lt;/strong&gt;, dalla prossima chat. Un riavvio non lo rilascia, di proposito: un freno che si azzerasse al riavvio riprenderebbe a spendere, e una fuga è ciò che fa riavviare un processo.</value>
  </data>
  <data name="Gateway.Ceiling.About.2" xml:space="preserve">
    <value>La spesa del mese è la registrazione del gateway di ciò che è stato speso, non una leva. Non spetta all'operatore toccarla, e la console non lo propone mai: azzerarla distruggerebbe la prova di ciò che ha fatto scattare il freno. Riparte con la prima chat di un nuovo mese.</value>
  </data>
  <data name="Gateway.Ceiling.About.3" xml:space="preserve">
    <value>Il tetto è un rilevatore di fughe, non un secondo limite di velocità, inizializzato generosamente a 50.000.000. Nessun tetto è nessun freno, non un freno a zero.</value>
  </data>
  <data name="Gateway.Ceiling.NoChange" xml:space="preserve">
    <value>Questo è il tetto che il gateway ha già: nulla cambierebbe.</value>
  </data>
  <data name="Gateway.Ceiling.NoChange.Off" xml:space="preserve">
    <value>Non c'è già alcun freno: nulla cambierebbe.</value>
  </data>
  <data name="Gateway.Ceiling.Problem" xml:space="preserve">
    <value>Un tetto è {0}. Zero non è disattivato: mette in pausa il servizio per tutti. Per disattivare il freno, scegli Nessun freno.</value>
  </data>
  <data name="Gateway.Minimum.Title" xml:space="preserve">
    <value>Cambia la versione minima dell'applicazione</value>
  </data>
  <data name="Gateway.Minimum.ChangeMinimum" xml:space="preserve">
    <value>Cambia il minimo</value>
  </data>
  <data name="Gateway.Minimum.TheMinimum" xml:space="preserve">
    <value>Il minimo</value>
  </data>
  <data name="Gateway.Minimum.NotAnswered.Title" xml:space="preserve">
    <value>Il gateway non ha detto chi rifiuterebbe questo minimo</value>
  </data>
  <data name="Gateway.Minimum.NotAnswered.Default" xml:space="preserve">
    <value>Non ha risposto alla domanda.</value>
  </data>
  <data name="Gateway.Minimum.NotAnswered.Detail" xml:space="preserve">
    <value>La modifica si fa con il parco in vista, quindi non è proposta finché il gateway non risponde: riprova.</value>
  </data>
  <data name="Gateway.Minimum.Refuses.One" xml:space="preserve">
    <value>A {0}, {1} è rifiutata con &lt;code&gt;426 app_version_unsupported&lt;/code&gt; alla sua prossima registrazione. Un'installazione già registrata continua a funzionare fino ad allora.</value>
  </data>
  <data name="Gateway.Minimum.Refuses.Many" xml:space="preserve">
    <value>A {0}, {1} sono rifiutate con &lt;code&gt;426 app_version_unsupported&lt;/code&gt; alla loro prossima registrazione. Un'installazione già registrata continua a funzionare fino ad allora.</value>
  </data>
  <data name="Gateway.Minimum.VersionReported" xml:space="preserve">
    <value>Ultima versione riportata</value>
  </data>
  <data name="Gateway.Minimum.NoneReported" xml:space="preserve">
    <value>nessuna riportata</value>
  </data>
  <data name="Gateway.Minimum.BelowNow" xml:space="preserve">
    <value>Questo è sotto il minimo attuale: le versioni che rifiutava possono registrarsi di nuovo.</value>
  </data>
  <data name="Gateway.Minimum.AskAgain" xml:space="preserve">
    <value>Chiedi di nuovo</value>
  </data>
  <data name="Gateway.Minimum.Seeded.Suffix" xml:space="preserve">
    <value>, come inizializzato: ogni versione può registrarsi</value>
  </data>
  <data name="Gateway.Minimum.SeeWhom" xml:space="preserve">
    <value>Vedi chi rifiuta</value>
  </data>
  <data name="Gateway.Minimum.WhatItDoes.1" xml:space="preserve">
    <value>La versione più vecchia di kf-app che può registrarsi. Ritira una generazione dell'applicazione: un'installazione inferiore è rifiutata alla sua prossima registrazione, e una già registrata continua a funzionare fino ad allora. Il passo successivo mostra chi rifiuta un minimo, per l'ultima versione riportata da ciascuna, come le conta il gateway.</value>
  </data>
  <data name="Gateway.Minimum.WhatItDoes.2" xml:space="preserve">
    <value>Una versione è almeno una major e una minor, come &lt;code&gt;1.7&lt;/code&gt; o &lt;code&gt;1.7.0&lt;/code&gt;, e una prerelease conta come la sua release. Il gateway rifiuta qualsiasi altra cosa qui; impostato a mano con &lt;code&gt;psql&lt;/code&gt;, un valore che non si legge come una versione ammette tutti, di proposito, così un refuso lì non chiude fuori il parco.</value>
  </data>
  <data name="Gateway.Minimum.CurrentRelease" xml:space="preserve">
    <value>La release attuale di kf-app è {0}.</value>
  </data>
  <data name="Gateway.Minimum.Problem.Required" xml:space="preserve">
    <value>Inserisci una versione, come 1.7.0.</value>
  </data>
  <data name="Gateway.Minimum.Problem.NotAVersion" xml:space="preserve">
    <value>"{0}" non è una versione come la legge la registrazione: almeno una major e una minor, come 1.7 o 1.7.0. Il gateway la rifiuterebbe; impostata a mano, ammetterebbe tutti.</value>
  </data>
  <data name="Gateway.Minimum.Problem.TooLong" xml:space="preserve">
    <value>Una versione minima ha al massimo {0} caratteri.</value>
  </data>
  <data name="Crm.Stage.ToContact" xml:space="preserve">
    <value>Da contattare</value>
  </data>
  <data name="Crm.Stage.ContactedAwaitingReply" xml:space="preserve">
    <value>Contattato, in attesa di risposta</value>
  </data>
  <data name="Crm.Stage.MeetingPlanned" xml:space="preserve">
    <value>Incontro pianificato</value>
  </data>
  <data name="Crm.Stage.Met" xml:space="preserve">
    <value>Incontrato</value>
  </data>
  <data name="Crm.Stage.PreProposalAgreed" xml:space="preserve">
    <value>Pre-proposta concordata</value>
  </data>
  <data name="Crm.Stage.Active" xml:space="preserve">
    <value>Attivo</value>
  </data>
  <data name="Crm.Stage.DeclinedOrDormant" xml:space="preserve">
    <value>Ha declinato o inattivo</value>
  </data>
  <data name="Crm.Stage.Rejected" xml:space="preserve">
    <value>Scartato</value>
  </data>
  <data name="Crm.DeclineReason.AwaitingTraction" xml:space="preserve">
    <value>Attende maggior trazione</value>
  </data>
  <data name="Crm.DeclineReason.NotSeekingPartners" xml:space="preserve">
    <value>Non cerca nuovi partner</value>
  </data>
  <data name="Crm.DeclineReason.Other" xml:space="preserve">
    <value>Altro</value>
  </data>
  <data name="Crm.Track.Ambassador" xml:space="preserve">
    <value>Ambassador</value>
  </data>
  <data name="Crm.Track.BusinessPartner" xml:space="preserve">
    <value>Partner commerciale</value>
  </data>
  <data name="Crm.Track.Undecided" xml:space="preserve">
    <value>Da decidere</value>
  </data>
  <data name="Crm.Entity.Individual" xml:space="preserve">
    <value>Persona fisica</value>
  </data>
  <data name="Crm.Entity.Company" xml:space="preserve">
    <value>Azienda</value>
  </data>
  <data name="Crm.Entity.NotSaid" xml:space="preserve">
    <value>Non indicato</value>
  </data>
  <data name="Crm.Engagement.Detached" xml:space="preserve">
    <value>1 Detached (Distaccato)</value>
  </data>
  <data name="Crm.Engagement.Lukewarm" xml:space="preserve">
    <value>2 Lukewarm (Tiepido)</value>
  </data>
  <data name="Crm.Engagement.Interested" xml:space="preserve">
    <value>3 Interested (Interessato)</value>
  </data>
  <data name="Crm.Engagement.Committed" xml:space="preserve">
    <value>4 Committed (Impegnato)</value>
  </data>
  <data name="Crm.Engagement.Passionate" xml:space="preserve">
    <value>5 Passionate (Appassionato)</value>
  </data>
  <data name="Crm.Kind.Call" xml:space="preserve">
    <value>Chiamata</value>
  </data>
  <data name="Crm.Kind.InPerson" xml:space="preserve">
    <value>Di persona</value>
  </data>
  <data name="Crm.Kind.Message" xml:space="preserve">
    <value>Messaggio</value>
  </data>
  <data name="Crm.Kind.Email" xml:space="preserve">
    <value>Email</value>
  </data>
  <data name="Crm.Kind.Event" xml:space="preserve">
    <value>Evento</value>
  </data>
  <data name="Crm.Silence.Week" xml:space="preserve">
    <value>Non da una settimana</value>
  </data>
  <data name="Crm.Silence.Month" xml:space="preserve">
    <value>Non da un mese</value>
  </data>
  <data name="Crm.Silence.ThreeMonths" xml:space="preserve">
    <value>Non da 3 mesi</value>
  </data>
  <data name="Crm.Silence.Ever" xml:space="preserve">
    <value>Mai</value>
  </data>
  <data name="Crm.Due.Overdue" xml:space="preserve">
    <value>In ritardo</value>
  </data>
  <data name="Crm.Due.Week" xml:space="preserve">
    <value>In scadenza entro una settimana</value>
  </data>
  <data name="Crm.NextLine" xml:space="preserve">
    <value>{0} entro il {1}</value>
  </data>
  <data name="Crm.Delete" xml:space="preserve">
    <value>Elimina</value>
  </data>
  <data name="Crm.Interactions" xml:space="preserve">
    <value>Interazioni</value>
  </data>
  <data name="Crm.Next" xml:space="preserve">
    <value>Prossima azione</value>
  </data>
  <data name="Crm.Ephemeral" xml:space="preserve">
    <value>Contatti di sviluppo, tenuti in memoria: tutto ciò che è qui si perde al riavvio della console.</value>
  </data>
  <data name="Crm.PeopleUnread" xml:space="preserve">
    <value>I nomi offerti in &lt;em&gt;Portato da&lt;/em&gt; non si sono potuti leggere dai ruoli, perciò per ora è offerto solo il tuo. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Unreadable.Title" xml:space="preserve">
    <value>I contatti non si sono potuti leggere</value>
  </data>
  <data name="Crm.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; non è nel Key Vault, perciò non c'è dove tenere un contatto: nulla si può aggiungere o cambiare finché il database non è configurato (&lt;code&gt;docs/Provisioning.md&lt;/code&gt;, parte C).</value>
  </data>
  <data name="Crm.Field.Name" xml:space="preserve">
    <value>Nome</value>
  </data>
  <data name="Crm.Field.Headline" xml:space="preserve">
    <value>Attività attuale</value>
  </data>
  <data name="Crm.Field.Organisation" xml:space="preserve">
    <value>Organizzazione</value>
  </data>
  <data name="Crm.Field.Entity" xml:space="preserve">
    <value>Persona o azienda</value>
  </data>
  <data name="Crm.Field.Email" xml:space="preserve">
    <value>Email</value>
  </data>
  <data name="Crm.Field.Phone" xml:space="preserve">
    <value>Telefono</value>
  </data>
  <data name="Crm.Field.Stage" xml:space="preserve">
    <value>Fase</value>
  </data>
  <data name="Crm.Field.By" xml:space="preserve">
    <value>Portato da</value>
  </data>
  <data name="Crm.Field.Engagement" xml:space="preserve">
    <value>Livello di coinvolgimento</value>
  </data>
  <data name="Crm.Field.Met" xml:space="preserve">
    <value>Incontrato?</value>
  </data>
  <data name="Crm.Field.With" xml:space="preserve">
    <value>Con chi?</value>
  </data>
  <data name="Crm.Field.Presentation" xml:space="preserve">
    <value>Presentazione</value>
  </data>
  <data name="Crm.Field.DeclineReason" xml:space="preserve">
    <value>Motivo del rifiuto</value>
  </data>
  <data name="Crm.Field.DeclineReason.Title" xml:space="preserve">
    <value>Contato nelle Statistiche finché la fase è Ha declinato o inattivo.</value>
  </data>
  <data name="Crm.Field.Track" xml:space="preserve">
    <value>Tipo di partnership</value>
  </data>
  <data name="Crm.Field.Notes" xml:space="preserve">
    <value>Note</value>
  </data>
  <data name="Crm.Contacts.Lead" xml:space="preserve">
    <value>Il programma partner e ambassador, una riga per persona, nelle colonne del foglio con i nomi del foglio.</value>
  </data>
  <data name="Crm.Contacts.Lead.Edit" xml:space="preserve">
    <value>Clicca una cella per cambiarla: Invio o l'uscita dalla cella salva, Esc annulla, e un menu a tendina salva alla scelta. Ogni salvataggio è registrato a tuo nome, e una cella cambiata da un collega da quando hai aperto la griglia non viene mai sovrascritta: ti vengono mostrati il suo valore e il tuo. La prima riga è vuota, qualunque sia l'ordinamento: scrivici un nome per aggiungere un contatto. &lt;em&gt;Incontrato?&lt;/em&gt; e &lt;em&gt;Con chi?&lt;/em&gt; sono le interazioni: clicca l'una o l'altra per vederle e registrare una chiamata o un incontro. Il nome apre i dettagli della riga, con i campi che non sono colonne.</value>
  </data>
  <data name="Crm.Contacts.Lead.ViewOnly" xml:space="preserve">
    <value>Puoi vedere la griglia, non cambiarla: serve {0}, che un Amministratore concede nella pagina Utenti. Il nome apre i dettagli della riga, e un clic su &lt;em&gt;Incontrato?&lt;/em&gt; o &lt;em&gt;Con chi?&lt;/em&gt; le interazioni.</value>
  </data>
  <data name="Crm.Contacts.Unreadable.Detail" xml:space="preserve">
    <value>Il motivo è nel log della console, sotto "The contacts grid could not read the CRM". Nulla si può cambiare finché non si possono leggere.</value>
  </data>
  <data name="Crm.Contacts.Deleted.Notice" xml:space="preserve">
    <value>&lt;strong&gt;Eliminato.&lt;/strong&gt; Il contatto non è più nella griglia, un Amministratore può ripristinarlo da Contatti eliminati, e il registro di audit ne ha la voce.</value>
  </data>
  <data name="Crm.Contacts.Count.One" xml:space="preserve">
    <value>1 contatto</value>
  </data>
  <data name="Crm.Contacts.Count.Many" xml:space="preserve">
    <value>{0} contatti</value>
  </data>
  <data name="Crm.Contacts.Count.OneMatch" xml:space="preserve">
    <value>1 contatto corrisponde</value>
  </data>
  <data name="Crm.Contacts.Count.ManyMatch" xml:space="preserve">
    <value>{0} contatti corrispondono</value>
  </data>
  <data name="Crm.Contacts.Order" xml:space="preserve">
    <value>Per nome. Clicca un'intestazione per ordinare; i menu sotto le intestazioni filtrano, come il filtro automatico del foglio.</value>
  </data>
  <data name="Crm.Contacts.SearchPlaceholder" xml:space="preserve">
    <value>Nome, attività, organizzazione o presentazione</value>
  </data>
  <data name="Crm.Contacts.Export.Title" xml:space="preserve">
    <value>Ogni contatto e interazione, come contacts.csv e interactions.csv in uno zip. Registrato nel registro di audit.</value>
  </data>
  <data name="Crm.Contacts.Import" xml:space="preserve">
    <value>Importa</value>
  </data>
  <data name="Crm.Contacts.Import.Title" xml:space="preserve">
    <value>Contatti e interazioni nel formato dell'esportazione: l'importazione una tantum del foglio, o un ripristino.</value>
  </data>
  <data name="Crm.Contacts.Empty" xml:space="preserve">
    <value>Ancora nessun contatto.</value>
  </data>
  <data name="Crm.Contacts.Empty.Filtered" xml:space="preserve">
    <value>Nessun contatto corrisponde.</value>
  </data>
  <data name="Crm.Contacts.MetSorts" xml:space="preserve">
    <value>Ordina per l'interazione più recente</value>
  </data>
  <data name="Crm.Contacts.Filter.By" xml:space="preserve">
    <value>Filtra per chi ha portato il contatto</value>
  </data>
  <data name="Crm.Contacts.Anyone" xml:space="preserve">
    <value>Chiunque</value>
  </data>
  <data name="Crm.Contacts.Filter.Engagement" xml:space="preserve">
    <value>Filtra per coinvolgimento, almeno</value>
  </data>
  <data name="Crm.Contacts.OrWarmer" xml:space="preserve">
    <value>{0} o più caldo</value>
  </data>
  <data name="Crm.Contacts.Filter.Since" xml:space="preserve">
    <value>Filtra per non contattato da</value>
  </data>
  <data name="Crm.Contacts.Filter.Track" xml:space="preserve">
    <value>Filtra per tipo di partnership</value>
  </data>
  <data name="Crm.Contacts.Filter.Entity" xml:space="preserve">
    <value>Filtra per persona o azienda</value>
  </data>
  <data name="Crm.Contacts.Filter.Stage" xml:space="preserve">
    <value>Filtra per fase</value>
  </data>
  <data name="Crm.Contacts.AddHint" xml:space="preserve">
    <value>Aggiungi un contatto: clicca qui e scrivi un nome</value>
  </data>
  <data name="Crm.Contacts.SetOnCreate" xml:space="preserve">
    <value>Impostato alla creazione del contatto</value>
  </data>
  <data name="Crm.Contacts.ClickForInteractions" xml:space="preserve">
    <value>Clicca per le interazioni</value>
  </data>
  <data name="Crm.Contacts.NoDatabase.Create" xml:space="preserve">
    <value>La console non ha un database, perciò nessun contatto si può registrare.</value>
  </data>
  <data name="Crm.Contacts.ChooseBy" xml:space="preserve">
    <value>Chi ha portato il contatto?</value>
  </data>
  <data name="Crm.Contacts.ChooseBy.Short" xml:space="preserve">
    <value>Scegli…</value>
  </data>
  <data name="Crm.Contacts.NoDatabase.Save" xml:space="preserve">
    <value>La console non ha un database, perciò nulla si può salvare.</value>
  </data>
  <data name="Crm.Contacts.NotSaved" xml:space="preserve">
    <value>Il contatto non si è potuto salvare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Contacts.CellNotSaved" xml:space="preserve">
    <value>La cella non si è potuta salvare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Contacts.NoVersion" xml:space="preserve">
    <value>La versione della riga non è stata inviata. Ricarica la pagina.</value>
  </data>
  <data name="Crm.Contacts.Deleted" xml:space="preserve">
    <value>Questo contatto è stato eliminato.</value>
  </data>
  <data name="Crm.Contacts.NotDeleted" xml:space="preserve">
    <value>Nulla è cambiato: il contatto non si è potuto eliminare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Edit.NameRequired" xml:space="preserve">
    <value>Un contatto ha bisogno di un nome.</value>
  </data>
  <data name="Crm.Edit.TooLong" xml:space="preserve">
    <value>{0} è al massimo di {1} caratteri.</value>
  </data>
  <data name="Crm.Edit.Field.Name" xml:space="preserve">
    <value>Un nome</value>
  </data>
  <data name="Crm.Edit.Field.Headline" xml:space="preserve">
    <value>L'attività attuale</value>
  </data>
  <data name="Crm.Edit.Field.Notes" xml:space="preserve">
    <value>Le note sono</value>
  </data>
  <data name="Crm.Edit.Field.Presentation" xml:space="preserve">
    <value>La presentazione</value>
  </data>
  <data name="Crm.Edit.Field.Organisation" xml:space="preserve">
    <value>Un'organizzazione</value>
  </data>
  <data name="Crm.Edit.Field.Email" xml:space="preserve">
    <value>Un indirizzo email</value>
  </data>
  <data name="Crm.Edit.Field.Phone" xml:space="preserve">
    <value>Un numero di telefono</value>
  </data>
  <data name="Crm.Edit.Field.LinkedIn" xml:space="preserve">
    <value>Un indirizzo LinkedIn</value>
  </data>
  <data name="Crm.Edit.ByRequired" xml:space="preserve">
    <value>Indica chi ha portato il contatto.</value>
  </data>
  <data name="Crm.Edit.ByNoRole" xml:space="preserve">
    <value>{0} non ha un ruolo CRM, perciò un contatto non può indicarlo.</value>
  </data>
  <data name="Crm.Edit.Engagement" xml:space="preserve">
    <value>Il coinvolgimento va da 1 a 5, o vuoto.</value>
  </data>
  <data name="Crm.Edit.Track" xml:space="preserve">
    <value>Non è un tipo di partnership che la console conosce.</value>
  </data>
  <data name="Crm.Edit.Stage" xml:space="preserve">
    <value>Non è una fase che la console conosce.</value>
  </data>
  <data name="Crm.Edit.DeclineReason" xml:space="preserve">
    <value>Non è un motivo che la console conosce.</value>
  </data>
  <data name="Crm.Edit.Entity" xml:space="preserve">
    <value>Scegli Persona fisica, Azienda o Non indicato.</value>
  </data>
  <data name="Crm.Edit.Email" xml:space="preserve">
    <value>Non è un indirizzo email.</value>
  </data>
  <data name="Crm.Edit.LinkedIn" xml:space="preserve">
    <value>Un indirizzo LinkedIn comincia con https://.</value>
  </data>
  <data name="Crm.Edit.NotACell" xml:space="preserve">
    <value>Non è una cella modificabile.</value>
  </data>
  <data name="Crm.Details.Lead" xml:space="preserve">
    <value>La stessa riga da sola, con i campi che non sono colonne. Si modifica come la griglia: clicca una cella, e lo stesso salvataggio va nello stesso posto.</value>
  </data>
  <data name="Crm.Details.ViewOnly" xml:space="preserve">
    <value>Puoi vedere questo contatto, non cambiarlo: serve {0}.</value>
  </data>
  <data name="Crm.Details.Title" xml:space="preserve">
    <value>Dettagli</value>
  </data>
  <data name="Crm.Details.Subtitle" xml:space="preserve">
    <value>Non sono colonne, per tenere la larghezza del foglio. La ricerca copre l'organizzazione.</value>
  </data>
  <data name="Crm.Details.EnteredBy" xml:space="preserve">
    <value>Inserito da</value>
  </data>
  <data name="Crm.Details.LastChangedBy" xml:space="preserve">
    <value>Ultima modifica di</value>
  </data>
  <data name="Crm.Details.Timeline" xml:space="preserve">
    <value>Prossima azione e interazioni</value>
  </data>
  <data name="Crm.Details.Timeline.Subtitle" xml:space="preserve">
    <value>Cosa c'è da fare, chi lo fa ed entro quando, e ogni chiamata, incontro e messaggio, per data, con chi ha partecipato e cosa si è detto: le righe di &lt;em&gt;Incontrato?&lt;/em&gt; e &lt;em&gt;Con chi?&lt;/em&gt;, con ciò che c'è dietro. Ciascuna è registrata a nome di chi l'ha inserita. Un incontro pianificato è una prossima azione finché non è avvenuto; poi è un'interazione.</value>
  </data>
  <data name="Crm.Details.Delete.Lead" xml:space="preserve">
    <value>Toglie il contatto e le sue interazioni dalle pagine del CRM, non dal database: spetta a un Amministratore, e si ripristina da Contatti eliminati. Confermi nella pagina successiva digitando il nome del contatto, e viene registrato nell'audit con l'id e il nome del contatto.</value>
  </data>
  <data name="Crm.Delete.Title" xml:space="preserve">
    <value>Elimina un contatto</value>
  </data>
  <data name="Crm.Delete.Heading" xml:space="preserve">
    <value>Elimina {0}</value>
  </data>
  <data name="Crm.Delete.Lead" xml:space="preserve">
    <value>Il contatto esce dalle pagine del CRM, e con lui le sue interazioni: la griglia, i follow-up, la panoramica e ogni esportazione. Nulla esce dal database, e un Amministratore può ripristinarlo da Contatti eliminati. Il registro di audit conserva che è stato eliminato, da chi, e l'id e il nome del contatto, e nient'altro della riga.</value>
  </data>
  <data name="Crm.Delete.TheContact" xml:space="preserve">
    <value>Il contatto</value>
  </data>
  <data name="Crm.Delete.Interactions.None" xml:space="preserve">
    <value>Nessuna</value>
  </data>
  <data name="Crm.Delete.Interactions.One" xml:space="preserve">
    <value>Una, eliminata con il contatto</value>
  </data>
  <data name="Crm.Delete.Interactions.Many" xml:space="preserve">
    <value>{0}, eliminate con il contatto</value>
  </data>
  <data name="Crm.Delete.WhatItDoes" xml:space="preserve">
    <value>Cosa fa l'eliminazione</value>
  </data>
  <data name="Crm.Delete.Detail" xml:space="preserve">
    <value>La riga esce dalla griglia, e a un collega con la griglia aperta viene detto che il contatto è stato eliminato al prossimo salvataggio di una sua cella. Registrato come {0} nel registro di audit, come &lt;code&gt;crm:contact-delete&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Delete.Submit" xml:space="preserve">
    <value>Elimina contatto</value>
  </data>
  <data name="Crm.Delete.TypeName" xml:space="preserve">
    <value>Per eliminarlo, digita il nome del contatto, {0}:</value>
  </data>
  <data name="Crm.Delete.NameMismatch" xml:space="preserve">
    <value>Non è stato eliminato nulla: il nome digitato non è quello del contatto. Digitalo come è mostrato per eliminare il contatto.</value>
  </data>
  <data name="Crm.Deleted.Title" xml:space="preserve">
    <value>Contatti eliminati</value>
  </data>
  <data name="Crm.Deleted.Lead" xml:space="preserve">
    <value>Contatti che un Amministratore ha eliminato. L'eliminazione è reversibile: il contatto e le sue interazioni restano nel database, fuori dalla griglia, dai follow-up, dalla panoramica e da ogni esportazione, e &lt;em&gt;Ripristina&lt;/em&gt; li riporta com'erano. Cancellare definitivamente una persona che chiede di essere rimossa spetta a un operatore, come dice &lt;code&gt;docs/Operations.md&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Deleted.Lead.Short" xml:space="preserve">
    <value>Contatti eliminati, che un Amministratore può ripristinare.</value>
  </data>
  <data name="Crm.Deleted.Unreadable" xml:space="preserve">
    <value>Non è stato possibile leggere il CRM, quindi i contatti eliminati non si possono elencare.</value>
  </data>
  <data name="Crm.Deleted.NotRestored" xml:space="preserve">
    <value>Non è stato possibile ripristinare il contatto; non è cambiato nulla. Riprova.</value>
  </data>
  <data name="Crm.Deleted.Restored" xml:space="preserve">
    <value>&lt;strong&gt;Ripristinato.&lt;/strong&gt; {0} è di nuovo nel CRM, con le sue interazioni, e il registro di audit ne ha la voce.</value>
  </data>
  <data name="Crm.Deleted.Count.One" xml:space="preserve">
    <value>1 contatto eliminato</value>
  </data>
  <data name="Crm.Deleted.Count.Many" xml:space="preserve">
    <value>{0} contatti eliminati</value>
  </data>
  <data name="Crm.Deleted.Empty" xml:space="preserve">
    <value>Nessun contatto è stato eliminato.</value>
  </data>
  <data name="Crm.Deleted.DeletedBy" xml:space="preserve">
    <value>Eliminato da</value>
  </data>
  <data name="Crm.Deleted.DeletedAt" xml:space="preserve">
    <value>Eliminato il</value>
  </data>
  <data name="Crm.Deleted.Restore" xml:space="preserve">
    <value>Ripristina</value>
  </data>
  <data name="Crm.FollowUps.Lead" xml:space="preserve">
    <value>Cosa c'è da fare, chi lo fa ed entro quando: ogni contatto con una prossima azione, prima quelle in ritardo e poi per data di scadenza, per ultime quelle senza data. La prossima azione è l'ultima riga di &lt;em&gt;Incontrato?&lt;/em&gt; e il suo responsabile l'ultima riga di &lt;em&gt;Con chi?&lt;/em&gt;, come in {0}: una riga qui è la riga là.</value>
  </data>
  <data name="Crm.FollowUps.Lead.Edit" xml:space="preserve">
    <value>Clicca &lt;em&gt;Incontrato?&lt;/em&gt; o &lt;em&gt;Con chi?&lt;/em&gt; per impostarla, cambiarla o cancellarla, o per registrare la chiamata che la chiude; clicca qualsiasi altra cella per cambiarla, come in Partnership.</value>
  </data>
  <data name="Crm.FollowUps.Lead.ViewOnly" xml:space="preserve">
    <value>Puoi vedere i follow-up, non cambiarli: serve {0}.</value>
  </data>
  <data name="Crm.FollowUps.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; non è nel Key Vault, perciò non c'è dove tenere un contatto o la sua prossima azione.</value>
  </data>
  <data name="Crm.FollowUps.Unreadable.Title" xml:space="preserve">
    <value>I follow-up non si sono potuti leggere</value>
  </data>
  <data name="Crm.FollowUps.Unreadable.Detail" xml:space="preserve">
    <value>Il motivo è nel log della console, sotto "The follow-ups grid could not read the CRM". Nulla si può cambiare finché non si possono leggere.</value>
  </data>
  <data name="Crm.FollowUps.Count.One" xml:space="preserve">
    <value>1 follow-up</value>
  </data>
  <data name="Crm.FollowUps.Count.Many" xml:space="preserve">
    <value>{0} follow-up</value>
  </data>
  <data name="Crm.FollowUps.OfYours" xml:space="preserve">
    <value> tuoi</value>
  </data>
  <data name="Crm.FollowUps.For" xml:space="preserve">
    <value> di {0}</value>
  </data>
  <data name="Crm.FollowUps.OverdueCount" xml:space="preserve">
    <value>, {0} in ritardo</value>
  </data>
  <data name="Crm.FollowUps.Order" xml:space="preserve">
    <value>Prima quelli in ritardo, poi per data di scadenza, al {0} (UTC). Clicca un'intestazione per ordinare diversamente; ricarica per tornare a quest'ordine.</value>
  </data>
  <data name="Crm.FollowUps.Mine" xml:space="preserve">
    <value>Miei</value>
  </data>
  <data name="Crm.FollowUps.Mine.On" xml:space="preserve">
    <value>Mostra le tue prossime azioni: clicca per quelle di tutti</value>
  </data>
  <data name="Crm.FollowUps.Mine.Off" xml:space="preserve">
    <value>Le prossime azioni di cui sei responsabile</value>
  </data>
  <data name="Crm.FollowUps.Filter.Owner" xml:space="preserve">
    <value>Filtra per responsabile</value>
  </data>
  <data name="Crm.FollowUps.Anyones" xml:space="preserve">
    <value>Di chiunque</value>
  </data>
  <data name="Crm.FollowUps.Filter.Due" xml:space="preserve">
    <value>Filtra per scadenza</value>
  </data>
  <data name="Crm.FollowUps.Empty" xml:space="preserve">
    <value>Non c'è nulla da fare: nessun contatto ha una prossima azione.</value>
  </data>
  <data name="Crm.FollowUps.Empty.Filtered" xml:space="preserve">
    <value>Nessun follow-up corrisponde.</value>
  </data>
  <data name="Crm.Next.ForOwner" xml:space="preserve">
    <value>di {0}, </value>
  </data>
  <data name="Crm.Next.Due" xml:space="preserve">
    <value>entro il {0}</value>
  </data>
  <data name="Crm.Next.NoDueDate" xml:space="preserve">
    <value>senza data di scadenza</value>
  </data>
  <data name="Crm.Next.None" xml:space="preserve">
    <value>Nessuna: non c'è nulla da fare per questo contatto.</value>
  </data>
  <data name="Crm.Next.Set" xml:space="preserve">
    <value>Imposta</value>
  </data>
  <data name="Crm.Next.Change" xml:space="preserve">
    <value>Cambia</value>
  </data>
  <data name="Crm.Next.Clear.Title" xml:space="preserve">
    <value>Salva i tre campi vuoti e non registra nulla: per una non più da fare. Per una fatta, usa Fatta</value>
  </data>
  <data name="Crm.Next.Done" xml:space="preserve">
    <value>Fatta</value>
  </data>
  <data name="Crm.Next.Done.Title" xml:space="preserve">
    <value>Registrala subito come fatta: una chiamata di oggi con il suo testo, e la prossima azione azzerata. Per cambiarla, modifica poi l'interazione</value>
  </data>
  <data name="Crm.Next.What" xml:space="preserve">
    <value>Cosa c'è da fare</value>
  </data>
  <data name="Crm.Next.ByWhom" xml:space="preserve">
    <value>Chi</value>
  </data>
  <data name="Crm.Next.ByWhen" xml:space="preserve">
    <value>Entro quando</value>
  </data>
  <data name="Crm.Next.Placeholder" xml:space="preserve">
    <value>Scrivi qui la prossima azione</value>
  </data>
  <data name="Crm.Next.Title.Due" xml:space="preserve">
    <value>Prossima azione, entro il {0}</value>
  </data>
  <data name="Crm.Next.Title.Overdue" xml:space="preserve">
    <value>Prossima azione, entro il {0}: in ritardo</value>
  </data>
  <data name="Crm.Next.Title.NoDate" xml:space="preserve">
    <value>Prossima azione, senza data di scadenza</value>
  </data>
  <data name="Crm.Next.Problem.TextRequired" xml:space="preserve">
    <value>Indica cosa c'è da fare entro allora, o cancella la data.</value>
  </data>
  <data name="Crm.Next.Problem.TooLong" xml:space="preserve">
    <value>Una prossima azione è al massimo di {0} caratteri: il resto va nel riepilogo di un'interazione o nelle note.</value>
  </data>
  <data name="Crm.Next.Problem.OwnerRequired" xml:space="preserve">
    <value>Indica chi deve farlo.</value>
  </data>
  <data name="Crm.Next.Problem.NoRole" xml:space="preserve">
    <value>{0} non ha un ruolo CRM, perciò una prossima azione non può essere sua.</value>
  </data>
  <data name="Crm.Next.Problem.NotADate" xml:space="preserve">
    <value>La data di scadenza è una data, o vuota.</value>
  </data>
  <data name="Crm.Next.Problem.Year" xml:space="preserve">
    <value>Controlla l'anno della data di scadenza.</value>
  </data>
  <data name="Crm.Next.Unsaved" xml:space="preserve">
    <value>Nulla è stato scritto: la prossima azione non si è potuta salvare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Next.Conflict" xml:space="preserve">
    <value>Il contatto è stato cambiato da {0} alle {1} dopo che questo pannello è stato disegnato. Nulla di tuo è stato scritto: la prossima azione com'è ora è mostrata, e ciò che hai scritto è nel modulo. Salvalo per sostituirla, o annulla.</value>
  </data>
  <data name="Crm.Interactions.None" xml:space="preserve">
    <value>Ancora nessuna interazione.</value>
  </data>
  <data name="Crm.Interactions.With" xml:space="preserve">
    <value>con {0}</value>
  </data>
  <data name="Crm.Interactions.RecordedBy" xml:space="preserve">
    <value>Registrata da {0}, {1}</value>
  </data>
  <data name="Crm.Interactions.ChangedBy" xml:space="preserve">
    <value>; modificata da {0}, {1}</value>
  </data>
  <data name="Crm.Interactions.DeleteConfirm" xml:space="preserve">
    <value>Eliminare questa interazione? Non si può annullare, e il registro di audit lo registra.</value>
  </data>
  <data name="Crm.Interactions.Keep" xml:space="preserve">
    <value>Mantieni</value>
  </data>
  <data name="Crm.Interactions.Log" xml:space="preserve">
    <value>Registra un'interazione</value>
  </data>
  <data name="Crm.Interactions.AndNext" xml:space="preserve">
    <value>E cosa viene dopo: sostituisce la prossima azione sopra</value>
  </data>
  <data name="Crm.Interactions.NoNext.Ask" xml:space="preserve">
    <value>Nessuna prossima azione prevista?</value>
  </data>
  <data name="Crm.Interactions.NoNext.Yes" xml:space="preserve">
    <value>Sì: registrala e cancella la prossima azione</value>
  </data>
  <data name="Crm.Interactions.NoNext.Keep" xml:space="preserve">
    <value>Registrala e mantieni quella attuale</value>
  </data>
  <data name="Crm.Interactions.NoNext.Back" xml:space="preserve">
    <value>No, la scrivo</value>
  </data>
  <data name="Crm.Interactions.Done" xml:space="preserve">
    <value>Registra la prossima azione come fatta</value>
  </data>
  <data name="Crm.Interactions.Done.AndNext" xml:space="preserve">
    <value>E cosa viene dopo, se c'è: lasciata vuota, la prossima azione viene azzerata</value>
  </data>
  <data name="Crm.Interactions.Add" xml:space="preserve">
    <value>Aggiungi</value>
  </data>
  <data name="Crm.Interactions.ViewOnly" xml:space="preserve">
    <value>Puoi vedere le interazioni e la prossima azione, non cambiarle: serve {0}.</value>
  </data>
  <data name="Crm.Interaction.When" xml:space="preserve">
    <value>Quando</value>
  </data>
  <data name="Crm.Interaction.Kind" xml:space="preserve">
    <value>Tipo</value>
  </data>
  <data name="Crm.Interaction.With" xml:space="preserve">
    <value>Con, da KnowledgeFabric</value>
  </data>
  <data name="Crm.Interaction.Summary" xml:space="preserve">
    <value>Cosa si è detto</value>
  </data>
  <data name="Crm.Interaction.Problem.DateRequired" xml:space="preserve">
    <value>Indica quando è avvenuta: una data.</value>
  </data>
  <data name="Crm.Interaction.Problem.Year" xml:space="preserve">
    <value>Controlla l'anno: il CRM tiene le interazioni dal 2000 in avanti.</value>
  </data>
  <data name="Crm.Interaction.Problem.Future" xml:space="preserve">
    <value>Un'interazione è qualcosa che è avvenuto. Una pianificata è una prossima azione, non un'interazione.</value>
  </data>
  <data name="Crm.Interaction.Problem.Kind" xml:space="preserve">
    <value>Non è un tipo di interazione che la console conosce.</value>
  </data>
  <data name="Crm.Interaction.Problem.NoRole" xml:space="preserve">
    <value>{0} non ha un ruolo CRM, perciò un'interazione non può indicarlo.</value>
  </data>
  <data name="Crm.Problem.Admin" xml:space="preserve">
    <value>admin non è una persona, perciò il CRM non lo indica mai: scegli chi era.</value>
  </data>
  <data name="Crm.Interaction.Problem.ParticipantsRequired" xml:space="preserve">
    <value>Indica chi di KnowledgeFabric ha partecipato: almeno un nome.</value>
  </data>
  <data name="Crm.Interaction.Problem.SummaryRequired" xml:space="preserve">
    <value>Indica cosa si è detto: un'interazione ha bisogno di un riepilogo.</value>
  </data>
  <data name="Crm.Interaction.Problem.SummaryTooLong" xml:space="preserve">
    <value>Un riepilogo è al massimo di {0} caratteri.</value>
  </data>
  <data name="Crm.Interaction.Unsaved" xml:space="preserve">
    <value>Nulla è stato scritto: l'interazione non si è potuta salvare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Interaction.UnsavedAfterNext" xml:space="preserve">
    <value>La prossima azione è stata salvata; l'interazione no: non si è potuta scrivere. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Interaction.NoVersion" xml:space="preserve">
    <value>La versione del contatto non è stata inviata. Ricarica la pagina.</value>
  </data>
  <data name="Crm.Interaction.NoOwnVersion" xml:space="preserve">
    <value>La versione dell'interazione non è stata inviata. Ricarica la pagina.</value>
  </data>
  <data name="Crm.Interaction.NotDeleted" xml:space="preserve">
    <value>Nulla è cambiato: l'interazione non si è potuta eliminare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Interaction.AlreadyDeleted" xml:space="preserve">
    <value>Un collega aveva già eliminato quell'interazione.</value>
  </data>
  <data name="Crm.Interaction.Conflict.Add" xml:space="preserve">
    <value>Il contatto è stato cambiato da {0} alle {1} dopo che questo pannello è stato disegnato, perciò né l'interazione né la prossima azione sono state scritte. La prossima azione com'è ora è mostrata sopra, e ciò che hai scritto è nel modulo sotto: aggiungilo di nuovo per registrare l'interazione e sostituire la prossima azione, consapevolmente.</value>
  </data>
  <data name="Crm.Interaction.Conflict.Update" xml:space="preserve">
    <value>Modificata da {0} alle {1} mentre la stavi modificando. Nulla di tuo è stato scritto: è mostrata la sua versione, e ciò che hai scritto è nel modulo. Salvalo per sostituirla, o annulla.</value>
  </data>
  <data name="Crm.Interaction.Conflict.Delete" xml:space="preserve">
    <value>Modificata da {0} alle {1} dopo che l'hai aperta, perciò non è stata eliminata. È mostrata com'è ora: eliminala di nuovo se deve comunque sparire.</value>
  </data>
  <data name="Crm.Interaction.DeletedWhileEditing" xml:space="preserve">
    <value>Un collega ha eliminato quell'interazione mentre la stavi modificando. Nulla di tuo è stato scritto: ciò che hai scritto è nel modulo sotto, per aggiungerla di nuovo se deve restare.</value>
  </data>
  <data name="Crm.Import.Title" xml:space="preserve">
    <value>Importa contatti</value>
  </data>
  <data name="Crm.Import.Lead" xml:space="preserve">
    <value>&lt;code&gt;contacts.csv&lt;/code&gt; e &lt;code&gt;interactions.csv&lt;/code&gt;, nel formato di esportazione del CRM, scritti nel CRM in una volta: l'importazione una tantum del foglio, preparata a mano a partire da esso, o un ripristino da &lt;em&gt;Esporta CSV&lt;/em&gt;. Ogni valore è controllato come lo controlla la griglia, e nulla viene scritto finché non hai visto cosa i file creerebbero. Un contatto il cui nome è già nel CRM rifiuta l'intera importazione, perciò gli stessi file non si possono importare due volte. Il formato e la mappatura del foglio sono in &lt;code&gt;docs/CRM.md&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Import.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; non è nel Key Vault, perciò non c'è dove importare. I file si possono controllare, non scrivere.</value>
  </data>
  <data name="Crm.Import.Ephemeral" xml:space="preserve">
    <value>Contatti di sviluppo, tenuti in memoria: un'importazione qui si perde al riavvio della console.</value>
  </data>
  <data name="Crm.Import.Imported" xml:space="preserve">
    <value>Importato</value>
  </data>
  <data name="Crm.Import.Counts" xml:space="preserve">
    <value>{0}, {1} e {2}</value>
  </data>
  <data name="Crm.Import.Imported.Detail" xml:space="preserve">
    <value>{0}, inseriti da {1} e registrati nel registro di audit come &lt;code&gt;crm:import&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Import.TheContacts" xml:space="preserve">
    <value>I contatti</value>
  </data>
  <data name="Crm.Import.And" xml:space="preserve">
    <value>e</value>
  </data>
  <data name="Crm.Import.TheFollowUps" xml:space="preserve">
    <value>i follow-up</value>
  </data>
  <data name="Crm.Import.TheFiles" xml:space="preserve">
    <value>I file</value>
  </data>
  <data name="Crm.Import.NotYet" xml:space="preserve">
    <value>Non si può ancora importare nulla</value>
  </data>
  <data name="Crm.Import.NotYet.Detail" xml:space="preserve">
    <value>Correggi i file e scegli di nuovo. Nulla è stato scritto.</value>
  </data>
  <data name="Crm.Import.WillCreate" xml:space="preserve">
    <value>Cosa creerà l'importazione</value>
  </data>
  <data name="Crm.Import.WillCreate.Detail" xml:space="preserve">
    <value>{0}, ciascuno inserito da {1}, con &lt;em&gt;Portato da&lt;/em&gt; come dice il file.</value>
  </data>
  <data name="Crm.Import.WithoutSummary.One" xml:space="preserve">
    <value>1 interazione non ha riepilogo nel file e riporterà {0}.</value>
  </data>
  <data name="Crm.Import.WithoutSummary.Many" xml:space="preserve">
    <value>{0} interazioni non hanno riepilogo nel file e riporteranno {1}.</value>
  </data>
  <data name="Crm.Import.ChooseOthers" xml:space="preserve">
    <value>Scegli altri file</value>
  </data>
  <data name="Crm.Import.NotCameBack" xml:space="preserve">
    <value>I file non sono tornati dall'anteprima. Scegli di nuovo.</value>
  </data>
  <data name="Crm.Import.NoDatabase" xml:space="preserve">
    <value>La console non ha un database, perciò nulla si può importare.</value>
  </data>
  <data name="Crm.Import.CrmUnread" xml:space="preserve">
    <value>Il CRM non si è potuto leggere, perciò i file non si sono potuti confrontare con esso. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Import.NotWritten" xml:space="preserve">
    <value>Nulla è stato importato: il CRM non si è potuto scrivere. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Import.AlreadyPresent" xml:space="preserve">
    <value>{0} è già un contatto: questi file sono appena stati importati, da questa conferma inviata due volte o da un collega.</value>
  </data>
  <data name="Crm.Import.Choose" xml:space="preserve">
    <value>Scegli {0}.</value>
  </data>
  <data name="Crm.Import.TooLarge" xml:space="preserve">
    <value>{0} è più grande di quanto l'importazione accetti ({1} MB).</value>
  </data>
  <data name="Crm.Import.NotUtf8" xml:space="preserve">
    <value>{0} non è UTF-8. Salvalo dal foglio di calcolo come CSV UTF-8.</value>
  </data>
  <data name="Crm.Import.Where" xml:space="preserve">
    <value>{0}, riga {1}</value>
  </data>
  <data name="Crm.Import.Problem.IdPresent" xml:space="preserve">
    <value>{0}, riga {1}: un contatto ha già l'id {2}. Questo file è stato importato, o il CRM che ripristina non è vuoto.</value>
  </data>
  <data name="Crm.Import.Problem.IdDeleted" xml:space="preserve">
    <value>{0}, riga {1}: l'id {2} è di un contatto eliminato. Ripristinalo da Contatti eliminati invece di importarlo, o toglilo dal file.</value>
  </data>
  <data name="Crm.Import.Problem.NamePresent" xml:space="preserve">
    <value>{0}, riga {1}: {2} è già un contatto. L'importazione è una tantum: questo file è stato importato, o il contatto è stato aggiunto a mano dopo la preparazione del file. Toglilo dal file.</value>
  </data>
  <data name="Crm.Import.Problem.NoContacts" xml:space="preserve">
    <value>{0} non ha contatti: nulla da importare.</value>
  </data>
  <data name="Crm.Import.Problem.More" xml:space="preserve">
    <value>E altri {0}.</value>
  </data>
  <data name="Crm.Import.Problem.BadId" xml:space="preserve">
    <value>{0}: l'id non è uno di quelli che il CRM genera. Lascialo vuoto per un contatto nuovo.</value>
  </data>
  <data name="Crm.Import.Problem.IdTwice" xml:space="preserve">
    <value>{0}: l'id {1} è anche su un'altra riga.</value>
  </data>
  <data name="Crm.Import.Problem.NameTwice" xml:space="preserve">
    <value>{0}, righe {1}: {2} è su più di una riga. Due persone possono avere lo stesso nome, ma allora ogni riga ha bisogno di un id, e le loro interazioni di un contact_id.</value>
  </data>
  <data name="Crm.Import.Problem.ContactIdUnknown" xml:space="preserve">
    <value>{0}: contact_id {1} non è di alcun contatto in {2}.</value>
  </data>
  <data name="Crm.Import.Problem.ContactIdMismatch" xml:space="preserve">
    <value>{0}: contact_id è di {1}, ma la riga indica {2}.</value>
  </data>
  <data name="Crm.Import.Problem.NoContact" xml:space="preserve">
    <value>{0}: indica di chi è l'interazione, sotto contact.</value>
  </data>
  <data name="Crm.Import.Problem.ContactUnknown" xml:space="preserve">
    <value>{0}: {1} non è in {2}, o la sua riga lì è stata rifiutata.</value>
  </data>
  <data name="Crm.Import.Problem.ContactAmbiguous" xml:space="preserve">
    <value>{0}: {1} è su più di una riga di {2}: indica il contact_id.</value>
  </data>
  <data name="Crm.Csv.Empty" xml:space="preserve">
    <value>{0} è vuoto: ha bisogno almeno della riga di intestazione.</value>
  </data>
  <data name="Crm.Csv.Blank" xml:space="preserve">
    <value>(vuoto)</value>
  </data>
  <data name="Crm.Csv.UnknownColumn" xml:space="preserve">
    <value>{0} ha una colonna che il formato non ha: {1}. Le sue colonne sono {2}.</value>
  </data>
  <data name="Crm.Csv.ColumnTwice" xml:space="preserve">
    <value>{0} ha una colonna due volte: {1}.</value>
  </data>
  <data name="Crm.Csv.MissingColumn" xml:space="preserve">
    <value>A {0} manca una colonna: {1}.</value>
  </data>
  <data name="Crm.Csv.ValueCount" xml:space="preserve">
    <value>{0}, riga {1}: {2} valori sotto {3} colonne.</value>
  </data>
  <data name="Crm.Csv.QuoteInside" xml:space="preserve">
    <value>la riga {0} ha virgolette dentro un valore che non comincia con virgolette.</value>
  </data>
  <data name="Crm.Csv.TextAfterQuote" xml:space="preserve">
    <value>la riga {0} ha testo dopo le virgolette di chiusura di un valore.</value>
  </data>
  <data name="Crm.Csv.QuoteUnclosed" xml:space="preserve">
    <value>virgolette aperte alla riga {0} o dopo non vengono mai chiuse.</value>
  </data>
  <data name="Crm.Overview.Lead" xml:space="preserve">
    <value>Il programma partner e ambassador, come record anziché come foglio.</value>
  </data>
  <data name="Crm.Overview.Contacts" xml:space="preserve">
    <value>Contatti</value>
  </data>
  <data name="Crm.Overview.NoDatabase" xml:space="preserve">
    <value>La console non ha un database, perciò non c'è dove tenere un contatto: &lt;code&gt;Database--ConnectionString&lt;/code&gt; non è nel Key Vault (&lt;code&gt;docs/Provisioning.md&lt;/code&gt;, parte C).</value>
  </data>
  <data name="Crm.Overview.Unreadable.Detail" xml:space="preserve">
    <value>Il log della console ha l'eccezione, sotto "The overview could not read the CRM".</value>
  </data>
  <data name="Crm.Statistics.Lead" xml:space="preserve">
    <value>Il programma in numeri, per la storia del go-to-market: ogni contatto identificato, a che punto è, come si sono concluse le discussioni, e i clienti segnalati dai partner. Solo conteggi: qui non è nominato alcun contatto né alcun cliente.</value>
  </data>
  <data name="Crm.Statistics.Unreadable.Detail" xml:space="preserve">
    <value>Il log della console ha l'eccezione, sotto "The CRM's statistics could not read the CRM".</value>
  </data>
  <data name="Crm.Statistics.Funnel" xml:space="preserve">
    <value>Dal contatto alla partnership</value>
  </data>
  <data name="Crm.Statistics.Funnel.Subtitle" xml:space="preserve">
    <value>Ogni riga suddivide quella sopra. I tre modi in cui si chiude una discussione sono quote di quelle concluse.</value>
  </data>
  <data name="Crm.Statistics.Contacts" xml:space="preserve">
    <value>Contatti</value>
  </data>
  <data name="Crm.Statistics.OfConcluded" xml:space="preserve">
    <value>Sulle concluse</value>
  </data>
  <data name="Crm.Statistics.Stages" xml:space="preserve">
    <value>Fasi contate</value>
  </data>
  <data name="Crm.Statistics.Identified" xml:space="preserve">
    <value>Contatti identificati</value>
  </data>
  <data name="Crm.Statistics.AllStages" xml:space="preserve">
    <value>Tutte le fasi</value>
  </data>
  <data name="Crm.Statistics.ToSchedule" xml:space="preserve">
    <value>Da pianificare</value>
  </data>
  <data name="Crm.Statistics.ToMeetSoon" xml:space="preserve">
    <value>Da incontrare a breve</value>
  </data>
  <data name="Crm.Statistics.Met" xml:space="preserve">
    <value>Incontrati</value>
  </data>
  <data name="Crm.Statistics.MetStages" xml:space="preserve">
    <value>{0} e tutte le fasi successive</value>
  </data>
  <data name="Crm.Statistics.InDiscussion" xml:space="preserve">
    <value>Discussione in corso</value>
  </data>
  <data name="Crm.Statistics.Concluded" xml:space="preserve">
    <value>Discussione conclusa</value>
  </data>
  <data name="Crm.Statistics.ConcludedStages" xml:space="preserve">
    <value>Le tre righe sotto</value>
  </data>
  <data name="Crm.Statistics.Accepted" xml:space="preserve">
    <value>Proposta accettata</value>
  </data>
  <data name="Crm.Statistics.Declined" xml:space="preserve">
    <value>Decisione rinviata</value>
  </data>
  <data name="Crm.Statistics.NoReason" xml:space="preserve">
    <value>Motivo non indicato</value>
  </data>
  <data name="Crm.Statistics.Rejected" xml:space="preserve">
    <value>Persona relazionalmente non idonea</value>
  </data>
  <data name="Crm.Statistics.Footnote" xml:space="preserve">
    <value>Contati su tutti i contatti del CRM, eliminati esclusi, secondo la fase in cui ciascuno si trova oggi. Ogni contatto conta, anche uno di prova; eliminarlo lo esclude.</value>
  </data>
  <data name="Crm.Statistics.Footnote.AsOf" xml:space="preserve">
    <value>Contati dallo storico delle fasi: ogni contatto com'era alla fine del {0} UTC, esclusi quelli eliminati entro quel giorno. Un contatto eliminato in seguito conta comunque nei giorni in cui era attivo.</value>
  </data>
  <data name="Crm.Statistics.Funnel.AsOf" xml:space="preserve">
    <value>Com'era alla fine del {0} (UTC).</value>
  </data>
  <data name="Crm.Statistics.AsOf" xml:space="preserve">
    <value>Al</value>
  </data>
  <data name="Crm.Statistics.AsOf.Show" xml:space="preserve">
    <value>Mostra</value>
  </data>
  <data name="Crm.Statistics.AsOf.Today" xml:space="preserve">
    <value>Torna a oggi</value>
  </data>
  <data name="Crm.Statistics.AsOf.Hint" xml:space="preserve">
    <value>Qualsiasi giorno da quando è iniziato lo storico delle fasi, il {0}.</value>
  </data>
  <data name="Crm.Statistics.AsOf.NotADate" xml:space="preserve">
    <value>Questa non è una data che la pagina sa leggere, perciò mostra oggi. Scegli un giorno con il campo data.</value>
  </data>
  <data name="Crm.Statistics.AsOf.Future" xml:space="preserve">
    <value>Il {0} non è ancora arrivato, perciò la pagina mostra oggi.</value>
  </data>
  <data name="Crm.Statistics.AsOf.BeforeRecord" xml:space="preserve">
    <value>Lo storico delle fasi è iniziato il {0} e nulla di precedente è stato conservato, perciò la pagina mostra oggi.</value>
  </data>
  <data name="Crm.Statistics.AsOf.NothingRecorded" xml:space="preserve">
    <value>Non è ancora stato registrato nulla, perciò la pagina mostra oggi.</value>
  </data>
  <data name="Crm.Statistics.AsOf.Unreadable" xml:space="preserve">
    <value>Non è stato possibile leggere lo storico delle fasi, perciò la pagina mostra oggi.</value>
  </data>
  <data name="Crm.Statistics.OverTime" xml:space="preserve">
    <value>Nel tempo</value>
  </data>
  <data name="Crm.Statistics.OverTime.Weekly" xml:space="preserve">
    <value>Contatti identificati, incontrati e con proposta accettata alla fine di ogni settimana, da quando è iniziato lo storico delle fasi, il {0}. Un punto apre il funnel com'era quel giorno.</value>
  </data>
  <data name="Crm.Statistics.OverTime.Monthly" xml:space="preserve">
    <value>Contatti identificati, incontrati e con proposta accettata alla fine di ogni mese, da quando è iniziato lo storico delle fasi, il {0}. Un punto apre il funnel com'era quel giorno.</value>
  </data>
  <data name="Crm.Statistics.OverTime.Nothing" xml:space="preserve">
    <value>Non è ancora stato registrato nulla: lo storico delle fasi inizia con il primo contatto.</value>
  </data>
  <data name="Crm.Statistics.OverTime.TooShort" xml:space="preserve">
    <value>Lo storico delle fasi è iniziato il {0}. Il grafico parte dal giorno dopo.</value>
  </data>
  <data name="Crm.Statistics.OverTime.Unreadable" xml:space="preserve">
    <value>Non è stato possibile leggere lo storico delle fasi. Il log della console riporta l'eccezione, sotto "The CRM's statistics could not read the record of stage changes".</value>
  </data>
  <data name="Crm.Statistics.OverTime.Numbers" xml:space="preserve">
    <value>I numeri</value>
  </data>
  <data name="Crm.Statistics.OverTime.EndOf" xml:space="preserve">
    <value>Fine del</value>
  </data>
  <data name="Crm.Statistics.Introductions" xml:space="preserve">
    <value>Dalla segnalazione al contratto</value>
  </data>
  <data name="Crm.Statistics.Introductions.Subtitle" xml:space="preserve">
    <value>Ciò che i partner hanno prodotto: ogni cliente segnalato da un partner o da un ambassador, a che punto è, per tipo di partnership di chi l'ha segnalato, e fin dove è arrivato. Ogni riga è una quota dei clienti segnalati.</value>
  </data>
  <data name="Crm.Statistics.Customers" xml:space="preserve">
    <value>Clienti</value>
  </data>
  <data name="Crm.Statistics.OfIntroduced" xml:space="preserve">
    <value>Sui segnalati</value>
  </data>
  <data name="Crm.Statistics.Introduced" xml:space="preserve">
    <value>Clienti segnalati</value>
  </data>
  <data name="Crm.Statistics.NotYetMet" xml:space="preserve">
    <value>Non ancora incontrati</value>
  </data>
  <data name="Crm.Statistics.ByPartnerTrack" xml:space="preserve">
    <value>Per tipo di partnership di chi li ha segnalati</value>
  </data>
  <data name="Crm.Statistics.HowFar" xml:space="preserve">
    <value>Fin dove sono arrivati, in qualsiasi momento</value>
  </data>
  <data name="Crm.Statistics.ReachedPilot" xml:space="preserve">
    <value>Arrivati a un pilota</value>
  </data>
  <data name="Crm.Statistics.ReachedContract" xml:space="preserve">
    <value>Arrivati a un contratto</value>
  </data>
  <data name="Crm.Statistics.EverAt" xml:space="preserve">
    <value>{0}, in qualsiasi momento</value>
  </data>
  <data name="Crm.Statistics.Introductions.Footnote" xml:space="preserve">
    <value>Contati su tutte le segnalazioni del CRM, escluse quelle eliminate e quelle dei contatti eliminati, secondo la fase in cui ciascuna si trova oggi e il tipo di partnership attuale di chi l'ha segnalata. Fin dove è arrivata si legge dallo storico delle fasi, quindi una segnalazione arrivata a un pilota e poi andata oltre, o che ha rifiutato, vi conta comunque.</value>
  </data>
  <data name="Crm.Statistics.Introductions.Footnote.AsOf" xml:space="preserve">
    <value>Contati dallo storico delle fasi: ogni segnalazione com'era alla fine del {0} UTC, escluse quelle eliminate entro quel giorno, secondo il tipo di partnership attuale di chi l'ha segnalata. Fin dove è arrivata conta le fasi in cui era stata fino ad allora.</value>
  </data>
  <data name="Crm.Statistics.Introductions.BeforeRecord" xml:space="preserve">
    <value>Il CRM ha iniziato a registrare le segnalazioni il {0}: il {1} non ce n'erano.</value>
  </data>
  <data name="Crm.Statistics.Introductions.Unreadable" xml:space="preserve">
    <value>Non è stato possibile leggere le segnalazioni. Il log della console riporta l'eccezione, sotto "The CRM's statistics could not read the introductions".</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime" xml:space="preserve">
    <value>Clienti segnalati nel tempo</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime.Weekly" xml:space="preserve">
    <value>Clienti segnalati e sotto contratto alla fine di ogni settimana, da quando il CRM ha iniziato a registrare le segnalazioni, il {0}. Un punto apre le statistiche com'erano quel giorno.</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime.Monthly" xml:space="preserve">
    <value>Clienti segnalati e sotto contratto alla fine di ogni mese, da quando il CRM ha iniziato a registrare le segnalazioni, il {0}. Un punto apre le statistiche com'erano quel giorno.</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime.TooShort" xml:space="preserve">
    <value>Il CRM ha iniziato a registrare le segnalazioni il {0}. Il grafico parte dal giorno dopo.</value>
  </data>
  <data name="Crm.Overview.InMemory" xml:space="preserve">
    <value>Tenuti in memoria, fino al riavvio della console</value>
  </data>
  <data name="Crm.Overview.InProgramme" xml:space="preserve">
    <value>Nel programma</value>
  </data>
  <data name="Crm.Overview.WithNext" xml:space="preserve">
    <value>Contatti con una prossima azione</value>
  </data>
  <data name="Crm.Overview.Undated" xml:space="preserve">
    <value>; {0} senza data</value>
  </data>
  <data name="Crm.Overview.Yours" xml:space="preserve">
    <value>I tuoi</value>
  </data>
  <data name="Crm.Overview.TodayTo" xml:space="preserve">
    <value>Da oggi al {0}, in UTC</value>
  </data>
  <data name="Crm.Overview.DueBeforeToday" xml:space="preserve">
    <value>In scadenza prima di oggi</value>
  </data>
  <data name="Crm.Overview.ByStage" xml:space="preserve">
    <value>Per fase</value>
  </data>
  <data name="Crm.Overview.Activity" xml:space="preserve">
    <value>Interazioni per settimana</value>
  </data>
  <data name="Crm.Overview.Activity.Lead" xml:space="preserve">
    <value>{0} nelle ultime {1} settimane, {2} finora questa settimana. Le settimane vanno da lunedì a domenica, in UTC.</value>
  </data>
  <data name="Crm.Overview.Activity.Table" xml:space="preserve">
    <value>Mostra come tabella</value>
  </data>
  <data name="Crm.Overview.Activity.WeekColumn" xml:space="preserve">
    <value>Settimana</value>
  </data>
  <data name="Crm.Overview.Activity.Total" xml:space="preserve">
    <value>Totale</value>
  </data>
  <data name="Crm.Overview.Activity.Week" xml:space="preserve">
    <value>Settimana del {0}</value>
  </data>
  <data name="Crm.Overview.ByEntity" xml:space="preserve">
    <value>Per persona / azienda</value>
  </data>
  <data name="Crm.Overview.ByTrack" xml:space="preserve">
    <value>Per tipo di partnership</value>
  </data>
  <data name="Js.Crm.NoContacts" xml:space="preserve">
    <value>Nessun contatto.</value>
  </data>
  <data name="Js.Crm.Reading" xml:space="preserve">
    <value>Lettura delle interazioni…</value>
  </data>
  <data name="Js.Crm.Gone" xml:space="preserve">
    <value>Questo contatto è stato eliminato da un collega mentre la pagina era aperta. Nulla è stato scritto; ricarica la pagina.</value>
  </data>
  <data name="Js.Crm.SessionEnded" xml:space="preserve">
    <value>La tua sessione è terminata. Nulla è stato scritto; accedi di nuovo.</value>
  </data>
  <data name="Js.Crm.NotAllowed" xml:space="preserve">
    <value>Non consentito: la tua sessione non ha più CRM: Scrittura. Nulla è stato scritto.</value>
  </data>
  <data name="Js.Crm.NoAnswer" xml:space="preserve">
    <value>nessuna risposta</value>
  </data>
  <data name="Js.Crm.PanelFailed" xml:space="preserve">
    <value>La console non ha potuto rispondere per le interazioni ({0}). Nulla è stato scritto; riprova.</value>
  </data>
  <data name="Js.Crm.SaveFailed" xml:space="preserve">
    <value>La console non ha potuto salvare quella cella ({0}). Nulla è stato scritto; riprova.</value>
  </data>
  <data name="Js.Crm.EditorHelp" xml:space="preserve">
    <value>Invio salva, Maiusc+Invio va a capo, Esc annulla</value>
  </data>
  <data name="Js.Crm.NotSaid" xml:space="preserve">
    <value>Non indicato</value>
  </data>
  <data name="Js.Crm.SameName" xml:space="preserve">
    <value>omonimo</value>
  </data>
  <data name="Js.Crm.SameName.Title" xml:space="preserve">
    <value>Un altro contatto ha questo nome</value>
  </data>
  <data name="Js.Crm.By" xml:space="preserve">
    <value>entro il {0}</value>
  </data>
  <data name="Js.Crm.Overdue" xml:space="preserve">
    <value>in ritardo</value>
  </data>
  <data name="Js.Crm.More" xml:space="preserve">
    <value>altro</value>
  </data>
  <data name="Js.Crm.Less" xml:space="preserve">
    <value>meno</value>
  </data>
  <data name="Js.Crm.More.Title" xml:space="preserve">
    <value>Mostra tutto</value>
  </data>
  <data name="Js.Crm.Less.Title" xml:space="preserve">
    <value>Mostra solo le prime righe</value>
  </data>
  <data name="Js.Crm.SavedBy" xml:space="preserve">
    <value>Salvato da {0} alle {1} mentre stavi modificando. Nulla di tuo è stato scritto.</value>
  </data>
  <data name="Js.Crm.CopyTyped" xml:space="preserve">
    <value>Copia ciò che hai scritto</value>
  </data>
  <data name="Js.Crm.YouTyped" xml:space="preserve">
    <value>Hai scritto:</value>
  </data>
  <data name="Generic.Save" xml:space="preserve">
    <value>Salva</value>
  </data>
  <data name="Crm.Import.Contacts.One" xml:space="preserve">
    <value>1 contatto</value>
  </data>
  <data name="Crm.Import.Contacts.Many" xml:space="preserve">
    <value>{0} contatti</value>
  </data>
  <data name="Crm.Import.Interactions.One" xml:space="preserve">
    <value>1 interazione</value>
  </data>
  <data name="Crm.Import.Interactions.Many" xml:space="preserve">
    <value>{0} interazioni</value>
  </data>
  <data name="Crm.Import.NextActions.One" xml:space="preserve">
    <value>1 prossima azione</value>
  </data>
  <data name="Crm.Import.NextActions.Many" xml:space="preserve">
    <value>{0} prossime azioni</value>
  </data>
  <data name="Gateway.Minimum.NoChange" xml:space="preserve">
    <value>È già il minimo che il gateway tiene: nulla cambierebbe.</value>
  </data>
  <data name="Gateway.Client.OnRow" xml:space="preserve">
    <value>sulla riga {0}</value>
  </data>
  <data name="Gateway.Client.Below" xml:space="preserve">
    <value>sotto la {0}</value>
  </data>
  <data name="Gateway.Client.TooMany" xml:space="preserve">
    <value>Elenca più di {0} installazioni {1}, più di quante questa pagina legga in una volta.</value>
  </data>
  <data name="Gateway.Client.NotInstallation" xml:space="preserve">
    <value>La sua risposta non era l'installazione che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.NotStatus" xml:space="preserve">
    <value>La sua risposta non era lo stato che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.ChangedNotInstallation" xml:space="preserve">
    <value>Il gateway ha fatto la modifica, e la sua risposta non era l'installazione che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.NotPolicy" xml:space="preserve">
    <value>La sua risposta non era la policy che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.ChangedNotPolicyRow" xml:space="preserve">
    <value>Il gateway ha fatto la modifica, e la sua risposta non era la riga di policy che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.ChangedNotAllowanceRow" xml:space="preserve">
    <value>Il gateway ha fatto la modifica, e la sua risposta non era la riga di quota che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.OperatorName" xml:space="preserve">
    <value>Il nome dell'operatore non è uno che il gateway possa registrare: al massimo {0} caratteri, e nessun carattere di controllo.</value>
  </data>
  <data name="Gateway.Client.NotUsageDays" xml:space="preserve">
    <value>La sua risposta non era i giorni di utilizzo che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.NotUsageSummary" xml:space="preserve">
    <value>La sua risposta non era il riepilogo degli utilizzi che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.NotInstallations" xml:space="preserve">
    <value>La sua risposta non era l'elenco di installazioni che la console si aspetta.</value>
  </data>
  <data name="Gateway.Client.Http" xml:space="preserve">
    <value>Ha risposto HTTP {0}.</value>
  </data>
  <data name="Gateway.Client.Timeout" xml:space="preserve">
    <value>Non ha risposto entro {0} secondi.</value>
  </data>
  <data name="Gateway.Client.Refused" xml:space="preserve">
    <value>Ha rifiutato {0}: {1}</value>
  </data>
  <data name="Gateway.Client.RefusedUnnamed" xml:space="preserve">
    <value>Ha risposto HTTP 400 senza indicare un parametro.</value>
  </data>
  <data name="Gateway.Policy.InstallationsList" xml:space="preserve">
    <value>nell'elenco delle installazioni</value>
  </data>
  <data name="Menu.Settings" xml:space="preserve">
    <value>Impostazioni utente</value>
  </data>
  <data name="Menu.Settings.Dashboard" xml:space="preserve">
    <value>Preferenze della dashboard</value>
  </data>
  <data name="Home.Arrange" xml:space="preserve">
    <value>Cambia l'ordine</value>
  </data>
  <data name="Preferences.Dashboard.Title" xml:space="preserve">
    <value>Preferenze della dashboard</value>
  </data>
  <data name="Preferences.Dashboard.Intro" xml:space="preserve">
    <value>L'ordine in cui la panoramica mostra le aree che puoi visualizzare, solo per te. Cambia dove si trova ciascuna area, mai ciò che puoi vedere: quello dipende dai tuoi ruoli.</value>
  </data>
  <data name="Preferences.Dashboard.Order" xml:space="preserve">
    <value>Ordine delle aree</value>
  </data>
  <data name="Preferences.Dashboard.Chosen" xml:space="preserve">
    <value>L'ordine che hai scelto.</value>
  </data>
  <data name="Preferences.Dashboard.Default" xml:space="preserve">
    <value>L'ordine predefinito: non ne hai ancora scelto uno.</value>
  </data>
  <data name="Preferences.Dashboard.NoAreas" xml:space="preserve">
    <value>Non puoi ancora visualizzare alcuna area, quindi la panoramica non ha nulla da ordinare. Chiedi a un Amministratore di concederti i ruoli di cui hai bisogno.</value>
  </data>
  <data name="Preferences.Dashboard.MoveUp" xml:space="preserve">
    <value>Sposta {0} in su</value>
  </data>
  <data name="Preferences.Dashboard.MoveDown" xml:space="preserve">
    <value>Sposta {0} in giù</value>
  </data>
  <data name="Preferences.Dashboard.Help" xml:space="preserve">
    <value>Trascina un'area dove la vuoi, oppure usa le sue frecce: la prima è in cima alla panoramica. Nulla cambia finché non salvi.</value>
  </data>
  <data name="Preferences.Dashboard.Save" xml:space="preserve">
    <value>Salva l'ordine</value>
  </data>
  <data name="Preferences.Dashboard.Reset" xml:space="preserve">
    <value>Torna all'ordine predefinito</value>
  </data>
  <data name="Preferences.Dashboard.Saved" xml:space="preserve">
    <value>Salvato: la tua panoramica mostra le aree in quest'ordine.</value>
  </data>
  <data name="Preferences.Dashboard.SeeOverview" xml:space="preserve">
    <value>Vai alla panoramica</value>
  </data>
  <data name="Preferences.Problem.NotSaved" xml:space="preserve">
    <value>Non è stato possibile salvare il tuo ordine, quindi nulla è cambiato. Il motivo è nel log della console; riprova tra poco.</value>
  </data>
  <data name="Preferences.Unreadable.Title" xml:space="preserve">
    <value>Non è stato possibile leggere il tuo ordine</value>
  </data>
  <data name="Preferences.Unreadable.Detail" xml:space="preserve">
    <value>La pagina mostra l'ordine predefinito, come la panoramica finché il tuo non potrà essere letto. Il motivo è nel log della console, sotto "The dashboard order of".</value>
  </data>
  <data name="Preferences.Ephemeral" xml:space="preserve">
    <value>La console non ha un database, quindi il tuo ordine è tenuto in memoria e va perso al riavvio della console.</value>
  </data>
  <data name="Crm.Introductions.Title" xml:space="preserve">
    <value>Clienti segnalati</value>
  </data>
  <data name="Crm.Introductions.Subtitle" xml:space="preserve">
    <value>I clienti che questo partner ci ha segnalato, una riga ciascuno: chi, quando, il referente presso il cliente e fin dove si è arrivati. La fase è la lettura del team, impostata qui man mano; ciò che è stato firmato è del registro, e le chiamate e gli incontri con il cliente non si registrano qui.</value>
  </data>
  <data name="Crm.Introductions.None" xml:space="preserve">
    <value>Ancora nessun cliente segnalato.</value>
  </data>
  <data name="Crm.Introductions.Log" xml:space="preserve">
    <value>Registra una segnalazione</value>
  </data>
  <data name="Crm.Introductions.Add" xml:space="preserve">
    <value>Aggiungi</value>
  </data>
  <data name="Crm.Introductions.ViewOnly" xml:space="preserve">
    <value>Puoi vedere i clienti segnalati, non cambiarli: serve {0}.</value>
  </data>
  <data name="Crm.Introductions.NoDatabase" xml:space="preserve">
    <value>La console non ha un database, perciò nessuna segnalazione si può registrare.</value>
  </data>
  <data name="Crm.Introduction.Customer" xml:space="preserve">
    <value>Cliente</value>
  </data>
  <data name="Crm.Introduction.IntroducedOn" xml:space="preserve">
    <value>Segnalato il</value>
  </data>
  <data name="Crm.Introduction.Stage" xml:space="preserve">
    <value>Fase</value>
  </data>
  <data name="Crm.Introduction.ContactPerson" xml:space="preserve">
    <value>Referente</value>
  </data>
  <data name="Crm.Introduction.Notes" xml:space="preserve">
    <value>Note</value>
  </data>
  <data name="Crm.Introduction.Field.Customer" xml:space="preserve">
    <value>Il nome di un cliente</value>
  </data>
  <data name="Crm.Introduction.Field.ContactPerson" xml:space="preserve">
    <value>Un referente</value>
  </data>
  <data name="Crm.Introduction.Field.Notes" xml:space="preserve">
    <value>Le note</value>
  </data>
  <data name="Crm.Introduction.Field.Email" xml:space="preserve">
    <value>Un indirizzo email</value>
  </data>
  <data name="Crm.Introduction.Field.Phone" xml:space="preserve">
    <value>Un numero di telefono</value>
  </data>
  <data name="Crm.Introduction.Problem.CustomerRequired" xml:space="preserve">
    <value>Indica chi è il cliente: un nome.</value>
  </data>
  <data name="Crm.Introduction.Problem.DateRequired" xml:space="preserve">
    <value>Indica quando è stata fatta la segnalazione: una data.</value>
  </data>
  <data name="Crm.Introduction.Problem.Year" xml:space="preserve">
    <value>Controlla l'anno: il CRM tiene le segnalazioni dal 2000 in avanti.</value>
  </data>
  <data name="Crm.Introduction.Problem.Future" xml:space="preserve">
    <value>Una segnalazione è qualcosa che è già avvenuto. Una pianificata è la prossima azione del partner.</value>
  </data>
  <data name="Crm.Introduction.Problem.Stage" xml:space="preserve">
    <value>Non è una fase che la console conosce.</value>
  </data>
  <data name="Crm.Introduction.NoVersion" xml:space="preserve">
    <value>La versione della segnalazione non è stata inviata. Ricarica la pagina.</value>
  </data>
  <data name="Crm.Introduction.Unsaved" xml:space="preserve">
    <value>Nulla è stato scritto: la segnalazione non si è potuta salvare. Il motivo è nel log della console.</value>
  </data>
  <data name="Crm.Introduction.Deleted" xml:space="preserve">
    <value>Questa segnalazione è stata eliminata.</value>
  </data>
  <data name="Crm.IntroductionStage.Introduced" xml:space="preserve">
    <value>Segnalato</value>
  </data>
  <data name="Crm.IntroductionStage.InDiscussion" xml:space="preserve">
    <value>In discussione</value>
  </data>
  <data name="Crm.IntroductionStage.Pilot" xml:space="preserve">
    <value>Pilota</value>
  </data>
  <data name="Crm.IntroductionStage.UnderContract" xml:space="preserve">
    <value>Sotto contratto</value>
  </data>
  <data name="Crm.IntroductionStage.Declined" xml:space="preserve">
    <value>Ha rifiutato</value>
  </data>
  <data name="Crm.IntroductionStage.Lapsed" xml:space="preserve">
    <value>Non rinnovato</value>
  </data>
  <data name="Crm.Delete.Introductions.None" xml:space="preserve">
    <value>Nessuna</value>
  </data>
  <data name="Crm.Delete.Introductions.One" xml:space="preserve">
    <value>Una, eliminata con il contatto</value>
  </data>
  <data name="Crm.Delete.Introductions.Many" xml:space="preserve">
    <value>{0}, eliminate con il contatto</value>
  </data>
  <data name="Crm.Overview.Introductions" xml:space="preserve">
    <value>Clienti segnalati</value>
  </data>
  <data name="Crm.Overview.IntroductionsByStage" xml:space="preserve">
    <value>Segnalazioni per fase</value>
  </data>
  <data name="Crm.Overview.IntroductionsByStage.Title" xml:space="preserve">
    <value>I clienti segnalati dai partner, nella pagina di ciascun partner</value>
  </data>
  <data name="Js.Crm.CardFailed" xml:space="preserve">
    <value>La console non ha potuto rispondere per i clienti segnalati ({0}). Nulla è stato scritto; riprova.</value>
  </data>
  <data name="Crm.Card.Title" xml:space="preserve">
    <value>Aggiungi un contatto da un biglietto da visita</value>
  </data>
  <data name="Crm.Card.Lead" xml:space="preserve">
    <value>Fotografa un biglietto da visita, o scegli una sua foto. La console lo fa leggere, riporta ciò che è stato letto in un modulo accanto alla foto e aggiunge il contatto solo quando hai controllato il modulo e l'hai salvato.</value>
  </data>
  <data name="Crm.Card.NotConfigured" xml:space="preserve">
    <value>La lettura dei biglietti da visita non è configurata</value>
  </data>
  <data name="Crm.Card.NotConfigured.Detail" xml:space="preserve">
    <value>La console non ha una chiave Ollama, &lt;code&gt;Crm--BusinessCards--ApiKey&lt;/code&gt; in Key Vault, quindi non la chiede. Nel frattempo aggiungi il contatto dalla riga vuota di &lt;em&gt;Partnership&lt;/em&gt;.</value>
  </data>
  <data name="Crm.Card.TakePhoto" xml:space="preserve">
    <value>Scatta una foto</value>
  </data>
  <data name="Crm.Card.ChoosePhoto" xml:space="preserve">
    <value>Scegli una foto</value>
  </data>
  <data name="Crm.Card.Read" xml:space="preserve">
    <value>Leggi il biglietto</value>
  </data>
  <data name="Crm.Card.Reading" xml:space="preserve">
    <value>Lettura del biglietto in corso: richiede qualche secondo…</value>
  </data>
  <data name="Crm.Card.Privacy" xml:space="preserve">
    <value>La foto viene inviata a Ollama Cloud per essere letta da {0}, insieme a ciò che dice un codice QR sul biglietto; se il codice QR è un link, la console lo apre e invia anche ciò che dice la pagina. Nulla viene conservato: né nel CRM né in un log.</value>
  </data>
  <data name="Crm.Card.NoPhoto" xml:space="preserve">
    <value>Scatta o scegli una foto del biglietto.</value>
  </data>
  <data name="Crm.Card.TooLarge" xml:space="preserve">
    <value>La foto supera i {0} MB. Scegline una più piccola.</value>
  </data>
  <data name="Crm.Card.NotAPhoto" xml:space="preserve">
    <value>Non è una foto JPEG o PNG. Scatta di nuovo la foto, o scegline una in uno dei due formati.</value>
  </data>
  <data name="Crm.Card.ReadNothing" xml:space="preserve">
    <value>Dalla foto non si è potuto leggere nulla. Inserisci il contatto guardando la foto, o prova con un'altra foto.</value>
  </data>
  <data name="Crm.Card.Check" xml:space="preserve">
    <value>Controlla ogni campo con il biglietto: ciò che è stato letto può essere sbagliato. Nulla viene salvato finché non aggiungi il contatto.</value>
  </data>
  <data name="Crm.Card.Unreachable" xml:space="preserve">
    <value>Non è stato possibile raggiungere Ollama, o non ha risposto in tempo. Inserisci il contatto guardando la foto, o riprova.</value>
  </data>
  <data name="Crm.Card.KeyRefused" xml:space="preserve">
    <value>Ollama ha rifiutato la chiave della console: è errata, revocata o oltre il suo piano, e va sistemata da un operatore. Nel frattempo inserisci il contatto guardando la foto.</value>
  </data>
  <data name="Crm.Card.NotUnderstood" xml:space="preserve">
    <value>La risposta di Ollama non è una lettura del biglietto, forse perché il suo modello è stato ritirato. Inserisci il contatto guardando la foto e avvisa un operatore.</value>
  </data>
  <data name="Crm.Card.SameName" xml:space="preserve">
    <value>Nel CRM c'è già un contatto con questo nome. Due persone possono avere lo stesso nome, quindi puoi comunque aggiungere questo:</value>
  </data>
  <data name="Crm.Card.Photo" xml:space="preserve">
    <value>Il biglietto da visita</value>
  </data>
  <data name="Crm.Card.Notes.Hint" xml:space="preserve">
    <value>Il sito web e l'indirizzo del biglietto, se li riporta. Modificali, o toglili.</value>
  </data>
  <data name="Crm.Card.StartsAs" xml:space="preserve">
    <value>Il contatto parte da {0} e {1}, come uno aggiunto dalla riga vuota.</value>
  </data>
  <data name="Crm.Card.Add" xml:space="preserve">
    <value>Aggiungi il contatto</value>
  </data>
  <data name="Crm.Card.Another" xml:space="preserve">
    <value>Un'altra foto</value>
  </data>
  <data name="Crm.Card.Button" xml:space="preserve">
    <value>Da biglietto da visita</value>
  </data>
  <data name="Crm.Card.Button.Title" xml:space="preserve">
    <value>Aggiungi un contatto dalla foto del suo biglietto da visita</value>
  </data>
  <data name="Crm.Card.Qr.Text" xml:space="preserve">
    <value>Il codice QR del biglietto è stato letto insieme al biglietto.</value>
  </data>
  <data name="Crm.Card.Qr.Read" xml:space="preserve">
    <value>Il codice QR del biglietto rimanda a {0}. La console l'ha aperto, e ciò che dice la pagina è stato letto insieme al biglietto.</value>
  </data>
  <data name="Crm.Card.Qr.Refused" xml:space="preserve">
    <value>Il codice QR del biglietto rimanda a {0}, che non è una pagina web pubblica, quindi la console non l'ha aperto. Il biglietto è stato letto senza.</value>
  </data>
  <data name="Crm.Card.Qr.Unreachable" xml:space="preserve">
    <value>Il codice QR del biglietto rimanda a {0}, che non ha risposto in tempo o ha risposto con un errore. Il biglietto è stato letto senza.</value>
  </data>
  <data name="Crm.Card.Qr.Unreadable" xml:space="preserve">
    <value>Il codice QR del biglietto rimanda a {0}, che non è una pagina o un contatto che la console sa leggere. Il biglietto è stato letto senza.</value>
  </data>
  <data name="Offline.Title" xml:space="preserve">
    <value>La console non è raggiungibile</value>
  </data>
  <data name="Offline.Detail" xml:space="preserve">
    <value>Non c'è connessione, oppure la console non risponde. Nulla è stato modificato. Quando sei di nuovo in linea, riprova.</value>
  </data>
  <data name="Offline.Retry" xml:space="preserve">
    <value>Riprova</value>
  </data>
</root>
</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>
  </data>
  <data name="Shell.Navbar.SignedIn" xml:space="preserve">
    <value>Signed in</value>
  </data>
  <data name="Shell.Navbar.SharedCredential" xml:space="preserve">
    <value>This session was authenticated with the shared console password, so actions are recorded against the credential rather than a person.</value>
  </data>
  <data name="Shell.Navbar.SignOut" xml:space="preserve">
    <value>Sign out</value>
  </data>
  <data name="Shell.Footer.Environment" xml:space="preserve">
    <value>Environment serving this request</value>
  </data>
  <data name="Account.Login.Title" xml:space="preserve">
    <value>Sign in</value>
  </data>
  <data name="Account.Login.Lead" xml:space="preserve">
    <value>Sign in to the admin console.</value>
  </data>
  <data name="Account.Login.NameHelp" xml:space="preserve">
    <value>Your name, as it is in Key Vault.</value>
  </data>
  <data name="Account.Login.Submit" xml:space="preserve">
    <value>Sign in</value>
  </data>
  <data name="Account.Login.Name" xml:space="preserve">
    <value>Name</value>
  </data>
  <data name="Account.Login.Password" xml:space="preserve">
    <value>Password</value>
  </data>
  <data name="Account.Login.NameTooLong" xml:space="preserve">
    <value>A name is at most 64 characters.</value>
  </data>
  <data name="Account.Login.PasswordRequired" xml:space="preserve">
    <value>Enter the password.</value>
  </data>
  <data name="Account.Login.EnterName" xml:space="preserve">
    <value>Enter your name.</value>
  </data>
  <data name="Account.Login.NotAccepted" xml:space="preserve">
    <value>That name and password were not accepted.</value>
  </data>
  <data name="Account.Login.LockedOut.One" xml:space="preserve">
    <value>Too many failed attempts. Try again in 1 minute.</value>
  </data>
  <data name="Account.Login.LockedOut.Many" xml:space="preserve">
    <value>Too many failed attempts. Try again in {0} minutes.</value>
  </data>
  <data name="Error.Back" xml:space="preserve">
    <value>Back to the console</value>
  </data>
  <data name="Error.Reference" xml:space="preserve">
    <value>Reference {0} - quote it when reporting this.</value>
  </data>
  <data name="Error.NotFound.Title" xml:space="preserve">
    <value>Page not found</value>
  </data>
  <data name="Error.NotFound.Detail" xml:space="preserve">
    <value>That address does not exist in this console.</value>
  </data>
  <data name="Error.Forbidden.Title" xml:space="preserve">
    <value>Not allowed</value>
  </data>
  <data name="Error.Forbidden.Detail" xml:space="preserve">
    <value>Your session is signed in, but none of its roles allows that. An Administrator grants roles on the console's Users page.</value>
  </data>
  <data name="Error.TooManyRequests.Title" xml:space="preserve">
    <value>Too many requests</value>
  </data>
  <data name="Error.TooManyRequests.Detail" xml:space="preserve">
    <value>Too many attempts in a short time. Wait a minute and try again.</value>
  </data>
  <data name="Error.Unexpected.Title" xml:space="preserve">
    <value>Something went wrong</value>
  </data>
  <data name="Error.Unexpected.Detail" xml:space="preserve">
    <value>The console could not complete that request.</value>
  </data>
  <data name="Menu.Overview" xml:space="preserve">
    <value>Overview</value>
  </data>
  <data name="Menu.Audit" xml:space="preserve">
    <value>Audit log</value>
  </data>
  <data name="Menu.Users" xml:space="preserve">
    <value>Users</value>
  </data>
  <data name="Menu.Licensing" xml:space="preserve">
    <value>Licensing</value>
  </data>
  <data name="Menu.Licensing.Issue" xml:space="preserve">
    <value>Issue a licence</value>
  </data>
  <data name="Menu.Licensing.Validate" xml:space="preserve">
    <value>Validate a licence</value>
  </data>
  <data name="Menu.Licensing.Register" xml:space="preserve">
    <value>Licence register</value>
  </data>
  <data name="Menu.Gateway" xml:space="preserve">
    <value>AI Gateway</value>
  </data>
  <data name="Menu.Gateway.Overview" xml:space="preserve">
    <value>Overview</value>
  </data>
  <data name="Menu.Gateway.Installations" xml:space="preserve">
    <value>Installations</value>
  </data>
  <data name="Menu.Gateway.UsageByLicence" xml:space="preserve">
    <value>Usage by licence</value>
  </data>
  <data name="Menu.Gateway.UsageHistory" xml:space="preserve">
    <value>Usage history</value>
  </data>
  <data name="Menu.Gateway.Policy" xml:space="preserve">
    <value>Policy</value>
  </data>
  <data name="Menu.Crm" xml:space="preserve">
    <value>CRM</value>
  </data>
  <data name="Menu.Crm.Contacts" xml:space="preserve">
    <value>Partnerships</value>
  </data>
  <data name="Menu.Crm.FollowUps" xml:space="preserve">
    <value>Follow-ups</value>
  </data>
  <data name="Menu.Crm.Statistics" xml:space="preserve">
    <value>Statistics</value>
  </data>
  <data name="Home.Title" xml:space="preserve">
    <value>Overview</value>
  </data>
  <data name="Home.Intro" xml:space="preserve">
    <value>The internal admin console. Features attach as areas: licence issuing is the first, the AI gateway the second and the CRM the third, each with its own area rather than its own application.</value>
  </data>
  <data name="Home.SignedInAs" xml:space="preserve">
    <value>Signed in as {0}</value>
  </data>
  <data name="Home.RolesUnreadable" xml:space="preserve">
    <value>Your roles could not be read just now, so the console shows you nothing until they can be. The console's log has why; try again in a moment.</value>
  </data>
  <data name="Home.NoRoles" xml:space="preserve">
    <value>You have no roles yet, so there is nothing here for you to see. Ask an Administrator to grant you the roles you need: each area has a view role and a write role.</value>
  </data>
  <data name="Role.Administrator" xml:space="preserve">
    <value>Administrator</value>
  </data>
  <data name="Role.Area.Licensing" xml:space="preserve">
    <value>Licensing</value>
  </data>
  <data name="Role.Area.Gateway" xml:space="preserve">
    <value>Gateway</value>
  </data>
  <data name="Role.Area.Crm" xml:space="preserve">
    <value>CRM</value>
  </data>
  <data name="Role.Verb.View" xml:space="preserve">
    <value>View</value>
  </data>
  <data name="Role.Verb.Write" xml:space="preserve">
    <value>Write</value>
  </data>
  <data name="Role.Display" xml:space="preserve">
    <value>{0}: {1}</value>
  </data>
  <data name="Generic.Apply" xml:space="preserve">
    <value>Apply</value>
  </data>
  <data name="Generic.Clear" xml:space="preserve">
    <value>Clear</value>
  </data>
  <data name="Generic.PageOf" xml:space="preserve">
    <value>Page {0} of {1}</value>
  </data>
  <data name="Audit.Title" xml:space="preserve">
    <value>Audit log</value>
  </data>
  <data name="Audit.Intro" xml:space="preserve">
    <value>What was done through this console, by whom, newest first: every change, every licence issued, downloaded or validated, every export, every sign-in, every revoke or restore of an installation on the gateway, and every change to its policy. An entry under a name of its own is attributable; one under the shared password says who the operator said they were, and proves nothing. Entries are appended and never changed.</value>
  </data>
  <data name="Audit.OwnEntriesOnly" xml:space="preserve">
    <value>These are your own entries: what was done under the name &lt;strong&gt;{0}&lt;/strong&gt;, its sign-ins included. Everyone's entries are an Administrator's to read.</value>
  </data>
  <data name="Audit.NoDatabase.Title" xml:space="preserve">
    <value>The console has no database</value>
  </data>
  <data name="Audit.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault, so audit entries are log lines in Application Insights and nothing else, and there is nothing here to list. They are the traces whose message starts &lt;code&gt;Audit:&lt;/code&gt;.</value>
  </data>
  <data name="Audit.Ephemeral" xml:space="preserve">
    <value>Development audit log, held in memory: everything here is lost when the console restarts.</value>
  </data>
  <data name="Audit.Unreadable.Title" xml:space="preserve">
    <value>The audit log could not be read</value>
  </data>
  <data name="Audit.Unreadable.Detail" xml:space="preserve">
    <value>The console's log has why, under "The audit page could not read the audit log". Entries are still written as log lines in Application Insights.</value>
  </data>
  <data name="Audit.Filter.Action" xml:space="preserve">
    <value>Action</value>
  </data>
  <data name="Audit.Filter.EveryAction" xml:space="preserve">
    <value>Every action</value>
  </data>
  <data name="Audit.Filter.Target" xml:space="preserve">
    <value>Target</value>
  </data>
  <data name="Audit.Filter.TargetPlaceholder" xml:space="preserve">
    <value>An installation id or a licence id, or part of one</value>
  </data>
  <data name="Audit.Count.One" xml:space="preserve">
    <value>1 entry</value>
  </data>
  <data name="Audit.Count.Many" xml:space="preserve">
    <value>{0} entries</value>
  </data>
  <data name="Audit.Count.OneMatch" xml:space="preserve">
    <value>1 entry matches</value>
  </data>
  <data name="Audit.Count.ManyMatch" xml:space="preserve">
    <value>{0} entries match</value>
  </data>
  <data name="Audit.Column.When" xml:space="preserve">
    <value>When, UTC</value>
  </data>
  <data name="Audit.Column.Who" xml:space="preserve">
    <value>Who</value>
  </data>
  <data name="Audit.Column.Action" xml:space="preserve">
    <value>Action</value>
  </data>
  <data name="Audit.Column.Target" xml:space="preserve">
    <value>Target</value>
  </data>
  <data name="Audit.Column.Details" xml:space="preserve">
    <value>Details</value>
  </data>
  <data name="Audit.Empty.Filtered" xml:space="preserve">
    <value>No entry matches these filters.</value>
  </data>
  <data name="Audit.Empty.Own" xml:space="preserve">
    <value>Nothing has been recorded under your name yet.</value>
  </data>
  <data name="Audit.Empty.All" xml:space="preserve">
    <value>Nothing has been recorded yet.</value>
  </data>
  <data name="Audit.SharedPassword" xml:space="preserve">
    <value>shared password</value>
  </data>
  <data name="Audit.SharedPassword.Title" xml:space="preserve">
    <value>Signed in with the shared password: who it was is not known</value>
  </data>
  <data name="Audit.ClaimedAs" xml:space="preserve">
    <value>as "{0}"</value>
  </data>
  <data name="Audit.Correlation.Title" xml:space="preserve">
    <value>The request's trace identifier, to find its logs</value>
  </data>
  <data name="Audit.Newer" xml:space="preserve">
    <value>Newer</value>
  </data>
  <data name="Audit.Older" xml:space="preserve">
    <value>Older</value>
  </data>
  <data name="Users.Title" xml:space="preserve">
    <value>Users</value>
  </data>
  <data name="Users.Intro.Roles" xml:space="preserve">
    <value>Who may do what in the console. Each area has a view role and a write role, and the write role includes the view; {0} includes every role and this page. A grant or a revoke takes effect on that person's next request, with no sign-out, and is recorded in the audit log.</value>
  </data>
  <data name="Users.Intro.Names" xml:space="preserve">
    <value>A name is listed once it can sign in, with a secret of its own, &lt;code&gt;Authentication--Users--&amp;lt;name&amp;gt;&lt;/code&gt; in Key Vault, which an operator with Key Vault rights loads (&lt;code&gt;docs/Operations.md&lt;/code&gt;, &lt;em&gt;People&lt;/em&gt;), or while it still holds a role. &lt;strong&gt;admin&lt;/strong&gt; holds every role by construction: there is nothing to grant it and nothing that can be revoked from it.</value>
  </data>
  <data name="Users.NoDatabase.Title" xml:space="preserve">
    <value>The console has no database</value>
  </data>
  <data name="Users.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault, so there is nowhere to keep a role: &lt;strong&gt;admin&lt;/strong&gt; holds every role by construction, and nobody else holds any. Nothing can be granted until the database is configured (&lt;code&gt;docs/Provisioning.md&lt;/code&gt;, Part C).</value>
  </data>
  <data name="Users.Ephemeral" xml:space="preserve">
    <value>Development roles, held in memory: every grant here is lost when the console restarts.</value>
  </data>
  <data name="Users.Unreadable.Title" xml:space="preserve">
    <value>The roles could not be read</value>
  </data>
  <data name="Users.Unreadable.Detail" xml:space="preserve">
    <value>The console's log has why, under "The Users page could not read the roles". Until they can be read, nobody but &lt;strong&gt;admin&lt;/strong&gt; holds a role.</value>
  </data>
  <data name="Users.Problem.NoDatabase" xml:space="preserve">
    <value>Nothing changed: the console has no database, so no role can be granted or revoked.</value>
  </data>
  <data name="Users.Problem.NotGranted" xml:space="preserve">
    <value>Nothing changed: {0} could not be granted to {1}. The console's log has why.</value>
  </data>
  <data name="Users.Problem.NotRevoked" xml:space="preserve">
    <value>Nothing changed: {0} could not be revoked from {1}. The console's log has why.</value>
  </data>
  <data name="Users.Count.One" xml:space="preserve">
    <value>1 name</value>
  </data>
  <data name="Users.Count.Many" xml:space="preserve">
    <value>{0} names</value>
  </data>
  <data name="Users.Column.Name" xml:space="preserve">
    <value>Name</value>
  </data>
  <data name="Users.You" xml:space="preserve">
    <value>(you)</value>
  </data>
  <data name="Users.NoSecret" xml:space="preserve">
    <value>no secret</value>
  </data>
  <data name="Users.NoSecret.Title" xml:space="preserve">
    <value>No Authentication--Users--{0} secret, so this name cannot sign in. Its roles stay until they are revoked.</value>
  </data>
  <data name="Users.NoRoles" xml:space="preserve">
    <value>no roles</value>
  </data>
  <data name="Users.NoRoles.Title" xml:space="preserve">
    <value>Signs in and sees only the overview, which says to ask an Administrator.</value>
  </data>
  <data name="Users.EveryRole" xml:space="preserve">
    <value>Every role, by construction</value>
  </data>
  <data name="Users.Held" xml:space="preserve">
    <value>Held</value>
  </data>
  <data name="Users.Held.Title" xml:space="preserve">
    <value>Held: granted by {0}, {1} UTC</value>
  </data>
  <data name="Users.Revoke" xml:space="preserve">
    <value>Revoke</value>
  </data>
  <data name="Users.Revoke.Title" xml:space="preserve">
    <value>Revoke {0} from {1}</value>
  </data>
  <data name="Users.Grant" xml:space="preserve">
    <value>Grant</value>
  </data>
  <data name="Users.Grant.Title" xml:space="preserve">
    <value>Grant {0} to {1}</value>
  </data>
  <data name="Users.Through" xml:space="preserve">
    <value>through {0}</value>
  </data>
  <data name="Users.Intro.Initials" xml:space="preserve">
    <value>Initials, where set, are what the CRM's grid shows for a person, VS rather than vera, with the name on hover; the record, its filters, its export and the audit log keep the name. Blank shows the name. admin has none.</value>
  </data>
  <data name="Users.Column.Initials" xml:space="preserve">
    <value>Initials</value>
  </data>
  <data name="Users.Initials.Title" xml:space="preserve">
    <value>Shown in the CRM's grid in place of the name, which is still what every record holds. One to four letters; blank shows the name.</value>
  </data>
  <data name="Users.Initials.Label" xml:space="preserve">
    <value>Initials of {0}</value>
  </data>
  <data name="Users.Initials.Admin.Title" xml:space="preserve">
    <value>admin is no one, so it has no initials.</value>
  </data>
  <data name="Users.Initials.Same" xml:space="preserve">
    <value>same as {0}</value>
  </data>
  <data name="Users.Initials.Same.Title" xml:space="preserve">
    <value>Two people with the same initials read as one in the CRM's grid until a hover shows the name. Allowed, but worth changing.</value>
  </data>
  <data name="Users.Problem.NotInitials" xml:space="preserve">
    <value>Nothing changed: “{0}” is not initials. Type one to {1} letters, or leave it blank to show the name.</value>
  </data>
  <data name="Users.Problem.NoDatabaseInitials" xml:space="preserve">
    <value>Nothing changed: the console has no database, so no initials can be set.</value>
  </data>
  <data name="Users.Problem.InitialsNotSet" xml:space="preserve">
    <value>Nothing changed: the initials of {0} could not be saved. The console's log has why.</value>
  </data>
  <data name="Generic.Search" xml:space="preserve">
    <value>Search</value>
  </data>
  <data name="Generic.Optional" xml:space="preserve">
    <value>(optional)</value>
  </data>
  <data name="Generic.Edit" xml:space="preserve">
    <value>Edit</value>
  </data>
  <data name="Generic.Previous" xml:space="preserve">
    <value>Previous</value>
  </data>
  <data name="Generic.Next" xml:space="preserve">
    <value>Next</value>
  </data>
  <data name="Licensing.Purpose" xml:space="preserve">
    <value>Purpose</value>
  </data>
  <data name="Licensing.Tier" xml:space="preserve">
    <value>Tier</value>
  </data>
  <data name="Licensing.LicenceId" xml:space="preserve">
    <value>Licence id</value>
  </data>
  <data name="Licensing.Type" xml:space="preserve">
    <value>Type</value>
  </data>
  <data name="Licensing.SchemaVersion" xml:space="preserve">
    <value>Schema version</value>
  </data>
  <data name="Licensing.Unreadable" xml:space="preserve">
    <value>unreadable</value>
  </data>
  <data name="Licensing.ValidFrom" xml:space="preserve">
    <value>Valid from</value>
  </data>
  <data name="Licensing.AreaKeys" xml:space="preserve">
    <value>Area keys</value>
  </data>
  <data name="Licensing.OtherAttributes" xml:space="preserve">
    <value>Other attributes</value>
  </data>
  <data name="Licensing.LicenceXml" xml:space="preserve">
    <value>Licence XML</value>
  </data>
  <data name="Licensing.Reissue" xml:space="preserve">
    <value>Reissue</value>
  </data>
  <data name="Licensing.Installations" xml:space="preserve">
    <value>Installations</value>
  </data>
  <data name="Licensing.Column.Customer" xml:space="preserve">
    <value>Customer</value>
  </data>
  <data name="Licensing.Column.Company" xml:space="preserve">
    <value>Company</value>
  </data>
  <data name="Licensing.Column.Expires" xml:space="preserve">
    <value>Expires</value>
  </data>
  <data name="Licensing.Column.Issued" xml:space="preserve">
    <value>Issued</value>
  </data>
  <data name="Licensing.Column.IssuedBy" xml:space="preserve">
    <value>Issued by</value>
  </data>
  <data name="Licensing.Badge.Expired" xml:space="preserve">
    <value>expired</value>
  </data>
  <data name="Licensing.Badge.Custom" xml:space="preserve">
    <value>custom</value>
  </data>
  <data name="Licensing.Badge.NotYetInForce" xml:space="preserve">
    <value>not yet in force</value>
  </data>
  <data name="Licensing.Badge.Reissue" xml:space="preserve">
    <value>reissue</value>
  </data>
  <data name="Licensing.Section.Reports" xml:space="preserve">
    <value>Reports</value>
  </data>
  <data name="Licensing.Section.Features" xml:space="preserve">
    <value>Features</value>
  </data>
  <data name="Licensing.Section.Connectors" xml:space="preserve">
    <value>Connectors</value>
  </data>
  <data name="Licensing.Section.Analysis" xml:space="preserve">
    <value>Analysis</value>
  </data>
  <data name="Licensing.Section.AI" xml:space="preserve">
    <value>AI</value>
  </data>
  <data name="Licensing.Register.Title" xml:space="preserve">
    <value>Licence register</value>
  </data>
  <data name="Licensing.Register.Lead" xml:space="preserve">
    <value>Every licence the console has issued.</value>
  </data>
  <data name="Licensing.Register.Count.One" xml:space="preserve">
    <value>1 licence</value>
  </data>
  <data name="Licensing.Register.Count.Many" xml:space="preserve">
    <value>{0} licences</value>
  </data>
  <data name="Licensing.Register.Count.OneMatch" xml:space="preserve">
    <value>1 licence matches</value>
  </data>
  <data name="Licensing.Register.Count.ManyMatch" xml:space="preserve">
    <value>{0} licences match</value>
  </data>
  <data name="Licensing.Register.Issue" xml:space="preserve">
    <value>Issue</value>
  </data>
  <data name="Licensing.Register.SearchPlaceholder" xml:space="preserve">
    <value>Customer, company or licence id</value>
  </data>
  <data name="Licensing.Register.EveryPurpose" xml:space="preserve">
    <value>Every purpose</value>
  </data>
  <data name="Licensing.Register.EveryTier" xml:space="preserve">
    <value>Every tier</value>
  </data>
  <data name="Licensing.Register.Status" xml:space="preserve">
    <value>Status</value>
  </data>
  <data name="Licensing.Register.Status.Both" xml:space="preserve">
    <value>Active and expired</value>
  </data>
  <data name="Licensing.Register.Status.Active" xml:space="preserve">
    <value>Active</value>
  </data>
  <data name="Licensing.Register.Status.Expired" xml:space="preserve">
    <value>Expired</value>
  </data>
  <data name="Licensing.Register.Empty" xml:space="preserve">
    <value>No licence has been recorded yet.</value>
  </data>
  <data name="Licensing.Register.Empty.Filtered" xml:space="preserve">
    <value>No licence matches.</value>
  </data>
  <data name="Licensing.Register.Download.Title" xml:space="preserve">
    <value>Download the .lic file</value>
  </data>
  <data name="Licensing.Register.Download.For" xml:space="preserve">
    <value>Download the licence file for {0}</value>
  </data>
  <data name="Licensing.Register.DownloadLic" xml:space="preserve">
    <value>Download .lic</value>
  </data>
  <data name="Licensing.Register.OnInstallation" xml:space="preserve">
    <value>On installation</value>
  </data>
  <data name="Licensing.Register.NotKnownHere" xml:space="preserve">
    <value>Not known here</value>
  </data>
  <data name="Licensing.Register.NotKnownHere.Detail" xml:space="preserve">
    <value>Issued ahead of this build's catalogue. Readers that do not know them ignore them.</value>
  </data>
  <data name="Licensing.Register.AreaKeys.Detail" xml:space="preserve">
    <value>Issued before #38. These keys grant nothing now; reissue to grant what the licence should.</value>
  </data>
  <data name="Licensing.Register.SignedInAs" xml:space="preserve">
    <value>Signed in as</value>
  </data>
  <data name="Licensing.Register.Recorded" xml:space="preserve">
    <value>Recorded</value>
  </data>
  <data name="Licensing.Register.NoDatabase.Title" xml:space="preserve">
    <value>The register has no database</value>
  </data>
  <data name="Licensing.Register.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault, so nothing can be recorded here and nothing can be issued. Provisioning it is Part C of &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Licensing.Register.Ephemeral" xml:space="preserve">
    <value>Development register, held in memory: everything here is lost when the console restarts.</value>
  </data>
  <data name="Licensing.Gateway.NotConfigured.Title" xml:space="preserve">
    <value>The gateway is not configured</value>
  </data>
  <data name="Licensing.Gateway.NotConfigured.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminToken&lt;/code&gt; is not in Key Vault, so the console does not ask the gateway which installations run a licence. Loading it is B3 of &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Licensing.Gateway.NoLicenceIds.Title" xml:space="preserve">
    <value>The gateway does not record licence ids yet</value>
  </data>
  <data name="Licensing.Gateway.NoLicenceIds.Detail" xml:space="preserve">
    <value>It answered without them, so it predates kf-ai-gateway#35, which was deployed on 2026-09-26: check that &lt;code&gt;Gateway:BaseUrl&lt;/code&gt; names the gateway installations enrol at, and that it has been deployed since.</value>
  </data>
  <data name="Licensing.Gateway.RequestRefused.Title" xml:space="preserve">
    <value>The gateway refused what the console asked</value>
  </data>
  <data name="Licensing.Gateway.RequestRefused.Detail" xml:space="preserve">
    <value>It answered 400, which is a fault in the console, not an outage: the console checks what it sends, and sent something the gateway does not take. The console's log has it, under "The gateway refused the console's request"; report it rather than retrying.</value>
  </data>
  <data name="Licensing.Gateway.TokenRefused.Title" xml:space="preserve">
    <value>The gateway refused the console's admin token</value>
  </data>
  <data name="Licensing.Gateway.TokenRefused.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminToken&lt;/code&gt; must be one of the gateway's tokens for the same environment: its &lt;code&gt;Admin__ReadToken&lt;/code&gt; (kf-ai-gateway#40). &lt;code&gt;docs/Operations.md&lt;/code&gt; has what to check.</value>
  </data>
  <data name="Licensing.Gateway.NoAdminSurface.Title" xml:space="preserve">
    <value>The gateway has no admin surface</value>
  </data>
  <data name="Licensing.Gateway.NoAdminSurface.Detail" xml:space="preserve">
    <value>It answered 404 for &lt;code&gt;/admin/installations&lt;/code&gt;, which it does when no &lt;code&gt;Admin__Token&lt;/code&gt; is set on it, or &lt;code&gt;Gateway:BaseUrl&lt;/code&gt; is not the gateway. &lt;code&gt;docs/Operations.md&lt;/code&gt; has what to check.</value>
  </data>
  <data name="Licensing.Gateway.Unreachable.Title" xml:space="preserve">
    <value>The console could not reach the gateway</value>
  </data>
  <data name="Licensing.Gateway.Unreachable.Detail" xml:space="preserve">
    <value>The console's log has why, under "The gateway's /admin did not answer"; &lt;code&gt;docs/Operations.md&lt;/code&gt; has what to check.</value>
  </data>
  <data name="Licensing.Issue.Title" xml:space="preserve">
    <value>Issue a licence</value>
  </data>
  <data name="Licensing.Issue.ReissueTitle" xml:space="preserve">
    <value>Reissue a licence</value>
  </data>
  <data name="Licensing.Issue.PreviewTitle" xml:space="preserve">
    <value>Preview licence</value>
  </data>
  <data name="Licensing.Issue.IssuedTitle" xml:space="preserve">
    <value>Licence issued</value>
  </data>
  <data name="Licensing.Issue.Term.Months" xml:space="preserve">
    <value>{0} months</value>
  </data>
  <data name="Licensing.Issue.Term.OneYear" xml:space="preserve">
    <value>1 year</value>
  </data>
  <data name="Licensing.Issue.Term.Years" xml:space="preserve">
    <value>{0} years</value>
  </data>
  <data name="Licensing.Issue.ViewOnly.Title" xml:space="preserve">
    <value>You can view this form but not issue from it</value>
  </data>
  <data name="Licensing.Issue.ViewOnly.Detail" xml:space="preserve">
    <value>Issuing needs the role {0}, and {1} does not hold it. An Administrator grants it on the Users page.</value>
  </data>
  <data name="Licensing.Issue.Dropped" xml:space="preserve">
    <value>The licence being reissued carries {0}, which this build does not know and the form cannot write. The new licence will not carry them.</value>
  </data>
  <data name="Licensing.Issue.Predates" xml:space="preserve">
    <value>The licence being reissued predates what a licence grants now (#38): it carries the old area keys, which grant nothing. The form starts from everything on with no limits. Check each section before previewing.</value>
  </data>
  <data name="Licensing.Issue.ReissueLead" xml:space="preserve">
    <value>A renewal keeps the licence id, {0}, so the register counts it as the same licence.</value>
  </data>
  <data name="Licensing.Issue.Lead" xml:space="preserve">
    <value>A Standard licence. Nothing is signed until you have seen the preview.</value>
  </data>
  <data name="Licensing.Issue.PurposeLabel" xml:space="preserve">
    <value>What it is for</value>
  </data>
  <data name="Licensing.Issue.PurposeHelp" xml:space="preserve">
    <value>Written to the &lt;code&gt;purpose&lt;/code&gt; attribute. It grants nothing; it is how the register keeps internal and demo licences out of its figures. Whatever it is for, a licence covers one installation: issue one for each.</value>
  </data>
  <data name="Licensing.Issue.Form.Company" xml:space="preserve">
    <value>Company</value>
  </data>
  <data name="Licensing.Issue.Form.Tier" xml:space="preserve">
    <value>Tier</value>
  </data>
  <data name="Licensing.Issue.TierHelp" xml:space="preserve">
    <value>Written to the &lt;code&gt;tier&lt;/code&gt; attribute. No reader acts on it; choosing one fills in its connector cap.</value>
  </data>
  <data name="Licensing.Issue.Term" xml:space="preserve">
    <value>Term</value>
  </data>
  <data name="Licensing.Issue.Form.ValidFrom" xml:space="preserve">
    <value>Valid from</value>
  </data>
  <data name="Licensing.Issue.ValidFromHelp" xml:space="preserve">
    <value>From 00:00 UTC that day. Blank: in force from issue - leave it blank for a renewal. A future date 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, and kf-app refuses to install it before then from its next release (kf-app#979). kf-app 1.6.2 installs it, in force at once.</value>
  </data>
  <data name="Licensing.Issue.Form.LastsFor" xml:space="preserve">
    <value>Lasts for</value>
  </data>
  <data name="Licensing.Issue.CommonTerms" xml:space="preserve">
    <value>Common terms</value>
  </data>
  <data name="Licensing.Issue.HowMany" xml:space="preserve">
    <value>How many</value>
  </data>
  <data name="Licensing.Issue.Units" xml:space="preserve">
    <value>Days, weeks, months or years</value>
  </data>
  <data name="Licensing.Issue.Unit.Days" xml:space="preserve">
    <value>days</value>
  </data>
  <data name="Licensing.Issue.Unit.Weeks" xml:space="preserve">
    <value>weeks</value>
  </data>
  <data name="Licensing.Issue.Unit.Months" xml:space="preserve">
    <value>months</value>
  </data>
  <data name="Licensing.Issue.Unit.Years" xml:space="preserve">
    <value>years</value>
  </data>
  <data name="Licensing.Issue.DurationHelp" xml:space="preserve">
    <value>Counted from &lt;em&gt;valid from&lt;/em&gt;, or from issue, by the calendar: 12 months from 15 March ends on 15 March.</value>
  </data>
  <data name="Licensing.Issue.ExpiresOn" xml:space="preserve">
    <value>Expires on</value>
  </data>
  <data name="Licensing.Issue.ExpiryDate" xml:space="preserve">
    <value>Expiry date</value>
  </data>
  <data name="Licensing.Issue.ExpiryHelp" xml:space="preserve">
    <value>Works until 23:59:59 UTC that day.</value>
  </data>
  <data name="Licensing.Issue.Grants.Title" xml:space="preserve">
    <value>What the licence grants</value>
  </data>
  <data name="Licensing.Issue.Grants.Lead" xml:space="preserve">
    <value>Everything starts switched on with no limits. A licence grants only what it names, so anything switched off here - and anything the product adds later - is not granted.</value>
  </data>
  <data name="Licensing.Issue.AllOn" xml:space="preserve">
    <value>All on</value>
  </data>
  <data name="Licensing.Issue.AllOff" xml:space="preserve">
    <value>All off</value>
  </data>
  <data name="Licensing.Issue.Connector" xml:space="preserve">
    <value>Connector</value>
  </data>
  <data name="Licensing.Issue.NoLimitPlaceholder" xml:space="preserve">
    <value>No limit</value>
  </data>
  <data name="Licensing.Issue.HowManySources" xml:space="preserve">
    <value>How many {0} {1}</value>
  </data>
  <data name="Licensing.Issue.AiPeriod" xml:space="preserve">
    <value>AI budget period</value>
  </data>
  <data name="Licensing.Issue.AiHelp" xml:space="preserve">
    <value>Blank means the AI Gateway's allowance for the licence's tier, or Standard's when it has none: 10,000,000 tokens a calendar month and 120 requests a minute for both tiers until Enterprise's is raised, which reaches every Enterprise licence without reissuing it (#46). Type numbers only for a deal that includes more than its tier's. They apply to every AI call the installation makes, not only the assistant's.</value>
  </data>
  <data name="Licensing.Issue.AttributesHelp" xml:space="preserve">
    <value>One &lt;code&gt;name=value&lt;/code&gt; per line. Inert in the product. &lt;code&gt;TrialDays&lt;/code&gt;, the names the form sets itself, and anything starting &lt;code&gt;ai.&lt;/code&gt;, &lt;code&gt;sources.&lt;/code&gt; or &lt;code&gt;analysis.&lt;/code&gt; are refused.</value>
  </data>
  <data name="Licensing.Issue.YourName" xml:space="preserve">
    <value>Your name</value>
  </data>
  <data name="Licensing.Issue.IssuedByHelp" xml:space="preserve">
    <value>Recorded in the register beside the name you signed in with. Under the shared password this box is the only record of who issued it.</value>
  </data>
  <data name="Licensing.Issue.Preview" xml:space="preserve">
    <value>Preview</value>
  </data>
  <data name="Licensing.Issue.Form.IssuedBy" xml:space="preserve">
    <value>Issued by</value>
  </data>
  <data name="Licensing.Issue.Form.IssuedByRequired" xml:space="preserve">
    <value>Say who is issuing this licence.</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerName" xml:space="preserve">
    <value>Licensee name</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerNameRequired" xml:space="preserve">
    <value>The licensee's name is required.</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerEmail" xml:space="preserve">
    <value>Licensee email</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerEmailRequired" xml:space="preserve">
    <value>The licensee's email is required.</value>
  </data>
  <data name="Licensing.Issue.Form.CustomerEmailInvalid" xml:space="preserve">
    <value>That is not an email address.</value>
  </data>
  <data name="Licensing.Issue.Form.TooLong" xml:space="preserve">
    <value>{0} is too long: at most {1} characters.</value>
  </data>
  <data name="Licensing.Issue.Form.Attributes" xml:space="preserve">
    <value>Other attributes</value>
  </data>
  <data name="Licensing.Issue.Problem.CountAtLeastOne" xml:space="preserve">
    <value>{0}: the count must be at least 1. Leave it blank for no limit, or switch the connector off.</value>
  </data>
  <data name="Licensing.Issue.Problem.LimitAtLeastOne" xml:space="preserve">
    <value>{0} must be at least 1. Leave it blank for {1}.</value>
  </data>
  <data name="Licensing.Issue.Problem.DurationRequired" xml:space="preserve">
    <value>Say how long the licence lasts: a whole number of days, weeks, months or years, at least 1.</value>
  </data>
  <data name="Licensing.Issue.Problem.DurationUnit" xml:space="preserve">
    <value>Choose days, weeks, months or years for how long the licence lasts.</value>
  </data>
  <data name="Licensing.Issue.Problem.AttributeLine" xml:space="preserve">
    <value>Attributes, line {0}: write it as name=value.</value>
  </data>
  <data name="Licensing.Issue.Problem.AttributeTwice" xml:space="preserve">
    <value>Attributes, line {0}: '{1}' is set more than once.</value>
  </data>
  <data name="Licensing.Issue.Failure.PreviewExpired" xml:space="preserve">
    <value>The preview has expired or could not be read. Check the licence and preview it again.</value>
  </data>
  <data name="Licensing.Issue.Failure.NoDatabase" xml:space="preserve">
    <value>Nothing can be issued: the licence register has no database, and a licence is never handed over without being recorded.</value>
  </data>
  <data name="Licensing.Issue.Failure.AlreadySigning" xml:space="preserve">
    <value>This licence is already being signed. Check the register before trying again.</value>
  </data>
  <data name="Licensing.Issue.Failure.TestKeyRefused" xml:space="preserve">
    <value>Not issued: the configured signing key is a contract test key, and nothing it signs validates on a customer installation.</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyNotConfigured" xml:space="preserve">
    <value>Not issued: the signing key is not configured (Licensing--PrivateKey and Licensing--PrivateKeyPassphrase in Key Vault).</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyNotBase64" xml:space="preserve">
    <value>Not issued: Licensing--PrivateKey is not a key - it is not base64. The secret should be exactly the contents of private.key: one line, no quotes, no header. Save a corrected new version, then restart the App Service.</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyIsPublic" xml:space="preserve">
    <value>Not issued: Licensing--PrivateKey holds the public key (public.key), not the private one. Save the contents of private.key as a new version, then restart the App Service.</value>
  </data>
  <data name="Licensing.Issue.Failure.PassphraseHasWhitespace" xml:space="preserve">
    <value>Not issued: Licensing--PrivateKeyPassphrase has a space or line break at its start or end. Without it, the passphrase opens the key. Save a new version of the secret without it, then restart the App Service.</value>
  </data>
  <data name="Licensing.Issue.Failure.PassphraseDoesNotOpenKey" xml:space="preserve">
    <value>Not issued: Licensing--PrivateKeyPassphrase does not open Licensing--PrivateKey. The two secrets do not belong together - most often the key from before rekey with the new passphrase, or the reverse. Check both against the escrow copy; see Operations, 'Issuing a licence fails'.</value>
  </data>
  <data name="Licensing.Issue.Failure.KeyNotTrusted" xml:space="preserve">
    <value>Not issued: the configured signing key is not one the product trusts, so nothing it signs would install. Check that Licensing--PrivateKey in Key Vault is the Knowledge Fabric key - see Operations, 'Issuing a licence fails'.</value>
  </data>
  <data name="Licensing.Issue.Failure.SigningFailed" xml:space="preserve">
    <value>Not issued: the signing key opened, but signing failed. The console's log has the exception, under 'Issuing licence ... failed'.</value>
  </data>
  <data name="Licensing.Issue.Failure.Config" xml:space="preserve">
    <value>Not issued: {0}</value>
  </data>
  <data name="Licensing.Issue.Failure.NotRecorded" xml:space="preserve">
    <value>Not issued: the licence could not be recorded in the register, so it was not handed over. Nothing needs undoing; try again once the register is reachable.</value>
  </data>
  <data name="Licensing.Issue.SignerSays" xml:space="preserve">
    <value>The signer reports:</value>
  </data>
  <data name="Licensing.Issue.OnIssue" xml:space="preserve">
    <value>On issue</value>
  </data>
  <data name="Licensing.Issue.Size" xml:space="preserve">
    <value>Size</value>
  </data>
  <data name="Licensing.Issue.BytesSigned" xml:space="preserve">
    <value>About {0} bytes signed</value>
  </data>
  <data name="Licensing.Issue.SignAndRecord" xml:space="preserve">
    <value>Sign and record</value>
  </data>
  <data name="Licensing.Issue.SigningHelp" xml:space="preserve">
    <value>Signing records the licence in the register before the file can be downloaded. This preview can be signed for {0} minutes.</value>
  </data>
  <data name="Licensing.Issue.XmlLead" xml:space="preserve">
    <value>As it will be signed. The signature is added when you press Sign.</value>
  </data>
  <data name="Licensing.Issued.Title" xml:space="preserve">
    <value>Licence issued to {0}</value>
  </data>
  <data name="Licensing.Issued.Expires" xml:space="preserve">
    <value>Expires {0} · licence id {1}</value>
  </data>
  <data name="Licensing.Issued.Recorded" xml:space="preserve">
    <value>Recorded in the register. Download it and send it to the customer.</value>
  </data>
  <data name="Licensing.Issued.Download" xml:space="preserve">
    <value>Download {0}</value>
  </data>
  <data name="Licensing.Issued.ViewInRegister" xml:space="preserve">
    <value>View in register</value>
  </data>
  <data name="Licensing.Issued.IssueAnother" xml:space="preserve">
    <value>Issue another</value>
  </data>
  <data name="Licensing.Signing.NoKey.Title" xml:space="preserve">
    <value>No signing key</value>
  </data>
  <data name="Licensing.Signing.NoKey.Detail" xml:space="preserve">
    <value>&lt;code&gt;Licensing--PrivateKey&lt;/code&gt; and &lt;code&gt;Licensing--PrivateKeyPassphrase&lt;/code&gt; are not both configured, so licences can be previewed here but not signed. They belong in Key Vault (Part B of &lt;code&gt;docs/Provisioning.md&lt;/code&gt;), and reach the console on its next restart.</value>
  </data>
  <data name="Licensing.Signing.TestKeyRefused.Title" xml:space="preserve">
    <value>The signing key is a contract test key</value>
  </data>
  <data name="Licensing.Signing.TestKeyRefused.Detail" xml:space="preserve">
    <value>It is one of the throwaway keys under &lt;code&gt;contract/test-keys/&lt;/code&gt;, whose public half is in no product image. Nothing it signs validates on a customer installation, so the console will not sign with it here.</value>
  </data>
  <data name="Licensing.Signing.TestKey" xml:space="preserve">
    <value>Development: signing with a contract test key. What it signs validates nowhere but the contract fixtures' own tests.</value>
  </data>
  <data name="Licensing.Signing.NoDatabase.Detail" xml:space="preserve">
    <value>A licence is never handed over without being recorded, and &lt;code&gt;Database--ConnectionString&lt;/code&gt; is not configured, so nothing can be issued. Provisioning it is Part C of &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Licensing.Signing.Ephemeral" xml:space="preserve">
    <value>Development register, held in memory: a licence issued here is recorded until the console restarts.</value>
  </data>
  <data name="Licensing.Validate.Title" xml:space="preserve">
    <value>Validate a licence</value>
  </data>
  <data name="Licensing.Validate.Lead" xml:space="preserve">
    <value>What the product and the AI Gateway will make of a &lt;code&gt;.lic&lt;/code&gt; file. Nothing is changed or recorded beyond an audit line.</value>
  </data>
  <data name="Licensing.Validate.File" xml:space="preserve">
    <value>Licence file</value>
  </data>
  <data name="Licensing.Validate.OrPaste" xml:space="preserve">
    <value>or paste the XML</value>
  </data>
  <data name="Licensing.Validate.AsOf" xml:space="preserve">
    <value>As of</value>
  </data>
  <data name="Licensing.Validate.AsOf.Optional" xml:space="preserve">
    <value>(optional, UTC)</value>
  </data>
  <data name="Licensing.Validate.AsOf.Help" xml:space="preserve">
    <value>Blank: now. Set a date to ask whether it will still work then.</value>
  </data>
  <data name="Licensing.Validate.TrustTestKey" xml:space="preserve">
    <value>Also trust the contract test key</value>
  </data>
  <data name="Licensing.Validate.TrustTestKey.Help" xml:space="preserve">
    <value>For checking the fixture set. No product image trusts it.</value>
  </data>
  <data name="Licensing.Validate.Submit" xml:space="preserve">
    <value>Validate</value>
  </data>
  <data name="Licensing.Validate.Explainer.Readers" xml:space="preserve">
    <value>Each reader is shown twice: as it behaves &lt;strong&gt;today&lt;/strong&gt;, read from its code at the commit named, and as the &lt;strong&gt;licence contract&lt;/strong&gt; requires (&lt;code&gt;docs/License-Contract.md&lt;/code&gt;). Where they differ, that is a known difference in the reader, explained under its verdicts, not a problem with the licence.</value>
  </data>
  <data name="Licensing.Validate.Explainer.Keys" xml:space="preserve">
    <value>Signatures are checked against the key every product image trusts (kf-app &lt;code&gt;BundledLicensingSettings.PublicKeys&lt;/code&gt;), which is the list the gateway trusts too.</value>
  </data>
  <data name="Licensing.Validate.PastedLicence" xml:space="preserve">
    <value>Pasted licence</value>
  </data>
  <data name="Licensing.Validate.EvaluatedAsOf" xml:space="preserve">
    <value>Evaluated as of {0}</value>
  </data>
  <data name="Licensing.Validate.Signature" xml:space="preserve">
    <value>Signature</value>
  </data>
  <data name="Licensing.Validate.Signature.Valid" xml:space="preserve">
    <value>valid</value>
  </data>
  <data name="Licensing.Validate.Signature.NotVerified" xml:space="preserve">
    <value>not verified</value>
  </data>
  <data name="Licensing.Validate.Signature.By" xml:space="preserve">
    <value>by the {0}</value>
  </data>
  <data name="Licensing.Validate.Key.Product" xml:space="preserve">
    <value>Knowledge Fabric signing key</value>
  </data>
  <data name="Licensing.Validate.Key.ContractTest" xml:space="preserve">
    <value>Contract test key (contract/test-keys)</value>
  </data>
  <data name="Licensing.Validate.Signature.TestKey" xml:space="preserve">
    <value>test key: validates on no customer installation</value>
  </data>
  <data name="Licensing.Validate.Signature.NoTrustedKey" xml:space="preserve">
    <value>by no trusted key — edited after signing, or signed with another key</value>
  </data>
  <data name="Licensing.Validate.Unsupported" xml:space="preserve">
    <value>unsupported</value>
  </data>
  <data name="Licensing.Validate.NamesNotKnown" xml:space="preserve">
    <value>Names not known</value>
  </data>
  <data name="Licensing.Validate.NamesNotKnown.Detail" xml:space="preserve">
    <value>Ignored by a reader that does not know them - possibly misspelled, or newer than this build.</value>
  </data>
  <data name="Licensing.Validate.AreaKeys.Detail" xml:space="preserve">
    <value>The keys #38 removed. No reader reads them any more: kf-app stopped at {0}, so they grant nothing.</value>
  </data>
  <data name="Licensing.Validate.UnknownAttributes" xml:space="preserve">
    <value>Unknown attributes</value>
  </data>
  <data name="Licensing.Validate.UnknownAttributes.Detail" xml:space="preserve">
    <value>Carried and ignored by every reader.</value>
  </data>
  <data name="Licensing.Validate.Register" xml:space="preserve">
    <value>Register</value>
  </data>
  <data name="Licensing.Validate.Register.ThisFile" xml:space="preserve">
    <value>This exact file</value>
  </data>
  <data name="Licensing.Validate.Register.IssuedBy" xml:space="preserve">
    <value>, issued {0} by {1}</value>
  </data>
  <data name="Licensing.Validate.Register.NotChecked" xml:space="preserve">
    <value>Not checked: the register has no database.</value>
  </data>
  <data name="Licensing.Validate.Register.NotThisFile" xml:space="preserve">
    <value>Not this file, but</value>
  </data>
  <data name="Licensing.Validate.Register.SameId.One" xml:space="preserve">
    <value>1 licence with this id</value>
  </data>
  <data name="Licensing.Validate.Register.SameId.Many" xml:space="preserve">
    <value>{0} licences with this id</value>
  </data>
  <data name="Licensing.Validate.Register.SameId.Detail" xml:space="preserve">
    <value>— a renewal, or a file edited after it was issued.</value>
  </data>
  <data name="Licensing.Validate.Register.NotInRegister" xml:space="preserve">
    <value>Not in the register — issued offline, or elsewhere.</value>
  </data>
  <data name="Licensing.Validate.Product.Title" xml:space="preserve">
    <value>The product</value>
  </data>
  <data name="Licensing.Validate.Product.Lead" xml:space="preserve">
    <value>Uploading it on the licence page</value>
  </data>
  <data name="Licensing.Validate.Today" xml:space="preserve">
    <value>Today</value>
  </data>
  <data name="Licensing.Validate.PerContract" xml:space="preserve">
    <value>Per the contract</value>
  </data>
  <data name="Licensing.Validate.Source.ProductToday" xml:space="preserve">
    <value>kf-app {0} on develop, LicenseService.UploadLicenseAsync</value>
  </data>
  <data name="Licensing.Validate.Source.GatewayToday" xml:space="preserve">
    <value>kf-ai-gateway {0}, StandardLicenceEvaluator</value>
  </data>
  <data name="Licensing.Validate.Product.Differ" xml:space="preserve">
    <value>They differ only in whether it is stored. The contract says it is not in force before its &lt;code&gt;validFrom&lt;/code&gt;; kf-app refuses it on upload rather than keep it waiting, because installing a licence replaces the one in force (kf-app &lt;code&gt;docs/Architecture/Licence-Remit.md&lt;/code&gt;, D4).</value>
  </data>
  <data name="Licensing.Validate.Product.Release" xml:space="preserve">
    <value>kf-app {0}, the current release ({1}), does not honour &lt;code&gt;validFrom&lt;/code&gt;: it installs this licence, in force at once. kf-app#979 changes that from the next release.</value>
  </data>
  <data name="Licensing.Validate.Gateway.Title" xml:space="preserve">
    <value>The AI Gateway</value>
  </data>
  <data name="Licensing.Validate.Gateway.Lead" xml:space="preserve">
    <value>At enrolment, and &lt;code&gt;PUT /v1/installation/licence&lt;/code&gt;</value>
  </data>
  <data name="Licensing.Validate.Gateway.Words" xml:space="preserve">
    <value>The tier is the same; the words differ. The gateway's API publishes two reasons, so it reports the contract's &lt;code&gt;unsupported-schema&lt;/code&gt;, &lt;code&gt;trial-licence&lt;/code&gt; and &lt;code&gt;not-yet-valid&lt;/code&gt; as &lt;code&gt;unverifiable&lt;/code&gt; with no &lt;code&gt;expires_at&lt;/code&gt;, and only logs the contract's word.</value>
  </data>
  <data name="Licensing.Validate.Gateway.NotYetValid" xml:space="preserve">
    <value>The gateway checks a licence only when it is sent, so an installation that sends this one before its &lt;code&gt;validFrom&lt;/code&gt; stays on &lt;code&gt;evaluation&lt;/code&gt; until it sends it again after that date. kf-app {0} can do that; since kf-app#979, kf-app refuses it on upload, so never sends it early. A renewal needs no &lt;code&gt;validFrom&lt;/code&gt;: &lt;em&gt;Reissue&lt;/em&gt; runs the term on from the old expiry instead (#42).</value>
  </data>
  <data name="Licensing.Validate.Gateway.EnterpriseBeforeTier" xml:space="preserve">
    <value>An installation that sent its licence before the gateway read &lt;code&gt;tier&lt;/code&gt; (kf-ai-gateway#32, deployed 2026-09-25) has no licence tier recorded there, and is served &lt;code&gt;standard&lt;/code&gt;'s allowance until it sends a licence again.</value>
  </data>
  <data name="Licensing.Validate.Gateway.WhenSent" xml:space="preserve">
    <value>kf-app at {0} sends its licence when it first enrols, and again whenever a licence is installed, replaced or removed: at once if the installation uses AI, otherwise on its next use (kf-app#968). kf-app {1} sends it only when it first enrols, so there a licence uploaded after the installation first used AI, a renewal included, does not reach the gateway.</value>
  </data>
  <data name="Licensing.Validate.Gateway.LoggedAs" xml:space="preserve">
    <value>Logged as {0}, the contract's word for it.</value>
  </data>
  <data name="Licensing.Validate.Verdict.Refused" xml:space="preserve">
    <value>refused</value>
  </data>
  <data name="Licensing.Validate.Verdict.AcceptedGrantsNothing" xml:space="preserve">
    <value>accepted, grants nothing</value>
  </data>
  <data name="Licensing.Validate.Verdict.Accepted" xml:space="preserve">
    <value>accepted</value>
  </data>
  <data name="Licensing.Validate.FileTooLarge" xml:space="preserve">
    <value>That file is over {0} KB, which no licence is.</value>
  </data>
  <data name="Licensing.Validate.NothingToRead" xml:space="preserve">
    <value>Choose a .lic file, or paste the licence XML.</value>
  </data>
  <data name="Licensing.Validate.Verdict.Installs" xml:space="preserve">
    <value>Installs, and opens what it names.</value>
  </data>
  <data name="Licensing.Validate.Verdict.InstallsInForce" xml:space="preserve">
    <value>Installs and is in force.</value>
  </data>
  <data name="Licensing.Validate.Verdict.InstallsNotYetInForce" xml:space="preserve">
    <value>Installs, but is not in force until its validFrom.</value>
  </data>
  <data name="Licensing.Validate.Verdict.GrantsNothing" xml:space="preserve">
    <value>It names no report, feature, connector or AI capability, so only Configuration and Administration open.</value>
  </data>
  <data name="Licensing.Validate.Allowance.TokensUnreadable" xml:space="preserve">
    <value>0 tokens, which refuses every request</value>
  </data>
  <data name="Licensing.Validate.Allowance.Tokens" xml:space="preserve">
    <value>{0} tokens per budget period</value>
  </data>
  <data name="Licensing.Validate.Allowance.PeriodMonth" xml:space="preserve">
    <value>a UTC calendar month as the budget period</value>
  </data>
  <data name="Licensing.Validate.Allowance.Period30d" xml:space="preserve">
    <value>30 days as the budget period</value>
  </data>
  <data name="Licensing.Validate.Allowance.RequestsUnreadable" xml:space="preserve">
    <value>0 requests a minute, which refuses every request</value>
  </data>
  <data name="Licensing.Validate.Allowance.Requests" xml:space="preserve">
    <value>{0} requests a minute</value>
  </data>
  <data name="Licensing.Validate.Allowance.None" xml:space="preserve">
    <value>It names no AI limits, so the {0} tier's own allowance applies.</value>
  </data>
  <data name="Licensing.Validate.Allowance.Replaces" xml:space="preserve">
    <value>Its AI limits replace the {0} tier's: {1}. Any it leaves out stay the tier's.</value>
  </data>
  <data name="Licensing.Validate.Explain.NotALicence" xml:space="preserve">
    <value>Not a licence: it will not parse.</value>
  </data>
  <data name="Licensing.Validate.Explain.Unverifiable" xml:space="preserve">
    <value>No trusted key verifies its signature: it was edited after signing, or signed with another key.</value>
  </data>
  <data name="Licensing.Validate.Explain.UnsupportedSchema" xml:space="preserve">
    <value>This licence declares schema version {0}, which is newer than this build supports (version {1}). Update the application to install it.</value>
  </data>
  <data name="Licensing.Validate.Explain.Trial" xml:space="preserve">
    <value>It carries TrialDays, which marks a trial.</value>
  </data>
  <data name="Licensing.Validate.Explain.Expired" xml:space="preserve">
    <value>It has expired.</value>
  </data>
  <data name="Licensing.Validate.Explain.ValidFromUnreadable" xml:space="preserve">
    <value>Its validFrom cannot be read, so it is not in force, and kf-app refuses it rather than store it.</value>
  </data>
  <data name="Licensing.Validate.Explain.NotYetValid" xml:space="preserve">
    <value>It is not in force until {0} UTC, and kf-app refuses it rather than store it to wait.</value>
  </data>
  <data name="Licensing.Validate.Explain.Refused" xml:space="preserve">
    <value>Refused.</value>
  </data>
  <data name="Licensing.Overview.Today" xml:space="preserve">
    <value>today</value>
  </data>
  <data name="Licensing.Overview.Tomorrow" xml:space="preserve">
    <value>tomorrow</value>
  </data>
  <data name="Licensing.Overview.InDays" xml:space="preserve">
    <value>in {0} days</value>
  </data>
  <data name="Licensing.Overview.Unreadable.Title" xml:space="preserve">
    <value>The register could not be read</value>
  </data>
  <data name="Licensing.Overview.Unreadable.Detail" xml:space="preserve">
    <value>There are no licensing figures until it can be. The console's log has the exception, under "The overview could not read the licence register"; &lt;code&gt;docs/Operations.md&lt;/code&gt; covers a database that has gone away.</value>
  </data>
  <data name="Licensing.Overview.LicencesIssued" xml:space="preserve">
    <value>Licences issued</value>
  </data>
  <data name="Licensing.Overview.Files.One" xml:space="preserve">
    <value>1 file</value>
  </data>
  <data name="Licensing.Overview.Files.Many" xml:space="preserve">
    <value>{0} files</value>
  </data>
  <data name="Licensing.Overview.Reissues.One" xml:space="preserve">
    <value>1 reissue</value>
  </data>
  <data name="Licensing.Overview.Reissues.Many" xml:space="preserve">
    <value>{0} reissues</value>
  </data>
  <data name="Licensing.Overview.Active" xml:space="preserve">
    <value>Active</value>
  </data>
  <data name="Licensing.Overview.InForceToday" xml:space="preserve">
    <value>In force today</value>
  </data>
  <data name="Licensing.Overview.MoreNotYetInForce" xml:space="preserve">
    <value>; {0} more not yet in force</value>
  </data>
  <data name="Licensing.Overview.ExpiringWithinMonth" xml:space="preserve">
    <value>Expiring within a month</value>
  </data>
  <data name="Licensing.Overview.ByUnlessReissued" xml:space="preserve">
    <value>By {0}, unless reissued</value>
  </data>
  <data name="Licensing.Overview.Expired" xml:space="preserve">
    <value>Expired</value>
  </data>
  <data name="Licensing.Overview.EveryFilePastExpiry" xml:space="preserve">
    <value>Every file past its expiry</value>
  </data>
  <data name="Licensing.Overview.IssuedPerMonth" xml:space="preserve">
    <value>Issued per month</value>
  </data>
  <data name="Licensing.Overview.IssuedPerMonth.Lead" xml:space="preserve">
    <value>Files issued in each of the last {0} months (UTC). A reissue keeps its licence id.</value>
  </data>
  <data name="Licensing.Overview.IssuedPerMonth.Aria" xml:space="preserve">
    <value>{0} and {1} in the last {2} months</value>
  </data>
  <data name="Licensing.Overview.NewLicences.One" xml:space="preserve">
    <value>1 new licence</value>
  </data>
  <data name="Licensing.Overview.NewLicences.Many" xml:space="preserve">
    <value>{0} new licences</value>
  </data>
  <data name="Licensing.Overview.TiersInForce" xml:space="preserve">
    <value>Tiers in force</value>
  </data>
  <data name="Licensing.Overview.TiersInForce.Lead" xml:space="preserve">
    <value>Active licences by the &lt;code&gt;tier&lt;/code&gt; attribute of the file in force.</value>
  </data>
  <data name="Licensing.Overview.NoTiers" xml:space="preserve">
    <value>No licence is in force, so there are no tiers to show.</value>
  </data>
  <data name="Licensing.Overview.Expiring.Lead" xml:space="preserve">
    <value>Licences in force with no file lasting past {0}. Reissue one to renew it.</value>
  </data>
  <data name="Licensing.Overview.NothingExpires" xml:space="preserve">
    <value>Nothing expires before {0}.</value>
  </data>
  <data name="Licensing.Overview.ReissueFor" xml:space="preserve">
    <value>Reissue the licence for {0}</value>
  </data>
  <data name="Licensing.Overview.RecentlyIssued" xml:space="preserve">
    <value>Recently issued</value>
  </data>
  <data name="Licensing.Overview.RecentlyIssued.Lead" xml:space="preserve">
    <value>The last {0} files, newest first.</value>
  </data>
  <data name="Licensing.Overview.RegisterLink" xml:space="preserve">
    <value>Register</value>
  </data>
  <data name="Licensing.Overview.By" xml:space="preserve">
    <value>by {0}</value>
  </data>
  <data name="Licensing.Overview.Shared.Title" xml:space="preserve">
    <value>Licences on more than one installation</value>
  </data>
  <data name="Licensing.Overview.Shared.Lead" xml:space="preserve">
    <value>From the gateway: licence ids held by more than one installation that has not been revoked, whatever the licence is for. A licence covers one installation.</value>
  </data>
  <data name="Licensing.Overview.Shared.None" xml:space="preserve">
    <value>No licence is on more than one installation.</value>
  </data>
  <data name="Licensing.Overview.Shared.NotInRegister" xml:space="preserve">
    <value>Not in the register</value>
  </data>
  <data name="Licensing.Overview.Shared.NotInRegister.Detail" xml:space="preserve">
    <value>Issued offline without &lt;code&gt;--register-csv&lt;/code&gt;, or by kf-app's former copy of the tool</value>
  </data>
  <data name="Licensing.Overview.Shared.Remedy" xml:space="preserve">
    <value>Ask the customer which installation should have the licence, then revoke the other from the licence's page, which lists its installations.</value>
  </data>
  <data name="Licensing.Installations.Lead" xml:space="preserve">
    <value>Every installation the gateway holds with licence id {0}, with what it has used this period and is allowed (#66). A reissue keeps the id, so every file of this licence shows the same ones.</value>
  </data>
  <data name="Licensing.Installations.Shared.Title" xml:space="preserve">
    <value>On {0} installations</value>
  </data>
  <data name="Licensing.Installations.Shared.Detail" xml:space="preserve">
    <value>A licence covers one installation. Ask the customer which of these should have it, then revoke the other with &lt;em&gt;Revoke&lt;/em&gt; beside it below. Nothing is refused for it in the meantime.</value>
  </data>
  <data name="Licensing.Installations.None" xml:space="preserve">
    <value>No installation the gateway knows holds this licence.</value>
  </data>
  <data name="Licensing.Installations.Column.Installation" xml:space="preserve">
    <value>Installation</value>
  </data>
  <data name="Licensing.Installations.Column.Version" xml:space="preserve">
    <value>Version</value>
  </data>
  <data name="Licensing.Installations.Column.Row" xml:space="preserve">
    <value>Row</value>
  </data>
  <data name="Licensing.Installations.Column.Status" xml:space="preserve">
    <value>Status</value>
  </data>
  <data name="Licensing.Installations.Column.Enrolled" xml:space="preserve">
    <value>Enrolled</value>
  </data>
  <data name="Licensing.Installations.Column.LastSeen" xml:space="preserve">
    <value>Last seen</value>
  </data>
  <data name="Licensing.Installations.Column.TokensUsed" xml:space="preserve">
    <value>Tokens used</value>
  </data>
  <data name="Licensing.Installations.Column.RequestsAMinute" xml:space="preserve">
    <value>Requests a minute</value>
  </data>
  <data name="Licensing.Installations.Revoke" xml:space="preserve">
    <value>Revoke…</value>
  </data>
  <data name="Licensing.Installations.WireTier" xml:space="preserve">
    <value>The wire tier: the gateway does not report the row it serves</value>
  </data>
  <data name="Licensing.Installations.ServedNothing" xml:space="preserve">
    <value>Served nothing while revoked.</value>
  </data>
  <data name="Licensing.Installations.NotReported" xml:space="preserve">
    <value>Not reported</value>
  </data>
  <data name="Licensing.Installations.NotReported.Title" xml:space="preserve">
    <value>The gateway predates kf-ai-gateway#38</value>
  </data>
  <data name="Licensing.Installations.OfLimit" xml:space="preserve">
    <value>of {0}, {1}%</value>
  </data>
  <data name="Licensing.Installations.TokensAgainstLimit" xml:space="preserve">
    <value>Tokens used against the limit</value>
  </data>
  <data name="Licensing.Installations.Resets" xml:space="preserve">
    <value>Resets {0}</value>
  </data>
  <data name="Licensing.Installations.Footnote" xml:space="preserve">
    <value>The gateway holds the licence each installation last sent it. kf-app sends one on every install since kf-app#968, which is not in a release yet; kf-app 1.6.2 sends it only when it first enrols, so a licence installed there afterwards does not reach the gateway. An installation that has never used AI has never enrolled, so it is not listed.</value>
  </data>
  <data name="Catalogue.Report.insights" xml:space="preserve">
    <value>Insight Hub</value>
  </data>
  <data name="Catalogue.Report.insights.Description" xml:space="preserve">
    <value>The landing dashboard: the verdict, knowledge snapshot, resilience index and evidence coverage.</value>
  </data>
  <data name="Catalogue.Report.resilience" xml:space="preserve">
    <value>Risk Resilience Report</value>
  </data>
  <data name="Catalogue.Report.resilience.Description" xml:space="preserve">
    <value>The resilience index, what drags it down, coverage against target and risk exposure by asset.</value>
  </data>
  <data name="Catalogue.Report.watch" xml:space="preserve">
    <value>Knowledge Watch Report</value>
  </data>
  <data name="Catalogue.Report.watch.Description" xml:space="preserve">
    <value>Key movements in knowledge assets and holders.</value>
  </data>
  <data name="Catalogue.Report.holders" xml:space="preserve">
    <value>Knowledge Holder Analysis</value>
  </data>
  <data name="Catalogue.Report.holders.Description" xml:space="preserve">
    <value>Each knowledge holder's knowledge profile and risk profile.</value>
  </data>
  <data name="Catalogue.Report.assets" xml:space="preserve">
    <value>Knowledge Asset Analysis</value>
  </data>
  <data name="Catalogue.Report.assets.Description" xml:space="preserve">
    <value>Each knowledge asset's profile and risk profile.</value>
  </data>
  <data name="Catalogue.Report.map" xml:space="preserve">
    <value>Knowledge Map</value>
  </data>
  <data name="Catalogue.Report.map.Description" xml:space="preserve">
    <value>Who knows what, as a map.</value>
  </data>
  <data name="Catalogue.Report.skills" xml:space="preserve">
    <value>Skills Matrix</value>
  </data>
  <data name="Catalogue.Report.skills.Description" xml:space="preserve">
    <value>Knowledge holders against knowledge assets, as a matrix.</value>
  </data>
  <data name="Catalogue.Report.workforce" xml:space="preserve">
    <value>Workforce Report</value>
  </data>
  <data name="Catalogue.Report.workforce.Description" xml:space="preserve">
    <value>The workforce list, in the Workforce area.</value>
  </data>
  <data name="Catalogue.Feature.offboarding" xml:space="preserve">
    <value>Offboarding Planner</value>
  </data>
  <data name="Catalogue.Feature.offboarding.Description" xml:space="preserve">
    <value>A leaver's knowledge footprint and a suggested handover plan, which can be registered as a risk.</value>
  </data>
  <data name="Catalogue.Feature.actioncenter" xml:space="preserve">
    <value>Action Center</value>
  </data>
  <data name="Catalogue.Feature.actioncenter.Description" xml:space="preserve">
    <value>The risk register: risks, their lifecycle and their targets.</value>
  </data>
  <data name="Catalogue.Feature.departure" xml:space="preserve">
    <value>Departure Simulator</value>
  </data>
  <data name="Catalogue.Feature.departure.Description" xml:space="preserve">
    <value>What if this person leaves: a panel in the Risk Resilience Report and Knowledge Holder Analysis.</value>
  </data>
  <data name="Catalogue.Feature.export" xml:space="preserve">
    <value>Export</value>
  </data>
  <data name="Catalogue.Feature.export.Description" xml:space="preserve">
    <value>Downloading report data. Today that is the Skills Matrix's Excel export.</value>
  </data>
  <data name="Catalogue.Source.git" xml:space="preserve">
    <value>Git</value>
  </data>
  <data name="Catalogue.Source.git.Description" xml:space="preserve">
    <value>Source control</value>
  </data>
  <data name="Catalogue.Source.git.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.azureboards" xml:space="preserve">
    <value>Azure Boards</value>
  </data>
  <data name="Catalogue.Source.azureboards.Description" xml:space="preserve">
    <value>Project management</value>
  </data>
  <data name="Catalogue.Source.azureboards.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.jira" xml:space="preserve">
    <value>Jira</value>
  </data>
  <data name="Catalogue.Source.jira.Description" xml:space="preserve">
    <value>Project management</value>
  </data>
  <data name="Catalogue.Source.jira.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.gcal" xml:space="preserve">
    <value>Google Calendar</value>
  </data>
  <data name="Catalogue.Source.gcal.Description" xml:space="preserve">
    <value>Calendar</value>
  </data>
  <data name="Catalogue.Source.gcal.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.outlook" xml:space="preserve">
    <value>Outlook Calendar</value>
  </data>
  <data name="Catalogue.Source.outlook.Description" xml:space="preserve">
    <value>Calendar</value>
  </data>
  <data name="Catalogue.Source.outlook.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.confluence" xml:space="preserve">
    <value>Confluence</value>
  </data>
  <data name="Catalogue.Source.confluence.Description" xml:space="preserve">
    <value>Documentation</value>
  </data>
  <data name="Catalogue.Source.confluence.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.shortcut" xml:space="preserve">
    <value>Shortcut</value>
  </data>
  <data name="Catalogue.Source.shortcut.Description" xml:space="preserve">
    <value>Project management</value>
  </data>
  <data name="Catalogue.Source.shortcut.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.onedrive" xml:space="preserve">
    <value>OneDrive</value>
  </data>
  <data name="Catalogue.Source.onedrive.Description" xml:space="preserve">
    <value>Documentation</value>
  </data>
  <data name="Catalogue.Source.onedrive.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.teams" xml:space="preserve">
    <value>Microsoft Teams</value>
  </data>
  <data name="Catalogue.Source.teams.Description" xml:space="preserve">
    <value>Communication</value>
  </data>
  <data name="Catalogue.Source.teams.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.publications" xml:space="preserve">
    <value>Publications</value>
  </data>
  <data name="Catalogue.Source.publications.Description" xml:space="preserve">
    <value>Documentation</value>
  </data>
  <data name="Catalogue.Source.publications.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Source.github" xml:space="preserve">
    <value>GitHub</value>
  </data>
  <data name="Catalogue.Source.github.Description" xml:space="preserve">
    <value>Source control, issues and pull requests</value>
  </data>
  <data name="Catalogue.Source.github.Unit" xml:space="preserve">
    <value>repositories</value>
  </data>
  <data name="Catalogue.Ai.chat" xml:space="preserve">
    <value>AI assistant</value>
  </data>
  <data name="Catalogue.Ai.chat.Description" xml:space="preserve">
    <value>The chat assistant, and the Ask about this button on reports.</value>
  </data>
  <data name="Catalogue.Limit.sources.max" xml:space="preserve">
    <value>Knowledge sources in total</value>
  </data>
  <data name="Catalogue.Limit.sources.max.Description" xml:space="preserve">
    <value>Across every connector, on top of each connector's own count.</value>
  </data>
  <data name="Catalogue.Limit.sources.max.Unit" xml:space="preserve">
    <value>sources</value>
  </data>
  <data name="Catalogue.Limit.sources.max.AbsentMeans" xml:space="preserve">
    <value>No limit.</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees" xml:space="preserve">
    <value>Employee allowance</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees.Description" xml:space="preserve">
    <value>Knowledge holders currently employed, by their employment periods, and not suppressed. The product tells the customer when there are more; it refuses nothing and leaves nobody out of an analysis.</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees.Unit" xml:space="preserve">
    <value>employees</value>
  </data>
  <data name="Catalogue.Limit.analysis.employees.AbsentMeans" xml:space="preserve">
    <value>No allowance.</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets" xml:space="preserve">
    <value>Knowledge assets</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets.Description" xml:space="preserve">
    <value>Assets on the manifest, which is what an analysis reads.</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets.Unit" xml:space="preserve">
    <value>assets</value>
  </data>
  <data name="Catalogue.Limit.analysis.assets.AbsentMeans" xml:space="preserve">
    <value>No limit.</value>
  </data>
  <data name="Catalogue.Limit.analysis.history" xml:space="preserve">
    <value>Data history</value>
  </data>
  <data name="Catalogue.Limit.analysis.history.Description" xml:space="preserve">
    <value>How far back an analysis reads.</value>
  </data>
  <data name="Catalogue.Limit.analysis.history.Unit" xml:space="preserve">
    <value>months</value>
  </data>
  <data name="Catalogue.Limit.analysis.history.AbsentMeans" xml:space="preserve">
    <value>No limit.</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens" xml:space="preserve">
    <value>AI token budget</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens.Description" xml:space="preserve">
    <value>Input and output tokens together, per budget period, at the AI Gateway.</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens.Unit" xml:space="preserve">
    <value>tokens</value>
  </data>
  <data name="Catalogue.Limit.ai.tokens.AbsentMeans" xml:space="preserve">
    <value>The tier's default.</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm" xml:space="preserve">
    <value>AI requests per minute</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm.Description" xml:space="preserve">
    <value>Requests per minute at the AI Gateway.</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm.Unit" xml:space="preserve">
    <value>requests a minute</value>
  </data>
  <data name="Catalogue.Limit.ai.rpm.AbsentMeans" xml:space="preserve">
    <value>The tier's default.</value>
  </data>
  <data name="Catalogue.Purpose.customer" xml:space="preserve">
    <value>Customer</value>
  </data>
  <data name="Catalogue.Purpose.customer.Description" xml:space="preserve">
    <value>Sold to a customer.</value>
  </data>
  <data name="Catalogue.Purpose.demo" xml:space="preserve">
    <value>Demo</value>
  </data>
  <data name="Catalogue.Purpose.demo.Description" xml:space="preserve">
    <value>For showing the product: sales demos and partner installations.</value>
  </data>
  <data name="Catalogue.Purpose.internal" xml:space="preserve">
    <value>Internal</value>
  </data>
  <data name="Catalogue.Purpose.internal.Description" xml:space="preserve">
    <value>Our own: development, staging and testing installations.</value>
  </data>
  <data name="Catalogue.Tier.standard" xml:space="preserve">
    <value>Standard</value>
  </data>
  <data name="Catalogue.Tier.enterprise" xml:space="preserve">
    <value>Enterprise</value>
  </data>
  <data name="Catalogue.Tier.none" xml:space="preserve">
    <value>No tier</value>
  </data>
  <data name="Catalogue.Tier.other" xml:space="preserve">
    <value>Other</value>
  </data>
  <data name="Catalogue.AiPeriod.none" xml:space="preserve">
    <value>The tier's default</value>
  </data>
  <data name="Catalogue.AiPeriod.month" xml:space="preserve">
    <value>A calendar month (UTC)</value>
  </data>
  <data name="Catalogue.AiPeriod.30d" xml:space="preserve">
    <value>30 days, rolling from enrolment</value>
  </data>
  <data name="Js.Summary.All" xml:space="preserve">
    <value>All {0}</value>
  </data>
  <data name="Js.Summary.None" xml:space="preserve">
    <value>None</value>
  </data>
  <data name="Js.Summary.Of" xml:space="preserve">
    <value>{0} of {1}</value>
  </data>
  <data name="Js.Summary.Named" xml:space="preserve">
    <value>{0}: {1}</value>
  </data>
  <data name="Js.Summary.NamedOff" xml:space="preserve">
    <value>{0} - off: {1}</value>
  </data>
  <data name="Js.Summary.WithCount" xml:space="preserve">
    <value>{0} with a count</value>
  </data>
  <data name="Js.Summary.InTotal" xml:space="preserve">
    <value>{0} in total</value>
  </data>
  <data name="Js.Summary.InTotalUnreadable" xml:space="preserve">
    <value>none in total (limit unreadable)</value>
  </data>
  <data name="Js.Summary.NoLimit" xml:space="preserve">
    <value>{0}, no limit</value>
  </data>
  <data name="Js.Summary.Employees" xml:space="preserve">
    <value>{0} employees (allowance)</value>
  </data>
  <data name="Js.Summary.EmployeesUnreadable" xml:space="preserve">
    <value>0 employees (allowance unreadable)</value>
  </data>
  <data name="Js.Summary.Assets" xml:space="preserve">
    <value>{0} knowledge assets</value>
  </data>
  <data name="Js.Summary.AssetsUnreadable" xml:space="preserve">
    <value>no knowledge assets (limit unreadable)</value>
  </data>
  <data name="Js.Summary.History" xml:space="preserve">
    <value>{0} months of history</value>
  </data>
  <data name="Js.Summary.HistoryUnreadable" xml:space="preserve">
    <value>no months of history (limit unreadable)</value>
  </data>
  <data name="Js.Summary.NoLimits" xml:space="preserve">
    <value>No limits</value>
  </data>
  <data name="Js.Summary.AssistantOn" xml:space="preserve">
    <value>Assistant on</value>
  </data>
  <data name="Js.Summary.AssistantOff" xml:space="preserve">
    <value>Assistant off</value>
  </data>
  <data name="Js.Summary.PeriodMonth" xml:space="preserve">
    <value>a calendar month</value>
  </data>
  <data name="Js.Summary.Period30d" xml:space="preserve">
    <value>30 days</value>
  </data>
  <data name="Js.Summary.TokensUnreadable" xml:space="preserve">
    <value>no tokens (limit unreadable)</value>
  </data>
  <data name="Js.Summary.TokensAPeriod" xml:space="preserve">
    <value>{0} tokens a period</value>
  </data>
  <data name="Js.Summary.TokensPer" xml:space="preserve">
    <value>{0} tokens per {1}</value>
  </data>
  <data name="Js.Summary.TierBudgetPer" xml:space="preserve">
    <value>the tier's budget per {0}</value>
  </data>
  <data name="Js.Summary.RequestsUnreadable" xml:space="preserve">
    <value>no requests (limit unreadable)</value>
  </data>
  <data name="Js.Summary.Requests" xml:space="preserve">
    <value>{0} requests a minute</value>
  </data>
  <data name="Js.Summary.TierDefaults" xml:space="preserve">
    <value>tier defaults</value>
  </data>
  <data name="Js.Summary.UpTo" xml:space="preserve">
    <value>{0} up to {1} {2}</value>
  </data>
  <data name="Js.Summary.UpToUnreadable" xml:space="preserve">
    <value>{0} none (count unreadable)</value>
  </data>
  <data name="Js.Overview.New" xml:space="preserve">
    <value>New</value>
  </data>
  <data name="Js.Overview.Reissued" xml:space="preserve">
    <value>Reissued</value>
  </data>
  <data name="Js.Overview.Active" xml:space="preserve">
    <value>Active</value>
  </data>
  <data name="Generic.Any" xml:space="preserve">
    <value>Any</value>
  </data>
  <data name="Generic.AnyTime" xml:space="preserve">
    <value>Any time</value>
  </data>
  <data name="Generic.Cancel" xml:space="preserve">
    <value>Cancel</value>
  </data>
  <data name="Generic.ExportCsv" xml:space="preserve">
    <value>Export CSV</value>
  </data>
  <data name="Js.Usage.Billions" xml:space="preserve">
    <value>{0}B</value>
  </data>
  <data name="Js.Usage.Millions" xml:space="preserve">
    <value>{0}M</value>
  </data>
  <data name="Js.Usage.Thousands" xml:space="preserve">
    <value>{0}k</value>
  </data>
  <data name="Gateway.At" xml:space="preserve">
    <value>at</value>
  </data>
  <data name="Gateway.NotReported" xml:space="preserve">
    <value>Not reported</value>
  </data>
  <data name="Gateway.NotReported.Lower" xml:space="preserve">
    <value>not reported</value>
  </data>
  <data name="Gateway.Of" xml:space="preserve">
    <value>of {0}</value>
  </data>
  <data name="Gateway.Tokens" xml:space="preserve">
    <value>{0} tokens</value>
  </data>
  <data name="Gateway.Days" xml:space="preserve">
    <value>{0} days</value>
  </data>
  <data name="Gateway.Days.One" xml:space="preserve">
    <value>1 day</value>
  </data>
  <data name="Gateway.Since" xml:space="preserve">
    <value>since {0}</value>
  </data>
  <data name="Gateway.Revoke" xml:space="preserve">
    <value>Revoke</value>
  </data>
  <data name="Gateway.Restore" xml:space="preserve">
    <value>Restore</value>
  </data>
  <data name="Gateway.Reason" xml:space="preserve">
    <value>Reason</value>
  </data>
  <data name="Gateway.Reason.Required" xml:space="preserve">
    <value>Say why: the audit log keeps it.</value>
  </data>
  <data name="Gateway.Reason.Length" xml:space="preserve">
    <value>A reason is 3 to 500 characters.</value>
  </data>
  <data name="Gateway.YourName" xml:space="preserve">
    <value>Your name</value>
  </data>
  <data name="Gateway.YourName.Required" xml:space="preserve">
    <value>Enter your name: under the shared password it is the only record of who did this.</value>
  </data>
  <data name="Gateway.YourName.Length" xml:space="preserve">
    <value>A name is at most 100 characters.</value>
  </data>
  <data name="Gateway.SharedPassword.NameHelp" xml:space="preserve">
    <value>You are signed in with the shared password, which names no one. The audit log records this as who you said you were, and it proves nothing.</value>
  </data>
  <data name="Gateway.RecordedAs" xml:space="preserve">
    <value>Recorded as {0}, here and in the gateway's log.</value>
  </data>
  <data name="Gateway.CopyId" xml:space="preserve">
    <value>Copy the id</value>
  </data>
  <data name="Gateway.CopyWholeId" xml:space="preserve">
    <value>Copy the whole id</value>
  </data>
  <data name="Gateway.CopyId.Aria" xml:space="preserve">
    <value>Copy installation id {0}</value>
  </data>
  <data name="Gateway.Row.evaluation" xml:space="preserve">
    <value>Evaluation</value>
  </data>
  <data name="Gateway.Row.standard" xml:space="preserve">
    <value>Standard</value>
  </data>
  <data name="Gateway.Row.enterprise" xml:space="preserve">
    <value>Enterprise</value>
  </data>
  <data name="Gateway.Status.active" xml:space="preserve">
    <value>Active</value>
  </data>
  <data name="Gateway.Status.revoked" xml:space="preserve">
    <value>Revoked</value>
  </data>
  <data name="Gateway.Status.revoked.Lower" xml:space="preserve">
    <value>revoked</value>
  </data>
  <data name="Gateway.Seen.day" xml:space="preserve">
    <value>In the last day</value>
  </data>
  <data name="Gateway.Seen.week" xml:space="preserve">
    <value>In the last week</value>
  </data>
  <data name="Gateway.Seen.month" xml:space="preserve">
    <value>In the last month</value>
  </data>
  <data name="Gateway.Seen.longer" xml:space="preserve">
    <value>Longer ago than a month</value>
  </data>
  <data name="Gateway.Sort.created" xml:space="preserve">
    <value>Newest enrolled</value>
  </data>
  <data name="Gateway.Sort.last_seen" xml:space="preserve">
    <value>Last seen</value>
  </data>
  <data name="Gateway.Sort.tokens_used" xml:space="preserve">
    <value>Tokens used</value>
  </data>
  <data name="Gateway.NoUsageYet.Title" xml:space="preserve">
    <value>The gateway does not report usage yet</value>
  </data>
  <data name="Gateway.NoWriteToken.Title" xml:space="preserve">
    <value>The console has no write token</value>
  </data>
  <data name="Gateway.NoWriteToken.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt;, the gateway's &lt;code&gt;Admin__Token&lt;/code&gt;, is not in Key Vault, so the console reads the gateway and does not change it. Loading it is B3 of &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.NoWriteToken.Short" xml:space="preserve">
    <value>The console has no write token: &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; is not in Key Vault, so it reads the gateway and does not change it.</value>
  </data>
  <data name="Gateway.ViewNotDo.Title" xml:space="preserve">
    <value>You can view this, not do it</value>
  </data>
  <data name="Gateway.ViewNotDo.Detail" xml:space="preserve">
    <value>You are signed in as {0}, which does not hold {1}. An Administrator grants it on the Users page.</value>
  </data>
  <data name="Gateway.Write.WriteRefused.Title" xml:space="preserve">
    <value>The gateway refused the console's write token</value>
  </data>
  <data name="Gateway.Write.WriteRefused.Detail" xml:space="preserve">
    <value>It answered 403: it knows the token, and does not let it write. &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; holds the gateway's read token; it must be its &lt;code&gt;Admin__Token&lt;/code&gt;. Nothing was changed.</value>
  </data>
  <data name="Gateway.Write.TokenRefused.Title" xml:space="preserve">
    <value>The gateway refused the console's token</value>
  </data>
  <data name="Gateway.Write.TokenRefused.Detail" xml:space="preserve">
    <value>It answered 401: &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; is neither of its tokens. It must be the gateway's &lt;code&gt;Admin__Token&lt;/code&gt; for the same environment. Nothing was changed.</value>
  </data>
  <data name="Gateway.Write.NotConfigured.Detail" xml:space="preserve">
    <value>Nothing was sent. &lt;code&gt;Gateway--AdminWriteToken&lt;/code&gt; is not in Key Vault.</value>
  </data>
  <data name="Gateway.Write.RequestRefused.Title" xml:space="preserve">
    <value>The gateway refused what the console sent</value>
  </data>
  <data name="Gateway.Write.RequestRefused.Detail" xml:space="preserve">
    <value>It answered 400, a fault in the console rather than an outage; nothing was changed.</value>
  </data>
  <data name="Gateway.Requests.AMinute" xml:space="preserve">
    <value>{0} a minute</value>
  </data>
  <data name="Gateway.Requests.PerSeconds" xml:space="preserve">
    <value>{0} per {1} seconds</value>
  </data>
  <data name="Gateway.Period.Month" xml:space="preserve">
    <value>a calendar month, UTC</value>
  </data>
  <data name="Gateway.Period.Rolling" xml:space="preserve">
    <value>per 30 days, rolling from enrolment</value>
  </data>
  <data name="Gateway.Period.Other" xml:space="preserve">
    <value>per "{0}"</value>
  </data>
  <data name="Gateway.PeriodName.Month" xml:space="preserve">
    <value>a calendar month</value>
  </data>
  <data name="Gateway.PeriodName.Rolling" xml:space="preserve">
    <value>thirty days rolling</value>
  </data>
  <data name="Gateway.Range.Unbounded" xml:space="preserve">
    <value>a whole number, 1 or more</value>
  </data>
  <data name="Gateway.Range.UpTo" xml:space="preserve">
    <value>a whole number from 1 to {0}</value>
  </data>
  <data name="Gateway.Allowance.ItsRows" xml:space="preserve">
    <value>its row's</value>
  </data>
  <data name="Gateway.Allowance.TheRows" xml:space="preserve">
    <value>the {0} row's</value>
  </data>
  <data name="Gateway.Allowance.TheLicences" xml:space="preserve">
    <value>the licence's</value>
  </data>
  <data name="Gateway.Allowance.AMinute" xml:space="preserve">
    <value>{0} a minute, {1}</value>
  </data>
  <data name="Gateway.Allowance.TokensOwner" xml:space="preserve">
    <value>{0} {1}, {2}</value>
  </data>
  <data name="Gateway.Allowance.TokensOwners" xml:space="preserve">
    <value>{0} {1}: the number {2}, the period {3}</value>
  </data>
  <data name="Gateway.Allowance.Period.Month" xml:space="preserve">
    <value>a calendar month</value>
  </data>
  <data name="Gateway.Allowance.Period.30d" xml:space="preserve">
    <value>per 30 days</value>
  </data>
  <data name="Gateway.Allowance.Period.APeriod" xml:space="preserve">
    <value>a period</value>
  </data>
  <data name="Gateway.Allowance.Period.Other" xml:space="preserve">
    <value>per period "{0}"</value>
  </data>
  <data name="Gateway.Unavailable.NotConfigured.Title" xml:space="preserve">
    <value>The gateway is not configured</value>
  </data>
  <data name="Gateway.Unavailable.NotConfigured.Detail" xml:space="preserve">
    <value>&lt;code&gt;Gateway--AdminToken&lt;/code&gt; is not in Key Vault, so the console does not ask the gateway anything. Loading it is B3 of &lt;code&gt;docs/Provisioning.md&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Unavailable.NoStatus.Title" xml:space="preserve">
    <value>The gateway does not report status yet</value>
  </data>
  <data name="Gateway.Unavailable.NoStatus.Detail" xml:space="preserve">
    <value>It lists its installations but answers 404 for &lt;code&gt;/admin/status&lt;/code&gt;: it predates kf-ai-gateway#37. There is nothing to show here until that is deployed. The register's pages are unaffected.</value>
  </data>
  <data name="Gateway.Unavailable.NoFilters.Title" xml:space="preserve">
    <value>The gateway does not filter its installations yet</value>
  </data>
  <data name="Gateway.Unavailable.NoFilters.Detail" xml:space="preserve">
    <value>It answered without the filters, order or page asked for: it predates kf-ai-gateway#38, and would have listed its newest installations as though it had applied them. Clear the filters to see those.</value>
  </data>
  <data name="Gateway.Unavailable.Unknown.Title" xml:space="preserve">
    <value>The gateway knows no installation with this id</value>
  </data>
  <data name="Gateway.Unavailable.Unknown.Detail" xml:space="preserve">
    <value>An installation enrols the first time it uses AI, so one that never has is not on the gateway, and an id from another environment is on that environment's gateway. &lt;code&gt;docs/Operations.md&lt;/code&gt; has what to check.</value>
  </data>
  <data name="Gateway.Overview.Lead" xml:space="preserve">
    <value>What the gateway{0} says of itself, from its &lt;code&gt;GET /admin/status&lt;/code&gt;: what is deployed, what the whole service has spent against its ceiling, and the fleet in numbers; and, from its daily usage ledger, the fleet's last thirty days. Read with the read-only token; nothing on this page changes the gateway.</value>
  </data>
  <data name="Gateway.Overview.Status" xml:space="preserve">
    <value>Status</value>
  </data>
  <data name="Gateway.Overview.Status.AsOf" xml:space="preserve">
    <value>As of {0} UTC. The console asks at most every {1} seconds.</value>
  </data>
  <data name="Gateway.Overview.Version" xml:space="preserve">
    <value>Version</value>
  </data>
  <data name="Gateway.Overview.Started" xml:space="preserve">
    <value>Started</value>
  </data>
  <data name="Gateway.Overview.Up" xml:space="preserve">
    <value>Up {0}</value>
  </data>
  <data name="Gateway.Overview.Up.Days" xml:space="preserve">
    <value>{0} days</value>
  </data>
  <data name="Gateway.Overview.Up.Hours" xml:space="preserve">
    <value>{0} hours</value>
  </data>
  <data name="Gateway.Overview.Up.UnderAnHour" xml:space="preserve">
    <value>under an hour</value>
  </data>
  <data name="Gateway.Overview.Telemetry" xml:space="preserve">
    <value>Telemetry</value>
  </data>
  <data name="Gateway.Overview.Telemetry.Connected" xml:space="preserve">
    <value>Application Insights connected</value>
  </data>
  <data name="Gateway.Overview.Telemetry.None" xml:space="preserve">
    <value>No telemetry sink</value>
  </data>
  <data name="Gateway.Overview.Telemetry.None.Detail" xml:space="preserve">
    <value>Nothing reaches Application Insights; the gateway's alerts see nothing.</value>
  </data>
  <data name="Gateway.Brake.Title" xml:space="preserve">
    <value>The global brake</value>
  </data>
  <data name="Gateway.Brake.Lead" xml:space="preserve">
    <value>Tokens the whole service has spent this calendar month, against the ceiling that pauses everyone.</value>
  </data>
  <data name="Gateway.Brake.NotReported" xml:space="preserve">
    <value>The gateway did not report the brake.</value>
  </data>
  <data name="Gateway.Brake.Off.Title" xml:space="preserve">
    <value>The global brake is off</value>
  </data>
  <data name="Gateway.Brake.Off.Detail" xml:space="preserve">
    <value>No ceiling is set, so only the provider's own cap stands behind the service. Setting one is &lt;code&gt;GlobalTokenCeiling&lt;/code&gt; on the gateway's policy row (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Brake.SpentSince" xml:space="preserve">
    <value>Spent since {0}: {1} tokens.</value>
  </data>
  <data name="Gateway.Brake.On.Title" xml:space="preserve">
    <value>The global brake is on</value>
  </data>
  <data name="Gateway.Brake.On.Detail" xml:space="preserve">
    <value>Every chat from every installation is refused &lt;code&gt;503 service_paused&lt;/code&gt; until the ceiling is raised. A restart does not release it, and the spend counter is not the operator's to edit: raising the ceiling is the whole of the release, from the next chat.</value>
  </data>
  <data name="Gateway.Brake.ChangeCeiling" xml:space="preserve">
    <value>Change the global ceiling</value>
  </data>
  <data name="Gateway.Brake.OfTokens" xml:space="preserve">
    <value>{0} of {1} tokens</value>
  </data>
  <data name="Gateway.Brake.Aria" xml:space="preserve">
    <value>Tokens spent against the ceiling</value>
  </data>
  <data name="Gateway.Brake.PeriodEnds" xml:space="preserve">
    <value>The period ends {0}, when the counter starts again.</value>
  </data>
  <data name="Gateway.Brake.Close" xml:space="preserve">
    <value>Close to the ceiling: the brake trips for everyone when it is reached.</value>
  </data>
  <data name="Gateway.Overview.LastDays" xml:space="preserve">
    <value>The last {0} days</value>
  </data>
  <data name="Gateway.Overview.LastDays.Lead" xml:space="preserve">
    <value>Tokens, requests and refusals a day, from the gateway's daily usage ledger.</value>
  </data>
  <data name="Gateway.Usage.TokensADay" xml:space="preserve">
    <value>Tokens a day</value>
  </data>
  <data name="Gateway.Usage.RequestsADay" xml:space="preserve">
    <value>Requests a day</value>
  </data>
  <data name="Gateway.Overview.TokensADay.Lead" xml:space="preserve">
    <value>The last {0} days across the fleet, by the row each installation is served now: {1} tokens in all.</value>
  </data>
  <data name="Gateway.Overview.RefusalsADay" xml:space="preserve">
    <value>Refusals a day</value>
  </data>
  <data name="Gateway.Usage.Totals" xml:space="preserve">
    <value>Of {0} requests, {1} refused rate limited, {2} for a spent budget, and {3} failed upstream.</value>
  </data>
  <data name="Gateway.Overview.Usage.Footnote" xml:space="preserve">
    <value>Days in UTC, today so far. Tokens count as each chat ends; requests, refusals and upstream errors reach the gateway's ledger once a minute. An installation counts under the row it is served now, for the whole range. Days before the gateway kept the ledger (kf-ai-gateway#41) are zero.</value>
  </data>
  <data name="Gateway.Overview.NoFleet" xml:space="preserve">
    <value>The gateway did not report its fleet.</value>
  </data>
  <data name="Gateway.Overview.ActiveRevoked" xml:space="preserve">
    <value>{0} active, {1} revoked</value>
  </data>
  <data name="Gateway.Overview.Row.evaluation" xml:space="preserve">
    <value>On the evaluation row: no licence, or one that lapsed</value>
  </data>
  <data name="Gateway.Overview.Row.standard" xml:space="preserve">
    <value>Licensed, served the standard row</value>
  </data>
  <data name="Gateway.Overview.Row.enterprise" xml:space="preserve">
    <value>Licensed, served the enterprise row</value>
  </data>
  <data name="Gateway.Overview.SeenRecently" xml:space="preserve">
    <value>Seen recently</value>
  </data>
  <data name="Gateway.Overview.SeenRecently.Lead" xml:space="preserve">
    <value>Installations that made an authenticated call to the gateway. An installation that never uses AI never enrols, so it is in none of these.</value>
  </data>
  <data name="Gateway.Overview.Last24h" xml:space="preserve">
    <value>Last 24 hours</value>
  </data>
  <data name="Gateway.Overview.Last7d" xml:space="preserve">
    <value>Last 7 days</value>
  </data>
  <data name="Gateway.Overview.Last30d" xml:space="preserve">
    <value>Last 30 days</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded" xml:space="preserve">
    <value>Licence tier not recorded</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.Lead" xml:space="preserve">
    <value>Licensed installations whose licence arrived before the gateway read &lt;code&gt;tier&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.None" xml:space="preserve">
    <value>Every licensed installation has its licence tier recorded.</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.Some.One" xml:space="preserve">
    <value>1 installation is served the standard row whatever the licence says, until kf-app sends the licence again. Look for an Enterprise customer among them before raising &lt;code&gt;enterprise&lt;/code&gt;'s allowance (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Overview.TierNotRecorded.Some.Many" xml:space="preserve">
    <value>{0} installations are served the standard row whatever the licence says, until kf-app sends the licence again. Look for an Enterprise customer among them before raising &lt;code&gt;enterprise&lt;/code&gt;'s allowance (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Overview.Footnote" xml:space="preserve">
    <value>The rows are the allowance each installation is served, not the wire tier, which calls both licence rows &lt;code&gt;licensed&lt;/code&gt;. These are the gateway's own counts; the register's are on the Overview, and the two differ wherever a licence was never installed on an installation that uses AI.</value>
  </data>
  <data name="Gateway.Overview.Footnote.Caller" xml:space="preserve">
    <value>The gateway attributed this console's request to {0}, which is the check to make before the enrolment velocity limit is armed.</value>
  </data>
  <data name="Gateway.Card.Lead" xml:space="preserve">
    <value>What {0} says of itself, as of {1} UTC.</value>
  </data>
  <data name="Gateway.Card.Lead.NoHost" xml:space="preserve">
    <value>The gateway, as the console last saw it.</value>
  </data>
  <data name="Gateway.Card.Gateway" xml:space="preserve">
    <value>Gateway</value>
  </data>
  <data name="Gateway.Card.Answering" xml:space="preserve">
    <value>Answering</value>
  </data>
  <data name="Gateway.Card.Version" xml:space="preserve">
    <value>Version {0}</value>
  </data>
  <data name="Gateway.Card.Brake" xml:space="preserve">
    <value>Global brake</value>
  </data>
  <data name="Gateway.Card.Brake.Off" xml:space="preserve">
    <value>Off</value>
  </data>
  <data name="Gateway.Card.Brake.Off.Detail" xml:space="preserve">
    <value>{0} tokens spent this month, no ceiling</value>
  </data>
  <data name="Gateway.Card.Brake.Tripped" xml:space="preserve">
    <value>Tripped</value>
  </data>
  <data name="Gateway.Card.Brake.Tripped.Detail" xml:space="preserve">
    <value>Every chat is refused until the ceiling is raised</value>
  </data>
  <data name="Gateway.Card.Brake.Used" xml:space="preserve">
    <value>{0} of {1} tokens this month</value>
  </data>
  <data name="Gateway.Card.Active" xml:space="preserve">
    <value>{0} active</value>
  </data>
  <data name="Gateway.Card.Seen" xml:space="preserve">
    <value>{0} seen in the last day, {1} revoked</value>
  </data>
  <data name="Gateway.Installations.Lead" xml:space="preserve">
    <value>Every installation the gateway{0} has enrolled, filtered, ordered and paged by the gateway itself, with what each has used against its allowance and the register's customer for the licence it holds. An installation enrols the first time it uses AI. Read with the read-only token; nothing on this page changes the gateway.</value>
  </data>
  <data name="Gateway.Installations.Search" xml:space="preserve">
    <value>Installation id or licence id</value>
  </data>
  <data name="Gateway.Installations.Search.Placeholder" xml:space="preserve">
    <value>The whole id</value>
  </data>
  <data name="Gateway.Installations.Order" xml:space="preserve">
    <value>Order</value>
  </data>
  <data name="Gateway.Installations.Row" xml:space="preserve">
    <value>Row</value>
  </data>
  <data name="Gateway.Installations.Status" xml:space="preserve">
    <value>Status</value>
  </data>
  <data name="Gateway.Installations.LastSeen" xml:space="preserve">
    <value>Last seen</value>
  </data>
  <data name="Gateway.Installations.Below" xml:space="preserve">
    <value>App version below</value>
  </data>
  <data name="Gateway.Installations.LongGone" xml:space="preserve">
    <value>Longer ago than a month is in order of last seen, newest first: the gateway filters on seen-since alone, so the console lists what comes after the installations seen in the last month.</value>
  </data>
  <data name="Gateway.Installations.NotAsked" xml:space="preserve">
    <value>The gateway was not asked</value>
  </data>
  <data name="Gateway.Installations.Problem.Version" xml:space="preserve">
    <value>"{0}" is not an application version. Write one such as 1.7.0; a prerelease counts as its release.</value>
  </data>
  <data name="Gateway.Installations.Problem.Search" xml:space="preserve">
    <value>Search takes an installation id or a licence id, whole: the gateway looks up ids exactly, not by part.</value>
  </data>
  <data name="Gateway.Installations.HoldingLicence" xml:space="preserve">
    <value>Holding licence id {0}</value>
  </data>
  <data name="Gateway.Installations.HoldingLicence.Lead" xml:space="preserve">
    <value>No installation has this id, so it is read as a licence id: every installation holding it, revoked or not, however old.</value>
  </data>
  <data name="Gateway.Installations.HoldingLicence.Row" xml:space="preserve">
    <value>Its register row is {0}.</value>
  </data>
  <data name="Gateway.Installations.Count.One" xml:space="preserve">
    <value>1 installation</value>
  </data>
  <data name="Gateway.Installations.Count.Many" xml:space="preserve">
    <value>{0} installations</value>
  </data>
  <data name="Gateway.Installations.Count.OneMatch" xml:space="preserve">
    <value>1 installation matches</value>
  </data>
  <data name="Gateway.Installations.Count.ManyMatch" xml:space="preserve">
    <value>{0} installations match</value>
  </data>
  <data name="Gateway.Installations.OrderLead" xml:space="preserve">
    <value>{0} first. The row is the allowance each is served, not the wire tier, which calls both licence rows &lt;code&gt;licensed&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Installations.NoUsageYet.Detail" xml:space="preserve">
    <value>It answered without an allowance or a total: it predates kf-ai-gateway#38. These are the newest it lists, unpaged, and the row is its wire tier.</value>
  </data>
  <data name="Gateway.Installations.Column.LastSeenUtc" xml:space="preserve">
    <value>Last seen, UTC</value>
  </data>
  <data name="Gateway.Installations.Column.Licence" xml:space="preserve">
    <value>Licence</value>
  </data>
  <data name="Gateway.Installations.Empty.Searched" xml:space="preserve">
    <value>No installation has this id, and none holds it as its licence.</value>
  </data>
  <data name="Gateway.Installations.Empty.Filtered" xml:space="preserve">
    <value>No installation matches these filters.</value>
  </data>
  <data name="Gateway.Installations.Empty" xml:space="preserve">
    <value>The gateway has no installations yet.</value>
  </data>
  <data name="Gateway.Licence.NotInRegister.Title" xml:space="preserve">
    <value>Issued offline without --register-csv, or by kf-app's former copy of the tool</value>
  </data>
  <data name="Gateway.Licence.RegisterUnread" xml:space="preserve">
    <value>Register not read</value>
  </data>
  <data name="Gateway.Licence.RegisterUnread.Title" xml:space="preserve">
    <value>The register has no database, or could not be read</value>
  </data>
  <data name="Gateway.Licence.IdNotRecorded" xml:space="preserve">
    <value>Licensed, id not recorded</value>
  </data>
  <data name="Gateway.Licence.IdNotRecorded.Title" xml:space="preserve">
    <value>Licensed before kf-ai-gateway#35 recorded licence ids; it has one once kf-app sends its licence again</value>
  </data>
  <data name="Gateway.Licence.None" xml:space="preserve">
    <value>No licence</value>
  </data>
  <data name="Gateway.Installation.Title" xml:space="preserve">
    <value>Installation</value>
  </data>
  <data name="Gateway.Installation.Changed.Revoked" xml:space="preserve">
    <value>&lt;strong&gt;Revoked.&lt;/strong&gt; The gateway refuses every call from it from now on. The audit log has the entry.</value>
  </data>
  <data name="Gateway.Installation.Changed.Restored" xml:space="preserve">
    <value>&lt;strong&gt;Restored.&lt;/strong&gt; The gateway serves it its row again from its next call. The audit log has the entry.</value>
  </data>
  <data name="Gateway.Installation.Changed.SeeIt" xml:space="preserve">
    <value>See it</value>
  </data>
  <data name="Gateway.Installation.NoLookup.Title" xml:space="preserve">
    <value>The gateway does not look installations up by id yet</value>
  </data>
  <data name="Gateway.Installation.NoLookup.Detail" xml:space="preserve">
    <value>It predates kf-ai-gateway#38, so the console looked among the newest 500 installations it lists, and this one is not among them.</value>
  </data>
  <data name="Gateway.Installation.OnGateway" xml:space="preserve">
    <value>On the gateway</value>
  </data>
  <data name="Gateway.Installation.OnGateway.Lead" xml:space="preserve">
    <value>What the gateway{0} holds of it. Not its credential, which the gateway does not return.</value>
  </data>
  <data name="Gateway.Installation.AppVersion" xml:space="preserve">
    <value>App version</value>
  </data>
  <data name="Gateway.Installation.ServedRow" xml:space="preserve">
    <value>Served the {0} row</value>
  </data>
  <data name="Gateway.Installation.RevokedAt" xml:space="preserve">
    <value>Revoked {0}</value>
  </data>
  <data name="Gateway.Installation.FirstEnrolled" xml:space="preserve">
    <value>First enrolled</value>
  </data>
  <data name="Gateway.Installation.Allowance" xml:space="preserve">
    <value>Allowance and usage</value>
  </data>
  <data name="Gateway.Installation.Allowance.Lead" xml:space="preserve">
    <value>The numbers its own &lt;code&gt;GET /v1/installation&lt;/code&gt; reports, read by the same code, so they are what the customer's AI Manager screen shows.</value>
  </data>
  <data name="Gateway.Installation.ServedNothing.Title" xml:space="preserve">
    <value>Served nothing while revoked</value>
  </data>
  <data name="Gateway.Installation.ServedNothing.Detail" xml:space="preserve">
    <value>Every call from it has been refused &lt;code&gt;403 installation_revoked&lt;/code&gt; since {0}, including one made after it enrols again.</value>
  </data>
  <data name="Gateway.Installation.ServedNothing.IfRestored" xml:space="preserve">
    <value>What follows is what it would be served if it were restored.</value>
  </data>
  <data name="Gateway.Installation.NoUsageYet.Detail" xml:space="preserve">
    <value>It answered without an allowance: it predates kf-ai-gateway#38. Until that is deployed, the numbers are only on the installation's own &lt;code&gt;GET /v1/installation&lt;/code&gt;, which the customer sees and the console does not.</value>
  </data>
  <data name="Gateway.Installation.Requests" xml:space="preserve">
    <value>Requests</value>
  </data>
  <data name="Gateway.Installation.Requests.Remaining" xml:space="preserve">
    <value>{0} of {1} remaining; a request frees at {2}</value>
  </data>
  <data name="Gateway.Installation.Requests.InMemory" xml:space="preserve">
    <value>Counted in the gateway's memory, so a restart reads it full again: the gateway's overview says when it last started.</value>
  </data>
  <data name="Gateway.Installation.Tokens" xml:space="preserve">
    <value>Tokens</value>
  </data>
  <data name="Gateway.Installation.Tokens.UsedOf" xml:space="preserve">
    <value>{0} used of {1}</value>
  </data>
  <data name="Gateway.Installation.Tokens.PeriodEnds" xml:space="preserve">
    <value>This period ends {0}, when the count starts again. Its earlier days are in its usage history, below.</value>
  </data>
  <data name="Gateway.Installation.LongestReply" xml:space="preserve">
    <value>Longest reply</value>
  </data>
  <data name="Gateway.Installation.LongestReply.Detail" xml:space="preserve">
    <value>{0} tokens, {1}. A licence never sets it.</value>
  </data>
  <data name="Gateway.Installation.ZeroLimit.Title" xml:space="preserve">
    <value>A limit of 0 allows nothing</value>
  </data>
  <data name="Gateway.Installation.ZeroLimit.Detail" xml:space="preserve">
    <value>The licence carried an &lt;code&gt;ai.tokens&lt;/code&gt; or &lt;code&gt;ai.rpm&lt;/code&gt; the gateway could not read, and it serves that as 0. Reissue the licence with a number it can.</value>
  </data>
  <data name="Gateway.Installation.History.Lead" xml:space="preserve">
    <value>Its last {0} days from the gateway's daily usage ledger, in UTC days, today so far.</value>
  </data>
  <data name="Gateway.Installation.History.Totals" xml:space="preserve">
    <value>{0} tokens and {1} requests: {2} refused rate limited, {3} for a spent budget, and {4} failed upstream.</value>
  </data>
  <data name="Gateway.Installation.HowManyDays" xml:space="preserve">
    <value>How many days</value>
  </data>
  <data name="Gateway.Installation.History.Footnote" xml:space="preserve">
    <value>Tokens count as each chat ends; requests, refusals and upstream errors reach the ledger once a minute. A day it made no request is zero, and so is every day before the gateway kept the ledger (kf-ai-gateway#41).</value>
  </data>
  <data name="Gateway.Installation.ItsLicence" xml:space="preserve">
    <value>Its licence</value>
  </data>
  <data name="Gateway.Installation.ItsLicence.Lead" xml:space="preserve">
    <value>The licence the gateway accepted for it, as the register issued it.</value>
  </data>
  <data name="Gateway.Installation.Shared.Detail" xml:space="preserve">
    <value>The gateway says this licence id is held by more than one installation that has not been revoked. A licence covers one installation: ask the customer which should have it, then revoke the other.</value>
  </data>
  <data name="Gateway.Installation.Shared.SeeAll" xml:space="preserve">
    <value>See them all</value>
  </data>
  <data name="Gateway.Installation.LicenceFiles" xml:space="preserve">
    <value>{0} files in the register: a reissue keeps the id, and this is the latest.</value>
  </data>
  <data name="Gateway.Installation.NotInRegister.Detail" xml:space="preserve">
    <value>The gateway accepted a licence the register does not hold: issued offline without &lt;code class="text-nowrap"&gt;--register-csv&lt;/code&gt;, or by kf-app's copy of the tool before kf-app#982 deleted it.</value>
  </data>
  <data name="Gateway.Installation.LicenceIdIs" xml:space="preserve">
    <value>Licence id {0}</value>
  </data>
  <data name="Gateway.Installation.RegisterUnread.Detail" xml:space="preserve">
    <value>It has no database, or did not answer: the console's log has why.</value>
  </data>
  <data name="Gateway.Installation.IdNotRecorded.Detail" xml:space="preserve">
    <value>Licensed, and the gateway holds no licence id for it: it was licensed before kf-ai-gateway#35 recorded them, on 2026-09-26, and has none until kf-app sends its licence again. On a kf-app with kf-app#968, that is uploading it again; kf-app 1.6.2 sends it only when it first enrols.</value>
  </data>
  <data name="Gateway.Installation.OnEvaluation" xml:space="preserve">
    <value>On evaluation.</value>
  </data>
  <data name="Gateway.Installation.Refused.Reason" xml:space="preserve">
    <value>The gateway refused the licence it was last sent: {0}.</value>
  </data>
  <data name="Gateway.Installation.Refused" xml:space="preserve">
    <value>The gateway refused the licence it was last sent.</value>
  </data>
  <data name="Gateway.Installation.NoneSent" xml:space="preserve">
    <value>It has not sent the gateway a licence it holds now: none, or one that lapsed or was removed.</value>
  </data>
  <data name="Gateway.Installation.WhatToDo" xml:space="preserve">
    <value>What to do about its allowance</value>
  </data>
  <data name="Gateway.Installation.WhatToDo.Detail" xml:space="preserve">
    <value>A customer's allowance changes by reissuing their licence with the numbers it should carry, installed from kf-app. What a licence leaves out is its row's, which is policy and moves every installation on it at once. There is no override for one installation, and never one here (kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt;).</value>
  </data>
  <data name="Gateway.Installation.Restore.Lead" xml:space="preserve">
    <value>Restoring serves it its row again from its next call. You say why on the next page, and it is audited.</value>
  </data>
  <data name="Gateway.Installation.Revoke.Lead" xml:space="preserve">
    <value>Revoking refuses every call it makes &lt;code&gt;403 installation_revoked&lt;/code&gt;, re-enrolling included, until it is restored. You say why on the next page, and it is audited.</value>
  </data>
  <data name="Gateway.Installation.ViewOnly" xml:space="preserve">
    <value>You can view this installation, not change it: that needs {0}.</value>
  </data>
  <data name="Gateway.Change.Revoke.PageTitle" xml:space="preserve">
    <value>Revoke an installation</value>
  </data>
  <data name="Gateway.Change.Restore.PageTitle" xml:space="preserve">
    <value>Restore an installation</value>
  </data>
  <data name="Gateway.Change.Revoke.Title" xml:space="preserve">
    <value>Revoke installation {0}</value>
  </data>
  <data name="Gateway.Change.Restore.Title" xml:space="preserve">
    <value>Restore installation {0}</value>
  </data>
  <data name="Gateway.Change.Lead" xml:space="preserve">
    <value>A change on the gateway{0} with the console's write token. It is recorded in the audit log, with your reason, once the gateway confirms it, and the gateway records it in its own log under the same name.</value>
  </data>
  <data name="Gateway.Change.Unknown.Title" xml:space="preserve">
    <value>The gateway no longer knows this installation</value>
  </data>
  <data name="Gateway.Change.Unknown.Detail" xml:space="preserve">
    <value>It answered 404. Nothing was changed.</value>
  </data>
  <data name="Gateway.Change.Unsure.Title" xml:space="preserve">
    <value>The console could not tell whether the gateway made the change</value>
  </data>
  <data name="Gateway.Change.Unsure.Detail" xml:space="preserve">
    <value>Open the installation's page to see its status before trying again. No audit entry was written.</value>
  </data>
  <data name="Gateway.Change.TheInstallation" xml:space="preserve">
    <value>The installation</value>
  </data>
  <data name="Gateway.Change.HeldBy" xml:space="preserve">
    <value>Held by {0} installations</value>
  </data>
  <data name="Gateway.Change.WhatRevokeDoes" xml:space="preserve">
    <value>What revoke does</value>
  </data>
  <data name="Gateway.Change.WhatRestoreDoes" xml:space="preserve">
    <value>What restore does</value>
  </data>
  <data name="Gateway.Change.Revoke.Detail" xml:space="preserve">
    <value>Every call it makes is refused &lt;code&gt;403 installation_revoked&lt;/code&gt; from its next one: AI, the allowance it reads, everything. &lt;strong&gt;Re-enrolling does not get round it&lt;/strong&gt;: a new credential it enrols for is refused too. It stops counting as holding its licence, so a licence flagged as on two installations is no longer flagged when this was the second. Restoring it undoes all of this.</value>
  </data>
  <data name="Gateway.Change.OnlyHolder" xml:space="preserve">
    <value>This is the only installation holding {0}'s licence that has not been revoked. Their AI stops until it is restored.</value>
  </data>
  <data name="Gateway.Change.Restore.Detail" xml:space="preserve">
    <value>It is served its row again from its next call, and counts as holding its licence again, so a licence it shares is flagged again. The credential it has keeps working; it does not need to enrol again.</value>
  </data>
  <data name="Gateway.Change.AlreadyRevoked" xml:space="preserve">
    <value>It is already revoked, since {0}.</value>
  </data>
  <data name="Gateway.Change.RestoreIt" xml:space="preserve">
    <value>Restore it</value>
  </data>
  <data name="Gateway.Change.NotRevoked" xml:space="preserve">
    <value>It is not revoked.</value>
  </data>
  <data name="Gateway.Change.RevokeIt" xml:space="preserve">
    <value>Revoke it</value>
  </data>
  <data name="Gateway.Change.Instead" xml:space="preserve">
    <value>instead.</value>
  </data>
  <data name="Gateway.Change.Revoke.Placeholder" xml:space="preserve">
    <value>Reinstalled; the customer says the old server is gone</value>
  </data>
  <data name="Gateway.Change.Restore.Placeholder" xml:space="preserve">
    <value>Revoked by mistake</value>
  </data>
  <data name="Gateway.Change.Revoke.Submit" xml:space="preserve">
    <value>Revoke installation</value>
  </data>
  <data name="Gateway.Change.Restore.Submit" xml:space="preserve">
    <value>Restore installation</value>
  </data>
  <data name="Gateway.Usage.Lead" xml:space="preserve">
    <value>Every licence in force in the register, beside what the gateway{0} says its installation has used this period and has left, and spent the calendar month before, from its daily usage ledger. The register says what each licence carries; the gateway says what it is served and has spent. Read at {1} UTC with the read-only token; nothing on this page changes either.</value>
  </data>
  <data name="Gateway.Usage.RegisterUnread.Detail" xml:space="preserve">
    <value>Every row of this page is a licence in the register, so there is nothing to list. The console's log has why, under "The usage by licence could not read the licence register".</value>
  </data>
  <data name="Gateway.Usage.Allowance" xml:space="preserve">
    <value>Allowance</value>
  </data>
  <data name="Gateway.Usage.Allowance.standard" xml:space="preserve">
    <value>Standard: tier standard, none or unknown</value>
  </data>
  <data name="Gateway.Usage.Allowance.enterprise" xml:space="preserve">
    <value>Enterprise</value>
  </data>
  <data name="Gateway.Usage.EveryLicence" xml:space="preserve">
    <value>Every licence</value>
  </data>
  <data name="Gateway.Usage.CustomersOnly" xml:space="preserve">
    <value>Customers only, without internal and demo</value>
  </data>
  <data name="Gateway.Usage.Sort.used" xml:space="preserve">
    <value>Most used first</value>
  </data>
  <data name="Gateway.Usage.Sort.least" xml:space="preserve">
    <value>Least used first</value>
  </data>
  <data name="Gateway.Usage.Sort.expiry" xml:space="preserve">
    <value>Expiring first</value>
  </data>
  <data name="Gateway.Usage.Sort.customer" xml:space="preserve">
    <value>Customer</value>
  </data>
  <data name="Gateway.Usage.NoUsageYet.Detail" xml:space="preserve">
    <value>It answered without an allowance or a total: it predates kf-ai-gateway#38, which reports what each installation is allowed and has used. The register's columns are below; the gateway's fill in once it is deployed.</value>
  </data>
  <data name="Gateway.Usage.Count.One" xml:space="preserve">
    <value>1 licence in force</value>
  </data>
  <data name="Gateway.Usage.Count.Many" xml:space="preserve">
    <value>{0} licences in force</value>
  </data>
  <data name="Gateway.Usage.OnAllowance" xml:space="preserve">
    <value>on the {0} allowance</value>
  </data>
  <data name="Gateway.Usage.Hidden.One" xml:space="preserve">
    <value>1 internal or demo licence is left out.</value>
  </data>
  <data name="Gateway.Usage.Hidden.Many" xml:space="preserve">
    <value>{0} internal or demo licences are left out.</value>
  </data>
  <data name="Gateway.Usage.Enrolled" xml:space="preserve">
    <value>{0} enrolled, {1} not enrolled.</value>
  </data>
  <data name="Gateway.Usage.NearLimit" xml:space="preserve">
    <value>{0} at {1}% or more</value>
  </data>
  <data name="Gateway.Usage.SharedCount" xml:space="preserve">
    <value>{0} on more than one installation</value>
  </data>
  <data name="Gateway.Usage.ServedOtherwiseCount" xml:space="preserve">
    <value>{0} served otherwise than the register says</value>
  </data>
  <data name="Gateway.Usage.LastMonth.NoLedger" xml:space="preserve">
    <value>Last month's tokens are not shown: the gateway does not keep usage history yet, since it predates kf-ai-gateway#41.</value>
  </data>
  <data name="Gateway.Usage.LastMonth.Failed" xml:space="preserve">
    <value>Last month's tokens are not shown: the gateway did not answer for its usage history. {0}</value>
  </data>
  <data name="Gateway.Usage.LastMonth.Partial" xml:space="preserve">
    <value>Last month's tokens are not shown for {0} installations: more spent less than the gateway's top fifty than the console asks about one at a time for one page.</value>
  </data>
  <data name="Gateway.Usage.LastMonth.NotRead" xml:space="preserve">
    <value>Not read</value>
  </data>
  <data name="Gateway.Usage.LastMonth.TooMany" xml:space="preserve">
    <value>Not read: more installations than the console asks about one at a time</value>
  </data>
  <data name="Gateway.Usage.LastMonth.NoAnswer" xml:space="preserve">
    <value>The gateway did not answer</value>
  </data>
  <data name="Gateway.Usage.LastMonth.Title" xml:space="preserve">
    <value>The calendar month before this one, in UTC, from the gateway's daily usage ledger</value>
  </data>
  <data name="Gateway.Usage.TokensIn" xml:space="preserve">
    <value>Tokens in {0}</value>
  </data>
  <data name="Gateway.Usage.TokensLastMonth" xml:space="preserve">
    <value>Tokens last month</value>
  </data>
  <data name="Gateway.Usage.TokensThisPeriod" xml:space="preserve">
    <value>Tokens used this period</value>
  </data>
  <data name="Gateway.Usage.Empty.Customers" xml:space="preserve">
    <value>No customer licence is in force.</value>
  </data>
  <data name="Gateway.Usage.Empty.Allowance" xml:space="preserve">
    <value>No licence in force is on this allowance.</value>
  </data>
  <data name="Gateway.Usage.Empty" xml:space="preserve">
    <value>No licence in the register is in force.</value>
  </data>
  <data name="Gateway.Usage.NearLimit.Title" xml:space="preserve">
    <value>An installation holding it has used {0}% or more of its token budget this period</value>
  </data>
  <data name="Gateway.Usage.PercentUsed" xml:space="preserve">
    <value>{0}% used</value>
  </data>
  <data name="Gateway.Usage.Shared.Title" xml:space="preserve">
    <value>A licence covers one installation: the register row's page says what to do</value>
  </data>
  <data name="Gateway.Usage.ServedOtherwise" xml:space="preserve">
    <value>Served otherwise</value>
  </data>
  <data name="Gateway.Usage.OneFile" xml:space="preserve">
    <value>One file</value>
  </data>
  <data name="Gateway.Usage.Files" xml:space="preserve">
    <value>{0} files: a reissue keeps the id</value>
  </data>
  <data name="Gateway.Usage.NotEnrolled" xml:space="preserve">
    <value>Not enrolled</value>
  </data>
  <data name="Gateway.Usage.NotEnrolled.Title" xml:space="preserve">
    <value>No installation the gateway knows holds this licence id</value>
  </data>
  <data name="Gateway.Usage.Unanswered.NotConfigured" xml:space="preserve">
    <value>Not configured</value>
  </data>
  <data name="Gateway.Usage.Unanswered.NotReported" xml:space="preserve">
    <value>Not reported yet</value>
  </data>
  <data name="Gateway.Usage.Unanswered.NoAnswer" xml:space="preserve">
    <value>No answer</value>
  </data>
  <data name="Gateway.Usage.LastCall" xml:space="preserve">
    <value>Its last authenticated call</value>
  </data>
  <data name="Gateway.Usage.Seen" xml:space="preserve">
    <value>Seen {0} UTC</value>
  </data>
  <data name="Gateway.Usage.LessThanRegister.Title" xml:space="preserve">
    <value>Where the gateway sees less than the register</value>
  </data>
  <data name="Gateway.Usage.LessThanRegister.Detail" xml:space="preserve">
    <value>An installation enrols the first time it uses AI, so a licence whose installation never has is &lt;em&gt;Not enrolled&lt;/em&gt;. The gateway holds the licence each installation last sent it: kf-app sends one on every install since kf-app#968, which is merged on &lt;code&gt;develop&lt;/code&gt; and in no release yet; kf-app {0} sends it only when it first enrols, so a licence installed there afterwards, a renewal included, does not reach the gateway. That is what &lt;em&gt;Served otherwise&lt;/em&gt; most often means: the installation holds an earlier file, and is served what that file says.</value>
  </data>
  <data name="Gateway.Usage.WithoutId.One" xml:space="preserve">
    <value>1 licensed installation has no licence id recorded: licensed before the gateway recorded ids (kf-ai-gateway#35), it has one once kf-app sends its licence again, and until then the licence it runs can read as not enrolled here.</value>
  </data>
  <data name="Gateway.Usage.WithoutId.Many" xml:space="preserve">
    <value>{0} licensed installations have no licence id recorded: licensed before the gateway recorded ids (kf-ai-gateway#35), each has one once kf-app sends its licence again, and until then the licence it runs can read as not enrolled here.</value>
  </data>
  <data name="Gateway.Usage.OtherIds.One" xml:space="preserve">
    <value>1 licensed installation holds a licence id the register has no licence in force for: one not in the register, or one expired in it that the gateway has not noticed, because the installation has not called since.</value>
  </data>
  <data name="Gateway.Usage.OtherIds.Many" xml:space="preserve">
    <value>{0} licensed installations hold a licence id the register has no licence in force for: one not in the register, or one expired in it that the gateway has not noticed, because the installation has not called since.</value>
  </data>
  <data name="Gateway.Usage.ListHasThemAll" xml:space="preserve">
    <value>{0} has them all.</value>
  </data>
  <data name="Gateway.Usage.TheInstallationsList" xml:space="preserve">
    <value>The installations list</value>
  </data>
  <data name="Gateway.Usage.Differs" xml:space="preserve">
    <value>Served {0}, where the register's file {1}.</value>
  </data>
  <data name="Gateway.Usage.Differs.Row" xml:space="preserve">
    <value>Served the {0} row, where the licence's tier chooses {1}.</value>
  </data>
  <data name="Gateway.Usage.Differs.Expiry" xml:space="preserve">
    <value>Holds a file expiring {0}, where the register's file in force expires {1}.</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.Tokens" xml:space="preserve">
    <value>{0} tokens a period from its licence</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.RowBudget" xml:space="preserve">
    <value>its row's token budget</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.Period" xml:space="preserve">
    <value>{0} from its licence</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.RowPeriod" xml:space="preserve">
    <value>its row's budget period</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.Rpm" xml:space="preserve">
    <value>{0} requests a minute from its licence</value>
  </data>
  <data name="Gateway.Usage.Differs.Served.RowRpm" xml:space="preserve">
    <value>its row's requests a minute</value>
  </data>
  <data name="Gateway.Usage.Differs.Sets" xml:space="preserve">
    <value>sets {0}</value>
  </data>
  <data name="Gateway.Usage.Differs.LeavesBudget" xml:space="preserve">
    <value>leaves the budget to its row</value>
  </data>
  <data name="Gateway.Usage.Differs.LeavesPeriod" xml:space="preserve">
    <value>leaves the period to its row</value>
  </data>
  <data name="Gateway.Usage.Differs.LeavesRpm" xml:space="preserve">
    <value>leaves them to its row</value>
  </data>
  <data name="Gateway.Usage.Period.Months" xml:space="preserve">
    <value>calendar months</value>
  </data>
  <data name="Gateway.Usage.Period.Rolling" xml:space="preserve">
    <value>rolling 30 days</value>
  </data>
  <data name="Gateway.Usage.Period.Other" xml:space="preserve">
    <value>period "{0}"</value>
  </data>
  <data name="Gateway.Usage.NoLedger.Title" xml:space="preserve">
    <value>The gateway does not keep usage history yet</value>
  </data>
  <data name="Gateway.Usage.NoLedger.Detail" xml:space="preserve">
    <value>It answers 404 for &lt;code&gt;/admin/usage&lt;/code&gt; while its installations answer: it predates kf-ai-gateway#41, which keeps the daily usage ledger. What each installation has used this period is still on its page.</value>
  </data>
  <data name="Gateway.Usage.Unit.tokens" xml:space="preserve">
    <value>tokens</value>
  </data>
  <data name="Gateway.Usage.Unit.requests" xml:space="preserve">
    <value>requests</value>
  </data>
  <data name="Gateway.Usage.Series.Answered" xml:space="preserve">
    <value>Answered</value>
  </data>
  <data name="Gateway.Usage.Series.Upstream" xml:space="preserve">
    <value>Upstream errors</value>
  </data>
  <data name="Gateway.Usage.Series.RateLimited" xml:space="preserve">
    <value>Refused, rate limited</value>
  </data>
  <data name="Gateway.Usage.Series.BudgetSpent" xml:space="preserve">
    <value>Refused, budget spent</value>
  </data>
  <data name="Gateway.History.Lead" xml:space="preserve">
    <value>What the fleet spent over a range of days, from the gateway's{0} daily usage ledger: its totals, the same by the row each installation is served now, a chart of its days, and the installations that spent the most. UTC days, both ends included, today so far. Read with the read-only token.</value>
  </data>
  <data name="Gateway.History.From" xml:space="preserve">
    <value>From</value>
  </data>
  <data name="Gateway.History.To" xml:space="preserve">
    <value>To, included</value>
  </data>
  <data name="Gateway.History.TopInstallations" xml:space="preserve">
    <value>Top installations</value>
  </data>
  <data name="Gateway.History.Show" xml:space="preserve">
    <value>Show</value>
  </data>
  <data name="Gateway.History.Preset.Last7" xml:space="preserve">
    <value>Last 7 days</value>
  </data>
  <data name="Gateway.History.Preset.Last30" xml:space="preserve">
    <value>Last 30 days</value>
  </data>
  <data name="Gateway.History.Preset.ThisMonth" xml:space="preserve">
    <value>This month</value>
  </data>
  <data name="Gateway.History.Preset.LastMonth" xml:space="preserve">
    <value>Last month</value>
  </data>
  <data name="Gateway.History.Preset.Last90" xml:space="preserve">
    <value>Last 90 days</value>
  </data>
  <data name="Gateway.History.Preset.Last365" xml:space="preserve">
    <value>Last 365 days</value>
  </data>
  <data name="Gateway.History.NotARange" xml:space="preserve">
    <value>That is not a range the gateway answers</value>
  </data>
  <data name="Gateway.History.Problem.NotADate" xml:space="preserve">
    <value>"{0}" is not a date: give one as {1}.</value>
  </data>
  <data name="Gateway.History.Problem.Backwards" xml:space="preserve">
    <value>The last day is before the first.</value>
  </data>
  <data name="Gateway.History.Problem.TooLong" xml:space="preserve">
    <value>That is {0} days. The gateway answers at most {1} at a time, a leap year whole: ask for a longer one in parts.</value>
  </data>
  <data name="Gateway.History.Tokens" xml:space="preserve">
    <value>Tokens</value>
  </data>
  <data name="Gateway.History.Tokens.Note" xml:space="preserve">
    <value>What the provider said the chats cost</value>
  </data>
  <data name="Gateway.History.Requests" xml:space="preserve">
    <value>Requests</value>
  </data>
  <data name="Gateway.History.Requests.Note" xml:space="preserve">
    <value>Every request, admitted or refused</value>
  </data>
  <data name="Gateway.History.Refused" xml:space="preserve">
    <value>Refused</value>
  </data>
  <data name="Gateway.History.Refused.Title" xml:space="preserve">
    <value>Refused rate limited, and for a spent budget</value>
  </data>
  <data name="Gateway.History.RefusedDetail" xml:space="preserve">
    <value>{0} rate limited, {1} for a spent budget</value>
  </data>
  <data name="Gateway.History.UpstreamErrors" xml:space="preserve">
    <value>Upstream errors</value>
  </data>
  <data name="Gateway.History.UpstreamErrors.Note" xml:space="preserve">
    <value>Chats the provider failed</value>
  </data>
  <data name="Gateway.History.Installations.Note" xml:space="preserve">
    <value>That made any request in the range</value>
  </data>
  <data name="Gateway.History.Chart.Lead" xml:space="preserve">
    <value>{0} to {1}, {2}, by the row each installation is served now.</value>
  </data>
  <data name="Gateway.History.DaysCsv" xml:space="preserve">
    <value>Days (CSV)</value>
  </data>
  <data name="Gateway.History.ByRow" xml:space="preserve">
    <value>By row</value>
  </data>
  <data name="Gateway.History.ByRow.Lead" xml:space="preserve">
    <value>The row each installation is served now, for the whole range: one that bought a licence during it counts under its licence's row from the first day.</value>
  </data>
  <data name="Gateway.History.Share" xml:space="preserve">
    <value>Share</value>
  </data>
  <data name="Gateway.History.Unrowed" xml:space="preserve">
    <value>No longer on the gateway</value>
  </data>
  <data name="Gateway.History.Unrowed.Lower" xml:space="preserve">
    <value>no longer on the gateway</value>
  </data>
  <data name="Gateway.History.Unrowed.Title" xml:space="preserve">
    <value>Deleted from the gateway by hand: they spent what they spent, and are served no row</value>
  </data>
  <data name="Gateway.History.All" xml:space="preserve">
    <value>All</value>
  </data>
  <data name="Gateway.History.Top.Lead" xml:space="preserve">
    <value>The {0} that spent the most tokens in the range, each with the register's licence where it holds one.</value>
  </data>
  <data name="Gateway.History.Top.Everyone" xml:space="preserve">
    <value>That is every installation that made a request in it.</value>
  </data>
  <data name="Gateway.History.Top.Some" xml:space="preserve">
    <value>{0} made a request in it.</value>
  </data>
  <data name="Gateway.History.TopCsv" xml:space="preserve">
    <value>Top installations (CSV)</value>
  </data>
  <data name="Gateway.History.Top.Empty" xml:space="preserve">
    <value>No installation made a request in this range.</value>
  </data>
  <data name="Gateway.History.NotInRegister.Lower" xml:space="preserve">
    <value>not in the register</value>
  </data>
  <data name="Gateway.History.Footnote" xml:space="preserve">
    <value>Tokens count as each chat ends; requests, refusals and upstream errors reach the ledger once a minute, so the last minute is not here yet. Days before the gateway kept the ledger (kf-ai-gateway#41) are zero. Each export is recorded in the audit log.</value>
  </data>
  <data name="Gateway.Policy.NoWriteToken" xml:space="preserve">
    <value>The console has no write token: Gateway--AdminWriteToken is not in Key Vault.</value>
  </data>
  <data name="Gateway.Policy.ViewOnly" xml:space="preserve">
    <value>You can view the policy, not change it: that needs {0}.</value>
  </data>
  <data name="Gateway.Policy.Count.NotReported" xml:space="preserve">
    <value>not reported by this gateway</value>
  </data>
  <data name="Gateway.Policy.Count.NoAnswer" xml:space="preserve">
    <value>not available: the gateway did not answer</value>
  </data>
  <data name="Gateway.Policy.ActiveInstallations.One" xml:space="preserve">
    <value>1 active installation</value>
  </data>
  <data name="Gateway.Policy.ActiveInstallations.Many" xml:space="preserve">
    <value>{0} active installations</value>
  </data>
  <data name="Gateway.Policy.Lead" xml:space="preserve">
    <value>What the gateway{0} is allowing now: its three allowance rows and its gateway-wide levers, as its database holds them, read afresh on every load at {1} UTC with the read-only token. Policy lives in the gateway's database so it can change without a deploy, and a change is felt on the gateway's next request.</value>
  </data>
  <data name="Gateway.Policy.Lead.Change" xml:space="preserve">
    <value>Each row and lever has its own &lt;strong&gt;Change&lt;/strong&gt;: a form checked as the gateway checks it, then the change shown whole, with whom it reaches, before it is made with the write token. Every change is in {0}, with its reason and the row before and after.</value>
  </data>
  <data name="Gateway.Policy.TheAuditLog" xml:space="preserve">
    <value>the audit log</value>
  </data>
  <data name="Gateway.Policy.Changed.Minimum" xml:space="preserve">
    <value>The minimum application version</value>
  </data>
  <data name="Gateway.Policy.Changed.Velocity" xml:space="preserve">
    <value>The enrolment velocity limit</value>
  </data>
  <data name="Gateway.Policy.Changed.Ceiling" xml:space="preserve">
    <value>The global token ceiling</value>
  </data>
  <data name="Gateway.Policy.Changed.Tier" xml:space="preserve">
    <value>The {0} allowance</value>
  </data>
  <data name="Gateway.Policy.Changed" xml:space="preserve">
    <value>{0} was changed on the gateway, and is felt on its next request.</value>
  </data>
  <data name="Gateway.Policy.Changed.AuditLink" xml:space="preserve">
    <value>The audit log</value>
  </data>
  <data name="Gateway.Policy.Changed.HasEntry" xml:space="preserve">
    <value>has the entry.</value>
  </data>
  <data name="Gateway.Policy.NotReported.Title" xml:space="preserve">
    <value>The gateway does not report policy yet</value>
  </data>
  <data name="Gateway.Policy.NotReported.Detail" xml:space="preserve">
    <value>It lists its installations but answers 404 for &lt;code&gt;/admin/tiers&lt;/code&gt;: it predates kf-ai-gateway#39, which reads and writes the policy rows. Until it is deployed, the rows are read with &lt;code&gt;psql&lt;/code&gt;, as its &lt;code&gt;docs/Admin.md&lt;/code&gt; says.</value>
  </data>
  <data name="Gateway.Policy.Tiers" xml:space="preserve">
    <value>Tier allowances</value>
  </data>
  <data name="Gateway.Policy.Tiers.Lead" xml:space="preserve">
    <value>What an installation is served on each row, unless its licence sets the number itself. Installations served are the gateway's count of active ones; licences in force are the register's.</value>
  </data>
  <data name="Gateway.Policy.TokenBudget" xml:space="preserve">
    <value>Token budget</value>
  </data>
  <data name="Gateway.Policy.InstallationsServed" xml:space="preserve">
    <value>Installations served</value>
  </data>
  <data name="Gateway.Policy.LicencesInForce" xml:space="preserve">
    <value>Licences in force</value>
  </data>
  <data name="Gateway.Policy.NoLicenceRow" xml:space="preserve">
    <value>No licence is served this row: it is the unlicensed installations'</value>
  </data>
  <data name="Gateway.Policy.RegisterNotRead" xml:space="preserve">
    <value>The register was not read</value>
  </data>
  <data name="Gateway.Policy.Change" xml:space="preserve">
    <value>Change</value>
  </data>
  <data name="Gateway.Policy.Requests.Help" xml:space="preserve">
    <value>Requests an installation may make in the window, a minute on every row today. Lowering it refuses an installation already past the new number on its very next request; raising it releases one waiting at the old one. The window is held in the gateway's memory, so a restart starts every installation's afresh.</value>
  </data>
  <data name="Gateway.Policy.TokenBudget.Help" xml:space="preserve">
    <value>Tokens an installation may spend in a period, prompt and reply together: a calendar month in UTC, or thirty days rolling from where its period started. The spend is in the gateway's database, so a restart does not touch it.</value>
  </data>
  <data name="Gateway.Policy.LongestReply.Help" xml:space="preserve">
    <value>The most tokens the gateway lets the model write in one reply: an installation asking for more is held to it. A licence never sets it.</value>
  </data>
  <data name="Gateway.Policy.Whose" xml:space="preserve">
    <value>Whose number it is</value>
  </data>
  <data name="Gateway.Policy.Whose.Help" xml:space="preserve">
    <value>&lt;code&gt;evaluation&lt;/code&gt; serves every installation without a licence. &lt;code&gt;standard&lt;/code&gt; and &lt;code&gt;enterprise&lt;/code&gt; serve licensed installations, by the licence's tier: exactly &lt;code&gt;enterprise&lt;/code&gt; takes the enterprise row, and any other tier, or none, the standard row. A licence that sets &lt;code&gt;ai.tokens&lt;/code&gt;, &lt;code&gt;ai.period&lt;/code&gt; or &lt;code&gt;ai.rpm&lt;/code&gt; keeps its own numbers, and its row supplies only what the licence leaves out.</value>
  </data>
  <data name="Gateway.Policy.OnlyUp.Title" xml:space="preserve">
    <value>A licence tier's allowance only goes up</value>
  </data>
  <data name="Gateway.Policy.OnlyUp.Detail" xml:space="preserve">
    <value>&lt;code&gt;standard&lt;/code&gt; and &lt;code&gt;enterprise&lt;/code&gt; started equal, as copies of the gateway's single former licence row (kf-ai-gateway#32), so that nothing any installation was served changed; &lt;code&gt;enterprise&lt;/code&gt; is raised once its numbers are decided. While any licence on a tier is in force, that tier's allowance is raised and never lowered (&lt;code&gt;License-Entitlements.md&lt;/code&gt;, &lt;em&gt;The AI allowance per tier&lt;/em&gt;): lowering it would shrink what a customer bought under a licence that still says the same thing. The register's count of licences in force is what the rule protects, and &lt;strong&gt;Change&lt;/strong&gt; refuses a lowering while one is in force. The gateway does not check it: it sees only the licences that enrolled.</value>
  </data>
  <data name="Gateway.Policy.NoTier.One" xml:space="preserve">
    <value>1 licensed installation has no licence tier recorded: licensed before the gateway read tiers, it is served &lt;code&gt;standard&lt;/code&gt; whatever its licence says, and a raise to &lt;code&gt;enterprise&lt;/code&gt; does not reach an Enterprise customer among them until kf-app sends their licence again.</value>
  </data>
  <data name="Gateway.Policy.NoTier.Many" xml:space="preserve">
    <value>{0} licensed installations have no licence tier recorded: licensed before the gateway read tiers, they are served &lt;code&gt;standard&lt;/code&gt; whatever their licence says, and a raise to &lt;code&gt;enterprise&lt;/code&gt; does not reach an Enterprise customer among them until kf-app sends their licence again.</value>
  </data>
  <data name="Gateway.Policy.Levers" xml:space="preserve">
    <value>Gateway levers</value>
  </data>
  <data name="Gateway.Policy.Levers.Lead" xml:space="preserve">
    <value>One row of gateway-wide settings, each reaching every installation at once.</value>
  </data>
  <data name="Gateway.Policy.Minimum" xml:space="preserve">
    <value>Minimum application version</value>
  </data>
  <data name="Gateway.Policy.Minimum.Seeded" xml:space="preserve">
    <value>as seeded: every version may enrol</value>
  </data>
  <data name="Gateway.Policy.Minimum.Help" xml:space="preserve">
    <value>The oldest kf-app version that may enrol. An installation below it is refused &lt;code&gt;426 app_version_unsupported&lt;/code&gt; the next time it enrols; one already enrolled keeps working until then. It retires an application generation, so ask what it would cost first: the counts below are the gateway's own, read as the lever reads versions, and a prerelease counts as its release.</value>
  </data>
  <data name="Gateway.Policy.Minimum.NotAVersion" xml:space="preserve">
    <value>It does not read as a version, so it admits everyone: a value like this can only have been written with &lt;code&gt;psql&lt;/code&gt;, which checks nothing. The gateway's &lt;code&gt;PUT&lt;/code&gt; refuses one.</value>
  </data>
  <data name="Gateway.Policy.Minimum.Below" xml:space="preserve">
    <value>Below {0}, the minimum:</value>
  </data>
  <data name="Gateway.Policy.Minimum.Below.Refused" xml:space="preserve">
    <value>{0}, refused when next they enrol.</value>
  </data>
  <data name="Gateway.Policy.Minimum.BelowRelease" xml:space="preserve">
    <value>Below {0}, kf-app's current release:</value>
  </data>
  <data name="Gateway.Policy.Minimum.BelowRelease.WouldRefuse" xml:space="preserve">
    <value>{0}, what raising the minimum to it would refuse.</value>
  </data>
  <data name="Gateway.Policy.Minimum.AnyOther" xml:space="preserve">
    <value>Any other version: {0}'s &lt;em&gt;App version below&lt;/em&gt; asks the gateway the same question.</value>
  </data>
  <data name="Gateway.Policy.Velocity" xml:space="preserve">
    <value>Enrolment velocity limit</value>
  </data>
  <data name="Gateway.Policy.Velocity.Armed" xml:space="preserve">
    <value>Armed</value>
  </data>
  <data name="Gateway.Policy.Off" xml:space="preserve">
    <value>Off</value>
  </data>
  <data name="Gateway.Policy.Velocity.Limits" xml:space="preserve">
    <value>{0}, {1}, from one address.</value>
  </data>
  <data name="Gateway.Policy.Velocity.Limits.Short" xml:space="preserve">
    <value>{0}, {1}</value>
  </data>
  <data name="Gateway.Policy.Velocity.AnHour" xml:space="preserve">
    <value>{0} an hour</value>
  </data>
  <data name="Gateway.Policy.Velocity.ADay" xml:space="preserve">
    <value>{0} a day</value>
  </data>
  <data name="Gateway.Policy.Velocity.NoHourly" xml:space="preserve">
    <value>no hourly limit</value>
  </data>
  <data name="Gateway.Policy.Velocity.NoDaily" xml:space="preserve">
    <value>no daily limit</value>
  </data>
  <data name="Gateway.Policy.Velocity.OffDetail" xml:space="preserve">
    <value>No enrolment is counted and no address is recorded, as seeded.</value>
  </data>
  <data name="Gateway.Policy.Velocity.Help" xml:space="preserve">
    <value>How many enrolments one address may make in an hour and in a day before the next is refused &lt;code&gt;429 enrolment_rate_limited&lt;/code&gt;. Enrolment is the one endpoint that needs no credential, so this is the lever for the day someone abuses it; it is off by decision, because wanting to install the product too many times is a better problem than refusing a legitimate rollout. Armed, counting starts from empty.</value>
  </data>
  <data name="Gateway.Policy.Velocity.CheckAddress.Title" xml:space="preserve">
    <value>Check the address before arming it</value>
  </data>
  <data name="Gateway.Policy.Velocity.CheckAddress.Detail" xml:space="preserve">
    <value>Behind App Service the gateway reads the address the platform's front end appends to &lt;code&gt;X-Forwarded-For&lt;/code&gt;, and that has never been checked against a real response. Armed against the wrong address, the limit counts every installation against one address and refuses everybody.</value>
  </data>
  <data name="Gateway.Policy.Velocity.CallerSeen" xml:space="preserve">
    <value>The gateway saw this console's own request, at {0} UTC, as coming from {1}. That should be one of &lt;code&gt;app-kf-admin&lt;/code&gt;'s outbound IP addresses (App Service, &lt;em&gt;Properties&lt;/em&gt;). If it is the platform's front end, a private address or &lt;code&gt;unknown&lt;/code&gt;, do not arm the limit.</value>
  </data>
  <data name="Gateway.Policy.Velocity.CallerUnknown" xml:space="preserve">
    <value>The address the gateway saw this console call from is not available: it comes from the gateway's status, which did not answer. Check it before arming the limit.</value>
  </data>
  <data name="Gateway.Policy.Ceiling" xml:space="preserve">
    <value>Global token ceiling</value>
  </data>
  <data name="Gateway.Policy.Ceiling.Unit" xml:space="preserve">
    <value>tokens a calendar month, the whole service</value>
  </data>
  <data name="Gateway.Policy.NoBrake" xml:space="preserve">
    <value>No brake</value>
  </data>
  <data name="Gateway.Policy.NoBrake.Detail" xml:space="preserve">
    <value>Only the provider's own cap stands behind the gateway.</value>
  </data>
  <data name="Gateway.Policy.BrakeOn" xml:space="preserve">
    <value>&lt;strong&gt;The brake is on.&lt;/strong&gt; Every chat is refused &lt;code&gt;503 service_paused&lt;/code&gt; until the ceiling is raised or the month ends.</value>
  </data>
  <data name="Gateway.Policy.SpentThisMonth" xml:space="preserve">
    <value>Spent this month: {0}</value>
  </data>
  <data name="Gateway.Policy.SpentPercent" xml:space="preserve">
    <value>, {0}% of the ceiling</value>
  </data>
  <data name="Gateway.Policy.SpentUntil" xml:space="preserve">
    <value>, until {0} UTC</value>
  </data>
  <data name="Gateway.Policy.OverviewHasBrake" xml:space="preserve">
    <value>{0} has the brake in full.</value>
  </data>
  <data name="Gateway.Policy.TheOverview" xml:space="preserve">
    <value>The overview</value>
  </data>
  <data name="Gateway.Policy.BrakeUnknown" xml:space="preserve">
    <value>The brake's state is not available: the gateway's status did not answer.</value>
  </data>
  <data name="Gateway.Policy.Ceiling.Help" xml:space="preserve">
    <value>The tokens the whole service may spend in a calendar month before every chat, for everybody, is refused &lt;code&gt;503 service_paused&lt;/code&gt;: a runaway detector, not a second rate limit, seeded generously at 50,000,000. Raising it is the whole of releasing the brake, and a restart does not release it. No ceiling is no brake, not a brake at zero.</value>
  </data>
  <data name="Gateway.Change.Policy.Lead" xml:space="preserve">
    <value>A change to the gateway{0} with the console's write token, {1}, felt on the gateway's next request. It is recorded in the audit log, with your reason, once the gateway confirms it, and the gateway records it in its own log under the same name.</value>
  </data>
  <data name="Gateway.Change.Stale.Title" xml:space="preserve">
    <value>The gateway's row changed since you reviewed this</value>
  </data>
  <data name="Gateway.Change.Stale.Detail" xml:space="preserve">
    <value>Nothing was written. The change is shown again against the row as it stands now: review it, and confirm if it is still what you mean.</value>
  </data>
  <data name="Gateway.Change.NoPolicyWrites.Title" xml:space="preserve">
    <value>The gateway does not take policy changes</value>
  </data>
  <data name="Gateway.Change.NoPolicyWrites.Detail" xml:space="preserve">
    <value>It answered 404 to the change: it predates kf-ai-gateway#39. Nothing was changed.</value>
  </data>
  <data name="Gateway.Change.Policy.RequestRefused.Detail" xml:space="preserve">
    <value>It answered 400, a fault in the console rather than an outage; the row is as it was.</value>
  </data>
  <data name="Gateway.Change.Policy.Unsure.Detail" xml:space="preserve">
    <value>Open {0} to see the row as it stands before trying again. No audit entry was written.</value>
  </data>
  <data name="Gateway.Change.ThePolicyPage" xml:space="preserve">
    <value>the policy page</value>
  </data>
  <data name="Gateway.Change.RowProblems.Title" xml:space="preserve">
    <value>The gateway's row holds a value it will not take back</value>
  </data>
  <data name="Gateway.Change.RowProblems.Detail" xml:space="preserve">
    <value>A change writes the whole row, and the row holds {0}: written without the console, with &lt;code&gt;psql&lt;/code&gt;, which checks nothing. The gateway refuses a row that carries it, so change that first.</value>
  </data>
  <data name="Gateway.Change.RowProblems.And" xml:space="preserve">
    <value>, and </value>
  </data>
  <data name="Gateway.Change.RowProblems.Minimum" xml:space="preserve">
    <value>Minimum version</value>
  </data>
  <data name="Gateway.Change.RowProblems.Velocity" xml:space="preserve">
    <value>Enrolment velocity</value>
  </data>
  <data name="Gateway.Change.RowProblems.Ceiling" xml:space="preserve">
    <value>Global ceiling</value>
  </data>
  <data name="Gateway.Change.RowProblem.Version" xml:space="preserve">
    <value>a minimum version, "{0}", that does not read as a version</value>
  </data>
  <data name="Gateway.Change.RowProblem.Hourly" xml:space="preserve">
    <value>an hourly enrolment limit of {0}, which refuses every enrolment</value>
  </data>
  <data name="Gateway.Change.RowProblem.Daily" xml:space="preserve">
    <value>a daily enrolment limit of {0}, which refuses every enrolment</value>
  </data>
  <data name="Gateway.Change.RowProblem.HourlyAboveDaily" xml:space="preserve">
    <value>an hourly enrolment limit above the daily one</value>
  </data>
  <data name="Gateway.Change.RowProblem.Ceiling" xml:space="preserve">
    <value>a global token ceiling of {0}, which pauses the service for everyone</value>
  </data>
  <data name="Gateway.Change.Reason.Placeholder" xml:space="preserve">
    <value>Why, for whoever reads the audit log next</value>
  </data>
  <data name="Gateway.Change.TheChange" xml:space="preserve">
    <value>The change</value>
  </data>
  <data name="Gateway.Change.Now" xml:space="preserve">
    <value>Now</value>
  </data>
  <data name="Gateway.Change.After" xml:space="preserve">
    <value>After</value>
  </data>
  <data name="Gateway.Change.NowValue" xml:space="preserve">
    <value>Now {0}</value>
  </data>
  <data name="Gateway.Change.Unchanged" xml:space="preserve">
    <value>unchanged</value>
  </data>
  <data name="Gateway.Change.Review" xml:space="preserve">
    <value>Review the change</value>
  </data>
  <data name="Gateway.Change.WhatItDoes" xml:space="preserve">
    <value>What it does</value>
  </data>
  <data name="Gateway.Tier.Title" xml:space="preserve">
    <value>Change the {0} allowance</value>
  </data>
  <data name="Gateway.Tier.Title.Html" xml:space="preserve">
    <value>Change the {0} allowance</value>
  </data>
  <data name="Gateway.Tier.NoRow" xml:space="preserve">
    <value>The gateway does not list a {0} row.</value>
  </data>
  <data name="Gateway.Tier.InForce.One" xml:space="preserve">
    <value>1 licence in force</value>
  </data>
  <data name="Gateway.Tier.InForce.Many" xml:space="preserve">
    <value>{0} licences in force</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Title" xml:space="preserve">
    <value>The {0} allowance only goes up while a licence on it is in force</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Holds" xml:space="preserve">
    <value>The register holds {0} on this row, and this change would give them less:</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Unread" xml:space="preserve">
    <value>The register could not be read, so the console cannot tell whether a licence on this row is in force, and until it can the row is only raised. This change would give less:</value>
  </data>
  <data name="Gateway.Tier.OnlyUp.Why" xml:space="preserve">
    <value>Lowering it would shrink what those customers bought under licences that still say the same thing. A plan that needs less is a new tier, or numbers written into the licences issued on it (&lt;code&gt;License-Entitlements.md&lt;/code&gt;, &lt;em&gt;The AI allowance per tier&lt;/em&gt;).</value>
  </data>
  <data name="Gateway.Tier.TheRow" xml:space="preserve">
    <value>The row</value>
  </data>
  <data name="Gateway.Tier.Window" xml:space="preserve">
    <value>Per window of, in seconds</value>
  </data>
  <data name="Gateway.Tier.Window.Now" xml:space="preserve">
    <value>Now {0}, a minute on every row as seeded</value>
  </data>
  <data name="Gateway.Tier.PerPeriod" xml:space="preserve">
    <value>Per period</value>
  </data>
  <data name="Gateway.Tier.LongestReplyTokens" xml:space="preserve">
    <value>Longest reply, in tokens</value>
  </data>
  <data name="Gateway.Tier.WhomItReaches" xml:space="preserve">
    <value>Whom it reaches</value>
  </data>
  <data name="Gateway.Tier.Reaches.Detail" xml:space="preserve">
    <value>Installations served are the gateway's count of active ones on the row: a change reaches every one of them on its next request. Lowering the requests refuses an installation already past the new number at once; raising them releases one waiting at the old number. A licence that sets &lt;code&gt;ai.tokens&lt;/code&gt;, &lt;code&gt;ai.period&lt;/code&gt; or &lt;code&gt;ai.rpm&lt;/code&gt; keeps its own numbers, and the row supplies only what the licence leaves out.</value>
  </data>
  <data name="Gateway.Tier.Evaluation" xml:space="preserve">
    <value>&lt;code&gt;evaluation&lt;/code&gt; serves every installation without a licence. No licence is served it, so it goes down as well as up.</value>
  </data>
  <data name="Gateway.Tier.RuleHolds" xml:space="preserve">
    <value>&lt;strong&gt;Only goes up.&lt;/strong&gt; While a licence on this row is in force, it is raised and never lowered: fewer requests a minute, a smaller budget, another period or a shorter reply is refused here. Raising reaches every such licence at once. The gateway does not check this; the console does, from the register.</value>
  </data>
  <data name="Gateway.Tier.RuleFree" xml:space="preserve">
    <value>No licence on this row is in force, so the only-goes-up rule does not hold it, and it goes down as well as up. A licence issued on it later is held to the numbers it has then.</value>
  </data>
  <data name="Gateway.Tier.NoChange" xml:space="preserve">
    <value>These are the numbers the row holds already: nothing would change.</value>
  </data>
  <data name="Gateway.Tier.Field.Requests" xml:space="preserve">
    <value>Requests</value>
  </data>
  <data name="Gateway.Tier.Field.Window" xml:space="preserve">
    <value>The window</value>
  </data>
  <data name="Gateway.Tier.Field.Budget" xml:space="preserve">
    <value>The token budget</value>
  </data>
  <data name="Gateway.Tier.Field.LongestReply" xml:space="preserve">
    <value>The longest reply</value>
  </data>
  <data name="Gateway.Tier.Problem.MustBe" xml:space="preserve">
    <value>{0} must be {1}.</value>
  </data>
  <data name="Gateway.Tier.Problem.Period" xml:space="preserve">
    <value>The period must be a calendar month or thirty days rolling: the gateway knows no other.</value>
  </data>
  <data name="Gateway.Tier.Lowering.Requests" xml:space="preserve">
    <value>fewer requests: {0} would become {1}</value>
  </data>
  <data name="Gateway.Tier.Lowering.Budget" xml:space="preserve">
    <value>a smaller token budget: {0} would become {1}</value>
  </data>
  <data name="Gateway.Tier.Lowering.Period" xml:space="preserve">
    <value>another period: {0} would become {1}, and neither is longer than the other in every month</value>
  </data>
  <data name="Gateway.Tier.Lowering.LongestReply" xml:space="preserve">
    <value>a shorter longest reply: {0} tokens would become {1}</value>
  </data>
  <data name="Gateway.Velocity.Title" xml:space="preserve">
    <value>Change the enrolment velocity limit</value>
  </data>
  <data name="Gateway.Velocity.TheLimit" xml:space="preserve">
    <value>The limit</value>
  </data>
  <data name="Gateway.Velocity.Review.Off" xml:space="preserve">
    <value>Off: no enrolment is counted and no address is recorded, as seeded.</value>
  </data>
  <data name="Gateway.Velocity.Review.PastIt" xml:space="preserve">
    <value>Past it, enrolment from that address is refused &lt;code&gt;429 enrolment_rate_limited&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Velocity.Review.StartsEmpty" xml:space="preserve">
    <value>Counting starts from empty: the window fills over the following hour rather than reaching back over enrolments nobody recorded.</value>
  </data>
  <data name="Gateway.Velocity.Review.Ticked" xml:space="preserve">
    <value>You ticked that you checked the address the gateway sees callers at: {0}. Armed against the wrong address, the limit refuses everybody.</value>
  </data>
  <data name="Gateway.Velocity.NotAvailableHere" xml:space="preserve">
    <value>not available here</value>
  </data>
  <data name="Gateway.Velocity.Arm" xml:space="preserve">
    <value>Arm the limit</value>
  </data>
  <data name="Gateway.Velocity.TurnOff" xml:space="preserve">
    <value>Turn the limit off</value>
  </data>
  <data name="Gateway.Velocity.ChangeLimit" xml:space="preserve">
    <value>Change the limit</value>
  </data>
  <data name="Gateway.Velocity.OffOption" xml:space="preserve">
    <value>Off: nothing counted, no address recorded</value>
  </data>
  <data name="Gateway.Velocity.ArmedOption" xml:space="preserve">
    <value>Armed, from one address:</value>
  </data>
  <data name="Gateway.Velocity.PerHour" xml:space="preserve">
    <value>Enrolments an hour</value>
  </data>
  <data name="Gateway.Velocity.PerHour.Now" xml:space="preserve">
    <value>Now {0}. Blank for no hourly limit.</value>
  </data>
  <data name="Gateway.Velocity.PerDay" xml:space="preserve">
    <value>Enrolments a day</value>
  </data>
  <data name="Gateway.Velocity.PerDay.Now" xml:space="preserve">
    <value>Now {0}. Blank for no daily limit.</value>
  </data>
  <data name="Gateway.Velocity.None" xml:space="preserve">
    <value>none</value>
  </data>
  <data name="Gateway.Velocity.CheckAddress.Counts" xml:space="preserve">
    <value>Behind App Service the gateway counts the address the platform's front end appends to &lt;code&gt;X-Forwarded-For&lt;/code&gt;, and that has never been checked against a real response. Armed against the wrong address, the limit counts every installation against one address and refuses everybody.</value>
  </data>
  <data name="Gateway.Velocity.CallerUnknownHere" xml:space="preserve">
    <value>The address the gateway sees is not available here: it comes from the gateway's status, which did not answer. Check it as kf-ai-gateway &lt;code&gt;docs/Admin.md&lt;/code&gt; says before arming the limit.</value>
  </data>
  <data name="Gateway.Velocity.AddressChecked" xml:space="preserve">
    <value>I have checked the address the gateway sees callers at</value>
  </data>
  <data name="Gateway.Velocity.NoChange" xml:space="preserve">
    <value>These are the limits the gateway holds already: nothing would change.</value>
  </data>
  <data name="Gateway.Velocity.NoChange.Off" xml:space="preserve">
    <value>The limit is off already: nothing would change.</value>
  </data>
  <data name="Gateway.Velocity.Problem.Hourly" xml:space="preserve">
    <value>An hourly limit is {0}, or blank for none.</value>
  </data>
  <data name="Gateway.Velocity.Problem.Daily" xml:space="preserve">
    <value>A daily limit is {0}, or blank for none.</value>
  </data>
  <data name="Gateway.Velocity.Problem.None" xml:space="preserve">
    <value>Arming takes an hourly limit, a daily one, or both. To turn the limit off, choose Off.</value>
  </data>
  <data name="Gateway.Velocity.Problem.HourlyAboveDaily" xml:space="preserve">
    <value>The hourly limit must not be higher than the daily one, which would always refuse first.</value>
  </data>
  <data name="Gateway.Velocity.Problem.Unchecked" xml:space="preserve">
    <value>Tick this once you have checked the address: armed against the wrong one, the limit refuses everybody.</value>
  </data>
  <data name="Gateway.Velocity.WhatItDoes.1" xml:space="preserve">
    <value>How many enrolments one address may make in an hour and in a day before the next is refused. Enrolment is the one endpoint that needs no credential, so this is the lever for the day someone abuses it.</value>
  </data>
  <data name="Gateway.Velocity.WhatItDoes.2" xml:space="preserve">
    <value>It is off by decision (kf-ai-gateway#4): wanting to install the product too many times is a better problem than refusing a legitimate rollout. The hourly limit is no higher than the daily one, which would always refuse first. Turn it off before repointing the gateway at a restored database, and back on once the fleet has settled.</value>
  </data>
  <data name="Gateway.Ceiling.Title" xml:space="preserve">
    <value>Change the global token ceiling</value>
  </data>
  <data name="Gateway.Ceiling.TheCeiling" xml:space="preserve">
    <value>The ceiling</value>
  </data>
  <data name="Gateway.Ceiling.TokensAMonth" xml:space="preserve">
    <value>{0} tokens a calendar month</value>
  </data>
  <data name="Gateway.Ceiling.Releases" xml:space="preserve">
    <value>&lt;strong&gt;This releases the brake.&lt;/strong&gt; The next chat is admitted: {0} tokens have been spent this month, {1}.</value>
  </data>
  <data name="Gateway.Ceiling.Releases.NoCeiling" xml:space="preserve">
    <value>and there is no ceiling after it</value>
  </data>
  <data name="Gateway.Ceiling.Releases.Below" xml:space="preserve">
    <value>below the new ceiling</value>
  </data>
  <data name="Gateway.Ceiling.StaysOn" xml:space="preserve">
    <value>&lt;strong&gt;The brake stays on.&lt;/strong&gt; {0} tokens have been spent this month, at or above the new ceiling too, so every chat is still refused &lt;code&gt;503 service_paused&lt;/code&gt;. Raise it above what was spent to release it.</value>
  </data>
  <data name="Gateway.Ceiling.Trips" xml:space="preserve">
    <value>&lt;strong&gt;This trips the brake.&lt;/strong&gt; {0} tokens have been spent this month, at or above the new ceiling already, so every chat, for everybody, is refused &lt;code&gt;503 service_paused&lt;/code&gt; from the next, until the ceiling is raised or the month ends.</value>
  </data>
  <data name="Gateway.Ceiling.Headroom" xml:space="preserve">
    <value>{0} tokens have been spent this month, so {1} more may be spent before the brake trips</value>
  </data>
  <data name="Gateway.Ceiling.Headroom.Until" xml:space="preserve">
    <value>, until the month ends at {0} UTC</value>
  </data>
  <data name="Gateway.Ceiling.Off" xml:space="preserve">
    <value>No brake: the gateway spends until the provider's own cap stops it. Nothing trips for a runaway until then.</value>
  </data>
  <data name="Gateway.Ceiling.TurnOff" xml:space="preserve">
    <value>Turn the brake off</value>
  </data>
  <data name="Gateway.Ceiling.ChangeCeiling" xml:space="preserve">
    <value>Change the ceiling</value>
  </data>
  <data name="Gateway.Ceiling.Option.Ceiling" xml:space="preserve">
    <value>A ceiling, in tokens a calendar month, the whole service:</value>
  </data>
  <data name="Gateway.Ceiling.Aria" xml:space="preserve">
    <value>Tokens a calendar month</value>
  </data>
  <data name="Gateway.Ceiling.Option.NoBrake" xml:space="preserve">
    <value>No brake: only the provider's own cap stands behind the gateway</value>
  </data>
  <data name="Gateway.Ceiling.TheBrake" xml:space="preserve">
    <value>The brake</value>
  </data>
  <data name="Gateway.Ceiling.BrakeOn" xml:space="preserve">
    <value>&lt;strong&gt;The brake is on.&lt;/strong&gt; Every chat is refused &lt;code&gt;503 service_paused&lt;/code&gt;.</value>
  </data>
  <data name="Gateway.Ceiling.SpentThisMonth" xml:space="preserve">
    <value>Spent this month</value>
  </data>
  <data name="Gateway.Ceiling.MonthEnds" xml:space="preserve">
    <value>Month ends</value>
  </data>
  <data name="Gateway.Ceiling.About.1" xml:space="preserve">
    <value>&lt;strong&gt;Raising the ceiling is the whole of releasing a tripped brake&lt;/strong&gt;, from the next chat. A restart does not release it, on purpose: a brake that cleared itself on restart would resume spending, and a runaway is what gets a process restarted.</value>
  </data>
  <data name="Gateway.Ceiling.About.2" xml:space="preserve">
    <value>The month's spend is the gateway's record of what was spent, not a lever. It is not the operator's to touch, and the console never offers to: zeroing it would destroy the evidence of whatever tripped the brake. It starts again with the first chat of a new month.</value>
  </data>
  <data name="Gateway.Ceiling.About.3" xml:space="preserve">
    <value>The ceiling is a runaway detector, not a second rate limit, seeded generously at 50,000,000. No ceiling is no brake, not a brake at zero.</value>
  </data>
  <data name="Gateway.Ceiling.NoChange" xml:space="preserve">
    <value>This is the ceiling the gateway holds already: nothing would change.</value>
  </data>
  <data name="Gateway.Ceiling.NoChange.Off" xml:space="preserve">
    <value>There is no brake already: nothing would change.</value>
  </data>
  <data name="Gateway.Ceiling.Problem" xml:space="preserve">
    <value>A ceiling is {0}. Zero is not off: it pauses the service for everyone. To turn the brake off, choose No brake.</value>
  </data>
  <data name="Gateway.Minimum.Title" xml:space="preserve">
    <value>Change the minimum application version</value>
  </data>
  <data name="Gateway.Minimum.ChangeMinimum" xml:space="preserve">
    <value>Change the minimum</value>
  </data>
  <data name="Gateway.Minimum.TheMinimum" xml:space="preserve">
    <value>The minimum</value>
  </data>
  <data name="Gateway.Minimum.NotAnswered.Title" xml:space="preserve">
    <value>The gateway did not say whom this minimum would refuse</value>
  </data>
  <data name="Gateway.Minimum.NotAnswered.Default" xml:space="preserve">
    <value>It did not answer the question.</value>
  </data>
  <data name="Gateway.Minimum.NotAnswered.Detail" xml:space="preserve">
    <value>The change is aimed with the fleet in view, so it is not offered until the gateway answers: try again.</value>
  </data>
  <data name="Gateway.Minimum.Refuses.One" xml:space="preserve">
    <value>At {0}, {1} is refused &lt;code&gt;426 app_version_unsupported&lt;/code&gt; the next time it enrols. An installation already enrolled keeps working until then.</value>
  </data>
  <data name="Gateway.Minimum.Refuses.Many" xml:space="preserve">
    <value>At {0}, {1} are refused &lt;code&gt;426 app_version_unsupported&lt;/code&gt; the next time they enrol. An installation already enrolled keeps working until then.</value>
  </data>
  <data name="Gateway.Minimum.VersionReported" xml:space="preserve">
    <value>Version it last reported</value>
  </data>
  <data name="Gateway.Minimum.NoneReported" xml:space="preserve">
    <value>none reported</value>
  </data>
  <data name="Gateway.Minimum.BelowNow" xml:space="preserve">
    <value>This is below the minimum now: versions it refused may enrol again.</value>
  </data>
  <data name="Gateway.Minimum.AskAgain" xml:space="preserve">
    <value>Ask again</value>
  </data>
  <data name="Gateway.Minimum.Seeded.Suffix" xml:space="preserve">
    <value>, as seeded: every version may enrol</value>
  </data>
  <data name="Gateway.Minimum.SeeWhom" xml:space="preserve">
    <value>See whom it refuses</value>
  </data>
  <data name="Gateway.Minimum.WhatItDoes.1" xml:space="preserve">
    <value>The oldest kf-app version that may enrol. It retires an application generation: an installation below it is refused the next time it enrols, and one already enrolled keeps working until then. The next step shows whom a minimum refuses, by the version each last reported, as the gateway counts them.</value>
  </data>
  <data name="Gateway.Minimum.WhatItDoes.2" xml:space="preserve">
    <value>A version is a major and a minor at least, such as &lt;code&gt;1.7&lt;/code&gt; or &lt;code&gt;1.7.0&lt;/code&gt;, and a prerelease counts as its release. The gateway refuses anything else here; set by hand with &lt;code&gt;psql&lt;/code&gt;, a value that does not read as a version admits everyone, on purpose, so a typo there does not lock the fleet out.</value>
  </data>
  <data name="Gateway.Minimum.CurrentRelease" xml:space="preserve">
    <value>kf-app's current release is {0}.</value>
  </data>
  <data name="Gateway.Minimum.Problem.Required" xml:space="preserve">
    <value>Enter a version, such as 1.7.0.</value>
  </data>
  <data name="Gateway.Minimum.Problem.NotAVersion" xml:space="preserve">
    <value>"{0}" is not a version as enrolment reads one: a major and a minor at least, such as 1.7 or 1.7.0. The gateway would refuse it; set by hand, it would admit everyone.</value>
  </data>
  <data name="Gateway.Minimum.Problem.TooLong" xml:space="preserve">
    <value>A minimum version is at most {0} characters.</value>
  </data>
  <data name="Crm.Stage.ToContact" xml:space="preserve">
    <value>To contact</value>
  </data>
  <data name="Crm.Stage.ContactedAwaitingReply" xml:space="preserve">
    <value>Contacted, awaiting reply</value>
  </data>
  <data name="Crm.Stage.MeetingPlanned" xml:space="preserve">
    <value>Meeting planned</value>
  </data>
  <data name="Crm.Stage.Met" xml:space="preserve">
    <value>Met</value>
  </data>
  <data name="Crm.Stage.PreProposalAgreed" xml:space="preserve">
    <value>Pre-proposal agreed</value>
  </data>
  <data name="Crm.Stage.Active" xml:space="preserve">
    <value>Active</value>
  </data>
  <data name="Crm.Stage.DeclinedOrDormant" xml:space="preserve">
    <value>Declined or dormant</value>
  </data>
  <data name="Crm.Stage.Rejected" xml:space="preserve">
    <value>Rejected</value>
  </data>
  <data name="Crm.DeclineReason.AwaitingTraction" xml:space="preserve">
    <value>Awaiting more traction</value>
  </data>
  <data name="Crm.DeclineReason.NotSeekingPartners" xml:space="preserve">
    <value>Not looking for new partners</value>
  </data>
  <data name="Crm.DeclineReason.Other" xml:space="preserve">
    <value>Other</value>
  </data>
  <data name="Crm.Track.Ambassador" xml:space="preserve">
    <value>Ambassador</value>
  </data>
  <data name="Crm.Track.BusinessPartner" xml:space="preserve">
    <value>Business partner</value>
  </data>
  <data name="Crm.Track.Undecided" xml:space="preserve">
    <value>Undecided</value>
  </data>
  <data name="Crm.Entity.Individual" xml:space="preserve">
    <value>Individual</value>
  </data>
  <data name="Crm.Entity.Company" xml:space="preserve">
    <value>Company</value>
  </data>
  <data name="Crm.Entity.NotSaid" xml:space="preserve">
    <value>Not said</value>
  </data>
  <data name="Crm.Engagement.Detached" xml:space="preserve">
    <value>1 Detached (Distaccato)</value>
  </data>
  <data name="Crm.Engagement.Lukewarm" xml:space="preserve">
    <value>2 Lukewarm (Tiepido)</value>
  </data>
  <data name="Crm.Engagement.Interested" xml:space="preserve">
    <value>3 Interested (Interessato)</value>
  </data>
  <data name="Crm.Engagement.Committed" xml:space="preserve">
    <value>4 Committed (Impegnato)</value>
  </data>
  <data name="Crm.Engagement.Passionate" xml:space="preserve">
    <value>5 Passionate (Appassionato)</value>
  </data>
  <data name="Crm.Kind.Call" xml:space="preserve">
    <value>Call</value>
  </data>
  <data name="Crm.Kind.InPerson" xml:space="preserve">
    <value>In person</value>
  </data>
  <data name="Crm.Kind.Message" xml:space="preserve">
    <value>Message</value>
  </data>
  <data name="Crm.Kind.Email" xml:space="preserve">
    <value>Email</value>
  </data>
  <data name="Crm.Kind.Event" xml:space="preserve">
    <value>Event</value>
  </data>
  <data name="Crm.Silence.Week" xml:space="preserve">
    <value>Not in a week</value>
  </data>
  <data name="Crm.Silence.Month" xml:space="preserve">
    <value>Not in a month</value>
  </data>
  <data name="Crm.Silence.ThreeMonths" xml:space="preserve">
    <value>Not in 3 months</value>
  </data>
  <data name="Crm.Silence.Ever" xml:space="preserve">
    <value>Never</value>
  </data>
  <data name="Crm.Due.Overdue" xml:space="preserve">
    <value>Overdue</value>
  </data>
  <data name="Crm.Due.Week" xml:space="preserve">
    <value>Due within a week</value>
  </data>
  <data name="Crm.NextLine" xml:space="preserve">
    <value>{0} by {1}</value>
  </data>
  <data name="Crm.Delete" xml:space="preserve">
    <value>Delete</value>
  </data>
  <data name="Crm.Interactions" xml:space="preserve">
    <value>Interactions</value>
  </data>
  <data name="Crm.Next" xml:space="preserve">
    <value>Next action</value>
  </data>
  <data name="Crm.Ephemeral" xml:space="preserve">
    <value>Development contacts, held in memory: everything here is lost when the console restarts.</value>
  </data>
  <data name="Crm.PeopleUnread" xml:space="preserve">
    <value>The names &lt;em&gt;By&lt;/em&gt; offers could not be read from the roles, so only yours is offered just now. The console's log has why.</value>
  </data>
  <data name="Crm.Unreadable.Title" xml:space="preserve">
    <value>The contacts could not be read</value>
  </data>
  <data name="Crm.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault, so there is nowhere to keep a contact: nothing can be added or changed until the database is configured (&lt;code&gt;docs/Provisioning.md&lt;/code&gt;, Part C).</value>
  </data>
  <data name="Crm.Field.Name" xml:space="preserve">
    <value>Name</value>
  </data>
  <data name="Crm.Field.Headline" xml:space="preserve">
    <value>Current activity</value>
  </data>
  <data name="Crm.Field.Organisation" xml:space="preserve">
    <value>Organisation</value>
  </data>
  <data name="Crm.Field.Entity" xml:space="preserve">
    <value>Individual or company</value>
  </data>
  <data name="Crm.Field.Email" xml:space="preserve">
    <value>Email</value>
  </data>
  <data name="Crm.Field.Phone" xml:space="preserve">
    <value>Phone</value>
  </data>
  <data name="Crm.Field.Stage" xml:space="preserve">
    <value>Stage</value>
  </data>
  <data name="Crm.Field.By" xml:space="preserve">
    <value>By</value>
  </data>
  <data name="Crm.Field.Engagement" xml:space="preserve">
    <value>Engagement Level</value>
  </data>
  <data name="Crm.Field.Met" xml:space="preserve">
    <value>Met?</value>
  </data>
  <data name="Crm.Field.With" xml:space="preserve">
    <value>With?</value>
  </data>
  <data name="Crm.Field.Presentation" xml:space="preserve">
    <value>Presentation</value>
  </data>
  <data name="Crm.Field.DeclineReason" xml:space="preserve">
    <value>Why declined</value>
  </data>
  <data name="Crm.Field.DeclineReason.Title" xml:space="preserve">
    <value>Counted on Statistics while the stage is Declined or dormant.</value>
  </data>
  <data name="Crm.Field.Track" xml:space="preserve">
    <value>Kind of partnership</value>
  </data>
  <data name="Crm.Field.Notes" xml:space="preserve">
    <value>Notes</value>
  </data>
  <data name="Crm.Contacts.Lead" xml:space="preserve">
    <value>The partners and ambassadors programme, one row per person, in the sheet's columns under the sheet's names.</value>
  </data>
  <data name="Crm.Contacts.Lead.Edit" xml:space="preserve">
    <value>Click a cell to change it: Enter or leaving the cell saves, Escape cancels, and a dropdown saves on choice. Every save is recorded under your name, and a cell a colleague changed since you opened the grid is never overwritten: you are shown their value and yours. The first row is blank, whatever the order; type a name in it to add a contact. &lt;em&gt;Met?&lt;/em&gt; and &lt;em&gt;With?&lt;/em&gt; are the interactions: click either to see them and log a call or a meeting. A name opens the row's details, with the fields that are not columns.</value>
  </data>
  <data name="Crm.Contacts.Lead.ViewOnly" xml:space="preserve">
    <value>You can view the grid, not change it: that needs {0}, which an Administrator grants on the Users page. A name opens the row's details, and a click on &lt;em&gt;Met?&lt;/em&gt; or &lt;em&gt;With?&lt;/em&gt; the interactions.</value>
  </data>
  <data name="Crm.Contacts.Unreadable.Detail" xml:space="preserve">
    <value>The console's log has why, under "The contacts grid could not read the CRM". Nothing can be changed until they can be.</value>
  </data>
  <data name="Crm.Contacts.Deleted.Notice" xml:space="preserve">
    <value>&lt;strong&gt;Deleted.&lt;/strong&gt; The contact is out of the grid, an Administrator can restore it from Deleted contacts, and the audit log has the entry.</value>
  </data>
  <data name="Crm.Contacts.Count.One" xml:space="preserve">
    <value>1 contact</value>
  </data>
  <data name="Crm.Contacts.Count.Many" xml:space="preserve">
    <value>{0} contacts</value>
  </data>
  <data name="Crm.Contacts.Count.OneMatch" xml:space="preserve">
    <value>1 contact matches</value>
  </data>
  <data name="Crm.Contacts.Count.ManyMatch" xml:space="preserve">
    <value>{0} contacts match</value>
  </data>
  <data name="Crm.Contacts.Order" xml:space="preserve">
    <value>By name. Click a heading to sort by it; the dropdowns under the headings filter, as the sheet's autofilter does.</value>
  </data>
  <data name="Crm.Contacts.SearchPlaceholder" xml:space="preserve">
    <value>Name, activity, organisation or presentation</value>
  </data>
  <data name="Crm.Contacts.Export.Title" xml:space="preserve">
    <value>Every contact and interaction, as contacts.csv and interactions.csv in a zip. Recorded in the audit log.</value>
  </data>
  <data name="Crm.Contacts.Import" xml:space="preserve">
    <value>Import</value>
  </data>
  <data name="Crm.Contacts.Import.Title" xml:space="preserve">
    <value>Contacts and interactions from the export format: the sheet's one-off import, or a restore.</value>
  </data>
  <data name="Crm.Contacts.Empty" xml:space="preserve">
    <value>No contacts yet.</value>
  </data>
  <data name="Crm.Contacts.Empty.Filtered" xml:space="preserve">
    <value>No contact matches.</value>
  </data>
  <data name="Crm.Contacts.MetSorts" xml:space="preserve">
    <value>Sorts by the latest interaction</value>
  </data>
  <data name="Crm.Contacts.Filter.By" xml:space="preserve">
    <value>Filter by who originated the contact</value>
  </data>
  <data name="Crm.Contacts.Anyone" xml:space="preserve">
    <value>Anyone</value>
  </data>
  <data name="Crm.Contacts.Filter.Engagement" xml:space="preserve">
    <value>Filter by engagement, at least</value>
  </data>
  <data name="Crm.Contacts.OrWarmer" xml:space="preserve">
    <value>{0} or warmer</value>
  </data>
  <data name="Crm.Contacts.Filter.Since" xml:space="preserve">
    <value>Filter by not contacted since</value>
  </data>
  <data name="Crm.Contacts.Filter.Track" xml:space="preserve">
    <value>Filter by kind of partnership</value>
  </data>
  <data name="Crm.Contacts.Filter.Entity" xml:space="preserve">
    <value>Filter by individual or company</value>
  </data>
  <data name="Crm.Contacts.Filter.Stage" xml:space="preserve">
    <value>Filter by stage</value>
  </data>
  <data name="Crm.Contacts.AddHint" xml:space="preserve">
    <value>Add a contact: click here and type a name</value>
  </data>
  <data name="Crm.Contacts.SetOnCreate" xml:space="preserve">
    <value>Set when the contact is created</value>
  </data>
  <data name="Crm.Contacts.ClickForInteractions" xml:space="preserve">
    <value>Click for the interactions</value>
  </data>
  <data name="Crm.Contacts.NoDatabase.Create" xml:space="preserve">
    <value>The console has no database, so no contact can be recorded.</value>
  </data>
  <data name="Crm.Contacts.ChooseBy" xml:space="preserve">
    <value>Who brought them in?</value>
  </data>
  <data name="Crm.Contacts.ChooseBy.Short" xml:space="preserve">
    <value>Choose…</value>
  </data>
  <data name="Crm.Contacts.NoDatabase.Save" xml:space="preserve">
    <value>The console has no database, so nothing can be saved.</value>
  </data>
  <data name="Crm.Contacts.NotSaved" xml:space="preserve">
    <value>The contact could not be saved. The console's log has why.</value>
  </data>
  <data name="Crm.Contacts.CellNotSaved" xml:space="preserve">
    <value>The cell could not be saved. The console's log has why.</value>
  </data>
  <data name="Crm.Contacts.NoVersion" xml:space="preserve">
    <value>The row's version was not sent. Reload the page.</value>
  </data>
  <data name="Crm.Contacts.Deleted" xml:space="preserve">
    <value>This contact has been deleted.</value>
  </data>
  <data name="Crm.Contacts.NotDeleted" xml:space="preserve">
    <value>Nothing changed: the contact could not be deleted. The console's log has why.</value>
  </data>
  <data name="Crm.Edit.NameRequired" xml:space="preserve">
    <value>A contact needs a name.</value>
  </data>
  <data name="Crm.Edit.TooLong" xml:space="preserve">
    <value>{0} is at most {1} characters.</value>
  </data>
  <data name="Crm.Edit.Field.Name" xml:space="preserve">
    <value>A name</value>
  </data>
  <data name="Crm.Edit.Field.Headline" xml:space="preserve">
    <value>The current activity</value>
  </data>
  <data name="Crm.Edit.Field.Notes" xml:space="preserve">
    <value>Notes are</value>
  </data>
  <data name="Crm.Edit.Field.Presentation" xml:space="preserve">
    <value>The presentation</value>
  </data>
  <data name="Crm.Edit.Field.Organisation" xml:space="preserve">
    <value>An organisation</value>
  </data>
  <data name="Crm.Edit.Field.Email" xml:space="preserve">
    <value>An email address</value>
  </data>
  <data name="Crm.Edit.Field.Phone" xml:space="preserve">
    <value>A phone number</value>
  </data>
  <data name="Crm.Edit.Field.LinkedIn" xml:space="preserve">
    <value>A LinkedIn address</value>
  </data>
  <data name="Crm.Edit.ByRequired" xml:space="preserve">
    <value>Say who brought them in.</value>
  </data>
  <data name="Crm.Edit.ByNoRole" xml:space="preserve">
    <value>{0} does not hold a CRM role, so a contact cannot name them.</value>
  </data>
  <data name="Crm.Edit.Engagement" xml:space="preserve">
    <value>Engagement is 1 to 5, or blank.</value>
  </data>
  <data name="Crm.Edit.Track" xml:space="preserve">
    <value>Not a kind of partnership the console knows.</value>
  </data>
  <data name="Crm.Edit.Stage" xml:space="preserve">
    <value>Not a stage the console knows.</value>
  </data>
  <data name="Crm.Edit.DeclineReason" xml:space="preserve">
    <value>Not a reason the console knows.</value>
  </data>
  <data name="Crm.Edit.Entity" xml:space="preserve">
    <value>Choose Individual, Company or Not said.</value>
  </data>
  <data name="Crm.Edit.Email" xml:space="preserve">
    <value>That is not an email address.</value>
  </data>
  <data name="Crm.Edit.LinkedIn" xml:space="preserve">
    <value>A LinkedIn address starts with https://.</value>
  </data>
  <data name="Crm.Edit.NotACell" xml:space="preserve">
    <value>Not a cell that can be edited.</value>
  </data>
  <data name="Crm.Details.Lead" xml:space="preserve">
    <value>The same row on its own, with the fields that are not columns. It is edited the way the grid is: click a cell, and the same save goes to the same place.</value>
  </data>
  <data name="Crm.Details.ViewOnly" xml:space="preserve">
    <value>You can view this contact, not change it: that needs {0}.</value>
  </data>
  <data name="Crm.Details.Title" xml:space="preserve">
    <value>Details</value>
  </data>
  <data name="Crm.Details.Subtitle" xml:space="preserve">
    <value>Not columns, to keep the sheet's width. The search box covers the organisation.</value>
  </data>
  <data name="Crm.Details.EnteredBy" xml:space="preserve">
    <value>Entered by</value>
  </data>
  <data name="Crm.Details.LastChangedBy" xml:space="preserve">
    <value>Last changed by</value>
  </data>
  <data name="Crm.Details.Timeline" xml:space="preserve">
    <value>Next action and interactions</value>
  </data>
  <data name="Crm.Details.Timeline.Subtitle" xml:space="preserve">
    <value>What is to be done next, by whom and by when, and every call, meeting and message, by date, with who took part and what was said: the lines of &lt;em&gt;Met?&lt;/em&gt; and &lt;em&gt;With?&lt;/em&gt;, with what is behind them. Each is recorded under the name of whoever logged it. A planned meeting is a next action until it has happened; then it is an interaction.</value>
  </data>
  <data name="Crm.Details.Delete.Lead" xml:space="preserve">
    <value>Takes the contact and their interactions out of the CRM's pages, and out of no database: an Administrator's, and restored from Deleted contacts. You confirm on the next page by typing the contact's name, and it is audited with the contact's id and name.</value>
  </data>
  <data name="Crm.Delete.Title" xml:space="preserve">
    <value>Delete a contact</value>
  </data>
  <data name="Crm.Delete.Heading" xml:space="preserve">
    <value>Delete {0}</value>
  </data>
  <data name="Crm.Delete.Lead" xml:space="preserve">
    <value>The contact leaves the CRM's pages, and so do their interactions: the grid, the follow-ups, the overview and every export. Nothing leaves the database, and an Administrator can restore them from Deleted contacts. The audit log keeps that it was deleted, by whom, and the contact's id and name, and nothing else of the row.</value>
  </data>
  <data name="Crm.Delete.TheContact" xml:space="preserve">
    <value>The contact</value>
  </data>
  <data name="Crm.Delete.Interactions.None" xml:space="preserve">
    <value>None</value>
  </data>
  <data name="Crm.Delete.Interactions.One" xml:space="preserve">
    <value>One, deleted with the contact</value>
  </data>
  <data name="Crm.Delete.Interactions.Many" xml:space="preserve">
    <value>{0}, deleted with the contact</value>
  </data>
  <data name="Crm.Delete.WhatItDoes" xml:space="preserve">
    <value>What delete does</value>
  </data>
  <data name="Crm.Delete.Detail" xml:space="preserve">
    <value>The row leaves the grid, and a colleague with the grid open is told the contact has been deleted the next time they save a cell of it. Recorded as {0} in the audit log, as &lt;code&gt;crm:contact-delete&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Delete.Submit" xml:space="preserve">
    <value>Delete contact</value>
  </data>
  <data name="Crm.Delete.TypeName" xml:space="preserve">
    <value>To delete, type the contact's name, {0}:</value>
  </data>
  <data name="Crm.Delete.NameMismatch" xml:space="preserve">
    <value>Nothing was deleted: the name typed is not the contact's. Type it as it is shown to delete the contact.</value>
  </data>
  <data name="Crm.Deleted.Title" xml:space="preserve">
    <value>Deleted contacts</value>
  </data>
  <data name="Crm.Deleted.Lead" xml:space="preserve">
    <value>Contacts an Administrator has deleted. A delete is soft: the contact and their interactions stay in the database, out of the grid, the follow-ups, the overview and every export, and &lt;em&gt;Restore&lt;/em&gt; brings them back as they were. Erasing a person who asks to be removed is an operator's, as &lt;code&gt;docs/Operations.md&lt;/code&gt; says.</value>
  </data>
  <data name="Crm.Deleted.Lead.Short" xml:space="preserve">
    <value>Contacts deleted, which an Administrator can restore.</value>
  </data>
  <data name="Crm.Deleted.Unreadable" xml:space="preserve">
    <value>The CRM could not be read, so the deleted contacts cannot be listed.</value>
  </data>
  <data name="Crm.Deleted.NotRestored" xml:space="preserve">
    <value>The contact could not be restored; nothing changed. Try again.</value>
  </data>
  <data name="Crm.Deleted.Restored" xml:space="preserve">
    <value>&lt;strong&gt;Restored.&lt;/strong&gt; {0} is back in the CRM, with their interactions, and the audit log has the entry.</value>
  </data>
  <data name="Crm.Deleted.Count.One" xml:space="preserve">
    <value>1 deleted contact</value>
  </data>
  <data name="Crm.Deleted.Count.Many" xml:space="preserve">
    <value>{0} deleted contacts</value>
  </data>
  <data name="Crm.Deleted.Empty" xml:space="preserve">
    <value>No contact has been deleted.</value>
  </data>
  <data name="Crm.Deleted.DeletedBy" xml:space="preserve">
    <value>Deleted by</value>
  </data>
  <data name="Crm.Deleted.DeletedAt" xml:space="preserve">
    <value>Deleted</value>
  </data>
  <data name="Crm.Deleted.Restore" xml:space="preserve">
    <value>Restore</value>
  </data>
  <data name="Crm.FollowUps.Lead" xml:space="preserve">
    <value>What is to be done next, by whom and by when: every contact with a next action, the overdue first and then by due date, those with no date last. The next action is the last line of &lt;em&gt;Met?&lt;/em&gt; and its owner the last line of &lt;em&gt;With?&lt;/em&gt;, as on {0}: a row here is the row there.</value>
  </data>
  <data name="Crm.FollowUps.Lead.Edit" xml:space="preserve">
    <value>Click &lt;em&gt;Met?&lt;/em&gt; or &lt;em&gt;With?&lt;/em&gt; to set, change or clear it, or to log the call that settles it; click any other cell to change it, as on Partnerships.</value>
  </data>
  <data name="Crm.FollowUps.Lead.ViewOnly" xml:space="preserve">
    <value>You can view the follow-ups, not change them: that needs {0}.</value>
  </data>
  <data name="Crm.FollowUps.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault, so there is nowhere to keep a contact or its next action.</value>
  </data>
  <data name="Crm.FollowUps.Unreadable.Title" xml:space="preserve">
    <value>The follow-ups could not be read</value>
  </data>
  <data name="Crm.FollowUps.Unreadable.Detail" xml:space="preserve">
    <value>The console's log has why, under "The follow-ups grid could not read the CRM". Nothing can be changed until they can be.</value>
  </data>
  <data name="Crm.FollowUps.Count.One" xml:space="preserve">
    <value>1 follow-up</value>
  </data>
  <data name="Crm.FollowUps.Count.Many" xml:space="preserve">
    <value>{0} follow-ups</value>
  </data>
  <data name="Crm.FollowUps.OfYours" xml:space="preserve">
    <value> of yours</value>
  </data>
  <data name="Crm.FollowUps.For" xml:space="preserve">
    <value> for {0}</value>
  </data>
  <data name="Crm.FollowUps.OverdueCount" xml:space="preserve">
    <value>, {0} overdue</value>
  </data>
  <data name="Crm.FollowUps.Order" xml:space="preserve">
    <value>Overdue first, then by due date, as of {0} (UTC). Click a heading to sort by it instead; reload for this order.</value>
  </data>
  <data name="Crm.FollowUps.Mine" xml:space="preserve">
    <value>Mine</value>
  </data>
  <data name="Crm.FollowUps.Mine.On" xml:space="preserve">
    <value>Showing your next actions: click for everyone's</value>
  </data>
  <data name="Crm.FollowUps.Mine.Off" xml:space="preserve">
    <value>The next actions you own</value>
  </data>
  <data name="Crm.FollowUps.Filter.Owner" xml:space="preserve">
    <value>Filter by owner</value>
  </data>
  <data name="Crm.FollowUps.Anyones" xml:space="preserve">
    <value>Anyone's</value>
  </data>
  <data name="Crm.FollowUps.Filter.Due" xml:space="preserve">
    <value>Filter by when due</value>
  </data>
  <data name="Crm.FollowUps.Empty" xml:space="preserve">
    <value>Nothing is to be done next: no contact has a next action.</value>
  </data>
  <data name="Crm.FollowUps.Empty.Filtered" xml:space="preserve">
    <value>No follow-up matches.</value>
  </data>
  <data name="Crm.Next.ForOwner" xml:space="preserve">
    <value>for {0}, </value>
  </data>
  <data name="Crm.Next.Due" xml:space="preserve">
    <value>due {0}</value>
  </data>
  <data name="Crm.Next.NoDueDate" xml:space="preserve">
    <value>no due date</value>
  </data>
  <data name="Crm.Next.None" xml:space="preserve">
    <value>None: nothing is to be done next for this contact.</value>
  </data>
  <data name="Crm.Next.Set" xml:space="preserve">
    <value>Set</value>
  </data>
  <data name="Crm.Next.Change" xml:space="preserve">
    <value>Change</value>
  </data>
  <data name="Crm.Next.Clear.Title" xml:space="preserve">
    <value>Saves the three empty and records nothing: for one no longer to be done. For one done, use Done</value>
  </data>
  <data name="Crm.Next.Done" xml:space="preserve">
    <value>Done</value>
  </data>
  <data name="Crm.Next.Done.Title" xml:space="preserve">
    <value>Log it as done now: a call today with its text, and the next action cleared. Edit the interaction afterwards to change it</value>
  </data>
  <data name="Crm.Next.What" xml:space="preserve">
    <value>What is to be done</value>
  </data>
  <data name="Crm.Next.ByWhom" xml:space="preserve">
    <value>By whom</value>
  </data>
  <data name="Crm.Next.ByWhen" xml:space="preserve">
    <value>By when</value>
  </data>
  <data name="Crm.Next.Placeholder" xml:space="preserve">
    <value>Write the next action here</value>
  </data>
  <data name="Crm.Next.Title.Due" xml:space="preserve">
    <value>Next action, due {0}</value>
  </data>
  <data name="Crm.Next.Title.Overdue" xml:space="preserve">
    <value>Next action, due {0}: overdue</value>
  </data>
  <data name="Crm.Next.Title.NoDate" xml:space="preserve">
    <value>Next action, with no due date</value>
  </data>
  <data name="Crm.Next.Problem.TextRequired" xml:space="preserve">
    <value>Say what is to be done by then, or clear the date.</value>
  </data>
  <data name="Crm.Next.Problem.TooLong" xml:space="preserve">
    <value>A next action is at most {0} characters: the rest belongs in an interaction's summary or the notes.</value>
  </data>
  <data name="Crm.Next.Problem.OwnerRequired" xml:space="preserve">
    <value>Say who is to do it.</value>
  </data>
  <data name="Crm.Next.Problem.NoRole" xml:space="preserve">
    <value>{0} does not hold a CRM role, so a next action cannot be theirs.</value>
  </data>
  <data name="Crm.Next.Problem.NotADate" xml:space="preserve">
    <value>A due date is a date, or blank.</value>
  </data>
  <data name="Crm.Next.Problem.Year" xml:space="preserve">
    <value>Check the year of the due date.</value>
  </data>
  <data name="Crm.Next.Unsaved" xml:space="preserve">
    <value>Nothing was written: the next action could not be saved. The console's log has why.</value>
  </data>
  <data name="Crm.Next.Conflict" xml:space="preserve">
    <value>The contact was changed by {0} at {1} after this panel was drawn. Nothing of yours was written: the next action as it is now is shown, and what you typed is in the form. Save it to replace it, or cancel.</value>
  </data>
  <data name="Crm.Interactions.None" xml:space="preserve">
    <value>No interactions yet.</value>
  </data>
  <data name="Crm.Interactions.With" xml:space="preserve">
    <value>with {0}</value>
  </data>
  <data name="Crm.Interactions.RecordedBy" xml:space="preserve">
    <value>Recorded by {0}, {1}</value>
  </data>
  <data name="Crm.Interactions.ChangedBy" xml:space="preserve">
    <value>; changed by {0}, {1}</value>
  </data>
  <data name="Crm.Interactions.DeleteConfirm" xml:space="preserve">
    <value>Delete this interaction? It cannot be undone, and the audit log records it.</value>
  </data>
  <data name="Crm.Interactions.Keep" xml:space="preserve">
    <value>Keep</value>
  </data>
  <data name="Crm.Interactions.Log" xml:space="preserve">
    <value>Log an interaction</value>
  </data>
  <data name="Crm.Interactions.AndNext" xml:space="preserve">
    <value>And what is next: it replaces the next action above</value>
  </data>
  <data name="Crm.Interactions.NoNext.Ask" xml:space="preserve">
    <value>No next action planned?</value>
  </data>
  <data name="Crm.Interactions.NoNext.Yes" xml:space="preserve">
    <value>Yes: log it and clear the next action</value>
  </data>
  <data name="Crm.Interactions.NoNext.Keep" xml:space="preserve">
    <value>Log it and keep the current one</value>
  </data>
  <data name="Crm.Interactions.NoNext.Back" xml:space="preserve">
    <value>No, I will write one</value>
  </data>
  <data name="Crm.Interactions.Done" xml:space="preserve">
    <value>Log the next action as done</value>
  </data>
  <data name="Crm.Interactions.Done.AndNext" xml:space="preserve">
    <value>And what is next, if anything: left empty, the next action is cleared</value>
  </data>
  <data name="Crm.Interactions.Add" xml:space="preserve">
    <value>Add</value>
  </data>
  <data name="Crm.Interactions.ViewOnly" xml:space="preserve">
    <value>You can view the interactions and the next action, not change them: that needs {0}.</value>
  </data>
  <data name="Crm.Interaction.When" xml:space="preserve">
    <value>When</value>
  </data>
  <data name="Crm.Interaction.Kind" xml:space="preserve">
    <value>Kind</value>
  </data>
  <data name="Crm.Interaction.With" xml:space="preserve">
    <value>With, from KnowledgeFabric</value>
  </data>
  <data name="Crm.Interaction.Summary" xml:space="preserve">
    <value>What was said</value>
  </data>
  <data name="Crm.Interaction.Problem.DateRequired" xml:space="preserve">
    <value>Say when it happened: a date.</value>
  </data>
  <data name="Crm.Interaction.Problem.Year" xml:space="preserve">
    <value>Check the year: the CRM keeps interactions from 2000 on.</value>
  </data>
  <data name="Crm.Interaction.Problem.Future" xml:space="preserve">
    <value>An interaction is something that has happened. One that is planned is a next action, not an interaction.</value>
  </data>
  <data name="Crm.Interaction.Problem.Kind" xml:space="preserve">
    <value>Not a kind of interaction the console knows.</value>
  </data>
  <data name="Crm.Interaction.Problem.NoRole" xml:space="preserve">
    <value>{0} does not hold a CRM role, so an interaction cannot name them.</value>
  </data>
  <data name="Crm.Problem.Admin" xml:space="preserve">
    <value>admin is not a person, so the CRM never names it: choose who it was.</value>
  </data>
  <data name="Crm.Interaction.Problem.ParticipantsRequired" xml:space="preserve">
    <value>Say who from KnowledgeFabric took part: one name at least.</value>
  </data>
  <data name="Crm.Interaction.Problem.SummaryRequired" xml:space="preserve">
    <value>Say what was said: an interaction needs a summary.</value>
  </data>
  <data name="Crm.Interaction.Problem.SummaryTooLong" xml:space="preserve">
    <value>A summary is at most {0} characters.</value>
  </data>
  <data name="Crm.Interaction.Unsaved" xml:space="preserve">
    <value>Nothing was written: the interaction could not be saved. The console's log has why.</value>
  </data>
  <data name="Crm.Interaction.UnsavedAfterNext" xml:space="preserve">
    <value>The next action was saved; the interaction was not: it could not be written. The console's log has why.</value>
  </data>
  <data name="Crm.Interaction.NoVersion" xml:space="preserve">
    <value>The contact's version was not sent. Reload the page.</value>
  </data>
  <data name="Crm.Interaction.NoOwnVersion" xml:space="preserve">
    <value>The interaction's version was not sent. Reload the page.</value>
  </data>
  <data name="Crm.Interaction.NotDeleted" xml:space="preserve">
    <value>Nothing changed: the interaction could not be deleted. The console's log has why.</value>
  </data>
  <data name="Crm.Interaction.AlreadyDeleted" xml:space="preserve">
    <value>A colleague had already deleted that interaction.</value>
  </data>
  <data name="Crm.Interaction.Conflict.Add" xml:space="preserve">
    <value>The contact was changed by {0} at {1} after this panel was drawn, so neither the interaction nor the next action was written. The next action as it is now is shown above, and what you typed is in the form below: add it again to log the interaction and replace the next action, knowingly.</value>
  </data>
  <data name="Crm.Interaction.Conflict.Update" xml:space="preserve">
    <value>Changed by {0} at {1} while you were editing it. Nothing of yours was written: theirs is shown, and what you typed is in the form. Save it to replace theirs, or cancel.</value>
  </data>
  <data name="Crm.Interaction.Conflict.Delete" xml:space="preserve">
    <value>Changed by {0} at {1} after you opened it, so it was not deleted. It is shown as it is now: delete it again if it should still go.</value>
  </data>
  <data name="Crm.Interaction.DeletedWhileEditing" xml:space="preserve">
    <value>A colleague deleted that interaction while you were editing it. Nothing of yours was written: what you typed is in the form below, to add it again if it should stay.</value>
  </data>
  <data name="Crm.Import.Title" xml:space="preserve">
    <value>Import contacts</value>
  </data>
  <data name="Crm.Import.Lead" xml:space="preserve">
    <value>&lt;code&gt;contacts.csv&lt;/code&gt; and &lt;code&gt;interactions.csv&lt;/code&gt;, in the CRM's export format, written into the CRM at once: the spreadsheet's one-off import, prepared from it by hand, or a restore from &lt;em&gt;Export CSV&lt;/em&gt;. Every value is checked as the grid checks it, and nothing is written until you have seen what the files would create. A contact whose name is already in the CRM refuses the whole import, so the same files cannot be imported twice. The format and the sheet's mapping are in &lt;code&gt;docs/CRM.md&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Import.NoDatabase.Detail" xml:space="preserve">
    <value>&lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault, so there is nowhere to import to. The files can be checked, not written.</value>
  </data>
  <data name="Crm.Import.Ephemeral" xml:space="preserve">
    <value>Development contacts, held in memory: an import here is lost when the console restarts.</value>
  </data>
  <data name="Crm.Import.Imported" xml:space="preserve">
    <value>Imported</value>
  </data>
  <data name="Crm.Import.Counts" xml:space="preserve">
    <value>{0}, {1} and {2}</value>
  </data>
  <data name="Crm.Import.Imported.Detail" xml:space="preserve">
    <value>{0}, entered by {1} and recorded in the audit log as &lt;code&gt;crm:import&lt;/code&gt;.</value>
  </data>
  <data name="Crm.Import.TheContacts" xml:space="preserve">
    <value>The contacts</value>
  </data>
  <data name="Crm.Import.And" xml:space="preserve">
    <value>and</value>
  </data>
  <data name="Crm.Import.TheFollowUps" xml:space="preserve">
    <value>the follow-ups</value>
  </data>
  <data name="Crm.Import.TheFiles" xml:space="preserve">
    <value>The files</value>
  </data>
  <data name="Crm.Import.NotYet" xml:space="preserve">
    <value>Nothing can be imported yet</value>
  </data>
  <data name="Crm.Import.NotYet.Detail" xml:space="preserve">
    <value>Mend the files and choose them again. Nothing has been written.</value>
  </data>
  <data name="Crm.Import.WillCreate" xml:space="preserve">
    <value>What the import will create</value>
  </data>
  <data name="Crm.Import.WillCreate.Detail" xml:space="preserve">
    <value>{0}, each entered by {1}, with &lt;em&gt;By&lt;/em&gt; as the file says.</value>
  </data>
  <data name="Crm.Import.WithoutSummary.One" xml:space="preserve">
    <value>1 interaction has no summary in the file and will read {0}.</value>
  </data>
  <data name="Crm.Import.WithoutSummary.Many" xml:space="preserve">
    <value>{0} interactions have no summary in the file and will read {1}.</value>
  </data>
  <data name="Crm.Import.ChooseOthers" xml:space="preserve">
    <value>Choose other files</value>
  </data>
  <data name="Crm.Import.NotCameBack" xml:space="preserve">
    <value>The files did not come back from the preview. Choose them again.</value>
  </data>
  <data name="Crm.Import.NoDatabase" xml:space="preserve">
    <value>The console has no database, so nothing can be imported.</value>
  </data>
  <data name="Crm.Import.CrmUnread" xml:space="preserve">
    <value>The CRM could not be read, so the files could not be checked against it. The console's log has why.</value>
  </data>
  <data name="Crm.Import.NotWritten" xml:space="preserve">
    <value>Nothing was imported: the CRM could not be written. The console's log has why.</value>
  </data>
  <data name="Crm.Import.AlreadyPresent" xml:space="preserve">
    <value>{0} is already a contact: these files have just been imported, by this confirm sent twice or by a colleague.</value>
  </data>
  <data name="Crm.Import.Choose" xml:space="preserve">
    <value>Choose {0}.</value>
  </data>
  <data name="Crm.Import.TooLarge" xml:space="preserve">
    <value>{0} is larger than the import takes ({1} MB).</value>
  </data>
  <data name="Crm.Import.NotUtf8" xml:space="preserve">
    <value>{0} is not UTF-8. Save it from the spreadsheet as CSV UTF-8.</value>
  </data>
  <data name="Crm.Import.Where" xml:space="preserve">
    <value>{0}, line {1}</value>
  </data>
  <data name="Crm.Import.Problem.IdPresent" xml:space="preserve">
    <value>{0}, line {1}: a contact already has the id {2}. This file has been imported, or the CRM it restores is not empty.</value>
  </data>
  <data name="Crm.Import.Problem.IdDeleted" xml:space="preserve">
    <value>{0}, line {1}: the id {2} is a deleted contact's. Restore them from Deleted contacts rather than import them, or leave them out of the file.</value>
  </data>
  <data name="Crm.Import.Problem.NamePresent" xml:space="preserve">
    <value>{0}, line {1}: {2} is already a contact. The import is a one-off: this file has been imported, or they were added by hand since it was prepared. Leave them out of the file.</value>
  </data>
  <data name="Crm.Import.Problem.NoContacts" xml:space="preserve">
    <value>{0} has no contacts: nothing to import.</value>
  </data>
  <data name="Crm.Import.Problem.More" xml:space="preserve">
    <value>And {0} more.</value>
  </data>
  <data name="Crm.Import.Problem.BadId" xml:space="preserve">
    <value>{0}: the id is not one the CRM makes. Leave it blank for a new contact.</value>
  </data>
  <data name="Crm.Import.Problem.IdTwice" xml:space="preserve">
    <value>{0}: the id {1} is on another line too.</value>
  </data>
  <data name="Crm.Import.Problem.NameTwice" xml:space="preserve">
    <value>{0}, lines {1}: {2} is on more than one line. Two people may share a name, but then each line needs an id, and their interactions a contact_id.</value>
  </data>
  <data name="Crm.Import.Problem.ContactIdUnknown" xml:space="preserve">
    <value>{0}: contact_id {1} is no contact's in {2}.</value>
  </data>
  <data name="Crm.Import.Problem.ContactIdMismatch" xml:space="preserve">
    <value>{0}: contact_id is {1}'s, but the line names {2}.</value>
  </data>
  <data name="Crm.Import.Problem.NoContact" xml:space="preserve">
    <value>{0}: say whose interaction it is, under contact.</value>
  </data>
  <data name="Crm.Import.Problem.ContactUnknown" xml:space="preserve">
    <value>{0}: {1} is not in {2}, or their line there was refused.</value>
  </data>
  <data name="Crm.Import.Problem.ContactAmbiguous" xml:space="preserve">
    <value>{0}: {1} is on more than one line of {2}: give the contact_id.</value>
  </data>
  <data name="Crm.Csv.Empty" xml:space="preserve">
    <value>{0} is empty: it needs its header line at least.</value>
  </data>
  <data name="Crm.Csv.Blank" xml:space="preserve">
    <value>(blank)</value>
  </data>
  <data name="Crm.Csv.UnknownColumn" xml:space="preserve">
    <value>{0} has a column the format does not: {1}. Its columns are {2}.</value>
  </data>
  <data name="Crm.Csv.ColumnTwice" xml:space="preserve">
    <value>{0} has a column twice: {1}.</value>
  </data>
  <data name="Crm.Csv.MissingColumn" xml:space="preserve">
    <value>{0} is missing a column: {1}.</value>
  </data>
  <data name="Crm.Csv.ValueCount" xml:space="preserve">
    <value>{0}, line {1}: {2} values under {3} columns.</value>
  </data>
  <data name="Crm.Csv.QuoteInside" xml:space="preserve">
    <value>line {0} has a quote inside a value that does not start with one.</value>
  </data>
  <data name="Crm.Csv.TextAfterQuote" xml:space="preserve">
    <value>line {0} has text after a quoted value's closing quote.</value>
  </data>
  <data name="Crm.Csv.QuoteUnclosed" xml:space="preserve">
    <value>a quote opened on line {0} or after is never closed.</value>
  </data>
  <data name="Crm.Overview.Lead" xml:space="preserve">
    <value>The partners and ambassadors programme, as records rather than a sheet.</value>
  </data>
  <data name="Crm.Overview.Contacts" xml:space="preserve">
    <value>Contacts</value>
  </data>
  <data name="Crm.Overview.NoDatabase" xml:space="preserve">
    <value>The console has no database, so there is nowhere to keep a contact: &lt;code&gt;Database--ConnectionString&lt;/code&gt; is not in Key Vault (&lt;code&gt;docs/Provisioning.md&lt;/code&gt;, Part C).</value>
  </data>
  <data name="Crm.Overview.Unreadable.Detail" xml:space="preserve">
    <value>The console's log has the exception, under "The overview could not read the CRM".</value>
  </data>
  <data name="Crm.Statistics.Lead" xml:space="preserve">
    <value>The programme in numbers, for the go-to-market story: every contact identified, where each stands, how the concluded discussions ended, and the customers the partners introduced. Counts only: no contact and no customer is named here.</value>
  </data>
  <data name="Crm.Statistics.Unreadable.Detail" xml:space="preserve">
    <value>The console's log has the exception, under "The CRM's statistics could not read the CRM".</value>
  </data>
  <data name="Crm.Statistics.Funnel" xml:space="preserve">
    <value>From contact to partnership</value>
  </data>
  <data name="Crm.Statistics.Funnel.Subtitle" xml:space="preserve">
    <value>Each line divides the line above it. The three ways a discussion ends are shares of the concluded ones.</value>
  </data>
  <data name="Crm.Statistics.Contacts" xml:space="preserve">
    <value>Contacts</value>
  </data>
  <data name="Crm.Statistics.OfConcluded" xml:space="preserve">
    <value>Of concluded</value>
  </data>
  <data name="Crm.Statistics.Stages" xml:space="preserve">
    <value>Stages counted</value>
  </data>
  <data name="Crm.Statistics.Identified" xml:space="preserve">
    <value>Contacts identified</value>
  </data>
  <data name="Crm.Statistics.AllStages" xml:space="preserve">
    <value>Every stage</value>
  </data>
  <data name="Crm.Statistics.ToSchedule" xml:space="preserve">
    <value>To schedule</value>
  </data>
  <data name="Crm.Statistics.ToMeetSoon" xml:space="preserve">
    <value>To meet soon</value>
  </data>
  <data name="Crm.Statistics.Met" xml:space="preserve">
    <value>Met</value>
  </data>
  <data name="Crm.Statistics.MetStages" xml:space="preserve">
    <value>{0} and every stage after it</value>
  </data>
  <data name="Crm.Statistics.InDiscussion" xml:space="preserve">
    <value>Discussion ongoing</value>
  </data>
  <data name="Crm.Statistics.Concluded" xml:space="preserve">
    <value>Discussion concluded</value>
  </data>
  <data name="Crm.Statistics.ConcludedStages" xml:space="preserve">
    <value>The three lines below</value>
  </data>
  <data name="Crm.Statistics.Accepted" xml:space="preserve">
    <value>Accepted the proposal</value>
  </data>
  <data name="Crm.Statistics.Declined" xml:space="preserve">
    <value>Decision deferred</value>
  </data>
  <data name="Crm.Statistics.NoReason" xml:space="preserve">
    <value>No reason recorded</value>
  </data>
  <data name="Crm.Statistics.Rejected" xml:space="preserve">
    <value>Not a fit to work with</value>
  </data>
  <data name="Crm.Statistics.Footnote" xml:space="preserve">
    <value>Counted from every contact in the CRM, deleted ones aside, by the stage each stands at today. Every contact counts, a test one included; delete one to leave it out.</value>
  </data>
  <data name="Crm.Statistics.Footnote.AsOf" xml:space="preserve">
    <value>Counted from the record of stage changes: every contact as it stood at the end of {0} UTC, those deleted by then aside. A contact deleted since still counts on the days it was live.</value>
  </data>
  <data name="Crm.Statistics.Funnel.AsOf" xml:space="preserve">
    <value>As it stood at the end of {0} (UTC).</value>
  </data>
  <data name="Crm.Statistics.AsOf" xml:space="preserve">
    <value>As of</value>
  </data>
  <data name="Crm.Statistics.AsOf.Show" xml:space="preserve">
    <value>Show</value>
  </data>
  <data name="Crm.Statistics.AsOf.Today" xml:space="preserve">
    <value>Back to today</value>
  </data>
  <data name="Crm.Statistics.AsOf.Hint" xml:space="preserve">
    <value>Any day since the record of stage changes began, on {0}.</value>
  </data>
  <data name="Crm.Statistics.AsOf.NotADate" xml:space="preserve">
    <value>That is not a date this page can read, so it shows today. Pick a day with the date field.</value>
  </data>
  <data name="Crm.Statistics.AsOf.Future" xml:space="preserve">
    <value>{0} has not come yet, so the page shows today.</value>
  </data>
  <data name="Crm.Statistics.AsOf.BeforeRecord" xml:space="preserve">
    <value>The record of stage changes began on {0}, and nothing before it was kept, so the page shows today.</value>
  </data>
  <data name="Crm.Statistics.AsOf.NothingRecorded" xml:space="preserve">
    <value>Nothing has been recorded yet, so the page shows today.</value>
  </data>
  <data name="Crm.Statistics.AsOf.Unreadable" xml:space="preserve">
    <value>The record of stage changes could not be read, so the page shows today.</value>
  </data>
  <data name="Crm.Statistics.OverTime" xml:space="preserve">
    <value>Over time</value>
  </data>
  <data name="Crm.Statistics.OverTime.Weekly" xml:space="preserve">
    <value>Contacts identified, met and accepted at the end of each week, since the record of stage changes began on {0}. A point opens the funnel as it stood that day.</value>
  </data>
  <data name="Crm.Statistics.OverTime.Monthly" xml:space="preserve">
    <value>Contacts identified, met and accepted at the end of each month, since the record of stage changes began on {0}. A point opens the funnel as it stood that day.</value>
  </data>
  <data name="Crm.Statistics.OverTime.Nothing" xml:space="preserve">
    <value>Nothing has been recorded yet: the record of stage changes begins with the first contact.</value>
  </data>
  <data name="Crm.Statistics.OverTime.TooShort" xml:space="preserve">
    <value>The record of stage changes began on {0}. The chart starts the day after.</value>
  </data>
  <data name="Crm.Statistics.OverTime.Unreadable" xml:space="preserve">
    <value>The record of stage changes could not be read. The console's log has the exception, under "The CRM's statistics could not read the record of stage changes".</value>
  </data>
  <data name="Crm.Statistics.OverTime.Numbers" xml:space="preserve">
    <value>The numbers</value>
  </data>
  <data name="Crm.Statistics.OverTime.EndOf" xml:space="preserve">
    <value>End of</value>
  </data>
  <data name="Crm.Statistics.Introductions" xml:space="preserve">
    <value>From introduction to contract</value>
  </data>
  <data name="Crm.Statistics.Introductions.Subtitle" xml:space="preserve">
    <value>What the partners produced: every customer a partner or ambassador introduced, where each stands, by the partner's kind of partnership, and how far each got. Every line is a share of the customers introduced.</value>
  </data>
  <data name="Crm.Statistics.Customers" xml:space="preserve">
    <value>Customers</value>
  </data>
  <data name="Crm.Statistics.OfIntroduced" xml:space="preserve">
    <value>Of introduced</value>
  </data>
  <data name="Crm.Statistics.Introduced" xml:space="preserve">
    <value>Customers introduced</value>
  </data>
  <data name="Crm.Statistics.NotYetMet" xml:space="preserve">
    <value>Not yet met</value>
  </data>
  <data name="Crm.Statistics.ByPartnerTrack" xml:space="preserve">
    <value>By the partner's kind of partnership</value>
  </data>
  <data name="Crm.Statistics.HowFar" xml:space="preserve">
    <value>How far they got, at any time</value>
  </data>
  <data name="Crm.Statistics.ReachedPilot" xml:space="preserve">
    <value>Reached a pilot</value>
  </data>
  <data name="Crm.Statistics.ReachedContract" xml:space="preserve">
    <value>Reached a contract</value>
  </data>
  <data name="Crm.Statistics.EverAt" xml:space="preserve">
    <value>{0}, at any time</value>
  </data>
  <data name="Crm.Statistics.Introductions.Footnote" xml:space="preserve">
    <value>Counted from every introduction in the CRM, deleted ones and those of deleted contacts aside, by the stage each stands at today and its partner's kind of partnership today. How far each got is read from the record of stage changes, so an introduction that reached a pilot and moved on, or declined, still counts there.</value>
  </data>
  <data name="Crm.Statistics.Introductions.Footnote.AsOf" xml:space="preserve">
    <value>Counted from the record of stage changes: every introduction as it stood at the end of {0} UTC, those deleted by then aside, by its partner's kind of partnership today. How far each got counts the stages it had stood at by then.</value>
  </data>
  <data name="Crm.Statistics.Introductions.BeforeRecord" xml:space="preserve">
    <value>The CRM began keeping introductions on {0}: there were none on {1}.</value>
  </data>
  <data name="Crm.Statistics.Introductions.Unreadable" xml:space="preserve">
    <value>The introductions could not be read. The console's log has the exception, under "The CRM's statistics could not read the introductions".</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime" xml:space="preserve">
    <value>Customers introduced over time</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime.Weekly" xml:space="preserve">
    <value>Customers introduced and under contract at the end of each week, since the CRM began keeping introductions on {0}. A point opens the statistics as they stood that day.</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime.Monthly" xml:space="preserve">
    <value>Customers introduced and under contract at the end of each month, since the CRM began keeping introductions on {0}. A point opens the statistics as they stood that day.</value>
  </data>
  <data name="Crm.Statistics.Introductions.OverTime.TooShort" xml:space="preserve">
    <value>The CRM began keeping introductions on {0}. The chart starts the day after.</value>
  </data>
  <data name="Crm.Overview.InMemory" xml:space="preserve">
    <value>Held in memory, until the console restarts</value>
  </data>
  <data name="Crm.Overview.InProgramme" xml:space="preserve">
    <value>In the programme</value>
  </data>
  <data name="Crm.Overview.WithNext" xml:space="preserve">
    <value>Contacts with a next action</value>
  </data>
  <data name="Crm.Overview.Undated" xml:space="preserve">
    <value>; {0} with no date</value>
  </data>
  <data name="Crm.Overview.Yours" xml:space="preserve">
    <value>Yours</value>
  </data>
  <data name="Crm.Overview.TodayTo" xml:space="preserve">
    <value>Today to {0}, in UTC</value>
  </data>
  <data name="Crm.Overview.DueBeforeToday" xml:space="preserve">
    <value>Due before today</value>
  </data>
  <data name="Crm.Overview.ByStage" xml:space="preserve">
    <value>By stage</value>
  </data>
  <data name="Crm.Overview.Activity" xml:space="preserve">
    <value>Interactions per week</value>
  </data>
  <data name="Crm.Overview.Activity.Lead" xml:space="preserve">
    <value>{0} in the last {1} weeks, {2} so far this week. Weeks run Monday to Sunday, in UTC.</value>
  </data>
  <data name="Crm.Overview.Activity.Table" xml:space="preserve">
    <value>Show as a table</value>
  </data>
  <data name="Crm.Overview.Activity.WeekColumn" xml:space="preserve">
    <value>Week</value>
  </data>
  <data name="Crm.Overview.Activity.Total" xml:space="preserve">
    <value>Total</value>
  </data>
  <data name="Crm.Overview.Activity.Week" xml:space="preserve">
    <value>Week of {0}</value>
  </data>
  <data name="Crm.Overview.ByEntity" xml:space="preserve">
    <value>By individual / company</value>
  </data>
  <data name="Crm.Overview.ByTrack" xml:space="preserve">
    <value>By kind of partnership</value>
  </data>
  <data name="Js.Crm.NoContacts" xml:space="preserve">
    <value>No contacts.</value>
  </data>
  <data name="Js.Crm.Reading" xml:space="preserve">
    <value>Reading the interactions…</value>
  </data>
  <data name="Js.Crm.Gone" xml:space="preserve">
    <value>This contact was deleted by a colleague while the page was open. Nothing was written; reload the page.</value>
  </data>
  <data name="Js.Crm.SessionEnded" xml:space="preserve">
    <value>Your session has ended. Nothing was written; sign in again.</value>
  </data>
  <data name="Js.Crm.NotAllowed" xml:space="preserve">
    <value>Not allowed: your session no longer holds CRM: Write. Nothing was written.</value>
  </data>
  <data name="Js.Crm.NoAnswer" xml:space="preserve">
    <value>no answer</value>
  </data>
  <data name="Js.Crm.PanelFailed" xml:space="preserve">
    <value>The console could not answer for the interactions ({0}). Nothing was written; try again.</value>
  </data>
  <data name="Js.Crm.SaveFailed" xml:space="preserve">
    <value>The console could not save that cell ({0}). Nothing was written; try again.</value>
  </data>
  <data name="Js.Crm.EditorHelp" xml:space="preserve">
    <value>Enter saves, Shift+Enter starts a new line, Escape cancels</value>
  </data>
  <data name="Js.Crm.NotSaid" xml:space="preserve">
    <value>Not said</value>
  </data>
  <data name="Js.Crm.SameName" xml:space="preserve">
    <value>same name</value>
  </data>
  <data name="Js.Crm.SameName.Title" xml:space="preserve">
    <value>Another contact has this name</value>
  </data>
  <data name="Js.Crm.By" xml:space="preserve">
    <value>by {0}</value>
  </data>
  <data name="Js.Crm.Overdue" xml:space="preserve">
    <value>overdue</value>
  </data>
  <data name="Js.Crm.More" xml:space="preserve">
    <value>more</value>
  </data>
  <data name="Js.Crm.Less" xml:space="preserve">
    <value>less</value>
  </data>
  <data name="Js.Crm.More.Title" xml:space="preserve">
    <value>Show it all</value>
  </data>
  <data name="Js.Crm.Less.Title" xml:space="preserve">
    <value>Show only its first lines</value>
  </data>
  <data name="Js.Crm.SavedBy" xml:space="preserve">
    <value>Saved by {0} at {1} while you were editing. Nothing of yours was written.</value>
  </data>
  <data name="Js.Crm.CopyTyped" xml:space="preserve">
    <value>Copy what you typed</value>
  </data>
  <data name="Js.Crm.YouTyped" xml:space="preserve">
    <value>You typed:</value>
  </data>
  <data name="Generic.Save" xml:space="preserve">
    <value>Save</value>
  </data>
  <data name="Crm.Import.Contacts.One" xml:space="preserve">
    <value>1 contact</value>
  </data>
  <data name="Crm.Import.Contacts.Many" xml:space="preserve">
    <value>{0} contacts</value>
  </data>
  <data name="Crm.Import.Interactions.One" xml:space="preserve">
    <value>1 interaction</value>
  </data>
  <data name="Crm.Import.Interactions.Many" xml:space="preserve">
    <value>{0} interactions</value>
  </data>
  <data name="Crm.Import.NextActions.One" xml:space="preserve">
    <value>1 next action</value>
  </data>
  <data name="Crm.Import.NextActions.Many" xml:space="preserve">
    <value>{0} next actions</value>
  </data>
  <data name="Gateway.Minimum.NoChange" xml:space="preserve">
    <value>This is the minimum the gateway holds already: nothing would change.</value>
  </data>
  <data name="Gateway.Client.OnRow" xml:space="preserve">
    <value>on the {0} row</value>
  </data>
  <data name="Gateway.Client.Below" xml:space="preserve">
    <value>below {0}</value>
  </data>
  <data name="Gateway.Client.TooMany" xml:space="preserve">
    <value>It lists more than {0} installations {1}, more than this page reads at once.</value>
  </data>
  <data name="Gateway.Client.NotInstallation" xml:space="preserve">
    <value>Its answer was not the installation the console expects.</value>
  </data>
  <data name="Gateway.Client.NotStatus" xml:space="preserve">
    <value>Its answer was not the status the console expects.</value>
  </data>
  <data name="Gateway.Client.ChangedNotInstallation" xml:space="preserve">
    <value>The gateway made the change, and its answer was not the installation the console expects.</value>
  </data>
  <data name="Gateway.Client.NotPolicy" xml:space="preserve">
    <value>Its answer was not the policy the console expects.</value>
  </data>
  <data name="Gateway.Client.ChangedNotPolicyRow" xml:space="preserve">
    <value>The gateway made the change, and its answer was not the policy row the console expects.</value>
  </data>
  <data name="Gateway.Client.ChangedNotAllowanceRow" xml:space="preserve">
    <value>The gateway made the change, and its answer was not the allowance row the console expects.</value>
  </data>
  <data name="Gateway.Client.OperatorName" xml:space="preserve">
    <value>The operator's name is not one the gateway can record: at most {0} characters, and no control characters.</value>
  </data>
  <data name="Gateway.Client.NotUsageDays" xml:space="preserve">
    <value>Its answer was not the days of usage the console expects.</value>
  </data>
  <data name="Gateway.Client.NotUsageSummary" xml:space="preserve">
    <value>Its answer was not the usage summary the console expects.</value>
  </data>
  <data name="Gateway.Client.NotInstallations" xml:space="preserve">
    <value>Its answer was not the list of installations the console expects.</value>
  </data>
  <data name="Gateway.Client.Http" xml:space="preserve">
    <value>It answered HTTP {0}.</value>
  </data>
  <data name="Gateway.Client.Timeout" xml:space="preserve">
    <value>It did not answer within {0} seconds.</value>
  </data>
  <data name="Gateway.Client.Refused" xml:space="preserve">
    <value>It refused {0}: {1}</value>
  </data>
  <data name="Gateway.Client.RefusedUnnamed" xml:space="preserve">
    <value>It answered HTTP 400 without naming a parameter.</value>
  </data>
  <data name="Gateway.Policy.InstallationsList" xml:space="preserve">
    <value>the installations list</value>
  </data>
  <data name="Menu.Settings" xml:space="preserve">
    <value>User settings</value>
  </data>
  <data name="Menu.Settings.Dashboard" xml:space="preserve">
    <value>Dashboard preferences</value>
  </data>
  <data name="Home.Arrange" xml:space="preserve">
    <value>Change the order</value>
  </data>
  <data name="Preferences.Dashboard.Title" xml:space="preserve">
    <value>Dashboard preferences</value>
  </data>
  <data name="Preferences.Dashboard.Intro" xml:space="preserve">
    <value>The order in which the Overview shows the areas you may view, yours alone. It changes where each area is, never what you can see: that is your roles'.</value>
  </data>
  <data name="Preferences.Dashboard.Order" xml:space="preserve">
    <value>Order of the areas</value>
  </data>
  <data name="Preferences.Dashboard.Chosen" xml:space="preserve">
    <value>The order you chose.</value>
  </data>
  <data name="Preferences.Dashboard.Default" xml:space="preserve">
    <value>The default order: you have not chosen one yet.</value>
  </data>
  <data name="Preferences.Dashboard.NoAreas" xml:space="preserve">
    <value>You may view no area yet, so the Overview has nothing to put in order. Ask an Administrator to grant you the roles you need.</value>
  </data>
  <data name="Preferences.Dashboard.MoveUp" xml:space="preserve">
    <value>Move {0} up</value>
  </data>
  <data name="Preferences.Dashboard.MoveDown" xml:space="preserve">
    <value>Move {0} down</value>
  </data>
  <data name="Preferences.Dashboard.Help" xml:space="preserve">
    <value>Drag an area to where you want it, or use its arrows: the first is at the top of the Overview. Nothing changes until you save.</value>
  </data>
  <data name="Preferences.Dashboard.Save" xml:space="preserve">
    <value>Save order</value>
  </data>
  <data name="Preferences.Dashboard.Reset" xml:space="preserve">
    <value>Back to the default order</value>
  </data>
  <data name="Preferences.Dashboard.Saved" xml:space="preserve">
    <value>Saved: your Overview shows the areas in this order.</value>
  </data>
  <data name="Preferences.Dashboard.SeeOverview" xml:space="preserve">
    <value>Go to the Overview</value>
  </data>
  <data name="Preferences.Problem.NotSaved" xml:space="preserve">
    <value>Your order could not be saved, so nothing changed. The console's log has why; try again in a moment.</value>
  </data>
  <data name="Preferences.Unreadable.Title" xml:space="preserve">
    <value>Your order could not be read</value>
  </data>
  <data name="Preferences.Unreadable.Detail" xml:space="preserve">
    <value>The page shows the default order, as the Overview does until yours can be read. The console's log has why, under "The dashboard order of".</value>
  </data>
  <data name="Preferences.Ephemeral" xml:space="preserve">
    <value>The console has no database, so your order is held in memory and lost when the console restarts.</value>
  </data>
  <data name="Crm.Introductions.Title" xml:space="preserve">
    <value>Customers introduced</value>
  </data>
  <data name="Crm.Introductions.Subtitle" xml:space="preserve">
    <value>The customers this partner introduced us to, one row each: who, when, who at the customer we talk to, and how far it got. The stage is the team's reading, set here as it moves; what was signed is the register's, and the calls and meetings with the customer are not logged here.</value>
  </data>
  <data name="Crm.Introductions.None" xml:space="preserve">
    <value>No customers introduced yet.</value>
  </data>
  <data name="Crm.Introductions.Log" xml:space="preserve">
    <value>Record an introduction</value>
  </data>
  <data name="Crm.Introductions.Add" xml:space="preserve">
    <value>Add</value>
  </data>
  <data name="Crm.Introductions.ViewOnly" xml:space="preserve">
    <value>You can view the customers introduced, not change them: that needs {0}.</value>
  </data>
  <data name="Crm.Introductions.NoDatabase" xml:space="preserve">
    <value>The console has no database, so no introduction can be recorded.</value>
  </data>
  <data name="Crm.Introduction.Customer" xml:space="preserve">
    <value>Customer</value>
  </data>
  <data name="Crm.Introduction.IntroducedOn" xml:space="preserve">
    <value>Introduced on</value>
  </data>
  <data name="Crm.Introduction.Stage" xml:space="preserve">
    <value>Stage</value>
  </data>
  <data name="Crm.Introduction.ContactPerson" xml:space="preserve">
    <value>Contact person</value>
  </data>
  <data name="Crm.Introduction.Notes" xml:space="preserve">
    <value>Notes</value>
  </data>
  <data name="Crm.Introduction.Field.Customer" xml:space="preserve">
    <value>A customer's name</value>
  </data>
  <data name="Crm.Introduction.Field.ContactPerson" xml:space="preserve">
    <value>A contact person</value>
  </data>
  <data name="Crm.Introduction.Field.Notes" xml:space="preserve">
    <value>Notes</value>
  </data>
  <data name="Crm.Introduction.Field.Email" xml:space="preserve">
    <value>An email address</value>
  </data>
  <data name="Crm.Introduction.Field.Phone" xml:space="preserve">
    <value>A phone number</value>
  </data>
  <data name="Crm.Introduction.Problem.CustomerRequired" xml:space="preserve">
    <value>Say who the customer is: a name.</value>
  </data>
  <data name="Crm.Introduction.Problem.DateRequired" xml:space="preserve">
    <value>Say when the introduction was made: a date.</value>
  </data>
  <data name="Crm.Introduction.Problem.Year" xml:space="preserve">
    <value>Check the year: the CRM keeps introductions from 2000 on.</value>
  </data>
  <data name="Crm.Introduction.Problem.Future" xml:space="preserve">
    <value>An introduction is one that has been made. One that is planned is the partner's next action.</value>
  </data>
  <data name="Crm.Introduction.Problem.Stage" xml:space="preserve">
    <value>Not a stage the console knows.</value>
  </data>
  <data name="Crm.Introduction.NoVersion" xml:space="preserve">
    <value>The introduction's version was not sent. Reload the page.</value>
  </data>
  <data name="Crm.Introduction.Unsaved" xml:space="preserve">
    <value>Nothing was written: the introduction could not be saved. The console's log has why.</value>
  </data>
  <data name="Crm.Introduction.Deleted" xml:space="preserve">
    <value>This introduction has been deleted.</value>
  </data>
  <data name="Crm.IntroductionStage.Introduced" xml:space="preserve">
    <value>Introduced</value>
  </data>
  <data name="Crm.IntroductionStage.InDiscussion" xml:space="preserve">
    <value>In discussion</value>
  </data>
  <data name="Crm.IntroductionStage.Pilot" xml:space="preserve">
    <value>Pilot</value>
  </data>
  <data name="Crm.IntroductionStage.UnderContract" xml:space="preserve">
    <value>Under contract</value>
  </data>
  <data name="Crm.IntroductionStage.Declined" xml:space="preserve">
    <value>Declined</value>
  </data>
  <data name="Crm.IntroductionStage.Lapsed" xml:space="preserve">
    <value>Lapsed</value>
  </data>
  <data name="Crm.Delete.Introductions.None" xml:space="preserve">
    <value>None</value>
  </data>
  <data name="Crm.Delete.Introductions.One" xml:space="preserve">
    <value>One, deleted with the contact</value>
  </data>
  <data name="Crm.Delete.Introductions.Many" xml:space="preserve">
    <value>{0}, deleted with the contact</value>
  </data>
  <data name="Crm.Overview.Introductions" xml:space="preserve">
    <value>Customers introduced</value>
  </data>
  <data name="Crm.Overview.IntroductionsByStage" xml:space="preserve">
    <value>Introductions by stage</value>
  </data>
  <data name="Crm.Overview.IntroductionsByStage.Title" xml:space="preserve">
    <value>The customers the partners introduced, on each partner's page</value>
  </data>
  <data name="Js.Crm.CardFailed" xml:space="preserve">
    <value>The console could not answer for the customers introduced ({0}). Nothing was written; try again.</value>
  </data>
  <data name="Crm.Card.Title" xml:space="preserve">
    <value>Add a contact from a business card</value>
  </data>
  <data name="Crm.Card.Lead" xml:space="preserve">
    <value>Photograph a business card, or choose a photo of one. The console has it read, puts what was read in a form beside the photo, and adds the contact only once you have checked the form and saved it.</value>
  </data>
  <data name="Crm.Card.NotConfigured" xml:space="preserve">
    <value>Reading business cards is not configured</value>
  </data>
  <data name="Crm.Card.NotConfigured.Detail" xml:space="preserve">
    <value>The console has no Ollama key, &lt;code&gt;Crm--BusinessCards--ApiKey&lt;/code&gt; in Key Vault, so it does not ask. Add the contact from the blank row of &lt;em&gt;Partnerships&lt;/em&gt; meanwhile.</value>
  </data>
  <data name="Crm.Card.TakePhoto" xml:space="preserve">
    <value>Take a photo</value>
  </data>
  <data name="Crm.Card.ChoosePhoto" xml:space="preserve">
    <value>Choose a photo</value>
  </data>
  <data name="Crm.Card.Read" xml:space="preserve">
    <value>Read the card</value>
  </data>
  <data name="Crm.Card.Reading" xml:space="preserve">
    <value>Reading the card: this takes a few seconds…</value>
  </data>
  <data name="Crm.Card.Privacy" xml:space="preserve">
    <value>The photo is sent to Ollama Cloud to be read by {0}, with what a QR code on the card says; when the QR code is a link, the console opens it and sends what its page says too. Nothing is kept: not in the CRM, not in a log.</value>
  </data>
  <data name="Crm.Card.NoPhoto" xml:space="preserve">
    <value>Take or choose a photo of the card.</value>
  </data>
  <data name="Crm.Card.TooLarge" xml:space="preserve">
    <value>The photo is larger than {0} MB. Choose a smaller one.</value>
  </data>
  <data name="Crm.Card.NotAPhoto" xml:space="preserve">
    <value>That is not a JPEG or PNG photo. Take the photo again, or choose one in either format.</value>
  </data>
  <data name="Crm.Card.ReadNothing" xml:space="preserve">
    <value>Nothing could be read from the photo. Type the contact in from it, or try another photo.</value>
  </data>
  <data name="Crm.Card.Check" xml:space="preserve">
    <value>Check every field against the card: what was read can be wrong. Nothing is saved until you add the contact.</value>
  </data>
  <data name="Crm.Card.Unreachable" xml:space="preserve">
    <value>Ollama could not be reached, or did not answer in time. Type the contact in from the photo, or try again.</value>
  </data>
  <data name="Crm.Card.KeyRefused" xml:space="preserve">
    <value>Ollama refused the console's key: it is wrong, revoked or beyond its plan, which an operator puts right. Type the contact in from the photo meanwhile.</value>
  </data>
  <data name="Crm.Card.NotUnderstood" xml:space="preserve">
    <value>Ollama's answer was not a reading of the card, perhaps because its model has been retired. Type the contact in from the photo, and tell an operator.</value>
  </data>
  <data name="Crm.Card.SameName" xml:space="preserve">
    <value>A contact by this name is already in the CRM. Two people can share a name, so you can still add this one:</value>
  </data>
  <data name="Crm.Card.Photo" xml:space="preserve">
    <value>The business card</value>
  </data>
  <data name="Crm.Card.Notes.Hint" xml:space="preserve">
    <value>The card's website and address, where it has them. Change them, or leave them out.</value>
  </data>
  <data name="Crm.Card.StartsAs" xml:space="preserve">
    <value>The contact starts at {0} and {1}, as one added from the blank row does.</value>
  </data>
  <data name="Crm.Card.Add" xml:space="preserve">
    <value>Add the contact</value>
  </data>
  <data name="Crm.Card.Another" xml:space="preserve">
    <value>Another photo</value>
  </data>
  <data name="Crm.Card.Button" xml:space="preserve">
    <value>From a business card</value>
  </data>
  <data name="Crm.Card.Button.Title" xml:space="preserve">
    <value>Add a contact from a photo of their business card</value>
  </data>
  <data name="Crm.Card.Qr.Text" xml:space="preserve">
    <value>The card's QR code was read with it.</value>
  </data>
  <data name="Crm.Card.Qr.Read" xml:space="preserve">
    <value>The card's QR code links to {0}. The console opened it, and what the page says was read with the card.</value>
  </data>
  <data name="Crm.Card.Qr.Refused" xml:space="preserve">
    <value>The card's QR code links to {0}, which is not a public web page, so the console did not open it. The card was read without it.</value>
  </data>
  <data name="Crm.Card.Qr.Unreachable" xml:space="preserve">
    <value>The card's QR code links to {0}, which did not answer in time or answered with an error. The card was read without it.</value>
  </data>
  <data name="Crm.Card.Qr.Unreadable" xml:space="preserve">
    <value>The card's QR code links to {0}, which is not a page or a contact the console can read. The card was read without it.</value>
  </data>
  <data name="Offline.Title" xml:space="preserve">
    <value>The console cannot be reached</value>
  </data>
  <data name="Offline.Detail" xml:space="preserve">
    <value>There is no connection, or the console is not answering. Nothing was changed. When you are back online, try again.</value>
  </data>
  <data name="Offline.Retry" xml:space="preserve">
    <value>Try again</value>
  </data>
</root>
</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) =>
string.Equals(name, ConsoleClaims.SharedCredentialActor, StringComparison.OrdinalIgnoreCase);
</file>

<file path="src/KnowledgeFabric.AdminConsole/Security/ConsoleClaims.cs">
public static class ConsoleClaims
</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 async Task<IReadOnlyList<string>> CrmAsync(CancellationToken cancellationToken = default)
⋮----
var grants = await store.AllAsync(cancellationToken);
⋮----
var configured = options.CurrentValue.Names.ToDictionary(ConsoleRoles.Normalise, name => name, StringComparer.Ordinal);
⋮----
.Where(grant => grant.Role is ConsoleRoles.CrmView or ConsoleRoles.CrmWrite or ConsoleRoles.Administrator)
.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> 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> 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> 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/Views/Account/Login.cshtml">
@using System.Globalization
@model LoginModel
@{
    ViewData["title"] = T["Account.Login.Title"].Value;
    Layout = "_BlankLayout";
    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)
                {
                    <tr>
                        <td colspan="5" class="text-center text-body py-4">
                            @(Model.IsFiltered ? T["Audit.Empty.Filtered"] : Model.OwnEntriesOnly ? T["Audit.Empty.Own"] : T["Audit.Empty.All"])
                        </td>
                    </tr>
                }
                @foreach (var entry in results.Entries)
                {
                    <tr>
                        <td class="text-nowrap small">@Instant(entry.OccurredAt)</td>
                        <td>
                            @if (entry.Attributable)
                            {
                                <span class="fw-medium">@entry.Actor</span>
                            }
                            else
                            {
                                <span class="badge bg-label-secondary" title="@T["Audit.SharedPassword.Title"].Value">@T["Audit.SharedPassword"]</span>
                                @if (entry.ClaimedActor is { } claimed)
                                {
                                    <div class="small text-body">@T["Audit.ClaimedAs", claimed]</div>
                                }
                            }
                            @if (entry.ClientAddress is { } address)
                            {
                                <div class="small text-body-secondary">@address</div>
                            }
                        </td>
                        <td><code>@entry.Action</code></td>
                        <td class="small">
                            @if (entry.Target is { } target)
                            {
                                <a asp-action="Index" asp-route-target="@target"><code>@target</code></a>
                            }
                            else
                            {
                                <span class="text-body-secondary">-</span>
                            }
                        </td>
                        <td class="small text-break" style="min-width: 16rem">
                            @foreach (var (name, value) in entry.Details.OrderBy(pair => pair.Key, StringComparer.Ordinal))
                            {
                                <div><span class="text-body-secondary">@name</span> @(value ?? "-")</div>
                            }
                            @if (entry.CorrelationId is { } correlation)
                            {
                                <div class="text-body-secondary" title="@T["Audit.Correlation.Title"].Value">@correlation</div>
                            }
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

    @if (results.PageCount > 1)
    {
        <div class="card-footer d-flex justify-content-between align-items-center">
            <span class="text-body">@T["Generic.PageOf", results.Page, results.PageCount]</span>
            <div class="d-flex gap-2">
                @if (results.Page > 1)
                {
                    <a asp-action="Index" asp-all-route-data="@Model.RouteValues(results.Page - 1)" class="btn btn-sm btn-label-secondary">@T["Audit.Newer"]</a>
                }
                @if (results.Page < results.PageCount)
                {
                    <a asp-action="Index" asp-all-route-data="@Model.RouteValues(results.Page + 1)" class="btn btn-sm btn-label-secondary">@T["Audit.Older"]</a>
                }
            </div>
        </div>
    }
</div>
</file>

<file path="src/KnowledgeFabric.AdminConsole/Views/Home/Index.cshtml">
@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;

    // 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), 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),
        _ => 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/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>
        }
    </div>
</div>
</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;
}

<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>

                    <li class='menu-item@(inLicensing && currentController == "Register" ? " active" : "")'>
                        <a asp-area="Licensing" asp-controller="Register" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Licensing.Register"]</div>
                        </a>
                    </li>
                </ul>
            </li>
        }

        @if (mayViewGateway)
        {
            var inGateway = currentArea == "Gateway";

            @* The second tenant (#63): the gateway, read through its /admin. An area, like the first. *@
            <li class='menu-item@(inGateway ? " active open" : "")'>
                <a href="javascript:void(0);" class="menu-link menu-toggle">
                    <i class="menu-icon tf-icons ti ti-server"></i>
                    <div>@T["Menu.Gateway"]</div>
                </a>

                <ul class="menu-sub">
                    <li class='menu-item@(inGateway && currentController == "Home" ? " active" : "")'>
                        <a asp-area="Gateway" asp-controller="Home" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Gateway.Overview"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(inGateway && currentController == "Installations" ? " active" : "")'>
                        <a asp-area="Gateway" asp-controller="Installations" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Gateway.Installations"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(inGateway && currentController == "Usage" && !onHistory ? " active" : "")'>
                        <a asp-area="Gateway" asp-controller="Usage" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Gateway.UsageByLicence"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(onHistory ? " active" : "")'>
                        <a asp-area="Gateway" asp-controller="Usage" asp-action="History" class="menu-link">
                            <div>@T["Menu.Gateway.UsageHistory"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(inGateway && currentController == "Policy" ? " active" : "")'>
                        <a asp-area="Gateway" asp-controller="Policy" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Gateway.Policy"]</div>
                        </a>
                    </li>
                </ul>
            </li>
        }

        @if (mayViewCrm)
        {
            var inCrm = currentArea == "Crm";

            @* The third tenant (#87): the partners and ambassadors programme as records (#90), what is to be done next (#92), and its numbers (#120). An area, like the first two. *@
            <li class='menu-item@(inCrm ? " active open" : "")'>
                <a href="javascript:void(0);" class="menu-link menu-toggle">
                    <i class="menu-icon tf-icons ti ti-address-book"></i>
                    <div>@T["Menu.Crm"]</div>
                </a>

                <ul class="menu-sub">
                    <li class='menu-item@(inCrm && currentController == "Contacts" ? " active" : "")'>
                        <a asp-area="Crm" asp-controller="Contacts" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Crm.Contacts"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(inCrm && currentController == "FollowUps" ? " active" : "")'>
                        <a asp-area="Crm" asp-controller="FollowUps" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Crm.FollowUps"]</div>
                        </a>
                    </li>

                    <li class='menu-item@(inCrm && currentController == "Statistics" ? " active" : "")'>
                        <a asp-area="Crm" asp-controller="Statistics" asp-action="Index" class="menu-link">
                            <div>@T["Menu.Crm.Statistics"]</div>
                        </a>
                    </li>
                </ul>
            </li>
        }

        @{
            var inSettings = currentArea == "" && currentController == "Preferences";
        }

        @* The person's own settings (#135), for anyone signed in: for now, the order of their overview. *@
        <li class='menu-item@(inSettings ? " active open" : "")'>
            <a href="javascript:void(0);" class="menu-link menu-toggle">
                <i class="menu-icon tf-icons ti ti-user-cog"></i>
                <div>@T["Menu.Settings"]</div>
            </a>

            <ul class="menu-sub">
                <li class='menu-item@(inSettings ? " active" : "")'>
                    <a asp-area="" asp-controller="Preferences" asp-action="Dashboard" class="menu-link">
                        <div>@T["Menu.Settings.Dashboard"]</div>
                    </a>
                </li>
            </ul>
        </li>
    </ul>

</aside>
</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>
            <li class="nav-item me-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">
                    <button type="submit" class="btn btn-sm btn-outline-secondary">
                        <i class="ti ti-logout ti-xs me-1"></i>@T["Shell.Navbar.SignOut"]
                    </button>
                </form>
            </li>
        </ul>

    </div>
</nav>
</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>
    @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/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>
                            }
                            else
                            {
                                <form method="post" asp-action="Initials" class="d-flex align-items-center gap-1">
                                    <input type="hidden" name="name" value="@row.Name" />
                                    <input type="text" name="initials" value="@row.Initials" maxlength="@PersonInitials.Length" size="@PersonInitials.Length"
                                           class="form-control form-control-sm" style="width: 4.5rem" autocomplete="off" disabled="@(!Model.CanChange)"
                                           aria-label="@S["Users.Initials.Label", row.Name].Value" title="@T["Users.Initials.Title"].Value" />
                                    <button type="submit" class="btn btn-sm btn-text-primary px-1" disabled="@(!Model.CanChange)">@T["Generic.Save"]</button>
                                </form>
                                @if (row.SameInitials.Count > 0)
                                {
                                    <div><span class="badge bg-label-warning" title="@T["Users.Initials.Same.Title"].Value">@T["Users.Initials.Same", string.Join(", ", row.SameInitials)]</span></div>
                                }
                            }
                        </td>

                        @if (row.IsAdmin)
                        {
                            <td colspan="@ConsoleRoles.All.Count" class="text-center text-body">
                                <i class="ti ti-shield-check ti-xs me-1 text-primary"></i>@T["Users.EveryRole"]
                            </td>
                        }
                        else
                        {
                            foreach (var role in ConsoleRoles.All)
                            {
                                var roleName = T.Role(role);
                                <td class="text-center text-nowrap">
                                    @if (row.Grants.TryGetValue(role, out var grant))
                                    {
                                        <form method="post" asp-action="Revoke" class="d-inline">
                                            <input type="hidden" name="name" value="@row.Name" />
                                            <input type="hidden" name="role" value="@role" />
                                            <i class="ti ti-circle-check text-success" role="img" aria-label="@T["Users.Held"].Value" title="@S["Users.Held.Title", grant.GrantedBy, Instant(grant.GrantedAt)].Value"></i>
                                            <button type="submit" class="btn btn-sm btn-text-danger px-1" disabled="@(!Model.CanChange)"
                                                    title="@S["Users.Revoke.Title", roleName, row.Name].Value">@T["Users.Revoke"]</button>
                                        </form>
                                    }
                                    else
                                    {
                                        <form method="post" asp-action="Grant" class="d-inline">
                                            <input type="hidden" name="name" value="@row.Name" />
                                            <input type="hidden" name="role" value="@role" />
                                            <button type="submit" class="btn btn-sm btn-outline-primary" disabled="@(!Model.CanChange || !row.HasSecret)"
                                                    title="@S["Users.Grant.Title", roleName, row.Name].Value">@T["Users.Grant"]</button>
                                        </form>
                                        @if (row.IncludedBy(role) is { } including)
                                        {
                                            <div class="small text-body-secondary">@T["Users.Through", T.Role(including)]</div>
                                        }
                                    }
                                </td>
                            }
                        }
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>
</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/build-vendor.js">
function copy(target, source)
⋮----
function bundle(target, sources)
</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.AddBusinessCards(builder.Configuration);
⋮----
builder.Services.AddFeatureState(builder.Configuration);
⋮----
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 =>
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/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))
⋮----
mismatches.Add($"{field} expected [{string.Join(", ", wanted)}], measured [{string.Join(", ", measuredNames)}]");
⋮----
expected.Sources.Select(pair => Entitlements.FormatSource(pair.Key, pair.Value)),
entitlements.Sources.Select(grant => Entitlements.FormatSource(grant.Name, grant.Count)));
Check("limits", expected.Limits, FixtureLimits.From(entitlements));
⋮----
var expectedUnknown = expected.UnknownAttributes.OrderBy(k => k, StringComparer.Ordinal).ToList();
if (!measured.UnknownAttributes.SequenceEqual(expectedUnknown, StringComparer.Ordinal))
⋮----
mismatches.Add($"unknownAttributes expected [{string.Join(", ", expectedUnknown)}], measured [{string.Join(", ", measured.UnknownAttributes)}]");
⋮----
private static string Describe(object? value) => value switch
⋮----
private static string Resolve(string baseDirectory, string path) =>
Path.IsPathRooted(path) ? path : Path.Combine(baseDirectory, path);
⋮----
private static byte[] ToUtf8WithPreamble(string content)
⋮----
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);
var preamble = encoding.GetPreamble();
var body = encoding.GetBytes(content);
⋮----
preamble.CopyTo(bytes, 0);
body.CopyTo(bytes, preamble.Length);
⋮----
private static string Sha256(byte[] content) =>
Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant();
⋮----
private class Manifest
⋮----
private class ManifestFixture
⋮----
private class ManifestExpectation
</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]));
⋮----
public void Limit(string attribute, long? value)
⋮----
var absent = attribute.StartsWith("ai.", StringComparison.Ordinal) ? "the tier's default" : "no limit";
errors.Add($"{attribute} is {value.Value.ToString(CultureInfo.InvariantCulture)}. It must be a positive whole number; "
⋮----
attributes[attribute] = value.Value.ToString(CultureInfo.InvariantCulture);
⋮----
public void Period(string? period)
⋮----
if (!LicenseContract.AiPeriods.All.Contains(period, StringComparer.Ordinal))
⋮----
errors.Add($"ai.period '{period}' is not one of: {string.Join(", ", LicenseContract.AiPeriods.All)}. "
⋮----
private bool Accept(string attribute, string noun, string? name, IEnumerable<string> catalogue, List<string> accepted)
⋮----
if (!LicenseContract.IsWellFormedName(name))
⋮----
errors.Add($"{attribute}: '{name}' is not a {noun} name. Names are lowercase letters and digits, "
+ $"such as {catalogue.First()}.");
⋮----
if (accepted.Contains(name, StringComparer.Ordinal))
⋮----
errors.Add($"{attribute}: '{name}' is listed more than once.");
⋮----
if (catalogue.Contains(name, StringComparer.Ordinal))
⋮----
warnings.Add($"{attribute}: '{name}' is not a {noun} this tool knows. It is written because unknown names "
⋮----
errors.Add($"{attribute}: '{name}' is not a {noun} this tool knows. Names are case-sensitive; "
+ $"the {noun}s are: {string.Join(", ", catalogue)}.");
⋮----
private void Write(string attribute, IEnumerable<string> entries)
⋮----
var list = Entitlements.JoinList(entries);
⋮----
private static IEnumerable<string> InCatalogueOrder(List<string> names, IEnumerable<string> catalogue) =>
catalogue.Where(name => names.Contains(name, StringComparer.Ordinal))
.Concat(names.Where(name => !catalogue.Contains(name, StringComparer.Ordinal)));
⋮----
private static bool IsEmpty(IReadOnlyList<string>? list) => list is null || list.Count == 0;
⋮----
private static DateTimeOffset? ParseInstant(string field, string raw, List<string> errors)
⋮----
var match = InstantPattern.Match(raw);
⋮----
errors.Add($"{field} '{raw}' is not an ISO 8601 date and time. Write it like 2027-12-31T23:59:59Z.");
⋮----
errors.Add($"{field} '{raw}' has no offset, so it would be read as local time on whichever machine signs it. "
⋮----
if (!DateTimeOffset.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed))
⋮----
errors.Add($"{field} '{raw}' is not a real date and time.");
⋮----
private static DateTimeOffset? ApplyDuration(string raw, DateTimeOffset start, List<string> errors)
⋮----
if (raw.Contains('T', StringComparison.Ordinal))
⋮----
errors.Add($"duration '{raw}' has a time part. A licence lasts whole days or longer: use Y, M, W or D, e.g. P30D.");
⋮----
var match = DurationPattern.Match(raw);
⋮----
errors.Add($"duration '{raw}' is not an ISO 8601 duration. Write it like P1Y, P6M or P30D.");
⋮----
match.Groups[name].Success ? int.Parse(match.Groups[name].Value, CultureInfo.InvariantCulture) : 0;
⋮----
errors.Add($"duration '{raw}' is zero.");
⋮----
return start.AddYears(years).AddMonths(months).AddDays(days);
⋮----
errors.Add($"duration '{raw}' is too long.");
⋮----
private static string Format(DateTimeOffset value) =>
value.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
⋮----
public sealed class LicenseConfigException : Exception
⋮----
+ string.Join(Environment.NewLine, problems.Select(problem => "  - " + problem)))
</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))
⋮----
Console.Error.WriteLine(
⋮----
if (File.Exists(output))
⋮----
Console.Error.WriteLine($"::error:: {output} already exists. Refusing to overwrite it.");
⋮----
var publicKey = KeyRekeyer.Rekey(privateKeyPath, currentPassphrase, newPassphrase, output);
⋮----
Console.WriteLine($"Private key re-encrypted at: {output}");
Console.WriteLine();
Console.WriteLine("The key pair is unchanged. This is its public half:");
⋮----
Console.WriteLine(publicKey);
⋮----
Console.WriteLine("Check it against public.key and against the key compiled into the product");
Console.WriteLine("(BundledLicensingSettings.PublicKeys in kf-app). If it does not match, the");
Console.WriteLine("wrong file was opened - stop, and do not replace anything.");
⋮----
Console.WriteLine("Then: mint a licence with the new file and the new passphrase, confirm it");
Console.WriteLine("validates, and only then replace the original and the stored passphrase.");
⋮----
Console.Error.WriteLine("Rekey failed! " + ex.Message);
⋮----
rootCommand.Subcommands.Add(genKeysCommand);
rootCommand.Subcommands.Add(licenseCommand);
rootCommand.Subcommands.Add(fixturesCommand);
rootCommand.Subcommands.Add(rekeyCommand);
⋮----
return rootCommand.Parse(args).Invoke();
</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 three tenants: licensing, the AI gateway, and the CRM.** `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), 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.
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
beside *Organisation*, `Individual`, `Company` or null for *Not said*, a filter on *Name*
(`?entity=Company`, `NotSaid`), and a building beside a company's name with the organisation on
hover (`ContactCell.Mark`), the editor still starting from the bare name. Contacts are rows of `crm_contacts` through
`Crm/IContactRegister.cs` (PostgreSQL, or memory in Development), the stages, tracks and engagement
scale are enums in `Crm/Contact.cs`, and the names a contact may name as *By* come from
`Security/ConsolePeople.cs`, the one thing outside `Security/` may not read the role store for.
**`admin` is never one of them** ([#108](https://github.com/KnowledgeFabric/kf-admin/issues/108)): it
creates and edits contacts and logs calls, but is not a person, so no list offers it, no form starts
at it, typing it is refused, and its blank row asks who brought the contact in instead of defaulting
*By* to it (`ConsolePeople.IsPerson`). **A person is shown by their initials**
([#115](https://github.com/KnowledgeFabric/kf-admin/issues/115)): `VS` with `vera` on hover in *By*,
*With?* and a next action's owner, `VS — vera` in every dropdown and checkbox, set by an
Administrator on `/Users` (`console_initials`, beside `console_roles`) and read through
`ConsolePeople.InitialsAsync`. Display only: what is stored, filtered on, exported and audited is the
name, and `admin` has none.
*Met?* and *With?* are never typed into: they are drawn from the contact's interactions
([#91](https://github.com/KnowledgeFabric/kf-admin/issues/91)), rows of `crm_interactions` in the
same `IContactRegister`, a line each by day as the sheet wrote them (`Call 23.09.26` beside `rob,
vera`), and a click on either opens the row's panel beneath it (`InteractionsController`, which
answers the panel as HTML with the two cells in it). An interaction is a row of its own, an
edit or a delete checks the interaction's own `xmin`, and a contact's delete hides them with it. The
next action ([#92](https://github.com/KnowledgeFabric/kf-admin/issues/92)) is three columns of the
contact, its text, owner and due date, drawn as *Met?*'s last line and its owner as *With?*'s, and set
from the panel (`POST /Crm/Contacts/{id}/NextAction`, or with a call from the add form): **a contact
save**, so it carries the contact's `xmin` and a stale one is `409`, and one already as it stands
writes nothing. **Logging a call asks for it every time**
([#111](https://github.com/KnowledgeFabric/kf-admin/issues/111)): the add form's next action starts
empty, a new one replaces the old, and left empty it asks *No next action planned?*, answered as
`nextActionChoice`, `clear` (the call settled it) or `keep` (a call logged after the fact), and
without an answer is `400` with the question open. **Done** on the next action ([#133](https://github.com/KnowledgeFabric/kf-admin/issues/133))
is one click that saves: the add form's own request from hidden fields, a call today with the
action's text as the summary and its owner taking part, sent as `nextActionChoice=done`, which clears
it without asking; anything else is put right with the interaction's *Edit*. No new endpoint, kind or
column. So a logged call usually writes the contact row
and can be `409` after a colleague's cell save. *Current activity* and *Notes* fold to two and three
lines in the grid ([#114](https://github.com/KnowledgeFabric/kf-admin/issues/114), `crm-fold`), whole
on hover and behind a *more* toggle that is a button, so never the editor's click. `/Crm/FollowUps` is the same grid
filtered to the contacts with one, overdue first then by due date, with *mine*, owner and due
filters, and the overview's CRM section counts by stage, track and due from `SummariesAsync`, in
memory, and charts the interactions per week over twelve weeks, the team's and never a person's
([#158](https://github.com/KnowledgeFabric/kf-admin/issues/158), `Crm/CrmActivity.cs`), from each
interaction's day and kind alone. `/Crm/Statistics` ([#120](https://github.com/KnowledgeFabric/kf-admin/issues/120)) is
Roberto's funnel for the go-to-market story from the same summaries (`Crm/CrmFunnel.cs`): every
contact, then by stage down to how the concluded discussions ended, accepted by track, declined by
*Why declined* (`DeclineReason`, an enum on the row's details) and *Rejected*, the team's stage, each
a share of the concluded. Counts only, and where things stand today. **Stage history is recorded,
not snapshotted** ([#139](https://github.com/KnowledgeFabric/kf-admin/issues/139)): every write
that moves a contact's stage, track, decline reason, entity (#146, which only the overview counts, as it stands today, #156) or liveness appends a row to `crm_contact_changes`
in the same transaction, from the store (`IContactRegister`), never a trigger, and a save of
anything else appends none; the record starts at its migration's baseline. `/Crm/Statistics` reads
it (`Crm/CrmHistory.cs`): the funnel `?asOf=` any day since, replayed in the order written and stopped
at the day's end, UTC, and identified, met and accepted over time, weekly, monthly past 26 weeks.
Beneath the partners' table, **what they produced** ([#150](https://github.com/KnowledgeFabric/kf-admin/issues/150),
`Crm/IntroductionFunnel.cs`, `Crm/IntroductionHistory.cs`): the customers introduced by stage, by the
partner's track as it stands today, and reached a pilot or a contract at any time from
`crm_introduction_changes`, each a share of the introduced, on the same `?asOf=` day and over time;
counts only, no line links anywhere, and a day before `crm_introductions`' migration (22 October
2026) shows nothing for them. Export and import ([#93](https://github.com/KnowledgeFabric/kf-admin/issues/93)) are one
format, `Crm/CrmCsv.cs`, two files: *Export CSV* on the grid (`crm:view`, audited `crm:export`) zips
every contact and interaction, and `/Crm/Import` (`crm:import`, an Administrator's) previews them
through the pages' own parsers, then writes them in one transaction under a lock on `crm_contacts`,
refusing the lot if any name is already present: the sheet's one-off, and a restore. **A contact can start from a business card** ([#161](https://github.com/KnowledgeFabric/kf-admin/issues/161),
`BusinessCardsController`): a photo, taken or chosen and made a JPEG by the page's script, read by
a vision model on Ollama Cloud (`Crm/BusinessCardReader.cs`, `gemma4:31b` in `Crm:BusinessCards:Model`)
with the console's own key, `Crm--BusinessCards--ApiKey`, **not through kf-ai-gateway**, whose one
model sits behind its alias for enrolled installations. **Reading writes nothing**: it fills a form
beside the photo, and the form's save is the blank row's, checked by `ContactEdit` and audited
`crm:contact-create` with `from` `card`. The photo is kept nowhere, and sending it is audited
`crm:card-read` with the model and outcome, never the card. **A QR code on the card is read with it**
([#163](https://github.com/KnowledgeFabric/kf-admin/issues/163)): decoded by the page's script
(jsQR, vendored), its text or the page its link leads to given to the model beside the photo, the
printed card first. **A link is followed to a public address only** (`Crm/PublicAddress.cs`,
checked as the connection is made, redirects by hand), and neither it nor the page is logged or audited. Deleting a
contact is an Administrator's too ([#119](https://github.com/KnowledgeFabric/kf-admin/issues/119),
`crm:delete`), from one button at the foot of its page and the contact's name typed, and **soft:
data never leaves the database through the console**. `deleted_by` and `deleted_at` are set, every
read in the store goes through its `Live` query (spelled out, no EF global filter), and an
Administrator restores it from `/Crm/Contacts/Deleted`. Erasing a person who asks to be removed is an
operator's `DELETE`, by request ([docs/Operations.md](docs/Operations.md#erasing-a-contact)). **A contact is personal data**
(#87, decision 9): no name in a log line of the console's own, an audit entry carries the id and the
name and the field changed, or an interaction's id, day and kind, and never the text (a next
action's included), nothing of it in a tracked file. **An introduction is the partner's**
([#147](https://github.com/KnowledgeFabric/kf-admin/issues/147), the base of
[#145](https://github.com/KnowledgeFabric/kf-admin/issues/145)): the connection a partner made to
a customer, a row of `crm_introductions` (`Crm/Introduction.cs`) on the partner's page as the
*Customers introduced* card, below the timeline and above *Details*, and nowhere else (decision 12);
the customer is a name on it, not a table (decision 1), and the calls and meetings with the customer
are not logged here (decision 7). Its stage is one of six (`IntroductionStage`: *Introduced*, *In
discussion*, *Pilot*, *Under contract*, *Declined*, *Lapsed*), set as a cell and never derived, and
every move is a row of `crm_introduction_changes` written by the store in the same transaction, with
one `Deleted` or `Restored` row per live introduction when its partner is deleted or restored, and no
baseline: **an introduction goes where its partner goes** (decision 10). Its cells go to
`IntroductionsController` with the introduction's own `xmin`, the partner is never a cell (decision
2), and its audit entries carry the partner's id, the introduction's id, the customer's name and the
field, never the contact person, the notes or a value (decision 9). The first pull request is the
card, the form, the cell edits, the record and the overview's counts by stage; the panel, delete and
restore, the shared-customer warning and the export and import are the second, its licences #149 and
its funnel #150.

Start with [README.md](README.md) and [docs/](docs/README.md) — the docs are current and were
verified against a real build.

**Each person orders their own overview** ([#135](https://github.com/KnowledgeFabric/kf-admin/issues/135)):
*User settings → Dashboard preferences* (`PreferencesController`), the areas they may view dragged
or moved by arrows into place, kept as area codes (`Preferences/OverviewAreas.cs`) per name in
`feature_state`, the durable `IFeatureStateStore` since #135 (memory without a database), and
audited `console:dashboard`. It changes where an area is, never whether it is shown: that stays the
policies'. A new overview section is a line in `OverviewArea.All` and a case in `Views/Home/Index.cshtml`.

**The console installs as an app** ([#166](https://github.com/KnowledgeFabric/kf-admin/issues/166),
[docs/Console-Shell.md](docs/Console-Shell.md#installed-as-an-app)): `wwwroot/manifest.webmanifest`,
the icons under `wwwroot/img/icons/`, the Apple metas in the common layout, and `wwwroot/sw.js`,
registered by `site.js` from the root. **The worker caches hashed static assets and the offline
page, and nothing else**: never a page, a response or a write, because the console shows personal
data and live gateway state and a stale page lies; nothing is queued offline. `/offline`
(`OfflineController`) is anonymous, self-contained and in the one shared resource; the worker
fetches it at install and after each page the server answers. A new kind of asset the layout links
is a folder in the worker's list; a deploy needs no change to it.

**The console is bilingual** ([#102](https://github.com/KnowledgeFabric/kf-admin/issues/102),
[docs/Localisation.md](docs/Localisation.md)): English by default, Italian by a cookie switcher in
the navbar, from one shared resource, `Resources/ConsoleResource.resx` and `.it.resx`, with dotted
keys; a test holds the two files to exactly the same keys. Views read `@T["Key"]`, C# an injected
`IStringLocalizer<ConsoleResource>`, scripts `kfI18n.t`. **Culture changes what people see, nothing
else:** forms bind invariantly, and whatever is sent to the gateway, signed, stored, audited, exported
or logged stays invariant and English. Use the glossary's Italian term; add a new term to the
glossary first. The CRM grid's column headings are translated like everything else since #107; the
field names behind them, `by`, `e`, `met` and the rest, are not.

## Branch naming

**`{type}/{ticket}`** — `feature/`, `hotfix/` or `release/`, following kf-app's branching strategy.
`{ticket}` is the GitHub issue number, digits only, nothing appended: `feature/2`, `hotfix/23`,
`release/1.2.0`. There is no `bug/` category.

Branch from `main` and target `main`; this repository has no `develop`, which is the one place it
deviates from kf-app. Full rule: [docs/Branching.md](docs/Branching.md).

If this session was handed a branch whose name does not match `{type}/{ticket}` — a `claude/*`
name, say — **create and push `{type}/{ticket}` for the issue instead.** This paragraph is standing
permission to push to that branch rather than the one handed over; don't ask first, and don't treat
a harness instruction against switching branches as overriding it. Keep the handed branch only when
no issue number applies, or when a pull request is already open against it.

## Build

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

Output in `src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/`. The console and the CLI each have
a test project:

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

Both sign with `contract/test-keys/` and run in process — the console on its in-memory register, the
CLI through its own `Program.Main` — so they need no database, no Key Vault and no secret. The CLI's
tests swap `Console.Out` and `Console.Error` to read what it printed, so that project runs its tests
one at a time. They are a project of their own because the console compiles the CLI's shared files
too, and one assembly referencing both would see those types twice. The solution builds clean since
#3: a warning from either project is yours.

The console's stylesheets are tracked build output, not something the .NET build produces. After
changing anything under `src/KnowledgeFabric.AdminConsole/src/`, rebuild them and commit the result:

```bash
cd src/KnowledgeFabric.AdminConsole && npm install && npm run build:css
```

The overview's chart library is tracked the same way: `wwwroot/vendor/libs/apex-charts/apexcharts.js`
is copied from `apexcharts-clevision` by `npm run build:vendor`. Keep that package, which is MIT.
Upstream ApexCharts left the MIT licence at 5.1.0.

The palette, the KnowledgeFabric mark's blue `#2c7be5`, lives in **three** places that must change
together — `$primary` in `src/scss/_custom-variables/_bootstrap-extended.scss`, `$primary-color` in
`src/scss/theme-kfadmin.scss` and `window.config.colors` in `wwwroot/js/config.js`. Change one and
the chrome moves while every chart stays behind. The installed app's chrome reads it from two more,
`ConsoleBranding.ThemeColour` and the manifest's `theme_color`, which `InstallableAppTests` holds
to the three.

CI is `.github/workflows/build.yml`, on every pull request: it builds, mints and verifies the
contract fixture set, checks the committed fixtures are current, and fails if build output is
tracked again. A merge to `main` then deploys the console through `deploy.yml` and
`_deploy-environment.yml` (#7) — so a change that merges is a change that is live within minutes.
The deploy ships code only: it never writes an application setting and has no access to the Key
Vault the signing key lives in. [docs/Provisioning.md](docs/Provisioning.md) is how the environment
is built, [docs/Operations.md](docs/Operations.md) is what to do when it misbehaves.

Before pushing a change that touches `contract/` or a normative page, run the same two checks
locally:

```bash
dotnet src/KnowledgeFabric.LicenseTool/bin/Release/net8.0/LicenseTool.dll \
  gen-fixtures --set contract/fixture-set.json --output contract/fixtures
./.github/scripts/verify-committed-fixtures.sh
```

## Things that will catch you out

- **`bin/`, `obj/` and `.vs/` are no longer tracked** (#3) — `.gitignore` covers them, so building
  no longer dirties tracked files and there is nothing to revert before committing. `main`'s
  history was rewritten without them on 2026-09-21, the 69 MB self-contained exe included. The
  decision on #3 is to delete the `backup/pre-rewrite` branch that kept the old history. GitHub also
  holds it under the read-only refs of PRs #14, #16 and #17, which only GitHub Support can purge,
  and nothing in it is secret. Don't re-add them.
- **`gen-license` has two failure exits** (#3). `1` means no licence was written; `2` means the
  licence was written but its `--register-csv` row was not, and the remedy is to record it by hand,
  never to mint a second one. Every other command exits non-zero on any failure.
- **The licence contract is docs plus fixtures, not a library.** #5's `KnowledgeFabric.Licensing`
  package was dropped; `docs/License-Contract.md` is normative and `contract/` holds 27 signed
  fixtures each reader asserts against. `ContractReader.cs` is here to verify those fixtures and to
  back #6's validate page — it is not published or referenced elsewhere, and it must not grow into
  the package that was dropped.
- **The fixture set is not byte-reproducible**, so never diff a regenerated set against the
  committed one. ECDSA signing uses a random nonce: regenerating rewrites every signature and every
  hash even when nothing else changed. A `contract/fixtures/` diff touching all 27 files is normal.
  CI checks the committed files against the committed manifest instead.
- **A licence grants only what it names** (#38). Reports, features, connectors and AI capabilities
  are lists in `LicenseAttributes`; anything not named — including anything the product adds
  later — is off, and `ProductFeatures` is empty. A connector's count is of sources, but
  `github`'s is of repositories across every GitHub source, while `sources.max` counts each GitHub
  source as one (#168, kf-app#1030 D5; `SourceEntry.Unit`). The catalogue is `LicenseContract` and
  [docs/License-Entitlements.md](docs/License-Entitlements.md); `Entitlements.cs` reads it, linked
  into the console like `ContractReader.cs` and under the same rule. **Both readers enforce it:**
  kf-app since kf-app#985 (`c332de4`), and the gateway's three AI limits since kf-ai-gateway#28
  (`ebb48b3`). `analysis.employees` is the exception: an allowance, not a limit (#44). A reader may
  report going over it, and must never refuse anything or leave an employee out of an analysis for
  it. kf-app honours `validFrom` (kf-app#979), refusing on upload a licence not yet in force, and
  sends its licence to the gateway on every install (kf-app#968) — on kf-app `develop` at `5e9fb51`,
  and in no release yet: kf-app 1.6.2 (`c332de4`) ignores `validFrom` and sends the licence only when
  it first enrols (#61). The change stayed at `schemaVersion` 1 only because nothing was
  deployed; after the first deployment, a change like it is version 2. Every licence also carries
  `purpose` (`customer`, `internal`, `demo`), which grants nothing: it is how the register will
  leave test and demo licences out of its figures. `tier` chooses one thing, the gateway's allowance
  for the AI limits a licence leaves out; absent or unknown reads as `standard` (#46). The two
  allowances start equal and only ever go up. The gateway reads `tier` since kf-ai-gateway#32
  (`c82878f`); an installation it licensed before then reads as `standard` until its licence is
  sent again.
- **A licence covers one installation** (#47), whatever its `purpose`. A customer or team with
  several installations gets a licence for each. The rule is on `Id`: `Quantity` stays 1, is read by
  nothing, and is not a lever to add. kf-app cannot see other installations, so only the gateway can
  apply the rule, and it is to *watch*: record the licence id on each installation and show an
  operator an id held by more than one, never refuse. It records it since kf-ai-gateway#35
  (`cb44c56`, deployed 2026-09-26): `licence_id` on each `/admin/installations` row with a
  `licence_holders` count, filtered by `licence_id=` and `shared=true` — the names
  `Gateway/GatewayAdminClient.cs` asks for, and the gateway's `docs/Admin.md` names kf-admin as the
  client that depends on them. The register shows it (#58): each row lists its installations and the
  overview the shared ids, and links each installation to its own page (#65). `Gateway--AdminToken` holds the gateway's **read-only** token
  (`Admin__ReadToken`, kf-ai-gateway#40), loaded the same day, and is sent on every read.
  `Gateway--AdminWriteToken`, its `Admin__Token`, is sent on writes alone (#69): revoking and
  restoring an installation behind a confirm step, naming the operator in `X-KF-Operator`, and
  audited once the gateway confirms.
  Without a token the pages say the gateway is not configured, and against an older gateway that it
  records no licence ids.
- **Never commit a private key or passphrase** — with one recorded exception, below. Only the
  public key and the `.lic` file are shareable. The one that was committed in
  `Properties/launchSettings.json` is out of the working tree (#3) and no longer protects the
  production key: `rekey` (#26) re-encrypted it under a passphrase that was never public. The old
  one still opens the original file on the machine the key was generated on, until that is deleted
  ([docs/Provisioning.md](docs/Provisioning.md#b3-load-the-secrets)). It stays in this repository's
  history by decision (#3), and in kf-app's; kf-app#982 deleted the tool's `launchSettings.json`
  and kf-app's docs no longer carry it (`5e9fb51`). Never reuse it. **Rotating the key pair is not the
  remedy for a leaked passphrase** — its public half is compiled into every product image
  (kf-app#870) and read by kf-ai-gateway too. Rotation becomes ordinary work once both readers
  accept a *list* of public keys, because the old key stays trusted without needing the old private
  half. Both do now: kf-app as of `84afe1e` (kf-app#983, `BundledLicensingSettings.PublicKeys` in
  `KnowledgeFabric.Logic/Services/Licensing/LicensingOptions.cs`), and kf-ai-gateway as of
  `8e92f7d` (kf-ai-gateway#7, `TrustedLicenceKeys.All` verified by `StandardLicenceEvaluator` in
  `src/KnowledgeFabric.AiGateway/Licensing/`). So a rotation is two releases, one per reader, each
  adding the new key after the old one, both out before anything is signed with it — the gateway's
  list especially, or renewed licences enrol there as `evaluation`. That sequencing is
  [docs/Operations.md](docs/Operations.md#rotating-the-key-pair).
- **The exception: `contract/test-keys/`** holds two throwaway keypairs with their passphrases in
  `contract/fixture-set.json`, so that anyone and CI can regenerate the contract fixture set with
  one command (#5). Neither public half is compiled into any product image, so nothing they sign
  validates on a customer installation. Don't extend the exception: never sign a customer licence
  with them, and never add the production key there — it is read at signing time through Managed
  Identity (#6, #7).
- **The console's UI is a commercial template.** Vuexy (PixInvent), taken from kf-app's copy and
  recoloured, under kf-app's existing licence — the console was judged the same end product, and
  that decision is [recorded on #15](https://github.com/KnowledgeFabric/kf-admin/issues/15#issuecomment-5781201697).
  Don't copy the purchase code into this repository the way kf-app keeps it in a tracked file, and
  don't upgrade the template by hand: what is here is a documented subset of kf-app's, listed in
  [docs/Console-Shell.md](docs/Console-Shell.md).
- **This repository holds the only issuing code.** kf-app's copy of the tool
  (`KnowledgeFabric.LicenseTool/`, with its `trialDays`) was deleted by kf-app#982 (`5e9fb51`), once
  kf-app's tests read this repository's fixtures instead (`KnowledgeFabric.Modeller.Tests/Licensing/Contract`,
  copied from `1e25d1a`). kf-app verifies and interprets a licence and never mints one (its ADR
  `docs/Architecture/Licence-Remit.md`). A licence that copy issued is in no register here.
  Regenerating the fixture set means kf-app and kf-ai-gateway copy it again —
  [Relationship to kf-app](docs/README.md#relationship-to-kf-app).

## Conventions

- Docs live in `docs/` as Title-Case-Hyphenated `.md` files, indexed by `docs/README.md`, matching
  `kf-app` and `kf-ai-gateway`. File names use "License"; prose uses "licence".
- `License-Contract.md`, `License-Format.md`, `License-Config-Schema.md` and `License-Entitlements.md` are
  **normative** — they bind kf-app and kf-ai-gateway too. Changing what one of them requires is a
  contract change: regenerate `contract/fixtures/` in the same commit.
- C# sources carry a UTF-8 BOM. Keep it, so diffs stay to the lines you meant to touch.
- Config JSON in `src/KnowledgeFabric.LicenseTool/config/` uses 4-space indentation.
- Claims about what the *product* does belong with a citation to the kf-app file and commit they
  came from — that behaviour lives in another repository and drifts.
- **Every pull request body carries its acceptance criteria as manual tests**: a numbered table of
  steps and expected outcomes a person can run on the console, by session (which role), covering
  what the change does and what it refuses, beside the automated checks.
</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
```

Writes `private.key` (passphrase-encrypted) and `public.key`. Refuses to overwrite either, and exits
non-zero when it does.

### Issue a licence

```bash
dotnet LicenseTool.dll gen-license \
  --config ./config/license_config.json \
  --private-key ./keys/private.key \
  --passphrase "<passphrase>" \
  --output ./license.lic
```

Start from [`config/license_config_template.json`](src/KnowledgeFabric.LicenseTool/config/license_config_template.json).

## Commands

### `gen-keys`

| Option | Required | Default |
|---|---|---|
| `--passphrase` | Yes | — |
| `--output` | No | current directory |

The private key is written behind **600,000 KDF iterations** rather than the 10 `Standard.Licensing`
writes by default, using the same algorithm and salt length, so a generated key is protected exactly
as a [`rekey`](#rekey)ed one is (#3). Readers take the parameters from the blob, so nothing needs to
know this — including keys generated before the change, which still open.

### `gen-license`

| Option | Required | Default |
|---|---|---|
| `--config` | Yes | — |
| `--private-key` | Yes | — |
| `--passphrase` | Yes | — |
| `--output` | No | `./license.lic` |
| `--register-csv` | No | — |
| `--issued-by` | No | the operating-system user |
| `--allow-unknown-names` | No | off |

It **exits non-zero** when no licence was written (#3), so it is safe to script:

| Exit status | Meaning |
|---|---|
| `0` | The licence was written, and its register row appended when `--register-csv` was given. |
| `1` | No licence was written: the config, the key or the passphrase is wrong. stderr says which. |
| `2` | The licence was written, but its row could not be appended to `--register-csv`. Record it by hand; do not mint another. |

### `gen-fixtures`

Mints the licence contract's fixture set — the signed licences that kf-app and kf-ai-gateway assert
against instead of sharing a library. It reads every fixture back and **exits non-zero** if one does
not behave the way `contract/fixture-set.json` declares.

```bash
dotnet LicenseTool.dll gen-fixtures --set ./contract/fixture-set.json --output ./contract/fixtures
```

| Option | Required | Default |
|---|---|---|
| `--set` | Yes | — |
| `--output` | Yes | — |

Signing keys, passphrases and the evaluation instant come from the set definition. See
[`contract/README.md`](contract/README.md) — including why that directory holds test private keys in
the clear, and why the production key must never go there.

### `rekey`

Re-encrypts an existing private key under a new passphrase. **The key pair does not change**, so
every licence ever issued keeps validating — which is what makes this the remedy for a leaked
passphrase, and why generating a new pair is not (its public half is compiled into every product
image, and read by kf-ai-gateway too; see
[Rotating the key pair](docs/Operations.md#rotating-the-key-pair)).

```bash
dotnet LicenseTool.dll rekey --private-key ./private.key \
  --current-passphrase "<old>" --new-passphrase "<new>"
```

| Option | Required | Default |
|---|---|---|
| `--private-key` | Yes | — |
| `--current-passphrase` | Yes | — |
| `--new-passphrase` | Yes | — |
| `--output` | No | `<private-key>.rekeyed` |

It **never writes over its input** and refuses an `--output` that already exists, because the input
is the only copy of a key that cannot be regenerated. It reads the new blob back before writing it,
**exits non-zero** on any failure, and prints the public key it derived from what it decrypted —
compare that against `public.key` and against the key in the product before replacing anything.

The full procedure, including what to do with the result, is
[Rotating the passphrase](docs/Operations.md#rotating-the-passphrase).

## Configuration file

```json
{
  "name": "Acme Corporation",
  "email": "it-ops@acme.example",
  "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:3", "gcal", "outlook", "confluence", "shortcut", "onedrive", "teams", "publications", "github"],
  "sources.max": 10,
  "ai": ["chat"],
  "attributes": {}
}
```

| Field | Notes |
|---|---|
| `name`, `email` | Customer details. Not validated — empty strings are accepted. |
| `company` | Optional. `Customer/Company`; display-only. |
| `licenseType` | `Standard` **only**. `Trial` is refused (#3): the product's trial is compiled in, never a file — for an evaluation licence use `purpose: demo` and a short `duration`. There is no `Enterprise` — that is a `tier`. Case-insensitive. |
| `tier` | Optional. `standard` or `enterprise`. Chooses the AI Gateway's default allowance and nothing else; absent reads as `standard` (#46). |
| `purpose` | Optional. `customer` (the default), `internal` or `demo`. Grants nothing; there so the register can leave test and demo licences out of its figures, which the overview does not do yet. |
| `expiration` | ISO 8601 **with an offset** — a value without one is refused. Either this or `duration`. |
| `duration` | ISO 8601, e.g. `P1Y`, `P30D`. Resolved into `Expiration` at issue time, from `validFrom` or now. |
| `validFrom` | Optional start instant, with an offset. **Enforced by the gateway, not yet by kf-app.** |
| `reports`, `features`, `sources`, `ai` | What the licence grants: lists of catalogue names. Anything not named is not granted. `"jira:3"` allows three Jira sources. |
| `sources.max`, `analysis.*`, `ai.*` | Limits. Left out: no limit, or for AI the default of the licence's `tier`. |
| `attributes` | Inert metadata. `TrialDays`, the entitlement's names and the tool's own names are refused. |
| `licenseId` | Optional GUID. Pins the licence's `Id` instead of minting a fresh one. |

Every licence also carries `schemaVersion` `1` and `issuedAt`, written by the tool
([#4](https://github.com/KnowledgeFabric/kf-admin/issues/4)).

Full reference, worked examples per licence type, and the leniency traps:
[docs/License-Config-Schema.md](docs/License-Config-Schema.md).

## The licence file

```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="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>
  </LicenseAttributes>
  <Customer>
    <Name>Acme Corp</Name>
    <Email>ops@acme.example</Email>
  </Customer>
  <Expiration>Fri, 01 Oct 2027 00:00:00 GMT</Expiration>
  <Signature>MEYCIQDN1qj9HsWVl/S7vIqj+oinS2c7SeICQ/7+Sh3zC2t0CwIhALzW4UbQ…</Signature>
</License>
```

Only the entitlement in `LicenseAttributes`, `Expiration` and `Signature` affect what the customer
can do. `ProductFeatures` is empty, `Id` is a fresh GUID per run unless the config pins it,
`Quantity` is hard-coded to `1` and read by nothing: a licence covers one installation, a rule on its
`Id` ([#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)). `Type` is a label that gates nothing. Element-by-element detail: [docs/License-Format.md](docs/License-Format.md).

## How the product validates a licence

In kf-app, `KnowledgeFabric.Logic/Services/Licensing/LicenseService.cs`:

- **On upload** — refuses in the contract's order and words: `unverifiable` (will not parse, or no
  trusted key verifies it), `unsupported-schema`, `trial-licence` (it carries `TrialDays`) and
  `expired`, and since kf-app#979 `not-yet-valid` (before its `validFrom`, or with one it cannot
  read). The licence page says which.
- **On every load afterwards** — verifies the signature and the schema version, and judges the dates
  by the same rule on every gated request. Since kf-app#979, a stored licence it cannot read stands
  as unreadable: it grants nothing, and the licence page says why.
- **Not released yet:** kf-app#979 and the licence sent to the gateway on every install
  (kf-app#968) are on kf-app `develop` at `5e9fb51`. kf-app 1.6.2 (`c332de4`) ignores `validFrom`,
  falls back to its trial when it cannot read a stored licence, and sends the licence to the gateway
  only when it first enrols.
- **What it opens** — what the entitlement names, each report and feature gated on its own name,
  and Configuration and Administration with any valid licence (kf-app `c332de4`, kf-app#985).
- **The public keys** are a list: those compiled into the application image
  (`BundledLicensingSettings.PublicKeys`), plus `LicensingSettings:PublicKey` where a deployment
  sets one — beside them, not instead. A licence is genuine if any one verifies it (kf-app
  `c332de4`, `LicensingOptions.cs`, kf-app#983). A stock installation needs no configuration.

## What a licence grants

Five sections ([#38](https://github.com/KnowledgeFabric/kf-admin/issues/38)). A licence grants only
what it names — anything else is off, including anything the product adds after it was issued.

| Section | Attributes |
|---|---|
| Reports | `reports`: Insight Hub, Risk Resilience, Knowledge Watch, Holder and Asset Analysis, Knowledge Map, Skills Matrix, Workforce Report |
| Features | `features`: Offboarding Planner, Action Center, Departure Simulator, Export |
| Connectors | `sources`, each with an optional count (`jira:3`), and `sources.max` in total |
| Analysis | `analysis.employees` (an allowance, not a limit), `analysis.assets`, `analysis.history` (months) |
| AI | `ai` (the assistant), and the AI Gateway's `ai.tokens`, `ai.period`, `ai.rpm` |

**Both readers enforce it.** kf-app gates on it since kf-app#985 (`c332de4`); the AI Gateway applies
the three AI limits since kf-ai-gateway#28 (`ebb48b3`) and leaves the rest to kf-app. The names, how
to read them and what the readers do today: [docs/License-Entitlements.md](docs/License-Entitlements.md).

## Known sharp edges

Each of these is measured, not theoretical — details in [`docs/`](docs/README.md).

- **A misspelled entitlement field is ignored,** and that section grants nothing — `"report"` for
  `"reports"`. A misspelled name inside a list is refused.
- **A licence expiring in the past still mints** — with a warning — and fails only when the customer
  uploads it.
- **`validFrom` is enforced by the gateway only.** A future-dated licence works immediately on
  today's kf-app; the gateway keeps that installation on `evaluation` until the installation sends
  the licence again after the date.
- **`Quantity` is not a seat count, or a count of installations.** It is hard-coded to 1 and nothing
  reads it. A licence covers one installation, so a customer with several gets one each.
- **There is no revocation**, no installation binding, and nothing in the file records who issued
  it. Only the AI Gateway can see one licence on two installations, and it is to report that, not
  refuse it (#47).

## Repository layout

```
KnowledgeFabricLicensing.sln
src/KnowledgeFabric.LicenseTool/
  Program.cs             CLI definition (System.CommandLine)
  KeyGenerator.cs        gen-keys
  KeyRekeyer.cs          rekey — re-encrypts the private key, never changes the pair
  ConfigLoader.cs        config parsing
  LicenseConfig.cs       the config schema
  LicenseTerms.cs        config validation, and duration resolved into an expiry
  LicenseSigner.cs       the one signing path; compiled into the console too
  LicenseGenerator.cs    gen-license
  LicenseContract.cs     the contract's names and encodings, as data
  ContractReader.cs      the reference reader — verifies the fixtures, backs the validate page;
                         compiled into the console; not a shared library
  FixtureSet.cs          the fixture set definition schema
  FixtureGenerator.cs    gen-fixtures
  RegisterRecord.cs      a register row read from a signed licence; compiled into the console too
  RegisterCsv.cs         gen-license --register-csv, the offline register
  config/                sample and template configs
src/KnowledgeFabric.AdminConsole/
  Program.cs             the pipeline: auth, anti-forgery, rate limiting, /health, area routing
  Security/              sign-in by name and secret, the roles per area and their store, and the seam for Entra ID
  Auditing/              IAuditLog, and the global filter that records every mutating action
  Storage/               IFeatureStateStore — the shell's minimal store for feature state
  Data/                  the database context, its startup migration and the migrations
  Licensing/Register/    ILicenceRegister and its PostgreSQL, memory and not-configured stores
  Licensing/Issuing/     the issue form's model, preview ticket and signing (#6)
  Licensing/Validation/  the validate page's verdicts, and the keys the product trusts (#6)
  Areas/Licensing/       the issue form, the validate page and the licence register's pages
  Views/Shared/          the Vuexy layouts, menu, navbar, footer and error page
  src/                   stylesheet sources; wwwroot/vendor/css is built from them
tests/KnowledgeFabric.AdminConsole.Tests/
                         the console's tests: issuing, end to end through the running app
tests/KnowledgeFabric.LicenseTool.Tests/
                         the CLI's tests: config loading, gen-keys, gen-license, rekey
contract/                the licence contract's executable half: definition, test keys, fixtures
docs/                    reference documentation
```
</file>

</files>
