設定政策

本頁面會簡要介紹資料夾,並說明如何使用資料夾管理文件。

政策引擎和規則

在 Document Warehouse 中,使用者可透過 Policy Engine 定義及執行文件上的常見作業 (例如驗證或更新),同時建立或更新文件。

規則和規則集

高階的 Rule 是指使用者定義的設定,可指定下列項目:

  • 觸發規則檢查的條件
  • 評估的條件,以及
  • 符合條件時執行的動作。

除了這些規格,規則還包含說明、來源、目標和觸發條件的相關資訊。

規則的邏輯集合稱為「RuleSet」RuleSet。舉例來說,對相同結構定義執行的規則可以分組為單一規則集。顧客可以定義多個規則集。

規則有助於在建立或更新文件時,自動觸發預先定義的動作。

規則包含三項主要內容:

  • TriggerType:應啟動規則檢查的事件。支援的觸發條件類型為「建立」和「更新」。
  • 規則條件:系統偵測到特定觸發條件類型後,會評估的條件。條件可以使用一般運算語言 (CEL) 表示。每個條件的評估結果都應為布林值。
  • 動作:滿足規則時執行的一組步驟。如果規則條件的評估結果為 true,系統就會執行規則中設定的相應動作。以下是 Document Warehouse 中實作特定動作的基本詳細資料:
    • 資料驗證動作:在建立或更新文件時,驗證文件中的特定欄位。
    • 資料更新動作:這項動作可在建立或更新文件時,更新文件中的特定欄位。當規則條件符合時,系統就會執行這類更新。
    • 刪除文件動作:如果特定欄位符合使用規則條件定義的刪除條件,即可在更新文件時刪除文件。
    • 資料夾納入動作:自動將特定資料夾中的新文件 (或更新文件) 新增至資料夾。這類資料夾可直接使用名稱指定。
    • 從資料夾中移除動作:當滿足規則層級條件時,系統會自動從指定資料夾中移除新文件。
    • 存取權控管動作:允許在建立文件期間更新存取權控制清單 (群組和使用者繫結) 的動作。當規則條件符合時,系統就會執行這類更新。
    • 發布動作:當滿足規則層級條件時,將特定訊息發布至使用者 Pub/Sub 通道的動作。

管理規則集

Document Warehouse 提供 API 來管理規則集 (建立、取得、更新、刪除、列出)。本節提供設定不同類型規則的範例。

建立規則集

如要建立規則集,請按照下列步驟操作:

REST

要求:

# Create a RuleSet for data validation.
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "trigger_type": "ON_CREATE",
      "condition": "documentType == \'W9\' && STATE ==\'CA\'",
      "actions": {
        "data_validation": {
          "conditions": {
            "NAME": "NAME != \'\'",
            "FILING_COST": "FILING_COST > 10.0"
          }
        }
      },
      "enabled": true
    }
  ],
  "description": "W9: Basic validation check rules."
}'

回應

{
  "description": "W9: Basic validation check rules.",
  "name": "RULE_SET_NAME",
  "rules": [
    {
      "actions": [
        {
          "actionId": "de0e6b84-106b-44ba-b1c4-0b3ad6ddc719",
          "dataValidation": {
            "conditions": {
              "FILING_COST": "FILING_COST > 10.0",
              "NAME": "NAME != ''"
            }
          }
        }
      ],
      "condition": "documentType == 'W9' && STATE =='CA'",
      "enabled": true,
      "triggerType": "ON_CREATE"
    }
  ]
}

Python

詳情請參閱 Document AI Warehouse Python API 參考文件

如要向 Document AI Warehouse 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = "YOUR_PROJECT_NUMBER"
# location = "us" # Format is 'us' or 'eu'


def create_rule_set(project_number: str, location: str) -> None:
    # Create a client
    client = contentwarehouse.RuleSetServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}
    parent = client.common_location_path(project=project_number, location=location)

    actions = contentwarehouse.Action(
        delete_document_action=contentwarehouse.DeleteDocumentAction(
            enable_hard_delete=True
        )
    )

    rules = contentwarehouse.Rule(
        trigger_type="ON_CREATE",
        condition="documentType == 'W9' && STATE =='CA'",
        actions=[actions],
    )

    rule_set = contentwarehouse.RuleSet(
        description="W9: Basic validation check rules.",
        source="My Organization",
        rules=[rules],
    )

    # Initialize request argument(s)
    request = contentwarehouse.CreateRuleSetRequest(parent=parent, rule_set=rule_set)

    # Make the request
    response = client.create_rule_set(request=request)

    # Handle the response
    print(f"Rule Set Created: {response}")

    # Initialize request argument(s)
    request = contentwarehouse.ListRuleSetsRequest(
        parent=parent,
    )

    # Make the request
    page_result = client.list_rule_sets(request=request)

    # Handle the response
    for response in page_result:
        print(f"Rule Sets: {response}")

