# Apply StoneOS Industry Package

> 为某个业务单元提出行业包方案并预览，然后等待有权限的人员审批。由应用执行变更；该 worker 只负责提议、等待和恢复。

Source: https://docs.sommatic.ai/zh/nodes/stoneos.industry.apply/

- 标识: `stoneos.industry.apply`
- 类别: 人工介入
- 版本: 1.0.0
- 状态: 部分可用. 创建变更提案后结束初始运行；工作流不会等待决定，提案也不会记录创建它的运行。
- 执行方式: async

为某个业务单元提出行业包方案并预览，然后等待有权限的人员审批。由应用执行变更；该 worker 只负责提议、等待和恢复。

## 配置

- `unit` (string, 必填): 业务单元代码（可使用表达式）
- `package_id` (string, 必填)
- `proposal_id` (string, 可选)
- `role` (string, 可选): 默认值: `principal`. 可选值: `principal`, `complement`.
- `size` (string, 可选)
- `jurisdiction` (string, 可选): 辖区代码；默认使用组织的辖区
- `reason` (string, 可选)
- `operation` (string, 可选)
- `approver_role` (string, 可选): 默认值: `administrator`.
- `timeout_ms` (integer, 可选): 默认值: `259200000`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `applied` (默认): 已批准并应用
- `rejected`: 有人驳回了该变更
- `timeout`: 无人在时限内作出决定
- `partial`: 仅部分应用；由流程决定后续处理
- `error`: 携带 error_code

## 输入契约

- `unit` (string, 可选)
- `package_id` (string, 可选)
- `proposal_id` (string, 可选)
- `role` (string, 可选)
- `size` (string, 可选)
- `operation` (string, 可选)
- `approver_role` (string, 可选)
- `timeout_ms` (integer, 可选)

## 输出契约

- `change_id` (string, 可选)
- `state` (string, 可选)
- `applied_apps` (array<string>, 可选)
- `failed_app` (string, 可选)
- `approver` (string, 可选)
- `error_code` (string, 可选)

## 在表达式中

后续节点可通过 `$("Apply StoneOS Industry Package").item.json.<路径>` 读取此节点输出中的内容（请把 `Apply StoneOS Industry Package` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `applied` 返回的路径，依据“端口”一节所示的输出。

- `$("Apply StoneOS Industry Package").item.json.change_id` (string) = `"chg-xxxxxxxxxxxx"`
- `$("Apply StoneOS Industry Package").item.json.state` (string) = `"applied"`
- `$("Apply StoneOS Industry Package").item.json.applied_apps` (array) = `[…] (2)`
- `$("Apply StoneOS Industry Package").item.json.failed_app` (string) **worker 不返回：读取结果为 undefined.**
- `$("Apply StoneOS Industry Package").item.json.approver` (string) = `"admin@example.com"`
- `$("Apply StoneOS Industry Package").item.json.error_code` (string) **worker 不返回：读取结果为 undefined.**


## 工作原理

为业务单元提议一个 StoneOS 行业包，生成其预览并返回挂起信号；之后人员的决定会通过编排器的恢复操作映射到 `applied`、`rejected`、`timeout` 或 `partial`。

1. 解析配置并合并到输入 payload 之上（配置优先）。若结果中有 `resume` 对象，则跳过提议，直接映射决定（见最后一步）。
2. 检查 `unit` 和 `package_id`，以及 StoneOS 行业服务是否已配置。
3. 以服务身份代表 `approver_role`（默认 `administrator`）调用该服务。
4. 创建变更，包含 `package_id`、`business_unit_code`（取自 `unit`）、`role`（默认 `principal`）、`size`、`jurisdiction` 和 `reasons`（`reason`，或包含包名的默认文本），然后请求预览，预览必须返回 `installation_id` 和 `installation_preview_hash`。
5. 返回 `{ __signal: "SUSPEND", __metadata: { type: "stoneos_industry_change", id, installation_id, preview_hash, expires_in_ms, resume_on } }`。信封没有端口，引擎将其路由到本节点未声明的 `out`：分支结束，运行完成。
6. 恢复：持有决定的系统调用编排器的恢复操作，传入 `workflow_instance_id`、`node_id`、可选的 `graph` 和 `input`，以及 `resume` `{ change_id, state, port?, approver, applied_apps?, failed_app?, error_code? }`。worker 以恢复模式再次运行，端口取 `resume.port` 或 `resume.state`；若提供了 `graph` 和 `node_id`，会从该端口相连的节点开始一次新运行，以 `data` 作为 payload。

