openlark-docs 0.18.0

飞书开放平台云文档服务模块 - 文档、表格、知识库API (202 APIs, 100% 覆盖,不含旧版本)
Documentation
//! Bitable 更新表单问题
//!
//! docPath: <https://open.feishu.cn/document/server-docs/docs/bitable-v1/app-table-form-field/patch>

use openlark_core::{
    api::{ApiRequest, ApiResponseTrait, ResponseFormat},
    config::Config,
    error::SDKResult,
    http::Transport,
    req_option::RequestOption,
    validate_required,
};
use serde::{Deserialize, Serialize};

use super::models::PatchFormFieldRequest;

/// 更新表单问题请求
///
/// 用于更新表单中的单个问题配置。
#[derive(Debug, Clone)]
pub struct PatchFormFieldQuestionRequest {
    config: Config,
    app_token: String,
    table_id: String,
    form_id: String,
    field_id: String,
    body: PatchFormFieldRequest,
}

impl PatchFormFieldQuestionRequest {
    /// 创建新的表单问题更新请求。
    pub fn new(config: Config) -> Self {
        Self {
            config,
            app_token: String::new(),
            table_id: String::new(),
            form_id: String::new(),
            field_id: String::new(),
            body: PatchFormFieldRequest::new(),
        }
    }

    /// 设置多维表格 token。
    pub fn app_token(mut self, app_token: String) -> Self {
        self.app_token = app_token;
        self
    }

    /// 设置数据表 ID。
    pub fn table_id(mut self, table_id: String) -> Self {
        self.table_id = table_id;
        self
    }

    /// 设置表单 ID。
    pub fn form_id(mut self, form_id: String) -> Self {
        self.form_id = form_id;
        self
    }

    /// 设置字段 ID。
    pub fn field_id(mut self, field_id: String) -> Self {
        self.field_id = field_id;
        self
    }

    /// 设置前置字段 ID。
    pub fn pre_field_id(mut self, pre_field_id: String) -> Self {
        self.body.pre_field_id = Some(pre_field_id);
        self
    }

    /// 设置标题。
    pub fn title(mut self, title: String) -> Self {
        self.body.title = Some(title);
        self
    }

    /// 设置描述。
    pub fn description(mut self, description: String) -> Self {
        self.body.description = Some(description);
        self
    }

    /// 设置是否必答。
    pub fn required(mut self, required: bool) -> Self {
        self.body.required = Some(required);
        self
    }

    /// 设置是否可见。
    pub fn visible(mut self, visible: bool) -> Self {
        self.body.visible = Some(visible);
        self
    }

    /// 执行请求。
    pub async fn execute(self) -> SDKResult<PatchFormFieldQuestionResponse> {
        self.execute_with_options(RequestOption::default()).await
    }

    /// 使用指定请求选项执行请求。
    pub async fn execute_with_options(
        self,
        option: RequestOption,
    ) -> SDKResult<PatchFormFieldQuestionResponse> {
        validate_required!(self.app_token.trim(), "app_token");
        validate_required!(self.table_id.trim(), "table_id");
        validate_required!(self.form_id.trim(), "form_id");
        validate_required!(self.field_id.trim(), "field_id");
        self.body.validate()?;

        use crate::common::api_endpoints::BitableApiV1;
        let api_endpoint = BitableApiV1::FormFieldPatch(
            self.app_token,
            self.table_id,
            self.form_id,
            self.field_id,
        );

        let api_request: ApiRequest<PatchFormFieldQuestionResponse> = api_endpoint
            .to_request()
            .body(serde_json::to_vec(&self.body)?);

        let response = Transport::request(api_request, &self.config, Some(option)).await?;
        response
            .data
            .ok_or_else(|| openlark_core::error::validation_error("response", "响应数据为空"))
    }
}

/// 更新表单问题 Builder
pub struct PatchFormFieldQuestionRequestBuilder {
    request: PatchFormFieldQuestionRequest,
}

