group.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. package schema
  2. import (
  3. "encoding/json"
  4. "github.com/Wei-Shaw/sub2api/ent/schema/mixins"
  5. "github.com/Wei-Shaw/sub2api/internal/domain"
  6. "entgo.io/ent"
  7. "entgo.io/ent/dialect"
  8. "entgo.io/ent/dialect/entsql"
  9. "entgo.io/ent/schema"
  10. "entgo.io/ent/schema/edge"
  11. "entgo.io/ent/schema/field"
  12. "entgo.io/ent/schema/index"
  13. )
  14. // Group holds the schema definition for the Group entity.
  15. type Group struct {
  16. ent.Schema
  17. }
  18. func (Group) Annotations() []schema.Annotation {
  19. return []schema.Annotation{
  20. entsql.Annotation{Table: "groups"},
  21. }
  22. }
  23. func (Group) Mixin() []ent.Mixin {
  24. return []ent.Mixin{
  25. mixins.TimeMixin{},
  26. mixins.SoftDeleteMixin{},
  27. }
  28. }
  29. func (Group) Fields() []ent.Field {
  30. return []ent.Field{
  31. // 唯一约束通过部分索引实现(WHERE deleted_at IS NULL),支持软删除后重用
  32. // 见迁移文件 016_soft_delete_partial_unique_indexes.sql
  33. field.String("name").
  34. MaxLen(100).
  35. NotEmpty(),
  36. field.String("description").
  37. Optional().
  38. Nillable().
  39. SchemaType(map[string]string{dialect.Postgres: "text"}),
  40. field.Float("rate_multiplier").
  41. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  42. Default(1.0),
  43. // 高峰时段倍率(added by migration 158)
  44. field.Bool("peak_rate_enabled").
  45. Default(false).
  46. Comment("是否启用高峰时段倍率"),
  47. field.String("peak_start").
  48. MaxLen(5).
  49. Default("").
  50. Comment("高峰开始时间 HH:MM(含),如 14:00;空表示未配置;不支持跨天"),
  51. field.String("peak_end").
  52. MaxLen(5).
  53. Default("").
  54. Comment("高峰结束时间 HH:MM(不含),必须大于 peak_start;不支持跨天,如 22:00-02:00"),
  55. field.Float("peak_rate_multiplier").
  56. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  57. Default(1.0).
  58. Comment("高峰时段叠加倍率,仅在 peak_rate_enabled 且处于 [peak_start, peak_end) 时乘入文本倍率"),
  59. field.Bool("is_exclusive").
  60. Default(false),
  61. // security_policy_enabled: 分组安全策略总开关,默认关闭。
  62. field.Bool("security_policy_enabled").
  63. Default(false).
  64. Comment("分组安全策略总开关,默认关闭"),
  65. // security_policy_mode: 命中后处置,block_session 断会话(默认)/
  66. // block_request 仅拦截当次请求。
  67. field.String("security_policy_mode").
  68. MaxLen(20).
  69. Default("block_session").
  70. Comment("安全策略命中后处置:block_session 断会话 / block_request 仅拦当次"),
  71. // security_policy_email_enabled: 命中是否邮件提醒用户,可自由开关。
  72. field.Bool("security_policy_email_enabled").
  73. Default(true).
  74. Comment("安全策略命中是否邮件提醒用户"),
  75. field.String("status").
  76. MaxLen(20).
  77. Default(domain.StatusActive),
  78. field.String("duplicate_operation_id").
  79. MaxLen(64).
  80. Optional().
  81. Nillable().
  82. Immutable().
  83. Comment("内部幂等恢复标识,不对 API 暴露"),
  84. // Subscription-related fields (added by migration 003)
  85. field.String("platform").
  86. MaxLen(50).
  87. Default(domain.PlatformAnthropic),
  88. field.String("subscription_type").
  89. MaxLen(20).
  90. Default(domain.SubscriptionTypeStandard),
  91. field.Float("daily_limit_usd").
  92. Optional().
  93. Nillable().
  94. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  95. field.Float("weekly_limit_usd").
  96. Optional().
  97. Nillable().
  98. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  99. field.Float("monthly_limit_usd").
  100. Optional().
  101. Nillable().
  102. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  103. field.Int("default_validity_days").
  104. Default(30),
  105. // 图片生成计费配置(antigravity 和 gemini 平台使用)
  106. field.Bool("allow_image_generation").
  107. Default(false).
  108. Comment("是否允许该分组使用图片生成能力"),
  109. field.Bool("allow_batch_image_generation").
  110. Default(false).
  111. Comment("是否允许该分组使用批量图片生成能力"),
  112. field.Bool("image_rate_independent").
  113. Default(false).
  114. Comment("图片生成是否使用独立倍率;false 表示共享分组有效倍率"),
  115. field.Float("image_rate_multiplier").
  116. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  117. Default(1.0).
  118. Comment("图片生成独立倍率,仅 image_rate_independent=true 时生效"),
  119. field.Float("image_price_1k").
  120. Optional().
  121. Nillable().
  122. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  123. field.Float("image_price_2k").
  124. Optional().
  125. Nillable().
  126. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  127. field.Float("image_price_4k").
  128. Optional().
  129. Nillable().
  130. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  131. field.Float("batch_image_discount_multiplier").
  132. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  133. Default(0.5).
  134. Comment("批量图片生成折扣倍率,最终单价会乘以该值;0 表示免费"),
  135. field.Float("batch_image_hold_multiplier").
  136. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  137. Default(0.6).
  138. Comment("批量图片生成冻结价格比例,按普通生图原价乘以该比例冻结,结算后释放差额"),
  139. field.Bool("video_rate_independent").
  140. Default(false).
  141. Comment("视频生成是否使用独立倍率;false 表示共享分组有效倍率"),
  142. field.Float("video_rate_multiplier").
  143. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  144. Default(1.0).
  145. Comment("视频生成独立倍率,仅 video_rate_independent=true 时生效"),
  146. field.Float("video_price_480p").
  147. Optional().
  148. Nillable().
  149. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  150. field.Float("video_price_720p").
  151. Optional().
  152. Nillable().
  153. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  154. field.Float("video_price_1080p").
  155. Optional().
  156. Nillable().
  157. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}),
  158. field.JSON("video_model_prices", map[string]map[string]float64{}).
  159. Optional().
  160. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  161. Comment("按模型族和分辨率覆盖视频每秒价格"),
  162. field.Float("web_search_price_per_call").
  163. Optional().
  164. Nillable().
  165. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
  166. Comment("Codex alpha/search 网页搜索单次价格(USD/次);nil 表示使用默认价 0.01(官方 $10/1000 次)"),
  167. // 搜索/工具调用显式定价(per 1k calls),用于 Grok web_search 等。
  168. field.Float("search_price_per_1k").
  169. Optional().
  170. Nillable().
  171. Min(0).
  172. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
  173. Comment("搜索工具价格 per 1000 calls(web_search 等)"),
  174. // Grok Voice 显式定价(realtime / TTS / STT),不按文本 RateMultiplier。
  175. field.Float("audio_realtime_price_per_min").
  176. Optional().
  177. Nillable().
  178. Min(0).
  179. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
  180. Comment("Voice realtime 每分钟价格(USD)"),
  181. field.Float("audio_tts_price_per_million_chars").
  182. Optional().
  183. Nillable().
  184. Min(0).
  185. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
  186. Comment("TTS 每百万字符价格(USD)"),
  187. field.Float("audio_stt_price_per_hour").
  188. Optional().
  189. Nillable().
  190. Min(0).
  191. SchemaType(map[string]string{dialect.Postgres: "decimal(20,8)"}).
  192. Comment("STT 每小时价格(USD)"),
  193. field.Bool("long_context_pricing_enabled").
  194. Default(true).
  195. Comment("是否按上下文长度应用模型阶梯价格;默认开启以保持官方/渠道长上下文价"),
  196. field.JSON("model_pricing", json.RawMessage{}).
  197. Optional().
  198. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  199. Comment("分组逐模型定价;优先级高于渠道和内置定价"),
  200. // Claude Code 客户端限制 (added by migration 029)
  201. field.Bool("claude_code_only").
  202. Default(false).
  203. Comment("是否仅允许 Claude Code 客户端"),
  204. field.Int64("fallback_group_id").
  205. Optional().
  206. Nillable().
  207. Comment("非 Claude Code 请求降级使用的分组 ID"),
  208. field.Int64("fallback_group_id_on_invalid_request").
  209. Optional().
  210. Nillable().
  211. Comment("无效请求兜底使用的分组 ID"),
  212. // 模型路由配置 (added by migration 040)
  213. field.JSON("model_routing", map[string][]int64{}).
  214. Optional().
  215. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  216. Comment("模型路由配置:模型模式 -> 优先账号ID列表"),
  217. // 模型路由开关 (added by migration 041)
  218. field.Bool("model_routing_enabled").
  219. Default(false).
  220. Comment("是否启用模型路由配置"),
  221. // MCP XML 协议注入开关 (added by migration 042)
  222. field.Bool("mcp_xml_inject").
  223. Default(true).
  224. Comment("是否注入 MCP XML 调用协议提示词(仅 antigravity 平台)"),
  225. // 支持的模型系列 (added by migration 046)
  226. field.JSON("supported_model_scopes", []string{}).
  227. Default([]string{"claude", "gemini_text", "gemini_image"}).
  228. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  229. Comment("支持的模型系列:claude, gemini_text, gemini_image"),
  230. // 分组排序 (added by migration 052)
  231. field.Int("sort_order").
  232. Default(0).
  233. Comment("分组显示排序,数值越小越靠前"),
  234. // OpenAI Messages 调度配置 (added by migration 069)
  235. field.Bool("allow_messages_dispatch").
  236. Default(false).
  237. Comment("是否允许 /v1/messages 调度到此 OpenAI 分组"),
  238. field.Bool("allow_live").
  239. Default(false).
  240. Comment("是否允许此 OpenAI 分组访问 Live 接口"),
  241. field.Bool("force_openai_fast").
  242. Default(false).
  243. Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority"),
  244. field.Bool("free_openai_fast").
  245. Default(false).
  246. Comment("是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费"),
  247. field.Bool("require_oauth_only").
  248. Default(false).
  249. Comment("仅允许非 apikey 类型账号关联到此分组"),
  250. field.Bool("require_privacy_set").
  251. Default(false).
  252. Comment("调度时仅允许 privacy 已成功设置的账号"),
  253. field.String("default_mapped_model").
  254. MaxLen(100).
  255. Default("").
  256. Comment("默认映射模型 ID,当账号级映射找不到时使用此值"),
  257. field.JSON("messages_dispatch_model_config", domain.OpenAIMessagesDispatchModelConfig{}).
  258. Default(domain.OpenAIMessagesDispatchModelConfig{}).
  259. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  260. Comment("OpenAI Messages 调度模型配置:按 Claude 系列/精确模型映射到目标 GPT 模型"),
  261. field.JSON("model_allowlist", domain.GroupModelAllowlist{}).
  262. Default(domain.GroupModelAllowlist{}).
  263. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  264. Comment("分组模型白名单:同时约束模型列表接口与请求准入"),
  265. field.JSON("codex_models_manifest_config", domain.GroupCodexModelsManifestConfig{}).
  266. Default(domain.GroupCodexModelsManifestConfig{}).
  267. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  268. Comment("固定账号获取 Codex Model Manifest 配置;开启后 /models 请求只用选定账号拉取(仅 openai 平台)"),
  269. // 分组级每分钟请求数上限(0 = 不限制)。设置后优先于用户级兜底生效。
  270. field.Int("rpm_limit").
  271. Default(0).
  272. Comment("分组 RPM 上限,0 表示不限制;设置后接管该分组用户的限流"),
  273. // OpenAI/Codex 请求的推理强度上限(空字符串表示不限制)。
  274. field.String("max_reasoning_effort").
  275. MaxLen(20).
  276. Default("").
  277. Comment("OpenAI reasoning effort 上限;可选 minimal/low/medium/high/xhigh/max"),
  278. field.String("max_reasoning_effort_over_limit").
  279. MaxLen(20).
  280. Default("downgrade").
  281. Comment("超过推理强度上限时的访问控制:downgrade 自动降档,deny 拒绝访问"),
  282. field.JSON("reasoning_effort_mappings", []domain.ReasoningEffortMapping{}).
  283. Default([]domain.ReasoningEffortMapping{}).
  284. SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
  285. Comment("OpenAI reasoning effort 自定义映射;可按模型精确名、前缀或后缀限定,先映射再应用上限"),
  286. // 分组利润控制(migration 192/193):openai/anthropic/gemini/grok/antigravity
  287. // 的 token 分组可启用,composite 分组不能直接启用。
  288. field.Bool("profit_control_enabled").
  289. Default(false).
  290. Comment("是否启用利润控制:调度时仅允许账号计费倍率满足毛利率要求的账号进入候选池"),
  291. field.Float("profit_min_margin").
  292. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  293. Default(0).
  294. Comment("最低毛利率,小数(0.30=30%);账号准入条件为 U <= D*(1-margin-buffer)"),
  295. field.Float("profit_safety_buffer").
  296. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  297. Default(0).
  298. Comment("安全缓冲,小数;与 margin 相加后从下游倍率中扣除,默认 0"),
  299. }
  300. }
  301. func (Group) Edges() []ent.Edge {
  302. return []ent.Edge{
  303. edge.To("api_keys", APIKey.Type),
  304. edge.To("redeem_codes", RedeemCode.Type),
  305. edge.To("subscriptions", UserSubscription.Type),
  306. edge.To("usage_logs", UsageLog.Type),
  307. edge.From("accounts", Account.Type).
  308. Ref("groups").
  309. Through("account_groups", AccountGroup.Type),
  310. edge.From("allowed_users", User.Type).
  311. Ref("allowed_groups").
  312. Through("user_allowed_groups", UserAllowedGroup.Type),
  313. // 注意:fallback_group_id 直接作为字段使用,不定义 edge
  314. // 这样允许多个分组指向同一个降级分组(M2O 关系)
  315. }
  316. }
  317. func (Group) Indexes() []ent.Index {
  318. return []ent.Index{
  319. // name 字段已在 Fields() 中声明 Unique(),无需重复索引
  320. index.Fields("status"),
  321. index.Fields("platform"),
  322. index.Fields("subscription_type"),
  323. index.Fields("is_exclusive"),
  324. index.Fields("deleted_at"),
  325. index.Fields("sort_order"),
  326. index.Fields("duplicate_operation_id").
  327. Unique().
  328. StorageKey("idx_groups_duplicate_operation_id_active").
  329. Annotations(entsql.IndexWhere("duplicate_operation_id IS NOT NULL AND deleted_at IS NULL")),
  330. }
  331. }