feat: validate and activate AI table bindings
This commit is contained in:
@@ -19,11 +19,12 @@ const defaultBase = "https://api.dingtalk.com"
|
||||
|
||||
// Config holds the required parameters for the DingTalk question-table client.
|
||||
type Config struct {
|
||||
ClientID string
|
||||
Secret string
|
||||
BaseID string
|
||||
SheetID string
|
||||
OperatorID string
|
||||
ClientID string
|
||||
Secret string
|
||||
BaseID string
|
||||
SheetID string
|
||||
OperatorID string
|
||||
FieldMapping map[string]string
|
||||
|
||||
// TokenURL overrides the token endpoint. Empty → default.
|
||||
TokenURL string
|
||||
@@ -54,11 +55,12 @@ var defaultTransport = func() *http.Transport {
|
||||
// Client is a stdlib-only DingTalk HTTP client that inserts records into a
|
||||
// Notable v1 base. It owns a mutex-protected in-memory access-token cache.
|
||||
type Client struct {
|
||||
clientID string
|
||||
secret string
|
||||
baseID string
|
||||
sheetID string
|
||||
operatorID string
|
||||
clientID string
|
||||
secret string
|
||||
baseID string
|
||||
sheetID string
|
||||
operatorID string
|
||||
fieldMapping map[string]string
|
||||
|
||||
tokenURL string
|
||||
baseURL string
|
||||
@@ -113,14 +115,15 @@ func NewClient(cfg Config, httpClient *http.Client) (*Client, error) {
|
||||
}
|
||||
|
||||
return &Client{
|
||||
clientID: clientID,
|
||||
secret: secret,
|
||||
baseID: baseID,
|
||||
sheetID: sheetID,
|
||||
operatorID: operatorID,
|
||||
tokenURL: tokenURL,
|
||||
baseURL: baseURL,
|
||||
http: httpClient,
|
||||
clientID: clientID,
|
||||
secret: secret,
|
||||
baseID: baseID,
|
||||
sheetID: sheetID,
|
||||
operatorID: operatorID,
|
||||
fieldMapping: cloneFieldMapping(cfg.FieldMapping),
|
||||
tokenURL: tokenURL,
|
||||
baseURL: baseURL,
|
||||
http: httpClient,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -161,6 +164,7 @@ func (c *Client) InsertRecord(ctx context.Context, row Row) (string, error) {
|
||||
// InsertFields sends one already-typed field map to DingTalk Notable v1 and
|
||||
// returns the record ID. It is shared by other reviewed Notable table schemas.
|
||||
func (c *Client) InsertFields(ctx context.Context, fields map[string]interface{}) (string, error) {
|
||||
fields = c.remapFields(fields)
|
||||
token, err := c.getAccessToken(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("questiontable token: %w", err)
|
||||
@@ -213,6 +217,37 @@ func (c *Client) InsertFields(ctx context.Context, fields map[string]interface{}
|
||||
return ir.Value[0].ID, nil
|
||||
}
|
||||
|
||||
func cloneFieldMapping(in map[string]string) map[string]string {
|
||||
out := make(map[string]string, len(in))
|
||||
for key, value := range in {
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var providerFieldLogical = map[string]string{
|
||||
"ZaMZF6j": "chinese_question", "SCug9My": "asked_time", "S2XA1uZ": "asker",
|
||||
"bETcL3r": "original_question", "Y4cpmxU": "answer", "JgY2f1z": "trigger_person",
|
||||
"DNIV3mQ": "language", "eBc6a6b": "department", "fPNLeVW": "region",
|
||||
"01ZM8y7": "standard_question", "fj3JQ1C": "original_question", "07YYagS": "language", "Eu7gkKu": "asker",
|
||||
}
|
||||
|
||||
func (c *Client) remapFields(in map[string]interface{}) map[string]interface{} {
|
||||
if len(c.fieldMapping) == 0 {
|
||||
return in
|
||||
}
|
||||
out := make(map[string]interface{}, len(in))
|
||||
for providerID, value := range in {
|
||||
logical := providerFieldLogical[providerID]
|
||||
if mapped := c.fieldMapping[logical]; logical != "" && mapped != "" {
|
||||
out[mapped] = value
|
||||
} else {
|
||||
out[providerID] = value
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// safeDoErr wraps an http.Do error without exposing the raw URL or credentials.
|
||||
// If the context is already done, returns a wrapped ctx.Err() so errors.Is works.
|
||||
func safeDoErr(ctx context.Context, err error) error {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package questiontable
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRemapFieldsUsesValidatedLogicalMapping(t *testing.T) {
|
||||
client := &Client{fieldMapping: map[string]string{"answer": "new-answer", "original_question": "new-question"}}
|
||||
got := client.remapFields(map[string]interface{}{FieldAnswer: "A", FieldOriginalQuestion: "Q"})
|
||||
if got["new-answer"] != "A" || got["new-question"] != "Q" {
|
||||
t.Fatalf("got=%#v", got)
|
||||
}
|
||||
if _, ok := got[FieldAnswer]; ok {
|
||||
t.Fatal("legacy field id must not remain when mapping exists")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Field struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type RequiredField struct {
|
||||
Logical string
|
||||
Name string
|
||||
Type string
|
||||
}
|
||||
|
||||
func QuestionSchema() []RequiredField {
|
||||
return []RequiredField{
|
||||
{"chinese_question", "中文问题", "text"},
|
||||
{"asked_time", "提问时间", "date"},
|
||||
{"asker", "提问人", "user"},
|
||||
{"original_question", "原始问题", "text"},
|
||||
{"answer", "AI答案", "text"},
|
||||
{"trigger_person", "流程触发人员信息", "text"},
|
||||
{"language", "语言", "text"},
|
||||
{"department", "部门", "text"},
|
||||
{"region", "区域", "text"},
|
||||
}
|
||||
}
|
||||
|
||||
func FAQSchema() []RequiredField {
|
||||
return []RequiredField{
|
||||
{"standard_question", "标准问题(必填)", "text"},
|
||||
{"original_question", "原始问题", "text"},
|
||||
{"language", "语言", "text"},
|
||||
{"asker", "提问人", "user"},
|
||||
}
|
||||
}
|
||||
|
||||
func MapRequiredFields(fields []Field, required []RequiredField) (map[string]string, error) {
|
||||
out := make(map[string]string, len(required))
|
||||
for _, want := range required {
|
||||
nameMatches := make([]Field, 0, 1)
|
||||
for _, got := range fields {
|
||||
if strings.TrimSpace(got.Name) == want.Name {
|
||||
nameMatches = append(nameMatches, got)
|
||||
}
|
||||
}
|
||||
if len(nameMatches) == 0 {
|
||||
return nil, errors.New("missing_field")
|
||||
}
|
||||
if len(nameMatches) > 1 {
|
||||
return nil, errors.New("duplicate_field")
|
||||
}
|
||||
if strings.TrimSpace(nameMatches[0].Type) != want.Type {
|
||||
return nil, errors.New("field_type_mismatch")
|
||||
}
|
||||
if strings.TrimSpace(nameMatches[0].ID) == "" {
|
||||
return nil, errors.New("missing_field_id")
|
||||
}
|
||||
out[want.Logical] = strings.TrimSpace(nameMatches[0].ID)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Client) ReadFields(ctx context.Context) ([]Field, error) {
|
||||
token, err := c.getAccessToken(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.New("schema_token_failed")
|
||||
}
|
||||
endpoint := fmt.Sprintf("%s/v1.0/notable/bases/%s/sheets/%s/fields?operatorId=%s", c.baseURL, url.PathEscape(c.baseID), url.PathEscape(c.sheetID), url.QueryEscape(c.operatorID))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, errors.New("schema_request_failed")
|
||||
}
|
||||
req.Header.Set("x-acs-dingtalk-access-token", token)
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, errors.New("schema_network_failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 256<<10))
|
||||
if err != nil {
|
||||
return nil, errors.New("schema_read_failed")
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("schema_http_%d", resp.StatusCode)
|
||||
}
|
||||
var payload struct {
|
||||
Value []Field `json:"value"`
|
||||
}
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return nil, errors.New("schema_decode_failed")
|
||||
}
|
||||
if len(payload.Value) == 0 {
|
||||
return nil, errors.New("schema_empty")
|
||||
}
|
||||
return payload.Value, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package questiontable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadFieldsUsesOperatorAndMapsQuestionSchema(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))
|
||||
})
|
||||
mux.HandleFunc("/v1.0/notable/bases/base/sheets/sheet/fields", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("operatorId") != "union" {
|
||||
t.Fatalf("operator=%q", r.URL.Query().Get("operatorId"))
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"value":[
|
||||
{"id":"q","name":"中文问题","type":"text"},{"id":"time","name":"提问时间","type":"date"},
|
||||
{"id":"asker","name":"提问人","type":"user"},{"id":"orig","name":"原始问题","type":"text"},
|
||||
{"id":"answer","name":"AI答案","type":"text"},{"id":"trigger","name":"流程触发人员信息","type":"text"},
|
||||
{"id":"lang","name":"语言","type":"text"},{"id":"dept","name":"部门","type":"text"},{"id":"region","name":"区域","type":"text"}]}`))
|
||||
})
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
client, err := NewClient(Config{ClientID: "id", Secret: "secret", BaseID: "base", SheetID: "sheet", OperatorID: "union", TokenURL: server.URL + "/token", BaseURL: server.URL}, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fields, err := client.ReadFields(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mapping, err := MapRequiredFields(fields, QuestionSchema())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mapping["answer"] != "answer" || len(mapping) != 9 {
|
||||
t.Fatalf("mapping=%v", mapping)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapRequiredFieldsRejectsMissingDuplicateAndWrongType(t *testing.T) {
|
||||
required := []RequiredField{{Logical: "question", Name: "问题", Type: "text"}}
|
||||
cases := []struct {
|
||||
name string
|
||||
fields []Field
|
||||
code string
|
||||
}{
|
||||
{"missing", nil, "missing_field"},
|
||||
{"duplicate", []Field{{ID: "1", Name: "问题", Type: "text"}, {ID: "2", Name: "问题", Type: "text"}}, "duplicate_field"},
|
||||
{"wrong type", []Field{{ID: "1", Name: "问题", Type: "user"}}, "field_type_mismatch"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := MapRequiredFields(tc.fields, required)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.code) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFAQSchemaUsesFourCurrentInsertFields(t *testing.T) {
|
||||
required := FAQSchema()
|
||||
if len(required) != 4 {
|
||||
t.Fatalf("len=%d", len(required))
|
||||
}
|
||||
want := map[string]string{"standard_question": "text", "original_question": "text", "language": "text", "asker": "user"}
|
||||
for _, field := range required {
|
||||
if want[field.Logical] != field.Type {
|
||||
t.Fatalf("field=%+v", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user