Java

詳情請參閱 Document AI Warehouse Java API 參考文件

如要向 Document AI Warehouse 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import com.google.cloud.contentwarehouse.v1.Action;
import com.google.cloud.contentwarehouse.v1.ActionOrBuilder;
import com.google.cloud.contentwarehouse.v1.CreateRuleSetRequest;
import com.google.cloud.contentwarehouse.v1.CreateRuleSetRequestOrBuilder;
import com.google.cloud.contentwarehouse.v1.DeleteDocumentAction;
import com.google.cloud.contentwarehouse.v1.DeleteDocumentActionOrBuilder;
import com.google.cloud.contentwarehouse.v1.ListRuleSetsRequest;
import com.google.cloud.contentwarehouse.v1.ListRuleSetsRequestOrBuilder;
import com.google.cloud.contentwarehouse.v1.LocationName;
import com.google.cloud.contentwarehouse.v1.Rule;
import com.google.cloud.contentwarehouse.v1.Rule.TriggerType;
import com.google.cloud.contentwarehouse.v1.RuleOrBuilder;
import com.google.cloud.contentwarehouse.v1.RuleSet;
import com.google.cloud.contentwarehouse.v1.RuleSetOrBuilder;
import com.google.cloud.contentwarehouse.v1.RuleSetServiceClient;
import com.google.cloud.contentwarehouse.v1.RuleSetServiceClient.ListRuleSetsPagedResponse;
import com.google.cloud.contentwarehouse.v1.RuleSetServiceSettings;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;


public class CreateRuleSet {

  public static void createRuleSet() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException { 
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    createRuleSet(projectId, location);
  }