## 在工作流中

### 节点

```json
{
  "node_id": "node-apply-industry",
  "label": "Apply industry package",
  "operator_slug": "stoneos.industry.apply",
  "operator_version": "1.0.0",
  "config": {
    "unit": "{{ $json.business_unit_code }}",
    "package_id": "<package_id>",
    "role": "principal",
    "reason": "New business unit onboarding",
    "approver_role": "administrator",
    "timeout_ms": 259200000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "change_id": "chg-xxxxxxxxxxxx",
    "state": "applied",
    "applied_apps": [
      "stoneos-notes",
      "stoneos-todo"
    ],
    "approver": "admin@example.com"
  },
  "port": "applied",
  "meta": {
    "approver": "admin@example.com"
  }
}
```

## 输出端口 (代码中的行为)

### `applied`

恢复时状态为 `applied` 且带有 `approver`。唯一 `ok: true` 的端口。

```json
{
  "change_id": "chg-xxxxxxxxxxxx",
  "state": "applied",
  "applied_apps": [
    "stoneos-notes",
    "stoneos-todo"
  ],
  "approver": "admin@example.com"
}
```

### `rejected`

恢复时状态为 `rejected` 且带有 `approver`。

```json
{
  "change_id": "chg-xxxxxxxxxxxx",
  "state": "rejected",
  "applied_apps": [],
  "approver": "admin@example.com"
}
```

### `timeout`

恢复时状态为 `timeout`；不需要 `approver`。

```json
{
  "change_id": "chg-xxxxxxxxxxxx",
  "state": "timeout",
  "applied_apps": []
}
```

### `partial`

恢复时状态为 `partial` 且带有 `approver`：部分应用已应用，`failed_app` 指出失败的应用。

```json
{
  "change_id": "chg-xxxxxxxxxxxx",
  "state": "partial",
  "applied_apps": [
    "stoneos-notes"
  ],
  "failed_app": "stoneos-todo",
  "approver": "admin@example.com"
}
```

### `error`

提议步骤失败，或恢复请求无效或报告错误。`data` 只携带 `error_code`；消息位于信封的 `error` 字段，不会传到下一个节点。

```json
{
  "error_code": "missing_unit"
}
```

## 代码中的行为

