Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: comment feishu approval on canceling it (#3512)
p0nyeff671a94f85
diff --git a/plugin/app/feishu/feishu.go b/plugin/app/feishu/feishu.goindex fb92eefa59..edc36a9f1f 100644--- a/plugin/app/feishu/feishu.go+++ b/plugin/app/feishu/feishu.go@@ -127,6 +127,12 @@ type GetExternalApprovalResponse struct {} `json:"data"`}+// CreateExternalApprovalCommentResponse is the response of CreateExternalApprovalComment.+type CreateExternalApprovalCommentResponse struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+}+// CancelExternalApprovalResponse is the response of CancelExternalApproval.type CancelExternalApprovalResponse struct {Code int `json:"code"`@@ -153,6 +159,11 @@ type CreateApprovalInstanceRequest struct {OpenID string `json:"open_id"`}+// CreateExternalApprovalCommentRequest is the request of CreateExternalApprovalComment.+type CreateExternalApprovalCommentRequest struct {+ Content string `json:"content"`+}+// CancelExternalApprovalRequest is the request of CancelExternalApproval.type CancelExternalApprovalRequest struct {ApprovalCode string `json:"approval_code"`@@ -425,7 +436,7 @@ func (p *Provider) CreateExternalApproval(ctx context.Context, tokenCtx TokenCtxurl := fmt.Sprintf("%s/approval/v4/instances", p.APIPath)formValue, err := formatForm(content)if err != nil {- return "", errors.Wrap(err, "failed to compose formValue")+ return "", errors.Wrapf(err, "failed to compose formValue, content %+v", content)}payload := CreateApprovalInstanceRequest{ApprovalCode: approvalCode,@@ -489,6 +500,44 @@ func (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx Tokenreturn response.Data.Status, nil}+// CreateExternalApprovalComment comments an external approval.+// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance-comment/create+func (p *Provider) CreateExternalApprovalComment(ctx context.Context, tokenCtx TokenCtx, instanceCode string, userID string, msg string) error {+ url := fmt.Sprintf("%s/approval/v4/instances/%s/comments?user_id=%s", p.APIPath, instanceCode, userID)+ content, err := json.Marshal(struct {+ Text string `json:"text"`+ }{+ Text: msg,+ })+ if err != nil {+ return errors.Wrap(err, "failed to marshal content")+ }+ payload := CreateExternalApprovalCommentRequest{+ Content: string(content),+ }+ body, err := json.Marshal(payload)+ if err != nil {+ return errors.Wrapf(err, "failed to marshal payload %+v", payload)+ }+ code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))+ if err != nil {+ return err+ }+ if code != http.StatusOK {+ return errors.Errorf("non-200 POST status code %d with body %q", code, b)+ }++ var response CreateExternalApprovalCommentResponse+ if err := json.Unmarshal([]byte(b), &response); err != nil {+ return err+ }+ if response.Code != 0 {+ return errors.Errorf("failed to create external approval comment, code %d, msg %s", response.Code, response.Msg)+ }++ return nil+}+// CancelExternalApproval cancels an external approval.// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance/cancelfunc (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtx, approvalCode, instanceCode, userID string) error {diff --git a/plugin/app/feishu/feishu_test.go b/plugin/app/feishu/feishu_test.goindex 0a8072e737..ece3b09abe 100644--- a/plugin/app/feishu/feishu_test.go+++ b/plugin/app/feishu/feishu_test.go@@ -132,6 +132,32 @@ func TestProvider_GetExternalApprovalStatus(t *testing.T) {a.Equal(want, status)}+func TestProvider_CreateExternalApprovalComemnt(t *testing.T) {+ a := require.New(t)+ p := NewProvider(APIPath)+ p.client = &http.Client{+ Transport: &common.MockRoundTripper{+ MockRoundTrip: func(r *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(`+{+ "code": 0,+ "data": {+ "comment_id": "7169475380984840194"+ },+ "msg": ""+}+`)),+ }, nil+ },+ },+ }+ ctx := context.Background()+ err := p.CreateExternalApprovalComment(ctx, TokenCtx{}, "", "", "test")+ a.NoError(err)+}+func TestProvider_CancelExternalApproval(t *testing.T) {a := require.New(t)p := NewProvider(APIPath)diff --git a/server/application_runner.go b/server/application_runner.goindex 1af9211770..ea981ed658 100644--- a/server/application_runner.go+++ b/server/application_runner.go@@ -16,7 +16,18 @@ import ("github.com/bytebase/bytebase/store")-const applicationRunnerInterval = time.Duration(60) * time.Second+const (+ applicationRunnerInterval = time.Duration(60) * time.Second++ // externalApprovalCancelReasonGeneral is the general reason, used as a default.+ externalApprovalCancelReasonGeneral string = "Canceled because the assignee has been changed, or all tasks of the stage have been approved or the issue is no longer open."+ // externalApprovalCancelReasonIssueNotOpen is used if the issue is not open.+ externalApprovalCancelReasonIssueNotOpen string = "Canceled because the containing issue is no longer open."+ // externalApprovalCancelReasonReassigned is used if the assignee has been changed.+ externalApprovalCancelReasonReassigned string = "Canceled because the assignee has changed."+ // externalApprovalCancelReasonNoTaskPendingApproval is used if there is no pending approval tasks.+ externalApprovalCancelReasonNoTaskPendingApproval string = "Canceled because all tasks have benn approved."+)// NewApplicationRunner returns a ApplicationRunner.func NewApplicationRunner(store *store.Store, activityManager *ActivityManager, feishuProvider *feishu.Provider) *ApplicationRunner {@@ -93,7 +104,7 @@ func (r *ApplicationRunner) Run(ctx context.Context, wg *sync.WaitGroup) {stage = issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]}if issue.Status != api.IssueOpen {- if err := r.CancelExternalApproval(ctx, issue.ID); err != nil {+ if err := r.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonIssueNotOpen); err != nil {log.Error("failed to cancel external approval", zap.Error(err))}continue@@ -176,11 +187,14 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Contexreturn nil, err}+ reason := externalApprovalCancelReasonGeneralcancelOld := func() bool {if payload.StageID != stage.ID {+ reason = externalApprovalCancelReasonNoTaskPendingApprovalreturn true}if payload.AssigneeID != issue.AssigneeID {+ reason = externalApprovalCancelReasonReassignedreturn true}pendingApprovalCount := 0@@ -189,13 +203,25 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.ContexpendingApprovalCount++}}- return pendingApprovalCount == 0+ if pendingApprovalCount == 0 {+ reason = externalApprovalCancelReasonNoTaskPendingApproval+ return true+ }+ return false}()if cancelOld {if _, err := r.store.PatchExternalApproval(ctx, &api.ExternalApprovalPatch{ID: approval.ID, RowStatus: api.Archived}); err != nil {return nil, err}+ botID, err := r.p.GetBotID(ctx,+ feishu.TokenCtx{+ AppID: settingValue.AppID,+ AppSecret: settingValue.AppSecret,+ })+ if err != nil {+ return nil, err+ }if err := r.p.CancelExternalApproval(ctx,feishu.TokenCtx{AppID: settingValue.AppID,@@ -203,7 +229,18 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Contex},settingValue.ExternalApproval.ApprovalDefinitionID,payload.InstanceCode,- payload.RequesterID,+ botID,+ ); err != nil {+ return nil, err+ }+ if err := r.p.CreateExternalApprovalComment(ctx,+ feishu.TokenCtx{+ AppID: settingValue.AppID,+ AppSecret: settingValue.AppSecret,+ },+ payload.InstanceCode,+ botID,+ string(reason),); err != nil {return nil, err}@@ -212,7 +249,7 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Contex}// CancelExternalApproval cancels the active external approval of an issue.-func (r *ApplicationRunner) CancelExternalApproval(ctx context.Context, issueID int) error {+func (r *ApplicationRunner) CancelExternalApproval(ctx context.Context, issueID int, reason string) error {settingName := api.SettingAppIMsetting, err := r.store.GetSetting(ctx, &api.SettingFind{Name: &settingName})if err != nil {@@ -245,14 +282,33 @@ func (r *ApplicationRunner) CancelExternalApproval(ctx context.Context, issueIDif _, err := r.store.PatchExternalApproval(ctx, &api.ExternalApprovalPatch{ID: approval.ID, RowStatus: api.Archived}); err != nil {return err}- return r.p.CancelExternalApproval(ctx,+ botID, err := r.p.GetBotID(ctx,+ feishu.TokenCtx{+ AppID: value.AppID,+ AppSecret: value.AppSecret,+ })+ if err != nil {+ return err+ }+ if err := r.p.CancelExternalApproval(ctx,feishu.TokenCtx{AppID: value.AppID,AppSecret: value.AppSecret,},value.ExternalApproval.ApprovalDefinitionID,payload.InstanceCode,- payload.RequesterID,+ botID,+ ); err != nil {+ return err+ }+ return r.p.CreateExternalApprovalComment(ctx,+ feishu.TokenCtx{+ AppID: value.AppID,+ AppSecret: value.AppSecret,+ },+ payload.InstanceCode,+ botID,+ reason,)}diff --git a/server/issue.go b/server/issue.goindex 67d1b05f51..1231180163 100644--- a/server/issue.go+++ b/server/issue.go@@ -1418,7 +1418,7 @@ func (s *Server) changeIssueStatus(ctx context.Context, issue *api.Issue, newSta// Cancel external approval, it's ok if we failed.if newStatus != api.IssueOpen {- if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID); err != nil {+ if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonIssueNotOpen); err != nil {log.Error("failed to cancel external approval on issue cancellation or completion", zap.Error(err))}}diff --git a/tests/fake/feishu.go b/tests/fake/feishu.goindex bc5b03536e..0d7dbb01f5 100644--- a/tests/fake/feishu.go+++ b/tests/fake/feishu.go@@ -28,6 +28,8 @@ type Feishu struct {approvalInstance map[string]*approval// email to user id mapping.users map[string]string+ // user id set+ userIDs map[string]bool}// FeishuProviderCreator is the function to create a fake feishu provider.@@ -48,14 +50,16 @@ func NewFeishu(port int) *Feishu {e.Use(middleware.Logger())e.Use(middleware.Recover())+ botID := uuid.NewString()f := &Feishu{port: port,echo: e,approvalDefinition: map[string]bool{},approvalInstance: map[string]*approval{},users: map[string]string{},+ userIDs: map[string]bool{botID: true},mutex: sync.Mutex{},- botID: uuid.NewString(),+ botID: botID,}// Routes@@ -63,6 +67,7 @@ func NewFeishu(port int) *Feishu {g.POST("/approval/v4/approvals", f.createApprovalDefinition)g.POST("/approval/v4/instances", f.createApprovalInstance)g.GET("/approval/v4/instances/:id", f.getApprovalInstanceStatus)+ g.POST("/approval/v4/instances/:id/comments", f.createApprovalInstanceComment)g.POST("/approval/v4/instances/cancel", f.cancelApprovalInstance)g.POST("/contact/v3/users/batch_get_id", f.getIDByEmail)g.GET("/bot/v3/info", f.getBotID)@@ -99,7 +104,9 @@ func (f *Feishu) RegisterEmails(emails ...string) error {if ok {return errors.Errorf("register email %s twice", email)}- f.users[email] = uuid.NewString()+ id := uuid.NewString()+ f.users[email] = id+ f.userIDs[id] = true}return nil}@@ -158,6 +165,16 @@ func (f *Feishu) createApprovalInstance(c echo.Context) error {if !f.approvalDefinition[create.ApprovalCode] {return errors.Errorf("not found approval code %s", create.ApprovalCode)}+ if !f.userIDs[create.OpenID] {+ return errors.Errorf("not found user id %s", create.OpenID)+ }+ for _, idList := range create.NodeApproverOpenIDList {+ for _, id := range idList.Value {+ if !f.userIDs[id] {+ return errors.Errorf("not found user id %s", id)+ }+ }+ }id := uuid.NewString()f.approvalInstance[id] = &approval{@@ -177,6 +194,32 @@ func (f *Feishu) createApprovalInstance(c echo.Context) error {})}+func (f *Feishu) createApprovalInstanceComment(c echo.Context) error {+ userID := c.QueryParam("user_id")+ instanceID := c.Param("id")+ b, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return errors.Wrap(err, "failed to read create approval instance body")+ }+ create := &feishu.CreateExternalApprovalCommentRequest{}+ if err := json.Unmarshal(b, create); err != nil {+ return errors.Wrap(err, "failed to unmarshal create approval instance body")+ }+ f.mutex.Lock()+ defer f.mutex.Unlock()+ if _, ok := f.approvalInstance[instanceID]; !ok {+ return errors.Errorf("not found approval instance code %s", instanceID)+ }+ if !f.userIDs[userID] {+ return errors.Errorf("not found user id %s", userID)+ }++ return c.JSON(http.StatusOK, &feishu.CreateExternalApprovalCommentResponse{+ Code: 0,+ Msg: "",+ })+}+func (f *Feishu) getApprovalInstanceStatus(c echo.Context) error {f.mutex.Lock()defer f.mutex.Unlock()@@ -212,6 +255,9 @@ func (f *Feishu) cancelApprovalInstance(c echo.Context) error {if !ok {return errors.Errorf("not found approval %s", req.InstanceCode)}+ if !f.userIDs[req.UserID] {+ return errors.Errorf("not found user id %s", req.UserID)+ }if approval.status != feishu.ApprovalStatusPending {return errors.Errorf(`expect to cancel a "pending" approval, but get status %q`, approval.status)}