Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(web): localize education status query (#40132)

yyh276c3b6e022e
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 408fd1d9083..c0b968118fc 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -6037,11 +6037,6 @@
"count": 1
}
},
- "web/service/use-education.ts": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/service/use-endpoints.ts": {
"no-restricted-imports": {
"count": 1
diff --git a/web/__mocks__/provider-context.ts b/web/__mocks__/provider-context.ts
index 0b2b2b90bf1..58bf3d2fa4c 100644
--- a/web/__mocks__/provider-context.ts
+++ b/web/__mocks__/provider-context.ts
@@ -24,11 +24,6 @@ export const baseProviderContextValue: ProviderContextState = {
datasetOperatorEnabled: false,
enableEducationPlan: false,
isEducationWorkspace: false,
- isEducationAccount: false,
- allowRefreshEducationVerify: false,
- educationAccountExpireAt: null,
- isLoadingEducationAccountInfo: false,
- isFetchingEducationAccountInfo: false,
webappCopyrightEnabled: false,
licenseLimit: {
workspace_members: {
diff --git a/web/__tests__/billing/billing-integration.test.tsx b/web/__tests__/billing/billing-integration.test.tsx
index 72b25cacb3b..2510af3b67f 100644
--- a/web/__tests__/billing/billing-integration.test.tsx
+++ b/web/__tests__/billing/billing-integration.test.tsx
@@ -17,11 +17,16 @@ import { Plan } from '@/app/components/billing/type'
import UpgradeBtn from '@/app/components/billing/upgrade-btn'
import VectorSpaceFull from '@/app/components/billing/vector-space-full'
import { consoleQuery } from '@/service/client'
-import { createConsoleQueryClient, createConsoleQueryWrapper } from '@/test/console/query-data'
+import {
+ createConsoleQueryClient,
+ createConsoleQueryWrapper,
+ seedEducationStatus,
+} from '@/test/console/query-data'
import { render as renderWithConsoleState } from '@/test/console/render'
let mockProviderCtx: Record<string, unknown> = {}
let mockConsoleState: Record<string, unknown> = {}
+let mockEducationStatus = { is_student: false, allow_refresh: false, expire_at: null }
const render = (ui: ReactElement, options: RenderOptions = {}, vectorSpaceUsageUnknown = false) => {
const queryClient = createConsoleQueryClient()
@@ -37,6 +42,7 @@ const render = (ui: ReactElement, options: RenderOptions = {}, vectorSpaceUsageU
queryClient.setQueryData(consoleQuery.billing.invoices.get.queryOptions().queryKey, {
url: 'https://billing.example.com',
})
+ seedEducationStatus(queryClient, mockEducationStatus)
const { wrapper } = createConsoleQueryWrapper({
systemFeatures: { deployment_edition: 'CLOUD' },
queryClient,
@@ -119,14 +125,19 @@ const createPlanData = (overrides: PlanOverrides = {}) => ({
const setupProviderContext = (
planOverrides: PlanOverrides = {},
extra: Record<string, unknown> = {},
+ educationStatus: Partial<typeof mockEducationStatus> = {},
) => {
+ mockEducationStatus = {
+ is_student: false,
+ allow_refresh: false,
+ expire_at: null,
+ ...educationStatus,
+ }
mockProviderCtx = {
plan: createPlanData(planOverrides),
enableBilling: true,
isFetchedPlan: true,
enableEducationPlan: false,
- isEducationAccount: false,
- allowRefreshEducationVerify: false,
...extra,
}
}
@@ -350,13 +361,7 @@ describe('Plan Type Display Integration', () => {
})
it('should show education verify button when enableEducationPlan is true and not yet verified', () => {
- setupProviderContext(
- { type: Plan.sandbox },
- {
- enableEducationPlan: true,
- isEducationAccount: false,
- },
- )
+ setupProviderContext({ type: Plan.sandbox }, { enableEducationPlan: true })
render(<PlanComp loc="test" />)
@@ -366,10 +371,8 @@ describe('Plan Type Display Integration', () => {
it('should show education discount to managers without billing permission keys', () => {
setupProviderContext(
{ type: Plan.sandbox },
- {
- enableEducationPlan: true,
- isEducationAccount: true,
- },
+ { enableEducationPlan: true },
+ { is_student: true },
)
setupConsoleState({ isCurrentWorkspaceManager: true, workspacePermissionKeys: [] })
@@ -381,10 +384,8 @@ describe('Plan Type Display Integration', () => {
it('should hide education discount from non-manager members', () => {
setupProviderContext(
{ type: Plan.sandbox },
- {
- enableEducationPlan: true,
- isEducationAccount: true,
- },
+ { enableEducationPlan: true },
+ { is_student: true },
)
setupConsoleState({
isCurrentWorkspaceManager: false,
diff --git a/web/__tests__/billing/cloud-plan-payment-flow.test.tsx b/web/__tests__/billing/cloud-plan-payment-flow.test.tsx
index f396a6c0c0a..225d35acd4a 100644
--- a/web/__tests__/billing/cloud-plan-payment-flow.test.tsx
+++ b/web/__tests__/billing/cloud-plan-payment-flow.test.tsx
@@ -16,12 +16,12 @@ import { ALL_PLANS } from '@/app/components/billing/config'
import { PlanRange } from '@/app/components/billing/pricing/plan-switcher/plan-range-switcher'
import CloudPlanItem from '@/app/components/billing/pricing/plans/cloud-plan-item'
import { Plan } from '@/app/components/billing/type'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { render } from '@/test/console/render'
// ─── Mock state ──────────────────────────────────────────────────────────────
let mockConsoleState: Record<string, unknown> = {}
const mockFetchSubscriptionUrls = vi.fn()
-const mockInvoices = vi.fn()
const mockOpenAsyncWindow = vi.fn()
// ─── Context mocks ───────────────────────────────────────────────────────────
@@ -36,16 +36,6 @@ vi.mock('@/service/billing', () => ({
fetchSubscriptionUrls: (...args: unknown[]) => mockFetchSubscriptionUrls(...args),
}))
-vi.mock('@/service/client', () => ({
- consoleClient: {
- billing: {
- invoices: {
- get: () => mockInvoices(),
- },
- },
- },
-}))
-
vi.mock('@/hooks/use-async-window-open', () => ({
useAsyncWindowOpen: () => mockOpenAsyncWindow,
}))
@@ -78,11 +68,13 @@ const renderCloudPlanItem = ({
planRange = PlanRange.monthly,
canPay = true,
}: RenderCloudPlanItemOptions = {}) => {
+ const { wrapper } = createConsoleQueryWrapper()
return render(
<>
<ToastHost timeout={0} />
<CloudPlanItem currentPlan={currentPlan} plan={plan} planRange={planRange} canPay={canPay} />
</>,
+ { wrapper },
)
}
@@ -96,7 +88,6 @@ describe('Cloud Plan Payment Flow', () => {
toast.dismiss()
setupConsoleState()
mockFetchSubscriptionUrls.mockResolvedValue({ url: 'https://pay.example.com/checkout' })
- mockInvoices.mockResolvedValue({ url: 'https://billing.example.com/invoices' })
})
// ─── 1. Plan Display ────────────────────────────────────────────────────
diff --git a/web/__tests__/billing/education-verification-flow.test.tsx b/web/__tests__/billing/education-verification-flow.test.tsx
index 4bbb6547e01..01c1ef9a488 100644
--- a/web/__tests__/billing/education-verification-flow.test.tsx
+++ b/web/__tests__/billing/education-verification-flow.test.tsx
@@ -17,11 +17,16 @@ import { defaultPlan } from '@/app/components/billing/config'
import PlanComp from '@/app/components/billing/plan'
import { Plan } from '@/app/components/billing/type'
import { consoleQuery } from '@/service/client'
-import { createConsoleQueryClient, createConsoleQueryWrapper } from '@/test/console/query-data'
+import {
+ createConsoleQueryClient,
+ createConsoleQueryWrapper,
+ seedEducationStatus,
+} from '@/test/console/query-data'
import { render as renderWithConsoleState } from '@/test/console/render'
let mockProviderCtx: Record<string, unknown> = {}
let mockConsoleState: Record<string, unknown> = {}
+let mockEducationStatus = { is_student: false, allow_refresh: false, expire_at: null }
const render = (ui: ReactElement, options: RenderOptions = {}) => {
const queryClient = createConsoleQueryClient()
@@ -34,6 +39,7 @@ const render = (ui: ReactElement, options: RenderOptions = {}) => {
limit: plan.total.vectorSpace,
usage_unknown: false,
})
+ seedEducationStatus(queryClient, mockEducationStatus)
const { wrapper } = createConsoleQueryWrapper({
systemFeatures: { deployment_edition: 'CLOUD' },
queryClient,
@@ -131,14 +137,19 @@ const setupContexts = (
planOverrides: PlanOverrides = {},
providerOverrides: Record<string, unknown> = {},
appOverrides: Record<string, unknown> = {},
+ educationStatus: Partial<typeof mockEducationStatus> = {},
) => {
+ mockEducationStatus = {
+ is_student: false,
+ allow_refresh: false,
+ expire_at: null,
+ ...educationStatus,
+ }
mockProviderCtx = {
plan: createPlanData(planOverrides),
enableBilling: true,
isFetchedPlan: true,
enableEducationPlan: false,
- isEducationAccount: false,
- allowRefreshEducationVerify: false,
...providerOverrides,
}
mockConsoleState = {
@@ -168,7 +179,7 @@ describe('Education Verification Flow', () => {
})
it('should show verify button when enableEducationPlan is true and not yet verified', () => {
- setupContexts({}, { enableEducationPlan: true, isEducationAccount: false })
+ setupContexts({}, { enableEducationPlan: true })
render(<PlanComp loc="test" />)
@@ -176,33 +187,23 @@ describe('Education Verification Flow', () => {
})
it('should not show verify button when already verified and not about to expire', () => {
- setupContexts(
- {},
- {
- enableEducationPlan: true,
- isEducationAccount: true,
- allowRefreshEducationVerify: false,
- },
- )
+ setupContexts({}, { enableEducationPlan: true }, {}, { is_student: true })
render(<PlanComp loc="test" />)
expect(screen.queryByText(/toVerified/i)).not.toBeInTheDocument()
})
- it('should show verify button when about to expire (allowRefreshEducationVerify is true)', () => {
+ it('should show verify button when the education status allows refresh', () => {
setupContexts(
{},
- {
- enableEducationPlan: true,
- isEducationAccount: true,
- allowRefreshEducationVerify: true,
- },
+ { enableEducationPlan: true },
+ {},
+ { is_student: true, allow_refresh: true },
)
render(<PlanComp loc="test" />)
- // Shown because isAboutToExpire = allowRefreshEducationVerify = true
expect(screen.getByText(/toVerified/i)).toBeInTheDocument()
})
})
@@ -211,11 +212,7 @@ describe('Education Verification Flow', () => {
describe('Successful verification flow', () => {
it('should let non-manager members start education verification', async () => {
mockMutateAsync.mockResolvedValue({ token: 'edu-token-123' })
- setupContexts(
- {},
- { enableEducationPlan: true, isEducationAccount: false },
- { isCurrentWorkspaceManager: false },
- )
+ setupContexts({}, { enableEducationPlan: true }, { isCurrentWorkspaceManager: false })
const user = userEvent.setup()
render(<PlanComp loc="test" />)
@@ -234,7 +231,7 @@ describe('Education Verification Flow', () => {
describe('Failed verification flow', () => {
it('should show VerifyStateModal with rejection info on error', async () => {
mockMutateAsync.mockRejectedValue(new Error('Verification failed'))
- setupContexts({}, { enableEducationPlan: true, isEducationAccount: false })
+ setupContexts({}, { enableEducationPlan: true })
const user = userEvent.setup()
render(<PlanComp loc="test" />)
@@ -257,7 +254,7 @@ describe('Education Verification Flow', () => {
it('should show email and link in VerifyStateModal', async () => {
mockMutateAsync.mockRejectedValue(new Error('fail'))
- setupContexts({}, { enableEducationPlan: true, isEducationAccount: false })
+ setupContexts({}, { enableEducationPlan: true })
const user = userEvent.setup()
render(<PlanComp loc="test" />)
@@ -272,7 +269,7 @@ describe('Education Verification Flow', () => {
it('should not redirect on verification failure', async () => {
mockMutateAsync.mockRejectedValue(new Error('fail'))
- setupContexts({}, { enableEducationPlan: true, isEducationAccount: false })
+ setupContexts({}, { enableEducationPlan: true })
const user = userEvent.setup()
render(<PlanComp loc="test" />)
@@ -291,10 +288,7 @@ describe('Education Verification Flow', () => {
// ─── 4. Education + Upgrade Coexistence ─────────────────────────────────
describe('Education and upgrade button coexistence', () => {
it('should show both education verify and upgrade buttons for sandbox user', () => {
- setupContexts(
- { type: Plan.sandbox },
- { enableEducationPlan: true, isEducationAccount: false },
- )
+ setupContexts({ type: Plan.sandbox }, { enableEducationPlan: true })
render(<PlanComp loc="test" />)
@@ -303,10 +297,7 @@ describe('Education Verification Flow', () => {
})
it('should not show upgrade button for enterprise plan', () => {
- setupContexts(
- { type: Plan.enterprise },
- { enableEducationPlan: true, isEducationAccount: false },
- )
+ setupContexts({ type: Plan.enterprise }, { enableEducationPlan: true })
render(<PlanComp loc="test" />)
@@ -316,7 +307,7 @@ describe('Education Verification Flow', () => {
})
it('should show team plan with plain upgrade button and education button', () => {
- setupContexts({ type: Plan.team }, { enableEducationPlan: true, isEducationAccount: false })
+ setupContexts({ type: Plan.team }, { enableEducationPlan: true })
render(<PlanComp loc="test" />)
diff --git a/web/__tests__/billing/pricing-modal-flow.test.tsx b/web/__tests__/billing/pricing-modal-flow.test.tsx
index 073d5e011a4..ffca3a4b80f 100644
--- a/web/__tests__/billing/pricing-modal-flow.test.tsx
+++ b/web/__tests__/billing/pricing-modal-flow.test.tsx
@@ -14,13 +14,20 @@ import * as React from 'react'
import { ALL_PLANS } from '@/app/components/billing/config'
import Pricing from '@/app/components/billing/pricing'
import { Plan } from '@/app/components/billing/type'
-import { render } from '@/test/console/render'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { render as renderWithConsoleState } from '@/test/console/render'
// ─── Mock state ──────────────────────────────────────────────────────────────
let mockProviderCtx: Record<string, unknown> = {}
let mockConsoleState: Record<string, unknown> = {}
+let mockEducationStatus = { is_student: false, allow_refresh: false, expire_at: null }
const mockFetchSubscriptionUrls = vi.hoisted(() => vi.fn())
+const render = (ui: React.ReactElement) => {
+ const { wrapper } = createConsoleQueryWrapper({ educationStatus: mockEducationStatus })
+ return renderWithConsoleState(ui, { wrapper })
+}
+
// ─── Context mocks ───────────────────────────────────────────────────────────
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => mockProviderCtx,
@@ -49,15 +56,24 @@ vi.mock('@/service/billing', () => ({
fetchSubscriptionUrls: (...args: unknown[]) => mockFetchSubscriptionUrls(...args),
}))
-vi.mock('@/service/client', () => ({
- consoleClient: {
- billing: {
- invoices: {
- get: vi.fn().mockResolvedValue({ url: 'https://invoice.example.com' }),
+vi.mock('@/service/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/client')>()
+ return {
+ ...actual,
+ consoleClient: new Proxy(actual.consoleClient, {
+ get(target, prop, receiver) {
+ if (prop === 'billing') {
+ return {
+ invoices: {
+ get: vi.fn().mockResolvedValue({ url: 'https://invoice.example.com' }),
+ },
+ }
+ }
+ return Reflect.get(target, prop, receiver)
},
- },
- },
-}))
+ }),
+ }
+})
vi.mock('@/hooks/use-async-window-open', () => ({
useAsyncWindowOpen: () => vi.fn(),
@@ -118,13 +134,12 @@ const setupContexts = (
planOverrides: Record<string, unknown> = {},
appOverrides: Record<string, unknown> = {},
) => {
+ mockEducationStatus = { is_student: false, allow_refresh: false, expire_at: null }
mockProviderCtx = {
plan: { ...defaultPlanData, ...planOverrides },
enableBilling: true,
isFetchedPlan: true,
enableEducationPlan: false,
- isEducationAccount: false,
- allowRefreshEducationVerify: false,
}
mockConsoleState = {
isCurrentWorkspaceManager: true,
@@ -282,8 +297,8 @@ describe('Pricing Modal Flow', () => {
mockProviderCtx = {
...mockProviderCtx,
enableEducationPlan: true,
- isEducationAccount: true,
}
+ mockEducationStatus.is_student = true
const user = userEvent.setup()
render(<Pricing onCancel={onCancel} />)
diff --git a/web/app/(commonLayout)/education-apply/page.tsx b/web/app/(commonLayout)/education-apply/page.tsx
index 10b4ddb67ee..74574c88d99 100644
--- a/web/app/(commonLayout)/education-apply/page.tsx
+++ b/web/app/(commonLayout)/education-apply/page.tsx
@@ -1,15 +1,19 @@
'use client'
+import { useQuery } from '@tanstack/react-query'
import { useEffect } from 'react'
import { FullScreenLoading } from '@/app/components/full-screen-loading'
import EducationApplyPage from '@/app/education-apply/education-apply-page'
import { useProviderContext } from '@/context/provider-context'
import { useRouter, useSearchParams } from '@/next/navigation'
+import { consoleQuery } from '@/service/client'
export default function EducationApply() {
const router = useRouter()
- const { enableEducationPlan, isFetchedPlanInfo, isLoadingEducationAccountInfo } =
- useProviderContext()
+ const { enableEducationPlan, isFetchedPlanInfo } = useProviderContext()
+ const { isLoading: isLoadingEducationStatus } = useQuery(
+ consoleQuery.account.education.get.queryOptions({ enabled: enableEducationPlan }),
+ )
const searchParams = useSearchParams()
const token = searchParams.get('token')
@@ -19,7 +23,7 @@ export default function EducationApply() {
if (!enableEducationPlan || !token) router.replace('/')
}, [enableEducationPlan, isFetchedPlanInfo, router, token])
- if (!isFetchedPlanInfo || !enableEducationPlan || !token || isLoadingEducationAccountInfo)
+ if (!isFetchedPlanInfo || !enableEducationPlan || !token || isLoadingEducationStatus)
return <FullScreenLoading />
return <EducationApplyPage />
diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsx
index 9a4f3ea8626..01f9e9ddf2a 100644
--- a/web/app/account/(commonLayout)/account-page/index.tsx
+++ b/web/app/account/(commonLayout)/account-page/index.tsx
@@ -51,7 +51,13 @@ export default function AccountPage() {
const userProfile = userProfileResp.profile
const mutateUserProfile = () =>
queryClient.invalidateQueries({ queryKey: userProfileQueryOptions().queryKey })
- const { isEducationAccount } = useProviderContext()
+ const { enableEducationPlan } = useProviderContext()
+ const { data: isEducationAccount = false } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: ({ is_student }) => is_student ?? false,
+ }),
+ )
const [editNameModalVisible, setEditNameModalVisible] = useState(false)
const [editName, setEditName] = useState('')
const [editing, setEditing] = useState(false)
diff --git a/web/app/account/(commonLayout)/avatar.tsx b/web/app/account/(commonLayout)/avatar.tsx
index c4d71b51a57..4a5c8e95db6 100644
--- a/web/app/account/(commonLayout)/avatar.tsx
+++ b/web/app/account/(commonLayout)/avatar.tsx
@@ -7,13 +7,14 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { resetUser } from '@/app/components/base/amplitude/utils'
import PremiumBadge from '@/app/components/base/premium-badge'
import { useProviderContext } from '@/context/provider-context'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useRouter } from '@/next/navigation'
+import { consoleQuery } from '@/service/client'
import { useLogout } from '@/service/use-common'
export default function AppSelector() {
@@ -22,7 +23,13 @@ export default function AppSelector() {
// Cache is hydrated by CommonLayoutHydrationBoundary; this hits cache synchronously.
const { data: userProfileResp } = useSuspenseQuery(userProfileQueryOptions())
const userProfile = userProfileResp.profile
- const { isEducationAccount } = useProviderContext()
+ const { enableEducationPlan } = useProviderContext()
+ const { data: isEducationAccount = false } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: ({ is_student }) => is_student ?? false,
+ }),
+ )
const { mutateAsync: logout } = useLogout()
diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
index 90c6fcc6876..16e26a4200d 100644
--- a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
@@ -56,11 +56,6 @@ const defaultProviderContext = {
datasetOperatorEnabled: false,
enableEducationPlan: false,
isEducationWorkspace: false,
- isEducationAccount: false,
- allowRefreshEducationVerify: false,
- educationAccountExpireAt: null,
- isLoadingEducationAccountInfo: false,
- isFetchingEducationAccountInfo: false,
webappCopyrightEnabled: false,
licenseLimit: {
workspace_members: {
diff --git a/web/app/components/billing/plan/index.tsx b/web/app/components/billing/plan/index.tsx
index 774cbc4a7b8..7b8e8b0e9e8 100644
--- a/web/app/components/billing/plan/index.tsx
+++ b/web/app/components/billing/plan/index.tsx
@@ -1,8 +1,9 @@
'use client'
+import type { EducationStatusResponse } from '@dify/contracts/api/console/account/types.gen'
import type { FC } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { RiBook2Line, RiFileEditLine, RiGroupLine } from '@remixicon/react'
-import { useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useUnmountedRef } from 'ahooks'
import { useAtomValue } from 'jotai'
import * as React from 'react'
@@ -15,6 +16,7 @@ import { useProviderContext } from '@/context/provider-context'
import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useRouter } from '@/next/navigation'
+import { consoleQuery } from '@/service/client'
import { useEducationVerify } from '@/service/use-education'
import { getDaysUntilEndOfMonth } from '@/utils/time'
import Loading from '../../base/icons/src/public/thought/Loading'
@@ -30,6 +32,11 @@ type Props = Readonly<{
loc: string
}>
+const selectEducationPlanStatus = ({ allow_refresh, is_student }: EducationStatusResponse) => ({
+ isAboutToExpire: allow_refresh ?? false,
+ isEducationAccount: is_student ?? false,
+})
+
const PlanComp: FC<Props> = ({ loc }) => {
const { t } = useTranslation()
const { data: deploymentEdition } = useSuspenseQuery({
@@ -40,9 +47,14 @@ const PlanComp: FC<Props> = ({ loc }) => {
const router = useRouter()
const userProfileEmail = useAtomValue(userProfileEmailAtom)
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
- const { plan, enableEducationPlan, allowRefreshEducationVerify, isEducationAccount } =
- useProviderContext()
- const isAboutToExpire = allowRefreshEducationVerify
+ const { plan, enableEducationPlan } = useProviderContext()
+ const { data: educationStatus } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: selectEducationPlanStatus,
+ }),
+ )
+ const { isAboutToExpire = false, isEducationAccount = false } = educationStatus ?? {}
const { type } = plan
const isEnterprisePlan = String(type) === SelfHostedPlan.enterprise
diff --git a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx b/web/app/components/billing/pricing/__tests__/dialog.spec.tsx
index e7387d05022..80ce4126a53 100644
--- a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx
+++ b/web/app/components/billing/pricing/__tests__/dialog.spec.tsx
@@ -4,6 +4,7 @@ import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useGetPricingPageLanguage } from '@/context/i18n'
import { useProviderContext } from '@/context/provider-context'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { render } from '@/test/console/render'
import { Plan } from '../../type'
import Pricing from '../index'
@@ -60,6 +61,7 @@ describe('Pricing dialog lifecycle', () => {
isCurrentWorkspaceManager: true,
}
;(useProviderContext as Mock).mockReturnValue({
+ enableEducationPlan: false,
plan: {
type: Plan.sandbox,
usage: buildUsage(),
@@ -72,7 +74,8 @@ describe('Pricing dialog lifecycle', () => {
it('should call onCancel when the pricing dialog is closed', async () => {
const user = userEvent.setup()
const onCancel = vi.fn()
- render(<Pricing onCancel={onCancel} />)
+ const { wrapper } = createConsoleQueryWrapper()
+ render(<Pricing onCancel={onCancel} />, { wrapper })
await user.click(screen.getByRole('button', { name: 'close' }))
diff --git a/web/app/components/billing/pricing/index.tsx b/web/app/components/billing/pricing/index.tsx
index a5b510ee6e0..096df9d69c1 100644
--- a/web/app/components/billing/pricing/index.tsx
+++ b/web/app/components/billing/pricing/index.tsx
@@ -10,12 +10,14 @@ import {
ScrollAreaThumb,
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
+import { useQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import * as React from 'react'
import { useState } from 'react'
import { useGetPricingPageLanguage } from '@/context/i18n'
import { useProviderContext } from '@/context/provider-context'
import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'
+import { consoleQuery } from '@/service/client'
import { NoiseBottom, NoiseTop } from './assets'
import Footer from './footer'
import Header from './header'
@@ -29,7 +31,13 @@ type PricingProps = {
}
const Pricing: FC<PricingProps> = ({ onCancel }) => {
- const { plan, enableEducationPlan, isEducationAccount } = useProviderContext()
+ const { plan, enableEducationPlan } = useProviderContext()
+ const { data: isEducationAccount = false } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: ({ is_student }) => is_student ?? false,
+ }),
+ )
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
const shouldDefaultToYearly =
isCurrentWorkspaceManager && enableEducationPlan && isEducationAccount
diff --git a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx
index d5de0c97ee3..75f15d6047f 100644
--- a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx
+++ b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx
@@ -10,13 +10,14 @@ import {
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
+import { useQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useProviderContext } from '@/context/provider-context'
import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'
import { fetchSubscriptionUrls } from '@/service/billing'
-import { consoleClient } from '@/service/client'
+import { consoleClient, consoleQuery } from '@/service/client'
import { ALL_PLANS } from '../../../config'
import { useEducationDiscount } from '../../../hooks/use-education-discount'
import { Plan } from '../../../type'
@@ -49,7 +50,13 @@ const CloudPlanItem: FC<CloudPlanItemProps> = ({ plan, currentPlan, planRange, c
const isCurrent = plan === currentPlan
const isCurrentPaidPlan = isCurrent && !isFreePlan
const isPlanDisabled = isCurrentPaidPlan ? false : planInfo.level <= ALL_PLANS[currentPlan].level
- const { enableEducationPlan, isEducationAccount } = useProviderContext()
+ const { enableEducationPlan } = useProviderContext()
+ const { data: isEducationAccount = false } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: ({ is_student }) => is_student ?? false,
+ }),
+ )
const isEducationDiscountMode = enableEducationPlan && isEducationAccount
const isEducationDiscountSupportedPlan = plan === Plan.professional && isYear
const educationDiscountWarningText =
diff --git a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx b/web/app/components/header/account-dropdown/__tests__/index.spec.tsx
index a01c3999904..aab01da7731 100644
--- a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-dropdown/__tests__/index.spec.tsx
@@ -79,7 +79,7 @@ describe('AccountDropdown', () => {
vi.clearAllMocks()
mockUseRouter.mockReturnValue({ push: mockPush })
vi.mocked(useProviderContext).mockReturnValue({
- isEducationAccount: false,
+ enableEducationPlan: false,
} as ProviderContextState)
vi.mocked(useLogout).mockReturnValue({
mutateAsync: mockLogout,
diff --git a/web/app/components/header/account-dropdown/main-nav-menu-content.tsx b/web/app/components/header/account-dropdown/main-nav-menu-content.tsx
index 51318285ba1..4e63f2877e0 100644
--- a/web/app/components/header/account-dropdown/main-nav-menu-content.tsx
+++ b/web/app/components/header/account-dropdown/main-nav-menu-content.tsx
@@ -16,7 +16,7 @@ import {
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useTheme } from 'next-themes'
import { useQueryState } from 'nuqs'
import { useTranslation } from 'react-i18next'
@@ -28,6 +28,7 @@ import {
import { useProviderContext } from '@/context/provider-context'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import Link from '@/next/link'
+import { consoleQuery } from '@/service/client'
import { ExternalLinkIndicator, MenuItemContent } from './menu-item-content'
type MainNavRadioItemContentProps = {
@@ -123,7 +124,13 @@ export function MainNavMenuContent({ onLogout }: MainNavMenuContentProps) {
...userProfileQueryOptions(),
select: (data) => data.profile,
})
- const { isEducationAccount } = useProviderContext()
+ const { enableEducationPlan } = useProviderContext()
+ const { data: isEducationAccount = false } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: ({ is_student }) => is_student ?? false,
+ }),
+ )
const [, setSettingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser)
return (
diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsx
index 506c6fcd7d3..b85284a35c1 100644
--- a/web/app/components/main-nav/__tests__/index.spec.tsx
+++ b/web/app/components/main-nav/__tests__/index.spec.tsx
@@ -491,7 +491,11 @@ const defaultMainNavSystemFeatures: MainNavSystemFeatures = {
const renderMainNav = (
systemFeatures: MainNavSystemFeatures = defaultMainNavSystemFeatures,
- options: { store?: ReturnType<typeof createStore>; extra?: ReactNode } = {},
+ options: {
+ store?: ReturnType<typeof createStore>
+ extra?: ReactNode
+ educationStatus?: NonNullable<Parameters<typeof renderWithConsoleQuery>[1]>['educationStatus']
+ } = {},
) => {
const queryClient = createConsoleQueryClient()
const currentConsoleState = mockConsoleState.current ?? consoleState
@@ -531,6 +535,7 @@ const renderMainNav = (
</JotaiProvider>,
{
systemFeatures: resolvedSystemFeatures,
+ educationStatus: options.educationStatus,
workspacePermissionKeys: currentConsoleState.workspacePermissionKeys,
queryClient,
},
@@ -579,7 +584,7 @@ describe('MainNav', () => {
mockConsoleState.current = consoleState
;(useProviderContext as Mock).mockReturnValue({
enableBilling: true,
- isEducationAccount: false,
+ enableEducationPlan: false,
isEducationWorkspace: false,
isFetchedPlan: true,
plan: { type: Plan.sandbox },
@@ -726,13 +731,15 @@ describe('MainNav', () => {
it('shows the user education badge in the account popup without adding the workspace plan there', async () => {
;(useProviderContext as Mock).mockReturnValue({
enableBilling: true,
- isEducationAccount: true,
+ enableEducationPlan: true,
isEducationWorkspace: false,
isFetchedPlan: true,
plan: { type: Plan.sandbox },
} as ProviderContextState)
- renderMainNav()
+ renderMainNav(defaultMainNavSystemFeatures, {
+ educationStatus: { is_student: true },
+ })
fireEvent.click(screen.getByRole('button', { name: 'common.account.account' }))
diff --git a/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx b/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx
index b83c4ebd0e1..aad653a814c 100644
--- a/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx
+++ b/web/app/components/main-nav/components/__tests__/workspace-card.spec.tsx
@@ -180,7 +180,7 @@ describe('WorkspaceCard', () => {
mockCurrentWorkspaceQuery()
vi.mocked(useProviderContext).mockReturnValue({
enableBilling: true,
- isEducationAccount: false,
+ enableEducationPlan: false,
isEducationWorkspace: false,
isFetchedPlan: true,
plan: { type: Plan.sandbox },
@@ -308,7 +308,7 @@ describe('WorkspaceCard', () => {
})
vi.mocked(useProviderContext).mockReturnValue({
enableBilling: false,
- isEducationAccount: false,
+ enableEducationPlan: false,
isEducationWorkspace: false,
isFetchedPlan: true,
plan: { type: Plan.sandbox },
diff --git a/web/app/education-apply/__tests__/education-apply-page.spec.tsx b/web/app/education-apply/__tests__/education-apply-page.spec.tsx
index b52afa04e77..9b0b4433986 100644
--- a/web/app/education-apply/__tests__/education-apply-page.spec.tsx
+++ b/web/app/education-apply/__tests__/education-apply-page.spec.tsx
@@ -53,11 +53,6 @@ vi.mock('@/service/billing', () => ({
fetchSubscriptionUrls: (...args: unknown[]) => mockFetchSubscriptionUrls(...args),
}))
-vi.mock('@/service/use-education', () => ({
- useEducationAdd: () => ({ isPending: false, mutateAsync: mockEducationAdd }),
- useInvalidateEducationStatus: () => vi.fn(),
-}))
-
vi.mock('@/service/use-common', () => ({
useLogout: () => ({ mutateAsync: vi.fn() }),
}))
@@ -75,6 +70,20 @@ vi.mock('@/service/client', () => ({
},
},
consoleQuery: {
+ account: {
+ education: {
+ get: {
+ key: () => ['account', 'education'],
+ queryOptions: (options: Record<string, unknown> = {}) => ({
+ queryKey: ['account', 'education'],
+ ...options,
+ }),
+ },
+ post: {
+ mutationOptions: () => ({ mutationFn: mockEducationAdd }),
+ },
+ },
+ },
systemFeatures: {
get: {
queryKey: () => ['system-features'],
@@ -103,7 +112,6 @@ vi.mock('@/service/client', () => ({
const setupContext = (isCurrentWorkspaceManager: boolean) => {
mockProviderContext = {
plan: { type: Plan.sandbox },
- isEducationAccount: true,
onPlanInfoChanged: vi.fn(),
}
mockConsoleState = {
@@ -118,7 +126,10 @@ const setupContext = (isCurrentWorkspaceManager: boolean) => {
}
const renderPage = () => {
- const { wrapper } = createConsoleQueryWrapper({ workspacePermissionKeys: null })
+ const { wrapper } = createConsoleQueryWrapper({
+ educationStatus: { is_student: true },
+ workspacePermissionKeys: null,
+ })
return render(<EducationApplyPage />, {
wrapper,
})
diff --git a/web/app/education-apply/__tests__/expire-notice.spec.tsx b/web/app/education-apply/__tests__/expire-notice.spec.tsx
index 329dbd51552..269ad682850 100644
--- a/web/app/education-apply/__tests__/expire-notice.spec.tsx
+++ b/web/app/education-apply/__tests__/expire-notice.spec.tsx
@@ -14,9 +14,7 @@ const mockPricingModal = vi.hoisted(() => ({ isOpen: false }))
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
- allowRefreshEducationVerify: mockEducationStatus.allowRefresh,
- educationAccountExpireAt: mockEducationStatus.expireAt,
- isLoadingEducationAccountInfo: mockEducationStatus.isLoading,
+ enableEducationPlan: true,
}),
}))
@@ -40,6 +38,12 @@ vi.mock('@/next/dynamic', () => ({
const renderNotice = (accountId = 'user-1') => {
const { wrapper } = createConsoleQueryWrapper({
accountProfile: { id: accountId, timezone: 'UTC' },
+ educationStatus: mockEducationStatus.isLoading
+ ? undefined
+ : {
+ allow_refresh: mockEducationStatus.allowRefresh,
+ expire_at: mockEducationStatus.expireAt,
+ },
})
return render(<EducationExpireNotice />, { wrapper })
diff --git a/web/app/education-apply/education-apply-page.tsx b/web/app/education-apply/education-apply-page.tsx
index 60b938e88b4..090536d684a 100644
--- a/web/app/education-apply/education-apply-page.tsx
+++ b/web/app/education-apply/education-apply-page.tsx
@@ -7,7 +7,6 @@ import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { toast } from '@langgenius/dify-ui/toast'
import { useMutation, useQuery } from '@tanstack/react-query'
-import { noop } from 'es-toolkit/function'
import { useAtomValue } from 'jotai'
import { useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -19,7 +18,6 @@ import { currentWorkspaceAtom, isCurrentWorkspaceManagerAtom } from '@/context/w
import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'
import { useRouter, useSearchParams } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/client'
-import { useEducationAdd, useInvalidateEducationStatus } from '@/service/use-education'
import { DifyLogo } from '../components/base/logo/dify-logo'
import AppliedEducationContent from './applied-education-content'
import RoleSelector from './role-selector'
@@ -40,11 +38,17 @@ const EducationApplyAgeContent = () => {
const [inSchoolChecked, setInSchoolChecked] = useState(false)
const [hasSubmittedEducation, setHasSubmittedEducation] = useState(false)
const [isOpeningBillingPortal, setIsOpeningBillingPortal] = useState(false)
- const { isPending, mutateAsync: educationAdd } = useEducationAdd({ onSuccess: noop })
- const { onPlanInfoChanged, isEducationAccount, plan } = useProviderContext()
+ const { isPending, mutateAsync: educationAdd } = useMutation(
+ consoleQuery.account.education.post.mutationOptions(),
+ )
+ const { onPlanInfoChanged, plan } = useProviderContext()
+ const { data: isEducationAccount = false } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ select: ({ is_student }) => is_student ?? false,
+ }),
+ )
const currentWorkspace = useAtomValue(currentWorkspaceAtom)
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
- const updateEducationStatus = useInvalidateEducationStatus()
const docLink = useDocLink()
const { handleEducationDiscount } = useEducationDiscount()
const router = useRouter()
@@ -62,13 +66,14 @@ const EducationApplyAgeContent = () => {
})()
const handleSubmit = () => {
educationAdd({
- token: token || '',
- role,
- institution: schoolName,
+ body: {
+ token: token || '',
+ role,
+ institution: schoolName,
+ },
}).then((res) => {
if (res.message === 'success') {
onPlanInfoChanged()
- updateEducationStatus()
setHasSubmittedEducation(true)
} else {
toast.error(t(($) => $.submitError, { ns: 'education' }))
diff --git a/web/app/education-apply/types.ts b/web/app/education-apply/types.ts
index ff435c6fc0f..8cc06101b82 100644
--- a/web/app/education-apply/types.ts
+++ b/web/app/education-apply/types.ts
@@ -3,9 +3,3 @@ export type SearchParams = {
page?: number
limit?: number
}
-
-export type EducationAddParams = {
- token: string
- institution: string
- role: string
-}
diff --git a/web/app/education-apply/use-expire-notice.ts b/web/app/education-apply/use-expire-notice.ts
index f109ea9c3bf..cf2f7ea057b 100644
--- a/web/app/education-apply/use-expire-notice.ts
+++ b/web/app/education-apply/use-expire-notice.ts
@@ -1,5 +1,6 @@
'use client'
+import type { EducationStatusResponse } from '@dify/contracts/api/console/account/types.gen'
import type { DismissedEducationExpireNotice, EducationExpireNoticePhase } from './storage'
import { useQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
@@ -7,11 +8,17 @@ import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'
import { useProviderContext } from '@/context/provider-context'
import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { consoleQuery } from '@/service/client'
import { useDismissedEducationExpireNotice } from './storage'
dayjs.extend(utc)
dayjs.extend(timezone)
+const selectEducationExpireStatus = ({ allow_refresh, expire_at }: EducationStatusResponse) => ({
+ allowRefresh: allow_refresh ?? false,
+ expireAt: expire_at ?? null,
+})
+
export type EducationExpireNotice = {
accountId: string
expireAt: number
@@ -67,15 +74,20 @@ export function useEducationExpireNotice() {
timezone: profile.timezone ?? undefined,
}),
})
- const { educationAccountExpireAt, allowRefreshEducationVerify, isLoadingEducationAccountInfo } =
- useProviderContext()
+ const { enableEducationPlan } = useProviderContext()
+ const { data: educationStatus, isLoading: isLoadingEducationStatus } = useQuery(
+ consoleQuery.account.education.get.queryOptions({
+ enabled: enableEducationPlan,
+ select: selectEducationExpireStatus,
+ }),
+ )
const [dismissedNotice, setDismissedNotice] = useDismissedEducationExpireNotice()
const notice = resolveEducationExpireNotice({
accountId: profile?.accountId,
- allowRefresh: allowRefreshEducationVerify,
+ allowRefresh: educationStatus?.allowRefresh ?? false,
dismissedNotice,
- expireAt: educationAccountExpireAt,
- isLoading: isLoadingEducationAccountInfo,
+ expireAt: educationStatus?.expireAt ?? null,
+ isLoading: isLoadingEducationStatus,
userTimezone: profile?.timezone,
})
diff --git a/web/context/provider-context-provider.tsx b/web/context/provider-context-provider.tsx
index 2ac64cf7090..0d8db65969c 100644
--- a/web/context/provider-context-provider.tsx
+++ b/web/context/provider-context-provider.tsx
@@ -21,7 +21,6 @@ import {
useModelListByType,
useSupportRetrievalMethods,
} from '@/service/use-common'
-import { useEducationStatus } from '@/service/use-education'
import { ProviderContext } from './provider-context'
type ProviderContextProviderProps = {
@@ -88,12 +87,6 @@ export const ProviderContextProvider = ({ children }: ProviderContextProviderPro
const [enableEducationPlan, setEnableEducationPlan] = useState(false)
const [isEducationWorkspace, setIsEducationWorkspace] = useState(false)
- const {
- data: educationAccountInfo,
- isLoading: isLoadingEducationAccountInfo,
- isFetching: isFetchingEducationAccountInfo,
- isFetchedAfterMount: isEducationDataFetchedAfterMount,
- } = useEducationStatus(!enableEducationPlan)
const [isAllowTransferWorkspace, setIsAllowTransferWorkspace] = useState(false)
const [
isAllowPublishAsCustomKnowledgePipelineTemplate,
@@ -192,17 +185,6 @@ export const ProviderContextProvider = ({ children }: ProviderContextProviderPro
datasetOperatorEnabled,
enableEducationPlan,
isEducationWorkspace,
- isEducationAccount: isEducationDataFetchedAfterMount
- ? (educationAccountInfo?.is_student ?? false)
- : false,
- allowRefreshEducationVerify: isEducationDataFetchedAfterMount
- ? (educationAccountInfo?.allow_refresh ?? false)
- : false,
- educationAccountExpireAt: isEducationDataFetchedAfterMount
- ? (educationAccountInfo?.expire_at ?? null)
- : null,
- isLoadingEducationAccountInfo,
- isFetchingEducationAccountInfo,
webappCopyrightEnabled,
licenseLimit,
refreshLicenseLimit: fetchPlan,
diff --git a/web/context/provider-context.ts b/web/context/provider-context.ts
index 8804377668c..73a69d20ae6 100644
--- a/web/context/provider-context.ts
+++ b/web/context/provider-context.ts
@@ -35,11 +35,6 @@ export type ProviderContextState = {
datasetOperatorEnabled: boolean
enableEducationPlan: boolean
isEducationWorkspace: boolean
- isEducationAccount: boolean
- allowRefreshEducationVerify: boolean
- educationAccountExpireAt: number | null
- isLoadingEducationAccountInfo: boolean
- isFetchingEducationAccountInfo: boolean
webappCopyrightEnabled: boolean
licenseLimit: {
workspace_members: {
@@ -72,11 +67,6 @@ export const baseProviderContextValue: ProviderContextState = {
datasetOperatorEnabled: false,
enableEducationPlan: false,
isEducationWorkspace: false,
- isEducationAccount: false,
- allowRefreshEducationVerify: false,
- educationAccountExpireAt: null,
- isLoadingEducationAccountInfo: false,
- isFetchingEducationAccountInfo: false,
webappCopyrightEnabled: false,
licenseLimit: {
workspace_members: {
diff --git a/web/service/__tests__/use-education.spec.tsx b/web/service/__tests__/use-education.spec.tsx
index a064eaa5da6..1d584d29f96 100644
--- a/web/service/__tests__/use-education.spec.tsx
+++ b/web/service/__tests__/use-education.spec.tsx
@@ -1,14 +1,18 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
-import { useEducationVerify } from '../use-education'
+import { useEducationAutocomplete, useEducationVerify } from '../use-education'
+const mockAutocompleteEducation = vi.hoisted(() => vi.fn())
const mockVerifyEducation = vi.hoisted(() => vi.fn())
vi.mock('../client', () => ({
consoleClient: {
account: {
education: {
+ autocomplete: {
+ get: mockAutocompleteEducation,
+ },
verify: {
get: mockVerifyEducation,
},
@@ -30,6 +34,29 @@ const createWrapper = () => {
)
}
+describe('useEducationAutocomplete', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('normalizes an empty generated response for the search UI', async () => {
+ mockAutocompleteEducation.mockResolvedValue({})
+ const { result } = renderHook(() => useEducationAutocomplete(), { wrapper: createWrapper() })
+
+ await act(async () => {
+ await expect(result.current.mutateAsync({ keywords: 'Dify' })).resolves.toEqual({
+ curr_page: 0,
+ data: [],
+ has_next: false,
+ })
+ })
+
+ expect(mockAutocompleteEducation).toHaveBeenCalledWith({
+ query: { keywords: 'Dify', limit: 40, page: 0 },
+ })
+ })
+})
+
describe('useEducationVerify', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/web/service/client.spec.ts b/web/service/client.spec.ts
index 97e6a23efaf..65360c80d18 100644
--- a/web/service/client.spec.ts
+++ b/web/service/client.spec.ts
@@ -572,6 +572,68 @@ describe('consoleQuery agent query defaults', () => {
})
})
+describe('consoleQuery education defaults', () => {
+ it('should not retry education status failures', async () => {
+ const request = vi.fn().mockRejectedValue(new Error('education status failed'))
+ const consoleQuery = await loadConsoleQueryWithRequest(request)
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: 2 },
+ },
+ })
+
+ await expect(
+ queryClient.fetchQuery(consoleQuery.account.education.get.queryOptions()),
+ ).rejects.toThrow('education status failed')
+
+ expect(request).toHaveBeenCalledTimes(1)
+ })
+
+ it('should invalidate education status after activation succeeds', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
+
+ await consoleQuery.account.education.post.mutationOptions().onSuccess?.(
+ { message: 'success' },
+ {
+ body: {
+ institution: 'Dify University',
+ role: 'Student',
+ token: 'education-token',
+ },
+ },
+ undefined,
+ createMutationContext(queryClient),
+ )
+
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: consoleQuery.account.education.get.key(),
+ })
+ })
+
+ it('should preserve education status after activation is rejected', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
+
+ await consoleQuery.account.education.post.mutationOptions().onSuccess?.(
+ { message: 'failed' },
+ {
+ body: {
+ institution: 'Dify University',
+ role: 'Student',
+ token: 'education-token',
+ },
+ },
+ undefined,
+ createMutationContext(queryClient),
+ )
+
+ expect(invalidateQueries).not.toHaveBeenCalled()
+ })
+})
+
describe('consoleQuery app mutation defaults', () => {
it('should write an updated app into its exact detail cache', async () => {
const consoleQuery = await loadConsoleQuery()
diff --git a/web/service/client.ts b/web/service/client.ts
index e6db101d8cf..4c13689daa5 100644
--- a/web/service/client.ts
+++ b/web/service/client.ts
@@ -382,6 +382,26 @@ export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQue
{
path: ['console'],
experimental_defaults: {
+ account: {
+ education: {
+ get: {
+ queryOptions: {
+ retry: false,
+ },
+ },
+ post: {
+ mutationOptions: {
+ onSuccess: (data, _variables, _onMutateResult, context) => {
+ if (data.message !== 'success') return
+
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.account.education.get.key(),
+ })
+ },
+ },
+ },
+ },
+ },
apps: {
post: {
mutationOptions: {
diff --git a/web/service/use-education.ts b/web/service/use-education.ts
index 010893f8e88..b473820fab3 100644
--- a/web/service/use-education.ts
+++ b/web/service/use-education.ts
@@ -1,8 +1,5 @@
-import type { EducationAddParams } from '@/app/education-apply/types'
-import { useMutation, useQuery } from '@tanstack/react-query'
-import { get, post } from './base'
+import { useMutation } from '@tanstack/react-query'
import { consoleClient } from './client'
-import { useInvalid } from './use-base'
const NAME_SPACE = 'education'
@@ -21,18 +18,6 @@ export const useEducationVerify = () => {
})
}
-export const useEducationAdd = ({ onSuccess }: { onSuccess?: () => void }) => {
- return useMutation({
- mutationKey: [NAME_SPACE, 'education-add'],
- mutationFn: (params: EducationAddParams) => {
- return post<{ message: string }>('/account/education', {
- body: params,
- })
- },
- onSuccess,
- })
-}
-
type SearchParams = {
keywords?: string
page?: number
@@ -40,29 +25,17 @@ type SearchParams = {
}
export const useEducationAutocomplete = () => {
return useMutation({
- mutationFn: (searchParams: SearchParams) => {
+ mutationFn: async (searchParams: SearchParams) => {
const { keywords = '', page = 0, limit = 40 } = searchParams
- return get<{ data: string[]; has_next: boolean; curr_page: number }>(
- `/account/education/autocomplete?keywords=${keywords}&page=${page}&limit=${limit}`,
- )
- },
- })
-}
+ const response = await consoleClient.account.education.autocomplete.get({
+ query: { keywords, limit, page },
+ })
-export const useEducationStatus = (disable?: boolean) => {
- return useQuery({
- enabled: !disable,
- queryKey: [NAME_SPACE, 'education-status'],
- queryFn: () => {
- return get<{ is_student: boolean; allow_refresh: boolean; expire_at: number | null }>(
- '/account/education',
- )
+ return {
+ curr_page: response.curr_page ?? page,
+ data: response.data ?? [],
+ has_next: response.has_next ?? false,
+ }
},
- retry: false,
- staleTime: 0, // Data expires immediately, ensuring fresh data on refetch
})
}
-
-export const useInvalidateEducationStatus = () => {
- return useInvalid([NAME_SPACE, 'education-status'])
-}
diff --git a/web/test/console/query-data.ts b/web/test/console/query-data.ts
index 0fc0efc26d3..a468bb0283a 100644
--- a/web/test/console/query-data.ts
+++ b/web/test/console/query-data.ts
@@ -1,4 +1,7 @@
-import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
+import type {
+ EducationStatusResponse,
+ GetAccountProfileResponse,
+} from '@dify/contracts/api/console/account/types.gen'
import type {
GetSystemFeaturesLicenseResponse,
GetSystemFeaturesResponse,
@@ -105,6 +108,20 @@ export const seedSystemFeaturesLicense = (
return data
}
+export const seedEducationStatus = (
+ queryClient: QueryClient,
+ overrides: Partial<EducationStatusResponse> = {},
+): EducationStatusResponse => {
+ const data: EducationStatusResponse = {
+ allow_refresh: false,
+ expire_at: null,
+ is_student: false,
+ ...overrides,
+ }
+ queryClient.setQueryData(consoleQuery.account.education.get.queryOptions().queryKey, data)
+ return data
+}
+
const ensureSystemFeatures = (queryClient: QueryClient) => {
const queryKey = consoleQuery.systemFeatures.get.queryKey()
const existingSystemFeatures = queryClient.getQueryData<GetSystemFeaturesResponse>(queryKey)
@@ -142,6 +159,7 @@ export type ConsoleQueryTestOptions = {
*/
systemFeatures?: DeepPartial<GetSystemFeaturesResponse> | null
accountProfile?: Partial<GetAccountProfileResponse> | null
+ educationStatus?: Partial<EducationStatusResponse>
currentWorkspace?: Partial<GetWorkspacesCurrentSummaryResponse> | null
trialModels?: readonly string[] | null
workspacePermissionKeys?: readonly string[] | null
@@ -167,6 +185,7 @@ export const createConsoleQueryWrapper = (
if (options.accountProfile) seedAccountProfileQuery(queryClient, options.accountProfile)
else ensureAccountProfileQuery(queryClient, { timezone: 'UTC' })
}
+ if (options.educationStatus) seedEducationStatus(queryClient, options.educationStatus)
if (options.currentWorkspace !== null) {
const queryKey = getCurrentWorkspaceQueryKey()
if (options.currentWorkspace)
@@ -205,6 +224,7 @@ export const renderWithConsoleQuery = (
const {
systemFeatures: sf,
accountProfile,
+ educationStatus,
currentWorkspace,
trialModels,
workspacePermissionKeys,
@@ -215,6 +235,7 @@ export const renderWithConsoleQuery = (
const { wrapper, queryClient, systemFeatures } = createConsoleQueryWrapper({
systemFeatures: sf,
accountProfile,
+ educationStatus,
currentWorkspace,
trialModels,
workspacePermissionKeys,
@@ -235,6 +256,7 @@ export const renderHookWithConsoleQuery = <Result, Props = void>(
const {
systemFeatures: sf,
accountProfile,
+ educationStatus,
currentWorkspace,
trialModels,
workspacePermissionKeys,
@@ -245,6 +267,7 @@ export const renderHookWithConsoleQuery = <Result, Props = void>(
const { wrapper, queryClient, systemFeatures } = createConsoleQueryWrapper({
systemFeatures: sf,
accountProfile,
+ educationStatus,
currentWorkspace,
trialModels,
workspacePermissionKeys,