  public static void createRuleSet(String projectId, String location)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    RuleSetServiceSettings ruleSetServiceSettings =
        RuleSetServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Create a Rule Set Service Client 
    try (RuleSetServiceClient ruleSetServiceClient = 
        RuleSetServiceClient.create(ruleSetServiceSettings)) {
      /*  The full resource name of the location, e.g.:
      projects/{project_number}/locations/{location} */
      String parent = LocationName.format(projectNumber, location); 

      // Create a Delete Document Action to be added to the Rule Set 
      DeleteDocumentActionOrBuilder deleteDocumentAction = 
          DeleteDocumentAction.newBuilder().setEnableHardDelete(true).build();

      // Add Delete Document Action to Action Object 
      ActionOrBuilder action = Action.newBuilder()
            .setDeleteDocumentAction((DeleteDocumentAction) deleteDocumentAction).build();

      // Create rule to add to rule set 
      RuleOrBuilder rule = Rule.newBuilder()
          .setTriggerType(TriggerType.ON_CREATE)
          .setCondition("documentType == 'W9' && STATE =='CA' ")
          .addActions(0, (Action) action).build();

      // Create rule set and add rule to it
      RuleSetOrBuilder ruleSetOrBuilder = RuleSet.newBuilder()
          .setDescription("W9: Basic validation check rules.")
          .setSource("My Organization")
          .addRules((Rule) rule).build();

      // Create and prepare rule set request to client
      CreateRuleSetRequestOrBuilder createRuleSetRequest = 
          CreateRuleSetRequest.newBuilder()
              .setParent(parent)
              .setRuleSet((RuleSet) ruleSetOrBuilder).build();

      RuleSet response = ruleSetServiceClient.createRuleSet(
          (CreateRuleSetRequest) createRuleSetRequest);

      System.out.println("Rule set created: " + response.toString());

      ListRuleSetsRequestOrBuilder listRuleSetsRequest = 
          ListRuleSetsRequest.newBuilder()
              .setParent(parent).build();

      ListRuleSetsPagedResponse listRuleSetsPagedResponse = 
          ruleSetServiceClient.listRuleSets((ListRuleSetsRequest) listRuleSetsRequest);

      listRuleSetsPagedResponse.iterateAll().forEach(
          (ruleSet -> System.out.print(ruleSet))
      );
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

列出規則集

如要列出專案下的規則集,請按照下列步驟操作:

REST

要求:

# List all rule-sets for a project.
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets

回應

{
  "ruleSets": [
    {
      "description": "W9: Basic validation check rules.",
      "rules": [
        {
          "triggerType": "ON_CREATE",
          "condition": "documentType == 'W9' && STATE =='CA'",
          "actions": [
            {
              "actionId": "fcf79ae8-9a1f-4462-9262-eb2e7161350c",
              "dataValidation": {
                "conditions": {
                  "NAME": "NAME != ''",
                  "FILING_COST": "FILING_COST > 10.0"
                }
              }
            }
          ],
          "enabled": true
        }
      ],
      "name": "RULE_SET_NAME"
    }
  ]
}

取得規則集

如要使用規則集名稱取得規則集,請按照下列步驟操作:

REST

要求:

# Get a rule-set using rule-set ID.
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets/RULE_SET

回應

{
  "description": "W9: Basic validation check rules.",
  "rules": [
    {
      "triggerType": "ON_CREATE",
      "condition": "documentType == 'W9' && STATE =='CA'",
      "actions": [
        {
          "actionId": "7559346b-ec9f-4143-ab1c-1912f5588807",
          "dataValidation": {
            "conditions": {
              "NAME": "NAME != ''",
              "FILING_COST": "FILING_COST > 10.0"
            }
          }
        }
      ],
      "enabled": true
    }
  ],
  "name": "RULE_SET_NAME"
}

刪除規則集

如要使用規則集名稱刪除規則集,請按照下列步驟操作:

REST

要求:

# Get a rule-set using rule-set ID.
curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets/RULE_SET

規則動作

本節將介紹規則運算式,並提供各項規則動作的範例。

範例條件

條件是指使用一般運算語言指定的運算式。

範例:

  • 字串欄位運算式
    • STATE == \'CA\'。檢查 STATE 欄位的值是否等於 CA
    • NAME != \'\'。確認 NAME 欄位的值並未留空。
  • 數值欄位運算式
    • FILING_COST > 10.0。檢查 FILING_COST 欄位的值 (定義為浮點數) 是否大於 10.0

如何檢查文件是否屬於特定結構定義

如要參照特定結構定義類型,請使用特殊欄位名稱 documentType (這是保留字)。系統會根據 DocumentSchema 中的 DisplayName 欄位進行評估。

範例:

  • documentType == \'W9\'

上述條件會檢查文件結構定義 (使用關鍵字 documentType) 是否有 W9 的顯示名稱。

如何參照舊/現有文件屬性值和新文件屬性值

如要支援包含現有和新指定屬性的條件,請使用下列兩個前置字元和 DOT 運算子,存取特定版本的屬性:

  • OLD_ 參照現有文件屬性。
  • NEW_,在要求中參照新的文件屬性。

範例:

  • OLD_.state == \'TX\' && NEW_.state == \'CA\' 檢查狀態屬性的現有值是否為 TX,以及提供的新值是否為 CA

處理日期欄位

如果DriverLicense文件EXPIRATION_DATE早於特定日期

  • 更新 (或新增,如果沒有的話) EXPIRATION_STATUS (列舉欄位),值等於 EXPIRING_BEFORE_CLOSING_DATE

如要新增日期值,請使用時間戳記函式,如下列範例所示。

REST

要求:

# Check if document expires before a date and update the status field
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules":[
    {
      "trigger_type": "ON_CREATE",
      "description": "Expiration date check rule",
      "condition": "documentType==\'DriverLicense\' && EXPIRATION_DATE  < timestamp(\'2021-08-01T00:00:00Z\')",
      "actions": {
        "data_update": {
          "entries": {
            "EXPIRATION_STATUS": "EXPIRING_BEFORE_CLOSING_DATE"
          }
        }
      }
    }
  ]
}'

資料驗證規則

驗證 STATE (文字欄位) 加州 W9 文件:

  • 確認 NAME (文字欄位) 不為空白。
  • 檢查 FILING_COST (浮點欄位) 是否大於 10.0

REST

要求:

# Rules for data validation.
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "trigger_type": "ON_CREATE",
      "condition": "documentType == \'W9\' && STATE ==\'CA\'",
      "actions": {
        "data_validation": {
          "conditions": {
            "NAME": "NAME != \'\'",
            "FILING_COST": "FILING_COST > 10.0"
          }
        }
      },
      "enabled": true
    }
  ],
  "description": "W9: Basic validation check rules."
}'

資料更新規則

如果是 W9 文件,且 BUSINESS_NAME 欄位為 Google:

  • 更新 (或新增,如果沒有) 等於 1600 Amphitheatre PkwyAddress 欄位。
  • 更新 (或新增,如果沒有) 等於 77666666EIN 欄位。

REST

要求:

# Rule for data update.
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules":[
    {
      "description": "W9: Rule to update address data and EIN.",
      "trigger_type": "ON_CREATE",
      "condition": "documentType==\'W9\' && BUSINESS_NAME == \'Google\'",
      "actions": {
        "data_update": {
          "entries": {
            "Address": "1600 Amphitheatre Pkwy",
            "EIN": "776666666"
          }
        }
      }
    }
  ]
}'

文件刪除規則

更新 W9 文件時,如果 BUSINESS_NAME 欄位變更為 Google,請刪除該文件。

