import { flushPromises, mount } from '@vue/test-utils' import { describe, expect, it, vi } from 'vitest' import { NCheckbox, NDatePicker, NInput, NInputNumber, NSelect } from 'naive-ui' import BoundedAuthorizationFields from '@/features/image-authorization/BoundedAuthorizationFields.vue' import { boundedImageEligibility, imageChargeEligibility } from '@/features/image-authorization/model' import { additionalImageFixture } from '../../fixtures/image-additional' import { billingCatalog, billingProfile } from '../../fixtures/billing' import { directionsResult } from '@/features/storyboard/testing/fixtures' import type { ImageBoundedAuthorizationInput } from '@/features/image-authorization/types' /** 独立的原unknown/standing和有限白名单,不代表真实批准。 */ function fixture() { const list = additionalImageFixture('bounded-project') list.requests[0]!.inputFingerprint = 'e'.repeat(64) const input: ImageBoundedAuthorizationInput = { mode: 'bounded', idempotencyKey: 'test-bounded', parentAuthorizationId: list.authorizations[0]!.id, acceptedUnknownRequests: [{ requestId: list.requests[0]!.id, inputFingerprint: 'e'.repeat(64) }], provider: 'openai-image', model: 'gpt-image-2.5-flare', targets: [ { shotId: 'shot-db-1-1', sourceFingerprint: 'c'.repeat(64), planFingerprint: 'b'.repeat(64), maxRequests: 2 } ], maxRequests: 2, expiresAt: new Date(Date.now() + 3600000).toISOString(), acknowledgeUnknownPriorBilling: true, acknowledgeVariableBilling: true, approvedBy: '隔离批准人', approvalNote: '仅原预算内有限继续' } list.additionalAuthorizations = [ { id: 'bounded-permit', status: 'approved', input: { ...input, parentInputFingerprint: 'a'.repeat(64) }, usedRequests: 0, remainingRequests: 2, targets: input.targets.map(row => ({ ...row, usedRequests: 0 })) } ] return list } /** 以字面真实范围调用正式准入逻辑。 */ function eligibility(list: ReturnType) { return boundedImageEligibility( list, 'bounded-permit', 'bounded-project', 'shot-db-1-1', 'gpt-image-2.5-flare', 'c'.repeat(64), 'b'.repeat(64) ) } describe('bounded沿原账本的有限风险许可', () => { it('仅选中的白名单可使用,原unknown/预留及billingBlocked保持', () => { const list = fixture() expect(eligibility(list).allowed).toBe(true) expect( imageChargeEligibility(list, 'keyframe', 'shot-db-1-1', 'gpt-image-2.5-flare', 'b'.repeat(64)).allowed ).toBe(false) expect(list.billingBlocked).toBe(true) expect(list.requests[0]!.status).toBe('unknown') expect(list.requests[0]!.output?.actualBilledMicros).toBeNull() }) it.each([ 'revoked', 'expired', 'total', 'per-shot', 'shot', 'source', 'plan', 'model', 'budget', 'parent', 'new-unknown', 'running', 'input-change' ])('拒绝许可/白名单/费用变化:%s', kind => { const list = fixture(), permit = list.additionalAuthorizations![0]!, target = permit.targets![0]!, grant = list.authorizations[0]! if (kind === 'revoked') permit.status = 'revoked' if (kind === 'expired' && permit.input.mode === 'bounded') permit.input.expiresAt = '2000-01-01T00:00:00Z' if (kind === 'total') permit.remainingRequests = 0 if (kind === 'per-shot') target.usedRequests = target.maxRequests if (kind === 'shot') target.shotId = 'other-shot' if (kind === 'source') target.sourceFingerprint = 'f'.repeat(64) if (kind === 'plan') target.planFingerprint = 'f'.repeat(64) if (kind === 'model' && permit.input.mode === 'bounded') permit.input.model = 'other-model' if (kind === 'budget') grant.remainingMicros = 0 if (kind === 'parent') grant.status = 'revoked' if (kind === 'input-change') list.requests[0]!.inputFingerprint = 'f'.repeat(64) if (kind === 'running') list.requests[0]!.status = 'running' if (kind === 'new-unknown') { list.requests.push({ ...structuredClone(list.requests[0]!), id: 'new-unknown' }) list.blockingRequestIds.push('new-unknown') } expect(eligibility(list).allowed).toBe(false) }) it('同计划完整结果在已撤销/用尽后仍可只读复用,不新增次数', () => { const list = fixture() list.additionalAuthorizations![0]!.status = 'revoked' const result = { ...structuredClone(list.requests[0]!), id: 'completed-result', status: 'completed', input: { ...list.requests[0]!.input, targetId: 'shot-db-1-1' }, output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'existing' } } } list.requests.push(result) expect( imageChargeEligibility(list, 'keyframe', 'shot-db-1-1', 'gpt-image-2.5-flare', 'b'.repeat(64), { id: 'bounded-permit', projectId: 'bounded-project', sourceFingerprint: 'c'.repeat(64) }) ).toMatchObject({ allowed: true, reusable: true }) }) it('用户明确填写/逐项接受后仅登记一次,body复用原预算且不生成', async () => { const list = fixture(), fetcher = vi.fn(async (url, init) => { const path = String(url) if (path === '/api/projects/bounded-project') return Response.json({ data: { id: 'bounded-project', episodes: [{ episode: 1 }] } }) if (path.endsWith('/creative-profile')) return Response.json({ data: { ...billingProfile, aspectRatio: '1:1' } }) if (path.includes('/storyboard-directions?')) return Response.json({ data: directionsResult('bounded-project') }) if (path.endsWith('/image-authorizations/preview')) { const body = JSON.parse(String(init?.body)) return Response.json({ data: { provider: 'openai-image', model: 'gpt-image-2.5-flare', context: { projectId: 'bounded-project', scope: 'keyframe', targetId: body.targetId, sourceFingerprint: 'c'.repeat(64) }, planFingerprint: 'b'.repeat(64), authorization: list } }) } if (path.endsWith('/image-authorizations') && init?.method === 'POST') return Response.json({ data: { authorizationId: 'created-bounded', status: 'approved' } }) throw new Error('未模拟 ' + path) }) vi.stubGlobal('fetch', fetcher) const wrapper = mount(BoundedAuthorizationFields, { props: { projectId: 'bounded-project', list, catalog: billingCatalog, disabled: false } }) try { await flushPromises() expect(wrapper.vm.canSubmit).toBe(false) wrapper .findAllComponents(NSelect) .find(row => row.attributes('aria-label') === '有限许可原授权')! .vm.$emit('update:value', list.authorizations[0]!.id) wrapper .findAllComponents(NSelect) .find(row => row.attributes('aria-label') === '有限许可镜头')! .vm.$emit('update:value', ['shot-db-1-1']) await flushPromises() await wrapper .findAll('button') .find(row => row.text() === '免费核对逐镜费用计划')! .trigger('click') await flushPromises() for (const row of wrapper.findAllComponents(NInputNumber)) row.vm.$emit('update:value', row.attributes('aria-label') === '有限许可总次数' ? 1 : 2) wrapper.getComponent(NDatePicker).vm.$emit('update:value', Date.now() + 1800000) wrapper .findAllComponents(NInput) .find(row => row.attributes('aria-label') === '有限许可批准人')! .vm.$emit('update:value', '人工批准人') wrapper .findAllComponents(NInput) .find(row => row.attributes('aria-label') === '有限许可批准说明')! .vm.$emit('update:value', '只批准本镜头一次,原费用保持未知') wrapper .findAllComponents(NCheckbox) .find(row => row.text().includes('明确接受此原请求'))! .vm.$emit('update:checked', true) await flushPromises() wrapper .findAllComponents(NCheckbox) .find(row => row.text().includes('我已核对原未知费用'))! .vm.$emit('update:checked', true) await flushPromises() expect(wrapper.vm.canSubmit).toBe(true) await Promise.all([wrapper.vm.submit(), wrapper.vm.submit()]) await flushPromises() const create = fetcher.mock.calls.filter( ([url, init]) => String(url).endsWith('/image-authorizations') && init?.method === 'POST' ) expect(create).toHaveLength(1) const body = JSON.parse(String(create[0]![1]?.body)) expect(body).toMatchObject({ mode: 'bounded', parentAuthorizationId: list.authorizations[0]!.id, maxRequests: 1, targets: [ { shotId: 'shot-db-1-1', maxRequests: 2, sourceFingerprint: 'c'.repeat(64), planFingerprint: 'b'.repeat(64) } ], acceptedUnknownRequests: [{ requestId: 'original-image-request', inputFingerprint: 'e'.repeat(64) }] }) expect(body).not.toHaveProperty('budgetMicros') expect(list.requests[0]!.status).toBe('unknown') expect(list.billingBlocked).toBe(true) expect( fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/primary|\/vision/.test(String(url))) ).toBe(false) } finally { wrapper.unmount() } }) })