codingPlanSubscriptionService.test.ts 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { BUILTIN_MODEL_PROVIDER_IDS, CODING_PLAN_SYSTEM_BUSY, type ApiClient } from "@zcode/shared";
  3. import {
  4. BigModelCodingPlanSubscriptionProvider,
  5. resolveCodingPlanClientConfigUrl,
  6. } from "../src/coding-plan-subscription/bigmodelCodingPlanSubscriptionProvider.js";
  7. import { ZaiCodingPlanSubscriptionProvider } from "../src/coding-plan-subscription/zaiCodingPlanSubscriptionProvider.js";
  8. import { createCodingPlanSubscriptionService } from "../src/coding-plan-subscription/codingPlanSubscriptionService.js";
  9. function createJsonResponse(body: unknown): Response {
  10. return new Response(JSON.stringify(body), {
  11. status: 200,
  12. headers: { "Content-Type": "application/json" },
  13. });
  14. }
  15. function createZaiBatchPreviewResponse(): Response {
  16. return createJsonResponse({
  17. code: 200,
  18. data: {
  19. productList: [
  20. {
  21. productId: "zai-product-pro",
  22. productName: "Z.ai Coding Pro",
  23. payAmount: 72,
  24. },
  25. ],
  26. isSubscribed: false,
  27. isAuthenticated: true,
  28. },
  29. });
  30. }
  31. function createHtmlErrorResponse(): Response {
  32. const body = [
  33. '<!doctypehtml><html lang="zh-cn"><title>405</title>',
  34. "<body>Sorry, your request has been blocked.</body></html>",
  35. ].join("");
  36. return new Response(body, {
  37. status: 405,
  38. headers: { "Content-Type": "text/html" },
  39. });
  40. }
  41. function createBigModelCredentialService(token = "oauth-token") {
  42. return {
  43. load: vi.fn(async (key: string) => (key === "oauth:bigmodel:access_token" ? token : null)),
  44. };
  45. }
  46. describe("BigModelCodingPlanSubscriptionProvider", () => {
  47. afterEach(() => {
  48. vi.useRealTimers();
  49. vi.unstubAllEnvs();
  50. });
  51. it("off-peak mock 直接使用 Built-in 模型,不等待远端 client config", async () => {
  52. vi.stubEnv("ZCODE_OFFPEAK_MOCK", "1");
  53. const apiClient: ApiClient = {
  54. request: vi.fn(async () => {
  55. throw new Error("mock mode must not request remote client config");
  56. }),
  57. };
  58. const provider = new BigModelCodingPlanSubscriptionProvider({
  59. apiClient,
  60. credentialService: { load: vi.fn() },
  61. resolveOffPeakModelSelectionView: async () =>
  62. ({
  63. revision: 1,
  64. providers: [
  65. {
  66. providerId: "account:zai-offpeak-idle-plan",
  67. config: { visibility: "hidden" },
  68. models: [{ modelId: "GLM-5.2", config: {} }],
  69. },
  70. ],
  71. }) as never,
  72. });
  73. await expect(provider.getOffPeakClientConfig({ forceRefresh: true })).resolves.toMatchObject({
  74. enabled: true,
  75. modelSelectionView: expect.objectContaining({
  76. providers: [
  77. expect.objectContaining({
  78. providerId: "account:zai-offpeak-idle-plan",
  79. }),
  80. ],
  81. }),
  82. codingPlanActive: true,
  83. });
  84. expect(apiClient.request).not.toHaveBeenCalled();
  85. });
  86. it("读取手动领取 preview 并归一化 plans", async () => {
  87. vi.stubEnv("ZCODE_ENDPOINT_ORIGIN", "https://preview.example.com");
  88. // Bugfix: 开发机 ambient ZCODE_BASE_URL 优先级高于 ZCODE_ENDPOINT_ORIGIN,置空避免 preview 域被生产域覆盖
  89. vi.stubEnv("ZCODE_BASE_URL", "");
  90. const apiClient: ApiClient = {
  91. request: vi.fn(async () =>
  92. createJsonResponse({
  93. code: 0,
  94. data: {
  95. server_time: 1_788_000_123,
  96. plans: [
  97. {
  98. plan_id: "weekend-plan",
  99. name: "Weekend Start Plan",
  100. description: "Weekend plan",
  101. priority: 100,
  102. entitlements: [
  103. {
  104. entitlement_id: "weekend-model",
  105. show_name: "GLM-5.1",
  106. meter: "model_usage",
  107. unit_type: "token",
  108. capabilities: ["model:GLM-5.1"],
  109. grant_units: 100_000,
  110. period: "daily",
  111. priority: 10,
  112. effective_at: 1_788_000_000,
  113. },
  114. ],
  115. },
  116. ],
  117. },
  118. }),
  119. ),
  120. };
  121. const provider = new BigModelCodingPlanSubscriptionProvider({
  122. apiClient,
  123. credentialService: {
  124. load: vi.fn(async (key: string) => (key === "zcodejwttoken" ? "zcode-jwt" : null)),
  125. },
  126. });
  127. await expect(provider.getManualClaimPlanPreviews()).resolves.toEqual({
  128. serverTime: 1_788_000_123_000,
  129. plans: [
  130. expect.objectContaining({
  131. planId: "weekend-plan",
  132. priority: 100,
  133. entitlements: [
  134. expect.objectContaining({
  135. entitlementId: "weekend-model",
  136. grantUnits: 100_000,
  137. effectiveAt: 1_788_000_000,
  138. }),
  139. ],
  140. }),
  141. ],
  142. });
  143. expect(apiClient.request).toHaveBeenCalledWith(
  144. expect.objectContaining({
  145. href: expect.stringContaining(
  146. "https://preview.example.com/api/v1/zcode-plan/billing/preview",
  147. ),
  148. }),
  149. expect.objectContaining({
  150. headers: { Authorization: "Bearer zcode-jwt" },
  151. method: "GET",
  152. }),
  153. );
  154. });
  155. it("未登录读取手动领取 preview 时不发送 Authorization", async () => {
  156. const apiClient: ApiClient = {
  157. request: vi.fn(async () =>
  158. createJsonResponse({
  159. code: 0,
  160. data: { server_time: "invalid", plans: [] },
  161. }),
  162. ),
  163. };
  164. const provider = new BigModelCodingPlanSubscriptionProvider({
  165. apiClient,
  166. credentialService: { load: vi.fn(async () => null) },
  167. });
  168. await expect(provider.getManualClaimPlanPreviews()).resolves.toEqual({
  169. plans: [],
  170. });
  171. expect(apiClient.request).toHaveBeenCalledWith(
  172. expect.any(URL),
  173. expect.objectContaining({ headers: undefined, method: "GET" }),
  174. );
  175. });
  176. it("保留手动领取失败 code 但忽略顶层 msg", async () => {
  177. const provider = new BigModelCodingPlanSubscriptionProvider({
  178. apiClient: {
  179. request: vi.fn(async () =>
  180. createJsonResponse({
  181. code: 1003,
  182. msg: "already claimed",
  183. data: null,
  184. }),
  185. ),
  186. },
  187. credentialService: { load: vi.fn(async () => "zcode-jwt") },
  188. });
  189. await expect(
  190. provider.claimManualPlan({
  191. planId: "weekend-plan",
  192. }),
  193. ).resolves.toEqual({ success: false, code: 1003, message: "" });
  194. });
  195. it("保留领取额度耗尽响应中的 plan 结束时间供 UI 生成日期提示", async () => {
  196. const provider = new BigModelCodingPlanSubscriptionProvider({
  197. apiClient: {
  198. request: vi.fn(async () =>
  199. createJsonResponse({
  200. code: 1005,
  201. msg: "quota exhausted",
  202. data: {
  203. server_time: 1_788_000_123,
  204. plan: { ends_at: 1_788_431_999 },
  205. },
  206. }),
  207. ),
  208. },
  209. credentialService: { load: vi.fn(async () => "zcode-jwt") },
  210. });
  211. await expect(
  212. provider.claimManualPlan({
  213. planId: "weekend-plan",
  214. }),
  215. ).resolves.toEqual({
  216. success: false,
  217. code: 1005,
  218. message: "",
  219. serverTime: 1_788_000_123_000,
  220. failureEndsAt: 1_788_431_999,
  221. });
  222. });
  223. it.each([1005, "1005"])("领取失败 %s 原样传递 data.message 并忽略 msg", async (code) => {
  224. const message = "今日额度已领完。\n<b>请下次再来</b>";
  225. const provider = new BigModelCodingPlanSubscriptionProvider({
  226. apiClient: {
  227. request: vi.fn(async () =>
  228. createJsonResponse({
  229. code,
  230. msg: "DO NOT SHOW",
  231. data: { message, server_time: 1788000123 },
  232. }),
  233. ),
  234. },
  235. credentialService: { load: vi.fn(async () => "zcode-jwt") },
  236. });
  237. await expect(
  238. provider.claimManualPlan({
  239. planId: "weekend",
  240. }),
  241. ).resolves.toMatchObject({
  242. success: false,
  243. code: 1005,
  244. message,
  245. serverTime: 1788000123000,
  246. });
  247. });
  248. it.each([undefined, null, 42, "", " "])(
  249. "领取失败不使用 msg 兜底:message=%s",
  250. async (message) => {
  251. const provider = new BigModelCodingPlanSubscriptionProvider({
  252. apiClient: {
  253. request: vi.fn(async () =>
  254. createJsonResponse({
  255. code: "1005",
  256. msg: "DO NOT SHOW",
  257. data: { message },
  258. }),
  259. ),
  260. },
  261. credentialService: { load: vi.fn(async () => "zcode-jwt") },
  262. });
  263. const result = await provider.claimManualPlan({
  264. planId: "weekend",
  265. });
  266. expect(result.message).toBe(typeof message === "string" ? message : "");
  267. },
  268. );
  269. it.each(["legacy", "preflight-v1", "unknown", undefined])(
  270. "预算固定 preflight-v1,不消费远端 strategy=%s 的缓存",
  271. async (strategy) => {
  272. const request = vi.fn(async () =>
  273. createJsonResponse({
  274. code: 0,
  275. data: { configs: { modelContextBudget: { strategy } } },
  276. }),
  277. );
  278. const provider = new BigModelCodingPlanSubscriptionProvider({
  279. apiClient: { request },
  280. credentialService: { load: vi.fn() },
  281. });
  282. // 由其他消费者填充真实共享缓存;预算不能再读出旧算法或发起刷新。
  283. await provider.getForceUpdateConfig();
  284. request.mockClear();
  285. await expect(provider.getModelContextBudgetStrategy()).resolves.toBe("preflight-v1");
  286. expect(request).not.toHaveBeenCalled();
  287. },
  288. );
  289. it("配置永不返回时预算立即完成,不发请求也不启动超时器", async () => {
  290. vi.useFakeTimers();
  291. const request = vi.fn(() => new Promise<Response>(() => {}));
  292. const provider = new BigModelCodingPlanSubscriptionProvider({
  293. apiClient: { request },
  294. credentialService: { load: vi.fn() },
  295. });
  296. let value: string | undefined;
  297. void provider.getModelContextBudgetStrategy().then((result) => {
  298. value = result;
  299. });
  300. await vi.advanceTimersByTimeAsync(0);
  301. expect(value).toBe("preflight-v1");
  302. expect(request).not.toHaveBeenCalled();
  303. expect(vi.getTimerCount()).toBe(0);
  304. });
  305. it("batchPreview 使用 BigModel OAuth token 且不添加 Bearer", async () => {
  306. const apiClient: ApiClient = {
  307. request: vi.fn(async () =>
  308. createJsonResponse({
  309. code: 200,
  310. data: {
  311. productList: [
  312. {
  313. productId: "product-pro",
  314. productName: "Coding Plan Pro",
  315. payAmount: 149,
  316. },
  317. ],
  318. isSubscribed: false,
  319. isAuthenticated: true,
  320. },
  321. }),
  322. ),
  323. };
  324. const provider = new BigModelCodingPlanSubscriptionProvider({
  325. apiClient,
  326. credentialService: {
  327. load: vi.fn(async (key) => (key === "oauth:bigmodel:access_token" ? "oauth-token" : null)),
  328. },
  329. });
  330. const result = await provider.batchPreview();
  331. expect(result.productList).toHaveLength(1);
  332. expect(apiClient.request).toHaveBeenCalledWith(
  333. "https://bigmodel.cn/api/biz/pay/batch-preview",
  334. expect.objectContaining({
  335. method: "POST",
  336. headers: {
  337. Authorization: "oauth-token",
  338. "Content-Type": "application/json",
  339. },
  340. }),
  341. );
  342. });
  343. it("ZCODE_ENV=test 时 BigModel Coding Plan API 使用 bigmodel.cn", async () => {
  344. vi.stubEnv("ZCODE_ENV", "test");
  345. const apiClient: ApiClient = {
  346. request: vi.fn(async () =>
  347. createJsonResponse({
  348. code: 200,
  349. data: {
  350. productList: [],
  351. isSubscribed: false,
  352. isAuthenticated: true,
  353. },
  354. }),
  355. ),
  356. };
  357. const provider = new BigModelCodingPlanSubscriptionProvider({
  358. apiClient,
  359. credentialService: createBigModelCredentialService(),
  360. });
  361. await provider.batchPreview();
  362. expect(apiClient.request).toHaveBeenCalledWith(
  363. "https://bigmodel.cn/api/biz/pay/batch-preview",
  364. expect.objectContaining({
  365. method: "POST",
  366. }),
  367. );
  368. });
  369. it("缺少 BigModel OAuth token 时不回退其他 key", async () => {
  370. const apiClient: ApiClient = {
  371. request: vi.fn(),
  372. };
  373. const provider = new BigModelCodingPlanSubscriptionProvider({
  374. apiClient,
  375. credentialService: {
  376. load: vi.fn(async () => null),
  377. },
  378. });
  379. await expect(provider.batchPreview()).rejects.toThrow("bigmodel_oauth_required");
  380. expect(apiClient.request).not.toHaveBeenCalled();
  381. });
  382. it("BigModel OAuth token 被旧版 zcode JWT 污染时不请求套餐接口", async () => {
  383. const apiClient: ApiClient = {
  384. request: vi.fn(),
  385. };
  386. const provider = new BigModelCodingPlanSubscriptionProvider({
  387. apiClient,
  388. credentialService: {
  389. load: vi.fn(async (key) =>
  390. key === "oauth:bigmodel:access_token" || key === "zcodejwttoken"
  391. ? "stale-zcode-jwt"
  392. : null,
  393. ),
  394. },
  395. });
  396. await expect(provider.batchPreview()).rejects.toThrow("bigmodel_oauth_required");
  397. expect(apiClient.request).not.toHaveBeenCalled();
  398. });
  399. it("支付接口返回 HTML/WAF 页面时统一返回系统繁忙错误", async () => {
  400. const apiClient: ApiClient = {
  401. request: vi.fn(async () => createHtmlErrorResponse()),
  402. };
  403. const provider = new BigModelCodingPlanSubscriptionProvider({
  404. apiClient,
  405. credentialService: createBigModelCredentialService(),
  406. });
  407. await expect(
  408. provider.preview({
  409. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  410. productId: "product-pro",
  411. }),
  412. ).rejects.toThrow(CODING_PLAN_SYSTEM_BUSY);
  413. });
  414. it("Z.ai batchPreview 直接使用持久化的业务 token", async () => {
  415. const apiClient: ApiClient = {
  416. request: vi.fn(async () => createZaiBatchPreviewResponse()),
  417. };
  418. const provider = new BigModelCodingPlanSubscriptionProvider({
  419. apiClient,
  420. credentialService: {
  421. load: vi.fn(async (key) => (key === "oauth:zai:access_token" ? "zai-business-jwt" : null)),
  422. },
  423. });
  424. const result = await provider.batchPreview({
  425. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  426. });
  427. expect(result.productList).toHaveLength(1);
  428. expect(apiClient.request).toHaveBeenCalledTimes(1);
  429. expect(apiClient.request).toHaveBeenCalledWith(
  430. "https://api.z.ai/api/biz/pay/batch-preview",
  431. expect.objectContaining({
  432. method: "POST",
  433. headers: {
  434. Authorization: "zai-business-jwt",
  435. "Content-Type": "application/json",
  436. },
  437. }),
  438. );
  439. });
  440. it("ZCODE_ENV=test 时 Z.ai Coding Plan 业务接口使用 api.z.ai", async () => {
  441. vi.stubEnv("ZCODE_ENV", "test");
  442. // 修复原因:开发机若设了 ZAI_BUSINESS_BASE_URL=https://api.z.ai,
  443. // resolveZaiBusinessBaseUrl 会优先读它,覆盖 ZCODE_ENV fallback,导致断言不稳定。
  444. vi.stubEnv("ZAI_BUSINESS_BASE_URL", "");
  445. const apiClient: ApiClient = {
  446. request: vi.fn(async (input) => {
  447. const url = String(input);
  448. if (url.includes("/product/info")) {
  449. return createJsonResponse({
  450. code: 200,
  451. data: { productId: "zai-product-pro" },
  452. });
  453. }
  454. if (url.includes("/pay/check") && !url.includes("check-pending-orders")) {
  455. return createJsonResponse({ code: 200, data: "SUCCESS" });
  456. }
  457. if (url.includes("check-pending-orders") || url.includes("stripe/query")) {
  458. return createJsonResponse({ code: 200, data: [] });
  459. }
  460. return createJsonResponse({
  461. code: 200,
  462. data: {
  463. productList: [],
  464. productId: "zai-product-pro",
  465. bizId: "zai-biz-1",
  466. soldOut: false,
  467. payAmount: 18,
  468. orderId: "order-1",
  469. status: "SUCCEEDED",
  470. resultStatus: "SUCCESS",
  471. setupTokenId: "setup-token-1",
  472. },
  473. });
  474. }),
  475. };
  476. const provider = new BigModelCodingPlanSubscriptionProvider({
  477. apiClient,
  478. credentialService: {
  479. load: vi.fn(async (key) => (key === "oauth:zai:access_token" ? "zai-business-jwt" : null)),
  480. },
  481. });
  482. await provider.batchPreview({
  483. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  484. });
  485. await provider.productInfo({
  486. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  487. productId: "zai-product-pro",
  488. });
  489. await provider.preview({
  490. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  491. productId: "zai-product-pro",
  492. });
  493. await provider.checkPayment({
  494. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  495. bizId: "zai-biz-1",
  496. });
  497. await provider.checkPendingOrders({
  498. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  499. });
  500. await provider.queryStripeCards({
  501. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  502. });
  503. await provider.payStripe({
  504. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  505. productId: "zai-product-pro",
  506. paymentMethodId: "pm_1",
  507. returnUrl: "https://chat.z.ai",
  508. estimatePayAmount: { thirdPartyPayAmount: 18 },
  509. bizId: "zai-biz-1",
  510. });
  511. await provider.createPaypalSetupToken({
  512. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  513. returnUrl: "https://chat.z.ai/return",
  514. cancelUrl: "https://chat.z.ai/cancel",
  515. });
  516. expect(vi.mocked(apiClient.request).mock.calls.map((call) => String(call[0]))).toEqual([
  517. "https://api.z.ai/api/biz/pay/batch-preview",
  518. "https://api.z.ai/api/biz/product/info?productId=zai-product-pro",
  519. "https://api.z.ai/api/biz/pay/zai-preview",
  520. "https://api.z.ai/api/biz/pay/check?bizId=zai-biz-1",
  521. "https://api.z.ai/api/biz/pay/check-pending-orders",
  522. "https://api.z.ai/api/pay/stripe/query",
  523. "https://api.z.ai/api/pay/stripe/pay",
  524. "https://api.z.ai/api/pay/paypal/setupToken",
  525. ]);
  526. });
  527. it("Z.ai 缺少登录态 token 时返回未登录错误", async () => {
  528. const apiClient: ApiClient = {
  529. request: vi.fn(),
  530. };
  531. const provider = new BigModelCodingPlanSubscriptionProvider({
  532. apiClient,
  533. credentialService: {
  534. load: vi.fn(async () => null),
  535. },
  536. });
  537. await expect(
  538. provider.batchPreview({
  539. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  540. }),
  541. ).rejects.toThrow("zai_oauth_required");
  542. expect(apiClient.request).not.toHaveBeenCalled();
  543. });
  544. describe.each(["bigmodel", "zai"] as const)("%s 静态套餐配置 ID 兼容", (family) => {
  545. it.each(["legacy", "current", "both", "empty", "missing"] as const)(
  546. "%s 同时覆盖个人与团队目录",
  547. async (scenario) => {
  548. const currentId =
  549. family === "bigmodel"
  550. ? BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan
  551. : BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan;
  552. const legacyId = `builtin:${family}-coding-plan`;
  553. const product = (productId: string) => ({
  554. productId,
  555. productName: productId,
  556. tier: "LITE",
  557. subscribeMode: "CONTINUOUS",
  558. subscribePeriod: "MONTHLY",
  559. purchaseMethodName: "月付",
  560. priceCurrency: "CNY",
  561. payAmount: 123,
  562. });
  563. const config = {
  564. ...(scenario === "legacy" || scenario === "both"
  565. ? { [legacyId]: [product("legacy")] }
  566. : {}),
  567. ...(scenario === "empty" ? { [legacyId]: [] } : {}),
  568. ...(scenario === "current" || scenario === "both" || scenario === "empty"
  569. ? { [currentId]: [product("current")] }
  570. : {}),
  571. };
  572. const load = vi.fn();
  573. const provider = new BigModelCodingPlanSubscriptionProvider({
  574. apiClient: {
  575. request: vi.fn(async () =>
  576. createJsonResponse({
  577. code: 0,
  578. data: {
  579. configs: {
  580. codingPlanStaticProducts: config,
  581. codingPlanStaticTeamProducts: config,
  582. },
  583. },
  584. }),
  585. ),
  586. },
  587. credentialService: { load },
  588. });
  589. for (const result of [
  590. await provider.getStaticProducts(),
  591. await provider.getStaticTeamProducts(),
  592. ]) {
  593. expect(result[currentId]?.map((item) => item.productId)).toEqual(
  594. scenario === "missing"
  595. ? undefined
  596. : scenario === "empty"
  597. ? []
  598. : [scenario === "current" ? "current" : "legacy"],
  599. );
  600. expect(Object.hasOwn(result, legacyId)).toBe(false);
  601. }
  602. expect(load).not.toHaveBeenCalled();
  603. },
  604. );
  605. });
  606. it("getStaticProducts 从 ZCode client config 读取套餐配置且不需要 OAuth", async () => {
  607. const apiClient: ApiClient = {
  608. request: vi.fn(async () =>
  609. createJsonResponse({
  610. code: 0,
  611. msg: "",
  612. data: {
  613. configs: {
  614. codingPlanStaticProducts: {
  615. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]: [
  616. {
  617. productId: "remote-zai-lite",
  618. productName: "Remote Lite",
  619. description: ["Base usage included", "Small repo iteration"],
  620. priceUnit: "month",
  621. displayOrder: 1,
  622. priceCurrency: "USD",
  623. payAmount: 18,
  624. },
  625. ],
  626. },
  627. },
  628. },
  629. }),
  630. ),
  631. };
  632. const provider = new BigModelCodingPlanSubscriptionProvider({
  633. apiClient,
  634. credentialService: {
  635. load: vi.fn(),
  636. },
  637. });
  638. const result = await provider.getStaticProducts();
  639. expect(result[BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]?.[0]?.productId).toBe(
  640. "remote-zai-lite",
  641. );
  642. expect(result[BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan]?.[0]?.description).toEqual([
  643. "Base usage included",
  644. "Small repo iteration",
  645. ]);
  646. const requestUrl = String(vi.mocked(apiClient.request).mock.calls[0]?.[0]);
  647. expect(requestUrl).toContain("https://zcode.z.ai/api/v1/client/configs?");
  648. expect(requestUrl).toContain("app_version=");
  649. expect(requestUrl).toContain(`platform=${process.platform}-${process.arch}`);
  650. expect(apiClient.request).toHaveBeenCalledWith(expect.any(URL), expect.anything());
  651. expect(vi.mocked(apiClient.request).mock.calls[0]?.[1]).toEqual(
  652. expect.objectContaining({
  653. method: "GET",
  654. }),
  655. );
  656. });
  657. it("getStaticTeamProducts 按 provider 读取团队套餐静态配置", async () => {
  658. const apiClient: ApiClient = {
  659. request: vi.fn(async () =>
  660. createJsonResponse({
  661. code: 0,
  662. data: {
  663. configs: {
  664. codingPlanStaticTeamProducts: {
  665. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]: [
  666. {
  667. productId: "team-lite-monthly-continuous",
  668. productName: "标准版",
  669. tier: "LITE",
  670. subscribeMode: "CONTINUOUS",
  671. subscribePeriod: "MONTHLY",
  672. purchaseMethodName: "连续包月",
  673. priceCurrency: "CNY",
  674. payAmount: 199,
  675. equity: [{ text: "5小时最多:0.6亿 tokens" }],
  676. description: [{ text: "团队成员席位统一管理" }],
  677. },
  678. ],
  679. },
  680. },
  681. },
  682. }),
  683. ),
  684. };
  685. const provider = new BigModelCodingPlanSubscriptionProvider({
  686. apiClient,
  687. credentialService: { load: vi.fn() },
  688. });
  689. const result = await provider.getStaticTeamProducts();
  690. expect(result[BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]?.[0]).toMatchObject({
  691. productName: "标准版",
  692. equity: [{ text: "5小时最多:0.6亿 tokens" }],
  693. description: [{ text: "团队成员席位统一管理" }],
  694. });
  695. });
  696. it("getStaticTeamProducts 拒绝非数组 provider 配置", async () => {
  697. const apiClient: ApiClient = {
  698. request: vi.fn(async () =>
  699. createJsonResponse({
  700. code: 0,
  701. data: {
  702. configs: {
  703. codingPlanStaticTeamProducts: {
  704. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]: {},
  705. },
  706. },
  707. },
  708. }),
  709. ),
  710. };
  711. const provider = new BigModelCodingPlanSubscriptionProvider({
  712. apiClient,
  713. credentialService: { load: vi.fn() },
  714. });
  715. await expect(provider.getStaticTeamProducts()).rejects.toThrow(
  716. "invalid Coding Plan team products",
  717. );
  718. });
  719. it("getStaticTeamProducts 拒绝字段或枚举无效的商品", async () => {
  720. const apiClient: ApiClient = {
  721. request: vi.fn(async () =>
  722. createJsonResponse({
  723. code: 0,
  724. data: {
  725. configs: {
  726. codingPlanStaticTeamProducts: {
  727. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]: [
  728. {
  729. productId: "",
  730. productName: "标准版",
  731. tier: "UNKNOWN",
  732. subscribeMode: "CONTINUOUS",
  733. subscribePeriod: "MONTHLY",
  734. purchaseMethodName: "连续包月",
  735. priceCurrency: "CNY",
  736. },
  737. ],
  738. },
  739. },
  740. },
  741. }),
  742. ),
  743. };
  744. const provider = new BigModelCodingPlanSubscriptionProvider({
  745. apiClient,
  746. credentialService: { load: vi.fn() },
  747. });
  748. await expect(provider.getStaticTeamProducts()).rejects.toThrow(
  749. "invalid Coding Plan team products",
  750. );
  751. });
  752. it("getStaticTeamProducts 拒绝无效的团队文案条目", async () => {
  753. const apiClient: ApiClient = {
  754. request: vi.fn(async () =>
  755. createJsonResponse({
  756. code: 0,
  757. data: {
  758. configs: {
  759. codingPlanStaticTeamProducts: {
  760. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]: [
  761. {
  762. productId: "team-lite-monthly-continuous",
  763. productName: "标准版",
  764. tier: "LITE",
  765. subscribeMode: "CONTINUOUS",
  766. subscribePeriod: "MONTHLY",
  767. purchaseMethodName: "连续包月",
  768. priceCurrency: "CNY",
  769. equity: [null],
  770. },
  771. ],
  772. },
  773. },
  774. },
  775. }),
  776. ),
  777. };
  778. const provider = new BigModelCodingPlanSubscriptionProvider({
  779. apiClient,
  780. credentialService: { load: vi.fn() },
  781. });
  782. await expect(provider.getStaticTeamProducts()).rejects.toThrow(
  783. "invalid Coding Plan team products",
  784. );
  785. });
  786. it("client configs 根据 ZCODE_ENV 选择测试或生产环境", () => {
  787. expect(
  788. resolveCodingPlanClientConfigUrl({
  789. ZCODE_ENV: "test",
  790. }).toString(),
  791. ).toBe("https://zcode.z.ai/api/v1/client/configs");
  792. expect(
  793. resolveCodingPlanClientConfigUrl({
  794. ZCODE_ENV: "production",
  795. ZCODE_PRODUCTION_BASE_URL: "https://runtime.example.com",
  796. }).toString(),
  797. ).toBe("https://runtime.example.com/api/v1/client/configs");
  798. });
  799. it("getForceUpdateConfig 从 ZCode client config 读取强制升级配置", async () => {
  800. const apiClient: ApiClient = {
  801. request: vi.fn(async () =>
  802. createJsonResponse({
  803. code: 0,
  804. msg: "",
  805. data: {
  806. configs: {
  807. forceUpdate: {
  808. minimalVersion: " 4.0.0 ",
  809. },
  810. },
  811. },
  812. }),
  813. ),
  814. };
  815. const provider = new BigModelCodingPlanSubscriptionProvider({
  816. apiClient,
  817. credentialService: {
  818. load: vi.fn(),
  819. },
  820. });
  821. await expect(provider.getForceUpdateConfig()).resolves.toEqual({
  822. minimalVersion: "4.0.0",
  823. });
  824. expect(apiClient.request).toHaveBeenCalledWith(
  825. expect.any(URL),
  826. expect.objectContaining({
  827. method: "GET",
  828. }),
  829. );
  830. });
  831. it("getForceUpdateConfig 在字段缺失时返回 null", async () => {
  832. const apiClient: ApiClient = {
  833. request: vi.fn(async () =>
  834. createJsonResponse({
  835. code: 0,
  836. msg: "",
  837. data: {
  838. configs: {},
  839. },
  840. }),
  841. ),
  842. };
  843. const provider = new BigModelCodingPlanSubscriptionProvider({
  844. apiClient,
  845. credentialService: {
  846. load: vi.fn(),
  847. },
  848. });
  849. await expect(provider.getForceUpdateConfig()).resolves.toBeNull();
  850. });
  851. it("getForceUpdateConfig 在 minimalVersion 类型不合法时返回 null", async () => {
  852. const apiClient: ApiClient = {
  853. request: vi.fn(async () =>
  854. createJsonResponse({
  855. code: 0,
  856. msg: "",
  857. data: {
  858. configs: {
  859. forceUpdate: {
  860. minimalVersion: 4,
  861. },
  862. },
  863. },
  864. }),
  865. ),
  866. };
  867. const provider = new BigModelCodingPlanSubscriptionProvider({
  868. apiClient,
  869. credentialService: {
  870. load: vi.fn(),
  871. },
  872. });
  873. await expect(provider.getForceUpdateConfig()).resolves.toBeNull();
  874. });
  875. it("getStartPlanPreview 从 ZCode client config 读取未登录 Start Plan 预览", async () => {
  876. const apiClient: ApiClient = {
  877. request: vi.fn(async () =>
  878. createJsonResponse({
  879. code: 0,
  880. msg: "",
  881. data: {
  882. configs: {
  883. startPlanPreview: {
  884. planId: "zcode-v3-start-plan",
  885. name: "ZCode V3 Start Plan",
  886. entitlements: [
  887. {
  888. grantUnits: 10_000_000,
  889. meter: "model_usage",
  890. period: "daily",
  891. showName: "GLM-5.2",
  892. unitType: "token",
  893. },
  894. ],
  895. },
  896. },
  897. },
  898. }),
  899. ),
  900. };
  901. const provider = new BigModelCodingPlanSubscriptionProvider({
  902. apiClient,
  903. credentialService: {
  904. load: vi.fn(),
  905. },
  906. });
  907. const result = await provider.getStartPlanPreview();
  908. expect(result).toEqual({
  909. planId: "zcode-v3-start-plan",
  910. name: "ZCode V3 Start Plan",
  911. entitlements: [
  912. {
  913. grantUnits: 10_000_000,
  914. meter: "model_usage",
  915. period: "daily",
  916. showName: "GLM-5.2",
  917. unitType: "token",
  918. },
  919. ],
  920. });
  921. expect(apiClient.request).toHaveBeenCalledWith(
  922. expect.any(URL),
  923. expect.objectContaining({
  924. method: "GET",
  925. }),
  926. );
  927. });
  928. it("getBillingDiscount 仅在字段存在时返回活动配置", async () => {
  929. const apiClient: ApiClient = {
  930. request: vi.fn(async () =>
  931. createJsonResponse({
  932. code: 0,
  933. msg: "",
  934. data: {
  935. configs: {
  936. codingPlanBillingDiscount: {
  937. "zh-CN": {
  938. cardTitle: "限时 150% 配额活动",
  939. cardBody: "升级 Coding Plan,可在活动期内获得150% 配额",
  940. badgeBody: "150% 配额",
  941. },
  942. "en-US": {
  943. cardTitle: "Limited-time 150% Quota Campaign",
  944. cardBody: "Upgrade your Coding Plan to get 150% quota during the campaign period",
  945. badgeBody: "150% Quota",
  946. },
  947. },
  948. },
  949. },
  950. }),
  951. ),
  952. };
  953. const provider = new BigModelCodingPlanSubscriptionProvider({
  954. apiClient,
  955. credentialService: {
  956. load: vi.fn(),
  957. },
  958. });
  959. await expect(provider.getBillingDiscount()).resolves.toEqual({
  960. "zh-CN": {
  961. cardTitle: "限时 150% 配额活动",
  962. cardBody: "升级 Coding Plan,可在活动期内获得150% 配额",
  963. badgeBody: "150% 配额",
  964. },
  965. "en-US": {
  966. cardTitle: "Limited-time 150% Quota Campaign",
  967. cardBody: "Upgrade your Coding Plan to get 150% quota during the campaign period",
  968. badgeBody: "150% Quota",
  969. },
  970. });
  971. });
  972. it("getBillingDiscount 在字段缺失时返回 undefined", async () => {
  973. const apiClient: ApiClient = {
  974. request: vi.fn(async () =>
  975. createJsonResponse({
  976. code: 0,
  977. msg: "",
  978. data: {
  979. configs: {},
  980. },
  981. }),
  982. ),
  983. };
  984. const provider = new BigModelCodingPlanSubscriptionProvider({
  985. apiClient,
  986. credentialService: {
  987. load: vi.fn(),
  988. },
  989. });
  990. await expect(provider.getBillingDiscount()).resolves.toBeUndefined();
  991. });
  992. it("getStartPlanPreview、getStaticProducts 和 getBillingDiscount 共享同一次 client config 请求", async () => {
  993. let resolveRequest: ((response: Response) => void) | undefined;
  994. const apiClient: ApiClient = {
  995. request: vi.fn(
  996. () =>
  997. new Promise<Response>((resolve) => {
  998. resolveRequest = resolve;
  999. }),
  1000. ),
  1001. };
  1002. const provider = new BigModelCodingPlanSubscriptionProvider({
  1003. apiClient,
  1004. credentialService: {
  1005. load: vi.fn(),
  1006. },
  1007. });
  1008. const previewPromise = provider.getStartPlanPreview();
  1009. const productsPromise = provider.getStaticProducts();
  1010. const discountPromise = provider.getBillingDiscount();
  1011. resolveRequest?.(
  1012. createJsonResponse({
  1013. code: 0,
  1014. msg: "",
  1015. data: {
  1016. configs: {
  1017. startPlanPreview: {
  1018. planId: "zcode-v3-start-plan",
  1019. name: "ZCode V3 Start Plan",
  1020. entitlements: [
  1021. {
  1022. grantUnits: 10_000_000,
  1023. meter: "model_usage",
  1024. period: "daily",
  1025. showName: "GLM-5.2",
  1026. unitType: "token",
  1027. },
  1028. ],
  1029. },
  1030. codingPlanStaticProducts: {
  1031. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]: [
  1032. {
  1033. productId: "remote-bigmodel-lite",
  1034. productName: "Remote BigModel Lite",
  1035. productEquityList: [],
  1036. priceUnit: "month",
  1037. displayOrder: 1,
  1038. priceCurrency: "CNY",
  1039. payAmount: 49,
  1040. },
  1041. ],
  1042. },
  1043. codingPlanBillingDiscount: {
  1044. "zh-CN": {
  1045. cardTitle: "限时 150% 配额活动",
  1046. cardBody: "升级 Coding Plan,可在活动期内获得150% 配额",
  1047. badgeBody: "150% 配额",
  1048. },
  1049. },
  1050. },
  1051. },
  1052. }),
  1053. );
  1054. const [preview, products, discount] = await Promise.all([
  1055. previewPromise,
  1056. productsPromise,
  1057. discountPromise,
  1058. ]);
  1059. expect(apiClient.request).toHaveBeenCalledTimes(1);
  1060. expect(preview?.planId).toBe("zcode-v3-start-plan");
  1061. expect(products[BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan]?.[0]?.productId).toBe(
  1062. "remote-bigmodel-lite",
  1063. );
  1064. expect(discount).toEqual({
  1065. "zh-CN": {
  1066. cardTitle: "限时 150% 配额活动",
  1067. cardBody: "升级 Coding Plan,可在活动期内获得150% 配额",
  1068. badgeBody: "150% 配额",
  1069. },
  1070. });
  1071. await provider.getStartPlanPreview();
  1072. await provider.getStaticProducts();
  1073. await provider.getBillingDiscount();
  1074. expect(apiClient.request).toHaveBeenCalledTimes(1);
  1075. });
  1076. it("client configs 缓存 1 小时后重新请求", async () => {
  1077. vi.useFakeTimers();
  1078. vi.setSystemTime(new Date("2026-06-12T00:00:00.000Z"));
  1079. const apiClient: ApiClient = {
  1080. request: vi
  1081. .fn()
  1082. .mockResolvedValueOnce(
  1083. createJsonResponse({
  1084. code: 0,
  1085. msg: "",
  1086. data: {
  1087. configs: {
  1088. codingPlanBillingDiscount: {
  1089. "zh-CN": {
  1090. badgeBody: "第一版",
  1091. },
  1092. },
  1093. },
  1094. },
  1095. }),
  1096. )
  1097. .mockResolvedValueOnce(
  1098. createJsonResponse({
  1099. code: 0,
  1100. msg: "",
  1101. data: {
  1102. configs: {
  1103. codingPlanBillingDiscount: {
  1104. "zh-CN": {
  1105. badgeBody: "第二版",
  1106. },
  1107. },
  1108. },
  1109. },
  1110. }),
  1111. ),
  1112. };
  1113. const provider = new BigModelCodingPlanSubscriptionProvider({
  1114. apiClient,
  1115. credentialService: {
  1116. load: vi.fn(),
  1117. },
  1118. });
  1119. await expect(provider.getBillingDiscount()).resolves.toEqual({
  1120. "zh-CN": { badgeBody: "第一版" },
  1121. });
  1122. vi.setSystemTime(new Date("2026-06-12T00:59:59.000Z"));
  1123. await expect(provider.getBillingDiscount()).resolves.toEqual({
  1124. "zh-CN": { badgeBody: "第一版" },
  1125. });
  1126. expect(apiClient.request).toHaveBeenCalledTimes(1);
  1127. vi.setSystemTime(new Date("2026-06-12T01:00:01.000Z"));
  1128. await expect(provider.getBillingDiscount()).resolves.toEqual({
  1129. "zh-CN": { badgeBody: "第二版" },
  1130. });
  1131. expect(apiClient.request).toHaveBeenCalledTimes(2);
  1132. });
  1133. it("getEnterprisePricing 未登录时走公开定价接口且不读取 OAuth", async () => {
  1134. const apiClient: ApiClient = {
  1135. request: vi.fn(async () =>
  1136. createJsonResponse({
  1137. code: 200,
  1138. data: {
  1139. productList: [
  1140. {
  1141. productId: "enterprise-lite-monthly",
  1142. tier: "LITE",
  1143. subscribeMode: "ONE_TIME",
  1144. subscribePeriod: "MONTHLY",
  1145. purchaseMethodName: "按月采购",
  1146. originalAmount: 270,
  1147. discountAmount: 27,
  1148. payAmount: 243,
  1149. renewAmount: 243,
  1150. },
  1151. ],
  1152. },
  1153. }),
  1154. ),
  1155. };
  1156. const credentialService = { load: vi.fn() };
  1157. const provider = new BigModelCodingPlanSubscriptionProvider({
  1158. apiClient,
  1159. credentialService,
  1160. });
  1161. const result = await provider.getEnterprisePricing({
  1162. authenticated: false,
  1163. });
  1164. expect(result.productList[0]?.productId).toBe("enterprise-lite-monthly");
  1165. expect(credentialService.load).not.toHaveBeenCalled();
  1166. expect(apiClient.request).toHaveBeenCalledWith(
  1167. "https://bigmodel.cn/api/biz/campaign/partner/enterprise/pricing",
  1168. expect.objectContaining({
  1169. method: "GET",
  1170. }),
  1171. );
  1172. });
  1173. it("getEnterprisePricing 登录态使用 BigModel OAuth token 且不添加 Bearer", async () => {
  1174. const apiClient: ApiClient = {
  1175. request: vi.fn(async () =>
  1176. createJsonResponse({
  1177. code: 200,
  1178. data: { productList: [] },
  1179. }),
  1180. ),
  1181. };
  1182. const provider = new BigModelCodingPlanSubscriptionProvider({
  1183. apiClient,
  1184. credentialService: createBigModelCredentialService("oauth-token"),
  1185. });
  1186. await provider.getEnterprisePricing({ authenticated: true });
  1187. expect(apiClient.request).toHaveBeenCalledTimes(1);
  1188. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  1189. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing",
  1190. );
  1191. expect(vi.mocked(apiClient.request).mock.calls[0]?.[1]).toMatchObject({
  1192. method: "GET",
  1193. headers: {
  1194. Authorization: "oauth-token",
  1195. "Content-Type": "application/json",
  1196. },
  1197. });
  1198. });
  1199. it("getEnterprisePricing 会用 customerInfo 给已购 Team Plan 补齐项目上下文", async () => {
  1200. const apiClient: ApiClient = {
  1201. request: vi
  1202. .fn()
  1203. .mockResolvedValueOnce(
  1204. createJsonResponse({
  1205. code: 200,
  1206. data: {
  1207. productList: [
  1208. {
  1209. productId: "product-0e2085",
  1210. tier: "PRO",
  1211. subscribeMode: "CONTINUOUS",
  1212. subscribePeriod: "MONTHLY",
  1213. subscribed: true,
  1214. },
  1215. ],
  1216. },
  1217. }),
  1218. )
  1219. .mockResolvedValueOnce(
  1220. createJsonResponse({
  1221. code: 200,
  1222. data: {
  1223. organizations: [
  1224. {
  1225. organizationId: "org-team",
  1226. organizationName: "默认机构",
  1227. projects: [
  1228. {
  1229. projectId: "proj-default",
  1230. projectName: "团队编程套餐项目",
  1231. projectType: 1,
  1232. },
  1233. {
  1234. projectId: "proj-team",
  1235. projectName: "自定义团队项目",
  1236. projectType: 2,
  1237. },
  1238. ],
  1239. },
  1240. ],
  1241. },
  1242. }),
  1243. ),
  1244. };
  1245. const provider = new BigModelCodingPlanSubscriptionProvider({
  1246. apiClient,
  1247. credentialService: createBigModelCredentialService("oauth-token"),
  1248. });
  1249. const result = await provider.getEnterprisePricing({ authenticated: true });
  1250. expect(result.productList[0]).toMatchObject({
  1251. organizationId: "org-team",
  1252. projectId: "proj-team",
  1253. projectName: "自定义团队项目",
  1254. teamProjects: [
  1255. {
  1256. organizationId: "org-team",
  1257. projectId: "proj-team",
  1258. projectName: "自定义团队项目",
  1259. },
  1260. ],
  1261. });
  1262. });
  1263. it("getEnterprisePricing 已购 Team Plan 只有机构 ID 时仍从机构数组补齐项目上下文", async () => {
  1264. const apiClient: ApiClient = {
  1265. request: vi
  1266. .fn()
  1267. .mockResolvedValueOnce(
  1268. createJsonResponse({
  1269. code: 200,
  1270. data: {
  1271. productList: [
  1272. {
  1273. productId: "product-0e2085",
  1274. tier: "PRO",
  1275. subscribeMode: "CONTINUOUS",
  1276. subscribePeriod: "MONTHLY",
  1277. subscribed: true,
  1278. organizationId: "org-target",
  1279. },
  1280. ],
  1281. },
  1282. }),
  1283. )
  1284. .mockResolvedValueOnce(
  1285. createJsonResponse({
  1286. code: 200,
  1287. data: {
  1288. organizations: [
  1289. {
  1290. organizationId: "org-other",
  1291. organizationName: "其他机构",
  1292. projects: [
  1293. {
  1294. projectId: "proj-other",
  1295. projectName: "其他团队项目",
  1296. projectType: 2,
  1297. },
  1298. ],
  1299. },
  1300. {
  1301. organizationId: "org-target",
  1302. organizationName: "目标机构",
  1303. projects: [
  1304. {
  1305. projectId: "proj-default",
  1306. projectName: "默认项目",
  1307. projectType: 1,
  1308. },
  1309. {
  1310. projectId: "proj-team",
  1311. projectName: "目标团队项目",
  1312. projectType: 2,
  1313. },
  1314. ],
  1315. },
  1316. ],
  1317. },
  1318. }),
  1319. ),
  1320. };
  1321. const provider = new BigModelCodingPlanSubscriptionProvider({
  1322. apiClient,
  1323. credentialService: createBigModelCredentialService("oauth-token"),
  1324. });
  1325. const result = await provider.getEnterprisePricing({ authenticated: true });
  1326. expect(result.productList[0]).toMatchObject({
  1327. organizationId: "org-target",
  1328. organizationName: "目标机构",
  1329. projectId: "proj-team",
  1330. projectName: "目标团队项目",
  1331. teamProjects: [
  1332. {
  1333. organizationId: "org-target",
  1334. projectId: "proj-team",
  1335. projectName: "目标团队项目",
  1336. },
  1337. ],
  1338. });
  1339. });
  1340. it("getEnterprisePricing pricing 未标记订阅但 customerInfo 有团队项目时补 Team Plan 入口", async () => {
  1341. const apiClient: ApiClient = {
  1342. request: vi
  1343. .fn()
  1344. .mockResolvedValueOnce(
  1345. createJsonResponse({
  1346. code: 200,
  1347. data: {
  1348. productList: [
  1349. {
  1350. productId: "product-max",
  1351. tier: "MAX",
  1352. subscribeMode: "CONTINUOUS",
  1353. subscribePeriod: "MONTHLY",
  1354. subscribed: false,
  1355. },
  1356. {
  1357. productId: "product-pro-monthly",
  1358. tier: "PRO",
  1359. subscribeMode: "ONE_TIME",
  1360. subscribePeriod: "MONTHLY",
  1361. subscribed: false,
  1362. },
  1363. ],
  1364. },
  1365. }),
  1366. )
  1367. .mockResolvedValueOnce(
  1368. createJsonResponse({
  1369. code: 200,
  1370. data: {
  1371. organizations: [
  1372. {
  1373. organizationId: "org-default",
  1374. organizationName: "默认机构",
  1375. projects: [
  1376. {
  1377. projectId: "proj-default",
  1378. projectName: "默认项目",
  1379. projectType: 1,
  1380. },
  1381. ],
  1382. },
  1383. {
  1384. organizationId: "org-team",
  1385. organizationName: "团队机构",
  1386. projects: [
  1387. {
  1388. projectId: "proj-team",
  1389. projectName: "团队编程套餐项目",
  1390. projectType: 2,
  1391. },
  1392. ],
  1393. },
  1394. ],
  1395. },
  1396. }),
  1397. ),
  1398. };
  1399. const provider = new BigModelCodingPlanSubscriptionProvider({
  1400. apiClient,
  1401. credentialService: createBigModelCredentialService("oauth-token"),
  1402. });
  1403. const result = await provider.getEnterprisePricing({ authenticated: true });
  1404. expect(result.productList[1]).toMatchObject({
  1405. productId: "product-pro-monthly",
  1406. subscribed: true,
  1407. organizationId: "org-team",
  1408. projectId: "proj-team",
  1409. projectName: "团队编程套餐项目",
  1410. });
  1411. });
  1412. it("getEnterprisePricing 会为多个已购 Team Plan 项目预热 zcode-team-api-key", async () => {
  1413. const requestUrls: string[] = [];
  1414. const requestMethods: Array<string | undefined> = [];
  1415. const apiClient: ApiClient = {
  1416. request: vi.fn(async (input, init) => {
  1417. const url = input.toString();
  1418. requestUrls.push(url);
  1419. requestMethods.push(init?.method);
  1420. if (url.endsWith("/api/biz/subscription/enterprise/v2/pricing")) {
  1421. return createJsonResponse({
  1422. code: 200,
  1423. data: {
  1424. productList: [
  1425. {
  1426. productId: "product-pro-monthly",
  1427. tier: "PRO",
  1428. subscribeMode: "ONE_TIME",
  1429. subscribePeriod: "MONTHLY",
  1430. subscribed: true,
  1431. },
  1432. ],
  1433. },
  1434. });
  1435. }
  1436. if (url.endsWith("/api/biz/customer/getCustomerInfo")) {
  1437. return createJsonResponse({
  1438. code: 200,
  1439. data: {
  1440. organizations: [
  1441. {
  1442. organizationId: "org-a",
  1443. organizationName: "团队 A",
  1444. projects: [
  1445. {
  1446. projectId: "proj-a",
  1447. projectName: "项目 A",
  1448. projectType: 2,
  1449. },
  1450. ],
  1451. },
  1452. {
  1453. organizationId: "org-b",
  1454. organizationName: "团队 B",
  1455. projects: [
  1456. {
  1457. projectId: "proj-b",
  1458. projectName: "项目 B",
  1459. projectType: 2,
  1460. },
  1461. ],
  1462. },
  1463. ],
  1464. },
  1465. });
  1466. }
  1467. if (url.endsWith("/organization/org-a/projects/proj-a/api_keys")) {
  1468. if (init?.method === "GET") {
  1469. return createJsonResponse({
  1470. code: 200,
  1471. data: [{ apiKey: "team-a-ak", keyType: 2, name: "zcode-team-api-key" }],
  1472. });
  1473. }
  1474. }
  1475. if (url.endsWith("/organization/org-b/projects/proj-b/api_keys")) {
  1476. if (init?.method === "GET") {
  1477. return createJsonResponse({ code: 200, data: [] });
  1478. }
  1479. if (init?.method === "POST") {
  1480. expect(init.headers).toMatchObject({
  1481. "bigmodel-organization": "org-b",
  1482. "bigmodel-project": "proj-b",
  1483. });
  1484. expect(JSON.parse(String(init.body))).toEqual({
  1485. name: "zcode-team-api-key",
  1486. keyType: 2,
  1487. usageScene: 1,
  1488. });
  1489. return createJsonResponse({
  1490. code: 200,
  1491. data: {
  1492. apiKey: "team-b-ak",
  1493. keyType: 2,
  1494. name: "zcode-team-api-key",
  1495. },
  1496. });
  1497. }
  1498. }
  1499. throw new Error(`unexpected request: ${url}`);
  1500. }),
  1501. };
  1502. const provider = new BigModelCodingPlanSubscriptionProvider({
  1503. apiClient,
  1504. credentialService: createBigModelCredentialService("oauth-token"),
  1505. });
  1506. const result = await provider.getEnterprisePricing({ authenticated: true });
  1507. expect(result.productList[0]?.teamProjects).toHaveLength(2);
  1508. expect(result.productList[0]?.teamProjects).toMatchObject([
  1509. {
  1510. organizationId: "org-a",
  1511. projectId: "proj-a",
  1512. apiKeyStatus: "available",
  1513. },
  1514. {
  1515. organizationId: "org-b",
  1516. projectId: "proj-b",
  1517. apiKeyStatus: "available",
  1518. },
  1519. ]);
  1520. expect(requestUrls).toEqual([
  1521. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing",
  1522. "https://bigmodel.cn/api/biz/customer/getCustomerInfo",
  1523. "https://bigmodel.cn/api/biz/v1/organization/org-a/projects/proj-a/api_keys",
  1524. "https://bigmodel.cn/api/biz/v1/organization/org-b/projects/proj-b/api_keys",
  1525. "https://bigmodel.cn/api/biz/v1/organization/org-b/projects/proj-b/api_keys",
  1526. ]);
  1527. expect(requestMethods).toEqual(["GET", "GET", "GET", "GET", "POST"]);
  1528. });
  1529. it("getEnterprisePricing 单个 Team Plan 项目 key 预热失败不阻断其他团队", async () => {
  1530. const requestUrls: string[] = [];
  1531. const apiClient: ApiClient = {
  1532. request: vi.fn(async (input, init) => {
  1533. const url = input.toString();
  1534. requestUrls.push(url);
  1535. if (url.endsWith("/api/biz/subscription/enterprise/v2/pricing")) {
  1536. return createJsonResponse({
  1537. code: 200,
  1538. data: {
  1539. productList: [
  1540. {
  1541. productId: "product-pro-monthly",
  1542. tier: "PRO",
  1543. subscribeMode: "ONE_TIME",
  1544. subscribePeriod: "MONTHLY",
  1545. subscribed: true,
  1546. },
  1547. ],
  1548. },
  1549. });
  1550. }
  1551. if (url.endsWith("/api/biz/customer/getCustomerInfo")) {
  1552. return createJsonResponse({
  1553. code: 200,
  1554. data: {
  1555. organizations: [
  1556. {
  1557. organizationId: "org-a",
  1558. organizationName: "团队 A",
  1559. projects: [
  1560. {
  1561. projectId: "proj-a",
  1562. projectName: "项目 A",
  1563. projectType: 2,
  1564. },
  1565. ],
  1566. },
  1567. {
  1568. organizationId: "org-b",
  1569. organizationName: "团队 B",
  1570. projects: [
  1571. {
  1572. projectId: "proj-b",
  1573. projectName: "项目 B",
  1574. projectType: 2,
  1575. },
  1576. ],
  1577. },
  1578. ],
  1579. },
  1580. });
  1581. }
  1582. if (url.endsWith("/organization/org-a/projects/proj-a/api_keys")) {
  1583. throw new Error("org-a key failed");
  1584. }
  1585. if (
  1586. url.endsWith("/organization/org-b/projects/proj-b/api_keys") &&
  1587. init?.method === "GET"
  1588. ) {
  1589. return createJsonResponse({
  1590. code: 200,
  1591. data: [{ apiKey: "team-b-ak", keyType: 2, name: "zcode-team-api-key" }],
  1592. });
  1593. }
  1594. throw new Error(`unexpected request: ${url}`);
  1595. }),
  1596. };
  1597. const provider = new BigModelCodingPlanSubscriptionProvider({
  1598. apiClient,
  1599. credentialService: createBigModelCredentialService("oauth-token"),
  1600. });
  1601. const result = await provider.getEnterprisePricing({ authenticated: true });
  1602. expect(result.productList[0]?.teamProjects).toHaveLength(2);
  1603. expect(result.productList[0]?.teamProjects).toMatchObject([
  1604. {
  1605. organizationId: "org-a",
  1606. projectId: "proj-a",
  1607. apiKeyStatus: "unavailable",
  1608. apiKeyUnavailableReason: "request_failed",
  1609. },
  1610. {
  1611. organizationId: "org-b",
  1612. projectId: "proj-b",
  1613. apiKeyStatus: "available",
  1614. },
  1615. ]);
  1616. expect(requestUrls).toContain(
  1617. "https://bigmodel.cn/api/biz/v1/organization/org-b/projects/proj-b/api_keys",
  1618. );
  1619. });
  1620. it("getEnterprisePricing 会把没有有效团队套餐授权的 Team Plan 项目标为不可用", async () => {
  1621. const apiClient: ApiClient = {
  1622. request: vi.fn(async (input, init) => {
  1623. const url = input.toString();
  1624. if (url.endsWith("/api/biz/subscription/enterprise/v2/pricing")) {
  1625. return createJsonResponse({
  1626. code: 200,
  1627. data: {
  1628. productList: [
  1629. {
  1630. productId: "product-pro-monthly",
  1631. tier: "PRO",
  1632. subscribeMode: "ONE_TIME",
  1633. subscribePeriod: "MONTHLY",
  1634. subscribed: true,
  1635. },
  1636. ],
  1637. },
  1638. });
  1639. }
  1640. if (url.endsWith("/api/biz/customer/getCustomerInfo")) {
  1641. return createJsonResponse({
  1642. code: 200,
  1643. data: {
  1644. organizations: [
  1645. {
  1646. organizationId: "org-missing",
  1647. organizationName: "团队 Missing",
  1648. projects: [
  1649. {
  1650. projectId: "proj-missing",
  1651. projectName: "项目 Missing",
  1652. projectType: 2,
  1653. },
  1654. ],
  1655. },
  1656. ],
  1657. },
  1658. });
  1659. }
  1660. if (
  1661. url.endsWith("/organization/org-missing/projects/proj-missing/api_keys") &&
  1662. init?.method === "GET"
  1663. ) {
  1664. return createJsonResponse({ code: 200, data: [] });
  1665. }
  1666. if (
  1667. url.endsWith("/organization/org-missing/projects/proj-missing/api_keys") &&
  1668. init?.method === "POST"
  1669. ) {
  1670. return createJsonResponse({
  1671. code: 500,
  1672. success: false,
  1673. msg: "您当前暂无有效的团队套餐授权记录,无法创建API Key",
  1674. data: null,
  1675. });
  1676. }
  1677. throw new Error(`unexpected request: ${url}`);
  1678. }),
  1679. };
  1680. const provider = new BigModelCodingPlanSubscriptionProvider({
  1681. apiClient,
  1682. credentialService: createBigModelCredentialService("oauth-token"),
  1683. });
  1684. const result = await provider.getEnterprisePricing({ authenticated: true });
  1685. expect(result.productList[0]?.teamProjects?.[0]).toMatchObject({
  1686. organizationId: "org-missing",
  1687. projectId: "proj-missing",
  1688. apiKeyStatus: "unavailable",
  1689. apiKeyUnavailableReason: "no_valid_team_plan_authorization",
  1690. apiKeyUnavailableMessage: "您当前暂无有效的团队套餐授权记录,无法创建API Key",
  1691. });
  1692. });
  1693. it("ZCODE_ENV=test 时 Team Plan 企业接口使用 bigmodel.cn", async () => {
  1694. vi.stubEnv("ZCODE_ENV", "test");
  1695. const apiClient: ApiClient = {
  1696. request: vi
  1697. .fn()
  1698. .mockResolvedValueOnce(
  1699. createJsonResponse({
  1700. code: 200,
  1701. data: { productList: [] },
  1702. }),
  1703. )
  1704. .mockResolvedValueOnce(
  1705. createJsonResponse({
  1706. code: 200,
  1707. data: { productList: [] },
  1708. }),
  1709. )
  1710. .mockResolvedValueOnce(
  1711. createJsonResponse({
  1712. code: 200,
  1713. data: {
  1714. giveBalance: 0,
  1715. cashBalance: 0,
  1716. totalBalance: 0,
  1717. },
  1718. }),
  1719. )
  1720. .mockResolvedValueOnce(
  1721. createJsonResponse({
  1722. code: 200,
  1723. data: [],
  1724. }),
  1725. )
  1726. .mockResolvedValueOnce(
  1727. createJsonResponse({
  1728. code: 200,
  1729. data: { status: "SUCCESS" },
  1730. }),
  1731. ),
  1732. };
  1733. const provider = new BigModelCodingPlanSubscriptionProvider({
  1734. apiClient,
  1735. credentialService: createBigModelCredentialService("oauth-token"),
  1736. });
  1737. await provider.getEnterprisePricing({ authenticated: false });
  1738. await provider.getEnterprisePricing({ authenticated: true });
  1739. await provider.getEnterpriseBalance();
  1740. await provider.getEnterprisePendingOrders();
  1741. await provider.checkEnterpriseOrderStatus({ orderNo: "ORDER-1" });
  1742. expect(vi.mocked(apiClient.request).mock.calls.map((call) => String(call[0]))).toEqual([
  1743. "https://bigmodel.cn/api/biz/campaign/partner/enterprise/pricing",
  1744. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing",
  1745. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/balance",
  1746. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/orders/pending",
  1747. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/order/ORDER-1/status",
  1748. ]);
  1749. });
  1750. it("企业套餐试算和下单使用 BigModel OAuth token 并原样传递金额", async () => {
  1751. const apiClient: ApiClient = {
  1752. request: vi
  1753. .fn()
  1754. .mockResolvedValueOnce(
  1755. createJsonResponse({
  1756. code: 200,
  1757. data: {
  1758. totalOriginalAmount: 2700,
  1759. campaignDiscountAmount: 270,
  1760. discountDetails: [],
  1761. totalPayAmount: 2430,
  1762. giveDeductAmount: 0,
  1763. balanceDeductAmount: 0,
  1764. thirdPayAmount: 2430,
  1765. },
  1766. }),
  1767. )
  1768. .mockResolvedValueOnce(
  1769. createJsonResponse({
  1770. code: 200,
  1771. data: {
  1772. orderNo: "20260507001",
  1773. subscriptionNo: "SUB20260507",
  1774. totalOriginalAmount: 2700,
  1775. campaignDiscountAmount: 270,
  1776. totalPayAmount: 2430,
  1777. thirdPayAmount: 2430,
  1778. discountDetails: [],
  1779. payUrl: "https://openapi.alipay.com/pay",
  1780. alipayJumpSchema: "alipays://platformapi/startApp",
  1781. expireTime: "2026-05-07 10:30:00",
  1782. },
  1783. }),
  1784. ),
  1785. };
  1786. const provider = new BigModelCodingPlanSubscriptionProvider({
  1787. apiClient,
  1788. credentialService: createBigModelCredentialService("oauth-token"),
  1789. });
  1790. const estimate = await provider.calculateEnterpriseOrder({
  1791. productId: "enterprise-lite-monthly",
  1792. maxSeats: 10,
  1793. subscribePeriod: "MONTHLY",
  1794. subscribeMode: "ONE_TIME",
  1795. duration: 1,
  1796. giveAmount: 0,
  1797. balanceDeductAmount: 0,
  1798. });
  1799. await provider.createEnterpriseOrder({
  1800. productId: "enterprise-lite-monthly",
  1801. maxSeats: 10,
  1802. subscribePeriod: "MONTHLY",
  1803. subscribeMode: "ONE_TIME",
  1804. purchaseType: "PAY",
  1805. duration: 1,
  1806. giveAmount: 0,
  1807. balanceDeductAmount: 0,
  1808. totalOriginalAmount: estimate.totalOriginalAmount,
  1809. totalPayAmount: estimate.totalPayAmount,
  1810. thirdPayAmount: estimate.thirdPayAmount,
  1811. });
  1812. expect(apiClient.request).toHaveBeenNthCalledWith(
  1813. 1,
  1814. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/order/calculate",
  1815. expect.objectContaining({
  1816. method: "POST",
  1817. headers: {
  1818. Authorization: "oauth-token",
  1819. "Content-Type": "application/json",
  1820. },
  1821. body: JSON.stringify({
  1822. productId: "enterprise-lite-monthly",
  1823. maxSeats: 10,
  1824. subscribePeriod: "MONTHLY",
  1825. subscribeMode: "ONE_TIME",
  1826. duration: 1,
  1827. giveAmount: 0,
  1828. balanceDeductAmount: 0,
  1829. }),
  1830. }),
  1831. );
  1832. expect(apiClient.request).toHaveBeenNthCalledWith(
  1833. 2,
  1834. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/order",
  1835. expect.objectContaining({
  1836. method: "POST",
  1837. body: JSON.stringify({
  1838. productId: "enterprise-lite-monthly",
  1839. maxSeats: 10,
  1840. subscribePeriod: "MONTHLY",
  1841. subscribeMode: "ONE_TIME",
  1842. purchaseType: "PAY",
  1843. duration: 1,
  1844. giveAmount: 0,
  1845. balanceDeductAmount: 0,
  1846. totalOriginalAmount: 2700,
  1847. totalPayAmount: 2430,
  1848. thirdPayAmount: 2430,
  1849. }),
  1850. }),
  1851. );
  1852. });
  1853. it("getEnterpriseBalance 使用 BigModel OAuth token 查询企业余额", async () => {
  1854. const apiClient: ApiClient = {
  1855. request: vi.fn(async () =>
  1856. createJsonResponse({
  1857. code: 200,
  1858. data: {
  1859. giveBalance: 1000,
  1860. cashBalance: 1500,
  1861. totalBalance: 2500,
  1862. },
  1863. }),
  1864. ),
  1865. };
  1866. const provider = new BigModelCodingPlanSubscriptionProvider({
  1867. apiClient,
  1868. credentialService: createBigModelCredentialService("oauth-token"),
  1869. });
  1870. await expect(provider.getEnterpriseBalance()).resolves.toEqual({
  1871. giveBalance: 1000,
  1872. cashBalance: 1500,
  1873. totalBalance: 2500,
  1874. });
  1875. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  1876. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/balance",
  1877. );
  1878. expect(vi.mocked(apiClient.request).mock.calls[0]?.[1]).toMatchObject({
  1879. method: "GET",
  1880. headers: {
  1881. Authorization: "oauth-token",
  1882. "Content-Type": "application/json",
  1883. },
  1884. });
  1885. });
  1886. it("createSign 默认 ALI 且固定 isDelay=0", async () => {
  1887. const apiClient: ApiClient = {
  1888. request: vi.fn(async () =>
  1889. createJsonResponse({
  1890. code: 200,
  1891. data: {
  1892. orderId: "order-1",
  1893. sign: "<form></form>",
  1894. signType: "ALI",
  1895. },
  1896. }),
  1897. ),
  1898. };
  1899. const provider = new BigModelCodingPlanSubscriptionProvider({
  1900. apiClient,
  1901. credentialService: createBigModelCredentialService(),
  1902. });
  1903. await provider.createSign({ bizId: "biz-1" });
  1904. const init = (apiClient.request as ReturnType<typeof vi.fn>).mock.calls[0]?.[1] as RequestInit;
  1905. expect(JSON.parse(String(init.body))).toEqual({
  1906. bizId: "biz-1",
  1907. payType: "ALI",
  1908. renew: null,
  1909. isDelay: 0,
  1910. effectiveTime: null,
  1911. });
  1912. });
  1913. it("updateSign 调用套餐变更签约接口", async () => {
  1914. const apiClient: ApiClient = {
  1915. request: vi.fn(async () =>
  1916. createJsonResponse({
  1917. code: 200,
  1918. data: {
  1919. orderId: "order-2",
  1920. sign: "https://pay.example",
  1921. signType: "ALI",
  1922. },
  1923. }),
  1924. ),
  1925. };
  1926. const provider = new BigModelCodingPlanSubscriptionProvider({
  1927. apiClient,
  1928. credentialService: createBigModelCredentialService(),
  1929. });
  1930. await provider.updateSign({ bizId: "biz-2" });
  1931. expect(apiClient.request).toHaveBeenCalledWith(
  1932. "https://bigmodel.cn/api/biz/pay/product/update/sign",
  1933. expect.objectContaining({
  1934. method: "POST",
  1935. }),
  1936. );
  1937. });
  1938. it("preview 透传安全校验 ticket 和 randstr", async () => {
  1939. const apiClient: ApiClient = {
  1940. request: vi.fn(async () =>
  1941. createJsonResponse({
  1942. code: 200,
  1943. data: {
  1944. productId: "product-1",
  1945. bizId: "biz-1",
  1946. soldOut: false,
  1947. payAmount: 149,
  1948. },
  1949. }),
  1950. ),
  1951. };
  1952. const provider = new BigModelCodingPlanSubscriptionProvider({
  1953. apiClient,
  1954. credentialService: createBigModelCredentialService(),
  1955. });
  1956. await provider.preview({
  1957. productId: "product-1",
  1958. ticket: "fixture-ticket",
  1959. randstr: "fixture-randstr",
  1960. });
  1961. const init = (apiClient.request as ReturnType<typeof vi.fn>).mock.calls[0]?.[1] as RequestInit;
  1962. expect(JSON.parse(String(init.body))).toMatchObject({
  1963. productId: "product-1",
  1964. ticket: "fixture-ticket",
  1965. randstr: "fixture-randstr",
  1966. salesChannel: "zcode",
  1967. });
  1968. });
  1969. it("Z.ai preview 使用海外试算接口", async () => {
  1970. const apiClient: ApiClient = {
  1971. request: vi.fn(async () => {
  1972. return createJsonResponse({
  1973. code: 200,
  1974. data: {
  1975. productId: "zai-product-pro",
  1976. bizId: "zai-biz-1",
  1977. soldOut: false,
  1978. payAmount: 18,
  1979. },
  1980. });
  1981. }),
  1982. };
  1983. const provider = new BigModelCodingPlanSubscriptionProvider({
  1984. apiClient,
  1985. credentialService: {
  1986. load: vi.fn(async (key) => (key === "oauth:zai:access_token" ? "zai-business-jwt" : null)),
  1987. },
  1988. });
  1989. await provider.preview({
  1990. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  1991. productId: "zai-product-pro",
  1992. ticket: "fixture-ticket",
  1993. randstr: "fixture-randstr",
  1994. });
  1995. expect(apiClient.request).toHaveBeenNthCalledWith(
  1996. 1,
  1997. "https://api.z.ai/api/biz/pay/zai-preview",
  1998. expect.objectContaining({
  1999. method: "POST",
  2000. headers: {
  2001. Authorization: "zai-business-jwt",
  2002. "Content-Type": "application/json",
  2003. },
  2004. }),
  2005. );
  2006. const init = (apiClient.request as ReturnType<typeof vi.fn>).mock.calls[0]?.[1] as RequestInit;
  2007. expect(JSON.parse(String(init.body))).toMatchObject({
  2008. productId: "zai-product-pro",
  2009. ticket: "fixture-ticket",
  2010. randstr: "fixture-randstr",
  2011. salesChannel: "zcode",
  2012. });
  2013. });
  2014. it("Z.ai 不走 BigModel 支付宝签约接口", async () => {
  2015. const apiClient: ApiClient = {
  2016. request: vi.fn(),
  2017. };
  2018. const provider = new BigModelCodingPlanSubscriptionProvider({
  2019. apiClient,
  2020. credentialService: {
  2021. load: vi.fn(async () => "zai-business-jwt"),
  2022. },
  2023. });
  2024. await expect(
  2025. provider.createSign({
  2026. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  2027. bizId: "zai-biz-1",
  2028. }),
  2029. ).rejects.toThrow("coding_plan_zai_overseas_payment_required");
  2030. expect(apiClient.request).not.toHaveBeenCalled();
  2031. });
  2032. it("Z.ai Stripe 支付使用 pay 服务接口", async () => {
  2033. const apiClient: ApiClient = {
  2034. request: vi.fn(async () => {
  2035. return createJsonResponse({
  2036. code: 200,
  2037. data: {
  2038. orderId: "order-stripe-1",
  2039. paymentIntentId: "pi_1",
  2040. status: "SUCCEEDED",
  2041. },
  2042. });
  2043. }),
  2044. };
  2045. const provider = new BigModelCodingPlanSubscriptionProvider({
  2046. apiClient,
  2047. credentialService: {
  2048. load: vi.fn(async () => "zai-business-jwt"),
  2049. },
  2050. });
  2051. await provider.payStripe({
  2052. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  2053. productId: "zai-product-pro",
  2054. paymentMethodId: "pm_1",
  2055. returnUrl: "https://chat.z.ai",
  2056. estimatePayAmount: {
  2057. cashPayAmount: 0,
  2058. givePayAmount: 0,
  2059. thirdPartyPayAmount: 18,
  2060. },
  2061. bizId: "zai-biz-1",
  2062. renew: true,
  2063. });
  2064. expect(apiClient.request).toHaveBeenNthCalledWith(
  2065. 1,
  2066. "https://api.z.ai/api/pay/stripe/pay",
  2067. expect.objectContaining({
  2068. method: "POST",
  2069. }),
  2070. );
  2071. const init = (apiClient.request as ReturnType<typeof vi.fn>).mock.calls[0]?.[1] as RequestInit;
  2072. expect(JSON.parse(String(init.body))).toMatchObject({
  2073. productId: "zai-product-pro",
  2074. paymentMethodId: "pm_1",
  2075. returnUrl: "https://chat.z.ai",
  2076. estimatePayAmount: {
  2077. thirdPartyPayAmount: 18,
  2078. },
  2079. bizId: "zai-biz-1",
  2080. renew: true,
  2081. });
  2082. });
  2083. it("Z.ai Stripe 绑卡和解绑使用 pay 服务接口", async () => {
  2084. const apiClient: ApiClient = {
  2085. request: vi.fn(async (input) => {
  2086. if (String(input).includes("/stripe/bind")) {
  2087. return createJsonResponse({
  2088. code: 200,
  2089. data: {
  2090. paymentMethodId: "pm_1",
  2091. brand: "visa",
  2092. last4: "4242",
  2093. requiresAction: false,
  2094. },
  2095. });
  2096. }
  2097. return createJsonResponse({
  2098. code: 200,
  2099. data: "ok",
  2100. });
  2101. }),
  2102. };
  2103. const provider = new BigModelCodingPlanSubscriptionProvider({
  2104. apiClient,
  2105. credentialService: {
  2106. load: vi.fn(async () => "zai-business-jwt"),
  2107. },
  2108. });
  2109. await provider.bindStripeCard({
  2110. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  2111. paymentMethodId: "pm_1",
  2112. returnUrl: "https://chat.z.ai",
  2113. });
  2114. await provider.unbindStripeCard({
  2115. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  2116. paymentMethodId: "pm_1",
  2117. });
  2118. expect(apiClient.request).toHaveBeenNthCalledWith(
  2119. 1,
  2120. "https://api.z.ai/api/pay/stripe/bind",
  2121. expect.objectContaining({ method: "POST" }),
  2122. );
  2123. expect(apiClient.request).toHaveBeenNthCalledWith(
  2124. 2,
  2125. "https://api.z.ai/api/pay/stripe/unbind",
  2126. expect.objectContaining({ method: "POST" }),
  2127. );
  2128. });
  2129. it("Z.ai PayPal setupToken 和 subscribe 使用 pay 服务接口", async () => {
  2130. const apiClient: ApiClient = {
  2131. request: vi.fn(async (input) => {
  2132. if (String(input).includes("/paypal/setupToken")) {
  2133. return createJsonResponse({
  2134. code: 200,
  2135. data: {
  2136. resultStatus: "SUCCESS",
  2137. setupTokenId: "setup-token-1",
  2138. approveUrl: "https://paypal.example/approve",
  2139. },
  2140. });
  2141. }
  2142. return createJsonResponse({
  2143. code: 200,
  2144. data: {
  2145. resultStatus: "SUCCESS",
  2146. payStatus: "SUCCESS",
  2147. orderId: "paypal-order-1",
  2148. },
  2149. });
  2150. }),
  2151. };
  2152. const provider = new BigModelCodingPlanSubscriptionProvider({
  2153. apiClient,
  2154. credentialService: {
  2155. load: vi.fn(async () => "zai-business-jwt"),
  2156. },
  2157. });
  2158. await provider.createPaypalSetupToken({
  2159. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  2160. returnUrl: "https://chat.z.ai/return",
  2161. cancelUrl: "https://chat.z.ai/cancel",
  2162. });
  2163. await provider.subscribePaypal({
  2164. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  2165. productId: "zai-product-pro",
  2166. setupTokenId: "setup-token-1",
  2167. amount: 18,
  2168. estimatePayAmount: {
  2169. thirdPartyPayAmount: 18,
  2170. },
  2171. bizId: "zai-biz-1",
  2172. });
  2173. expect(apiClient.request).toHaveBeenNthCalledWith(
  2174. 1,
  2175. "https://api.z.ai/api/pay/paypal/setupToken",
  2176. expect.objectContaining({ method: "POST" }),
  2177. );
  2178. expect(apiClient.request).toHaveBeenNthCalledWith(
  2179. 2,
  2180. "https://api.z.ai/api/pay/paypal/subscribe",
  2181. expect.objectContaining({ method: "POST" }),
  2182. );
  2183. });
  2184. it("productInfo 使用产品详情接口补齐套餐展示信息", async () => {
  2185. const apiClient: ApiClient = {
  2186. request: vi.fn(async () =>
  2187. createJsonResponse({
  2188. code: 200,
  2189. data: {
  2190. productId: "product-lite",
  2191. productName: "GLM Coding Lite",
  2192. productBigTitle: "GLM Coding Plan",
  2193. productSmallTitle: "轻量日常使用",
  2194. },
  2195. }),
  2196. ),
  2197. };
  2198. const provider = new BigModelCodingPlanSubscriptionProvider({
  2199. apiClient,
  2200. credentialService: createBigModelCredentialService(),
  2201. });
  2202. const result = await provider.productInfo({ productId: "product-lite" });
  2203. expect(result.productName).toBe("GLM Coding Lite");
  2204. expect(apiClient.request).toHaveBeenCalledWith(
  2205. new URL("https://bigmodel.cn/api/biz/product/info?productId=product-lite"),
  2206. expect.objectContaining({
  2207. method: "GET",
  2208. headers: {
  2209. Authorization: "oauth-token",
  2210. "Content-Type": "application/json",
  2211. },
  2212. }),
  2213. );
  2214. });
  2215. });
  2216. describe("ZaiCodingPlanSubscriptionProvider (family-aware Team Plan)", () => {
  2217. afterEach(() => {
  2218. vi.unstubAllEnvs();
  2219. });
  2220. // 修复原因:开发机可能设了 ZAI_BUSINESS_BASE_URL=https://api.z.ai 环境变量,
  2221. // resolveZaiBusinessBaseUrl 会优先读它,覆盖 ZCODE_ENV 逻辑导致测试域名断言不稳定。
  2222. // 测试里统一 stub 成空,强制走 ZCODE_ENV fallback 链。
  2223. function createZaiCredentialService(token = "zai-business-jwt") {
  2224. return {
  2225. load: vi.fn(async (key: string) => (key === "oauth:zai:access_token" ? token : null)),
  2226. };
  2227. }
  2228. it("getEnterprisePricing 未登录走 zai 域名公开定价接口", async () => {
  2229. vi.stubEnv("ZAI_BUSINESS_BASE_URL", "");
  2230. const apiClient: ApiClient = {
  2231. request: vi.fn(async () =>
  2232. createJsonResponse({
  2233. code: 200,
  2234. data: {
  2235. productList: [
  2236. {
  2237. productId: "zai-team-pro",
  2238. tier: "PRO",
  2239. subscribeMode: "ONE_TIME",
  2240. subscribePeriod: "MONTHLY",
  2241. originalAmount: 18,
  2242. discountAmount: 0,
  2243. payAmount: 18,
  2244. renewAmount: 18,
  2245. },
  2246. ],
  2247. },
  2248. }),
  2249. ),
  2250. };
  2251. const provider = new ZaiCodingPlanSubscriptionProvider({
  2252. apiClient,
  2253. credentialService: { load: vi.fn() },
  2254. });
  2255. const result = await provider.getEnterprisePricing({
  2256. authenticated: false,
  2257. });
  2258. expect(result.productList[0]?.productId).toBe("zai-team-pro");
  2259. // 关键:zai 域名,不能误用 bigmodel.cn
  2260. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  2261. "https://api.z.ai/api/biz/campaign/partner/enterprise/pricing",
  2262. );
  2263. });
  2264. it("getEnterprisePricing 登录态使用 zai 域名 + zai OAuth token(非 bigmodel)", async () => {
  2265. vi.stubEnv("ZAI_BUSINESS_BASE_URL", "");
  2266. const apiClient: ApiClient = {
  2267. request: vi.fn(async () => createJsonResponse({ code: 200, data: { productList: [] } })),
  2268. };
  2269. const provider = new ZaiCodingPlanSubscriptionProvider({
  2270. apiClient,
  2271. credentialService: createZaiCredentialService("zai-business-jwt"),
  2272. });
  2273. await provider.getEnterprisePricing({ authenticated: true });
  2274. expect(apiClient.request).toHaveBeenCalledTimes(1);
  2275. // 关键:host 是 zai 域名,不是 bigmodel.cn
  2276. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  2277. "https://api.z.ai/api/biz/subscription/enterprise/v2/pricing",
  2278. );
  2279. // 关键:token 是 zai 的,不带 Bearer
  2280. expect(vi.mocked(apiClient.request).mock.calls[0]?.[1]).toMatchObject({
  2281. method: "GET",
  2282. headers: {
  2283. Authorization: "zai-business-jwt",
  2284. "Content-Type": "application/json",
  2285. },
  2286. });
  2287. });
  2288. it("ZCODE_ENV=test 时 zai Team Plan 企业接口使用 api.z.ai", async () => {
  2289. vi.stubEnv("ZCODE_ENV", "test");
  2290. // 开发机 ZAI_BUSINESS_BASE_URL 会覆盖 ZCODE_ENV fallback,这里 stub 成空强制走 fallback
  2291. vi.stubEnv("ZAI_BUSINESS_BASE_URL", "");
  2292. const apiClient: ApiClient = {
  2293. request: vi.fn(async () => createJsonResponse({ code: 200, data: { productList: [] } })),
  2294. };
  2295. const provider = new ZaiCodingPlanSubscriptionProvider({
  2296. apiClient,
  2297. credentialService: createZaiCredentialService(),
  2298. });
  2299. await provider.getEnterprisePricing({ authenticated: true });
  2300. // 关键:测试环境走 z.ai,不能把测试 token 发到生产 api.z.ai
  2301. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  2302. "https://api.z.ai/api/biz/subscription/enterprise/v2/pricing",
  2303. );
  2304. });
  2305. it("getEnterprisePricing 缺少 zai OAuth token 时抛 zai_oauth_required 且不请求", async () => {
  2306. const apiClient: ApiClient = { request: vi.fn() };
  2307. const provider = new ZaiCodingPlanSubscriptionProvider({
  2308. apiClient,
  2309. credentialService: { load: vi.fn(async () => null) },
  2310. });
  2311. await expect(provider.getEnterprisePricing({ authenticated: true })).rejects.toThrow(
  2312. "zai_oauth_required",
  2313. );
  2314. expect(apiClient.request).not.toHaveBeenCalled();
  2315. });
  2316. it("getEnterprisePricing 用 zai 域名的 customerInfo 给已购 Team Plan 补齐项目上下文", async () => {
  2317. vi.stubEnv("ZAI_BUSINESS_BASE_URL", "");
  2318. const requestUrls: string[] = [];
  2319. const apiClient: ApiClient = {
  2320. request: vi.fn(async (input) => {
  2321. const url = input.toString();
  2322. requestUrls.push(url);
  2323. if (url.endsWith("/api/biz/subscription/enterprise/v2/pricing")) {
  2324. return createJsonResponse({
  2325. code: 200,
  2326. data: {
  2327. productList: [
  2328. {
  2329. productId: "zai-team-pro",
  2330. tier: "PRO",
  2331. subscribeMode: "CONTINUOUS",
  2332. subscribePeriod: "MONTHLY",
  2333. subscribed: true,
  2334. },
  2335. ],
  2336. },
  2337. });
  2338. }
  2339. if (url.endsWith("/api/biz/customer/getCustomerInfo")) {
  2340. return createJsonResponse({
  2341. code: 200,
  2342. data: {
  2343. organizations: [
  2344. {
  2345. organizationId: "zai-org",
  2346. organizationName: "zai 默认机构",
  2347. projects: [
  2348. {
  2349. projectId: "zai-proj",
  2350. projectName: "zai 团队项目",
  2351. projectType: 2,
  2352. },
  2353. ],
  2354. },
  2355. ],
  2356. },
  2357. });
  2358. }
  2359. if (url.endsWith("/organization/zai-org/projects/zai-proj/api_keys")) {
  2360. // team-api-key 预热:返回已有可用 key,避免 create 调用
  2361. return createJsonResponse({
  2362. code: 200,
  2363. data: [{ apiKey: "zai-team-ak", keyType: 2, name: "zcode-team-api-key" }],
  2364. });
  2365. }
  2366. throw new Error(`unexpected request: ${url}`);
  2367. }),
  2368. };
  2369. const provider = new ZaiCodingPlanSubscriptionProvider({
  2370. apiClient,
  2371. credentialService: createZaiCredentialService("zai-token"),
  2372. });
  2373. const result = await provider.getEnterprisePricing({ authenticated: true });
  2374. // 关键:pricing + customerInfo + team-api-key 预热都走 zai 域名,
  2375. // 不能串到 bigmodel.cn。预热也必须用 zai host(符合"除购买外路径可复用"契约)。
  2376. expect(requestUrls).toEqual([
  2377. "https://api.z.ai/api/biz/subscription/enterprise/v2/pricing",
  2378. "https://api.z.ai/api/biz/customer/getCustomerInfo",
  2379. "https://api.z.ai/api/biz/v1/organization/zai-org/projects/zai-proj/api_keys",
  2380. ]);
  2381. expect(result.productList[0]).toMatchObject({
  2382. organizationId: "zai-org",
  2383. projectId: "zai-proj",
  2384. projectName: "zai 团队项目",
  2385. });
  2386. });
  2387. });
  2388. describe("createCodingPlanSubscriptionService (family routing)", () => {
  2389. afterEach(() => {
  2390. vi.unstubAllEnvs();
  2391. });
  2392. function createCredentialService() {
  2393. return {
  2394. load: vi.fn(async (key: string) => {
  2395. if (key === "oauth:bigmodel:access_token") return "bigmodel-token";
  2396. if (key === "oauth:zai:access_token") return "zai-token";
  2397. return null;
  2398. }),
  2399. };
  2400. }
  2401. it("getEnterprisePricing 缺省 family 时走 bigmodel 域名(向后兼容)", async () => {
  2402. const requestUrls: string[] = [];
  2403. const apiClient: ApiClient = {
  2404. request: vi.fn(async (input) => {
  2405. requestUrls.push(input.toString());
  2406. return createJsonResponse({ code: 200, data: { productList: [] } });
  2407. }),
  2408. };
  2409. const service = createCodingPlanSubscriptionService({
  2410. apiClient,
  2411. credentialService: createCredentialService(),
  2412. });
  2413. await service.getEnterprisePricing({ authenticated: true });
  2414. expect(requestUrls).toEqual(["https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing"]);
  2415. });
  2416. it("getEnterprisePricing family=bigmodel 走 bigmodel 域名 + bigmodel token", async () => {
  2417. const apiClient: ApiClient = {
  2418. request: vi.fn(async () => createJsonResponse({ code: 200, data: { productList: [] } })),
  2419. };
  2420. const service = createCodingPlanSubscriptionService({
  2421. apiClient,
  2422. credentialService: createCredentialService(),
  2423. });
  2424. await service.getEnterprisePricing({
  2425. authenticated: true,
  2426. family: "bigmodel",
  2427. });
  2428. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  2429. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/pricing",
  2430. );
  2431. expect(vi.mocked(apiClient.request).mock.calls[0]?.[1]).toMatchObject({
  2432. headers: { Authorization: "bigmodel-token" },
  2433. });
  2434. });
  2435. it("getEnterprisePricing family=zai 走 zai 域名 + zai token", async () => {
  2436. vi.stubEnv("ZAI_BUSINESS_BASE_URL", "");
  2437. const apiClient: ApiClient = {
  2438. request: vi.fn(async () => createJsonResponse({ code: 200, data: { productList: [] } })),
  2439. };
  2440. const service = createCodingPlanSubscriptionService({
  2441. apiClient,
  2442. credentialService: createCredentialService(),
  2443. });
  2444. await service.getEnterprisePricing({ authenticated: true, family: "zai" });
  2445. // 关键:service 层按 family 路由,zai 不能误用 bigmodel.cn
  2446. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  2447. "https://api.z.ai/api/biz/subscription/enterprise/v2/pricing",
  2448. );
  2449. expect(vi.mocked(apiClient.request).mock.calls[0]?.[1]).toMatchObject({
  2450. headers: { Authorization: "zai-token" },
  2451. });
  2452. });
  2453. it("企业购买闭环接口仍走 bigmodel 域名(与 family 无关)", async () => {
  2454. const apiClient: ApiClient = {
  2455. request: vi.fn(async () =>
  2456. createJsonResponse({
  2457. code: 200,
  2458. data: { giveBalance: 0, cashBalance: 0, totalBalance: 0 },
  2459. }),
  2460. ),
  2461. };
  2462. const service = createCodingPlanSubscriptionService({
  2463. apiClient,
  2464. credentialService: createCredentialService(),
  2465. });
  2466. await service.getEnterpriseBalance();
  2467. expect(String(vi.mocked(apiClient.request).mock.calls[0]?.[0])).toBe(
  2468. "https://bigmodel.cn/api/biz/subscription/enterprise/v2/balance",
  2469. );
  2470. });
  2471. });