- `resume`: 未声明。当配置或输入 payload 中带有 `resume` 时，节点会将其映射到端口，而不是提议变更。
- `proposal_id`: 已声明但被忽略，`operation` 同样如此。
- `timeout_ms`: 默认 72 小时。仅作为 `__metadata.expires_in_ms` 返回；编排器不会强制执行。`timeout` 只会来自状态为 `timeout` 的恢复请求。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'unit'` | `error` | 缺少业务单元代码。`error_code`：`missing_unit`。 |
| `Missing 'package_id'` | `error` | 缺少行业包。`error_code`：`missing_package_id`。 |
| `services.stoneosIndustry.uri is not resolved` | `error` | 编排器未配置 StoneOS 行业服务。`error_code`：`service_not_configured`。 |
| `The change was not created` | `error` | 服务响应中没有变更 id。`error_code`：`change_not_created`。 |
| `The change preview was not created` | `error` | 预览中缺少 `installation_id` 或 `installation_preview_hash`。`error_code`：`preview_failed`。 |
| `<HTTP error message>` | `error` | 服务拒绝了调用；若服务返回了自己的 `error_code` 则使用该值。`error_code`：`request_failed`。 |
| `Unknown resume state '<port>'` | `error` | 恢复端口不是 `applied`、`rejected`、`timeout`、`partial` 或 `error`。`error_code`：`unknown_resume_state`。 |
| `The '<port>' port needs the person who approved` | `error` | `applied`、`rejected` 和 `partial` 需要 `resume.approver`。`error_code`：`approval_missing`。 |
| `<resume error>` | `error` | 恢复请求报告 `port` 或 `state` 为 `error`；`data` 保留恢复字段并附加 `error_code`（默认 `apply_failed`）。 |

## 说明与限制

- 变更请求中的 `workflow_instance_id` 和 `node_id` 为空（worker 从运行时未设置的字段读取它们），因此服务无法得知是哪次运行提议了变更；调用恢复操作的一方必须提供 `workflow_instance_id`、`node_id` 和 `graph`。
- 续跑是一次新的运行：本节点之前各节点的输出不可用（`$("Node")` 为空），`$input` 为恢复请求中的 `input`。
- `rejected`、`timeout` 和 `partial` 的 `ok` 为 false，但仍沿各自端口流转。worker 只负责提议和等待；行业包由 StoneOS 应用在批准后应用。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "stoneos.industry.apply",
  "name": "Apply StoneOS Industry Package",
  "category": "hitl",
  "version": "1.0.0",
  "description": "Proposes an industry package for a business unit, previews it and waits for a person with permission to approve. The app applies the change; the worker only proposes, waits and resumes.",
  "capabilities": [
    "industry",
    "configuration",
    "human"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "unit",
      "package_id"
    ],
    "properties": {
      "unit": {
        "type": "string",
        "title": "Business unit",
        "description": "Business unit code (expression allowed)"
      },
      "package_id": {
        "type": "string",
        "title": "Package"
      },
      "proposal_id": {
        "type": "string",
        "title": "Proposal"
      },
      "role": {
        "type": "string",
        "enum": [
          "principal",
          "complement"
        ],
        "default": "principal"
      },
      "size": {
        "type": "string",
        "title": "Size"
      },
      "jurisdiction": {
        "type": "string",
        "title": "Jurisdiction",
        "description": "Jurisdiction code; defaults to the organization one"
      },
      "reason": {
        "type": "string",
        "title": "Reason"
      },
      "operation": {
        "type": "string",
        "title": "Operation"
      },
      "approver_role": {
        "type": "string",
        "default": "administrator",
        "title": "Approver role"
      },
      "timeout_ms": {
        "type": "integer",
        "default": 259200000
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "unit": {
        "type": "string"
      },
      "package_id": {
        "type": "string"
      },
      "proposal_id": {
        "type": "string"
      },
      "role": {
        "type": "string"
      },
      "size": {
        "type": "string"
      },
      "operation": {
        "type": "string"
      },
      "approver_role": {
        "type": "string"
      },
      "timeout_ms": {
        "type": "integer"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "change_id": {
        "type": "string"
      },
      "state": {
        "type": "string"
      },
      "applied_apps": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "failed_app": {
        "type": "string"
      },
      "approver": {
        "type": "string"
      },
      "error_code": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "applied",
      "label": "Applied",
      "is_default": true,
      "description": "Approved and applied"
    },
    {
      "port_id": "rejected",
      "label": "Rejected",
      "description": "A person rejected the change"
    },
    {
      "port_id": "timeout",
      "label": "Timeout",
      "description": "Nobody decided in time"
    },
    {
      "port_id": "partial",
      "label": "Partial",
      "description": "Applied halfway; the flow decides"
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Carries error_code"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "industry",
    "configuration",
    "human"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "unit",
    "package_id"
  ],
  "properties": {
    "unit": {
      "type": "string",
      "title": "Business unit",
      "description": "Business unit code (expression allowed)"
    },
    "package_id": {
      "type": "string",
      "title": "Package"
    },
    "proposal_id": {
      "type": "string",
      "title": "Proposal"
    },
    "role": {
      "type": "string",
      "enum": [
        "principal",
        "complement"
      ],
      "default": "principal"
    },
    "size": {
      "type": "string",
      "title": "Size"
    },
    "jurisdiction": {
      "type": "string",
      "title": "Jurisdiction",
      "description": "Jurisdiction code; defaults to the organization one"
    },
    "reason": {
      "type": "string",
      "title": "Reason"
    },
    "operation": {
      "type": "string",
      "title": "Operation"
    },
    "approver_role": {
      "type": "string",
      "default": "administrator",
      "title": "Approver role"
    },
    "timeout_ms": {
      "type": "integer",
      "default": 259200000
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "unit": {
      "type": "string"
    },
    "package_id": {
      "type": "string"
    },
    "proposal_id": {
      "type": "string"
    },
    "role": {
      "type": "string"
    },
    "size": {
      "type": "string"
    },
    "operation": {
      "type": "string"
    },
    "approver_role": {
      "type": "string"
    },
    "timeout_ms": {
      "type": "integer"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "change_id": {
      "type": "string"
    },
    "state": {
      "type": "string"
    },
    "applied_apps": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "failed_app": {
      "type": "string"
    },
    "approver": {
      "type": "string"
    },
    "error_code": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "applied",
    "label": "Applied",
    "is_default": true,
    "description": "Approved and applied"
  },
  {
    "port_id": "rejected",
    "label": "Rejected",
    "description": "A person rejected the change"
  },
  {
    "port_id": "timeout",
    "label": "Timeout",
    "description": "Nobody decided in time"
  },
  {
    "port_id": "partial",
    "label": "Partial",
    "description": "Applied halfway; the flow decides"
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Carries error_code"
  }
]
```
