@macrowing/inbiz-codegen 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +592 -2
  2. package/bin/inbiz-codegen.mjs +7 -0
  3. package/package.json +32 -4
  4. package/scripts/prepare-templates.mjs +35 -0
  5. package/src/backend/init.mjs +170 -0
  6. package/src/config.mjs +150 -0
  7. package/src/favicon.mjs +100 -0
  8. package/src/generate.mjs +935 -0
  9. package/src/generated-output.mjs +107 -0
  10. package/src/index.mjs +346 -0
  11. package/src/menu/build.mjs +252 -0
  12. package/src/menu/check.mjs +163 -0
  13. package/src/menu/command.mjs +179 -0
  14. package/src/migrate-runtime.mjs +106 -0
  15. package/src/platform/client.mjs +167 -0
  16. package/src/platform/command.mjs +386 -0
  17. package/src/platform/pack.mjs +591 -0
  18. package/src/platform/recover.mjs +236 -0
  19. package/src/platform/startup.mjs +343 -0
  20. package/src/platform/state.mjs +116 -0
  21. package/src/platform/update.mjs +157 -0
  22. package/src/platform/zip.mjs +134 -0
  23. package/src/pull.mjs +284 -0
  24. package/src/scaffold/commands.mjs +349 -0
  25. package/src/scaffold/init.mjs +370 -0
  26. package/src/scaffold/template-files.mjs +40 -0
  27. package/src/scaffold/template-source.mjs +235 -0
  28. package/src/scaffold/template-sync.mjs +335 -0
  29. package/src/transform/heaviness.mjs +380 -0
  30. package/src/transform/preview-props.mjs +108 -0
  31. package/src/transform/published-page-links.mjs +61 -0
  32. package/src/transform/published-script.mjs +110 -0
  33. package/src/transform/registry.mjs +781 -0
  34. package/src/transform/schema-to-jsx.mjs +1708 -0
  35. package/src/util/des.mjs +10 -0
  36. package/templates/README.md +34 -0
  37. package/templates/backend/Directory.Build.props +19 -0
  38. package/templates/backend/Directory.Packages.props +49 -0
  39. package/templates/backend/Macrowing.Scaffold.slnx +13 -0
  40. package/templates/backend/host/Macrowing.Start/Init/app.json +8 -0
  41. package/templates/backend/host/Macrowing.Start/Init/menus.json +4 -0
  42. package/templates/backend/host/Macrowing.Start/Initialization/InitializationDefinition.cs +245 -0
  43. package/templates/backend/host/Macrowing.Start/Initialization/InitializationEndpoints.cs +57 -0
  44. package/templates/backend/host/Macrowing.Start/Initialization/InitializationHostedService.cs +63 -0
  45. package/templates/backend/host/Macrowing.Start/Initialization/InitializationOptions.cs +44 -0
  46. package/templates/backend/host/Macrowing.Start/Initialization/InitializationRunner.cs +294 -0
  47. package/templates/backend/host/Macrowing.Start/Initialization/InitializationState.cs +72 -0
  48. package/templates/backend/host/Macrowing.Start/Initialization/MenuFactory.cs +118 -0
  49. package/templates/backend/host/Macrowing.Start/Initialization/PackageBuilder.cs +317 -0
  50. package/templates/backend/host/Macrowing.Start/Initialization/PlatformAppImporter.cs +371 -0
  51. package/templates/backend/host/Macrowing.Start/Macrowing.Start.csproj +26 -0
  52. package/templates/backend/host/Macrowing.Start/Program.cs +33 -0
  53. package/templates/backend/host/Macrowing.Start/StartModule.cs +67 -0
  54. package/templates/backend/host/Macrowing.Start/appsettings.json +38 -0
  55. package/templates/backend/modules/Macrowing.Generated/Application/GeneratedApplicationAutoMapperProfile.cs +42 -0
  56. package/templates/backend/modules/Macrowing.Generated/Domain/Entities/GeneratedEntityBase.cs +72 -0
  57. package/templates/backend/modules/Macrowing.Generated/Domain/GeneratedConsts.cs +50 -0
  58. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContext.cs +55 -0
  59. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContextModelBuilderExtensions.cs +61 -0
  60. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/IGeneratedDbContext.cs +32 -0
  61. package/templates/backend/modules/Macrowing.Generated/GeneratedModule.cs +89 -0
  62. package/templates/backend/modules/Macrowing.Generated/Macrowing.Generated.csproj +22 -0
  63. package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsClient.cs +95 -0
  64. package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsModels.cs +81 -0
  65. package/templates/backend/modules/Macrowing.InBiz.SDK/Dictionary/DictionaryClient.cs +44 -0
  66. package/templates/backend/modules/Macrowing.InBiz.SDK/InBizSdkModule.cs +16 -0
  67. package/templates/backend/modules/Macrowing.InBiz.SDK/InterfaceEngine/InterfaceEngineClient.cs +50 -0
  68. package/templates/backend/modules/Macrowing.InBiz.SDK/Localization/LocalizationClient.cs +28 -0
  69. package/templates/backend/modules/Macrowing.InBiz.SDK/Macrowing.InBiz.SDK.csproj +16 -0
  70. package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageClient.cs +99 -0
  71. package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageModels.cs +63 -0
  72. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelClient.cs +131 -0
  73. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelQuery.cs +108 -0
  74. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelWrite.cs +44 -0
  75. package/templates/backend/modules/Macrowing.InBiz.SDK/Permission/PermissionClient.cs +86 -0
  76. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformException.cs +42 -0
  77. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformRegistration.cs +60 -0
  78. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformTransport.cs +96 -0
  79. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizRequestContext.cs +27 -0
  80. package/templates/backend/modules/Macrowing.InBiz.SDK/README.md +117 -0
  81. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsClient.cs +35 -0
  82. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsQuery.cs +20 -0
  83. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationRequests.cs +105 -0
  84. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationsClient.cs +53 -0
  85. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/README.md +132 -0
  86. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Tracking/WorkFlowTrackingClient.cs +50 -0
  87. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeClient.cs +78 -0
  88. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeModels.cs +34 -0
  89. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowContracts.cs +88 -0
  90. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowRegistration.cs +59 -0
  91. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowTransport.cs +163 -0
  92. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchClient.cs +59 -0
  93. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchModels.cs +76 -0
  94. package/templates/backend/modules/Macrowing.OC.SDK/Macrowing.OC.SDK.csproj +20 -0
  95. package/templates/backend/modules/Macrowing.OC.SDK/OcSdkModule.cs +18 -0
  96. package/templates/backend/modules/Macrowing.OC.SDK/Protos/README.md +22 -0
  97. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/Macrowing.InBiz.SDK.Tests.csproj +14 -0
  98. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformContractTests.cs +288 -0
  99. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformLiveTests.cs +173 -0
  100. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowHttpServer.cs +113 -0
  101. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowLiveTests.cs +269 -0
  102. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowOperationsTests.cs +80 -0
  103. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowQueryTests.cs +163 -0
  104. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowTransportTests.cs +111 -0
  105. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowUpgradeTests.cs +87 -0
  106. package/templates/frontend/components/README.md +39 -0
  107. package/templates/frontend/components/app-components/README.md +33 -0
  108. package/templates/frontend/components/app-components/common/.gitkeep +0 -0
  109. package/templates/frontend/components/app-components/components/.gitkeep +0 -0
  110. package/templates/frontend/components/app-components/package.json +20 -0
  111. package/templates/frontend/mgt/.umirc.ts +574 -0
  112. package/templates/frontend/mgt/package.json +96 -0
  113. package/templates/frontend/mgt/src/app-extends.ts +9 -0
  114. package/templates/frontend/mgt/src/app.tsx +20 -0
  115. package/templates/frontend/mgt/src/config/app.ts +31 -0
  116. package/templates/frontend/mgt/src/layout/header.tsx +14 -0
  117. package/templates/frontend/mgt/src/layout/index.tsx +11 -0
  118. package/templates/frontend/mgt/src/layout/sidebar.tsx +14 -0
  119. package/templates/frontend/mgt/src/locales.ts +8 -0
  120. package/templates/frontend/mgt/src/pages/.gitkeep +0 -0
  121. package/templates/frontend/mgt/src/root.tsx +12 -0
  122. package/templates/frontend/mgt/src/route-view.tsx +3 -0
  123. package/templates/frontend/mgt/src/runtime.ts +21 -0
  124. package/templates/frontend/mgt/src/styles/app.css +1 -0
  125. package/templates/frontend/mgt/src/styles/layout.less +79 -0
  126. package/templates/frontend/mgt/tsconfig.json +65 -0
  127. package/templates/frontend/mgt/typings.d.ts +57 -0
  128. package/templates/frontend/wap/.umirc.ts +574 -0
  129. package/templates/frontend/wap/package.json +73 -0
  130. package/templates/frontend/wap/src/app-extends.ts +9 -0
  131. package/templates/frontend/wap/src/app.tsx +28 -0
  132. package/templates/frontend/wap/src/config/app.ts +31 -0
  133. package/templates/frontend/wap/src/layout/header.tsx +14 -0
  134. package/templates/frontend/wap/src/layout/index.tsx +18 -0
  135. package/templates/frontend/wap/src/layout/sidebar.tsx +14 -0
  136. package/templates/frontend/wap/src/locales.ts +8 -0
  137. package/templates/frontend/wap/src/pages/.gitkeep +0 -0
  138. package/templates/frontend/wap/src/root.tsx +12 -0
  139. package/templates/frontend/wap/src/route-view.tsx +3 -0
  140. package/templates/frontend/wap/src/runtime.ts +21 -0
  141. package/templates/frontend/wap/src/styles/adaptation.less +190 -0
  142. package/templates/frontend/wap/src/styles/app.css +7 -0
  143. package/templates/frontend/wap/src/styles/global.less +81 -0
  144. package/templates/frontend/wap/src/styles/layout.less +92 -0
  145. package/templates/frontend/wap/tsconfig.json +66 -0
  146. package/templates/frontend/wap/typings.d.ts +24 -0
  147. package/templates/frontend/web/.umirc.ts +574 -0
  148. package/templates/frontend/web/package.json +26 -0
  149. package/templates/frontend/web/src/app-extends.ts +9 -0
  150. package/templates/frontend/web/src/app.tsx +25 -0
  151. package/templates/frontend/web/src/config/app.ts +31 -0
  152. package/templates/frontend/web/src/layout/header.tsx +14 -0
  153. package/templates/frontend/web/src/layout/index.tsx +11 -0
  154. package/templates/frontend/web/src/layout/sidebar.tsx +14 -0
  155. package/templates/frontend/web/src/locales.ts +8 -0
  156. package/templates/frontend/web/src/root.tsx +12 -0
  157. package/templates/frontend/web/src/route-view.tsx +3 -0
  158. package/templates/frontend/web/src/runtime.ts +21 -0
  159. package/templates/frontend/web/src/styles/app.css +104 -0
  160. package/templates/frontend/web/src/styles/layout.less +124 -0
  161. package/templates/frontend/web/tsconfig.json +91 -0
  162. package/templates/frontend/web/typings.d.ts +46 -0
  163. package/templates/package.json +14 -0
