Files
runny 9058149576
Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s
refactor: 项目更名 WeKnora → Academy
- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名)
- 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块)
- docreader proto 描述符采用等长替换,保持序列化字节布局有效
- Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像
- 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
2026-11-13 20:52:51 +08:00

364 lines
11 KiB
Go

// Package oa reads the 泛微 e-cology OA SQL Server directory to map employee
// workcodes (工号) to WeCom userids, porting the proven sync from the HXPH
// project (HXPH/backend/app/services/integrations/oa/wecom_sync.py):
// local-workcode-driven IN queries against userInfo_view (id = WeCom userid,
// workcode = 工号), three-way conflict detection (duplicate workcode in OA /
// employee already bound to a different userid / userid occupied by another
// employee), preview-first then apply. Nothing is written while conflicts
// exist.
package oa
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
_ "github.com/microsoft/go-mssqldb"
"gorm.io/gorm"
)
const (
// oaView is the read-only e-cology view exposing directory members;
// its id column IS the WeCom userid (same convention as HXPH).
oaView = "userInfo_view"
// oaBatchSize caps each IN query to avoid giant parameter lists.
oaBatchSize = 500
// previewLimit bounds the sample lists returned in a summary.
previewLimit = 20
)
// Config is the OA SQL Server connection; defaults mirror the HXPH
// deployment so the sync works out of the box on the same intranet.
type Config struct {
Host string
Port string
Database string
Username string
Password string
Timeout time.Duration
}
// ConfigFromEnv reads OA_SQLSERVER_* variables with HXPH-compatible defaults.
func ConfigFromEnv() Config {
return Config{
Host: getenv("OA_SQLSERVER_HOST", "192.168.100.225"),
Port: getenv("OA_SQLSERVER_PORT", "1433"),
Database: getenv("OA_SQLSERVER_DATABASE", "ecology"),
Username: getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA"),
Password: getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA"),
Timeout: 10 * time.Second,
}
}
func getenv(key, def string) string {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
return v
}
return def
}
// OABinding is one row of the OA directory: workcode → wecom userid.
type OABinding struct {
Workcode string
WecomUserid string
Name string
}
// Connect opens a short-lived SQL Server connection (keyword DSN avoids
// escaping issues with special characters in credentials).
func (c Config) Connect(ctx context.Context) (*sql.DB, error) {
dsn := fmt.Sprintf(
"server=%s;port=%s;user id=%s;password=%s;database=%s;encrypt=disable;connection timeout=%d",
c.Host, c.Port, c.Username, c.Password, c.Database,
int(c.Timeout/time.Second),
)
db, err := sql.Open("sqlserver", dsn)
if err != nil {
return nil, fmt.Errorf("open oa sqlserver: %w", err)
}
db.SetConnMaxLifetime(c.Timeout)
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, fmt.Errorf("ping oa sqlserver %s:%s: %w", c.Host, c.Port, err)
}
return db, nil
}
// FetchOAWecomBindings queries the OA directory for the deduplicated
// workcode list (batched IN queries).
func FetchOAWecomBindings(ctx context.Context, cfg Config, workcodes []string) ([]OABinding, error) {
unique := make([]string, 0, len(workcodes))
seen := make(map[string]bool, len(workcodes))
for _, code := range workcodes {
code = strings.TrimSpace(code)
if code == "" || seen[code] {
continue
}
seen[code] = true
unique = append(unique, code)
}
if len(unique) == 0 {
return nil, nil
}
conn, err := cfg.Connect(ctx)
if err != nil {
return nil, err
}
defer func() { _ = conn.Close() }()
bindings := make([]OABinding, 0, len(unique))
for offset := 0; offset < len(unique); offset += oaBatchSize {
end := offset + oaBatchSize
if end > len(unique) {
end = len(unique)
}
batch := unique[offset:end]
// go-mssqldb does not support '?' placeholders (pyodbc style); it
// requires positional @p1..@pN (see driver doc.go # Query Parameters).
placeholders := make([]string, len(batch))
args := make([]any, len(batch))
for i, code := range batch {
placeholders[i] = fmt.Sprintf("@p%d", i+1)
args[i] = code
}
query := fmt.Sprintf(
"SELECT id, workcode, lastname FROM %s WHERE workcode IN (%s) AND id IS NOT NULL",
oaView, strings.Join(placeholders, ","),
)
rows, err := conn.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("query %s: %w", oaView, err)
}
for rows.Next() {
var userid, workcode, name sql.NullString
if err := rows.Scan(&userid, &workcode, &name); err != nil {
_ = rows.Close()
return nil, fmt.Errorf("scan oa row: %w", err)
}
code := strings.TrimSpace(workcode.String)
wxid := strings.TrimSpace(userid.String)
if code == "" || wxid == "" {
continue
}
bindings = append(bindings, OABinding{
Workcode: code,
WecomUserid: wxid,
Name: strings.TrimSpace(name.String),
})
}
if err := rows.Err(); err != nil {
_ = rows.Close()
return nil, fmt.Errorf("iterate oa rows: %w", err)
}
_ = rows.Close()
}
return bindings, nil
}
// SyncConflict explains why one employee could not be auto-synced.
type SyncConflict struct {
EmployeeID string `json:"employee_id"`
EmployeeNo string `json:"employee_no"`
UserName string `json:"user_name"`
Reason string `json:"reason"`
ExistingWecomUserid string `json:"existing_wecom_userid,omitempty"`
NewWecomUserid string `json:"new_wecom_userid"`
OccupiedByEmployee string `json:"occupied_by_employee,omitempty"`
}
// SyncMissing is an employee whose workcode was not found in the OA view.
type SyncMissing struct {
EmployeeID string `json:"employee_id"`
EmployeeNo string `json:"employee_no"`
UserName string `json:"user_name"`
}
// SyncPending is one planned write in the preview.
type SyncPending struct {
EmployeeID string `json:"employee_id"`
EmployeeNo string `json:"employee_no"`
UserName string `json:"user_name"`
Name string `json:"name"`
WecomUserid string `json:"wecom_userid"`
}
// SyncSummary mirrors the HXPH sync report so the frontend presentation can
// follow the same binding-management page design.
type SyncSummary struct {
Apply bool `json:"apply"`
MatchKey string `json:"match_key"`
LocalCandidates int `json:"local_candidates"`
OaUsers int `json:"oa_users"`
LocalMatched int `json:"local_matched"`
AlreadyBound int `json:"already_bound"`
WouldUpdate int `json:"would_update"`
Updated int `json:"updated"`
LocalMissing int `json:"local_missing"`
ConflictCount int `json:"conflict_count"`
Conflicts []SyncConflict `json:"conflicts"`
MissingSamples []SyncMissing `json:"missing_samples"`
PendingUpdates []SyncPending `json:"pending_updates"`
}
// SyncWecomUseridsFromOA syncs org_employees.wecom_userid for one tenant's
// employees keyed by employee_no = OA workcode. Preview (apply=false) never
// writes; apply writes only when the conflict list is empty.
func SyncWecomUseridsFromOA(ctx context.Context, db *gorm.DB, tenantID uint64, apply bool) (*SyncSummary, error) {
cfg := ConfigFromEnv()
summary := &SyncSummary{
Apply: apply,
MatchKey: fmt.Sprintf("oa:%s.workcode = org_employees.employee_no", oaView),
Conflicts: []SyncConflict{},
MissingSamples: []SyncMissing{},
PendingUpdates: []SyncPending{},
}
var employees []*types.OrgEmployee
if err := db.WithContext(ctx).
Where("tenant_id = ? AND deleted_at IS NULL AND employee_no <> ''", tenantID).
Order("id").
Find(&employees).Error; err != nil {
return nil, fmt.Errorf("load org employees: %w", err)
}
summary.LocalCandidates = len(employees)
if len(employees) == 0 {
return summary, nil
}
workcodes := make([]string, 0, len(employees))
for _, e := range employees {
workcodes = append(workcodes, e.EmployeeNo)
}
bindings, err := FetchOAWecomBindings(ctx, cfg, workcodes)
if err != nil {
return nil, err
}
byWorkcode := make(map[string]OABinding, len(bindings))
for _, b := range bindings {
if _, dup := byWorkcode[b.Workcode]; dup {
summary.Conflicts = append(summary.Conflicts, SyncConflict{
EmployeeNo: b.Workcode,
Reason: "duplicate_workcode_in_oa",
NewWecomUserid: b.WecomUserid,
})
continue
}
byWorkcode[b.Workcode] = b
}
summary.OaUsers = len(byWorkcode)
duplicates := map[string]bool{}
for _, c := range summary.Conflicts {
duplicates[c.EmployeeNo] = true
}
// Occupied map: which employee (id) holds each already-bound wecom userid
// in this tenant, for the takeover conflict check.
var planned []struct {
employee *types.OrgEmployee
userid string
name string
}
for _, e := range employees {
if duplicates[e.EmployeeNo] {
continue
}
binding, ok := byWorkcode[e.EmployeeNo]
if !ok {
summary.LocalMissing++
if len(summary.MissingSamples) < previewLimit {
summary.MissingSamples = append(summary.MissingSamples, SyncMissing{
EmployeeID: e.ID,
EmployeeNo: e.EmployeeNo,
UserName: employeeName(e),
})
}
continue
}
summary.LocalMatched++
if e.WecomUserid == binding.WecomUserid {
summary.AlreadyBound++
continue
}
if e.WecomUserid != "" {
summary.Conflicts = append(summary.Conflicts, SyncConflict{
EmployeeID: e.ID,
EmployeeNo: e.EmployeeNo,
UserName: employeeName(e),
Reason: "bound_to_different_userid",
ExistingWecomUserid: e.WecomUserid,
NewWecomUserid: binding.WecomUserid,
})
continue
}
// userid taken by another employee in the same tenant?
var holder types.OrgEmployee
err := db.WithContext(ctx).
Where("tenant_id = ? AND wecom_userid = ? AND deleted_at IS NULL", tenantID, binding.WecomUserid).
First(&holder).Error
if err == nil {
summary.Conflicts = append(summary.Conflicts, SyncConflict{
EmployeeID: e.ID,
EmployeeNo: e.EmployeeNo,
UserName: employeeName(e),
Reason: "userid_occupied",
NewWecomUserid: binding.WecomUserid,
OccupiedByEmployee: employeeName(&holder) + "(" + holder.EmployeeNo + ")",
})
continue
} else if err != gorm.ErrRecordNotFound {
return nil, fmt.Errorf("check userid occupancy: %w", err)
}
summary.WouldUpdate++
if len(summary.PendingUpdates) < previewLimit {
summary.PendingUpdates = append(summary.PendingUpdates, SyncPending{
EmployeeID: e.ID,
EmployeeNo: e.EmployeeNo,
UserName: employeeName(e),
Name: binding.Name,
WecomUserid: binding.WecomUserid,
})
}
planned = append(planned, struct {
employee *types.OrgEmployee
userid string
name string
}{e, binding.WecomUserid, binding.Name})
}
summary.ConflictCount = len(summary.Conflicts)
if !apply || len(summary.Conflicts) > 0 {
// Preview, or blocked apply: nothing written.
return summary, nil
}
for _, p := range planned {
err := db.WithContext(ctx).Model(&types.OrgEmployee{}).
Where("tenant_id = ? AND id = ?", tenantID, p.employee.ID).
Update("wecom_userid", p.userid).Error
if err != nil {
return nil, fmt.Errorf("write wecom_userid for %s: %w", p.employee.EmployeeNo, err)
}
summary.Updated++
}
logger.Infof(ctx, "[oa_wecom_sync] tenant %d: updated=%d already_bound=%d conflicts=%d missing=%d",
tenantID, summary.Updated, summary.AlreadyBound, summary.ConflictCount, summary.LocalMissing)
return summary, nil
}
// employeeName picks the display name for reports.
func employeeName(e *types.OrgEmployee) string {
if e.UserName != "" {
return e.UserName
}
return e.EmployeeNo
}