REST

要求:

# Rule for deleting the document
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "description": "W9: Rule to delete the document during update.",
      "trigger_type": "ON_UPDATE",
      "condition": "documentType == \'W9\' && BUSINESS_NAME == \'Google\'",
      "actions": {
        "delete_document_action": {
          "enable_hard_delete": true
        }
      }
    }
  ]
}'

存取權控管規則

更新 W9 文件時,如果 BUSINESS_NAME 欄位為 Google,請更新控管文件存取權的政策繫結

新增繫結

當文件符合規則條件時:

  • user:a@example.comgroup:xxx@example.com 新增「編輯者」角色
  • user:b@example.comgroup:yyy@example.com 新增「檢視者」角色

REST

要求:

# Rule for adding new policy binding while creating the document.
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "description": "W9: Rule to add new policy binding."
      "trigger_type": "ON_CREATE",
      "condition": "documentType == \'aca13aa9-6d0d-4b6b-a1eb-315dcb876bd1\' && BUSINESS_NAME == \'Google\'",
      "actions": {
        "access_control": {
          "operation_type": "ADD_POLICY_BINDING",
          "policy": {
            "bindings": [
              {
                "role": "roles/contentwarehouse.documentEditor",
                "members": ["user:a@example.com", "group:xxx@example.com"]
              },
              {
                "role": "roles/contentwarehouse.documentViewer",
                "members": ["user:b@example.com", "group:yyy@example.com"]
              }
            ]
          }
        }
      }
    }
  ]
}'

取代現有繫結

當文件符合規則條件時,請取代現有繫結,只為 user:a@example.comgroup:xxx@example.com 納入編輯者角色。

REST

要求:

# Rule for replacing existing policy bindings with newly given bindings.
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "description": "W9: Rule to replace policy binding."
      "trigger_type": "ON_CREATE",
      "condition": "documentType == \'a9e37d07-9cfa-4b4d-b372-53162e3b8bd9\' && BUSINESS_NAME == \'Google\'",
      "actions": {
        "access_control": {
          "operation_type": "REPLACE_POLICY_BINDING",
          "policy": {
            "bindings": [
              {
                "role": "roles/contentwarehouse.documentEditor",
                "members": ["user:a@example.com", "group:xxx@example.com"]
              }
            ]
          }
        }
      }
    }
  ]
}'

新增資料夾規則

建立或更新資料夾時,可以將其新增至預先定義的靜態資料夾,或符合特定搜尋條件的資料夾。

設定靜態資料夾

建立新的 DriverLicense 後,請將其新增至已建立的資料夾。

REST

要求:

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "trigger_type": "ON_CREATE",
      "condition": "documentType == \'DriverLicense\'",
      "actions": {
        "add_to_folder": {
          "folders": ["projects/821411934445/locations/us/documents/445en119hqp70"]
        }
      }
    }
  ]
}'

發布至 Pub/Sub

建立或更新文件,或是建立或刪除連結時,您可以將通知訊息推送至 Pub/Sub 管道。

使用步驟

  • 在客戶專案中建立 Pub/Sub 主題。
  • 使用下列要求建立規則,觸發發布 Pub/Sub 動作。(請參閱以下範例)。
  • 呼叫 Document AI Warehouse API。
  • 確認訊息是否發布至 Pub/Sub 管道。

範例規則

在資料夾中新增文件時 (叫用 CreateLink API),可以使用下列規則將通知訊息傳送至 Pub/Sub 主題。

REST

要求:

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/ruleSets \
-d '{
  "rules": [
    {
      "trigger_type": "ON_CREATE_LINK",
      "condition": "documentType == \'DriverLicenseFolder\'",
      "actions": {
        "publish_to_pub_sub": {
          "topic_id": "<topic_name>"
          "messages": "Added document under a folder."
        }
      }
    }
  ]
}'

規則詳細資料

  • 這項動作支援下列觸發條件類型:

    • ON_CRATE:建立新文件時。
    • ON_UPDATE:文件更新時。
    • ON_CRATE_LINK:建立新連結時。
    • ON_DELETE_LINK:連結遭刪除時。
  • 如果是「建立及更新文件」觸發條件,條件可以包含建立或更新文件的屬性。

  • 如果是「建立連結」和「刪除連結」觸發條件,條件只能包含要新增或移除文件的資料夾文件屬性。

  • messages 欄位可用於將訊息清單傳送至 Pub/Sub 管道。請注意,除了這些訊息,根據預設,系統也會發布下列欄位:

    • 結構定義名稱、文件名稱、觸發條件類型、規則集名稱、規則 ID、動作 ID
    • 如果是「建立連結」和「刪除連結」觸發條件,通知會包含新增或刪除的相關連結資訊。