@@ -0,0 +1,132 @@
1
+ # InBiz WorkFlow SDK
2
+
3
+ 代码和公开命名空间均为 `Macrowing.InBiz.SDK.WorkFlow`。按场景注入所需接口;每个客户端共用同一套 HTTP、鉴权和错误处理。
4
+
5
+ ## 快速接入
6
+
7
+ 1. 引用 `Macrowing.InBiz.SDK`。后台模板的 `InBizSdkModule` 已注册客户端;独立宿主可在已有 `IConfiguration` 的服务容器中调用 `services.AddInBizWorkFlow()`。
8
+ 2. 配置 `InBiz:WorkFlow:BaseUrl`,例如 `https://workflow.example/edoc2Flow-web/`。地址必须带引擎的部署路径,不要填 Swagger 地址或单个接口地址。也可用环境变量 `InBiz__WorkFlow__BaseUrl`。`InBiz:WorkFlow:Timeout` 默认 `00:00:30`。
9
+ 3. 每次调用传入当前会话的 `WorkFlowCredential.Organization(orgToken, loginName)`,或 `WorkFlowCredential.Jwt(jwt)`。`loginName` 可省略,是否需要取决于引擎认证方式。`userId` 是工作台查询参数,不是令牌或登录名,应用应从可信会话中取得。
10
+
11
+ ```csharp
12
+ using Macrowing.InBiz.SDK.WorkFlow;
13
+
14
+ // workbench 通过构造函数注入;orgToken、loginName 和 userId 来自当前会话。
15
+ var credential = WorkFlowCredential.Organization(orgToken, loginName);
16
+ var pending = await workbench.GetMyPendingTasksAsync(
17
+ credential, new WorkFlowListQuery(userId) { PageIndex = 1, PageSize = 20 }, cancellationToken);
18
+ var rows = pending.Details?.Rows;
19
+ ```
20
+
21
+ ## 接口索引
22
+
23
+ ### 流程办理:`IWorkFlowOperationsClient`
24
+
25
+ | SDK 方法 | 用途 | 引擎动作(`process/operation/`) |
26
+ | --- | --- | --- |
27
+ | `StartProcessAsync` | 发起流程,返回实例 ID | `POST initiatingProcess` |
28
+ | `CompleteTaskAsync` | 完成或拒绝当前任务 | `POST processCompletion` |
29
+ | `ReturnTaskAsync` | 退回上一步、发起人,或退回发起人修改 | `POST processReturn` |
30
+ | `StopProcessAsync` | 终止实例 | `POST processStop` |
31
+ | `CanSaveDraftAsync` | 查询是否允许存草稿,不写入草稿 | `GET getIsDrafts` |
32
+
33
+ 发起时优先传 `ProcessDefinitionId`,可以锁定指定版本。仅按 `ProcessKey` 发起时不要传 `BusinessKey`:引擎在关联业务记录和清理草稿时会用定义 ID 查找流程。变量用 `Variables = [new("approved", "true")]`;引擎变量的值是字符串,SDK 负责按协议编码为 `variablesParams`。退回目标用 `WorkFlowReturnTarget`,调用方无须拼写 `retrunType`。
34
+
35
+ ### 工作台:`IWorkFlowWorkbenchClient`
36
+
37
+ 全部为 `GET process/getResults/…`,返回 `WorkFlowPage`。分页和过滤条件由 SDK 编码为平铺查询参数。
38
+
39
+ | SDK 方法 | 用途 | 引擎动作 |
40
+ | --- | --- | --- |
41
+ | `GetStartableProcessesAsync` | 可发起的流程定义 | `getMyApply` |
42
+ | `GetMyPendingTasksAsync` | 我的待办 | `getMyInbox` |
43
+ | `GetMyCompletedTasksAsync` | 我的已办 | `getMyComplete` |
44
+ | `GetMyArchivedProcessesAsync` | 我的归档 | `getMyArchive` |
45
+ | `GetMyCopiedProcessesAsync` | 抄送给我 | `getMyCctome` |
46
+ | `GetMyInitiatedProcessesAsync` | 我发起的流程 | `getMyInitiatorv6` |
47
+
48
+ ### 流程详情:`IWorkFlowDetailsClient`
49
+
50
+ 全部为 `GET process/getResults/…`。
51
+
52
+ | SDK 方法 | 用途 | 引擎动作 |
53
+ | --- | --- | --- |
54
+ | `GetProcessDetailsAsync` | 根据任务或实例获得详情和表单入口信息 | `getProcessDetails` |
55
+ | `GetStartProcessDetailsAsync` | 发起前查询表单和所需参数 | `getInitProcessDetails` |
56
+ | `UsesNewProcessAttributesAsync` | 判断该实例定义是否使用新版流程属性 | `getProcessType` |
57
+
58
+ ### 日志与流程图:`IWorkFlowTrackingClient`
59
+
60
+ | SDK 方法 | 用途 | 引擎请求 |
61
+ | --- | --- | --- |
62
+ | `GetProcessLogAsync` | 按单个实例 ID 查日志;多个实例分别查询 | `GET process/getResults/getProcessLog` |
63
+ | `GetProcessLogChartAsync` | 按定义取得流程图结构 | `GET process/logs/{processDefinitionId}/getProcessLogChart` |
64
+ | `GetHighlightedNodesAsync` | 按实例取得需要高亮的节点和连线数据 | `GET process/logs/process-instance/{processInstanceId}/getHighlighted` |
65
+ | `GetActivityInfosAsync` | 按实例取得活动节点信息 | `GET process/logs/process-instance/{processInstanceId}/getActivityInfos` |
66
+ | `GetFlowChartAsync` | 按定义或实例取得流程图数据 | `GET process/logs/process-instance/getFlowChart` |
67
+
68
+ ### 引擎升级:`IWorkFlowUpgradeClient`
69
+
70
+ 由有授权的运维入口调用;不要挂到普通用户的业务流程、宿主启动或自动重试任务。
71
+
72
+ | SDK 方法 | 用途 | 引擎动作(`process/upgrade/`) |
73
+ | --- | --- | --- |
74
+ | `CheckUpgradeAsync` | 检测旧版设计(`LegacyDesign`)或新版设计器 XML(`DesignerXml`)是否需要升级 | `GET upgradeTesting` |
75
+ | `UpgradeDesignAsync` | 提交流程设计全量迁移 | `POST processUpgrade` |
76
+ | `UpgradeXmlAsync` | 提交设计器 XML 全量迁移 | `POST processUpgradexml` |
77
+ | `ReleaseUpgradedDesignsAsync` | 提交升级后流程设计的发布 | `POST upgradeRelease` |
78
+ | `UpgradeDocumentControlAsync` | 迁移文控流程,返回引擎报告 | `POST docConProcessUpgrade` |
79
+ | `GetUpgradeResultAsync` | 根据提交返回的 `job.Key` 查询进度 | `GET getUpgadeResult` |
80
+
81
+ - 四个升级写请求都不带请求体。设计迁移和 XML 迁移在 HTTP 200 内返回业务码 `403` 和 `details: "processUpgrade"` 时表示任务已提交;其他普通拒绝不会被当作提交成功。
82
+ - 两种迁移共享引擎固定键 `processUpgrade`,不能并发执行或让多个调用方同时轮询同一个任务。发布使用固定键 `upgradeRelease`,也不是唯一任务 ID。
83
+ - 进度业务码 `200` 是无结果(不代表成功),`201` 是进行中,`202` 是已结束。读取 `Finished` 会消费引擎缓存,应保存第一次拿到的 `Log` 并检查逐条执行结果。取消等待只取消 SDK 请求,不会撤回引擎已接收的任务。
84
+
85
+ ## 返回值和错误
86
+
87
+ 常规接口使用 `WorkFlowResult<T>`;返回动态表单、图表或列表行的接口保留 `JsonElement`,避免丢失引擎数据。不要把可空的 `Details` 当作调用失败的唯一依据。
88
+
89
+ | 异常 | 含义 |
90
+ | --- | --- |
91
+ | `WorkFlowSessionException` | 引擎明确返回会话失效标识 `ErrorCode4` |
92
+ | `WorkFlowBusinessException` | HTTP 已完成,但引擎拒绝业务操作 |
93
+ | `WorkFlowHttpException` | 上游 HTTP 错误或重定向;普通 HTTP 403 不等同于登录过期 |
94
+ | `WorkFlowProtocolException` | JSON 或响应结构不符合契约 |
95
+ | `OperationCanceledException` | 调用取消或 HTTP 超时;写操作是否已经生效需要查询确认 |
96
+
97
+ 引擎要求在查询参数中传令牌。部署时优先使用 HTTPS,并在反向代理、访问日志和链路采集中关闭完整查询串记录。SDK 不跟随重定向、不复用 Cookie,也不添加写请求重试策略。
98
+
99
+ ## 验证范围
100
+
101
+ 本 SDK 收录以上 25 个接口。未封装 Swagger 中的全部接口,例如批量操作、委派和设计器内部接口。映射以流程引擎 Java 控制器、服务实现和 Swagger 为准。`Macrowing.InBiz.SDK.Tests` 用 Kestrel 回环地址运行真实 HTTP 契约测试,不需要共享环境或真实凭据。
102
+
103
+ 在后台模板根目录执行:
104
+
105
+ ```powershell
106
+ dotnet test Macrowing.Scaffold.slnx
107
+ ```
108
+
109
+ ### 真实引擎验收
110
+
111
+ `WorkFlowLiveTests` 与回环测试分开,默认显示为跳过。启用后会向指定的真实引擎写入两个实例;只在可写的隔离验收环境运行。
112
+
113
+ 1. 用流程设计器创建并发布一个名称以 `SDK Acceptance ` 开头的独立测试定义。使用有权限且显示的流程分组(`isShow=0`):开始 → 提交(发起账号)→ 一级审核(发起账号)→ 二级审核(另一个验收账号)→ 结束。原版引擎发起时会自动办理紧跟开始事件的首个用户任务,因此提交节点必须独立,不能当作一级审核。两级审核不配置自动跳转,开启办理、二级退回上一步和一级终止权限,不挂业务表单写入、通知或外部回调。使用流程管理入口确认发布成功并授予发起权限。
114
+ 2. 通过正常登录获取两个验收账号的会话。把下表变量注入测试进程,不将令牌写入文件、命令历史或测试报告。`USER_ID` 使用流程引擎里的办理人 ID,不是登录名。
115
+ 3. 执行筛选命令。用例先核对可发起列表和指定定义版本,再分别运行“发起 → 推进 → 退回 → 终止”和“发起 → 逐级办理 → 正常办结”。断言按实例 ID 回查待办、已办、我发起、归档及相应操作日志。测试输出记录定义 ID、业务键、实例 ID、待办节点和流程终态。
116
+ 4. 验收后按输出中的实例 ID 和独立定义清理。本用例保留记录供工作台人工交叉验收,不调用批量删除、全量迁移或自动重试写操作。若发起请求超时,先用发起前输出的唯一业务键对账,再决定是否重跑。
117
+
118
+ 原版引擎的「已办」只列出仍在运行的实例;终止和正常办结之后,参与人应在「归档」而不是「已办」找到该实例。归档由引擎在事务提交后异步写入;验收对每个参与人最多等待 15 秒,只轮询归档读接口,不重放流程操作。
119
+
120
+ | 变量 | 用途 |
121
+ | --- | --- |
122
+ | `INBIZ_WF_LIVE` | 必须由操作者设为 `isolated-test`,表示已确认环境可写且隔离 |
123
+ | `INBIZ_WF_BASE_URL` | 测试引擎服务根地址,包含 `/edoc2Flow-web/` |
124
+ | `INBIZ_WF_DEFINITION_NAME`、`INBIZ_WF_DEFINITION_ID` | 独立定义的名称及实际部署版本 ID |
125
+ | `INBIZ_WF_FIRST_STEP`、`INBIZ_WF_REVIEW_STEP` | 一级、二级审核节点在工作台显示的名称 |
126
+ | `INBIZ_WF_STARTER_USER_ID`、`INBIZ_WF_REVIEWER_USER_ID` | 两个不同的验收账号 ID |
127
+ | `INBIZ_WF_STARTER_ORG_TOKEN`、`INBIZ_WF_REVIEWER_ORG_TOKEN` | 两个账号各自的组织令牌;可选对应的 `*_LOGIN_NAME` |
128
+ | `INBIZ_WF_STARTER_JWT`、`INBIZ_WF_REVIEWER_JWT` | 对应账号的 JWT,可替代其组织令牌,不同时设置两种 |
129
+
130
+ ```powershell
131
+ dotnet test Macrowing.Scaffold.slnx -c Release --filter 'Category=WorkFlowLive' --logger 'console;verbosity=detailed'
132
+ ```
@@ -0,0 +1,50 @@
1
+ using System.Text.Json;
2
+
3
+ namespace Macrowing.InBiz.SDK.WorkFlow;
4
+
5
+ /// <summary>Read process history, flow charts and the nodes used to render them.</summary>
6
+ public interface IWorkFlowTrackingClient
7
+ {
8
+ /// <summary>Gets the logs for one process instance.</summary>
9
+ Task<WorkFlowResult<JsonElement?>> GetProcessLogAsync(WorkFlowCredential credential, string processInstanceId, CancellationToken cancellationToken = default);
10
+ /// <summary>Gets the definition-level chart used to render workflow logs.</summary>
11
+ Task<JsonElement> GetProcessLogChartAsync(WorkFlowCredential credential, string processDefinitionId, CancellationToken cancellationToken = default);
12
+ /// <summary>Gets the chart nodes and paths highlighted for an instance.</summary>
13
+ Task<JsonElement> GetHighlightedNodesAsync(WorkFlowCredential credential, string processInstanceId, CancellationToken cancellationToken = default);
14
+ /// <summary>Gets information about the activities executed in an instance.</summary>
15
+ Task<JsonElement> GetActivityInfosAsync(WorkFlowCredential credential, string processInstanceId, CancellationToken cancellationToken = default);
16
+ /// <summary>Gets the workflow chart by deployed definition or instance, with the optional engine chart type.</summary>
17
+ Task<WorkFlowResult<JsonElement?>> GetFlowChartAsync(WorkFlowCredential credential, string? processDefinitionId, string? processInstanceId, int? customType = null, CancellationToken cancellationToken = default);
18
+ }
19
+
20
+ internal sealed class WorkFlowTrackingClient(WorkFlowTransport transport) : IWorkFlowTrackingClient
21
+ {
22
+ private const string Logs = "process/logs/";
23
+ private const string InstanceLogs = Logs + "process-instance/";
24
+
25
+ public Task<WorkFlowResult<JsonElement?>> GetProcessLogAsync(WorkFlowCredential credential, string processInstanceId, CancellationToken cancellationToken)
26
+ {
27
+ ArgumentException.ThrowIfNullOrWhiteSpace(processInstanceId);
28
+ if (processInstanceId.Contains(','))
29
+ throw new ArgumentException("Query each process instance separately.", nameof(processInstanceId));
30
+ return transport.GetResultAsync<JsonElement?>(credential, HttpMethod.Get, "process/getResults/getProcessLog", cancellationToken,
31
+ [("processInstanceId", processInstanceId)]);
32
+ }
33
+
34
+ public Task<JsonElement> GetProcessLogChartAsync(WorkFlowCredential credential, string processDefinitionId, CancellationToken cancellationToken) =>
35
+ transport.GetValueAsync<JsonElement>(credential, Logs + WorkFlowTransport.PathSegment(processDefinitionId) + "/getProcessLogChart",
36
+ JsonValueKind.Object, cancellationToken);
37
+
38
+ public Task<JsonElement> GetHighlightedNodesAsync(WorkFlowCredential credential, string processInstanceId, CancellationToken cancellationToken) =>
39
+ transport.GetValueAsync<JsonElement>(credential, InstanceLogs + WorkFlowTransport.PathSegment(processInstanceId) + "/getHighlighted",
40
+ JsonValueKind.Object, cancellationToken);
41
+
42
+ public Task<JsonElement> GetActivityInfosAsync(WorkFlowCredential credential, string processInstanceId, CancellationToken cancellationToken) =>
43
+ transport.GetValueAsync<JsonElement>(credential, InstanceLogs + WorkFlowTransport.PathSegment(processInstanceId) + "/getActivityInfos",
44
+ JsonValueKind.Object, cancellationToken);
45
+
46
+ public Task<WorkFlowResult<JsonElement?>> GetFlowChartAsync(WorkFlowCredential credential, string? processDefinitionId, string? processInstanceId,
47
+ int? customType, CancellationToken cancellationToken) =>
48
+ transport.GetResultAsync<JsonElement?>(credential, HttpMethod.Get, InstanceLogs + "getFlowChart", cancellationToken,
49
+ [("processDefinitionId", processDefinitionId), ("processInstanceId", processInstanceId), ("customType", customType)]);
50
+ }
@@ -0,0 +1,78 @@
1
+ using System.Text.Json;
2
+
3
+ namespace Macrowing.InBiz.SDK.WorkFlow;
4
+
5
+ /// <summary>Engine-wide migration and publishing operations for authorized operators.</summary>
6
+ public interface IWorkFlowUpgradeClient
7
+ {
8
+ /// <summary>Runs the engine's upgrade readiness check for the selected migration family.</summary>
9
+ Task<WorkFlowResult<bool?>> CheckUpgradeAsync(WorkFlowCredential credential, WorkFlowUpgradeCheck check, CancellationToken cancellationToken = default);
10
+ /// <summary>Submits the engine-wide legacy design migration. Do not run concurrently with XML migration.</summary>
11
+ Task<WorkFlowUpgradeJob> UpgradeDesignAsync(WorkFlowCredential credential, CancellationToken cancellationToken = default);
12
+ /// <summary>Submits the engine-wide XML migration. Do not run concurrently with design migration.</summary>
13
+ Task<WorkFlowUpgradeJob> UpgradeXmlAsync(WorkFlowCredential credential, CancellationToken cancellationToken = default);
14
+ /// <summary>Submits a job that publishes migrated designs across the engine.</summary>
15
+ Task<WorkFlowUpgradeJob> ReleaseUpgradedDesignsAsync(WorkFlowCredential credential, CancellationToken cancellationToken = default);
16
+ /// <summary>Runs the document-control process migration for an authorized operator.</summary>
17
+ Task<WorkFlowResult<string>> UpgradeDocumentControlAsync(WorkFlowCredential credential, CancellationToken cancellationToken = default);
18
+ /// <summary>Reads progress. A Finished result consumes the engine's cached result and is not a success guarantee.</summary>
19
+ Task<WorkFlowUpgradeProgress> GetUpgradeResultAsync(WorkFlowCredential credential, string key, CancellationToken cancellationToken = default);
20
+ }
21
+
22
+ internal sealed class WorkFlowUpgradeClient(WorkFlowTransport transport) : IWorkFlowUpgradeClient
23
+ {
24
+ private const string Prefix = "process/upgrade/";
25
+
26
+ public Task<WorkFlowResult<bool?>> CheckUpgradeAsync(WorkFlowCredential credential, WorkFlowUpgradeCheck check, CancellationToken cancellationToken)
27
+ {
28
+ var type = check switch
29
+ {
30
+ WorkFlowUpgradeCheck.DesignerXml => "1",
31
+ WorkFlowUpgradeCheck.LegacyDesign => "0",
32
+ _ => throw new ArgumentOutOfRangeException(nameof(check))
33
+ };
34
+ return transport.GetResultAsync<bool?>(credential, HttpMethod.Get, Prefix + "upgradeTesting", cancellationToken, [("type", type)]);
35
+ }
36
+
37
+ public Task<WorkFlowUpgradeJob> UpgradeDesignAsync(WorkFlowCredential credential, CancellationToken cancellationToken) =>
38
+ SubmitAsync(credential, "processUpgrade", "processUpgrade", "403", cancellationToken);
39
+
40
+ public Task<WorkFlowUpgradeJob> UpgradeXmlAsync(WorkFlowCredential credential, CancellationToken cancellationToken) =>
41
+ SubmitAsync(credential, "processUpgradexml", "processUpgrade", "403", cancellationToken);
42
+
43
+ public Task<WorkFlowUpgradeJob> ReleaseUpgradedDesignsAsync(WorkFlowCredential credential, CancellationToken cancellationToken) =>
44
+ SubmitAsync(credential, "upgradeRelease", "upgradeRelease", "200", cancellationToken);
45
+
46
+ public Task<WorkFlowResult<string>> UpgradeDocumentControlAsync(WorkFlowCredential credential, CancellationToken cancellationToken) =>
47
+ transport.GetResultAsync<string>(credential, HttpMethod.Post, Prefix + "docConProcessUpgrade", cancellationToken);
48
+
49
+ public async Task<WorkFlowUpgradeProgress> GetUpgradeResultAsync(WorkFlowCredential credential, string key, CancellationToken cancellationToken)
50
+ {
51
+ ArgumentException.ThrowIfNullOrWhiteSpace(key);
52
+ var result = await transport.GetEnvelopeAsync(credential, HttpMethod.Get, Prefix + "getUpgadeResult", cancellationToken, [("key", key)]);
53
+ var state = result.Code switch
54
+ {
55
+ "201" => WorkFlowUpgradeState.InProgress,
56
+ "202" => WorkFlowUpgradeState.Finished,
57
+ _ => WorkFlowUpgradeState.NoResult
58
+ };
59
+ if (state == WorkFlowUpgradeState.NoResult)
60
+ result.RequireSuccess();
61
+ return new(state, result.Code, result.ToResult<string>().Details, result.Message);
62
+ }
63
+
64
+ private async Task<WorkFlowUpgradeJob> SubmitAsync(WorkFlowCredential credential, string action, string expectedKey, string submittedCode,
65
+ CancellationToken cancellationToken)
66
+ {
67
+ var result = await transport.GetEnvelopeAsync(credential, HttpMethod.Post, Prefix + action, cancellationToken);
68
+ // Both migration endpoints retain a legacy failure code on accepted jobs. Only the exact job key confirms acceptance.
69
+ if ((result.Code == submittedCode || result.Code == "200") && string.IsNullOrEmpty(result.ErrorCode)
70
+ && result.Details is { ValueKind: JsonValueKind.String } details && details.GetString() == expectedKey)
71
+ {
72
+ return new(expectedKey, result.Code, result.Message);
73
+ }
74
+
75
+ result.RequireSuccess();
76
+ throw new WorkFlowProtocolException("The workflow engine did not return the expected upgrade job key.");
77
+ }
78
+ }
@@ -0,0 +1,34 @@
1
+ namespace Macrowing.InBiz.SDK.WorkFlow;
2
+
3
+ /// <summary>Migration family to check on the workflow engine.</summary>
4
+ public enum WorkFlowUpgradeCheck
5
+ {
6
+ /// <summary>Legacy workflow design migration.</summary>
7
+ LegacyDesign,
8
+ /// <summary>Workflow designer XML migration.</summary>
9
+ DesignerXml
10
+ }
11
+
12
+ /// <summary>An accepted migration or release job. Acceptance does not indicate successful completion.</summary>
13
+ /// <param name="Key">Engine job key to pass to the progress endpoint.</param>
14
+ /// <param name="EngineCode">Original submission code, including legacy acceptance codes.</param>
15
+ /// <param name="EngineMessage">Optional engine diagnostic.</param>
16
+ public sealed record WorkFlowUpgradeJob(string Key, string EngineCode, string? EngineMessage);
17
+
18
+ /// <summary>Progress state of a workflow upgrade job.</summary>
19
+ public enum WorkFlowUpgradeState
20
+ {
21
+ /// <summary>No cached result is available.</summary>
22
+ NoResult,
23
+ /// <summary>The engine reports the job is still running.</summary>
24
+ InProgress,
25
+ /// <summary>The engine finished and reported a final result; inspect the log for failures.</summary>
26
+ Finished
27
+ }
28
+
29
+ /// <summary>Result of reading upgrade progress from the workflow engine.</summary>
30
+ /// <param name="State">Progress state, not a success indicator.</param>
31
+ /// <param name="EngineCode">Original engine status code.</param>
32
+ /// <param name="Log">Engine progress or final log, when supplied.</param>
33
+ /// <param name="EngineMessage">Optional server message.</param>
34
+ public sealed record WorkFlowUpgradeProgress(WorkFlowUpgradeState State, string EngineCode, string? Log, string? EngineMessage);
@@ -0,0 +1,88 @@
1
+ using System.Net;
2
+ using System.Text.Json;
3
+
4
+ namespace Macrowing.InBiz.SDK.WorkFlow;
5
+
6
+ /// <summary>Authorized caller identity for one workflow-engine request.</summary>
7
+ public sealed class WorkFlowCredential
8
+ {
9
+ private WorkFlowCredential(string parameter, string token, string? loginName)
10
+ {
11
+ ArgumentException.ThrowIfNullOrWhiteSpace(token);
12
+ Parameter = parameter;
13
+ Token = token;
14
+ LoginName = loginName;
15
+ }
16
+
17
+ internal string Parameter { get; }
18
+ internal string Token { get; }
19
+ internal string? LoginName { get; }
20
+
21
+ /// <summary>Uses the workflow engine's organization-token authentication.</summary>
22
+ /// <param name="token">InBiz organization token.</param>
23
+ /// <param name="loginName">Login name when required by the deployment.</param>
24
+ public static WorkFlowCredential Organization(string token, string? loginName = null) => new("orgToken", token, loginName);
25
+ /// <summary>Uses a JWT issued for the workflow engine.</summary>
26
+ /// <param name="token">Workflow JWT without the Bearer prefix.</param>
27
+ public static WorkFlowCredential Jwt(string token) => new("token", token, null);
28
+ }
29
+
30
+ /// <summary>Successful response envelope returned by a workflow operation.</summary>
31
+ /// <typeparam name="T">Shape of the details payload.</typeparam>
32
+ /// <param name="Code">Original engine result code.</param>
33
+ /// <param name="Message">Optional engine message.</param>
34
+ /// <param name="Details">Action-specific result, possibly absent.</param>
35
+ public sealed record WorkFlowResult<T>(string Code, string? Message, T? Details);
36
+
37
+ /// <summary>Base exception for workflow-engine response failures.</summary>
38
+ /// <param name="message">Diagnostic summary.</param>
39
+ public class WorkFlowException(string message) : Exception(message);
40
+
41
+ /// <summary>The workflow engine rejected the session.</summary>
42
+ /// <param name="statusCode">Actual HTTP response status.</param>
43
+ public sealed class WorkFlowSessionException(HttpStatusCode statusCode)
44
+ : WorkFlowException("The workflow engine session is invalid or expired.")
45
+ {
46
+ /// <summary>Actual HTTP status, which may be 200 when the error is in the response body.</summary>
47
+ public HttpStatusCode StatusCode { get; } = statusCode;
48
+ /// <summary>Workflow engine's session error code.</summary>
49
+ public string ErrorCode => "ErrorCode4";
50
+ }
51
+
52
+ /// <summary>The workflow call failed with an HTTP error outside the engine result contract.</summary>
53
+ /// <param name="statusCode">Actual HTTP response status.</param>
54
+ public sealed class WorkFlowHttpException(HttpStatusCode statusCode)
55
+ : WorkFlowException($"The workflow engine returned HTTP {(int)statusCode}.")
56
+ {
57
+ /// <summary>Actual HTTP response status.</summary>
58
+ public HttpStatusCode StatusCode { get; } = statusCode;
59
+ }
60
+
61
+ /// <summary>The workflow engine returned a business failure.</summary>
62
+ public sealed class WorkFlowBusinessException : WorkFlowException
63
+ {
64
+ internal WorkFlowBusinessException(string code, string? engineMessage, string? errorCode, JsonElement? details, string? innerException)
65
+ : base("The workflow engine rejected the operation. Inspect the engine error fields for details.")
66
+ {
67
+ Code = code;
68
+ EngineMessage = engineMessage;
69
+ ErrorCode = errorCode;
70
+ Details = details;
71
+ EngineInnerException = innerException;
72
+ }
73
+
74
+ /// <summary>Original result code.</summary>
75
+ public string Code { get; }
76
+ /// <summary>Server message, which may include business data.</summary>
77
+ public string? EngineMessage { get; }
78
+ /// <summary>More specific engine error code, when supplied.</summary>
79
+ public string? ErrorCode { get; }
80
+ /// <summary>Engine error details. The shape depends on the operation.</summary>
81
+ public JsonElement? Details { get; }
82
+ /// <summary>Engine-provided diagnostic text. Do not expose it to end users or log it indiscriminately.</summary>
83
+ public string? EngineInnerException { get; }
84
+ }
85
+
86
+ /// <summary>A workflow response did not match the expected wire contract.</summary>
87
+ /// <param name="message">Description of the contract mismatch.</param>
88
+ public sealed class WorkFlowProtocolException(string message) : WorkFlowException(message);
@@ -0,0 +1,59 @@
1
+ using Microsoft.Extensions.DependencyInjection;
2
+ using Microsoft.Extensions.Options;
3
+
4
+ namespace Macrowing.InBiz.SDK.WorkFlow;
5
+
6
+ /// <summary>Connection settings for the separate workflow engine service.</summary>
7
+ public sealed class WorkFlowOptions
8
+ {
9
+ /// <summary>Configuration section used by the workflow clients.</summary>
10
+ public const string SectionName = "InBiz:WorkFlow";
11
+
12
+ /// <summary>Absolute service URL including the context path, e.g. https://workflow.example/edoc2Flow-web/.</summary>
13
+ public string? BaseUrl { get; set; }
14
+
15
+ /// <summary>Maximum duration of an engine request. Defaults to 30 seconds.</summary>
16
+ public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30);
17
+ }
18
+
19
+ /// <summary>Dependency injection setup for workflow clients.</summary>
20
+ public static class WorkFlowRegistration
21
+ {
22
+ /// <summary>Registers all workflow clients. ABP hosts using <see cref="InBizSdkModule"/> already call this.</summary>
23
+ /// <param name="services">Host service collection.</param>
24
+ /// <returns>The same service collection.</returns>
25
+ public static IServiceCollection AddInBizWorkFlow(this IServiceCollection services)
26
+ {
27
+ services.AddOptions<WorkFlowOptions>().BindConfiguration(WorkFlowOptions.SectionName);
28
+
29
+ services.AddHttpClient("InBiz.WorkFlow", (provider, client) =>
30
+ {
31
+ var options = provider.GetRequiredService<IOptions<WorkFlowOptions>>().Value;
32
+ if (!Uri.TryCreate(options.BaseUrl, UriKind.Absolute, out var uri)
33
+ || uri.Scheme is not ("http" or "https") || uri.Host.Length == 0
34
+ || uri.Query.Length != 0 || uri.Fragment.Length != 0 || uri.UserInfo.Length != 0)
35
+ {
36
+ throw new InvalidOperationException("Configure InBiz:WorkFlow:BaseUrl as an absolute HTTP(S) service URL without credentials, query or fragment.");
37
+ }
38
+
39
+ client.BaseAddress = new Uri(uri.AbsoluteUri.TrimEnd('/') + "/");
40
+ client.Timeout = options.Timeout;
41
+ client.MaxResponseContentBufferSize = 32 * 1024 * 1024;
42
+ })
43
+ .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
44
+ {
45
+ AllowAutoRedirect = false,
46
+ UseCookies = false
47
+ })
48
+ // Spring authenticates via query parameters. Do not log request URIs for this client.
49
+ .RemoveAllLoggers();
50
+
51
+ services.AddTransient<WorkFlowTransport>();
52
+ services.AddTransient<IWorkFlowOperationsClient, WorkFlowOperationsClient>();
53
+ services.AddTransient<IWorkFlowWorkbenchClient, WorkFlowWorkbenchClient>();
54
+ services.AddTransient<IWorkFlowDetailsClient, WorkFlowDetailsClient>();
55
+ services.AddTransient<IWorkFlowTrackingClient, WorkFlowTrackingClient>();
56
+ services.AddTransient<IWorkFlowUpgradeClient, WorkFlowUpgradeClient>();
57
+ return services;
58
+ }
59
+ }
@@ -0,0 +1,163 @@
1
+ using System.Globalization;
2
+ using System.Net;
3
+ using System.Net.Http.Json;
4
+ using System.Text.Json;
5
+ using System.Text.Json.Serialization;
6
+
7
+ namespace Macrowing.InBiz.SDK.WorkFlow;
8
+
9
+ internal sealed class WorkFlowTransport(IHttpClientFactory factory)
10
+ {
11
+ private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
12
+ {
13
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
14
+ };
15
+
16
+ internal sealed record Envelope(string Code, string? Message, JsonElement? Details, string? InnerException, string? ErrorCode)
17
+ {
18
+ public void RequireSuccess()
19
+ {
20
+ if (Code != "200")
21
+ throw new WorkFlowBusinessException(Code, Message, ErrorCode, Details, InnerException);
22
+ }
23
+
24
+ public WorkFlowResult<T> ToResult<T>() => new(Code, Message, Details is { } value ? Decode<T>(value) : default);
25
+ }
26
+
27
+ internal static string PathSegment(string value)
28
+ {
29
+ ArgumentException.ThrowIfNullOrWhiteSpace(value);
30
+ if (value is "." or ".." || value.Contains('/') || value.Contains('\\'))
31
+ throw new ArgumentException("Expected a single workflow ID.", nameof(value));
32
+ return Uri.EscapeDataString(value);
33
+ }
34
+
35
+ internal async Task<Envelope> GetEnvelopeAsync(WorkFlowCredential credential, HttpMethod method, string route,
36
+ CancellationToken cancellationToken, (string Name, object? Value)[]? query = null, object? body = null)
37
+ {
38
+ var root = await SendAsync(credential, method, route, cancellationToken, query, body);
39
+ if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("code", out var code)
40
+ || code.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(code.GetString()))
41
+ {
42
+ throw new WorkFlowProtocolException("Expected a workflow result with a string business code.");
43
+ }
44
+
45
+ return Decode<Envelope>(root);
46
+ }
47
+
48
+ internal async Task<WorkFlowResult<T>> GetResultAsync<T>(WorkFlowCredential credential, HttpMethod method, string route,
49
+ CancellationToken cancellationToken, (string Name, object? Value)[]? query = null, object? body = null)
50
+ {
51
+ var result = await GetEnvelopeAsync(credential, method, route, cancellationToken, query, body);
52
+ result.RequireSuccess();
53
+ return result.ToResult<T>();
54
+ }
55
+
56
+ internal async Task<T> GetValueAsync<T>(WorkFlowCredential credential, string route, JsonValueKind expectedKind,
57
+ CancellationToken cancellationToken, (string Name, object? Value)[]? query = null)
58
+ {
59
+ var root = await SendAsync(credential, HttpMethod.Get, route, cancellationToken, query, null);
60
+ // The engine's exception handler can return an envelope even for bare boolean/object endpoints.
61
+ if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("code", out var code)
62
+ && code.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(code.GetString()))
63
+ {
64
+ Decode<Envelope>(root).RequireSuccess();
65
+ throw new WorkFlowProtocolException("Expected a bare workflow value, not a result envelope.");
66
+ }
67
+
68
+ if (root.ValueKind != expectedKind && !(expectedKind == JsonValueKind.True && root.ValueKind == JsonValueKind.False))
69
+ throw new WorkFlowProtocolException("Unexpected workflow response JSON shape.");
70
+
71
+ return Decode<T>(root);
72
+ }
73
+
74
+ private async Task<JsonElement> SendAsync(WorkFlowCredential credential, HttpMethod method, string route,
75
+ CancellationToken cancellationToken, (string Name, object? Value)[]? query, object? body)
76
+ {
77
+ ArgumentNullException.ThrowIfNull(credential);
78
+ var pairs = new List<string>();
79
+ Add(credential.Parameter, credential.Token);
80
+ Add("loginName", credential.LoginName);
81
+ if (query is not null)
82
+ {
83
+ foreach (var (name, value) in query)
84
+ Add(name, value);
85
+ }
86
+
87
+ using var client = factory.CreateClient("InBiz.WorkFlow");
88
+ using var request = new HttpRequestMessage(method, route + "?" + string.Join("&", pairs));
89
+ request.Headers.Add("vVersion", "6");
90
+ request.Headers.Accept.ParseAdd("application/json");
91
+ if (body is not null)
92
+ request.Content = JsonContent.Create(body, body.GetType(), options: Json);
93
+
94
+ try
95
+ {
96
+ using var response = await client.SendAsync(request, cancellationToken);
97
+ if (!response.IsSuccessStatusCode)
98
+ {
99
+ if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
100
+ {
101
+ // The interceptor labels this JSON text/html.
102
+ try
103
+ {
104
+ var error = await ReadJsonAsync(response, cancellationToken);
105
+ if (IsExpired(error))
106
+ throw new WorkFlowSessionException(response.StatusCode);
107
+ }
108
+ catch (JsonException)
109
+ {
110
+ // A proxy can return HTML for 401/403. Keep the actual HTTP status.
111
+ }
112
+ }
113
+
114
+ throw new WorkFlowHttpException(response.StatusCode);
115
+ }
116
+
117
+ var root = await ReadJsonAsync(response, cancellationToken);
118
+ if (IsExpired(root))
119
+ throw new WorkFlowSessionException(response.StatusCode);
120
+ return root;
121
+ }
122
+ catch (JsonException)
123
+ {
124
+ throw new WorkFlowProtocolException("The workflow engine did not return valid JSON.");
125
+ }
126
+ catch (HttpRequestException)
127
+ {
128
+ // The original exception may include a credential-bearing URL.
129
+ throw new WorkFlowException("The workflow HTTP request could not be completed.");
130
+ }
131
+
132
+ void Add(string name, object? value)
133
+ {
134
+ if (value is null)
135
+ return;
136
+ var text = value is bool flag ? (flag ? "true" : "false") : Convert.ToString(value, CultureInfo.InvariantCulture)!;
137
+ pairs.Add(Uri.EscapeDataString(name) + "=" + Uri.EscapeDataString(text));
138
+ }
139
+ }
140
+
141
+ private static bool IsExpired(JsonElement root) =>
142
+ root.ValueKind == JsonValueKind.Object && root.TryGetProperty("errorCode", out var code)
143
+ && code.ValueKind == JsonValueKind.String && code.GetString() == "ErrorCode4";
144
+
145
+ private static async Task<JsonElement> ReadJsonAsync(HttpResponseMessage response, CancellationToken cancellationToken)
146
+ {
147
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
148
+ using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
149
+ return document.RootElement.Clone();
150
+ }
151
+
152
+ private static T Decode<T>(JsonElement value)
153
+ {
154
+ try
155
+ {
156
+ return value.Deserialize<T>(Json)!;
157
+ }
158
+ catch (JsonException)
159
+ {
160
+ throw new WorkFlowProtocolException("The workflow response does not match the expected JSON contract.");
161
+ }
162
+ }
163
+ }