// 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 }