use crate::ccm::docx::models::block_update::BlockUpdateOperation;
use crate::ccm::docx::models::common_types::DocxBlock;
use crate::common::api_endpoints::DocxApiV1;
use openlark_core::{
SDKResult,
api::{ApiRequest, ApiResponseTrait, ResponseFormat},
config::Config,
http::Transport,
req_option::RequestOption,
validate_required,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateDocumentBlockParams {
#[serde(skip_serializing)]
pub document_id: String,
#[serde(skip_serializing)]
pub block_id: String,
#[serde(flatten)]
pub update: BlockUpdateOperation,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateDocumentBlockResponse {
pub block: DocxBlock,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub document_revision_id: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_token: Option<String>,
}
impl ApiResponseTrait for UpdateDocumentBlockResponse {
fn data_format() -> ResponseFormat {
ResponseFormat::Data
}
}
pub struct UpdateDocumentBlockRequest {
config: Config,
}
impl UpdateDocumentBlockRequest {
pub fn new(config: Config) -> Self {
Self { config }
}
pub async fn execute(
self,
params: UpdateDocumentBlockParams,
) -> SDKResult<UpdateDocumentBlockResponse> {
self.execute_with_options(params, RequestOption::default())
.await
}
pub async fn execute_with_options(
self,
params: UpdateDocumentBlockParams,
option: RequestOption,
) -> SDKResult<UpdateDocumentBlockResponse> {
validate_required!(params.document_id, "文档ID不能为空");
validate_required!(params.block_id, "块ID不能为空");
let api_endpoint =
DocxApiV1::DocumentBlockPatch(params.document_id.clone(), params.block_id.clone());
let mut api_request: ApiRequest<UpdateDocumentBlockResponse> = api_endpoint.to_request();
api_request = api_request.json_body(¶ms);
Transport::request_typed(api_request, &self.config, Some(option), "更新块的内容").await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ccm::docx::models::block_update::{
BlockUpdateOperation, InsertTableRowRequest, MergeTableCellsRequest,
};
use serde_json::json;
use wiremock::MockServer;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, ResponseTemplate};
#[tokio::test]
async fn test_update_document_block_returns_data_on_success() {
let server = MockServer::start().await;
Mock::given(method("PATCH"))
.and(path("/open-apis/docx/v1/documents/doc1/blocks/blk1"))
.and(header("Authorization", "Bearer test-tenant-token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"code": 0, "msg": "success",
"data": { "block": { "block_id": "blk1", "block_type": 1 } }
})))
.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();
let resp = UpdateDocumentBlockRequest::new(config)
.execute_with_options(
UpdateDocumentBlockParams {
document_id: "doc1".into(),
block_id: "blk1".into(),
update: BlockUpdateOperation::Raw(json!({
"update_text_elements": { "elements": [] }
})),
},
RequestOption::builder()
.tenant_access_token("test-tenant-token")
.build(),
)
.await
.expect("更新块内容应成功");
assert_eq!(resp.block.block_id, "blk1");
let received = server.received_requests().await.unwrap_or_default();
assert_eq!(received.len(), 1);
assert_eq!(
received[0].url.path(),
"/open-apis/docx/v1/documents/doc1/blocks/blk1"
);
let body: serde_json::Value =
serde_json::from_slice(&received[0].body).expect("请求体应为合法 JSON");
assert_eq!(body["update_text_elements"]["elements"], json!([]));
}
#[test]
fn test_block_update_operation_serializes_to_single_key() {
let op = BlockUpdateOperation::InsertTableRow(InsertTableRowRequest { row_index: 2 });
let json = serde_json::to_value(&op).unwrap();
assert_eq!(json["insert_table_row"]["row_index"], 2);
assert_eq!(json.as_object().unwrap().len(), 1);
}
#[test]
fn test_block_update_operation_merge_cells_all_fields() {
let op = BlockUpdateOperation::MergeTableCells(MergeTableCellsRequest {
row_start_index: 0,
row_end_index: 1,
column_start_index: 0,
column_end_index: 2,
});
let json = serde_json::to_value(&op).unwrap();
let inner = &json["merge_table_cells"];
assert_eq!(inner["row_start_index"], 0);
assert_eq!(inner["column_end_index"], 2);
}
#[test]
fn test_update_document_block_params_flatten_serialization() {
let params = UpdateDocumentBlockParams {
document_id: "docx123".to_string(),
block_id: "block456".to_string(),
update: BlockUpdateOperation::InsertTableRow(InsertTableRowRequest { row_index: 1 }),
};
let json = serde_json::to_value(¶ms).unwrap();
assert_eq!(json["insert_table_row"]["row_index"], 1);
assert!(json.get("document_id").is_none());
}
}