codingPlanSubscriptionService.test.ts 82 KB

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