动手加一个业务功能
本页从空白开始加一个「仓库」功能:新建能力包 XiHan.BasicApp.Inventory,带仓库的增删改查五个操作、四个权限码和一个租户侧的列表页。适合已按快速开始把后端与前端跑起来、想弄清一个功能从实体到页面要动哪些文件的开发者。
页里的代码就是在一份导出的仓库副本上验证过的那一份:Release 构建 0 警告,架构测试、页面登记核对与前端 pnpm check 全部通过,五个操作在 PostgreSQL 上逐个调通。照抄即可跑起来,再按自己的业务改名。
先定契约
后端、前端与测试都围着同一份契约写,动手前先把它定下来:
| 操作 ID | HTTP | 权限码 | 请求 → 响应 |
|---|---|---|---|
warehouses.list | POST /api/warehouses:list | inventory.warehouses.read | PageRequest → PageResult<WarehouseResponse> |
warehouses.get | GET /api/warehouses/{id} | inventory.warehouses.read | GetWarehouseRequest → WarehouseResponse |
warehouses.create | POST /api/warehouses(201) | inventory.warehouses.create | CreateWarehouseRequest → WarehouseResponse |
warehouses.update | PUT /api/warehouses/{id} | inventory.warehouses.update | UpdateWarehouseRequest → WarehouseResponse |
warehouses.delete | DELETE /api/warehouses?ids=… | inventory.warehouses.delete | WarehouseIdsRequest → BatchResult |
HTTP 方法与路由由框架按约定从操作推出,操作类里不写;导出的 openapi.json 里就是上表的结果。另外三样一起定:
- 页面:页面码
inventory.warehouses,路由/inventory/warehouses,菜单标题键inventory.warehouses.title,读权限inventory.warehouses.read。组件路径由路由去掉开头的/再接/index得出,即inventory/warehouses/index,对应前端的src/modules/inventory/views/warehouses/index.vue。 - 错误码:
INVENTORY_NOTFOUND_001(仓库不存在)、INVENTORY_CONFLICT_001(编码已被占用)、INVENTORY_VALIDATION_001(列表的筛选或排序字段不支持)。格式是<包大写>_<KIND>_<NNN>。 - 数据归属:仓库是业务数据,归租户。实体落租户库,四个权限码的作用侧都是
Tenant,所以要用租户身份登录才看得到菜单;平台账号superadmin调用这些操作得到 403SECURITY_DENIED_004。两种库的区别见多租户 SaaS。
建包
在 backend/src 下建目录 XiHan.BasicApp.Inventory,工程文件如下。目标框架、可空引用、XML 文档与「警告即错误」由 backend/Directory.Build.props 统一给,这里不写:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>XiHan.BasicApp.Inventory</RootNamespace>
<Description>XiHan.BasicApp 库存包(Tier 3):仓库的增删改查。</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../XiHan.BasicApp.Contracts/XiHan.BasicApp.Contracts.csproj" />
<ProjectReference Include="../XiHan.BasicApp.Runtime/XiHan.BasicApp.Runtime.csproj" />
</ItemGroup>
<ItemGroup>
<XiHanFrameworkReference Include="XiHan.Framework.Kernel" />
<XiHanFrameworkReference Include="XiHan.Framework.Domain" />
<XiHanFrameworkReference Include="XiHan.Framework.Persistence.Abstractions" />
<XiHanFrameworkReference Include="XiHan.Framework.Persistence.SqlSugar" />
<XiHanFrameworkReference Include="XiHan.Framework.Security.Abstractions" />
<XiHanFrameworkReference Include="XiHan.Framework.MultiTenancy.Abstractions" />
<XiHanFrameworkReference Include="XiHan.Framework.Localization.Abstractions" />
<XiHanFrameworkAnalyzer Include="XiHan.Framework.Kernel.Generators" />
<XiHanFrameworkAnalyzer Include="XiHan.Framework.Persistence.Generators" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Localization/*.json" LogicalName="Localization/%(Filename)%(Extension)" />
</ItemGroup>
</Project>- 只引用 Tier 0 的
Contracts与Runtime。新包按 Tier 3 声明(见后面的 Feature),只能向下依赖,TierDependencyTests守着。 XiHanFrameworkReference与XiHanFrameworkAnalyzer不写版本,由backend/props/framework.props按解决方案换成 NuGet 包或同级框架源码,见开发环境。- 两个分析器是源生成器:
Kernel.Generators为[Operation]生成AddGeneratedOperations(),Persistence.Generators为实体生成AddGeneratedRepositories(),Feature 里调用这两个方法。
实体
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using SqlSugar;
using XiHan.BasicApp.Contracts.Entities;
using XiHan.Framework.Persistence.Abstractions;
namespace XiHan.BasicApp.Inventory.Domain.Entities;
/// <summary>
/// 仓库(租户库实体)
/// </summary>
/// <remarks>
/// 业务数据归租户:落租户库,只看得见、只写得了当前租户的行
/// 编码租户内唯一、建后不改;软删除,用部分唯一索引,删除后同编码可以重建
/// </remarks>
[SugarTable(TableName = "inv_warehouse", TableDescription = "仓库(租户库实体)")]
[EntityIndex(nameof(TenantId), nameof(Code), IsUnique = true, Name = "ux_inv_warehouse_tenant_id_code")]
public sealed class Warehouse : TenantScopedAuditedEntity
{
/// <summary>
/// 编码
/// </summary>
[SugarColumn(ColumnName = "code", Length = 64, IsNullable = false, ColumnDescription = "编码:租户内唯一")]
public string Code { get; set; } = string.Empty;
/// <summary>
/// 名称
/// </summary>
[SugarColumn(ColumnName = "name", Length = 128, IsNullable = false, ColumnDescription = "名称")]
public string Name { get; set; } = string.Empty;
/// <summary>
/// 地址
/// </summary>
[SugarColumn(ColumnName = "address", Length = 512, IsNullable = true, ColumnDescription = "地址")]
public string? Address { get; set; }
}TenantScopedAuditedEntity带主键id、tenant_id、创建与修改的时间和人、软删除的三列与并发戳。新建时自动填当前租户;仓储与列表查询只看当前租户、未删除的行。- 表名、列名、长度、可空与说明都显式写,名字小写加下划线;索引名用
ux_/ix_加表名与列名。EntityMappingTests守这些写法。 - 软删除实体的唯一约束写
[EntityIndex(…, IsUnique = true)],框架建成部分唯一索引(PostgreSQL 上是UNIQUE (tenant_id, code) WHERE is_deleted = false):仓库删掉后不再占着编码,同一编码可以重建。 - 不用写建表脚本:开发配置打开了
InitTables,重启即按实体建表补列;正式库由表结构升级器按实体建表,见表结构升级。
能力、权限码、页面与错误码
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Contracts;
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包提供的能力
/// </summary>
public static class InventoryCapabilities
{
/// <summary>
/// 库存能力
/// </summary>
public const string Inventory = AppInfo.CapabilityPrefix + "inventory";
/// <summary>
/// 能力版本
/// </summary>
public const int Version = 1;
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Contracts.Security;
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包的权限码
/// </summary>
/// <remarks>
/// 仓库是租户库实体,权限码只在租户侧;写操作记审计
/// </remarks>
public static class InventoryPermissions
{
/// <summary>
/// 查看仓库
/// </summary>
public const string WarehousesRead = "inventory.warehouses.read";
/// <summary>
/// 新建仓库
/// </summary>
public const string WarehousesCreate = "inventory.warehouses.create";
/// <summary>
/// 修改仓库
/// </summary>
public const string WarehousesUpdate = "inventory.warehouses.update";
/// <summary>
/// 删除仓库
/// </summary>
public const string WarehousesDelete = "inventory.warehouses.delete";
/// <summary>
/// 全部权限描述
/// </summary>
public static IReadOnlyList<PermissionDescriptor> All { get; } =
[
new(WarehousesRead, "View warehouses", PermissionScope.Tenant, description: "List and view the warehouses of the current tenant."),
new(WarehousesCreate, "Create warehouses", PermissionScope.Tenant, audited: true, description: "Create warehouses in the current tenant."),
new(WarehousesUpdate, "Update warehouses", PermissionScope.Tenant, audited: true, description: "Update the name and address of warehouses."),
new(WarehousesDelete, "Delete warehouses", PermissionScope.Tenant, audited: true, description: "Delete warehouses."),
];
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Contracts.Pages;
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包的页面登记
/// </summary>
/// <remarks>
/// 前端页面在 <c>frontend/src/modules/inventory</c>
/// </remarks>
public static class InventoryPages
{
/// <summary>
/// 仓库管理页
/// </summary>
public static PageDescriptor Warehouses { get; } = new("inventory.warehouses", "/inventory/warehouses", "inventory.warehouses.title", "lucide:warehouse", 100, InventoryPermissions.WarehousesRead);
/// <summary>
/// 全部顶层页面
/// </summary>
public static IReadOnlyList<PageDescriptor> All { get; } = [Warehouses];
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包的错误码
/// </summary>
public static class InventoryErrors
{
/// <summary>
/// 仓库不存在
/// </summary>
public const string WarehouseNotFound = "INVENTORY_NOTFOUND_001";
/// <summary>
/// 仓库编码已被占用
/// </summary>
public const string WarehouseCodeTaken = "INVENTORY_CONFLICT_001";
/// <summary>
/// 列表的筛选或排序字段不受支持
/// </summary>
public const string QueryUnsupported = "INVENTORY_VALIDATION_001";
}- 权限码是
<包>.<资源>.<动作>,资源段与操作 ID 的资源段相同。PermissionDescriptor里的英文显示名只在区域文案都取不到时才用;audited: true的权限所保护的操作进操作审计。权限目录、菜单门控、套餐白名单与前端生成的permissions.ts都从InventoryPermissions.All派生,不另写清单。 PageDescriptor依次是页面码、路由、菜单标题键、图标、排序与读权限。种子access.menus按它对齐菜单;这里没挂目录,菜单出现在顶层,要挂到已有目录下时传directory:(目录常量在MenuDirectories)。- 能力码只在 Manifest 里用:声明这个包提供什么。
消息目录与后端文案
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.Framework.Localization.Abstractions.Messages;
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包的消息键
/// </summary>
/// <remarks>
/// 各区域文案在 <c>Localization/<区域>.json</c>
/// </remarks>
public static class InventoryMessages
{
/// <summary>
/// 消息目录名
/// </summary>
public const string CatalogName = "basicapp.inventory";
/// <summary>
/// 操作 <c>warehouses.create</c> 的说明
/// </summary>
public const string CreateWarehouseDescription = "warehouses.create.description";
/// <summary>
/// 操作 <c>warehouses.get</c> 的说明
/// </summary>
public const string GetWarehouseDescription = "warehouses.get.description";
/// <summary>
/// 操作 <c>warehouses.list</c> 的说明
/// </summary>
public const string ListWarehousesDescription = "warehouses.list.description";
/// <summary>
/// 操作 <c>warehouses.update</c> 的说明
/// </summary>
public const string UpdateWarehouseDescription = "warehouses.update.description";
/// <summary>
/// 操作 <c>warehouses.delete</c> 的说明
/// </summary>
public const string DeleteWarehousesDescription = "warehouses.delete.description";
/// <summary>
/// 仓库不存在
/// </summary>
/// <remarks>
/// 参数 <c>id</c>
/// </remarks>
public const string WarehouseNotFound = "inventory.warehouse.not_found";
/// <summary>
/// 仓库编码已被占用
/// </summary>
/// <remarks>
/// 参数 <c>code</c>
/// </remarks>
public const string WarehouseCodeTaken = "inventory.warehouse.code_taken";
/// <summary>
/// 不支持的筛选
/// </summary>
/// <remarks>
/// 参数 <c>field</c>、<c>operator</c>
/// </remarks>
public const string FilterUnsupported = "inventory.query.filter_unsupported";
/// <summary>
/// 不支持的排序
/// </summary>
/// <remarks>
/// 参数 <c>field</c>
/// </remarks>
public const string SortUnsupported = "inventory.query.sort_unsupported";
private static readonly Lazy<MessageCatalog> _catalog = new(static () => MessageCatalog.FromEmbeddedResources(CatalogName, typeof(InventoryMessages)));
/// <summary>
/// 本包的消息目录(嵌入的 10 种区域文件)
/// </summary>
public static MessageCatalog Catalog => _catalog.Value;
}每个区域一个 JSON 文件,放在 Localization/ 下,以嵌入资源编进程序集(工程文件里的 EmbeddedResource):
{
"warehouses.create.title": "新建仓库",
"warehouses.create.description": "在当前租户新建仓库:编码租户内唯一。",
"warehouses.get.title": "获取仓库",
"warehouses.get.description": "按主键取一个仓库。",
"warehouses.list.title": "列出仓库",
"warehouses.list.description": "分页列出当前租户的仓库:关键字匹配编码与名称,可按编码、名称与创建时间排序。",
"warehouses.update.title": "修改仓库",
"warehouses.update.description": "修改仓库的名称与地址,编码不可改。",
"warehouses.delete.title": "删除仓库",
"warehouses.delete.description": "批量删除仓库,逐项返回结果。",
"inventory.warehouse.not_found": "仓库 {id} 不存在。",
"inventory.warehouse.code_taken": "仓库编码 {code} 已被占用。",
"inventory.query.filter_unsupported": "不支持按 {field} 以 {operator} 筛选。",
"inventory.query.sort_unsupported": "不支持按 {field} 排序。",
"permissions.inventory.warehouses.read.name": "查看仓库",
"permissions.inventory.warehouses.read.description": "列出并查看当前租户的仓库。",
"permissions.inventory.warehouses.create.name": "新建仓库",
"permissions.inventory.warehouses.create.description": "在当前租户新建仓库。",
"permissions.inventory.warehouses.update.name": "修改仓库",
"permissions.inventory.warehouses.update.description": "修改仓库的名称与地址。",
"permissions.inventory.warehouses.delete.name": "删除仓库",
"permissions.inventory.warehouses.delete.description": "删除仓库。",
"openapi.tags.warehouses.name": "仓库",
"openapi.tags.warehouses.description": "仓库的增删改查。",
"openapi.groups.inventory.name": "库存",
"openapi.groups.inventory.description": "库存包:仓库管理。"
}{
"warehouses.create.title": "Create a warehouse",
"warehouses.create.description": "Create a warehouse in the current tenant; the code is unique within the tenant.",
"warehouses.get.title": "Get a warehouse",
"warehouses.get.description": "Get a warehouse by its ID.",
"warehouses.list.title": "List warehouses",
"warehouses.list.description": "Page through the warehouses of the current tenant; the keyword matches the code and the name, sortable by code, name and creation time.",
"warehouses.update.title": "Update a warehouse",
"warehouses.update.description": "Update the name and address of a warehouse; the code cannot be changed.",
"warehouses.delete.title": "Delete warehouses",
"warehouses.delete.description": "Delete warehouses in a batch, with a result for each item.",
"inventory.warehouse.not_found": "Warehouse '{id}' was not found.",
"inventory.warehouse.code_taken": "The warehouse code '{code}' is already taken.",
"inventory.query.filter_unsupported": "Filtering by '{field}' with '{operator}' is not supported.",
"inventory.query.sort_unsupported": "Sorting by '{field}' is not supported.",
"permissions.inventory.warehouses.read.name": "View warehouses",
"permissions.inventory.warehouses.read.description": "List and view the warehouses of the current tenant.",
"permissions.inventory.warehouses.create.name": "Create warehouses",
"permissions.inventory.warehouses.create.description": "Create warehouses in the current tenant.",
"permissions.inventory.warehouses.update.name": "Update warehouses",
"permissions.inventory.warehouses.update.description": "Update the name and address of warehouses.",
"permissions.inventory.warehouses.delete.name": "Delete warehouses",
"permissions.inventory.warehouses.delete.description": "Delete warehouses.",
"openapi.tags.warehouses.name": "Warehouses",
"openapi.tags.warehouses.description": "Create, read, update and delete warehouses.",
"openapi.groups.inventory.name": "Inventory",
"openapi.groups.inventory.description": "The inventory package: warehouse management."
}其余八个文件(zh-TW、ja-JP、ko-KR、de-DE、es-ES、fr-FR、pt-BR、ru-RU)放同一组键、各写译文。键分这几类:
| 键 | 用途 |
|---|---|
<操作 ID>.title | 接口文档里操作的摘要,每个操作必须有 |
<操作 ID>.description | 接口文档里操作的说明,可选;写了就要在 InventoryMessages 里有对应常量 |
inventory.warehouse.not_found 等 | 错误文案,{id} 这类占位由 MessageArguments 填 |
permissions.<权限码>.name / .description | 权限码的显示名与说明(权限码里的 - 换成 _) |
openapi.tags.<资源>.name / .description | 资源的显示名,也是权限目录里的资源名 |
openapi.groups.<包名小写>.name / .description | 接口文档里这个包的分组 |
架构测试 PackageStructureTests 要求 10 个文件都在、键集一致,并且正好等于 InventoryMessages 的常量加上表里的约定键,多一个、少一个都失败。错误响应的 detail 按请求头 Accept-Language 取区域。
请求与响应
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.ComponentModel.DataAnnotations;
using XiHan.BasicApp.Inventory.Domain.Entities;
namespace XiHan.BasicApp.Inventory.Operations.Warehouses;
/// <summary>
/// 仓库的网络契约
/// </summary>
/// <param name="Id">主键</param>
/// <param name="Code">编码</param>
/// <param name="Name">名称</param>
/// <param name="Address">地址</param>
/// <param name="CreatedAt">创建时间(UTC)</param>
public sealed record WarehouseResponse(Guid Id, string Code, string Name, string? Address, DateTimeOffset CreatedAt)
{
/// <summary>
/// 从实体投影
/// </summary>
/// <param name="warehouse">仓库</param>
public static WarehouseResponse From(Warehouse warehouse)
{
ArgumentNullException.ThrowIfNull(warehouse);
return new WarehouseResponse(warehouse.Id, warehouse.Code, warehouse.Name, warehouse.Address, warehouse.CreatedAt);
}
}
/// <summary>
/// <c>warehouses.create</c> 的请求
/// </summary>
/// <param name="Code">编码(租户内唯一)</param>
/// <param name="Name">名称</param>
/// <param name="Address">地址</param>
public sealed record CreateWarehouseRequest(
[Required, StringLength(64, MinimumLength = 1), RegularExpression("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")] string Code,
[Required, StringLength(128, MinimumLength = 1)] string Name,
[StringLength(512)] string? Address = null);
/// <summary>
/// <c>warehouses.get</c> 的请求
/// </summary>
/// <param name="Id">仓库主键</param>
public sealed record GetWarehouseRequest(Guid Id);
/// <summary>
/// <c>warehouses.update</c> 的请求:编码不在这里改
/// </summary>
/// <param name="Id">仓库主键</param>
/// <param name="Name">名称</param>
/// <param name="Address">地址</param>
public sealed record UpdateWarehouseRequest(
Guid Id,
[Required, StringLength(128, MinimumLength = 1)] string Name,
[StringLength(512)] string? Address = null);
/// <summary>
/// <c>warehouses.delete</c> 的请求
/// </summary>
/// <param name="Ids">仓库主键,1 到 100 个</param>
public sealed record WarehouseIdsRequest([Required, MinLength(1), MaxLength(100)] IReadOnlyList<Guid> Ids);请求与响应写成 sealed record,参数的 XML 文档就是接口文档里字段的说明。管道在进操作之前按数据注解校验请求,不通过返回 400,字段错误按字段放在 errors 里。响应只投影需要的字段,不直接返回实体。
操作
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Inventory.Domain.Entities;
using XiHan.Framework.Domain.Specifications;
using XiHan.Framework.Kernel.Operations;
using XiHan.Framework.Persistence.Abstractions.Identifiers;
using XiHan.Framework.Persistence.Abstractions.Queries;
using XiHan.Framework.Persistence.Abstractions.Repositories;
using XiHan.Framework.Primitives;
namespace XiHan.BasicApp.Inventory.Operations.Warehouses;
/// <summary>
/// 新建仓库
/// </summary>
/// <remarks>
/// <c>POST /api/warehouses</c>。编码租户内唯一,写入当前租户
/// </remarks>
/// <param name="warehouses">仓库仓储</param>
/// <param name="ids">标识生成器</param>
[Operation(Id, Stability = Stability.Preview, Expose = Expose.Http, Permission = InventoryPermissions.WarehousesCreate)]
public sealed class CreateWarehouse(IRepository<Warehouse, Guid> warehouses, IIdGenerator<Guid> ids) : IOperation<CreateWarehouseRequest, WarehouseResponse>
{
/// <summary>
/// 操作 ID
/// </summary>
public const string Id = "warehouses.create";
/// <inheritdoc />
public async ValueTask<Result<WarehouseResponse>> HandleAsync(CreateWarehouseRequest request, InvocationContext context)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(context);
var code = request.Code.Trim();
if (await warehouses.CountAsync(EntityQuery.All<Warehouse>().Where(new Specification<Warehouse>(w => w.Code == code)), context.CancellationToken).ConfigureAwait(false) > 0)
{
return Error.Conflict(InventoryErrors.WarehouseCodeTaken, InventoryMessages.WarehouseCodeTaken, MessageArguments.Of(("code", code)));
}
var warehouse = new Warehouse
{
Id = ids.NewId(),
Code = code,
Name = request.Name.Trim(),
Address = string.IsNullOrWhiteSpace(request.Address) ? null : request.Address.Trim(),
};
var added = await warehouses.AddAsync(warehouse, context.CancellationToken).ConfigureAwait(false);
return added.IsFailure ? added.Error! : WarehouseResponse.From(warehouse);
}
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Inventory.Domain.Entities;
using XiHan.Framework.Kernel.Operations;
using XiHan.Framework.Persistence.Abstractions.Repositories;
using XiHan.Framework.Primitives;
namespace XiHan.BasicApp.Inventory.Operations.Warehouses;
/// <summary>
/// 仓库详情
/// </summary>
/// <remarks>
/// <c>GET /api/warehouses/{id}</c>
/// </remarks>
/// <param name="warehouses">仓库仓储</param>
[Operation(Id, Stability = Stability.Preview, Expose = Expose.Http, Permission = InventoryPermissions.WarehousesRead)]
public sealed class GetWarehouse(IRepository<Warehouse, Guid> warehouses) : IOperation<GetWarehouseRequest, WarehouseResponse>
{
/// <summary>
/// 操作 ID
/// </summary>
public const string Id = "warehouses.get";
/// <inheritdoc />
public async ValueTask<Result<WarehouseResponse>> HandleAsync(GetWarehouseRequest request, InvocationContext context)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(context);
return (await warehouses.FindAsync(request.Id, context.CancellationToken).ConfigureAwait(false)).TryGetValue(out var warehouse)
? WarehouseResponse.From(warehouse)
: Error.NotFound(InventoryErrors.WarehouseNotFound, InventoryMessages.WarehouseNotFound, MessageArguments.Of(("id", request.Id)));
}
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Contracts.Paging;
using XiHan.BasicApp.Inventory.Queries;
using XiHan.Framework.Kernel.Operations;
using XiHan.Framework.Primitives;
namespace XiHan.BasicApp.Inventory.Operations.Warehouses;
/// <summary>
/// 仓库列表
/// </summary>
/// <remarks>
/// <c>POST /api/warehouses:list</c>(分页、关键字、筛选、排序),白名单见 <see cref="WarehouseQueries"/>
/// </remarks>
/// <param name="queries">仓库查询</param>
[Operation(Id, Stability = Stability.Preview, Expose = Expose.Http, Permission = InventoryPermissions.WarehousesRead)]
public sealed class ListWarehouses(WarehouseQueries queries) : IOperation<PageRequest, PageResult<WarehouseResponse>>
{
/// <summary>
/// 操作 ID
/// </summary>
public const string Id = "warehouses.list";
/// <inheritdoc />
public ValueTask<Result<PageResult<WarehouseResponse>>> HandleAsync(PageRequest request, InvocationContext context)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(context);
return queries.ListAsync(request, context);
}
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Inventory.Domain.Entities;
using XiHan.Framework.Kernel.Operations;
using XiHan.Framework.Persistence.Abstractions.Repositories;
using XiHan.Framework.Primitives;
namespace XiHan.BasicApp.Inventory.Operations.Warehouses;
/// <summary>
/// 修改仓库
/// </summary>
/// <remarks>
/// <c>PUT /api/warehouses/{id}</c>,整体替换名称与地址
/// </remarks>
/// <param name="warehouses">仓库仓储</param>
[Operation(Id, Stability = Stability.Preview, Expose = Expose.Http, Permission = InventoryPermissions.WarehousesUpdate)]
public sealed class UpdateWarehouse(IRepository<Warehouse, Guid> warehouses) : IOperation<UpdateWarehouseRequest, WarehouseResponse>
{
/// <summary>
/// 操作 ID
/// </summary>
public const string Id = "warehouses.update";
/// <inheritdoc />
public async ValueTask<Result<WarehouseResponse>> HandleAsync(UpdateWarehouseRequest request, InvocationContext context)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(context);
if (!(await warehouses.FindAsync(request.Id, context.CancellationToken).ConfigureAwait(false)).TryGetValue(out var warehouse))
{
return Error.NotFound(InventoryErrors.WarehouseNotFound, InventoryMessages.WarehouseNotFound, MessageArguments.Of(("id", request.Id)));
}
warehouse.Name = request.Name.Trim();
warehouse.Address = string.IsNullOrWhiteSpace(request.Address) ? null : request.Address.Trim();
var updated = await warehouses.UpdateAsync(warehouse, context.CancellationToken).ConfigureAwait(false);
return updated.IsFailure ? updated.Error! : WarehouseResponse.From(warehouse);
}
}// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using XiHan.BasicApp.Contracts.Batch;
using XiHan.BasicApp.Inventory.Domain.Entities;
using XiHan.Framework.Kernel.Operations;
using XiHan.Framework.Persistence.Abstractions.Repositories;
using XiHan.Framework.Primitives;
namespace XiHan.BasicApp.Inventory.Operations.Warehouses;
/// <summary>
/// 批量删除仓库
/// </summary>
/// <remarks>
/// <c>DELETE /api/warehouses?ids=...</c>。逐项:不存在的记进失败项,其余软删除
/// </remarks>
/// <param name="warehouses">仓库仓储</param>
[Operation(Id, Stability = Stability.Preview, Expose = Expose.Http, Permission = InventoryPermissions.WarehousesDelete)]
public sealed class DeleteWarehouses(IRepository<Warehouse, Guid> warehouses) : IOperation<WarehouseIdsRequest, BatchResult>
{
/// <summary>
/// 操作 ID
/// </summary>
public const string Id = "warehouses.delete";
/// <inheritdoc />
public async ValueTask<Result<BatchResult>> HandleAsync(WarehouseIdsRequest request, InvocationContext context)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(context);
var found = (await warehouses.FindManyAsync(request.Ids, context.CancellationToken).ConfigureAwait(false)).ToDictionary(static w => w.Id);
var succeeded = new List<Guid>();
var failed = new List<BatchFailure>();
foreach (var id in request.Ids.Distinct())
{
if (!found.TryGetValue(id, out var warehouse))
{
failed.Add(BatchFailure.From(id, Error.NotFound(InventoryErrors.WarehouseNotFound, InventoryMessages.WarehouseNotFound, MessageArguments.Of(("id", id)))));
continue;
}
var removed = await warehouses.RemoveAsync(warehouse, context.CancellationToken).ConfigureAwait(false);
if (removed.IsFailure)
{
return removed.Error!;
}
succeeded.Add(id);
}
return new BatchResult(succeeded, failed);
}
}- 一个操作一个类,放在
Operations/<资源>/:[Operation]写操作 ID、稳定级别、Expose与权限码,类实现IOperation<TRequest, TResponse>。Expose必须显式写(编译期检查XHG004),这里只发布到 HTTP;请求与响应类型必须登记在本工程的JsonSerializerContext里(XHG002)。 - Tier 3 包的清单与操作都标
Stability.Preview,StabilityTests核对。 - 失败是返回值:
Error.NotFound、Error.Conflict、Error.Validation带错误码、消息键与参数,管道转成 404 / 409 / 400 的application/problem+json。不抛业务异常,也不返回伪成功。 - 事务由管道开,操作里不写;
context.CancellationToken一路传给仓储。 - 编码唯一的检查只数当前租户的行,因为仓储自带租户条件。
- 批量删除逐项给结果:
BatchResult的succeeded列出删掉的主键,不存在的主键各记一条failed(带INVENTORY_NOTFOUND_001与文案),其余照删。删除是软删除。
列表查询
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using SqlSugar;
using XiHan.BasicApp.Contracts.Paging;
using XiHan.BasicApp.Inventory.Domain.Entities;
using XiHan.BasicApp.Inventory.Operations.Warehouses;
using XiHan.BasicApp.Runtime.Queries;
using XiHan.Framework.Persistence.SqlSugar;
using XiHan.Framework.Primitives;
namespace XiHan.BasicApp.Inventory.Queries;
/// <summary>
/// 仓库列表查询(SqlSugar 直查,租户库)
/// </summary>
/// <remarks>
/// 关键字匹配编码与名称;筛选 <c>code</c>(eq)、<c>name</c>(contains);排序 <c>code</c>、<c>name</c>、<c>createdAt</c>,缺省按创建时间倒序
/// </remarks>
/// <param name="unitOfWork">SqlSugar 工作单元</param>
public sealed class WarehouseQueries(SqlSugarUnitOfWork unitOfWork)
{
private const string FieldCode = "code";
private const string FieldName = "name";
private const string FieldCreatedAt = "createdAt";
/// <summary>
/// 分页列出仓库
/// </summary>
/// <param name="request">分页请求</param>
/// <param name="context">调用上下文</param>
public async ValueTask<Result<PageResult<WarehouseResponse>>> ListAsync(PageRequest request, InvocationContext context)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(context);
var query = await TenantScopedQuery.ForAsync<Warehouse>(unitOfWork.ConnectionFor(typeof(Warehouse)), context).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(request.Keyword))
{
var keyword = request.Keyword.Trim();
query = query.Where(w => w.Code.Contains(keyword) || w.Name.Contains(keyword));
}
foreach (var filter in request.Filters)
{
var value = filter.Value ?? string.Empty;
ISugarQueryable<Warehouse>? filtered = (filter.Field, filter.Operator) switch
{
(FieldCode, "eq") => query.Where(w => w.Code == value),
(FieldName, "contains") => query.Where(w => w.Name.Contains(value)),
_ => null,
};
if (filtered is null)
{
return Error.Validation(InventoryErrors.QueryUnsupported, InventoryMessages.FilterUnsupported, MessageArguments.Of(("field", filter.Field), ("operator", filter.Operator)));
}
query = filtered;
}
if (request.Sorts.Count == 0)
{
query = query.OrderBy(w => w.CreatedAt, OrderByType.Desc);
}
foreach (var sort in request.Sorts)
{
var direction = sort.Descending ? OrderByType.Desc : OrderByType.Asc;
var sorted = sort.Field switch
{
FieldCode => query.OrderBy(w => w.Code, direction),
FieldName => query.OrderBy(w => w.Name, direction),
FieldCreatedAt => query.OrderBy(w => w.CreatedAt, direction),
_ => null,
};
if (sorted is null)
{
return Error.Validation(InventoryErrors.QueryUnsupported, InventoryMessages.SortUnsupported, MessageArguments.Of(("field", sort.Field)));
}
query = sorted;
}
var total = new RefAsync<int>();
var rows = await query.ToPageListAsync(request.Page.Index, request.Page.Size, total, context.CancellationToken).ConfigureAwait(false);
return new PageResult<WarehouseResponse>(rows.Select(WarehouseResponse.From).ToList(), total.Value, request.Page);
}
}- 分页、筛选、排序这类直接查库的读在
Queries/里写,以TenantScopedQuery.ForAsync<T>起手:按实体落点取连接,补上软删除、租户与实体过滤器(如数据范围)的条件,与仓储看到的行一致;没有租户的调用一行也查不到。 - 筛选与排序只认白名单里的字段,其余返回 400
INVENTORY_VALIDATION_001,不静默忽略。页码、每页条数、筛选与排序的条数上限由框架校验PageRequest时把关,见接口对接指南。
序列化上下文与 Feature
// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Text.Json.Serialization;
using XiHan.BasicApp.Contracts.Batch;
using XiHan.BasicApp.Contracts.Paging;
using XiHan.BasicApp.Inventory.Operations.Warehouses;
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包的 JSON 序列化上下文(源生成)
/// </summary>
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
UseStringEnumConverter = true)]
[JsonSerializable(typeof(CreateWarehouseRequest))]
[JsonSerializable(typeof(GetWarehouseRequest))]
[JsonSerializable(typeof(UpdateWarehouseRequest))]
[JsonSerializable(typeof(WarehouseIdsRequest))]
[JsonSerializable(typeof(WarehouseResponse))]
[JsonSerializable(typeof(PageRequest))]
[JsonSerializable(typeof(PageResult<WarehouseResponse>))]
[JsonSerializable(typeof(BatchResult))]
public sealed partial class InventoryJsonContext : JsonSerializerContext;// Copyright (c) 2021-Present XiHanFun and contributors.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.Extensions.DependencyInjection;
using XiHan.BasicApp.Contracts;
using XiHan.BasicApp.Contracts.Pages;
using XiHan.BasicApp.Contracts.Security;
using XiHan.BasicApp.Inventory.Queries;
using XiHan.BasicApp.Runtime;
using XiHan.Framework.Kernel;
using XiHan.Framework.Kernel.Hosting;
using XiHan.Framework.Localization.Abstractions;
using XiHan.Framework.MultiTenancy.Abstractions;
using XiHan.Framework.Persistence.Abstractions;
using XiHan.Framework.Primitives;
using XiHan.Framework.Primitives.Manifests;
using XiHan.Framework.Security.Abstractions;
[assembly: AppPackage("Inventory", AppPackageRanks.Module)]
namespace XiHan.BasicApp.Inventory;
/// <summary>
/// 库存包(Tier 3)
/// </summary>
/// <remarks>
/// 仓库是租户库实体,只在租户侧管理:权限码全在租户侧,平台主体的菜单与操作里都没有
/// </remarks>
public sealed class InventoryFeature : IFeature
{
/// <inheritdoc />
public Manifest Manifest { get; } = new()
{
Id = AppInfo.ManifestIdPrefix + "inventory",
Package = "XiHan.BasicApp.Inventory",
Version = AppInfo.Version,
Primitives = 1,
Stability = Stability.Preview,
Kind = ManifestKind.Capability,
Provides = [new CapabilityDeclaration(InventoryCapabilities.Inventory, InventoryCapabilities.Version)],
Requires =
[
new CapabilityRequirement(KernelCapabilities.Hosting, KernelCapabilities.Version),
new CapabilityRequirement(PersistenceCapabilities.Relational, PersistenceCapabilities.Version),
new CapabilityRequirement(SecurityCapabilities.Authorization, SecurityCapabilities.Version),
new CapabilityRequirement(MultiTenancyCapabilities.Context, MultiTenancyCapabilities.Version),
new CapabilityRequirement(RuntimeCapabilities.Runtime, RuntimeCapabilities.Version),
],
Contributes = new Contributions
{
Permissions = InventoryPermissions.All.Select(static p => p.Code).ToList(),
},
Entry = typeof(InventoryFeature).FullName,
};
/// <inheritdoc />
public void Configure(FeatureContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.Services.AddMessageCatalog(InventoryMessages.Catalog);
context.Services.AddGeneratedRepositories();
context.Services.AddScoped<WarehouseQueries>();
context.Services.AddPermissionCatalog("inventory", InventoryPermissions.All);
context.Services.AddPageCatalog("inventory", InventoryPages.All);
foreach (var permission in InventoryPermissions.All)
{
context.AddPermission(permission.ToDefinition());
}
context.AddGeneratedOperations();
}
}[assembly: AppPackage("Inventory", AppPackageRanks.Module)]声明这是 Tier 3 的包。架构测试按宿主的工程引用收集包,层级、目录、文案键与稳定级别的检查都会带上它,不用另外登记。Manifest的 ID 是AppInfo.ManifestIdPrefix加包名小写,Provides/Requires声明提供与依赖的能力,Contributes.Permissions列出本包的权限码。Configure里逐项显式登记:消息目录、生成的仓储、查询类、权限目录与页面目录(第一个参数是包名小写)、框架的权限定义、生成的操作。没有约定扫描,漏登记的东西就不存在。
登记进宿主
新包要在解决方案与宿主里改四处。先加进解决方案与宿主的工程引用:
<Folder Name="/3.Optional/">
…
<Project Path="src/XiHan.BasicApp.AI/XiHan.BasicApp.AI.csproj" />
+ <Project Path="src/XiHan.BasicApp.Inventory/XiHan.BasicApp.Inventory.csproj" />
</Folder> <ProjectReference Include="../XiHan.BasicApp.AI/XiHan.BasicApp.AI.csproj" />
+ <ProjectReference Include="../XiHan.BasicApp.Inventory/XiHan.BasicApp.Inventory.csproj" />
</ItemGroup>用 backend/XiHanFun.Local.slnx 联调框架源码时,在它的 /XiHan.BasicApp/backend/src/ 目录下加同样一行 <Project Path="src/XiHan.BasicApp.Inventory/XiHan.BasicApp.Inventory.csproj" />。
再装配 Feature,并给接口文档加一个分组(组名即包名小写,第二个参数是分组的排序):
using XiHan.BasicApp.Identity.Infrastructure.External;
+using XiHan.BasicApp.Inventory;
using XiHan.BasicApp.Maintenance;
…
.UseFeature<WebhooksProtocolFeature>()
- .UseFeature<OpenPlatformFeature>();
+ .UseFeature<OpenPlatformFeature>()
+ .UseFeature<InventoryFeature>(); Group("plugins", 150),
+ Group("inventory", 200),
],这样装配的包总是启用。要像 Workflow、Chat 那样能用 BasicApp:Modules:<名>:Enabled 关掉,见新增能力包。
前端模块
在 frontend/src/modules 下建 inventory 目录。main.ts 按 src/modules/*/setup.ts 装配模块,不另列清单:
/*
* Copyright (c) 2021-Present XiHanFun and contributors.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
import { registerModuleLocales } from '~/locales'
/** 库存模块的启动钩子:登记本模块文案,页面由后端菜单下发 */
export default function setup(): void {
registerModuleLocales(import.meta.glob<{ default: Record<string, unknown> }>('./locales/*.ts'))
}前端文案同样 10 个区域,菜单标题键 inventory.warehouses.title 就在这里:
/*
* Copyright (c) 2021-Present XiHanFun and contributors.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
// 文案文件:键集须与 en-US.ts 完全对称(scripts/check-i18n.mjs 守护)
export default {
inventory: {
warehouses: {
title: '仓库管理',
keyword: '关键词',
keyword_placeholder: '搜索仓库编码/名称',
create_title: '新建仓库',
edit_title: '编辑仓库',
actions: {
create: '新建仓库',
},
fields: {
code: '仓库编码',
name: '仓库名称',
address: '地址',
created_at: '创建时间',
},
},
},
}/*
* Copyright (c) 2021-Present XiHanFun and contributors.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
export default {
inventory: {
warehouses: {
title: 'Warehouses',
keyword: 'Keyword',
keyword_placeholder: 'Search warehouse code/name',
create_title: 'New warehouse',
edit_title: 'Edit warehouse',
actions: {
create: 'New warehouse',
},
fields: {
code: 'Code',
name: 'Name',
address: 'Address',
created_at: 'Created at',
},
},
},
}其余八个区域放同一组键,pnpm check 里的 i18n:check 核对键集对称。
列表的数据资源与编辑弹窗的状态放进页面旁边的 composable:
/*
* Copyright (c) 2021-Present XiHanFun and contributors.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
import type { SchemaQueryParams, SchemaResource } from '~/components'
import type { ResponseOf } from '~/contracts'
import { computed, reactive, ref } from 'vue'
import { toPageRequest, toSchemaPageResult, warehouses as warehousesApi } from '~/contracts'
import { ApiError, throwOnFailed } from '~/request'
export type WarehouseRow = ResponseOf<'warehouses.list'>['items'][number]
/** 弹窗表单:新建与编辑共用(编码只在新建时可填) */
export interface WarehouseForm {
code: string
name: string
address: string
}
function emptyForm(): WarehouseForm {
return { code: '', name: '', address: '' }
}
function blankToNull(value: string): null | string {
return value.trim() === ''
? null
: value.trim()
}
/** SchemaPage 的资源:分页与删除;关键字匹配编码与名称 */
export function warehousesResource(): SchemaResource<WarehouseRow> {
return {
page: async (params: SchemaQueryParams) => toSchemaPageResult(
await warehousesApi.list(toPageRequest(params)),
params,
),
remove: async id => throwOnFailed(await warehousesApi.delete({
ids: [
String(id),
],
})),
}
}
/** 新建与编辑弹窗:字段级错误挂回对应字段,其余错误给整条提示 */
export function useWarehouseEditor() {
const open = ref(false)
const editing = ref<WarehouseRow | null>(null)
const form = reactive<WarehouseForm>(emptyForm())
const fieldErrors = ref<Record<string, string[]>>({})
const submitError = ref<string | null>(null)
const submitting = ref(false)
const isEdit = computed(() => editing.value !== null)
function reset(next: WarehouseForm) {
Object.assign(form, next)
fieldErrors.value = {}
submitError.value = null
}
function startCreate() {
editing.value = null
reset(emptyForm())
open.value = true
}
function startEdit(row: WarehouseRow) {
editing.value = row
reset({ code: row.code, name: row.name, address: row.address ?? '' })
open.value = true
}
function fieldError(field: keyof WarehouseForm): string | undefined {
return fieldErrors.value[field]?.[0]
}
async function submit(): Promise<boolean> {
submitting.value = true
submitError.value = null
fieldErrors.value = {}
try {
const current = editing.value
if (current) {
await warehousesApi.update({
id: current.id,
name: form.name.trim(),
address: blankToNull(form.address),
})
}
else {
await warehousesApi.create({
code: form.code.trim(),
name: form.name.trim(),
address: blankToNull(form.address),
})
}
open.value = false
return true
}
catch (error) {
if (error instanceof ApiError) {
fieldErrors.value = error.errors ?? {}
if (!error.hasFieldErrors)
submitError.value = error.detail
}
else {
submitError.value = String(error)
}
return false
}
finally {
submitting.value = false
}
}
return {
open,
isEdit,
form,
fieldError,
submitError,
submitting,
startCreate,
startEdit,
submit,
}
}页面本身:
<!--
Copyright (c) 2021-Present XiHanFun and contributors.
Licensed under the MIT License. See LICENSE in the project root for license information.
-->
<script lang="ts" setup>
import type { WarehouseRow } from './use-warehouses'
import type { ListFieldSchema, PageSchema, SchemaActionPayload, SchemaPageInstance } from '~/components'
import { XhFieldControl, XhFieldErrorText, XhFieldLabel, XhFieldRoot, XhFormRoot } from '@xihan-ui/vue'
import { computed, ref, useId } from 'vue'
import { useI18n } from 'vue-i18n'
import { deleteConfirmText, SchemaPage, XEditModal, XInput } from '~/components'
import { toast } from '~/composables'
import { useWarehouseEditor, warehousesResource } from './use-warehouses'
defineOptions({ name: 'InventoryWarehousesView' })
const { t } = useI18n()
const editor = useWarehouseEditor()
const resource = warehousesResource()
/** 编辑弹窗的保存钮靠这个 id 关联到表单 */
const editFormId = useId()
const schemaPageRef = ref<SchemaPageInstance | null>(null)
// SchemaPage 的行类型在框架边界放宽(Record):回调里按本页的行类型取用
const asRow = (row: object) => row as WarehouseRow
const fields = computed<ListFieldSchema[]>(() => [
{
key: 'keyword',
title: t('inventory.warehouses.keyword'),
dataType: 'string',
visible: false,
searchable: true,
searchPlaceholder: t('inventory.warehouses.keyword_placeholder'),
order: 0,
},
{
key: 'code',
title: t('inventory.warehouses.fields.code'),
dataType: 'string',
sortable: true,
minWidth: 140,
order: 1,
},
{
key: 'name',
title: t('inventory.warehouses.fields.name'),
dataType: 'string',
sortable: true,
minWidth: 180,
order: 2,
},
{
key: 'address',
title: t('inventory.warehouses.fields.address'),
dataType: 'string',
minWidth: 240,
order: 3,
},
{
key: 'createdAt',
title: t('inventory.warehouses.fields.created_at'),
dataType: 'datetime',
sortable: true,
minWidth: 170,
order: 4,
},
])
const schema = computed<PageSchema>(() => ({
pageCode: 'inventory.warehouses',
pageName: t('inventory.warehouses.title'),
rowKey: 'id',
batchRemovable: true,
removePermission: 'inventory.warehouses.delete',
fields: fields.value,
resource: resource as unknown as PageSchema['resource'],
actions: [
{
key: 'create',
title: t('inventory.warehouses.actions.create'),
scope: 'page',
tone: 'brand',
icon: 'lucide:plus',
permission: 'inventory.warehouses.create',
},
{
key: 'edit',
title: t('common.actions.edit'),
scope: 'row',
icon: 'lucide:pencil',
permission: 'inventory.warehouses.update',
},
{
key: 'delete',
title: t('common.actions.delete'),
scope: 'row',
icon: 'lucide:trash-2',
tone: 'danger',
confirm: true,
confirmText: row => deleteConfirmText(t, asRow(row).name),
permission: 'inventory.warehouses.delete',
},
],
}))
function reload() {
void schemaPageRef.value?.reload()
}
function onAction(payload: SchemaActionPayload) {
const row = payload.row
? asRow(payload.row)
: undefined
if (payload.key === 'create')
editor.startCreate()
else if (payload.key === 'edit' && row)
editor.startEdit(row)
else if (payload.key === 'delete' && row)
void removeRow(row)
}
async function removeRow(row: WarehouseRow) {
try {
await resource.remove?.(row.id)
toast.success(t('common.messages.delete_success'))
reload()
}
catch (error) {
toast.danger((error as Error).message || t('common.messages.delete_failed'))
}
}
async function onSubmit() {
if (await editor.submit()) {
toast.success(t('common.messages.save_success'))
reload()
}
}
</script>
<template>
<SchemaPage ref="schemaPageRef" :schema="schema" @action="onAction">
<XEditModal
v-model:show="editor.open.value"
:title="editor.isEdit.value ? t('inventory.warehouses.edit_title') : t('inventory.warehouses.create_title')"
:loading="editor.submitting.value"
:form-id="editFormId"
>
<XhFormRoot :id="editFormId" class="xh-edit-form-grid" novalidate @submit="onSubmit">
<XhFieldRoot :invalid="!!editor.fieldError('code')" :required="!editor.isEdit.value">
<XhFieldLabel>{{ t('inventory.warehouses.fields.code') }}</XhFieldLabel>
<XhFieldControl>
<XInput v-model:value="editor.form.code" name="code" clearable autocomplete="off" :disabled="editor.isEdit.value" />
</XhFieldControl>
<XhFieldErrorText v-if="editor.fieldError('code')">
{{ editor.fieldError('code') }}
</XhFieldErrorText>
</XhFieldRoot>
<XhFieldRoot :invalid="!!editor.fieldError('name')" required>
<XhFieldLabel>{{ t('inventory.warehouses.fields.name') }}</XhFieldLabel>
<XhFieldControl>
<XInput v-model:value="editor.form.name" name="name" clearable />
</XhFieldControl>
<XhFieldErrorText v-if="editor.fieldError('name')">
{{ editor.fieldError('name') }}
</XhFieldErrorText>
</XhFieldRoot>
<XhFieldRoot class="xh-span-2" :invalid="!!editor.fieldError('address')">
<XhFieldLabel>{{ t('inventory.warehouses.fields.address') }}</XhFieldLabel>
<XhFieldControl>
<XInput v-model:value="editor.form.address" name="address" type="textarea" :rows="2" clearable />
</XhFieldControl>
<XhFieldErrorText v-if="editor.fieldError('address')">
{{ editor.fieldError('address') }}
</XhFieldErrorText>
</XhFieldRoot>
<p v-if="editor.submitError.value" class="xh-span-2 text-caption text-fg-danger" role="alert">
{{ editor.submitError.value }}
</p>
</XhFormRoot>
</XEditModal>
</SchemaPage>
</template>- 接口调用一律从
~/contracts取:warehouses客户端的五个方法与ResponseOf<'warehouses.list'>类型都由下一节的pnpm gen:contracts生成,生成之前这两个文件编译不过。 - 列表页用
SchemaPage:fields定列与搜索项(keyword列隐藏,只出现在搜索栏);resource.page用toPageRequest把查询参数换成PageRequest,再用toSchemaPageResult换回来;batchRemovable打开多选批量删除,removePermission给它加权限门控。 - 按钮的
permission填后端权限码,只决定显示与否;真正的拦截在后端。 - 新增与编辑共用一个
XEditModal+XhFormRoot,每个字段都有可见标签;后端返回的字段错误(ApiError.errors)挂回对应字段,其余错误显示在表单底部。批量删除的逐项失败经throwOnFailed变成异常,页面用 toast 提示。
页面写法的完整说明见 Schema 驱动页面。
导出契约并生成契约层
在仓库根执行:
dotnet run --project backend/src/XiHan.BasicApp.Host -- contracts export --out "$PWD/frontend/contracts"
cd frontend && pnpm gen:contractscontracts export 不启动应用、不连数据库,把 openapi.json、realtime.json 与 events.json 写进 frontend/contracts/;gen:contracts 据此生成 packages/contracts/*,warehouses 客户端与四个权限码随之出现。这些都是生成物,不手改,和后端改动放进同一个提交。
验证
在仓库根依次执行:
dotnet build backend/XiHan.BasicApp.slnx -c Release --no-restore
backend/test/XiHan.BasicApp.Architecture.Tests/bin/Release/net10.0/XiHan.BasicApp.Architecture.Tests
backend/test/XiHan.BasicApp.Integration.Tests/bin/Release/net10.0/XiHan.BasicApp.Integration.Tests \
-class XiHan.BasicApp.Integration.Tests.PageViewsTests
cd frontend && pnpm check| 检查 | 应看到 | 常见的失败 |
|---|---|---|
| Release 构建 | 0 警告、0 错误 | 缺 XML 文档、请求类型没登记进 InventoryJsonContext(XHG002),警告都按错误算 |
| 架构测试 | 全部通过;以 NuGet 包构建时 FrameworkPinTests 跳过 | 区域文件少键、多键,错误码格式不对,实体缺 [SugarColumn] |
PageViewsTests | 通过 | 后端登记的组件路径找不到对应的 index.vue,或者反过来 |
pnpm check | 十项依次通过 | lint 的换行规则(一行写了 4 个以上属性、又超过 40 个字符的对象要一个属性一行)、前端文案键不对称、忘了重新生成契约 |
提交之前再照常跑一遍全量测试(dotnet test --solution backend/XiHan.BasicApp.slnx -c Release --no-build)。
跑起来看
按快速开始重启后端。开发配置下宿主按实体建出 inv_warehouse 表与 ux_inv_warehouse_tenant_id_code 索引,种子把这一页对齐进菜单。用演示租户的管理员登录(租户 demo、用户名 admin、密码 Demo@123456),菜单顶层出现「仓库管理」。
命令行调用前,先按快速开始关掉图形验证码,然后:
# 以演示租户的管理员登录,取 token.accessToken
curl -X POST http://localhost:9710/api/auth:login \
-H 'Content-Type: application/json' \
-d '{"tenant":"demo","userName":"admin","password":"Demo@123456"}'
# 新建:201,响应是 WarehouseResponse
curl -X POST http://localhost:9710/api/warehouses \
-H 'Authorization: Bearer <JWT>' -H 'Content-Type: application/json' \
-d '{"code":"WH-SH-01","name":"Shanghai No.1"}'
# 列表
curl -X POST http://localhost:9710/api/warehouses:list \
-H 'Authorization: Bearer <JWT>' -H 'Content-Type: application/json' \
-d '{"page":{"index":1,"size":20}}'实际调用的结果:
| 调用 | 结果 |
|---|---|
新建 WH-SH-01 | 201,{"id":"…","code":"WH-SH-01","name":"Shanghai No.1","address":null,"createdAt":"…"} |
再建一次同一编码,带 Accept-Language: zh-CN | 409 INVENTORY_CONFLICT_001,detail 为「仓库编码 WH-SH-01 已被占用。」 |
| 列表 | 200,{"items":[…],"total":1,"page":{"index":1,"size":20}} |
列表按 address 排序 | 400 INVENTORY_VALIDATION_001 |
PUT /api/warehouses/{id} 改名称与地址 | 200,返回改后的仓库 |
| 删除一个存在的和一个不存在的主键 | 200,succeeded 一项,failed 一项 INVENTORY_NOTFOUND_001 |
| 删除后用同一编码再建 | 201 |
平台账号 superadmin 调列表 | 403 SECURITY_DENIED_004,缺少 inventory.warehouses.read |
已初始化过的库要给套餐放行
套餐白名单只在套餐创建时按当时的权限目录写入。在加这个包之前就初始化过的库里,四个新权限码不在任何套餐里:演示租户的 admin 虽然持有通配授予 *,也会被套餐收窄,菜单不出现,调用返回 403 SECURITY_DENIED_004。用 superadmin 在「租户管理 › 套餐」里给相应套餐放行这四个码(操作 editions.set-permissions),或者换一个空库重新初始化。加包之后才首次初始化的库,企业版含全部四个码,免费、基础、专业三档只含读权限 inventory.warehouses.read。规则见权限管理。
用代码生成器做同样的事
本页手写的文件,代码生成器能按一张表生成出来:在「平台管理 › 在线开发 › 代码生成」页导入表、配好列与要生成的操作,生成目标选「新建包」,就得到同样结构的后端包(工程、Feature、Capabilities、Permissions、Pages、Errors、Messages、JsonContext、10 种区域文案、操作与 Queries/)和前端模块(setup.ts、文案与 SchemaPage 页面,字段与资源另拆成 schema 文件)。生成的包同样是 Tier 3、业务数据落租户库;附带的 _registration/<资源>.md 写明要加进解决方案与宿主的几行,就是上面「登记进宿主」那一节。
手写一遍的意义在于看懂生成物:知道每个文件管什么、改需求时该动哪里。生成的范围、模板与「加入已有包」见代码生成。