impl PatchFormFieldQuestionRequestBuilder {
    /// 创建新的表单问题更新 builder。
    pub fn new(config: Config) -> Self {
        Self {
            request: PatchFormFieldQuestionRequest::new(config),
        }
    }

    /// 设置多维表格 token。
    pub fn app_token(mut self, app_token: String) -> Self {
        self.request = self.request.app_token(app_token);
        self
    }

    /// 设置数据表 ID。
    pub fn table_id(mut self, table_id: String) -> Self {
        self.request = self.request.table_id(table_id);
        self
    }

    /// 设置表单 ID。
    pub fn form_id(mut self, form_id: String) -> Self {
        self.request = self.request.form_id(form_id);
        self
    }

    /// 设置字段 ID。
    pub fn field_id(mut self, field_id: String) -> Self {
        self.request = self.request.field_id(field_id);
        self
    }

    /// 设置前置字段 ID。
    pub fn pre_field_id(mut self, pre_field_id: String) -> Self {
        self.request = self.request.pre_field_id(pre_field_id);
        self
    }

    /// 设置标题。
    pub fn title(mut self, title: String) -> Self {
        self.request = self.request.title(title);
        self
    }

    /// 设置描述。
    pub fn description(mut self, description: String) -> Self {
        self.request = self.request.description(description);
        self
    }

    /// 设置是否必答。
    pub fn required(mut self, required: bool) -> Self {
        self.request = self.request.required(required);
        self
    }

    /// 设置是否可见。
    pub fn visible(mut self, visible: bool) -> Self {
        self.request = self.request.visible(visible);
        self
    }

    /// 构建请求对象。
    pub fn build(self) -> PatchFormFieldQuestionRequest {
        self.request
    }
}

/// 更新后的表单问题(响应 field)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PatchedFormFieldQuestion {
    /// 前置字段 ID。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_field_id: Option<String>,
    /// 标题。
    pub title: String,
    /// 描述。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// 是否必答。
    pub required: bool,
    /// 是否可见。
    pub visible: bool,
}

/// 更新表单问题响应(data)。
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PatchFormFieldQuestionResponse {
    /// 更新后的问题配置。
    pub field: PatchedFormFieldQuestion,
    /// 字段附加属性(官方 optional object,结构多变,用 Value 透传)。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fields: Option<serde_json::Value>,
}

impl ApiResponseTrait for PatchFormFieldQuestionResponse {
    fn data_format() -> ResponseFormat {
        ResponseFormat::Data
    }
}

/// 旧名兼容别名(将在 v1.0 移除)
#[deprecated(
    note = "renamed to PatchFormFieldQuestionRequestBuilder, will be removed in v1.0 (#271)"
)]
pub type PatchFormFieldQuestionBuilder = PatchFormFieldQuestionRequestBuilder;

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::MockServer;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, ResponseTemplate};

    /// 端到端:PATCH .../forms/{form_id}/fields/{field_id} → PatchFormFieldResponse。
    #[tokio::test]
    async fn test_patch_form_field_returns_data_on_success() {
        let server = MockServer::start().await;
        Mock::given(method("PATCH"))
            .and(path("/open-apis/bitable/v1/apps/app001/tables/tbl001/forms/form001/fields/fld001"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "code": 0, "msg": "success", "data": { "field": { "title": "标题", "required": false, "visible": true } }
            })))
            .mount(&server).await;
        let config = Config::builder()
            .app_id("ci_app_id")
            .app_secret("ci_app_secret")
            .base_url(server.uri())
            .enable_token_cache(false)
            .build();
        PatchFormFieldQuestionRequest::new(config)
            .app_token("app001".into())
            .table_id("tbl001".into())
            .form_id("form001".into())
            .field_id("fld001".into())
            .title("标题".into())
            .execute()
            .await
            .expect("更新表单字段应成功");
        let received = server.received_requests().await.unwrap_or_default();
        assert_eq!(received.len(), 1);
        assert_eq!(
            received[0].url.path(),
            "/open-apis/bitable/v1/apps/app001/tables/tbl001/forms/form001/fields/fld001"
        );
    }
}