RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
refactor: keep the enterprise code out of the community build (#21614)
Zhichang Yu9a71c10b090e
diff --git a/.gitignore b/.gitignoreindex 585abe5a47..72b988aa41 100644--- a/.gitignore+++ b/.gitignore@@ -1,3 +1,8 @@+# TLS / Private Keys+*.key+*.crt+*.expired+# Generated by Cargo# will have compiled files and executablesdebug/@@ -21,6 +26,7 @@ Cargo.lock.idea/.vscode/+.emdash/.cursor/settings.json.opencode/@@ -245,6 +251,14 @@ internal/binding/cpp/cmake-build-debug/# Go server build outputbin/*!bin/.gitkeep++# Vite build cache+.vite-cache/++# oh-my-claudecode session state+.omc/++.claude//ragflow_server.claude/settings.local.json@@ -277,3 +291,14 @@ deps/*.zip# external DeepDoc testdata, fetched on demand via scripts/fetch_deepdoc_testdata.sh# (symlinked into place from ~/.cache/ragflow-testdata; never committed)internal/deepdoc/native/testdata++# EE DeepDoc docker build staging: the *.ee.onnx model files are staged here before+# the docker build (Dockerfile_deepdoc_ee COPYs them into the image); they are+# large binaries and must never be committed.+deepdoc_ee_models/+# local scratch go module cache+gomod_cache+# unreferenced e2e sample data (scratch)+parity/+# downloaded Go native deps (fetched by ragflow_deps/download_go_deps.py)+ragflow_deps/diff --git a/build.sh b/build.shindex 38415ee992..2e17623097 100755--- a/build.sh+++ b/build.sh@@ -25,6 +25,29 @@ RAGFLOW_CLI_BINARY="$PROJECT_ROOT/bin/ragflow-cli"# Strip symbols from Go binaries (set via --strip / -s)STRIP_SYMBOLS=""+# Extra Go build tags appended to every build (comma separated). This tree has+# no enterprise edition, so 'ee' is rejected below rather than forwarded.+EXTRA_GO_TAGS="${RAGFLOW_GO_TAGS:-}"+GO_BUILD_TAGS="cgo,static,sonic"+[ -n "$EXTRA_GO_TAGS" ] && GO_BUILD_TAGS="$GO_BUILD_TAGS,$EXTRA_GO_TAGS"+# The go test calls below predate `go build`, so they spell tags both+# comma-separated ("cgo,static") and space-separated ("cgo static+# integration"). Both forms accept the extra tags, so keep one variant each.+EXTRA_TAGS_COMMA=""+EXTRA_TAGS_SPACE=""+if [ -n "$EXTRA_GO_TAGS" ]; then+ EXTRA_TAGS_COMMA=",$EXTRA_GO_TAGS"+ EXTRA_TAGS_SPACE=" $EXTRA_GO_TAGS"+fi+# This tree ships no enterprise sources, so the ee tag selects nothing: fail+# loudly instead of building a binary without them.+case ",$EXTRA_GO_TAGS," in+ *",ee,"*)+ echo "error: RAGFLOW_GO_TAGS contains 'ee', but this tree has no enterprise sources" >&2+ exit 1+ ;;+esac+# Native static library settings. These are the user-cache paths (~/ragflow-native-libs/).# If /opt/ragflow-native-libs/ exists (pre-seeded in CI runner image), it takes priority# and skips the network (download_dev_deps.py) fallback.@@ -797,12 +820,12 @@ build_go() {echo "Building RAGFlow binary: $RAGFLOW_CLI_BINARY, $RAGFLOW_SERVER_BINARY"set -xGOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} CGO_ENABLED=1 \- go build -tags cgo,static,sonic "${strip_flags[@]}" -o "$RAGFLOW_CLI_BINARY" cmd/ragflow-cli.go+ go build -tags "$GO_BUILD_TAGS" "${strip_flags[@]}" -o "$RAGFLOW_CLI_BINARY" cmd/ragflow-cli.goGOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} CGO_ENABLED=1 \CGO_CFLAGS="$CGO_CFLAGS" CGO_LDFLAGS="$CGO_LDFLAGS" \- go build -tags cgo,static,sonic "${strip_flags[@]}" -o "$RAGFLOW_SERVER_BINARY" \- cmd/ragflow_server.go cmd/deepdoc_server_ee.go+ go build -tags "$GO_BUILD_TAGS" "${strip_flags[@]}" -o "$RAGFLOW_SERVER_BINARY" \+ cmd/ragflow_server.go cmd/stub.goset +x@@ -1024,7 +1047,7 @@ run_go_tests() {fiGOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} CGO_ENABLED=1 \CGO_CFLAGS="$CGO_CFLAGS" CGO_LDFLAGS="$CGO_LDFLAGS" \- go test -tags cgo,static -count=1 "$@"+ go test -tags "cgo,static${EXTRA_TAGS_COMMA}" -count=1 "$@"run_native_tests}@@ -1042,7 +1065,7 @@ run_native_tests() {( cd "$PROJECT_ROOT" && \GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \CGO_ENABLED=1 \- go test -tags cgo,static -count=1 ./internal/deepdoc/native/... )+ go test -tags "cgo,static${EXTRA_TAGS_COMMA}" -count=1 ./internal/deepdoc/native/... )}# Run the model-backed integration tests of the native package and the@@ -1081,20 +1104,20 @@ run_native_integration_tests() {( cd "$PROJECT_ROOT" && \GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \CGO_ENABLED=1 \- go test -tags "cgo static integration fetch_testdata" -count=1 "${native_run_filter[@]}" ./internal/deepdoc/native/... )+ go test -tags "cgo static integration fetch_testdata${EXTRA_TAGS_SPACE}" -count=1 "${native_run_filter[@]}" ./internal/deepdoc/native/... )print_section "Running native integration concurrency tests (race detector on)"( cd "$PROJECT_ROOT" && \GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \CGO_ENABLED=1 \- go test -tags "cgo static integration fetch_testdata" -race -count=1 \+ go test -tags "cgo static integration fetch_testdata${EXTRA_TAGS_SPACE}" -race -count=1 \-run 'TestInferenceConcurrency' ./internal/deepdoc/native/... )print_section "Running native_analyzer race tests (race detector on)"( cd "$PROJECT_ROOT" && \GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \CGO_ENABLED=1 \- go test -tags "cgo static integration fetch_testdata" -race -count=1 \+ go test -tags "cgo static integration fetch_testdata${EXTRA_TAGS_SPACE}" -race -count=1 \./internal/deepdoc/parser/pdf/inference/native_analyzer/... )# EE build extensions hook (build_ee.sh, sourced near the top of this@@ -1125,7 +1148,7 @@ run_go_tests_tagged() {fiGOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} CGO_ENABLED=1 \CGO_CFLAGS="$CGO_CFLAGS" CGO_LDFLAGS="$CGO_LDFLAGS" \- go test -tags "${tags} static" -count=1 "$@"+ go test -tags "${tags} static${EXTRA_TAGS_SPACE}" -count=1 "$@"}# Clean build artifactsdiff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.goindex bfb2903f6d..230f62f086 100644--- a/cmd/ragflow_server.go+++ b/cmd/ragflow_server.go@@ -45,6 +45,7 @@ import (deepdocpkg "ragflow/internal/server/deepdoc"ingestorpkg "ragflow/internal/server/ingestor"syncerpkg "ragflow/internal/server/syncer"+ billing "ragflow/internal/service/billing""ragflow/internal/storage")@@ -541,6 +542,18 @@ func main() {common.Warn("Failed to initialize server variables from Redis, using defaults", zap.String("error", err.Error()))}+ // Billing owns the plan catalogue and the points/quota state machine.+ // It needs the database, cache and MQ to be ready, and only the API server+ // serves billing routes.+ if arguments.Mode != nil && *arguments.Mode == "api" {+ if err = billing.Init(ctx, server.GetConfig().GetBillingConfig()); err != nil {+ common.Fatal("Failed to initialize billing", zap.Error(err))+ }+ if err = billing.Start(ctx); err != nil {+ common.Fatal("Failed to start billing", zap.Error(err))+ }+ }+err = server.StartServer(ctx, cancel, serverName, serverType)if err != nil {common.Error("Failed to start EE server", err)diff --git a/cmd/deepdoc_server_ee.go b/cmd/stub.gosimilarity index 79%rename from cmd/deepdoc_server_ee.gorename to cmd/stub.goindex 4542c59a3c..3a4f76db8a 100644--- a/cmd/deepdoc_server_ee.go+++ b/cmd/stub.go@@ -14,16 +14,19 @@// limitations under the License.//+//go:build !ee+package mainimport ("context"+ "errors"- "ragflow/internal/common""ragflow/internal/server/bootstrap")+// runDeepDoc reports that the EE DeepDoc inference server is an enterprise+// capability.func runDeepDoc(ctx context.Context, serverName string, args *bootstrap.ServerArgs) error {- common.Info("DeepDoc server is not implemented")- return nil+ return errors.New("the DeepDoc inference server is only available in the enterprise edition")}diff --git a/go.mod b/go.modindex f992f21050..e3daad59ce 100644--- a/go.mod+++ b/go.mod@@ -76,7 +76,6 @@ require (github.com/zeebo/xxh3 v1.0.2go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0go.opentelemetry.io/otel v1.45.0- go.opentelemetry.io/otel/sdk v1.45.0go.opentelemetry.io/otel/trace v1.45.0go.uber.org/zap v1.27.1golang.org/x/crypto v0.58.0@@ -242,6 +241,7 @@ require (go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirectgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirectgo.opentelemetry.io/otel/metric v1.45.0 // indirect+ go.opentelemetry.io/otel/sdk v1.45.0 // indirectgo.opentelemetry.io/otel/sdk/metric v1.45.0 // indirectgo.uber.org/atomic v1.11.0 // indirectgo.uber.org/multierr v1.11.0 // indirectdiff --git a/internal/admin/handler_ee.go b/internal/admin/handler_ee.godeleted file mode 100644index d489efe6b1..0000000000--- a/internal/admin/handler_ee.go+++ /dev/null@@ -1,2126 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package admin--import (- "errors"- "net/http"- "ragflow/internal/common"- "ragflow/internal/dao"- "strconv"- "strings"- "time"-- "github.com/gin-gonic/gin"-)--// ListRoles handle list roles-func (h *Handler) ListRoles(c *gin.Context) {- ctx := c.Request.Context()- roles, err := h.service.ListRoles(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- if roles == nil {- roles = []map[string]interface{}{}- }-- common.SuccessWithData(c, roles, "")-}--// CreateRoleHTTPRequest create role request-type CreateRoleHTTPRequest struct {- RoleName string `json:"role_name" binding:"required"`- Description string `json:"description"`-}--// CreateRole handle create role-func (h *Handler) CreateRole(c *gin.Context) {- var req CreateRoleHTTPRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- ctx := c.Request.Context()- role, err := h.service.CreateRole(ctx, req.RoleName, req.Description)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, role, "")-}--// ShowRole handle show role-func (h *Handler) ShowRole(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- ctx := c.Request.Context()- role, err := h.service.ShowRole(ctx, roleName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, role, "")-}--// UpdateRoleHTTPRequest update role request-type UpdateRoleHTTPRequest struct {- Description string `json:"description" binding:"required"`-}--// UpdateRole handle update role-func (h *Handler) UpdateRole(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- var req UpdateRoleHTTPRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Role description is required")- return- }-- ctx := c.Request.Context()- role, err := h.service.UpdateRole(ctx, roleName, req.Description)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, role, "")-}--// DropRole handle drop role-func (h *Handler) DropRole(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- ctx := c.Request.Context()- role, err := h.service.DropRole(ctx, roleName)- if err != nil {- common.ErrorWithCode(c, common.CodeNotFound, "Role not found")- return- }-- common.SuccessWithData(c, role, "")-}--// ShowRolePermission handle get role permission-func (h *Handler) ShowRolePermission(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- ctx := c.Request.Context()- permissions, err := h.service.ShowRolePermission(ctx, roleName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, permissions, "")-}--// GrantRolePermissionHTTPRequest grant role permission request-type GrantRolePermissionHTTPRequest struct {- Actions []string `json:"actions" binding:"required"`- Resource string `json:"resource" binding:"required"`-}--// GrantRolePermission handle grant role permission-func (h *Handler) GrantRolePermission(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- var req GrantRolePermissionHTTPRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Permission is required")- return- }-- ctx := c.Request.Context()- result, err := h.service.GrantRolePermission(ctx, roleName, req.Actions, req.Resource)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "")-}--// RevokeRolePermissionHTTPRequest revoke role permission request-type RevokeRolePermissionHTTPRequest struct {- Actions []string `json:"actions" binding:"required"`- Resource string `json:"resource" binding:"required"`-}--// RevokeRolePermission handle revoke role permission-func (h *Handler) RevokeRolePermission(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- var req RevokeRolePermissionHTTPRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Permission is required")- return- }-- ctx := c.Request.Context()- result, err := h.service.RevokeRolePermission(ctx, roleName, req.Actions, req.Resource)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "")-}--// ListResources handle list role resources-func (h *Handler) ListResources(c *gin.Context) {- ctx := c.Request.Context()- resources, err := h.service.ListResources(ctx)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "Role not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, resources, "")-}--// ListRolesWithPermission handle list roles with permission-func (h *Handler) ListRolesWithPermission(c *gin.Context) {- ctx := c.Request.Context()- roles, err := h.service.ListRolesWithPermission(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, roles, "")-}--func (h *Handler) ShowRoleDefaultModels(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- ctx := c.Request.Context()- result, err := h.service.ShowRoleDefaultModels(ctx, roleName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "Role default model set successfully")-}--type SetRoleDefaultModelRequest struct {- ModelID string `json:"model_id"`- ModelType string `json:"model_type" binding:"required"`-}--func (h *Handler) SetRoleDefaultModel(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- var request SetRoleDefaultModelRequest- if err := c.ShouldBindJSON(&request); err != nil {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())- }-- ctx := c.Request.Context()- result, err := h.service.SetRoleDefaultModel(ctx, roleName, request.ModelID, request.ModelType)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "Role default model set successfully")-}--type ResetRoleDefaultModelRequest struct {- ModelType string `json:"model_type" binding:"required"`-}--func (h *Handler) ResetRoleDefaultModel(c *gin.Context) {- roleName := c.Param("role_name")- if roleName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }-- var request ResetRoleDefaultModelRequest- if err := c.ShouldBindJSON(&request); err != nil {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())- return- }-- ctx := c.Request.Context()- result, err := h.service.ResetRoleDefaultModel(ctx, roleName, request.ModelType)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "Role default model set successfully")-}--func (h *Handler) ListModelProviders(c *gin.Context) {-- keywords := ""- if queryKeywords := c.Query("available"); queryKeywords != "" {- keywords = queryKeywords- }-- // convert keywords to small case- keywords = strings.ToLower(keywords)-- ctx := c.Request.Context()- result, err := h.service.ListModelProviders(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "List model providers successfully")-}--type AddProviderRequest struct {- ProviderName string `json:"provider_name" binding:"required"`-}--func (h *Handler) AddModelProvider(c *gin.Context) {- var req AddProviderRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ResponseWithCodeData(c, common.CodeBadRequest, false, err.Error())- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.AddModelProvider(ctx, req.ProviderName, userID)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model provider added successfully")-}--func (h *Handler) ShowProvider(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- provider, err := dao.GetModelProviderManager().GetProviderByName(providerName)- if err != nil {- common.ErrorWithCode(c, common.CodeNotFound, err.Error())- return- }- common.SuccessWithData(c, provider, "success")-}--type DeleteProviderRequest struct {- ProviderNames []string `json:"provider_names" binding:"required"`-}--func (h *Handler) DeleteModelProvider(c *gin.Context) {- var req DeleteProviderRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.DeleteModelProviders(ctx, userID, req.ProviderNames)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model provider deleted successfully")-}--func (h *Handler) ListModels(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }- models, err := dao.GetModelProviderManager().ListModels(providerName)- if err != nil {- common.ErrorWithCode(c, common.CodeNotFound, err.Error())- return- }-- common.SuccessWithData(c, models, "success")-}--func (h *Handler) ShowProviderModel(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }- modelName := c.Param("model_name")- if modelName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Model name is required")- return- }- model, err := dao.GetModelProviderManager().GetModelByName(providerName, modelName)- if err != nil {- common.ErrorWithCode(c, common.CodeNotFound, err.Error())- return- }- common.SuccessWithData(c, model, "success")-}--func (h *Handler) ListModelInstances(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.ListModelInstances(ctx, userID, providerName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instances listed successfully")-}--func (h *Handler) ShowProviderInstance(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.ShowProviderInstance(ctx, userID, providerName, instanceName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instance shown successfully")-}--func (h *Handler) ShowProviderInstanceBalance(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.ShowProviderInstanceBalance(ctx, userID, providerName, instanceName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instance balance shown successfully")-}--func (h *Handler) CheckInstanceConnection(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.CheckInstanceConnection(ctx, userID, providerName, instanceName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instance connection checked successfully")-}--type CheckConnectionRequest struct {- APIKey string `json:"api_key"`- Region string `json:"region"`- BaseURL string `json:"base_url"`-}--func (h *Handler) CheckProviderConnection(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- var req CheckConnectionRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, err.Error())- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.CheckProviderConnection(ctx, userID, providerName, req.Region, req.APIKey, req.BaseURL)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instance connection checked successfully")-}--type AlterProviderInstanceRequest struct {- InstanceName string `json:"instance_name"`- APIKey string `json:"api_key"`-}--func (h *Handler) AlterProviderInstance(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }-- var req AlterProviderInstanceRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- userID := c.GetString("user_id")- if userID == "" {- common.ErrorWithCode(c, common.CodeUnauthorized, "Unauthorized")- return- }- ctx := c.Request.Context()- result, err := h.service.AlterProviderInstance(ctx, userID, providerName, instanceName, req.InstanceName, req.APIKey)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instance altered successfully")-}--type AddModelInstanceRequest struct {- InstanceName string `json:"instance_name" binding:"required"`-}--func (h *Handler) AddModelInstance(c *gin.Context) {- var req AddModelInstanceRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ResponseWithCodeData(c, common.CodeBadRequest, false, err.Error())- return- }-- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.AddModelInstance(ctx, userID, providerName, req.InstanceName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model instance added successfully")-}--type DropModelInstanceRequest struct {- InstanceNames []string `json:"instance_names" binding:"required"`-}--func (h *Handler) DeleteModelInstance(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- var req DropModelInstanceRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.DeleteModelInstances(ctx, userID, providerName, req.InstanceNames)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model provider added successfully")-}--func (h *Handler) ListInstanceModels(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.ListInstanceModels(ctx, userID, providerName, instanceName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Models listed successfully")-}--type EnableOrDisableModelRequest struct {- ModelID string `json:"model_id"`- Status string `json:"status"`-}--func (h *Handler) EnableOrDisableModel(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }-- var req EnableOrDisableModelRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- modelID := strings.TrimSpace(req.ModelID)- modelName := strings.TrimPrefix(c.Param("model_name"), "/")- modelName = strings.TrimSpace(modelName)- if modelName == "" && modelID == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "model_name or model_id is required")- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.EnableOrDisableModel(ctx, userID, providerName, instanceName, modelName, modelID, req.Status)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Models listed successfully")-}--type AddModelsRequest struct {- ModelNames []string `json:"model_names" binding:"required"`-}--func (h *Handler) AddModels(c *gin.Context) {- var req AddModelsRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ResponseWithCodeData(c, common.CodeBadRequest, false, err.Error())- return- }-- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.AddModels(ctx, userID, providerName, instanceName, req.ModelNames)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Models added successfully")-}--type DropModelsRequest struct {- ModelNames []string `json:"model_names" binding:"required"`-}--func (h *Handler) DeleteModels(c *gin.Context) {- providerName := c.Param("provider_name")- if providerName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Provider name is required")- return- }-- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Instance name is required")- return- }-- var req DropModelsRequest- if err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- userID := c.GetString("user_id")- ctx := c.Request.Context()- result, err := h.service.DeleteModels(ctx, userID, providerName, instanceName, req.ModelNames)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Model deleted successfully")-}--// GetSystemFingerprint handle get system fingerprint-func (h *Handler) GetSystemFingerprint(c *gin.Context) {- ctx := c.Request.Context()- fingerprint, err := h.service.GetSystemFingerprint(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, fingerprint, "")-}--type SetSystemLicenseRequest struct {- License string `json:"license" binding:"required"`-}--// SetSystemLicense to set system license-func (h *Handler) SetSystemLicense(c *gin.Context) {- var req SetSystemLicenseRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()-- result, err := h.service.SetSystemLicense(ctx, req.License)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "System license set successfully")-}--// ShowSystemLicense to get system license-func (h *Handler) ShowSystemLicense(c *gin.Context) {- check, ok := c.GetQuery("check")- if !ok {- check = "false"- }- checkFlag, err := strconv.ParseBool(check)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()-- var result map[string]interface{}- if checkFlag {- result, err = h.service.CheckSystemLicense(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- } else {- var license string- license, ok = c.GetQuery("license")- if !ok {- // Show license- result, err = h.service.ShowSystemLicense(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- }- // Verify license- result, err = h.service.VerifyLicense(ctx, license)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- }- common.SuccessWithData(c, result, "success")-}--type SetSystemLicenseConfigRequest struct {- TimeRecordSaveInterval int64 `json:"value1" binding:"required"`- TimeRecordTaskDuration int64 `json:"value2" binding:"required"`-}--func (h *Handler) UpdateSystemLicenseConfig(c *gin.Context) {- var req SetSystemLicenseConfigRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()- result, err := h.service.UpdateSystemLicenseConfig(ctx, req.TimeRecordSaveInterval, req.TimeRecordTaskDuration)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "System license config updated successfully")-}--type SetSoftFingerprintRequest struct {- SoftFingerprint string `json:"fingerprint" binding:"required"`-}--func (h *Handler) SetSoftFingerprint(c *gin.Context) {- var req SetSoftFingerprintRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()-- err := h.service.SetSoftFingerprint(ctx, req.SoftFingerprint)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessNoData(c, "SUCCESS")-}--func (h *Handler) ShowSoftFingerprint(c *gin.Context) {- ctx := c.Request.Context()-- softFingerprint, err := h.service.GetSoftFingerprint(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, softFingerprint, "")-}--func (h *Handler) DeleteSoftFingerprint(c *gin.Context) {- ctx := c.Request.Context()-- err := h.service.DeleteSoftFingerprint(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessNoData(c, "SUCCESS")-}--type ShowUserActivityRequest struct {- Days int `json:"days"`- Email string `json:"email"`-}--// ShowUserActivity handle show user activity-func (h *Handler) ShowUserActivity(c *gin.Context) {- var req ShowUserActivityRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()-- userActivity, err := h.service.ShowUserActivity(ctx, req.Email, req.Days)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, userActivity, "")-}--type ShowUserDatasetSummaryRequest struct {- Dataset string `json:"dataset"`-}--// ShowUserDatasetSummary handle show user dataset summary-func (h *Handler) ShowUserDatasetSummary(c *gin.Context) {- var req ShowUserDatasetSummaryRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- userDatasetSummary, err := h.service.ShowUserDatasetSummary(ctx, username, req.Dataset)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, userDatasetSummary, "")-}--// ShowUserSummary handle show user summary-func (h *Handler) ShowUserSummary(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- userSummary, err := h.service.ShowUserSummary(ctx, username)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, userSummary, "")-}--// ShowUserStorage handle show user storage-func (h *Handler) ShowUserStorage(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- userStorage, err := h.service.ShowUserStorage(ctx, username)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, userStorage, "")-}--// ShowUserQuota handle show user quota-func (h *Handler) ShowUserQuota(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- userQuota, err := h.service.ShowUserQuota(ctx, username)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, userQuota, "")-}--// ShowUserIndex handle show user index-func (h *Handler) ShowUserIndex(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- userIndex, err := h.service.ShowUserIndex(ctx, username)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, userIndex, "")-}--// UpdateUserRoleHTTPRequest update user role request-type UpdateUserRoleHTTPRequest struct {- RoleName string `json:"role_name" binding:"required"`-}--// UpdateUserRole handle update user role-func (h *Handler) UpdateUserRole(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- var req UpdateUserRoleHTTPRequest- if err = c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Role name is required")- return- }- ctx := c.Request.Context()-- result, err := h.service.UpdateUserRole(ctx, username, req.RoleName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "")-}--// ShowUserPermission handle show user permission-func (h *Handler) ShowUserPermission(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- permissions, err := h.service.ShowUserPermission(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, permissions, "")-}--// ListUserDatasets requires the enterprise edition.-func (h *Handler) ListUserDatasets(c *gin.Context) {- common.ResponseWithHttpCodeData(c, http.StatusNotImplemented, common.CodeNotImplemented, nil, "listing user datasets is only available in the enterprise edition")-}--// ListUserAgents requires the enterprise edition.-func (h *Handler) ListUserAgents(c *gin.Context) {- common.ResponseWithHttpCodeData(c, http.StatusNotImplemented, common.CodeNotImplemented, nil, "listing user agents is only available in the enterprise edition")-}--// ListUserChats handle show user chats-func (h *Handler) ListUserChats(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- chats, err := h.service.ListUserChats(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, chats, "")-}--// ListUserSearches handle show user searches-func (h *Handler) ListUserSearches(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- searches, err := h.service.ListUserSearches(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, searches, "")-}--// ListUserModels handle show user models-func (h *Handler) ListUserModels(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- models, err := h.service.ListUserModels(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, models, "")-}--// ListUserFiles handle show user files-func (h *Handler) ListUserFiles(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- files, err := h.service.ListUserFiles(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, files, "")-}--// ListUserProviders handle show user providers-func (h *Handler) ListUserProviders(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- providers, err := h.service.ListUserProviders(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, providers, "")-}--// ListUserProviderInstances handle show user provider instances-func (h *Handler) ListUserProviderInstances(c *gin.Context) {- userName, err := getUserName(c)- if err != nil {- return- }-- providerName := c.Param("provider_name")- if providerName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Provider name is required")- return- }- ctx := c.Request.Context()-- instances, err := h.service.ListUserProviderInstances(ctx, userName, providerName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, instances, "")-}--// ListUserProviderInstanceModels handle show user provider instance models-func (h *Handler) ListUserProviderInstanceModels(c *gin.Context) {- userName, err := getUserName(c)- if err != nil {- return- }-- providerName := c.Param("provider_name")- if providerName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Provider name is required")- return- }-- instanceName := c.Param("instance_name")- if instanceName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Instance name is required")- return- }- ctx := c.Request.Context()-- models, err := h.service.ListUserProviderInstanceModels(ctx, userName, providerName, instanceName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, models, "")-}--// ListUserDefaultModels handle show user default models-func (h *Handler) ListUserDefaultModels(c *gin.Context) {- userName, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()-- models, err := h.service.ListUserDefaultModels(ctx, userName)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, models, "")-}--// ShowUsersSummary handle show users summary-func (h *Handler) ShowUsersSummary(c *gin.Context) {- ctx := c.Request.Context()-- usersSummary, err := h.service.ShowUsersSummary(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersSummary, "")-}--type ShowUsersActivityRequest struct {- Days *int `json:"days"`- Window *int `json:"window"`-}--// ShowUsersActivity handle show users activity-func (h *Handler) ShowUsersActivity(c *gin.Context) {- var req ShowUsersActivityRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()-- usersActivity, err := h.service.ShowUsersActivity(ctx, req.Days, req.Window)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersActivity, "")-}--type ListUsersReportsRequest struct {- Status *string `json:"status"`- Days *int `json:"days"`- Plan *string `json:"plan"`-}--// ListUsersReports handle show users reports-func (h *Handler) ListUsersReports(c *gin.Context) {- var req ListUsersReportsRequest- if err := c.ShouldBindJSON(&req); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- var err error- pageIndex := 0- pageIndexStr := c.Param("page")- if pageIndexStr != "" {- pageIndex, err = strconv.Atoi(pageIndexStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page index must be an integer")- return- }- }- pageSize := 10- pageSizeStr := c.Param("page_size")- if pageSizeStr != "" {- pageSize, err = strconv.Atoi(pageSizeStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page size must be an integer")- return- }- }- ctx := c.Request.Context()-- usersReports, err := h.service.ListUsersReports(ctx, pageIndex, pageSize, req.Status, req.Plan, req.Days)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersReports, "")-}--// ListUsersStorage handle show users storage-func (h *Handler) ListUsersStorage(c *gin.Context) {-- var err error- pageIndex := 0- pageIndexStr := c.Param("page")- if pageIndexStr != "" {- pageIndex, err = strconv.Atoi(pageIndexStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page index must be an integer")- return- }- }- pageSize := 10- pageSizeStr := c.Param("page_size")- if pageSizeStr != "" {- pageSize, err = strconv.Atoi(pageSizeStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page size must be an integer")- return- }- }- top := 10- topStr := c.Param("top")- if topStr != "" {- top, err = strconv.Atoi(topStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")- }- }- ctx := c.Request.Context()-- usersStorage, err := h.service.ListUsersStorage(ctx, pageIndex, pageSize, top)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersStorage, "")-}--// ListUsersDocuments handle show users documents-func (h *Handler) ListUsersDocuments(c *gin.Context) {-- var err error- pageIndex := 0- pageIndexStr := c.Param("page")- if pageIndexStr != "" {- pageIndex, err = strconv.Atoi(pageIndexStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page index must be an integer")- return- }- }- pageSize := 10- pageSizeStr := c.Param("page_size")- if pageSizeStr != "" {- pageSize, err = strconv.Atoi(pageSizeStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page size must be an integer")- return- }- }- top := 10- topStr := c.Param("top")- if topStr != "" {- top, err = strconv.Atoi(topStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")- }- }- ctx := c.Request.Context()-- usersDocuments, err := h.service.ListUsersDocuments(ctx, pageIndex, pageSize, top)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersDocuments, "")-}--// ListUsersIndex handle show users index-func (h *Handler) ListUsersIndex(c *gin.Context) {-- var err error- pageIndex := 0- pageIndexStr := c.Param("page")- if pageIndexStr != "" {- pageIndex, err = strconv.Atoi(pageIndexStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page index must be an integer")- return- }- }- pageSize := 10- pageSizeStr := c.Param("page_size")- if pageSizeStr != "" {- pageSize, err = strconv.Atoi(pageSizeStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page size must be an integer")- return- }- }- top := 10- topStr := c.Param("top")- if topStr != "" {- top, err = strconv.Atoi(topStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")- }- }- ctx := c.Request.Context()-- usersIndex, err := h.service.ListUsersIndex(ctx, pageIndex, pageSize, top)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersIndex, "")-}--type ListUsersQuotaRequest struct {- QuotaThreshold *int `json:"quota_threshold"`- Plan *string `json:"plan"`- Days *int `json:"days"`-}--// ListUsersQuota handle show users quota-func (h *Handler) ListUsersQuota(c *gin.Context) {- var request ListUsersQuotaRequest- if err := c.ShouldBindJSON(&request); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }-- var err error- pageIndex := 0- pageIndexStr := c.Param("page")- if pageIndexStr != "" {- pageIndex, err = strconv.Atoi(pageIndexStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page index must be an integer")- return- }- }- pageSize := 10- pageSizeStr := c.Param("page_size")- if pageSizeStr != "" {- pageSize, err = strconv.Atoi(pageSizeStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Page size must be an integer")- return- }- }- top := 10- topStr := c.Param("top")- if topStr != "" {- top, err = strconv.Atoi(topStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")- }- }- ctx := c.Request.Context()-- usersQuota, err := h.service.ListUsersQuota(ctx, pageIndex, pageSize, top, request.QuotaThreshold, request.Plan, request.Days)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersQuota, "")-}--// ShowUsersPlanSummary handle show users plan summary-func (h *Handler) ShowUsersPlanSummary(c *gin.Context) {- ctx := c.Request.Context()- usersPlanSummary, err := h.service.ShowUsersPlanSummary(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersPlanSummary, "")-}--// ShowUsersPlan handle show users plan-func (h *Handler) ShowUsersPlan(c *gin.Context) {- var quota int- quotaStr := c.Query("quota")- if quotaStr != "" {- var err error- quota, err = strconv.Atoi(quotaStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Quota must be an integer")- return- }- }- ctx := c.Request.Context()- usersPlanQuota, err := h.service.ShowUsersPlanQuota(ctx, quota)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersPlanQuota, "")-}--// ShowUsersQuotaSummary handle show users quota summary-func (h *Handler) ShowUsersQuotaSummary(c *gin.Context) {- ctx := c.Request.Context()- usersQuotaSummary, err := h.service.ShowUsersQuotaSummary(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, usersQuotaSummary, "")-}--// ShowIngestionTasksSummary handle show ingestion tasks summary-func (h *Handler) ShowIngestionTasksSummary(c *gin.Context) {- ctx := c.Request.Context()- ingestionTasksSummary, err := h.service.ShowIngestionTasksSummary(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, ingestionTasksSummary, "")-}--// ListIngestionTasks requires the enterprise edition.-func (h *Handler) ListIngestionTasks(c *gin.Context) {- tasks, err := h.service.ListIngestionTasks(c.Request.Context())- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, tasks, "")-}--// RemoveIngestionTasks requires the enterprise edition.-func (h *Handler) RemoveIngestionTasks(c *gin.Context) {- result, err := h.service.RemoveIngestionTasks(c.Request.Context())- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "")-}--// StopIngestionTasks requires the enterprise edition.-func (h *Handler) StopIngestionTasks(c *gin.Context) {- result, err := h.service.StopIngestionTasks(c.Request.Context())- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }- common.SuccessWithData(c, result, "")-}--// ShowDataSummary handle show data summary-func (h *Handler) ShowDataSummary(c *gin.Context) {- ctx := c.Request.Context()- dataSummary, err := h.service.ShowDataSummary(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, dataSummary, "")-}--// ShowDataOrphan handle show data orphan-func (h *Handler) ShowDataOrphan(c *gin.Context) {- ctx := c.Request.Context()- dataOrphan, err := h.service.ShowDataOrphan(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, dataOrphan, "")-}--// ShowDataStorage handle show data storage-func (h *Handler) ShowDataStorage(c *gin.Context) {- ctx := c.Request.Context()- dataStorage, err := h.service.ShowDataStorage(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, dataStorage, "")-}--// ShowDataIndex handle show data index-func (h *Handler) ShowDataIndex(c *gin.Context) {- ctx := c.Request.Context()- dataIndex, err := h.service.ShowDataIndex(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, dataIndex, "")-}--type PurgeOrphanDataRequest struct {- Preview bool `json:"preview"`-}--// PurgeOrphanData handle purge orphan data-func (h *Handler) PurgeOrphanData(c *gin.Context) {- var request PurgeOrphanDataRequest- if err := c.ShouldBindJSON(&request); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()- result, err := h.service.PurgeOrphanData(ctx, request.Preview)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Orphan data purged successfully")-}--type PurgeUserDataRequest struct {- Preview bool `json:"preview"`-}--// PurgeUserData handle purge user data-func (h *Handler) PurgeUserData(c *gin.Context) {- var request PurgeUserDataRequest- if err := c.ShouldBindJSON(&request); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- username, err := getUserName(c)- if err != nil {- return- }- ctx := c.Request.Context()- result, err := h.service.PurgeUserData(ctx, username, request.Preview)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "")-}--type PurgeUsersDataRequest struct {- Preview bool `json:"preview"`- Days int `json:"days"`- Plan *string `json:"plan"`- UserStatus *string `json:"user_status"`-}--// PurgeUsersData handle purge users data-func (h *Handler) PurgeUsersData(c *gin.Context) {- var request PurgeUsersDataRequest- if err := c.ShouldBindJSON(&request); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- ctx := c.Request.Context()- result, err := h.service.PurgeUsersData(ctx, request.Preview, request.Days, request.Plan, request.UserStatus)- if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- common.ErrorWithCode(c, common.CodeNotFound, "User not found")- return- }- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "")-}--// GenerateUserAPIKey handle create tenant API key-func (h *Handler) GenerateUserAPIKey(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- apiKey, err := h.service.GenerateUserAPIKey(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, apiKey, "API key generated successfully")-}--// DeleteUserAPIKey handle delete user API key-func (h *Handler) DeleteUserAPIKey(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }- key := c.Param("key")- if key == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Username and key are required")- return- }-- ctx := c.Request.Context()-- result, err := h.service.DeleteUserAPIKey(ctx, username, key)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "API key deleted successfully")-}--// ListUserAPIKeys handle list user API keys-func (h *Handler) ListUserAPIKeys(c *gin.Context) {- username, err := getUserName(c)- if err != nil {- return- }-- ctx := c.Request.Context()-- result, err := h.service.ListUserAPIKeys(ctx, username)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "API keys listed successfully")-}--// DownloadSensitiveWords handle download sensitive words-func (h *Handler) DownloadSensitiveWords(c *gin.Context) {- ctx := c.Request.Context()- result, err := h.service.DownloadSensitiveWords(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Sensitive words downloaded successfully")-}--// UploadSensitiveWords handle upload sensitive words-func (h *Handler) UploadSensitiveWords(c *gin.Context) {- form, err := c.MultipartForm()- if err != nil || form == nil || len(form.File["file"]) == 0 {- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "No file part!")- return- }- files := form.File["file"]- for _, fh := range files {- if fh == nil || fh.Filename == "" {- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "No file or filename is empty")- return- }- }- if len(files) != 1 {- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Only one file is allowed")- return- }- file := files[0]- ctx := c.Request.Context()- result, err := h.service.UploadSensitiveWords(ctx, file)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Sensitive words uploaded successfully")-}--type BindVerificationEmailRequest struct {- Email string `json:"email"`- Host string `json:"host"`- Port int `json:"port"`- Username string `json:"username"`- Password string `json:"password"`- UseTLS bool `json:"use_tls"`- UseSSL bool `json:"use_ssl"`-}--// BindVerificationEmail handle bind verification email-func (h *Handler) BindVerificationEmail(c *gin.Context) {- var request BindVerificationEmailRequest- if err := c.ShouldBindJSON(&request); err != nil {- println("JSON bind error: %v (type: %T)", err, err)- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- if request.Email == "" || request.Host == "" || request.Username == "" || request.Password == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Email, host, username, and password are required")- return- }- ctx := c.Request.Context()-- result, err := h.service.BindVerificationEmail(ctx, request.Email, request.Host, request.Port, request.Username, request.Password, request.UseTLS, request.UseSSL)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Verification email bound successfully")-}--// ShowVerificationEmail handle show verification email-func (h *Handler) ShowVerificationEmail(c *gin.Context) {- ctx := c.Request.Context()- result, err := h.service.ShowVerificationEmail(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Verification email shown successfully")-}--// ShowWhiteList handle show white list-func (h *Handler) ShowWhiteList(c *gin.Context) {- ctx := c.Request.Context()- result, err := h.service.ShowWhiteList(ctx)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "White list shown successfully")-}--type AddWhiteListRequest struct {- Email string `json:"email"`-}--// AddWhiteList handle add white list-func (h *Handler) AddWhiteList(c *gin.Context) {- var request AddWhiteListRequest- if err := c.ShouldBindJSON(&request); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- if request.Email == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Email is required")- return- }- ctx := c.Request.Context()-- result, err := h.service.AddWhiteList(ctx, request.Email)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "White list added successfully")-}--// BatchAddWhiteList handle batch add white list-func (h *Handler) BatchAddWhiteList(c *gin.Context) {- form, err := c.MultipartForm()- if err != nil || form == nil || len(form.File["file"]) == 0 {- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "No file part!")- return- }- files := form.File["file"]- for _, fh := range files {- if fh == nil || fh.Filename == "" {- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "No file or filename is empty")- return- }- }- if len(files) != 1 {- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Only one file is allowed")- return- }- ctx := c.Request.Context()- file := files[0]- result, err := h.service.BatchAddWhiteList(ctx, file)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Batch add white list successfully")-}--// UpdateWhiteList handle update white list-func (h *Handler) UpdateWhiteList(c *gin.Context) {- id := c.Param("id")-- var request AddWhiteListRequest- if err := c.ShouldBindJSON(&request); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- if request.Email == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Email is required")- return- }- ctx := c.Request.Context()-- result, err := h.service.UpdateWhiteList(ctx, id, request.Email)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "White list updated successfully")-}--// DeleteWhiteList handle delete white list-func (h *Handler) DeleteWhiteList(c *gin.Context) {- idStr := c.Param("id")- id, err := strconv.Atoi(idStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Invalid id")- return- }- ctx := c.Request.Context()-- result, err := h.service.DeleteWhiteList(ctx, id)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "White list updated successfully")-}--type BatchDeleteWhiteListRequest struct {- Ids []int `json:"ids"`-}--// BatchDeleteWhiteList handle batch delete white list-func (h *Handler) BatchDeleteWhiteList(c *gin.Context) {- var request BatchDeleteWhiteListRequest- if err := c.ShouldBindJSON(&request); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())- return- }- if len(request.Ids) == 0 {- common.ErrorWithCode(c, common.CodeBadRequest, "Ids are required")- return- }- ctx := c.Request.Context()-- result, err := h.service.BatchDeleteWhiteList(ctx, request.Ids)- if err != nil {- common.ErrorWithCode(c, common.CodeServerError, err.Error())- return- }-- common.SuccessWithData(c, result, "Batch delete white list successfully")-}--// GetTokenStats returns API token statistics for the current user's tenant.-func (h *Handler) GetTokenStats(c *gin.Context) {-- userName := c.Query("user_name")- if userName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "User name is required")- return- }-- now := time.Now()- fromDate := c.DefaultQuery("from", now.AddDate(0, 0, -7).Format("2006-01-02 00:00:00"))- toDate := c.DefaultQuery("to", now.Format("2006-01-02 15:04:05"))- if len(toDate) == 10 {- toDate += " 23:59:59"- }-- granularity := c.Query("granularity")- if granularity == "" {- granularity = "hour"- }- granularity = strings.ToLower(granularity)-- ctx := c.Request.Context()-- stats, err := h.service.GetTokenStats(ctx, userName, fromDate, toDate, granularity)- if err != nil {- common.ErrorWithCode(c, common.CodeDataError, err.Error())- return- }-- common.SuccessWithData(c, stats, "success")-}--// GetTokenUsersStats returns API token statistics summary for the current user's tenant.-func (h *Handler) GetTokenUsersStats(c *gin.Context) {- now := time.Now()- fromDate := c.DefaultQuery("from", now.AddDate(0, 0, -7).Format("2006-01-02 00:00:00"))- toDate := c.DefaultQuery("to", now.Format("2006-01-02 15:04:05"))- if len(toDate) == 10 {- toDate += " 23:59:59"- }-- topStr := c.Query("top")- top, err := strconv.Atoi(topStr)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Invalid top")- return- }- ctx := c.Request.Context()-- stats, err := h.service.GetTokenUsersStats(ctx, fromDate, toDate, top)- if err != nil {- common.ErrorWithCode(c, common.CodeDataError, err.Error())- return- }-- common.SuccessWithData(c, stats, "success")-}--// GetTokenStatsSummary returns API token statistics summary for the current user's tenant.-func (h *Handler) GetTokenStatsSummary(c *gin.Context) {- now := time.Now()- fromDate := c.DefaultQuery("from", now.AddDate(0, 0, -7).Format("2006-01-02 00:00:00"))- toDate := c.DefaultQuery("to", now.Format("2006-01-02 15:04:05"))- if len(toDate) == 10 {- toDate += " 23:59:59"- }- ctx := c.Request.Context()-- stats, err := h.service.GetTokenStatsSummary(ctx, fromDate, toDate)- if err != nil {- common.ErrorWithCode(c, common.CodeDataError, err.Error())- return- }-- common.SuccessWithData(c, stats, "success")-}--func (h *Handler) ListLogs(c *gin.Context) {- userName := c.Query("user_name")- if userName == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "User name is required")- return- }- days := c.Query("days")- if days == "" {- days = "7"- }- daysInt, err := strconv.Atoi(days)- if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Invalid days")- return- }- ctx := c.Request.Context()-- stats, err := h.service.ListLogs(ctx, userName, daysInt)- if err != nil {- common.ErrorWithCode(c, common.CodeDataError, err.Error())- return- }-- common.SuccessWithData(c, stats, "success")-}diff --git a/internal/admin/router_ee.go b/internal/admin/router_ee.godeleted file mode 100644index ab0388ad5a..0000000000--- a/internal/admin/router_ee.go+++ /dev/null@@ -1,152 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package admin--import (- "github.com/gin-gonic/gin"-)--func SetupEERouter(engine *gin.Engine) {-}--func RegisterEERouter(protected *gin.RouterGroup, r *Router) {- // Role management- protected.GET("/roles", r.handler.ListRoles)- protected.POST("/roles", r.handler.CreateRole)- protected.GET("/roles/:role_name", r.handler.ShowRole)- protected.PUT("/roles/:role_name", r.handler.UpdateRole)- protected.DELETE("/roles/:role_name", r.handler.DropRole)- protected.GET("/roles/:role_name/permission", r.handler.ShowRolePermission)- protected.POST("/roles/:role_name/permission", r.handler.GrantRolePermission)- protected.DELETE("/roles/:role_name/permission", r.handler.RevokeRolePermission)- protected.GET("/roles/resource", r.handler.ListResources)- protected.GET("/roles/permission", r.handler.ListRolesWithPermission)- protected.GET("/roles/:role_name/default-models", r.handler.ShowRoleDefaultModels)- protected.PATCH("/roles/:role_name/default-models", r.handler.SetRoleDefaultModel)- protected.DELETE("/roles/:role_name/default-models", r.handler.ResetRoleDefaultModel)-- // Providers and models- provider := protected.Group("/providers")- {- provider.GET("/", r.handler.ListModelProviders)- provider.POST("/", r.handler.AddModelProvider)- provider.GET("/:provider_name", r.handler.ShowProvider)- provider.DELETE("/", r.handler.DeleteModelProvider)- provider.GET("/:provider_name/models", r.handler.ListModels)- provider.GET("/:provider_name/models/:model_name", r.handler.ShowProviderModel)-- provider.POST("/:provider_name/instances", r.handler.AddModelInstance)- provider.GET("/:provider_name/instances", r.handler.ListModelInstances)- provider.DELETE("/:provider_name/instances", r.handler.DeleteModelInstance)- provider.GET("/:provider_name/instances/:instance_name", r.handler.ShowProviderInstance)- provider.GET("/:provider_name/instances/:instance_name/balance", r.handler.ShowProviderInstanceBalance)- provider.GET("/:provider_name/instances/:instance_name/connection", r.handler.CheckInstanceConnection)- provider.POST("/:provider_name/connection", r.handler.CheckProviderConnection)- provider.PUT("/:provider_name/instances/:instance_name", r.handler.AlterProviderInstance)-- provider.GET("/:provider_name/instances/:instance_name/models", r.handler.ListInstanceModels)- provider.PATCH("/:provider_name/instances/:instance_name/models/*model_name", r.handler.EnableOrDisableModel)- provider.POST("/:provider_name/instances/:instance_name/models", r.handler.AddModels)- provider.DELETE("/:provider_name/instances/:instance_name/models", r.handler.DeleteModels)- }-- // License- protected.GET("/system/fingerprint", r.handler.GetSystemFingerprint)- protected.POST("/system/license", r.handler.SetSystemLicense)- protected.GET("/system/license", r.handler.ShowSystemLicense)- protected.PUT("/system/license/config", r.handler.UpdateSystemLicenseConfig)-- protected.POST("/system/soft-fingerprint", r.handler.SetSoftFingerprint)- protected.GET("/system/soft-fingerprint", r.handler.ShowSoftFingerprint)- protected.DELETE("/system/soft-fingerprint", r.handler.DeleteSoftFingerprint)-- // Token statistics- protected.GET("/stats/token", r.handler.GetTokenStats)- protected.GET("/stats/token/users", r.handler.GetTokenUsersStats)- protected.GET("/stats/token/summary", r.handler.GetTokenStatsSummary)-- // Logs- protected.GET("/logs", r.handler.ListLogs)-- // Stats data info- protected.GET("/users/:username/activity", r.handler.ShowUserActivity)- protected.GET("/users/:username/dataset", r.handler.ShowUserDatasetSummary)- protected.GET("/users/:username/summary", r.handler.ShowUserSummary)- protected.GET("/users/:username/storage", r.handler.ShowUserStorage)- protected.GET("/users/:username/quota", r.handler.ShowUserQuota)- protected.GET("/users/:username/index", r.handler.ShowUserIndex)- protected.PUT("/users/:username/role", r.handler.UpdateUserRole)- protected.GET("/users/:username/permission", r.handler.ShowUserPermission)- protected.GET("/users/:username/datasets", r.handler.ListUserDatasets)- protected.GET("/users/:username/agents", r.handler.ListUserAgents)- protected.GET("/users/:username/chats", r.handler.ListUserChats)- protected.GET("/users/:username/searches", r.handler.ListUserSearches)- protected.GET("/users/:username/models", r.handler.ListUserModels)- protected.GET("/users/:username/files", r.handler.ListUserFiles)- protected.GET("/users/:username/providers", r.handler.ListUserProviders)- protected.GET("/users/:username/providers/:provider_name/instances", r.handler.ListUserProviderInstances)- protected.GET("/users/:username/providers/:provider_name/instances/:instance_name/models", r.handler.ListUserProviderInstanceModels)- protected.GET("/users/:username/default-models", r.handler.ListUserDefaultModels)- protected.GET("/users/summary", r.handler.ShowUsersSummary)- protected.GET("/users/activity", r.handler.ShowUsersActivity)- protected.GET("/users/reports", r.handler.ListUsersReports)- protected.GET("/users/storage", r.handler.ListUsersStorage)- protected.GET("/users/documents", r.handler.ListUsersDocuments)- protected.GET("/users/index", r.handler.ListUsersIndex)- protected.GET("/users/quota", r.handler.ListUsersQuota)- protected.GET("/users/plan/summary", r.handler.ShowUsersPlanSummary)- protected.GET("/users/plan", r.handler.ShowUsersPlan)- protected.GET("/users/quota/summary", r.handler.ShowUsersQuotaSummary)- protected.DELETE("/ingestion/tasks", r.handler.RemoveIngestionTasks)- protected.PUT("/ingestion/tasks", r.handler.StopIngestionTasks)- protected.GET("/ingestion/tasks", r.handler.ListIngestionTasks)- protected.GET("/ingestion/tasks/summary", r.handler.ShowIngestionTasksSummary)- protected.GET("/data/summary", r.handler.ShowDataSummary)- protected.GET("/data/orphan", r.handler.ShowDataOrphan)- protected.GET("/data/storage", r.handler.ShowDataStorage)- protected.GET("/data/index", r.handler.ShowDataIndex)- protected.DELETE("/data/orphan", r.handler.PurgeOrphanData)- protected.DELETE("/users/:username/data", r.handler.PurgeUserData)- protected.DELETE("/users/data", r.handler.PurgeUsersData)-- // API Keys- protected.POST("/users/:username/keys", r.handler.GenerateUserAPIKey)- protected.DELETE("/users/:username/keys/:key", r.handler.DeleteUserAPIKey)- protected.GET("/users/:username/keys", r.handler.ListUserAPIKeys)-- protected.GET("/users/:username/tokens", r.handler.ListUserAPITokens)- //protected.POST("/users/:username/keys", r.handler.GenerateUserAPIToken)- protected.POST("/users/:username/tokens", r.handler.GenerateUserAPIToken)- protected.DELETE("/users/:username/tokens/:token", r.handler.DeleteUserAPIToken)-- // Sensitive words, EE- protected.GET("/sensitive-words", r.handler.DownloadSensitiveWords)- protected.POST("/sensitive-words", r.handler.UploadSensitiveWords)-- // Verification email, EE- protected.POST("/email/verification", r.handler.BindVerificationEmail)- protected.GET("/email/verification", r.handler.ShowVerificationEmail)-- // White list, EE- protected.GET("/white-list", r.handler.ShowWhiteList)- protected.POST("/white-list", r.handler.AddWhiteList)- protected.POST("/white-list/batch", r.handler.BatchAddWhiteList)- protected.PUT("/white-list/:id", r.handler.UpdateWhiteList)- protected.DELETE("/white-list/:id", r.handler.DeleteWhiteList)- protected.DELETE("/white-list/batch", r.handler.BatchDeleteWhiteList)--}diff --git a/internal/admin/service_ee.go b/internal/admin/service_ee.godeleted file mode 100644index 7846981b1c..0000000000--- a/internal/admin/service_ee.go+++ /dev/null@@ -1,1331 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package admin--import (- "context"- "errors"- "fmt"- "mime/multipart"- "ragflow/internal/server"-- "ragflow/internal/common"- "ragflow/internal/dao"- "ragflow/internal/entity"-)--func CheckServicePeriodically() {- globalConfig := server.GetConfig()-- // By default, if no heartbeat is received for 10 times, then the server is considered as stale- GlobalServerStore.CleanupStaleStatuses(globalConfig.GetHeartbeatInterval() * 10)-}--func UpdateServer(serverName string, status *common.BaseMessage) (common.ErrorCode, map[string]interface{}, string) {- err := GlobalServerStore.UpdateServerInfo(serverName, status)- if err != nil {- return common.CodeErrorServerStatus, nil, err.Error()- }- return CheckLicense()-}--// Role management methods--// ListRoles list all roles-func (s *Service) ListRoles(ctx context.Context) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "list_roles",- "error": "'list roles' is not supported",- },- }-- return result, nil-}--// CreateRole create a new role-func (s *Service) CreateRole(ctx context.Context, roleName, description string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "create_role",- "role_name": roleName,- "description": description,- "error": "'create role' is not supported",- }-- return result, nil-}--// ShowRole show role details-func (s *Service) ShowRole(ctx context.Context, roleName string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "show_role",- "role_name": roleName,- "error": "'show role' is not supported",- }-- return result, nil--}--// UpdateRole update role-func (s *Service) UpdateRole(ctx context.Context, roleName, description string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "update_role",- "role_name": roleName,- "description": description,- "error": "'update role' is not supported",- }-- return result, nil-}--// DropRole drop role-func (s *Service) DropRole(ctx context.Context, roleName string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "drop_role",- "role_name": roleName,- "error": "'drop role' is not supported",- }-- return result, nil-}--// ShowRolePermission get role permissions-func (s *Service) ShowRolePermission(ctx context.Context, roleName string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "show_role_permission",- "role_name": roleName,- "error": "'show role permissions' is not supported",- }-- return result, nil-}--// GrantRolePermission grant permission to role-func (s *Service) GrantRolePermission(ctx context.Context, roleName string, actions []string, resource string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "grant_role_permission",- "role_name": roleName,- "actions": actions,- "resource": resource,- "error": "'grant role permission' is not supported",- }-- return result, nil-}--// RevokeRolePermission revoke permission from role-func (s *Service) RevokeRolePermission(ctx context.Context, roleName string, actions []string, resource string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "revoke_role_permission",- "role_name": roleName,- "actions": actions,- "resource": resource,- "error": "'revoke role permission' is not supported",- }-- return result, nil-}--// ListResources list role resources-func (s *Service) ListResources(ctx context.Context) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "list_resources",- "error": "'list resources for role' is not supported",- }-- return result, nil-}--// ListRolesWithPermission list roles with permission-func (s *Service) ListRolesWithPermission(ctx context.Context) ([]map[string]interface{}, error) {- return []map[string]interface{}{- {- "command": "list_roles_with_permission",- "error": "'list roles with permission' is not supported",- },- }, nil-}--func (s *Service) ShowRoleDefaultModels(ctx context.Context, roleName string) ([]map[string]interface{}, error) {- return []map[string]interface{}{- {- "command": "show_role_default_models",- "role_name": roleName,- "error": "'show role default models' is not supported",- },- }, nil-}--// SetRoleDefaultModel set role default model-func (s *Service) SetRoleDefaultModel(ctx context.Context, roleName, modelID, modelType string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "set_role_default_model",- "role_name": roleName,- "model_id": modelID,- "model_type": modelType,- "error": "'set role default model' is not supported",- }, nil-}--// ResetRoleDefaultModel reset role default model-func (s *Service) ResetRoleDefaultModel(ctx context.Context, roleName, modelType string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "reset_role_default_model",- "role_name": roleName,- "model_type": modelType,- "error": "'reset role default model' is not supported",- }, nil-}--// ListModelProviders list model providers-func (s *Service) ListModelProviders(ctx context.Context) ([]map[string]interface{}, error) {- return []map[string]interface{}{- {- "command": "list_model_providers",- "error": "'list model providers' is not supported",- },- }, nil-}--// AddModelProvider Add model provider-func (s *Service) AddModelProvider(ctx context.Context, userID, providerName string) (map[string]interface{}, error) {-- return map[string]interface{}{- "command": "add_model_provider",- "user_id": userID,- "provider_id": providerName,- "error": "'add model provider' is not supported",- }, nil-}--// DeleteModelProviders delete model providers-func (s *Service) DeleteModelProviders(ctx context.Context, userID string, providerNames []string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "delete_model_providers",- "user_id": userID,- "provider_names": providerNames,- "error": "'delete model providers' is not supported",- }, nil-}--// ListModelInstances list model instances-func (s *Service) ListModelInstances(ctx context.Context, userID, providerName string) ([]map[string]interface{}, error) {-- return []map[string]interface{}{- {- "command": "list_model_instances",- "user_id": userID,- "provider_id": providerName,- "error": "'list model instances' is not supported",- },- }, nil-}--// ShowProviderInstance show provider instance-func (s *Service) ShowProviderInstance(ctx context.Context, userID, providerName, instanceName string) (map[string]interface{}, error) {-- return map[string]interface{}{- "command": "show_provider_instance",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "error": "'show provider instance' is not supported",- }, nil-}--// ShowProviderInstanceBalance show provider instance balance-func (s *Service) ShowProviderInstanceBalance(ctx context.Context, userID, providerName, instanceName string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "show_provider_instance_balance",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "error": "'show provider instance balance' is not supported",- }, nil-}--// CheckInstanceConnection check instance connection-func (s *Service) CheckInstanceConnection(ctx context.Context, userID, providerName, instanceName string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "check_instance_connection",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "error": "'check instance connection' is not supported",- }, nil-}--// CheckProviderConnection check provider connection-func (s *Service) CheckProviderConnection(ctx context.Context, userID, providerName, region, apiKey, baseURL string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "check_provider_connection",- "user_id": userID,- "provider_id": providerName,- "region": region,- "api_key": apiKey,- "base_url": baseURL,- }, nil-}--// AlterProviderInstance alter provider instance-func (s *Service) AlterProviderInstance(ctx context.Context, userID, providerName, instanceName, newInstanceName, newAPIKey string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "alter_provider_instance",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "new_instance_name": newInstanceName,- "new_api_key": newAPIKey,- "error": "'alter provider instance' is not supported",- }, nil-}--// AddModelInstance Add model instance-func (s *Service) AddModelInstance(ctx context.Context, userID, providerName, instanceName string) (map[string]interface{}, error) {-- return map[string]interface{}{- "command": "add_model_instance",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "error": "'add model instance' is not supported",- }, nil-}--// DeleteModelInstances delete model instances-func (s *Service) DeleteModelInstances(ctx context.Context, userID, providerName string, instances []string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "delete_model_instances",- "user_id": userID,- "provider_id": providerName,- "instances": instances,- "error": "'delete model instances' is not supported",- }, nil-}--// ListInstanceModels list models for instance-func (s *Service) ListInstanceModels(ctx context.Context, userID, providerName, instanceName string) ([]map[string]interface{}, error) {- return []map[string]interface{}{- {- "command": "list_instance_models",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "error": "'list instance models' is not supported",- },- }, nil-}--func (s *Service) EnableOrDisableModel(ctx context.Context, userID, providerName, instanceName, modelName, modelID, status string) (map[string]interface{}, error) {-- return map[string]interface{}{- "command": "enable_or_disable_model",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "model_name": modelName,- "model_id": modelID,- "status": status,- "error": "'enable or disable model' is not supported",- }, nil-}--// AddModel Add model--// AddModels Add models-func (s *Service) AddModels(ctx context.Context, userID, providerName, instanceName string, modelNames []string) (map[string]interface{}, error) {-- return map[string]interface{}{- "command": "add_model",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "model_names": modelNames,- "error": "'add model' is not supported",- }, nil-}--// DeleteModels delete models-func (s *Service) DeleteModels(ctx context.Context, userID, providerName, instanceName string, models []string) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "delete_models",- "user_id": userID,- "provider_id": providerName,- "instance_name": instanceName,- "models": models,- "error": "'delete models' is not supported",- }, nil-}--func (s *Service) GetSystemFingerprint(ctx context.Context) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "get_system_fingerprint",- "error": "'get system fingerprint' is not supported",- }-- return result, nil-}--func (s *Service) SetSystemLicense(ctx context.Context, licenseStr string) (map[string]interface{}, error) {- return nil, errors.New("'set system license' is not supported")-}--func (s *Service) ShowSystemLicense(ctx context.Context) (map[string]interface{}, error) {- var result map[string]interface{}- result = map[string]interface{}{- "command": "show_system_license",- "error": "'show system license' is not supported",- }-- return result, nil-}--func (s *Service) VerifyLicense(ctx context.Context, licenseStr string) (map[string]interface{}, error) {- var result map[string]interface{}- result = map[string]interface{}{- "command": "verify_license",- "error": "'verify license' is not supported",- }-- return result, nil-}--func (s *Service) CheckSystemLicense(ctx context.Context) (map[string]interface{}, error) {- var result map[string]interface{}- result = map[string]interface{}{- "command": "check_system_license",- "error": "'check system license' is not supported",- }-- return result, nil-}--func (s *Service) UpdateSystemLicenseConfig(ctx context.Context, timeRecordSaveInterval, timeRecordTaskDuration int64) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "update_system_license_config",- "time_record_save_interval": timeRecordSaveInterval,- "time_record_task_duration": timeRecordTaskDuration,- "error": "'update system license config' is not supported",- }-- return result, nil-}--func (s *Service) SetSoftFingerprint(ctx context.Context, softFingerprint string) error {- return errors.New("set soft fingerprint is not supported")-}--func (s *Service) GetSoftFingerprint(ctx context.Context) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "show_soft_fingerprint",- "error": "'show soft fingerprint' is not supported",- }-- return result, nil-}--func (s *Service) DeleteSoftFingerprint(ctx context.Context) error {- return errors.New("delete soft fingerprint is not supported")-}--// ShowUserActivity show user activity for enterprise edition-func (s *Service) ShowUserActivity(ctx context.Context, email string, days int) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "days": days,- "error": "'show user activity' is not supported",- }-- return result, nil-}--// ShowUserDatasetSummary show user dataset summary for enterprise edition-func (s *Service) ShowUserDatasetSummary(ctx context.Context, email, dataset string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "dataset": dataset,- "error": "'show user dataset summary' is not supported",- }-- return result, nil-}--// ShowUserSummary show user summary for enterprise edition-func (s *Service) ShowUserSummary(ctx context.Context, email string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.WithContext(ctx).Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "error": "'show user summary' is not supported",- }-- return result, nil-}--// ShowUserStorage show user storage for enterprise edition-func (s *Service) ShowUserStorage(ctx context.Context, email string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "error": "'show user storage' is not supported",- }-- return result, nil-}--// ShowUserQuota show user quota for enterprise edition-func (s *Service) ShowUserQuota(ctx context.Context, email string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.WithContext(ctx).Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "error": "'show user quota' is not supported",- }-- return result, nil-}--// ShowUserIndex show user index for enterprise edition-func (s *Service) ShowUserIndex(ctx context.Context, email string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "error": "'show user index' is not supported",- }-- return result, nil-}--// UpdateUserRole update user role-func (s *Service) UpdateUserRole(ctx context.Context, email, roleName string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "command": "update_user_role",- "role": roleName,- "email": user.Email,- "nickname": user.Nickname,- "error": "'update user role' is not supported",- }-- return result, nil-}--// ShowUserPermission show user permissions for enterprise edition-func (s *Service) ShowUserPermission(ctx context.Context, email string) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "command": "show_user_permission",- "email": user.Email,- "nickname": user.Nickname,- "error": "'show user permission' is not supported",- }-- return result, nil-}--// ListUserDatasets requires the enterprise edition.-func (s *Service) ListUserDatasets(ctx context.Context, email string) ([]map[string]interface{}, error) {- return nil, errors.New("listing user datasets is only available in the enterprise edition")-}--// ListUserAgents requires the enterprise edition.-func (s *Service) ListUserAgents(ctx context.Context, email, canvasCategory string, page, pageSize int) ([]map[string]interface{}, int64, error) {- return nil, 0, errors.New("listing user agents is only available in the enterprise edition")-}--// ListUserChats show user chats for enterprise edition-func (s *Service) ListUserChats(ctx context.Context, email string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_chats",- "email": user.Email,- "nickname": user.Nickname,- "error": "'list user chats' is not supported",- },- }-- return result, nil-}--// ListUserSearches show user searches for enterprise edition-func (s *Service) ListUserSearches(ctx context.Context, email string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_searches",- "email": user.Email,- "nickname": user.Nickname,- "error": "'list user searches' is not supported",- },- }-- return result, nil-}--// ListUserModels show user models for enterprise edition-func (s *Service) ListUserModels(ctx context.Context, email string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_models",- "email": user.Email,- "nickname": user.Nickname,- "error": "'list user models' is not supported",- },- }-- return result, nil-}--// ListUserFiles show user files for enterprise edition-func (s *Service) ListUserFiles(ctx context.Context, email string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_files",- "email": user.Email,- "nickname": user.Nickname,- "error": "'list user files' is not supported",- },- }-- return result, nil-}--// ListUserProviders show user providers for enterprise edition-func (s *Service) ListUserProviders(ctx context.Context, email string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_providers",- "email": user.Email,- "nickname": user.Nickname,- "error": "'list user providers' is not supported",- },- }-- return result, nil-}--// ListUserProviderInstances show user provider instances for enterprise edition-func (s *Service) ListUserProviderInstances(ctx context.Context, email, providerName string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_provider_instances",- "email": user.Email,- "nickname": user.Nickname,- "provider_name": providerName,- "error": "'list user provider instances' is not supported",- },- }-- return result, nil-}--// ListUserProviderInstanceModels show user provider instance models for enterprise edition-func (s *Service) ListUserProviderInstanceModels(ctx context.Context, email, providerName, instanceName string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_provider_instance_models",- "email": user.Email,- "nickname": user.Nickname,- "provider_name": providerName,- "instance_name": instanceName,- "error": "'list user provider instance models' is not supported",- },- }-- return result, nil-}--// ListUserDefaultModels show user default models for enterprise edition-func (s *Service) ListUserDefaultModels(ctx context.Context, email string) ([]map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := []map[string]interface{}{- {- "command": "list_user_default_models",- "email": user.Email,- "nickname": user.Nickname,- "error": "'list user default models' is not supported",- },- }-- return result, nil-}--// ShowUsersSummary show users summary for enterprise edition-func (s *Service) ShowUsersSummary(ctx context.Context) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "show_users_summary",- "error": "'show users summary' is not supported",- }-- return result, nil-}--// ShowUsersActivity show users activity for enterprise edition-func (s *Service) ShowUsersActivity(ctx context.Context, days, windows *int) (map[string]interface{}, error) {- daysInt := 0- if days != nil {- daysInt = *days- }- windowsInt := 0- if windows != nil {- windowsInt = *windows- }- result := map[string]interface{}{- "days": daysInt,- "windows": windowsInt,- "command": "show_users_activity",- "error": "'show users activity' is not supported",- }-- return result, nil-}--func (s *Service) ListUsersEE(ctx context.Context, pageIndex, pageSize int, name string, status, role, sort, orderBy, plan string, top, days int, quota *int) ([]map[string]interface{}, int64, error) {- item := map[string]interface{}{}- item["pageIndex"] = pageIndex- item["pageSize"] = pageSize- item["name"] = name- item["status"] = status- item["role"] = role- item["sort"] = sort- item["order_by"] = orderBy- item["plan"] = plan- item["top"] = top- item["days"] = days- quotaInt := 0- if quota != nil {- quotaInt = *quota- }- item["quota"] = quotaInt-- var result []map[string]interface{}- result = append(result, item)- return result, 0, nil-}--// ListUsersReports list users reports for enterprise edition-func (s *Service) ListUsersReports(ctx context.Context, pageIndex, pageSize int, status, plan *string, days *int) (map[string]interface{}, error) {-- statusStr := "all"- if status != nil {- statusStr = *status- }- planStr := "all"- daysInt := 0- if days != nil {- daysInt = *days- }- if plan != nil {- planStr = *plan- }-- result := map[string]interface{}{- "page_index": pageIndex,- "page_size": pageSize,- "status": statusStr,- "plan": planStr,- "days": daysInt,- "command": "list_users_reports",- "error": "'List users reports' is not supported",- }-- return result, nil-}--// ListUsersStorage list users storage for enterprise edition-func (s *Service) ListUsersStorage(ctx context.Context, pageIndex, pageSize, top int) (map[string]interface{}, error) {-- result := map[string]interface{}{- "page_index": pageIndex,- "page_size": pageSize,- "top": top,- "command": "list_users_storage",- "error": "'List users storage' is not supported",- }-- return result, nil-}--// ListUsersDocuments list users documents for enterprise edition-func (s *Service) ListUsersDocuments(ctx context.Context, pageIndex, pageSize, top int) (map[string]interface{}, error) {-- result := map[string]interface{}{- "page_index": pageIndex,- "page_size": pageSize,- "top": top,- "command": "list_users_documents",- "error": "'List users documents' is not supported",- }-- return result, nil-}--// ListUsersIndex list users index for enterprise edition-func (s *Service) ListUsersIndex(ctx context.Context, pageIndex, pageSize, top int) (map[string]interface{}, error) {-- result := map[string]interface{}{- "page_index": pageIndex,- "page_size": pageSize,- "top": top,- "command": "list_users_index",- "error": "'List users index' is not supported",- }-- return result, nil-}--// ListUsersQuota list users quota for enterprise edition-func (s *Service) ListUsersQuota(ctx context.Context, pageIndex, pageSize, top int, quotaThreshold *int, plan *string, days *int) (map[string]interface{}, error) {-- quotaThresholdInt := 0- if quotaThreshold != nil {- quotaThresholdInt = *quotaThreshold- }- planStr := "all"- daysInt := 0- if days != nil {- daysInt = *days- }- if plan != nil {- planStr = *plan- }-- result := map[string]interface{}{- "page_index": pageIndex,- "page_size": pageSize,- "top": top,- "quota_threshold": quotaThresholdInt,- "plan": planStr,- "days": daysInt,- "command": "list_users_quota",- "error": "'List users quota' is not supported",- }-- return result, nil-}--// ShowUsersPlanSummary show users plan summary for enterprise edition-func (s *Service) ShowUsersPlanSummary(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_users_plan_summary",- "error": "'Show users plan summary' is not supported",- }-- return result, nil-}--// ShowUsersPlanQuota show users plan quota for enterprise edition-func (s *Service) ShowUsersPlanQuota(ctx context.Context, quota int) (map[string]interface{}, error) {-- result := map[string]interface{}{- "quota": quota,- "command": "show_users_plan_quota",- "error": "'Show users plan quota' is not supported",- }-- return result, nil-}--// ShowUsersQuotaSummary show users quota summary for enterprise edition-func (s *Service) ShowUsersQuotaSummary(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_users_quota_summary",- "error": "'Show users quota summary' is not supported",- }-- return result, nil-}--// ShowIngestionTasksSummary show ingestion tasks summary for enterprise edition-func (s *Service) ShowIngestionTasksSummary(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_ingestion_tasks_summary",- "error": "'Show ingestion tasks summary' is not supported",- }-- return result, nil-}--// ShowDataSummary show data summary for enterprise edition-func (s *Service) ShowDataSummary(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_data_summary",- "error": "'Show data summary' is not supported",- }-- return result, nil-}--// ShowDataOrphan show data orphan for enterprise edition-func (s *Service) ShowDataOrphan(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_data_orphan",- "error": "'Show data orphan' is not supported",- }-- return result, nil-}--// ShowDataStorage show data storage for enterprise edition-func (s *Service) ShowDataStorage(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_data_storage",- "error": "'Show data storage' is not supported",- }-- return result, nil-}--// ShowDataIndex show data index for enterprise edition-func (s *Service) ShowDataIndex(ctx context.Context) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "show_data_index",- "error": "'Show data index' is not supported",- }-- return result, nil-}--// PurgeOrphanData purge orphan data for enterprise edition-func (s *Service) PurgeOrphanData(ctx context.Context, preview bool) (map[string]interface{}, error) {-- result := map[string]interface{}{- "command": "purge_orphan_data",- "preview": preview,- "error": "'Purge orphan data' is not supported",- }-- return result, nil-}--// PurgeUserData purge user data for enterprise edition-func (s *Service) PurgeUserData(ctx context.Context, email string, preview bool) (map[string]interface{}, error) {- // Query user by email- var user entity.User- err := dao.DB.Where("email = ?", email).First(&user).Error- if err != nil {- return nil, common.ErrUserNotFound- }-- result := map[string]interface{}{- "email": user.Email,- "nickname": user.Nickname,- "preview": preview,- "error": "'Purge user data' is not supported",- }-- return result, nil-}--// PurgeUsersData purge users data for enterprise edition-func (s *Service) PurgeUsersData(ctx context.Context, preview bool, days int, userPlan *string, userActivity *string) (map[string]interface{}, error) {-- plan := "all"- activity := "all"- if userPlan != nil {- plan = *userPlan- }- if userActivity != nil {- activity = *userActivity- }-- result := map[string]interface{}{- "command": "purge_users_data",- "preview": preview,- "days": days,- "plan": plan,- "activity": activity,- "error": "'Purge users data' is not supported",- }-- return result, nil-}--// GenerateUserAPIKey create tenant API key for tenant-func (s *Service) GenerateUserAPIKey(ctx context.Context, username string) (map[string]interface{}, error) {-- user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)- if err != nil {- return nil, fmt.Errorf("user not found: %w", err)- }-- result := map[string]interface{}{- "command": "create_user_api_key",- "email": user.Email,- "nickname": user.Nickname,- "error": "'Create user API key' is not supported",- }-- return result, nil-}--// DeleteUserAPIKey delete user API key-func (s *Service) DeleteUserAPIKey(ctx context.Context, username, key string) (map[string]interface{}, error) {-- user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)- if err != nil {- return nil, fmt.Errorf("user not found: %w", err)- }-- result := map[string]interface{}{- "command": "delete_user_api_key",- "email": user.Email,- "nickname": user.Nickname,- "api_key": key,- "error": "'Delete user API key' is not supported",- }-- return result, nil-}--// ListUserAPIKeys list user API keys-func (s *Service) ListUserAPIKeys(ctx context.Context, username string) ([]map[string]interface{}, error) {-- user, err := s.userDAO.GetByEmail(ctx, dao.DB, username)- if err != nil {- return nil, fmt.Errorf("user not found: %w", err)- }-- result := []map[string]interface{}{- {- "command": "list_user_api_keys",- "email": user.Email,- "nickname": user.Nickname,- "error": "'List user API keys' is not supported",- },- }-- return result, nil-}--// ListIngestionTasks reports that admin task listing is not supported.-func (s *Service) ListIngestionTasks(ctx context.Context) ([]map[string]interface{}, error) {- return []map[string]interface{}{- {- "command": "list_ingestion_tasks",- "error": "'list ingestion tasks' is not supported",- },- }, nil-}--// RemoveIngestionTasks reports that admin task removal is not supported.-func (s *Service) RemoveIngestionTasks(ctx context.Context) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "remove_ingestion_tasks",- "error": "'remove ingestion tasks' is not supported",- }, nil-}--// StopIngestionTasks reports that admin task stopping is not supported.-func (s *Service) StopIngestionTasks(ctx context.Context) (map[string]interface{}, error) {- return map[string]interface{}{- "command": "stop_ingestion_tasks",- "error": "'stop ingestion tasks' is not supported",- }, nil-}--func CheckClientStatus(serverName string, status *common.BaseMessage) error {- return nil-}--func CheckLicense() (common.ErrorCode, map[string]interface{}, string) {- return common.CodeLicenseValid, map[string]interface{}{}, ""-}--// DownloadSensitiveWords download sensitive words-func (s *Service) DownloadSensitiveWords(ctx context.Context) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "download_sensitive_words",- "error": "'Download sensitive words' is not supported",- },- }- return result, nil-}--// UploadSensitiveWords upload sensitive words-func (s *Service) UploadSensitiveWords(ctx context.Context, file *multipart.FileHeader) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "upload_sensitive_words",- "filename": file.Filename,- "error": "'Upload sensitive words' is not supported",- },- }- return result, nil-}--// BindVerificationEmail bind verification email-func (s *Service) BindVerificationEmail(ctx context.Context, email, host string, port int, username, password string, useTLS, useSSL bool) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "bind_verification_email",- "email": email,- "host": host,- "port": port,- "username": username,- "password": password,- "use_tls": useTLS,- "use_ssl": useSSL,- "error": "'Bind verification email' is not supported",- }- return result, nil-}--// ShowVerificationEmail show verification email-func (s *Service) ShowVerificationEmail(ctx context.Context) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "show_verification_email",- "error": "'Show verification email' is not supported",- }- return result, nil-}--// ShowWhiteList show white list-func (s *Service) ShowWhiteList(ctx context.Context) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "show_white_list",- "error": "'Show white list' is not supported",- },- }- return result, nil-}--// AddWhiteList add white list-func (s *Service) AddWhiteList(ctx context.Context, email string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "add_white_list",- "email": email,- "error": "'Add white list' is not supported",- }- return result, nil-}--// BatchAddWhiteList batch add white list-func (s *Service) BatchAddWhiteList(ctx context.Context, file *multipart.FileHeader) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "batch_add_white_list",- "filename": file.Filename,- "error": "'Batch add white list' is not supported",- }- return result, nil-}--// UpdateWhiteList update white list-func (s *Service) UpdateWhiteList(ctx context.Context, id, email string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "update_white_list",- "id": id,- "email": email,- "error": "'Update white list' is not supported",- }- return result, nil-}--// DeleteWhiteList delete white list-func (s *Service) DeleteWhiteList(ctx context.Context, id int) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "delete_white_list",- "id": id,- "error": "'Delete white list' is not supported",- }- return result, nil-}--// BatchDeleteWhiteList batch delete white list-func (s *Service) BatchDeleteWhiteList(ctx context.Context, ids []int) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "batch_delete_white_list",- "ids": ids,- "error": "'Batch delete white list' is not supported",- }- return result, nil-}--// GetTokenStats returns API token statistics for the user.-func (s *Service) GetTokenStats(ctx context.Context, userName, fromDate, toDate, granularity string) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "get_token_stats",- "user_name": userName,- "from_date": fromDate,- "to_date": toDate,- "granularity": granularity,- "error": "'Get API token stats' is not supported",- },- }- return result, nil-}--// GetTokenUsersStats returns API token statistics for all users.-func (s *Service) GetTokenUsersStats(ctx context.Context, fromDate, toDate string, top int) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "get_token_users_stats",- "from_date": fromDate,- "to_date": toDate,- "top": top,- "error": "'Get API token users stats' is not supported",- },- }- return result, nil-}--// GetTokenStatsSummary returns API token statistics summary for all users.-func (s *Service) GetTokenStatsSummary(ctx context.Context, fromDate, toDate string) (map[string]interface{}, error) {- result := map[string]interface{}{- "command": "get_token_stats_summary",- "from_date": fromDate,- "to_date": toDate,- "error": "'Get API token stats summary' is not supported",- }-- return result, nil-}--// ListLogs lists operation logs for the user.-func (s *Service) ListLogs(ctx context.Context, userName string, days int) ([]map[string]interface{}, error) {- result := []map[string]interface{}{- {- "command": "list_logs",- "user_name": userName,- "days": days,- "error": "'List operation logs' is not supported",- },- }- return result, nil-}--func (s *Service) GetEEServicesStatus(ctx context.Context) []ServiceStatus {- return []ServiceStatus{}-}diff --git a/internal/admin/stub.go b/internal/admin/stub.gonew file mode 100644index 0000000000..b049e258db--- /dev/null+++ b/internal/admin/stub.go@@ -0,0 +1,74 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package admin++import (+ "context"+ "errors"++ "ragflow/internal/common"+ "ragflow/internal/server"++ "github.com/gin-gonic/gin"+)++// SetupEERouter adds no enterprise middleware in the community edition.+func SetupEERouter(engine *gin.Engine) {}++// RegisterEERouter registers no enterprise admin routes in the community+// edition.+func RegisterEERouter(protected *gin.RouterGroup, r *Router) {}++// AppendServiceList adds no enterprise service entries.+func AppendServiceList(serviceInfos []*common.BaseMessage) []*common.BaseMessage {+ return serviceInfos+}++// GetEEServicesStatus reports no enterprise services in the community edition.+func (s *Service) GetEEServicesStatus(ctx context.Context) []ServiceStatus { return nil }++// ListUsersEE reports that per-user billing and quota filters are an+// enterprise capability.+func (s *Service) ListUsersEE(ctx context.Context, pageIndex, pageSize int, name string, status, role, sort, orderBy, plan string, top, days int, quota *int) ([]map[string]interface{}, int64, error) {+ return nil, 0, errors.New("listing users with plan and quota filters is only available in the enterprise edition")+}++// UpdateServer records the heartbeat in the server store. The community+// edition has no license state to reconcile, but reporting CodeLicenseValid+// keeps the shared client and admin contract intact: AdminClient.SendHeartbeat+// treats any other code as a failure.+func UpdateServer(serverName string, status *common.BaseMessage) (common.ErrorCode, map[string]interface{}, string) {+ if err := GlobalServerStore.UpdateServerInfo(serverName, status); err != nil {+ return common.CodeErrorServerStatus, nil, err.Error()+ }+ return common.CodeLicenseValid, map[string]interface{}{}, ""+}++// CheckClientStatus accepts every heartbeat: the community edition has no+// license to reconcile.+func CheckClientStatus(serverName string, status *common.BaseMessage) error { return nil }++// InitLicense is a no-op: the community edition has no license.+func InitLicense(ctx context.Context) error { return nil }++// CheckServicePeriodically is a no-op: the community edition has no license+// expiry to watch.+func CheckServicePeriodically() {+ GlobalServerStore.CleanupStaleStatuses(server.GetConfig().GetHeartbeatInterval() * 10)+}diff --git a/internal/cli/admin_command_ee_test.go b/internal/cli/admin_command_ee_test.godeleted file mode 100644index 5b15e067c1..0000000000--- a/internal/cli/admin_command_ee_test.go+++ /dev/null@@ -1,31 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package cli--import "testing"--func TestParseAdminListUserAgentsRequiresEE(_ *testing.T) {}--func TestAdminListUserAgentsRequiresEE(_ *testing.T) {}--func TestParseAPIListAgents(_ *testing.T) {}--func TestParseAdminListUserDatasetsRequiresEE(_ *testing.T) {}--func TestAdminListUserDatasetsRequiresEE(_ *testing.T) {}--func TestParseAPIListDatasets(_ *testing.T) {}diff --git a/internal/cli/admin_command_ee.go b/internal/cli/stub.gosimilarity index 67%rename from internal/cli/admin_command_ee.gorename to internal/cli/stub.goindex 4bd03b154d..5920e55a31 100644--- a/internal/cli/admin_command_ee.go+++ b/internal/cli/stub.go@@ -14,11 +14,15 @@// limitations under the License.//+//go:build !ee++// Admin ingestion and per-user inspection commands are enterprise features.+// The OSS build keeps the parser and dispatcher identical and rejects those+// commands at runtime.package cliimport "errors"-// AdminListUserAgentsCommand is available only in the enterprise edition.func (c *CLI) AdminListUserAgentsCommand(commandCount int, cmd *Command) (ResponseIf, error) {return nil, errors.New("listing user agents is only available in the enterprise edition")}@@ -27,7 +31,6 @@ func (p *Parser) parseAdminListUserAgentsEE(userName string) (*Command, error) {return nil, errors.New("listing user agents is only available in the enterprise edition")}-// AdminListUserDatasetsCommand is available only in the enterprise edition.func (c *CLI) AdminListUserDatasetsCommand(commandCount int, cmd *Command) (ResponseIf, error) {return nil, errors.New("listing user datasets is only available in the enterprise edition")}@@ -37,11 +40,11 @@ func (p *Parser) parseAdminListUserDatasetsEE(userName string) (*Command, error)}func (c *CLI) ListAdminIngestionTasks(commandCount int, cmd *Command) (ResponseIf, error) {- return nil, errors.New("listing admin ingestion tasks is not supported in the open-source edition")+ return nil, errors.New("listing admin ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminListIngestionTasks() (*Command, error) {- return nil, errors.New("listing admin ingestion tasks is not supported in the open-source edition")+ return nil, errors.New("listing admin ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminShowIngestionLog() (*Command, error) {@@ -57,41 +60,41 @@ func (c *CLI) AdminShowIngestionMessagesCommand(commandCount int, cmd *Command)}func (c *CLI) AdminListUserIngestionTasksCommand(commandCount int, cmd *Command) (ResponseIf, error) {- return nil, errors.New("listing user ingestion tasks in admin mode is not supported in the open-source edition")+ return nil, errors.New("listing user ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminListUserIngestionTasks(userName string) (*Command, error) {- return nil, errors.New("listing user ingestion tasks in admin mode is not supported in the open-source edition")+ return nil, errors.New("listing user ingestion tasks is only available in the enterprise edition")}func (c *CLI) AdminStopIngestionCommand(commandCount int, cmd *Command) (ResponseIf, error) {- return nil, errors.New("stopping admin ingestion tasks is not supported in the open-source edition")+ return nil, errors.New("stopping admin ingestion tasks is only available in the enterprise edition")}func (c *CLI) AdminRemoveIngestionCommand(commandCount int, cmd *Command) (ResponseIf, error) {- return nil, errors.New("removing admin ingestion tasks is not supported in the open-source edition")+ return nil, errors.New("removing admin ingestion tasks is only available in the enterprise edition")}func (c *CLI) AdminStopUserIngestionTasksCommand(commandCount int, cmd *Command) (ResponseIf, error) {- return nil, errors.New("stopping user ingestion tasks in admin mode is not supported in the open-source edition")+ return nil, errors.New("stopping user ingestion tasks is only available in the enterprise edition")}func (c *CLI) AdminRemoveUserIngestionTasksCommand(commandCount int, cmd *Command) (ResponseIf, error) {- return nil, errors.New("removing user ingestion tasks in admin mode is not supported in the open-source edition")+ return nil, errors.New("removing user ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminStopIngestionTasks() (*Command, error) {- return nil, errors.New("stopping admin ingestion tasks is not supported in the open-source edition")+ return nil, errors.New("stopping admin ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminRemoveIngestionTasks() (*Command, error) {- return nil, errors.New("removing admin ingestion tasks is not supported in the open-source edition")+ return nil, errors.New("removing admin ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminStopUserIngestionTasks(userName string) (*Command, error) {- return nil, errors.New("stopping user ingestion tasks in admin mode is not supported in the open-source edition")+ return nil, errors.New("stopping user ingestion tasks is only available in the enterprise edition")}func (p *Parser) parseAdminRemoveUserIngestionTasks(userName string) (*Command, error) {- return nil, errors.New("removing user ingestion tasks in admin mode is not supported in the open-source edition")+ return nil, errors.New("removing user ingestion tasks is only available in the enterprise edition")}diff --git a/internal/common/error_code.go b/internal/common/error_code.goindex ce632bd88e..95a4a0c4b0 100644--- a/internal/common/error_code.go+++ b/internal/common/error_code.go@@ -52,40 +52,57 @@ const (CodeConflict ErrorCode = 409CodeServerError ErrorCode = 500CodeNotImplemented ErrorCode = 501++ // Billing error codes match the Python RetCode values the web client+ // already handles in showPriceModal.+ CodeBillingResourceInsufficient ErrorCode = 2000+ CodeBillingAppsInsufficient ErrorCode = 2001+ CodeBillingSeatsInsufficient ErrorCode = 2002+ CodeBillingStorageInsufficient ErrorCode = 2003+ CodeBillingPointsInsufficient ErrorCode = 2004+ CodeBillingSubscriptionInvalid ErrorCode = 2005+ CodeBillingPaymentFailed ErrorCode = 2006)var errorMessages = map[ErrorCode]string{- CodeSuccess: "Success",- CodeLackResources: "Lack resources",- CodeNotEffective: "Not effective",- CodeExceptionError: "System exception",- CodeArgumentError: "Invalid argument",- CodeDataError: "Data error",- CodeOperatingError: "Operation error",- CodeTimeoutError: "Timeout",- CodeConnectionError: "Connection error",- CodeRunning: "System running",- CodeResourceExhausted: "Resource exhausted",- CodePermissionError: "Permission denied",- CodeAuthenticationError: "Authentication failed",- CodeParamError: "Invalid parameters",- CodeConnectionPoolExhausted: "Connection pool exhausted",- CodeLicenseValid: "License valid",- CodeLicenseInactiveError: "License inactive",- CodeLicenseExpiredError: "License expired",- CodeLicenseDigestError: "License digest error",- CodeLicenseTimeRollback: "License time rollback detected",- CodeLicenseNotFound: "License not found",- CodeLicenseUnexpectedError: "Unexpected license error",- CodeLicenseNotValidYet: "License not valid yet",- CodeErrorServerStatus: "Error server status",- CodeBadRequest: "Bad request",- CodeUnauthorized: "Unauthorized",- CodeForbidden: "Forbidden",- CodeNotFound: "Resource not found",- CodeConflict: "Resource conflict",- CodeServerError: "Internal server error",- CodeNotImplemented: "Not implemented",+ CodeSuccess: "Success",+ CodeLackResources: "Lack resources",+ CodeNotEffective: "Not effective",+ CodeExceptionError: "System exception",+ CodeArgumentError: "Invalid argument",+ CodeDataError: "Data error",+ CodeOperatingError: "Operation error",+ CodeTimeoutError: "Timeout",+ CodeConnectionError: "Connection error",+ CodeRunning: "System running",+ CodeResourceExhausted: "Resource exhausted",+ CodePermissionError: "Permission denied",+ CodeAuthenticationError: "Authentication failed",+ CodeParamError: "Invalid parameters",+ CodeConnectionPoolExhausted: "Connection pool exhausted",+ CodeLicenseValid: "License valid",+ CodeLicenseInactiveError: "License inactive",+ CodeLicenseExpiredError: "License expired",+ CodeLicenseDigestError: "License digest error",+ CodeLicenseTimeRollback: "License time rollback detected",+ CodeLicenseNotFound: "License not found",+ CodeLicenseUnexpectedError: "Unexpected license error",+ CodeLicenseNotValidYet: "License not valid yet",+ CodeErrorServerStatus: "Error server status",+ CodeBadRequest: "Bad request",+ CodeUnauthorized: "Unauthorized",+ CodeForbidden: "Forbidden",+ CodeNotFound: "Resource not found",+ CodeConflict: "Resource conflict",+ CodeServerError: "Internal server error",+ CodeNotImplemented: "Not implemented",+ CodeBillingResourceInsufficient: "Billing resource insufficient",+ CodeBillingAppsInsufficient: "Billing apps insufficient",+ CodeBillingSeatsInsufficient: "Billing seats insufficient",+ CodeBillingStorageInsufficient: "Billing storage insufficient",+ CodeBillingPointsInsufficient: "Billing points insufficient",+ CodeBillingSubscriptionInvalid: "Billing subscription invalid",+ CodeBillingPaymentFailed: "Billing payment failed",}func (e ErrorCode) Message() string {diff --git a/internal/common/error_code_test.go b/internal/common/error_code_test.gonew file mode 100644index 0000000000..dafd41fe28--- /dev/null+++ b/internal/common/error_code_test.go@@ -0,0 +1,95 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++package common++import "testing"++// allErrorCodes lists every ErrorCode constant. Keeping it in sync is what+// makes the coverage assertions below meaningful: a new code has to be added+// here together with its errorMessages entry.+var allErrorCodes = []ErrorCode{+ CodeSuccess,+ CodeLackResources,+ CodeNotEffective,+ CodeExceptionError,+ CodeArgumentError,+ CodeDataError,+ CodeOperatingError,+ CodeTimeoutError,+ CodeConnectionError,+ CodeRunning,+ CodeResourceExhausted,+ CodePermissionError,+ CodeAuthenticationError,+ CodeParamError,+ CodeConnectionPoolExhausted,+ CodeLicenseValid,+ CodeLicenseInactiveError,+ CodeLicenseExpiredError,+ CodeLicenseDigestError,+ CodeLicenseTimeRollback,+ CodeLicenseNotFound,+ CodeLicenseUnexpectedError,+ CodeLicenseNotValidYet,+ CodeErrorServerStatus,+ CodeBadRequest,+ CodeUnauthorized,+ CodeForbidden,+ CodeNotFound,+ CodeConflict,+ CodeServerError,+ CodeNotImplemented,+ CodeBillingResourceInsufficient,+ CodeBillingAppsInsufficient,+ CodeBillingSeatsInsufficient,+ CodeBillingStorageInsufficient,+ CodeBillingPointsInsufficient,+ CodeBillingSubscriptionInvalid,+ CodeBillingPaymentFailed,+}++// TestErrorMessagesCoverEveryCode keeps errorMessages one-to-one with the+// ErrorCode constants: every code has a message, no message is orphaned, and+// no code appears twice.+func TestErrorMessagesCoverEveryCode(t *testing.T) {+ listed := make(map[ErrorCode]bool, len(allErrorCodes))+ for _, code := range allErrorCodes {+ if listed[code] {+ t.Errorf("ErrorCode %d is listed twice in allErrorCodes", int(code))+ continue+ }+ listed[code] = true++ msg, ok := errorMessages[code]+ if !ok {+ t.Errorf("ErrorCode %d has no errorMessages entry", int(code))+ continue+ }+ if msg == "" {+ t.Errorf("ErrorCode %d has an empty message", int(code))+ }+ }++ if len(listed) != len(errorMessages) {+ t.Errorf("allErrorCodes lists %d distinct codes, errorMessages has %d entries", len(listed), len(errorMessages))+ }+ for code := range errorMessages {+ if !listed[code] {+ t.Errorf("errorMessages has an entry for %d but allErrorCodes does not list it", int(code))+ }+ }+}diff --git a/internal/common/http.go b/internal/common/http.goindex 2aecde99ea..bb1990b708 100644--- a/internal/common/http.go+++ b/internal/common/http.go@@ -824,3 +824,14 @@ func ParseRequestIntPositive(c *gin.Context, parameter, parameterName string, de}return parameterInt, nil}++// ResponseWithDetail returns an error envelope with a structured detail+// payload. Billing resource failures expose detail.current / detail.limit so+// the web upgrade modal can render the shortage.+func ResponseWithDetail(c *gin.Context, code ErrorCode, message string, detail interface{}) {+ c.JSON(http.StatusOK, struct {+ Code ErrorCode `json:"code"`+ Message interface{} `json:"message"`+ Detail interface{} `json:"detail,omitempty"`+ }{Code: code, Message: message, Detail: detail})+}diff --git a/internal/common/version_ee.go b/internal/common/stub.gosimilarity index 80%rename from internal/common/version_ee.gorename to internal/common/stub.goindex 22dd66f6f9..dbf96f3f8c 100644--- a/internal/common/version_ee.go+++ b/internal/common/stub.go@@ -1,3 +1,4 @@+//// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.//// Licensed under the Apache License, Version 2.0 (the "License");@@ -13,11 +14,16 @@// limitations under the License.//+//go:build !ee+package common-var OpenSourceVersion = "open source"-var EnterpriseEdition = "enterprise edition"+var (+ OpenSourceVersion = "open source"+ EnterpriseEdition = "enterprise edition"+)+// GetRAGFlowType reports the edition this binary was built for.func GetRAGFlowType() string {return OpenSourceVersion}diff --git a/internal/dao/api_token_ee.go b/internal/dao/api_token_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/api_token_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/billing_product_ee.go b/internal/dao/billing_product_ee.godeleted file mode 100644index 055c7e8e6a..0000000000--- a/internal/dao/billing_product_ee.go+++ /dev/null@@ -1,23 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--type BillingProductDAO struct{}--func NewBillingProductDAO() *BillingProductDAO {- return &BillingProductDAO{}-}diff --git a/internal/dao/billing_subscription_ee.go b/internal/dao/billing_subscription_ee.godeleted file mode 100644index b63ecc4d30..0000000000--- a/internal/dao/billing_subscription_ee.go+++ /dev/null@@ -1,23 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--type BillingSubscriptionDAO struct{}--func NewBillingSubscriptionDAO() *BillingSubscriptionDAO {- return &BillingSubscriptionDAO{}-}diff --git a/internal/dao/chat_ee.go b/internal/dao/chat_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/chat_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/database.go b/internal/dao/database.goindex 56cd6784a3..dfd7daa310 100644--- a/internal/dao/database.go+++ b/internal/dao/database.go@@ -217,6 +217,7 @@ func InitDB(ctx context.Context, migrateDB bool) error {&entity.CompilationTemplateGroup{},}dataModels = append(dataModels, permissionDataModelsEE()...)+ dataModels = append(dataModels, billingDataModelsEE()...)if migrateDB {// Mirror the Python flow, where tools/scripts/run_migrations.sh runs before@@ -241,6 +242,10 @@ func InitDB(ctx context.Context, migrateDB bool) error {}}+ if err = migrateBillingSchemaEE(ctx, DB); err != nil {+ return fmt.Errorf("failed to migrate billing schema: %w", err)+ }+// Split the conversation message and reference payloads out of their// parent tables. It has to run after AutoMigrate, which unlike// RunMigrations creates the child tables this backfill writes to.diff --git a/internal/dao/database_ee.go b/internal/dao/database_ee.godeleted file mode 100644index a6baabe90b..0000000000--- a/internal/dao/database_ee.go+++ /dev/null@@ -1,32 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--import (- "context"-- "gorm.io/gorm"-)--// permissionDataModelsEE returns no additional entities in the community edition.-func permissionDataModelsEE() []interface{} {- return nil-}--func initializeSystemSettingsEE(context.Context, *gorm.DB) error {- return nil-}diff --git a/internal/dao/document_ee.go b/internal/dao/document_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/document_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/file_ee.go b/internal/dao/file_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/file_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/kb_ee.go b/internal/dao/kb_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/kb_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/memory_ee.go b/internal/dao/memory_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/memory_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/permission_migration_ee.go b/internal/dao/permission_migration_ee.godeleted file mode 100644index a61f916651..0000000000--- a/internal/dao/permission_migration_ee.go+++ /dev/null@@ -1,28 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--import (- "context"-- "gorm.io/gorm"-)--// migratePermissionDataEE migrates enterprise permission data after schema setup.-func migratePermissionDataEE(context.Context, *gorm.DB) error {- return nil-}diff --git a/internal/dao/search_ee.go b/internal/dao/search_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/search_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/stub.go b/internal/dao/stub.gonew file mode 100644index 0000000000..668ac70a3d--- /dev/null+++ b/internal/dao/stub.go@@ -0,0 +1,80 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package dao++import (+ "context"++ "ragflow/internal/entity"++ "gorm.io/gorm"+)++// permissionDataModelsEE returns no additional entities in the community+// edition.+func permissionDataModelsEE() []interface{} { return nil }++// billingDataModelsEE returns no billing tables in the community edition.+func billingDataModelsEE() []interface{} { return nil }++// migrateBillingSchemaEE is a no-op in the community edition.+func migrateBillingSchemaEE(ctx context.Context, db *gorm.DB) error { return nil }++// initializeSystemSettingsEE is a no-op in the community edition.+func initializeSystemSettingsEE(ctx context.Context, db *gorm.DB) error { return nil }++// migratePermissionDataEE is a no-op in the community edition.+func migratePermissionDataEE(ctx context.Context, db *gorm.DB) error { return nil }++// initializeTenantDefaultRoleEE is a no-op in the community edition.+func initializeTenantDefaultRoleEE(ctx context.Context, db *gorm.DB, tenant *entity.Tenant) error {+ return nil+}++// ApplyDefaultTenantInviteEnabled is a no-op in the community edition.+func ApplyDefaultTenantInviteEnabled(ctx context.Context, db *gorm.DB, tenant *entity.Tenant) error {+ return nil+}++// TenantModelGroupDAO owns the enterprise model groups. The community edition+// has none.+type TenantModelGroupDAO struct{}++// NewTenantModelGroupDAO creates the model group DAO.+func NewTenantModelGroupDAO() *TenantModelGroupDAO { return &TenantModelGroupDAO{} }++// TenantModelGroupMapDAO owns the model-to-group mappings.+type TenantModelGroupMapDAO struct{}++// NewTenantModelGroupMapDAO creates the model group mapping DAO.+func NewTenantModelGroupMapDAO() *TenantModelGroupMapDAO { return &TenantModelGroupMapDAO{} }++// BillingProductDAO owns the billing product catalogue, which the community+// edition does not have.+type BillingProductDAO struct{}++// NewBillingProductDAO creates the billing product DAO.+func NewBillingProductDAO() *BillingProductDAO { return &BillingProductDAO{} }++// BillingSubscriptionDAO owns tenant subscriptions, which the community+// edition does not have.+type BillingSubscriptionDAO struct{}++// NewBillingSubscriptionDAO creates the billing subscription DAO.+func NewBillingSubscriptionDAO() *BillingSubscriptionDAO { return &BillingSubscriptionDAO{} }diff --git a/internal/dao/task_ee.go b/internal/dao/task_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/task_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/tenant_ee.go b/internal/dao/tenant_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/tenant_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/tenant_invite_ee.go b/internal/dao/tenant_invite_ee.godeleted file mode 100644index 7f356d2631..0000000000--- a/internal/dao/tenant_invite_ee.go+++ /dev/null@@ -1,29 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--import (- "context"-- "ragflow/internal/entity"-- "gorm.io/gorm"-)--func ApplyDefaultTenantInviteEnabled(context.Context, *gorm.DB, *entity.Tenant) error {- return nil-}diff --git a/internal/dao/tenant_model_group_ee.go b/internal/dao/tenant_model_group_ee.godeleted file mode 100644index 9e76679592..0000000000--- a/internal/dao/tenant_model_group_ee.go+++ /dev/null@@ -1,33 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--// TenantModelGroupDAO tenant model group data access object-type TenantModelGroupDAO struct{}--// NewTenantModelGroupDAO create tenant model group DAO-func NewTenantModelGroupDAO() *TenantModelGroupDAO {- return &TenantModelGroupDAO{}-}--// TenantModelGroupMapDAO tenant model group map data access object-type TenantModelGroupMapDAO struct{}--// NewTenantModelGroupMapDAO create tenant model group map DAO-func NewTenantModelGroupMapDAO() *TenantModelGroupMapDAO {- return &TenantModelGroupMapDAO{}-}diff --git a/internal/dao/tenant_role_ee.go b/internal/dao/tenant_role_ee.godeleted file mode 100644index 854bc9cafc..0000000000--- a/internal/dao/tenant_role_ee.go+++ /dev/null@@ -1,29 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package dao--import (- "context"-- "ragflow/internal/entity"-- "gorm.io/gorm"-)--func initializeTenantDefaultRoleEE(context.Context, *gorm.DB, *entity.Tenant) error {- return nil-}diff --git a/internal/dao/tenant_ee_test.go b/internal/dao/test_helpers_test.gosimilarity index 90%rename from internal/dao/tenant_ee_test.gorename to internal/dao/test_helpers_test.goindex 7a0a416010..f1d506f054 100644--- a/internal/dao/tenant_ee_test.go+++ b/internal/dao/test_helpers_test.go@@ -16,4 +16,5 @@package dao+// tenantDAOTestExtraModels adds no tables beyond the community schema.func tenantDAOTestExtraModels() []interface{} { return nil }diff --git a/internal/dao/user_canvas_ee.go b/internal/dao/user_canvas_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/user_canvas_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/user_ee.go b/internal/dao/user_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/user_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/dao/user_tenant_ee.go b/internal/dao/user_tenant_ee.godeleted file mode 100644index 0e180b9abc..0000000000--- a/internal/dao/user_tenant_ee.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package daodiff --git a/internal/engine/clickhouse/clickhouse_ee.go b/internal/engine/clickhouse/stub.gosimilarity index 58%rename from internal/engine/clickhouse/clickhouse_ee.gorename to internal/engine/clickhouse/stub.goindex ac0026684c..6579dbea37 100644--- a/internal/engine/clickhouse/clickhouse_ee.go+++ b/internal/engine/clickhouse/stub.go@@ -14,35 +14,24 @@// limitations under the License.//-package clickhouse+//go:build !ee-import (- "ragflow/internal/common"- "sync"-)+package clickhouse-var (- globalDriver *Driver- once sync.Once-)+import "ragflow/internal/common"-type Driver struct {-}+// Driver is the analytics sink. The OSS build never opens a ClickHouse+// connection, so every method drops what it is given.+type Driver struct{}-// GetDriver gets global stats client instance-func GetDriver() *Driver {- return globalDriver-}+// GetDriver returns the analytics sink, which the OSS build never creates.+func GetDriver() *Driver { return nil }-func (d *Driver) CollectModelUsage(modelUsage *common.ModelUsage) error {- //if modelUsage != nil {- // common.Info("CollectModelUsage", zap.Any("modelUsage", modelUsage.String()))- //}- return nil-}+// CollectModelUsage records token usage for analytics.+func (d *Driver) CollectModelUsage(modelUsage *common.ModelUsage) error { return nil }+// SaveOperationLog records an operation log entry.func (d *Driver) SaveOperationLog(operationLog *common.OperationLog) error { return nil }-func (d *Driver) Status() (map[string]interface{}, error) {- return nil, nil-}+// Status reports the analytics backend health.+func (d *Driver) Status() (map[string]interface{}, error) { return nil, nil }diff --git a/internal/entity/base.go b/internal/entity/base.goindex 97bf4bc385..1b3b3568f0 100644--- a/internal/entity/base.go+++ b/internal/entity/base.go@@ -184,3 +184,8 @@ func (j *JSONSlice) Scan(value interface{}) error {}return json.Unmarshal(b, j)}++// GormDataType tells GORM how to create a JSONSlice column.+func (j *JSONSlice) GormDataType() string {+ return "longtext"+}diff --git a/internal/entity/permission_change_log_ee.go b/internal/entity/permission_change_log_ee.godeleted file mode 100644index fc35ea7f18..0000000000--- a/internal/entity/permission_change_log_ee.go+++ /dev/null@@ -1,24 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package entity--// PermissionChangeLog is a test-only placeholder in the community edition.-type PermissionChangeLog struct {- BaseModel-}--func (PermissionChangeLog) TableName() string { return "permission_change_log" }diff --git a/internal/entity/permission_ee.go b/internal/entity/permission_ee.godeleted file mode 100644index 868e4c087a..0000000000--- a/internal/entity/permission_ee.go+++ /dev/null@@ -1,23 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package entity--const (- TenantPermissionManageMembers int32 = 1 << iota- TenantPermissionManageRoles- TenantPermissionOwner-)diff --git a/internal/admin/user_detail_ee_test.go b/internal/entity/stub.gosimilarity index 69%rename from internal/admin/user_detail_ee_test.gorename to internal/entity/stub.goindex 9edb6e4014..112654462d 100644--- a/internal/admin/user_detail_ee_test.go+++ b/internal/entity/stub.go@@ -14,10 +14,14 @@// limitations under the License.//-package admin+//go:build !ee-import "testing"+package entity-func TestUserAgentsRouteRequiresEE(_ *testing.T) {}--func TestUserDatasetsRouteRequiresEE(_ *testing.T) {}+// Tenant permission bits. The OSS build only ships the built-in tenant roles,+// so these are accepted by shared call sites and never granted.+const (+ TenantPermissionManageMembers int32 = 1 << iota+ TenantPermissionManageRoles+ TenantPermissionOwner+)diff --git a/internal/handler/agent.go b/internal/handler/agent.goindex 95fbd47de4..6aef2957c2 100644--- a/internal/handler/agent.go+++ b/internal/handler/agent.go@@ -292,6 +292,14 @@ func mapAgentError(err error) (common.ErrorCode, string) {// @Success 200 {object} entity.UserCanvas// @Router /api/v1/agents [post]func (h *AgentHandler) CreateAgent(c *gin.Context) {+ quotaUser, ok := billingQuotaUser(c)+ if !ok {+ return+ }+ if !billingEnforceApps(c, quotaUser.ID) {+ return+ }+user, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.ErrorWithCode(c, errorCode, errorMessage)diff --git a/internal/handler/auth.go b/internal/handler/auth.goindex 718464a39e..52757a82ec 100644--- a/internal/handler/auth.go+++ b/internal/handler/auth.go@@ -25,10 +25,23 @@ import ("ragflow/internal/permission""ragflow/internal/server/local""ragflow/internal/service"+ "ragflow/internal/service/billing""github.com/gin-gonic/gin")+// billingAllowsAPIToken applies the paid-plan gate for API key holders across+// every authentication path. The plan belongs to the token's tenant, not to+// the user record it resolves to.+func billingAllowsAPIToken(ctx context.Context, tenantID string) bool {+ service := billing.Get()+ if service == nil || !service.Enabled() {+ return true+ }+ allowed, err := service.APIAuthAllowed(ctx, tenantID)+ return err == nil && allowed+}+// AuthHandler auth handlertype AuthHandler struct {userService userTokenResolver@@ -44,9 +57,15 @@ func (h *AuthHandler) ResolveMCPUser(ctx context.Context, authorization string)return identity.User, nil}if identity, code, err := h.userService.ResolveAPIToken(ctx, authorization); err == nil && code == common.CodeSuccess {+ if !billingAllowsAPIToken(ctx, identity.TenantID) {+ return nil, fmt.Errorf("API key requires a Starter or Pro plan")+ }return identity.User, nil}if identity, code, err := h.userService.ResolveBetaAPIToken(ctx, authorization); err == nil && code == common.CodeSuccess {+ if !billingAllowsAPIToken(ctx, identity.TenantID) {+ return nil, fmt.Errorf("API key requires a Starter or Pro plan")+ }return identity.User, nil}return nil, fmt.Errorf("invalid authorization")@@ -105,6 +124,11 @@ func (h *AuthHandler) BetaAuthMiddleware() gin.HandlerFunc {}// Then try a regular API token (non-beta public bot flow).if identity, code, err := h.userService.ResolveAPIToken(ctx, auth); err == nil && code == common.CodeSuccess {+ if !billingAllowsAPIToken(ctx, identity.TenantID) {+ common.ResponseWithCodeData(c, common.CodePermissionError, nil, "API key requires a Starter or Pro plan")+ c.Abort()+ return+ }setAuthIdentity(c, identity)c.Set("auth_via_api_token", true)c.Next()@@ -112,6 +136,11 @@ func (h *AuthHandler) BetaAuthMiddleware() gin.HandlerFunc {}// Fall back to beta API token (public bot access).if identity, code, err := h.userService.ResolveBetaAPIToken(ctx, auth); err == nil && code == common.CodeSuccess {+ if !billingAllowsAPIToken(ctx, identity.TenantID) {+ common.ResponseWithCodeData(c, common.CodePermissionError, nil, "API key requires a Starter or Pro plan")+ c.Abort()+ return+ }setAuthIdentity(c, identity)c.Set("auth_via_beta_token", true)if identity.APIToken != nil && identity.APIToken.DialogID != nil {@@ -151,6 +180,23 @@ func (h *AuthHandler) AuthMiddleware() gin.HandlerFunc {authViaAPIToken = true}+ // API keys are a paid capability: Trial tenants must upgrade first.+ if authViaAPIToken {+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ allowed, gateErr := billingService.APIAuthAllowed(ctx, identity.TenantID)+ if gateErr != nil {+ common.ResponseWithHttpCodeData(c, http.StatusForbidden, common.CodeForbidden, nil, gateErr.Error())+ c.Abort()+ return+ }+ if !allowed {+ common.ResponseWithHttpCodeData(c, http.StatusForbidden, common.CodeForbidden, nil, "API key requires a Starter or Pro plan")+ c.Abort()+ return+ }+ }+ }+if identity.User.IsSuperuser != nil && *identity.User.IsSuperuser {common.ResponseWithHttpCodeData(c, http.StatusForbidden, common.CodeForbidden, nil, "Super user shouldn't access the URL")c.Abort()diff --git a/internal/handler/chat.go b/internal/handler/chat.goindex 825cc25fce..2434290e0b 100644--- a/internal/handler/chat.go+++ b/internal/handler/chat.go@@ -149,6 +149,14 @@ func (h *ChatHandler) ListChats(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/chats [post]func (h *ChatHandler) Create(c *gin.Context) {+ quotaUser, ok := billingQuotaUser(c)+ if !ok {+ return+ }+ if !billingEnforceApps(c, quotaUser.ID) {+ return+ }+user, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.ErrorWithCode(c, errorCode, errorMessage)diff --git a/internal/handler/dataset.go b/internal/handler/dataset.goindex c022b85058..57d98c4af4 100644--- a/internal/handler/dataset.go+++ b/internal/handler/dataset.go@@ -19,6 +19,7 @@ package handlerimport ("context""encoding/json"+ "errors""fmt""net/http""ragflow/internal/engine"@@ -32,6 +33,7 @@ import ("ragflow/internal/common""ragflow/internal/permission""ragflow/internal/service"+ "ragflow/internal/service/billing"dataset "ragflow/internal/service/dataset")@@ -272,6 +274,25 @@ func (h *DatasetsHandler) CreateDataset(c *gin.Context) {if tenantID == "" {tenantID = user.ID}++ // Application quota: every new dataset counts as one app, matching+ // Python's check_dynamic_resources(apps=1).+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ if quotaErr := billingService.CheckResources(ctx, tenantID, billing.ResourceDelta{Apps: 1}); quotaErr != nil {+ var insufficient *billing.InsufficientResourceError+ if errors.As(quotaErr, &insufficient) {+ common.ResponseWithDetail(c, common.CodeBillingAppsInsufficient, quotaErr.Error(), gin.H{+ "resource": "apps",+ "current": insufficient.Current,+ "limit": insufficient.Limit,+ })+ return+ }+ common.ErrorWithCode(c, common.CodeServerError, quotaErr.Error())+ return+ }+ }+result, code, err := h.datasetsService.CreateDataset(ctx, &req, permission.Subject{UserID: user.ID,TenantID: tenantID,diff --git a/internal/handler/document.go b/internal/handler/document.goindex 8254fb92f6..4d5068d6eb 100644--- a/internal/handler/document.go+++ b/internal/handler/document.go@@ -40,6 +40,7 @@ import ("ragflow/internal/dao""ragflow/internal/service"+ "ragflow/internal/service/billing""ragflow/internal/service/dataset""ragflow/internal/service/document")@@ -1020,6 +1021,15 @@ func (h *DocumentHandler) uploadLocalDocuments(c *gin.Context, kb *entity.Knowlereturn}files := form.File["file"]+ var totalSize int64+ for _, fh := range files {+ if fh != nil {+ totalSize += fh.Size+ }+ }+ if !billingEnforceStorage(c, tenantID, totalSize) {+ return+ }for _, fh := range files {if fh == nil || fh.Filename == "" {common.ResponseWithCodeData(c, common.CodeArgumentError, nil,@@ -1694,6 +1704,33 @@ func (h *DocumentHandler) UploadInfo(c *gin.Context) {}ctx := c.Request.Context()++ // Storage quota: reject the whole upload before any file is persisted.+ if len(fileHeaders) > 0 {+ var totalSize int64+ for _, header := range fileHeaders {+ totalSize += header.Size+ }+ if totalSize > 0 {+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ if quotaErr := billingService.CheckResources(ctx, user.ID, billing.ResourceDelta{Storage: totalSize}); quotaErr != nil {+ var insufficient *billing.InsufficientResourceError+ if errors.As(quotaErr, &insufficient) {+ common.ResponseWithDetail(c, common.CodeBillingStorageInsufficient, quotaErr.Error(), gin.H{+ "resource": "storage",+ "current": insufficient.Current,+ "limit": insufficient.Limit,+ "filename": fileHeaders[0].Filename,+ })+ return+ }+ common.ErrorWithCode(c, common.CodeServerError, quotaErr.Error())+ return+ }+ }+ }+ }+if rawURL != "" {data, code, err := h.fileService.UploadDocumentInfoByURL(ctx, user.ID, rawURL)if err != nil {diff --git a/internal/handler/file.go b/internal/handler/file.goindex 836a197954..305999c858 100644--- a/internal/handler/file.go+++ b/internal/handler/file.go@@ -260,6 +260,15 @@ func (h *FileHandler) UploadFile(c *gin.Context) {common.ResponseWithCodeData(c, common.CodeBadRequest, nil, "No file part!")return}+ var totalSize int64+ for _, headers := range form.File {+ for _, header := range headers {+ totalSize += header.Size+ }+ }+ if !billingEnforceStorage(c, userID, totalSize) {+ return+ }parentID := c.PostForm("parent_id")if parentID == "" {tenantID := strings.TrimSpace(c.GetString("tenant_id"))diff --git a/internal/handler/memory.go b/internal/handler/memory.goindex bcb32ed21f..5faf2a7d8a 100644--- a/internal/handler/memory.go+++ b/internal/handler/memory.go@@ -82,6 +82,14 @@ func NewMemoryHandler(memoryService *service.MemoryService) *MemoryHandler {// 3. Call service layer to create memory// 4. Return creation resultfunc (h *MemoryHandler) CreateMemory(c *gin.Context) {+ quotaUser, ok := billingQuotaUser(c)+ if !ok {+ return+ }+ if !billingEnforceApps(c, quotaUser.ID) {+ return+ }+// Check if API timing is enabled// If RAGFLOW_API_TIMING environment variable is set, request processing time will be loggedtimingEnabled := common.GetEnv(common.EnvRAGFlowAPITiming)diff --git a/internal/handler/providers_ee.go b/internal/handler/providers_ee.godeleted file mode 100644index 32842b4ec2..0000000000--- a/internal/handler/providers_ee.go+++ /dev/null@@ -1,48 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package handler--import (- "ragflow/internal/common"-- "github.com/gin-gonic/gin"-)--func (h *ProviderHandler) CreateModelGroup(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "CreateModelGroup not implemented")- return-}--func (h *ProviderHandler) DeleteModelGroup(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "DeleteModelGroup not implemented")- return-}--func (h *ProviderHandler) ShowModelGroup(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "ShowModelGroup not implemented")- return-}--func (h *ProviderHandler) AddModelToGroup(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "AddModelToGroup not implemented")- return-}--func (h *ProviderHandler) RemoveModelFromGroup(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "RemoveModelFromGroup not implemented")- return-}diff --git a/internal/handler/search.go b/internal/handler/search.goindex 72d40a7998..7a1bba35dd 100644--- a/internal/handler/search.go+++ b/internal/handler/search.go@@ -159,6 +159,14 @@ type CreateSearchRequest struct {}func (h *SearchHandler) CreateSearch(c *gin.Context) {+ quotaUser, ok := billingQuotaUser(c)+ if !ok {+ return+ }+ if !billingEnforceApps(c, quotaUser.ID) {+ return+ }+// Get current user from context (same as Python current_user)user, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {diff --git a/internal/handler/stats_ee.go b/internal/handler/stats_ee.godeleted file mode 100644index f9f6401ae6..0000000000--- a/internal/handler/stats_ee.go+++ /dev/null@@ -1,31 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package handler--import (- "ragflow/internal/common"-- "github.com/gin-gonic/gin"-)--func (h *StatsHandler) GetModelStats(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "GetModelStats not implemented")-}--func (h *StatsHandler) GetGroupStats(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "GetGroupStats not implemented")-}diff --git a/internal/handler/stub.go b/internal/handler/stub.gonew file mode 100644index 0000000000..3f711bc7ae--- /dev/null+++ b/internal/handler/stub.go@@ -0,0 +1,84 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package handler++import (+ "errors"++ "ragflow/internal/common"+ "ragflow/internal/entity"++ "github.com/gin-gonic/gin"+)++// billingQuotaUser resolves the caller that the plan quota applies to.+func billingQuotaUser(c *gin.Context) (*entity.User, bool) {+ user, code, message := GetUser(c)+ if code != common.CodeSuccess {+ common.ErrorWithCode(c, code, message)+ return nil, false+ }+ return user, true+}++// billingEnforceApps admits every new application: the community edition has+// no plan quota.+func billingEnforceApps(_ *gin.Context, _ string) bool { return true }++// billingEnforceStorage admits every upload: the community edition has no+// storage quota.+func billingEnforceStorage(_ *gin.Context, _ string, _ int64) bool { return true }++// issueUserAccessToken mints the access token returned after a successful+// login.+func issueUserAccessToken(user *entity.User, secretKey string) (string, error) {+ if user == nil || user.AccessToken == nil {+ return "", errors.New("user access token is missing")+ }+ return common.DumpAccessToken(*user.AccessToken, "", secretKey)+}++// eeNotImplemented answers an enterprise-only endpoint in the community+// edition. The route stays registered so clients see "not implemented" rather+// than "not found".+func eeNotImplemented(c *gin.Context, feature string) {+ common.ErrorWithCode(c, common.CodeNotImplemented, feature+" not implemented")+}++func (h *SystemHandler) GetEnableAdmin(c *gin.Context) { eeNotImplemented(c, "EnableAdmin") }+func (h *SystemHandler) GetCores(c *gin.Context) { eeNotImplemented(c, "Get cores") }+func (h *SystemHandler) SetCores(c *gin.Context) { eeNotImplemented(c, "Set cores") }+func (h *SystemHandler) GetMemory(c *gin.Context) { eeNotImplemented(c, "Get memory") }+func (h *SystemHandler) SetMemory(c *gin.Context) { eeNotImplemented(c, "Set memory") }+func (h *SystemHandler) GetConcurrency(c *gin.Context) { eeNotImplemented(c, "Get concurrency") }+func (h *SystemHandler) SetConcurrency(c *gin.Context) { eeNotImplemented(c, "Set concurrency") }+func (h *SystemHandler) GetQuota(c *gin.Context) { eeNotImplemented(c, "Get quota") }++func (h *UserHandler) IsAdmin(c *gin.Context) { eeNotImplemented(c, "IsAdmin") }+func (h *UserHandler) GetMeta(c *gin.Context) { eeNotImplemented(c, "GetMeta") }+func (h *ProviderHandler) CreateModelGroup(c *gin.Context) { eeNotImplemented(c, "CreateModelGroup") }+func (h *ProviderHandler) DeleteModelGroup(c *gin.Context) { eeNotImplemented(c, "DeleteModelGroup") }+func (h *ProviderHandler) ShowModelGroup(c *gin.Context) { eeNotImplemented(c, "ShowModelGroup") }+func (h *ProviderHandler) AddModelToGroup(c *gin.Context) { eeNotImplemented(c, "AddModelToGroup") }+func (h *ProviderHandler) RemoveModelFromGroup(c *gin.Context) {+ eeNotImplemented(c, "RemoveModelFromGroup")+}++func (h *StatsHandler) GetModelStats(c *gin.Context) { eeNotImplemented(c, "GetModelStats") }+func (h *StatsHandler) GetGroupStats(c *gin.Context) { eeNotImplemented(c, "GetGroupStats") }diff --git a/internal/handler/system_ee.go b/internal/handler/system_ee.godeleted file mode 100644index e253bd6c90..0000000000--- a/internal/handler/system_ee.go+++ /dev/null@@ -1,67 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package handler--import (- "ragflow/internal/common"-- "github.com/gin-gonic/gin"-)--// GetEnableAdmin admin access endpoint-// @Description Enable admin access endpoint-// @Tags system-// @Produce plain-// @Router /api/v1/system/enable-admin [GET]-func (h *SystemHandler) GetEnableAdmin(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "EnableAdmin not implemented")-}--// GetCores /api/v1/system/cores [GET]-func (h *SystemHandler) GetCores(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Get cores not implemented")-}--// SetCores /api/v1/system/cores [PUT]-func (h *SystemHandler) SetCores(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Set cores not implemented")-}--// GetMemory /api/v1/system/memory [GET]-func (h *SystemHandler) GetMemory(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Get memory not implemented")-}--// SetMemory /api/v1/system/memory [PUT]-func (h *SystemHandler) SetMemory(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Set memory not implemented")-}--// GetConcurrency /api/v1/system/concurrency [GET]-func (h *SystemHandler) GetConcurrency(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Get concurrency not implemented")-}--// SetConcurrency /api/v1/system/concurrency [PUT]-func (h *SystemHandler) SetConcurrency(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Set concurrency not implemented")-}--// GetQuota /api/v1/system/quota [GET]-func (h *SystemHandler) GetQuota(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Get quota not implemented")-}diff --git a/internal/handler/user_auth_ee.go b/internal/handler/user_auth_ee.godeleted file mode 100644index 2b164d12bb..0000000000--- a/internal/handler/user_auth_ee.go+++ /dev/null@@ -1,52 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package handler--import (- "fmt"- "ragflow/internal/common"- "ragflow/internal/entity"-- "github.com/gin-gonic/gin"-)--func (h *UserHandler) Captcha(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "Captcha not implemented")-}--func (h *UserHandler) SendOTP(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "SendOTP not implemented")-}--func (h *UserHandler) VerifyOTP(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "VerifyOTP not implemented")-}--func (h *UserHandler) IsAdmin(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "IsAdmin not implemented")-}--func (h *UserHandler) GetMeta(c *gin.Context) {- common.ErrorWithCode(c, common.CodeNotImplemented, "GetMeta not implemented")-}--func issueUserAccessToken(user *entity.User, secretKey string) (string, error) {- if user == nil || user.AccessToken == nil {- return "", fmt.Errorf("user access token is missing")- }- return common.DumpAccessToken(*user.AccessToken, "", secretKey)-}diff --git a/internal/ingestion/component/parser.go b/internal/ingestion/component/parser.goindex a262a9d56b..33791d9ec1 100644--- a/internal/ingestion/component/parser.go+++ b/internal/ingestion/component/parser.go@@ -91,6 +91,7 @@ import ("ragflow/internal/ingestion/component/progress""ragflow/internal/ingestion/component/schema""ragflow/internal/parser/parser"+ "ragflow/internal/service/billing""ragflow/internal/utility")@@ -563,6 +564,24 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st}lang, _ := getString(inputs, "lang")out := buildParserOutputs(ctx, dispatched, filename, binary, lang)++ // Parse billing: DeepDOC PDFs are metered per page after a successful+ // parse. A shortage fails the run, matching the Python hold contract.+ if tenantID, _ := getString(inputs, "tenant_id"); tenantID != "" && docID != "" && fileTypeExt == utility.FileTypePDF {+ if pdfSetup, ok := c.setups["pdf"]; ok {+ if method, _ := pdfSetup["parse_method"].(string); strings.Contains(strings.ToUpper(method), "DEEPDOC") {+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ if runKey := parseRunKey(ctx); runKey != "" {+ if pageCount := parserPageCount(dispatched.File); pageCount > 0 {+ if chargeErr := billingService.ChargeParsedDocument(ctx, tenantID, docID, runKey, pageCount, true); chargeErr != nil {+ return nil, chargeErr+ }+ }+ }+ }+ }+ }+ }out["file_type"] = string(fileTypeExt)// Forward the storage references so a downstream chunker can// re-acquire the source PDF and crop section images on demand,@@ -708,3 +727,31 @@ func init() {Outputs: pc.Outputs(),})}++// parserPageCount extracts page_count from parser metadata.+func parserPageCount(file map[string]any) int64 {+ if file == nil {+ return 0+ }+ switch value := file["page_count"].(type) {+ case int:+ return int64(value)+ case int64:+ return value+ case float64:+ return int64(value)+ default:+ return 0+ }+}++// parseRunKey returns the billing identity of this parse attempt. The ingestion+// task id is stable across checkpoint resume and component replay, so a retried+// run charges once; only runs without a task scope fall back to a fresh id.+func parseRunKey(ctx context.Context) string {+ if taskID := globals.TaskID(ctx); taskID != "" {+ return "task:" + taskID+ }+ // No task scope means a debug/dry-run preview: nothing is metered.+ return ""+}diff --git a/internal/permission/policy_ee.go b/internal/permission/policy_ee.godeleted file mode 100644index 3c039347fb..0000000000--- a/internal/permission/policy_ee.go+++ /dev/null@@ -1,22 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package permission--// Community Edition has no alternate permission policy.-func newPolicyEE(Source) (policy, bool) {- return nil, false-}diff --git a/internal/permission/stub.go b/internal/permission/stub.gonew file mode 100644index 0000000000..d856a7d5f7--- /dev/null+++ b/internal/permission/stub.go@@ -0,0 +1,39 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package permission++import (+ "context"++ "gorm.io/gorm"+)++// newPolicyEE reports that the OSS build has no enterprise policy: the caller+// falls back to communityPolicy.+func newPolicyEE(Source) (policy, bool) { return nil, false }++// tenantRoleMembershipEnabled reports whether tenant roles are stored as+// numeric IDs. The OSS build only stores the built-in roles.+func tenantRoleMembershipEnabled(db *gorm.DB) bool { return false }++// isTenantRoleID reports whether roleValue names an enterprise tenant role.+// The OSS build has none.+func isTenantRoleID(ctx context.Context, db *gorm.DB, tenantID, roleValue string) (bool, error) {+ return false, nil+}diff --git a/internal/permission/tenant_role_ee.go b/internal/permission/tenant_role_ee.godeleted file mode 100644index 4832542960..0000000000--- a/internal/permission/tenant_role_ee.go+++ /dev/null@@ -1,32 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package permission--import (- "context"-- "gorm.io/gorm"-)--// Community memberships use the legacy string roles and have no Tenant role table.-func tenantRoleMembershipEnabled(*gorm.DB) bool {- return false-}--func isTenantRoleID(context.Context, *gorm.DB, string, string) (bool, error) {- return false, nil-}diff --git a/internal/router/router.go b/internal/router/router.goindex 50c3f725cc..6a7c1c8dc0 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -194,7 +194,7 @@ func (r *Router) Setup(engine *gin.Engine) {RegisterPublicAgentWebhookRoutes(apiNoAuth.Group("/agents"), r.agentHandler)- RegisterEENoAuthRouter(apiNoAuth, r)+ RegisterEENoAuthRouter(engine, apiNoAuth, r)}// Beta-token routes. Mirrors python's@@ -241,6 +241,7 @@ func (r *Router) Setup(engine *gin.Engine) {authorized := engine.Group("")authorized.Use(r.authHandler.AuthMiddleware())RegisterEEProtectedRouter(authorized, r)+ RegisterEEAuthRouter(authorized, r){// API v1 route groupv1 := authorized.Group("/api/v1")diff --git a/internal/router/router_ee.go b/internal/router/router_ee.godeleted file mode 100644index ffa8835e7f..0000000000--- a/internal/router/router_ee.go+++ /dev/null@@ -1,93 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package router--import (- "github.com/gin-gonic/gin"-)--func SetupEERouter(engine *gin.Engine) {-}--func RegisterEENoAuthRouter(apiNoAuth *gin.RouterGroup, r *Router) {- // For EE- apiNoAuth.POST("/auth/register/captcha", r.userHandler.Captcha)- apiNoAuth.POST("/auth/register/otp", r.userHandler.SendOTP)- apiNoAuth.POST("/auth/register/otp/verify", r.userHandler.VerifyOTP)-}--func RegisterEEProtectedRouter(_ *gin.RouterGroup, _ *Router) {}--func ToggleWorkflow() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleChat() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleFile() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleSearch() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleModel() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleUserInTenant() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleGroup() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleEvaluation() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleDataset() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}--func ToggleMemory() gin.HandlerFunc {- return func(c *gin.Context) {- c.Next()- }-}diff --git a/internal/router/stub.go b/internal/router/stub.gonew file mode 100644index 0000000000..58aff1a56c--- /dev/null+++ b/internal/router/stub.go@@ -0,0 +1,52 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package router++import "github.com/gin-gonic/gin"++// SetupEERouter adds no enterprise middleware in the community edition.+func SetupEERouter(engine *gin.Engine) {}++// RegisterEENoAuthRouter keeps the unauthenticated enterprise endpoints+// registered so clients see "not implemented" instead of "not found".+// RegisterEEProtectedRouter registers no authenticated enterprise routes in+// the community edition.+// RegisterEENoAuthRouter registers no enterprise auth routes in the community+// edition.+func RegisterEENoAuthRouter(_ *gin.Engine, _ *gin.RouterGroup, _ *Router) {}++func RegisterEEProtectedRouter(_ *gin.RouterGroup, _ *Router) {}++// RegisterEEAuthRouter registers no enterprise auth routes in the community+// edition.+func RegisterEEAuthRouter(_ *gin.RouterGroup, _ *Router) {}++// allowAll is the community gate for a feature toggle: every request passes.+func allowAll() gin.HandlerFunc {+ return func(c *gin.Context) {+ c.Next()+ }+}++func ToggleChat() gin.HandlerFunc { return allowAll() }+func ToggleDataset() gin.HandlerFunc { return allowAll() }+func ToggleSearch() gin.HandlerFunc { return allowAll() }+func ToggleFile() gin.HandlerFunc { return allowAll() }+func ToggleMemory() gin.HandlerFunc { return allowAll() }+func ToggleModel() gin.HandlerFunc { return allowAll() }diff --git a/internal/server/config/billing_ee.go b/internal/server/config/billing_ee.godeleted file mode 100644index f5ecb03be1..0000000000--- a/internal/server/config/billing_ee.go+++ /dev/null@@ -1,26 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package config--import "github.com/spf13/viper"--type BillingConfig struct {-}--func (c *Config) ParseBillingConfig(v *viper.Viper) error {- return nil-}diff --git a/internal/server/config/model_config_ee.go b/internal/server/config/model_config_ee.godeleted file mode 100644index 504991a3f0..0000000000--- a/internal/server/config/model_config_ee.go+++ /dev/null@@ -1,70 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package config--import "github.com/spf13/viper"--// DefaultModelsConfig default models configuration-type DefaultModelsConfig struct {- ChatModel ModelConfig `mapstructure:"chat_model"`- EmbeddingModel ModelConfig `mapstructure:"embedding_model"`- RerankModel ModelConfig `mapstructure:"rerank_model"`- ASRModel ModelConfig `mapstructure:"asr_model"`- VisionModel ModelConfig `mapstructure:"vision_model"`- OCRModel ModelConfig `mapstructure:"ocr_model"`- TTSModel ModelConfig `mapstructure:"tts_model"`-}--// ModelConfig model configuration-type ModelConfig struct {- Name string `mapstructure:"name"`- APIKey string `mapstructure:"api_key"`- BaseURL string `mapstructure:"base_url"`- Factory string `mapstructure:"factory"`-}--func (c *Config) ParseDefaultModelsConfig(v *viper.Viper) error {- return nil-}--func (c *Config) GetDefaultChatModel() ModelConfig {- return c.defaultModels.ChatModel-}--func (c *Config) GetDefaultEmbeddingModel() ModelConfig {- return c.defaultModels.EmbeddingModel-}--func (c *Config) GetDefaultRerankModel() ModelConfig {- return c.defaultModels.RerankModel-}--func (c *Config) GetDefaultASRModel() ModelConfig {- return c.defaultModels.ASRModel-}--func (c *Config) GetDefaultVisionModel() ModelConfig {- return c.defaultModels.VisionModel-}--func (c *Config) GetDefaultOCRModel() ModelConfig {- return c.defaultModels.OCRModel-}--func (c *Config) GetDefaultTTSModel() ModelConfig {- return c.defaultModels.TTSModel-}diff --git a/internal/server/config/stub.go b/internal/server/config/stub.gonew file mode 100644index 0000000000..6baaf9a161--- /dev/null+++ b/internal/server/config/stub.go@@ -0,0 +1,84 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package config++import "github.com/spf13/viper"++// ModelConfig is one model chosen as a deployment default.+type ModelConfig struct {+ Name string `mapstructure:"name"`+ APIKey string `mapstructure:"api_key"`+ BaseURL string `mapstructure:"base_url"`+ Factory string `mapstructure:"factory"`+}++// DefaultModelsConfig carries the per-deployment default models. The OSS build+// leaves every slot empty.+type DefaultModelsConfig struct {+ ChatModel ModelConfig `mapstructure:"chat_model"`+ EmbeddingModel ModelConfig `mapstructure:"embedding_model"`+ RerankModel ModelConfig `mapstructure:"rerank_model"`+ ASRModel ModelConfig `mapstructure:"asr_model"`+ VisionModel ModelConfig `mapstructure:"vision_model"`+ OCRModel ModelConfig `mapstructure:"ocr_model"`+ TTSModel ModelConfig `mapstructure:"tts_model"`+}++// BillingConfig carries the billing deployment settings. The OSS build has no+// billing.+type BillingConfig struct{}++// GetBillingConfig returns the billing settings, which the OSS build leaves+// empty.+func (c *Config) GetBillingConfig() BillingConfig {+ return c.billing+}++// ParseBillingConfig ignores billing configuration: the OSS build has no+// billing.+func (c *Config) ParseBillingConfig(v *viper.Viper) error { return nil }++// ParseDefaultModelsConfig ignores deployment model defaults: the OSS build+// has none.+func (c *Config) ParseDefaultModelsConfig(v *viper.Viper) error { return nil }++// GetDefaultChatModel returns the deployment chat model, empty in the OSS+// build.+func (c *Config) GetDefaultChatModel() ModelConfig { return c.defaultModels.ChatModel }++// GetDefaultEmbeddingModel returns the deployment embedding model, empty in the+// OSS build.+func (c *Config) GetDefaultEmbeddingModel() ModelConfig { return c.defaultModels.EmbeddingModel }++// GetDefaultRerankModel returns the deployment rerank model, empty in the OSS+// build.+func (c *Config) GetDefaultRerankModel() ModelConfig { return c.defaultModels.RerankModel }++// GetDefaultASRModel returns the deployment ASR model, empty in the OSS build.+func (c *Config) GetDefaultASRModel() ModelConfig { return c.defaultModels.ASRModel }++// GetDefaultVisionModel returns the deployment vision model, empty in the OSS+// build.+func (c *Config) GetDefaultVisionModel() ModelConfig { return c.defaultModels.VisionModel }++// GetDefaultOCRModel returns the deployment OCR model, empty in the OSS build.+func (c *Config) GetDefaultOCRModel() ModelConfig { return c.defaultModels.OCRModel }++// GetDefaultTTSModel returns the deployment TTS model, empty in the OSS build.+func (c *Config) GetDefaultTTSModel() ModelConfig { return c.defaultModels.TTSModel }diff --git a/internal/server/local/admin_status_ee.go b/internal/server/local/stub.gosimilarity index 78%rename from internal/server/local/admin_status_ee.gorename to internal/server/local/stub.goindex d87a61f9a0..99126b1a18 100644--- a/internal/server/local/admin_status_ee.go+++ b/internal/server/local/stub.go@@ -14,8 +14,10 @@// limitations under the License.//+//go:build !ee+package local-func IsAdminAvailable() bool {- return true-}+// IsAdminAvailable reports whether the admin server may serve requests. The+// community edition runs without one.+func IsAdminAvailable() bool { return true }diff --git a/internal/server/server_ee.go b/internal/server/stub.gosimilarity index 65%rename from internal/server/server_ee.gorename to internal/server/stub.goindex 52fb1c07af..5ac1c3d6ab 100644--- a/internal/server/server_ee.go+++ b/internal/server/stub.go@@ -14,41 +14,22 @@// limitations under the License.//+//go:build !ee+package serverimport ("context"- "errors"- "ragflow/internal/common"- sdktrace "go.opentelemetry.io/otel/sdk/trace"+ "ragflow/internal/common")-var serverEE *EEServer--func init() {- serverEE = newEEServer()-}--type EEServer struct {- tracerProvider *sdktrace.TracerProvider-}--func newEEServer() *EEServer {- return &EEServer{}-}-+// StartServer starts the enterprise services attached to a server process.+// The community edition runs none of them.func StartServer(ctx context.Context, cancel context.CancelFunc, serverName string, serverType common.ServerType) error {- if serverEE == nil {- return errors.New("server EE is nil")- }-return nil}-func ShutdownServer(ctx context.Context) error {- if serverEE == nil {- return errors.New("server EE is nil")- }- return nil-}+// ShutdownServer stops the enterprise services attached to a server process.+// The community edition runs none of them.+func ShutdownServer(ctx context.Context) error { return nil }diff --git a/internal/service/admin_client_ee.go b/internal/service/admin_client_ee.godeleted file mode 100644index cf3336c1b8..0000000000--- a/internal/service/admin_client_ee.go+++ /dev/null@@ -1,28 +0,0 @@-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package service--import "ragflow/internal/common"--func (h *AdminClient) InitHTTPClientEE() error {- return nil-}--func (h *AdminClient) EnrichMessage(message *common.BaseMessage) (*common.BaseMessage, error) {- return message, nil-}--func (h *AdminClient) UpdateClient(clientInfo interface{}) error { return nil }diff --git a/internal/service/agent_creation_ee.go b/internal/service/agent_creation_ee.godeleted file mode 100644index c3ba4520fa..0000000000--- a/internal/service/agent_creation_ee.go+++ /dev/null@@ -1,21 +0,0 @@-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package service--import "context"--func prepareAgentCreation(_ context.Context, userID string) (string, error) {- return userID, nil-}diff --git a/internal/service/api_token.go b/internal/service/api_token.goindex 691f85e938..3b39579ad6 100644--- a/internal/service/api_token.go+++ b/internal/service/api_token.go@@ -22,6 +22,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/service/billing""time")@@ -108,6 +109,9 @@ func (s *SystemService) CreateAPIKey(ctx context.Context, userID, tenantID strinif err := APITokenDAO.Create(ctx, dao.DB, APIKeyData); err != nil {return nil, err}+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ billingService.SyncAPITokenAccess(ctx, tenantID, APIToken, betaAPIKey)+ }return &APIKeyResponse{UserID: userID,@@ -133,5 +137,10 @@ func apiTokenUserID(value *string) string {func (s *SystemService) DeleteAPIKey(ctx context.Context, tenantID, key string) error {APITokenDAO := dao.NewAPITokenDAO()_, err := APITokenDAO.DeleteByTenantIDAndToken(ctx, dao.DB, tenantID, key)+ if err == nil {+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ billingService.DeleteRateLimitKeys(ctx, key)+ }+ }return err}diff --git a/internal/service/billing/stub.go b/internal/service/billing/stub.gonew file mode 100644index 0000000000..d510403e16--- /dev/null+++ b/internal/service/billing/stub.go@@ -0,0 +1,93 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package billing++import (+ "context"+ "fmt"++ "ragflow/internal/server/config"+)++// Service is the billing facade. The OSS build never enables it, so every+// method is a no-op and Get returns nil; call sites stay identical to the EE+// build.+type Service struct{}++// ResourceDelta is the resource increment a call site wants to reserve.+type ResourceDelta struct {+ Apps int64+ Members int64+ Storage int64+}++// InsufficientResourceError reports a quota breach with the values the upgrade+// prompt renders.+type InsufficientResourceError struct {+ Resource string+ Current int64+ Limit int64+ Required int64+}++func (e *InsufficientResourceError) Error() string {+ return fmt.Sprintf("%s limit reached: current %d, limit %d, requested %d", e.Resource, e.Current, e.Limit, e.Required)+}++// Init is a no-op: billing is an enterprise capability.+func Init(ctx context.Context, cfg config.BillingConfig) error { return nil }++// Start is a no-op: billing is an enterprise capability.+func Start(ctx context.Context) error { return nil }++// Get returns the billing service, which the OSS build never creates.+func Get() *Service { return nil }++// Enabled reports whether billing is active. The OSS build never enables it.+func (s *Service) Enabled() bool { return false }++// CheckResources reports a quota breach, which cannot happen without billing.+func (s *Service) CheckResources(ctx context.Context, tenantID string, delta ResourceDelta) error {+ return nil+}++// SyncLoginTokenRateLimit applies the tenant plan to a freshly issued login+// token.+func (s *Service) SyncLoginTokenRateLimit(ctx context.Context, tenantID, accessToken string) {}++// SyncAPITokenAccess applies the tenant plan and per-token rate limits to a+// freshly issued set of API tokens.+func (s *Service) SyncAPITokenAccess(ctx context.Context, tenantID string, tokens ...string) {}++// DeleteRateLimitKeys drops the rate-limit entries of deleted tokens.+func (s *Service) DeleteRateLimitKeys(ctx context.Context, tokens ...string) {}++// APIAuthAllowed reports whether the tenant plan may authenticate with API+// keys.+func (s *Service) APIAuthAllowed(ctx context.Context, tenantID string) (bool, error) {+ return true, nil+}++// ChargeParsedDocument meters a parsed DeepDOC PDF.+func (s *Service) ChargeParsedDocument(ctx context.Context, tenantID, docID, runKey string, pageCount int64, deepdoc bool) error {+ return nil+}++// ReleaseDocumentHold releases a document's uncommitted parse hold.+func (s *Service) ReleaseDocumentHold(ctx context.Context, docID string) error { return nil }diff --git a/internal/service/dataset/dataset_test_helpers_ee_test.go b/internal/service/dataset/test_helpers_test.gosimilarity index 66%rename from internal/service/dataset/dataset_test_helpers_ee_test.gorename to internal/service/dataset/test_helpers_test.goindex 90d1970c62..71e903742c 100644--- a/internal/service/dataset/dataset_test_helpers_ee_test.go+++ b/internal/service/dataset/test_helpers_test.go@@ -1,3 +1,4 @@+//// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.//// Licensed under the Apache License, Version 2.0 (the "License");@@ -11,17 +12,24 @@// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.+//package dataset-import (- "testing"-)+import "testing"+// datasetTestExtraModels adds no tables beyond the community schema.func datasetTestExtraModels() []interface{} { return nil }+// datasetTestMembershipRole keeps the caller's membership role: the community+// edition has no tenant role table.func datasetTestMembershipRole(_ *testing.T, _ string, role string) string { return role }-func grantDatasetTestResource(_ *testing.T, _ string, _ string, _ string, _ string, _ ...string) {}+// grantDatasetTestResource grants nothing: the community edition has no+// per-resource permission table to seed.+func grantDatasetTestResource(_ *testing.T, _ string, _ string, _ string, _ string, _ ...string) {+}+// enableDatasetTestModelAccess grants nothing: the community edition has no+// model group access control.func enableDatasetTestModelAccess(_ *testing.T, _ string, _ string, _ string) {}diff --git a/internal/service/document/document_crud.go b/internal/service/document/document_crud.goindex e06649055f..ddd2546a91 100644--- a/internal/service/document/document_crud.go+++ b/internal/service/document/document_crud.go@@ -13,6 +13,7 @@ import ("ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response""ragflow/internal/service"+ "ragflow/internal/service/billing""ragflow/internal/storage""gorm.io/gorm"@@ -280,6 +281,13 @@ func (s *DocumentService) deleteDocumentFull(ctx context.Context, docID string)return err}+ // Release an uncommitted parse hold before the document disappears.+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ if releaseErr := billingService.ReleaseDocumentHold(ctx, docID); releaseErr != nil {+ common.Warn(fmt.Sprintf("failed to release billing hold for doc %s: %v", docID, releaseErr))+ }+ }+// Delete tasks from DBingestionTask, err := s.ingestionTaskDAO.GetByDocumentID(ctx, dao.DB, docID)if err != nil {diff --git a/internal/service/document/document_ee_test.go b/internal/service/document/document_ee_test.godeleted file mode 100644index bc0246fb1e..0000000000--- a/internal/service/document/document_ee_test.go+++ /dev/null@@ -1,30 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package document--import (- "context"- "testing"-- "gorm.io/gorm"-)--func documentTestExtraModels() []interface{} { return nil }--func assertUploadedDocumentOwnerGrant(_ *testing.T, _ context.Context, _ string) {}--func seedDocumentPreviewMemberAccessEE(_ *testing.T, _ *gorm.DB) {}diff --git a/internal/service/document/document_permission_ee.go b/internal/service/document/document_permission_ee.godeleted file mode 100644index 7b8e258d5d..0000000000--- a/internal/service/document/document_permission_ee.go+++ /dev/null@@ -1,29 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package document--import (- "context"-- "gorm.io/gorm"-- "ragflow/internal/entity"-)--func grantDocumentOwnerEE(context.Context, *gorm.DB, *entity.Document) error {- return nil-}diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.goindex ba0e731038..324786aa9e 100644--- a/internal/service/document/document_test.go+++ b/internal/service/document/document_test.go@@ -552,7 +552,6 @@ func setupServiceTestDBWithDSN(t *testing.T, dsn string) *gorm.DB {&entity.UserCanvas{},&entity.API4Conversation{},}- models = append(models, documentTestExtraModels()...)if err = db.AutoMigrate(models...); err != nil {t.Fatalf("failed to migrate: %v", err)}@@ -583,7 +582,6 @@ func seedDocumentPreviewMemberAccess(t *testing.T, db *gorm.DB) {}).Error; err != nil {t.Fatalf("insert Tenant member: %v", err)}- seedDocumentPreviewMemberAccessEE(t, db)}func testDocumentService(t *testing.T) *DocumentService {@@ -1277,7 +1275,6 @@ func TestUploadLocalDocuments_MirrorsPythonCoreFields(t *testing.T) {if doc["content_hash"] != "06b05ab6733a618578af5f94892f3950" {t.Fatalf("content_hash=%v", doc["content_hash"])}- assertUploadedDocumentOwnerGrant(t, ctx, doc["id"].(string))cfg := doc["parser_config"].(map[string]interface{})if cfg["existing"] != "value" || cfg["table_column_mode"] != "assist" {t.Fatalf("parser_config=%v", cfg)diff --git a/internal/admin/license_ee.go b/internal/service/document/stub.gosimilarity index 71%rename from internal/admin/license_ee.gorename to internal/service/document/stub.goindex 177d23c2e8..a38dbac1ee 100644--- a/internal/admin/license_ee.go+++ b/internal/service/document/stub.go@@ -14,17 +14,18 @@// limitations under the License.//-package admin+//go:build !ee++package documentimport ("context"- "ragflow/internal/common"-)-func InitLicense(ctx context.Context) error {- return nil-}+ "ragflow/internal/entity"++ "gorm.io/gorm"+)-func AppendServiceList(serviceInfos []*common.BaseMessage) []*common.BaseMessage {- return serviceInfos-}+// grantDocumentOwnerEE grants nothing: the community edition has no document+// permission records.+func grantDocumentOwnerEE(context.Context, *gorm.DB, *entity.Document) error { return nil }diff --git a/internal/service/edition_permissions_ee_test.go b/internal/service/edition_permissions_ee_test.godeleted file mode 100644index 064cfc8e71..0000000000--- a/internal/service/edition_permissions_ee_test.go+++ /dev/null@@ -1,17 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package servicediff --git a/internal/service/stub.go b/internal/service/stub.gonew file mode 100644index 0000000000..99261f70e3--- /dev/null+++ b/internal/service/stub.go@@ -0,0 +1,80 @@+//+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+//++//go:build !ee++package service++import (+ "context"++ "ragflow/internal/common"+ "ragflow/internal/entity"++ "gorm.io/gorm"+)++// InitHTTPClientEE is a no-op in the community edition.+func (h *AdminClient) InitHTTPClientEE() error { return nil }++// EnrichMessage leaves the heartbeat unchanged in the community edition.+func (h *AdminClient) EnrichMessage(message *common.BaseMessage) (*common.BaseMessage, error) {+ return message, nil+}++// UpdateClient ignores the heartbeat acknowledgement in the community edition.+func (h *AdminClient) UpdateClient(clientInfo any) error { return nil }++// prepareAgentCreation grants no additional permissions before an agent is+// created.+func prepareAgentCreation(_ context.Context, userID string) (string, error) { return userID, nil }++// tenantMemberPermissionEE leaves membership checks to the community policy.+func tenantMemberPermissionEE(ctx context.Context, db *gorm.DB, userID, tenantID string, required int32) (*entity.UserTenant, int32, bool, error) {+ return nil, 0, false, nil+}++// recordTenantPermissionChangeEE records nothing: the community edition has no+// permission audit trail.+func recordTenantPermissionChangeEE(tx *gorm.DB, tenantID, actorUserID, eventType, targetType, targetID, resourceType, resourceID, actionType string, beforePermission, afterPermission int32, beforeData, afterData interface{}) error {+ return nil+}++// resolveTenantInviteRoleEE leaves invite roles to the community default.+func resolveTenantInviteRoleEE(*gorm.DB, string) (tenantInviteRole, bool, error) {+ return tenantInviteRole{}, false, nil+}++// checkTenantInviteEnabledEE leaves the invite switch to the community+// default.+func (*TenantService) checkTenantInviteEnabledEE(context.Context, string) (common.ErrorCode, bool, error) {+ return common.CodeSuccess, false, nil+}++// resolveCurrentUserTenantEE leaves tenant resolution to the community path.+func resolveCurrentUserTenantEE(context.Context, string) (*entity.UserTenant, bool, error) {+ return nil, false, nil+}++// resolveDefaultTenantIDEE leaves tenant resolution to the community path.+func resolveDefaultTenantIDEE(context.Context, string) (string, bool, error) {+ return "", false, nil+}++// resolveUserAuthTenant keeps the token's tenant unchanged.+func resolveUserAuthTenant(_ context.Context, _ *entity.User, tenantID string) (string, error) {+ return tenantID, nil+}diff --git a/internal/service/tenant.go b/internal/service/tenant.goindex 55fcc9a611..88e15b4d9e 100644--- a/internal/service/tenant.go+++ b/internal/service/tenant.go@@ -26,6 +26,7 @@ import ("ragflow/internal/entity""ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response"+ "ragflow/internal/service/billing""strings""gorm.io/gorm"@@ -854,6 +855,16 @@ func (s *TenantService) AddMember(ctx context.Context, userID, tenantID string,if req == nil {return nil, common.CodeArgumentError, fmt.Errorf("request is required")}+ // Seat quota: inviting one member consumes one seat.+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ if quotaErr := billingService.CheckResources(ctx, tenantID, billing.ResourceDelta{Members: 1}); quotaErr != nil {+ var insufficient *billing.InsufficientResourceError+ if errors.As(quotaErr, &insufficient) {+ return nil, common.CodeBillingSeatsInsufficient, quotaErr+ }+ return nil, common.CodeServerError, quotaErr+ }+ }if strings.TrimSpace(req.Email) == "" {return nil, common.CodeArgumentError, fmt.Errorf("email is required")}@@ -983,6 +994,17 @@ func (s *TenantService) RemoveMember(ctx context.Context, userID, tenantID, targ// AcceptInvite assigns the Tenant default role when a pending invitation is accepted.func (s *TenantService) AcceptInvite(ctx context.Context, userID, tenantID string) (common.ErrorCode, error) {+ // Seat quota is enforced again at acceptance time: several pending+ // invitations can each fit the remaining seat but not all of them.+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ if quotaErr := billingService.CheckResources(ctx, tenantID, billing.ResourceDelta{Members: 1}); quotaErr != nil {+ if _, ok := quotaErr.(*billing.InsufficientResourceError); ok {+ return common.CodeBillingSeatsInsufficient, quotaErr+ }+ return common.CodeServerError, quotaErr+ }+ }+if s.userTenantDAO == nil {return common.CodeServerError, fmt.Errorf("userTenantDAO not initialized")}diff --git a/internal/service/tenant_invite_ee.go b/internal/service/tenant_invite_ee.godeleted file mode 100644index 800ebb3794..0000000000--- a/internal/service/tenant_invite_ee.go+++ /dev/null@@ -1,33 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package service--import (- "context"-- "ragflow/internal/common"-- "gorm.io/gorm"-)--func resolveTenantInviteRoleEE(*gorm.DB, string) (tenantInviteRole, bool, error) {- return tenantInviteRole{}, false, nil-}--func (*TenantService) checkTenantInviteEnabledEE(context.Context, string) (common.ErrorCode, bool, error) {- return common.CodeSuccess, false, nil-}diff --git a/internal/service/tenant_permission_ee.go b/internal/service/tenant_permission_ee.godeleted file mode 100644index cb022a7b34..0000000000--- a/internal/service/tenant_permission_ee.go+++ /dev/null@@ -1,30 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package service--import (- "context"-- "ragflow/internal/entity"-)--func resolveDefaultTenantIDEE(context.Context, string) (string, bool, error) {- return "", false, nil-}--func resolveCurrentUserTenantEE(context.Context, string) (*entity.UserTenant, bool, error) {- return nil, false, nil-}diff --git a/internal/service/tenant_role_ee.go b/internal/service/tenant_role_ee.godeleted file mode 100644index ab78c144b3..0000000000--- a/internal/service/tenant_role_ee.go+++ /dev/null@@ -1,33 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package service--import (- "context"-- "ragflow/internal/entity"-- "gorm.io/gorm"-)--func tenantMemberPermissionEE(context.Context, *gorm.DB, string, string, int32) (*entity.UserTenant, int32, bool, error) {- return nil, 0, false, nil-}--func recordTenantPermissionChangeEE(*gorm.DB, string, string, string, string, string, string, string, string, int32, int32, interface{}, interface{}) error {- return nil-}diff --git a/internal/service/tenant_test.go b/internal/service/tenant_test.goindex 851714a744..60354633e2 100644--- a/internal/service/tenant_test.go+++ b/internal/service/tenant_test.go@@ -38,7 +38,7 @@ func setupTenantPermissionTestDB(t *testing.T) *gorm.DB {if err != nil {t.Fatalf("open sqlite: %v", err)}- if err := db.AutoMigrate(&entity.UserTenant{}, &entity.PermissionChangeLog{}); err != nil {+ if err := db.AutoMigrate(append([]interface{}{&entity.UserTenant{}}, permissionChangeLogTestModels()...)...); err != nil {t.Fatalf("migrate tenant permission table: %v", err)}originalDB := dao.DBdiff --git a/internal/service/test_helpers_ee_test.go b/internal/service/test_helpers_ee_test.godeleted file mode 100644index 5acb821e34..0000000000--- a/internal/service/test_helpers_ee_test.go+++ /dev/null@@ -1,23 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package service--import "testing"--func grantServiceTestResource(_ *testing.T, _ string, _ string, _ string, _ string, _ int32) {}--func restrictServiceTestFeatureRole(_ *testing.T, _ string, _ string, _ int32) {}diff --git a/internal/service/test_helpers_test.go b/internal/service/test_helpers_test.goindex 8900e5d25f..369ec6f1f1 100644--- a/internal/service/test_helpers_test.go+++ b/internal/service/test_helpers_test.go@@ -275,6 +275,15 @@ func insertTestIngestionTask(t *testing.T, id, userID, docID, datasetID string)insertTestIngestionTaskWithStatus(t, id, userID, docID, datasetID, common.CREATED)}+// grantServiceTestResource grants nothing: the community edition has no+// per-resource permission table to seed.+func grantServiceTestResource(_ *testing.T, _ string, _ string, _ string, _ string, _ int32) {+}++// permissionChangeLogTestModels adds no tables: the community edition has no+// permission audit log.+func permissionChangeLogTestModels() []interface{} { return nil }+// insertTestIngestionTaskWithStatus inserts a test IngestionTask with a specific status.func insertTestIngestionTaskWithStatus(t *testing.T, id, userID, docID, datasetID, status string) {t.Helper()diff --git a/internal/service/user.go b/internal/service/user.goindex aade845600..92db76a67e 100644--- a/internal/service/user.go+++ b/internal/service/user.go@@ -41,6 +41,7 @@ import ("gorm.io/gorm""ragflow/internal/dao"+ "ragflow/internal/service/billing""ragflow/internal/utility")@@ -293,6 +294,9 @@ func (s *UserService) Login(ctx context.Context, req *LoginRequest) (*entity.Useif err := s.userDAO.Update(ctx, dao.DB, user); err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to update user: %w", err)}+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ billingService.SyncLoginTokenRateLimit(ctx, user.ID, token)+ }return user, common.CodeSuccess, nil}@@ -331,6 +335,9 @@ func (s *UserService) LoginByEmail(ctx context.Context, req *EmailLoginRequest)if err = s.userDAO.Update(ctx, dao.DB, user); err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to update user: %w", err)}+ if billingService := billing.Get(); billingService != nil && billingService.Enabled() {+ billingService.SyncLoginTokenRateLimit(ctx, user.ID, token)+ }return user, common.CodeSuccess, nil}diff --git a/internal/service/user_auth_ee.go b/internal/service/user_auth_ee.godeleted file mode 100644index ecc7c1c211..0000000000--- a/internal/service/user_auth_ee.go+++ /dev/null@@ -1,27 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package service--import (- "context"-- "ragflow/internal/entity"-)--func resolveUserAuthTenant(_ context.Context, _ *entity.User, _ string) (string, error) {- return "", nil-}diff --git a/internal/utility/fingerprint_ee.go b/internal/utility/fingerprint_ee.godeleted file mode 100644index 5c41b3124c..0000000000--- a/internal/utility/fingerprint_ee.go+++ /dev/null@@ -1,20 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.-//--package utility--type ClusterInfo struct {-}