From 59b99e08ee28806a70bdadb98d179b03549390d0 Mon Sep 17 00:00:00 2001 From: lws49 Date: Tue, 21 Jul 2026 02:09:26 +0800 Subject: [PATCH] feat(marketplace): system-admin allow-list management UI System::Admin page to manage the marketplace allow-list: add/remove typed rules (specific user, whole instance, or email domain) with a live preview of who each rule would let in, and an open-to-everyone / restrict toggle. --- .../assessment/marketplace/allowlist_rule.rb | 6 +- client/app/api/system/Admin.ts | 75 +++ .../system/admin/admin/AdminNavigator.tsx | 10 + .../MarketplaceAllowlistModeBanner.tsx | 133 +++++ .../forms/MarketplaceAllowlistRuleForm.tsx | 467 +++++++++++++++ .../MarketplaceAllowlistRuleForm.test.tsx | 543 ++++++++++++++++++ .../tables/MarketplaceAllowlistTable.tsx | 179 ++++++ .../MarketplaceAllowlistTable.test.tsx | 99 ++++ .../admin/pages/MarketplaceAllowlistIndex.tsx | 174 ++++++ .../MarketplaceAllowlistIndex.test.tsx | 435 ++++++++++++++ client/app/routers/courseless/systemAdmin.tsx | 11 + client/app/types/system/marketplaceAccess.ts | 19 + .../app/types/system/marketplaceAllowlist.ts | 19 + client/locales/en.json | 174 ++++++ client/locales/ko.json | 171 ++++++ client/locales/zh.json | 171 ++++++ ...etplace_allowlist_rules_controller_spec.rb | 2 +- .../marketplace/allowlist_rule_spec.rb | 10 +- 18 files changed, 2689 insertions(+), 9 deletions(-) create mode 100644 client/app/bundles/system/admin/admin/components/MarketplaceAllowlistModeBanner.tsx create mode 100644 client/app/bundles/system/admin/admin/components/forms/MarketplaceAllowlistRuleForm.tsx create mode 100644 client/app/bundles/system/admin/admin/components/forms/__test__/MarketplaceAllowlistRuleForm.test.tsx create mode 100644 client/app/bundles/system/admin/admin/components/tables/MarketplaceAllowlistTable.tsx create mode 100644 client/app/bundles/system/admin/admin/components/tables/__test__/MarketplaceAllowlistTable.test.tsx create mode 100644 client/app/bundles/system/admin/admin/pages/MarketplaceAllowlistIndex.tsx create mode 100644 client/app/bundles/system/admin/admin/pages/__test__/MarketplaceAllowlistIndex.test.tsx create mode 100644 client/app/types/system/marketplaceAccess.ts create mode 100644 client/app/types/system/marketplaceAllowlist.ts diff --git a/app/models/course/assessment/marketplace/allowlist_rule.rb b/app/models/course/assessment/marketplace/allowlist_rule.rb index a5c3317f169..b164934db3e 100644 --- a/app/models/course/assessment/marketplace/allowlist_rule.rb +++ b/app/models/course/assessment/marketplace/allowlist_rule.rb @@ -27,11 +27,11 @@ class Course::Assessment::Marketplace::AllowlistRule < ApplicationRecord # whose email matched nobody keeps user_id NULL, and Rails checks that as `user_id IS NULL`, # which matches every instance and email-domain rule — reporting a bogus duplicate on top of the # real "No user with that email." Scoping confines the check to rules of the same type. - validates :user_id, uniqueness: { scope: :rule_type, message: 'already has a rule.' }, + validates :user_id, uniqueness: { scope: :rule_type, message: 'already has the same rule.' }, if: :rule_type_user? - validates :instance_id, uniqueness: { scope: :rule_type, message: 'already has a rule.' }, + validates :instance_id, uniqueness: { scope: :rule_type, message: 'already has the same rule.' }, if: :rule_type_instance? - validates :email_domain, uniqueness: { scope: :rule_type, message: 'already has a rule.' }, + validates :email_domain, uniqueness: { scope: :rule_type, message: 'already has the same rule.' }, if: :rule_type_email_domain? # "Everyone" is the widest rule; only one may exist. Paired with a partial unique index. validates :rule_type, uniqueness: true, if: :rule_type_everyone? diff --git a/client/app/api/system/Admin.ts b/client/app/api/system/Admin.ts index 40eac58adc4..47eb69b80f4 100644 --- a/client/app/api/system/Admin.ts +++ b/client/app/api/system/Admin.ts @@ -5,6 +5,11 @@ import { } from 'types/course/announcements'; import { CourseListData } from 'types/system/courses'; import { InstanceListData, InstancePermissions } from 'types/system/instances'; +import { AllowlistRulePreviewData } from 'types/system/marketplaceAccess'; +import { + AllowlistRuleData, + AllowlistRuleFormData, +} from 'types/system/marketplaceAllowlist'; import { AdminStats, UserListData } from 'types/users'; import BaseSystemAPI from '../Base'; @@ -173,4 +178,74 @@ export default class AdminAPI extends BaseSystemAPI { getDeploymentInfo(): Promise> { return this.client.get(`${AdminAPI.#urlPrefix}/deployment_info`); } + + /** + * Fetches the marketplace allow-list rules. + */ + indexMarketplaceAllowlistRules(): Promise< + AxiosResponse<{ rules: AllowlistRuleData[]; everyoneRuleId: number | null }> + > { + return this.client.get( + `${AdminAPI.#urlPrefix}/marketplace_allowlist_rules`, + ); + } + + /** + * Creates a marketplace allow-list rule. + */ + createMarketplaceAllowlistRule( + params: AllowlistRuleFormData, + ): Promise> { + return this.client.post( + `${AdminAPI.#urlPrefix}/marketplace_allowlist_rules`, + { + allowlist_rule: { + rule_type: params.ruleType, + instance_id: params.instanceId, + email_domain: params.emailDomain, + email: params.email, + }, + }, + ); + } + + /** + * Dry run for a prospective allow-list rule: reports who it would let in, without saving it. + * Runs the same validations as create, so a duplicate rule is reported here as a 400. + */ + previewMarketplaceAllowlistRule( + params: AllowlistRuleFormData, + ): Promise> { + return this.client.post( + `${AdminAPI.#urlPrefix}/marketplace_allowlist_rules/preview`, + { + allowlist_rule: { + rule_type: params.ruleType, + instance_id: params.instanceId, + email_domain: params.emailDomain, + email: params.email, + }, + }, + ); + } + + /** + * Opens the marketplace to everyone by creating the single `everyone` allow-list rule. + * Returns the created rule; only its `id` is consumed (to later restrict). + */ + openMarketplaceToEveryone(): Promise> { + return this.client.post( + `${AdminAPI.#urlPrefix}/marketplace_allowlist_rules`, + { allowlist_rule: { rule_type: 'everyone' } }, + ); + } + + /** + * Deletes a marketplace allow-list rule. + */ + deleteMarketplaceAllowlistRule(id: number): Promise { + return this.client.delete( + `${AdminAPI.#urlPrefix}/marketplace_allowlist_rules/${id}`, + ); + } } diff --git a/client/app/bundles/system/admin/admin/AdminNavigator.tsx b/client/app/bundles/system/admin/admin/AdminNavigator.tsx index c445a5b9d15..ddb5875f3c7 100644 --- a/client/app/bundles/system/admin/admin/AdminNavigator.tsx +++ b/client/app/bundles/system/admin/admin/AdminNavigator.tsx @@ -5,6 +5,7 @@ import { Category, Chat, Group, + Storefront, } from '@mui/icons-material'; import useTranslation from 'lib/hooks/useTranslation'; @@ -32,6 +33,10 @@ const translations = defineMessages({ id: 'system.admin.admin.AdminNavigator.getHelp', defaultMessage: 'Get Help', }, + marketplace: { + id: 'system.admin.admin.AdminNavigator.marketplace', + defaultMessage: 'Marketplace Access', + }, systemAdminPanel: { id: 'system.admin.admin.AdminNavigator.systemAdminPanel', defaultMessage: 'System Admin Panel', @@ -64,6 +69,11 @@ const AdminNavigator = (): JSX.Element => { title: t(translations.courses), path: '/admin/courses', }, + { + icon: , + title: t(translations.marketplace), + path: '/admin/marketplace_allowlist_rules', + }, { icon: , title: t(translations.getHelp), diff --git a/client/app/bundles/system/admin/admin/components/MarketplaceAllowlistModeBanner.tsx b/client/app/bundles/system/admin/admin/components/MarketplaceAllowlistModeBanner.tsx new file mode 100644 index 00000000000..d2a218286e1 --- /dev/null +++ b/client/app/bundles/system/admin/admin/components/MarketplaceAllowlistModeBanner.tsx @@ -0,0 +1,133 @@ +import { useState } from 'react'; +import { defineMessages } from 'react-intl'; +import { Alert, FormControlLabel, Switch, Typography } from '@mui/material'; + +import Prompt from 'lib/components/core/dialogs/Prompt'; +import useTranslation from 'lib/hooks/useTranslation'; + +interface Props { + openToEveryone: boolean; + onOpenToEveryone: () => Promise; + onRestrict: () => Promise; +} + +const translations = defineMessages({ + scopedTitle: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.scopedTitle', + defaultMessage: 'Access is limited to the rules below.', + }, + everyoneTitle: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.everyoneTitle', + defaultMessage: + 'The marketplace is open to all eligible staff: course managers/owners and instance instructors/administrators. The rules below are preserved but inactive.', + }, + toggleLabel: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.toggleLabel', + defaultMessage: 'Open to everyone', + }, + openConfirmTitle: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmTitle', + defaultMessage: 'Open marketplace to everyone?', + }, + openConfirmBody: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmBody', + defaultMessage: + 'This makes the marketplace visible to all eligible staff: course managers/owners and instance instructors/administrators. You can restrict it again at any time; your scoped rules are kept.', + }, + restrictConfirmTitle: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmTitle', + defaultMessage: 'Restrict to scoped rules?', + }, + restrictConfirmBody: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmBody', + defaultMessage: + 'The marketplace will again be limited to the rules below. Eligible staff not covered by a rule will lose access.', + }, + confirmOpen: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.confirmOpen', + defaultMessage: 'Open to everyone', + }, + confirmRestrict: { + id: 'system.admin.admin.MarketplaceAllowlistModeBanner.confirmRestrict', + defaultMessage: 'Restrict', + }, +}); + +const MarketplaceAllowlistModeBanner = ({ + openToEveryone, + onOpenToEveryone, + onRestrict, +}: Props): JSX.Element => { + const { t } = useTranslation(); + const [isConfirmOpen, setIsConfirmOpen] = useState(false); + const [submitting, setSubmitting] = useState(false); + + const handleConfirm = async (): Promise => { + setSubmitting(true); + try { + await (openToEveryone ? onRestrict() : onOpenToEveryone()); + setIsConfirmOpen(false); + } finally { + setSubmitting(false); + } + }; + + return ( + <> + setIsConfirmOpen(true)} + /> + } + label={ + + {t(translations.toggleLabel)} + + } + labelPlacement="start" + sx={{ mr: 1 }} + /> + } + className="mb-4 [&_.MuiAlert-action]:items-center [&_.MuiAlert-action]:pt-0" + severity={openToEveryone ? 'success' : 'info'} + > + {openToEveryone + ? t(translations.everyoneTitle) + : t(translations.scopedTitle)} + + + setIsConfirmOpen(false)} + open={isConfirmOpen} + primaryColor={openToEveryone ? 'error' : 'primary'} + primaryDisabled={submitting} + primaryLabel={ + openToEveryone + ? t(translations.confirmRestrict) + : t(translations.confirmOpen) + } + title={ + openToEveryone + ? t(translations.restrictConfirmTitle) + : t(translations.openConfirmTitle) + } + > + {openToEveryone + ? t(translations.restrictConfirmBody) + : t(translations.openConfirmBody)} + + + ); +}; + +export default MarketplaceAllowlistModeBanner; diff --git a/client/app/bundles/system/admin/admin/components/forms/MarketplaceAllowlistRuleForm.tsx b/client/app/bundles/system/admin/admin/components/forms/MarketplaceAllowlistRuleForm.tsx new file mode 100644 index 00000000000..91881017aea --- /dev/null +++ b/client/app/bundles/system/admin/admin/components/forms/MarketplaceAllowlistRuleForm.tsx @@ -0,0 +1,467 @@ +import { useEffect, useState } from 'react'; +import { defineMessages } from 'react-intl'; +import { + Alert, + Autocomplete, + Box, + Chip, + MenuItem, + TextField, + Typography, +} from '@mui/material'; +import { AxiosError } from 'axios'; +import { AllowlistRulePreviewData } from 'types/system/marketplaceAccess'; +import { + AllowlistRuleFormData, + AllowlistRuleType, +} from 'types/system/marketplaceAllowlist'; + +import SystemAPI from 'api/system'; +import Prompt from 'lib/components/core/dialogs/Prompt'; +import Link from 'lib/components/core/Link'; +import LoadingIndicator from 'lib/components/core/LoadingIndicator'; +import Table, { ColumnTemplate } from 'lib/components/table'; +import useTranslation from 'lib/hooks/useTranslation'; + +interface InstanceOption { + id: number; + name: string; +} + +interface Props { + open: boolean; + onClose: () => void; + onSubmit: (data: AllowlistRuleFormData) => Promise; +} + +const translations = defineMessages({ + title: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.title', + defaultMessage: 'Add marketplace access rule', + }, + ruleType: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.ruleType', + defaultMessage: 'Rule type', + }, + typeUser: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.typeUser', + defaultMessage: 'Specific eligible user', + }, + typeInstance: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.typeInstance', + defaultMessage: 'All eligible users in an instance', + }, + typeEmailDomain: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.typeEmailDomain', + defaultMessage: 'All eligible users with an email domain', + }, + userEmail: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.userEmail', + defaultMessage: 'Eligible user email', + }, + eligibilityHint: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.eligibilityHint', + defaultMessage: + 'Eligible users refer to course managers & owners (of any course) and instance instructors & administrators (of any instance).', + }, + instanceLabel: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.instanceId', + defaultMessage: 'Instance', + }, + emailDomain: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.emailDomain', + defaultMessage: 'Email domain (e.g. schools.gov.sg)', + }, + next: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.next', + defaultMessage: 'Next', + }, + back: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.back', + defaultMessage: 'Back', + }, + confirmAdd: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.confirmAdd', + defaultMessage: 'Confirm add', + }, + counts: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.counts', + defaultMessage: + 'Grants access to {matched, plural, one {# eligible user} other {# eligible users}}', + }, + countsOfMatched: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.countsOfMatched', + defaultMessage: + 'Grants access to {granted} of {matched, plural, one {# eligible user} other {# eligible users}}', + }, + countsExistingClause: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.countsExistingClause', + defaultMessage: '{existing} already had access', + }, + countsBlockedClause: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.countsBlockedClause', + defaultMessage: '{blocked} blocked individually', + }, + noMatches: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.noMatches', + defaultMessage: 'This rule matches nobody eligible right now.', + }, + openToEveryone: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.openToEveryone', + defaultMessage: + 'The marketplace is currently open to everyone; this rule takes effect only if you restrict access again.', + }, + previewFailure: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.previewFailure', + defaultMessage: 'Could not preview this rule.', + }, + markerNew: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.markerNew', + defaultMessage: 'New', + }, + markerExisting: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.markerExisting', + defaultMessage: 'Already has access', + }, + markerBlocked: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.markerBlocked', + defaultMessage: 'Blocked', + }, + managesCourses: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.managesCourses', + defaultMessage: 'Manages {count, plural, one {# course} other {# courses}}', + }, + colName: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.colName', + defaultMessage: 'Name', + }, + colEligibleVia: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.colEligibleVia', + defaultMessage: 'Eligible via', + }, + colStatus: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.colStatus', + defaultMessage: 'Status', + }, + searchPlaceholder: { + id: 'system.admin.admin.MarketplaceAllowlistRuleForm.searchPlaceholder', + defaultMessage: 'Search by name or email', + }, +}); + +const MarketplaceAllowlistRuleForm = ({ + open, + onClose, + onSubmit, +}: Props): JSX.Element => { + const { t } = useTranslation(); + const [step, setStep] = useState<1 | 2>(1); + const [ruleType, setRuleType] = useState('email_domain'); + const [value, setValue] = useState(''); + const [instanceId, setInstanceId] = useState(null); + const [instances, setInstances] = useState([]); + const [instancesLoaded, setInstancesLoaded] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [previewing, setPreviewing] = useState(false); + const [preview, setPreview] = useState(null); + // A validation verdict (400) blocks the add; a transport failure does not. + const [rejection, setRejection] = useState(null); + const [previewFailed, setPreviewFailed] = useState(false); + + // The instance list is only needed for the `instance` rule type, so fetch it lazily the first + // time that type is selected — keeps the page's initial load free of an unused request. + useEffect(() => { + if (ruleType !== 'instance' || instancesLoaded) return; + SystemAPI.admin.indexInstances().then((response) => { + setInstances( + response.data.instances.map((instance) => ({ + id: instance.id, + name: instance.name, + })), + ); + setInstancesLoaded(true); + }); + }, [ruleType, instancesLoaded]); + + const buildData = (): AllowlistRuleFormData => { + switch (ruleType) { + case 'user': + return { ruleType, email: value.trim() }; + case 'instance': + return { ruleType, instanceId: instanceId ?? undefined }; + default: + return { ruleType, emailDomain: value.trim() }; + } + }; + + const reset = (): void => { + setStep(1); + setRuleType('email_domain'); + setValue(''); + setInstanceId(null); + setPreview(null); + setRejection(null); + setPreviewFailed(false); + }; + + const handleClose = (): void => { + reset(); + onClose(); + }; + + const goToPreview = async (): Promise => { + setStep(2); + setPreviewing(true); + setPreview(null); + setRejection(null); + setPreviewFailed(false); + + try { + const response = + await SystemAPI.admin.previewMarketplaceAllowlistRule(buildData()); + setPreview(response.data); + } catch (error) { + const response = error instanceof AxiosError ? error.response : undefined; + const message = response?.data?.errors; + if (response?.status === 400 && message) setRejection(message); + else setPreviewFailed(true); + } finally { + setPreviewing(false); + } + }; + + const submit = async (): Promise => { + setSubmitting(true); + await onSubmit(buildData()).finally(() => setSubmitting(false)); + reset(); + }; + + const valueLabel = { + user: t(translations.userEmail), + instance: t(translations.instanceLabel), + email_domain: t(translations.emailDomain), + }[ruleType]; + + const missingValue = + ruleType === 'instance' ? instanceId === null : value.trim() === ''; + + const marker = (user: AllowlistRulePreviewData['users'][number]): string => { + if (user.blocked) return t(translations.markerBlocked); + if (user.alreadyHasAccess) return t(translations.markerExisting); + return t(translations.markerNew); + }; + + // Blocked is the one status that means the rule does not reach this person, so it is the one + // worth colouring; New and Already-has-access are both benign and stay neutral. + const markerColor = ( + user: AllowlistRulePreviewData['users'][number], + ): 'warning' | 'default' => (user.blocked ? 'warning' : 'default'); + + const previewColumns: ColumnTemplate< + AllowlistRulePreviewData['users'][number] + >[] = [ + { + of: 'name', + title: t(translations.colName), + searchable: true, + cell: (user) => ( +
+ + {user.name} + + + + {user.email} + +
+ ), + }, + { + id: 'eligibleVia', + title: t(translations.colEligibleVia), + cell: (user) => + t(translations.managesCourses, { count: user.courseCount }), + }, + { + id: 'status', + title: t(translations.colStatus), + // Fixed width, wide enough for the longest marker: the table sizes columns from the rows on + // the CURRENT page, so a page holding a Blocked chip was laying out differently from a page + // of nothing but New, and the whole table shifted as the admin paged through. + className: 'w-[16rem]', + cell: (user) => ( + + ), + }, + ]; + + const renderCounts = (): JSX.Element => { + if (preview === null) return ; + if (preview.openToEveryone) { + return {t(translations.openToEveryone)}; + } + if (preview.matchedCount === 0) { + return {t(translations.noMatches)}; + } + + // "N are new" was noise when everyone is new (the common case); the useful signal is who the + // rule does NOT reach, so name those groups only when there IS one. A blocked user keeps their + // individual block — the rule grants them nothing — so they are neither granted nor "existing". + const blocked = preview.blockedCount; + const existing = preview.matchedCount - preview.newCount - blocked; + const clauses = [ + existing > 0 && t(translations.countsExistingClause, { existing }), + blocked > 0 && t(translations.countsBlockedClause, { blocked }), + ].filter(Boolean); + + const headline = + clauses.length > 0 + ? t(translations.countsOfMatched, { + granted: preview.newCount, + matched: preview.matchedCount, + }) + : t(translations.counts, { matched: preview.matchedCount }); + + return ( + + {[headline, ...clauses].join(' · ')} + + ); + }; + + const renderStepTwo = (): JSX.Element => { + if (previewing) return ; + if (rejection !== null) return {rejection}; + if (previewFailed) { + return {t(translations.previewFailure)}; + } + + // The prebuilt Table, not a hand-rolled list: a domain or instance rule routinely matches + // hundreds of people, which needs pagination and search, and its real columns keep the three + // headers aligned for free. With nobody matched there is nothing to page or search, so the + // headers and pagination chrome would be furniture around an empty box — the counts line + // already says what happened. + const users = preview?.users ?? []; + + return ( +
+ {renderCounts()} + + {users.length > 0 && ( + user.id.toString()} + pagination={{ initialPageSize: 10, rowsPerPage: [10, 20, 50, 100] }} + search={{ + searchPlaceholder: t(translations.searchPlaceholder), + searchProps: { + shouldInclude: (user, filterValue?: string): boolean => { + if (!filterValue) return true; + const query = filterValue.toLowerCase().trim(); + return ( + user.name.toLowerCase().includes(query) || + user.email.toLowerCase().includes(query) + ); + }, + }, + }} + /> + )} + + ); + }; + + return ( + setStep(1)} + onClose={handleClose} + open={open} + primaryDisabled={ + step === 1 + ? missingValue + : submitting || previewing || rejection !== null + } + primaryLabel={ + step === 1 ? t(translations.next) : t(translations.confirmAdd) + } + secondaryLabel={step === 2 ? t(translations.back) : undefined} + title={t(translations.title)} + > + {step === 1 ? ( +
+ { + setRuleType(e.target.value as AllowlistRuleType); + setValue(''); + setInstanceId(null); + }} + select + value={ruleType} + > + {t(translations.typeUser)} + {t(translations.typeInstance)} + + {t(translations.typeEmailDomain)} + + + + {ruleType === 'instance' ? ( + instance.name} + isOptionEqualToValue={(instance, chosen): boolean => + instance.id === chosen.id + } + onChange={(_, instance): void => + setInstanceId(instance?.id ?? null) + } + options={instances} + renderInput={(inputProps): JSX.Element => ( + + )} + renderOption={(optionProps, instance): JSX.Element => ( + + {instance.name} + + )} + value={ + instances.find((instance) => instance.id === instanceId) ?? null + } + /> + ) : ( + setValue(e.target.value)} + value={value} + /> + )} + + {/* `caption` renders inline by default, which drops the parent's vertical rhythm. */} + + {t(translations.eligibilityHint)} + +
+ ) : ( +
{renderStepTwo()}
+ )} +
+ ); +}; + +export default MarketplaceAllowlistRuleForm; diff --git a/client/app/bundles/system/admin/admin/components/forms/__test__/MarketplaceAllowlistRuleForm.test.tsx b/client/app/bundles/system/admin/admin/components/forms/__test__/MarketplaceAllowlistRuleForm.test.tsx new file mode 100644 index 00000000000..90bddf501f9 --- /dev/null +++ b/client/app/bundles/system/admin/admin/components/forms/__test__/MarketplaceAllowlistRuleForm.test.tsx @@ -0,0 +1,543 @@ +import userEvent from '@testing-library/user-event'; +import { createMockAdapter } from 'mocks/axiosMock'; +import { act, fireEvent, render, waitFor } from 'test-utils'; + +import SystemAPI from 'api/system'; +import { LOADING_INDICATOR_TEST_ID } from 'lib/components/core/LoadingIndicator'; + +import MarketplaceAllowlistRuleForm from '../MarketplaceAllowlistRuleForm'; + +const mock = createMockAdapter(SystemAPI.admin.client); +beforeEach(() => mock.reset()); + +const PREVIEW_URL = '/admin/marketplace_allowlist_rules/preview'; +const NUS_DOMAIN = 'nus.edu.sg'; +const EMAIL_DOMAIN_SUBTITLE = 'Email domain (e.g. schools.gov.sg)'; +const CONFIRM_ADD = 'Confirm add'; +const GRANT_ACCESS_TO_STAFF = 'Grants access to 1 eligible user'; + +const previewUser = { + id: 1, + name: 'Jane Tan', + email: 'jane@nus.edu.sg', + courseCount: 2, + instanceRole: null, + alreadyHasAccess: false, + blocked: false, +}; + +const renderForm = ( + onSubmit = jest.fn().mockResolvedValue(undefined), + onClose = jest.fn(), +): { + page: ReturnType; + onSubmit: jest.Mock; + onClose: jest.Mock; +} => { + const page = render( + , + ); + return { page, onSubmit, onClose }; +}; + +const fillDomainAndAdvance = async ( + page: ReturnType, + domain = NUS_DOMAIN, +): Promise => { + // findBy, not getBy: test-utils' render mounts providers asynchronously, so the dialog's fields + // are not in the DOM on the first tick. + await userEvent.type( + await page.findByLabelText(EMAIL_DOMAIN_SUBTITLE), + domain, + ); + fireEvent.click(page.getByRole('button', { name: 'Next' })); +}; + +it('previews the rule once when advancing to step 2', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 12, + newCount: 5, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect( + await page.findByText( + 'Grants access to 5 of 12 eligible users · 7 already had access', + ), + ).toBeVisible(); + // Settle any post-response re-render before pinning the count: a duplicate request fired from an + // effect would be recorded AFTER the counts paint, so asserting at paint time would miss exactly + // the failure this guards against. + await act(async () => { + await Promise.resolve(); + }); + expect(mock.history.post).toHaveLength(1); + expect(JSON.parse(mock.history.post[0].data)).toEqual({ + allowlist_rule: { rule_type: 'email_domain', email_domain: NUS_DOMAIN }, + }); +}); + +it('lists the matched people with links and a new marker', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 2, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [ + previewUser, + { + ...previewUser, + id: 2, + name: 'Kumar Raj', + email: 'kumar@nus.edu.sg', + // Distinct from Jane's 2 so each row's count is queryable on its own; also covers the + // singular arm of the `{count, plural, ...}` message. + courseCount: 1, + alreadyHasAccess: true, + }, + ], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + const link = await page.findByRole('link', { name: 'Jane Tan' }); + expect(link).toHaveAttribute('href', '/users/1'); + expect(page.getByText('New')).toBeVisible(); + expect(page.getByText('Already has access')).toBeVisible(); + expect(page.getByText('Manages 2 courses')).toBeVisible(); + expect(page.getByText('Manages 1 course')).toBeVisible(); + expect(page.getByText('jane@nus.edu.sg')).toBeVisible(); +}); + +it('heads the preview list with its three columns', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect(await page.findByText('Name')).toBeVisible(); + expect(page.getByText('Eligible via')).toBeVisible(); + expect(page.getByText('Status')).toBeVisible(); +}); + +it('drops the table entirely when nobody is matched', async () => { + // Column headers and pagination chrome around an empty box say nothing the counts line has not + // already said. + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 0, + newCount: 0, + blockedCount: 0, + openToEveryone: false, + users: [], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + await page.findByText('This rule matches nobody eligible right now.'); + expect(page.queryByRole('table')).not.toBeInTheDocument(); + expect(page.queryByText('Eligible via')).not.toBeInTheDocument(); + expect( + page.queryByPlaceholderText('Search by name or email'), + ).not.toBeInTheDocument(); +}); + +it('marks a blocked match', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 0, + blockedCount: 1, + openToEveryone: false, + users: [{ ...previewUser, blocked: true }], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect(await page.findByText('Blocked')).toBeVisible(); +}); + +it('names blocked matches apart from those who already had access', async () => { + // The counts line used to derive its "already had access" number as matched - new, which swept + // blocked people into it and claimed the rule granted them access. They are held back by their + // own block, which the rule does not lift, so they are neither granted nor pre-existing. + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 10, + newCount: 6, + blockedCount: 3, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect( + await page.findByText( + 'Grants access to 6 of 10 eligible users · 1 already had access · 3 blocked individually', + ), + ).toBeVisible(); +}); + +it('omits the already-had-access clause when every exclusion is a block', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 200, + newCount: 197, + blockedCount: 3, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect( + await page.findByText( + 'Grants access to 197 of 200 eligible users · 3 blocked individually', + ), + ).toBeVisible(); +}); + +it('prefers the blocked marker over already-has-access', async () => { + // A blocked person may also already hold access; "Blocked" is the marker that matters, because + // the rule will not let them in either way. Without this the two branches could be swapped and + // every other example would still pass. + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 0, + blockedCount: 1, + openToEveryone: false, + users: [{ ...previewUser, alreadyHasAccess: true, blocked: true }], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect(await page.findByText('Blocked')).toBeVisible(); + expect(page.queryByText('Already has access')).not.toBeInTheDocument(); +}); + +it('shows a loading state while the preview is in flight', async () => { + let release = (): void => {}; + mock.onPost(PREVIEW_URL).reply( + () => + new Promise((resolve) => { + release = (): void => + resolve([ + 200, + { + matchedCount: 1, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }, + ]); + }), + ); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect(await page.findByTestId(LOADING_INDICATOR_TEST_ID)).toBeVisible(); + // Confirming before the verdict lands would create a rule the admin never previewed. + expect(page.getByRole('button', { name: CONFIRM_ADD })).toBeDisabled(); + + release(); + + expect(await page.findByText(GRANT_ACCESS_TO_STAFF)).toBeVisible(); + expect(page.queryByTestId(LOADING_INDICATOR_TEST_ID)).not.toBeInTheDocument(); + expect(page.getByRole('button', { name: CONFIRM_ADD })).toBeEnabled(); +}); + +it('flags a zero-match rule with a warning severity, and keeps it addable', async () => { + // The rule matching nobody reports a problem, so the alert is a warning, not an info note; but a + // zero-match rule is still legitimate (e.g. pre-provisioning a domain before its staff exist), so + // the add stays enabled. Asserting the severity, not just the text, is what pins info→warning. + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 0, + newCount: 0, + blockedCount: 0, + openToEveryone: false, + users: [], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + const message = await page.findByText( + 'This rule matches nobody eligible right now.', + ); + expect(message).toBeVisible(); + expect(message.closest('.MuiAlert-root')).toHaveClass( + 'MuiAlert-standardWarning', + ); + expect(page.getByRole('button', { name: CONFIRM_ADD })).toBeEnabled(); +}); + +it('explains that the rule is inert while the marketplace is open to everyone', async () => { + // matchedCount 0 as well, so this also pins the branch ORDER: the open-to-everyone message must + // win over the "matches nobody" one, which is the more useful thing to say here. + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 0, + newCount: 0, + blockedCount: 0, + openToEveryone: true, + users: [], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect( + await page.findByText( + 'The marketplace is currently open to everyone; this rule takes effect only if you restrict access again.', + ), + ).toBeVisible(); +}); + +it('blocks a duplicate rule and reports the server message', async () => { + mock.onPost(PREVIEW_URL).reply(400, { + errors: 'Email domain already has the same rule.', + }); + + const { page, onSubmit } = renderForm(); + await fillDomainAndAdvance(page); + + expect( + await page.findByText('Email domain already has the same rule.'), + ).toBeVisible(); + expect(page.getByRole('button', { name: CONFIRM_ADD })).toBeDisabled(); + expect(onSubmit).not.toHaveBeenCalled(); +}); + +it('still allows adding when the preview request itself fails', async () => { + // A preview outage is not a verdict on the rule; it must not block creation. + mock.onPost(PREVIEW_URL).reply(500); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect(await page.findByText('Could not preview this rule.')).toBeVisible(); + expect(page.getByRole('button', { name: CONFIRM_ADD })).toBeEnabled(); +}); + +it('treats a 400 with no message as an outage, not a verdict', async () => { + // Only a 400 that says what is wrong is a rejection. A bare 400 is a broken response, and must + // take the soft path rather than silently blocking creation with no explanation. + mock.onPost(PREVIEW_URL).reply(400, {}); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + + expect(await page.findByText('Could not preview this rule.')).toBeVisible(); + expect(page.getByRole('button', { name: CONFIRM_ADD })).toBeEnabled(); +}); + +it('submits the rule from step 2', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page, onSubmit } = renderForm(); + await fillDomainAndAdvance(page); + await page.findByText(GRANT_ACCESS_TO_STAFF); + + fireEvent.click(page.getByRole('button', { name: CONFIRM_ADD })); + + await waitFor(() => + expect(onSubmit).toHaveBeenCalledWith({ + ruleType: 'email_domain', + emailDomain: NUS_DOMAIN, + }), + ); +}); + +it('keeps the entered value when going back to step 1', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + await fillDomainAndAdvance(page); + await page.findByText(GRANT_ACCESS_TO_STAFF); + + fireEvent.click(page.getByRole('button', { name: 'Back' })); + + expect(await page.findByLabelText(EMAIL_DOMAIN_SUBTITLE)).toHaveValue( + NUS_DOMAIN, + ); +}); + +it('resets to a clean step 1 when cancelled', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 4, + newCount: 2, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page, onClose } = renderForm(); + await fillDomainAndAdvance(page); + await page.findByText( + 'Grants access to 2 of 4 eligible users · 2 already had access', + ); + + fireEvent.click(page.getByRole('button', { name: 'Cancel' })); + + expect(onClose).toHaveBeenCalled(); + + // The dialog stays mounted (its `open` belongs to the parent), so the reset is observable: back + // at step 1, value cleared, cached preview discarded. Without this the next open would resume + // mid-flow, showing a preview of a rule the admin already abandoned. + expect(await page.findByLabelText(EMAIL_DOMAIN_SUBTITLE)).toHaveValue(''); + expect(page.getByRole('button', { name: 'Next' })).toBeDisabled(); + expect( + page.queryByText( + 'Grants access to 2 of 4 eligible users · 2 already had access', + ), + ).not.toBeInTheDocument(); +}); + +it('previews a user rule from an email address', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + + fireEvent.mouseDown(await page.findByLabelText('Rule type')); + fireEvent.click(page.getByRole('option', { name: 'Specific eligible user' })); + + // Surrounding whitespace is a paste artefact, not part of the address. + await userEvent.type( + page.getByLabelText('Eligible user email'), + ' jane@nus.edu.sg ', + ); + fireEvent.click(page.getByRole('button', { name: 'Next' })); + + await page.findByText(GRANT_ACCESS_TO_STAFF); + expect(JSON.parse(mock.history.post[0].data)).toEqual({ + allowlist_rule: { rule_type: 'user', email: 'jane@nus.edu.sg' }, + }); +}); + +it('previews an instance rule, loading the instance list lazily and once', async () => { + mock.onGet('/admin/instances').reply(200, { + instances: [ + { id: 1, name: 'Default', host: 'coursemology.org' }, + { id: 2, name: 'Alpha', host: 'alpha.coursemology.org' }, + ], + }); + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 3, + newCount: 3, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page } = renderForm(); + + // The instance list is not fetched until the instance rule type is chosen. + expect(await page.findByLabelText('Rule type')).toBeVisible(); + expect(mock.history.get).toHaveLength(0); + + fireEvent.mouseDown(page.getByLabelText('Rule type')); + fireEvent.click( + page.getByRole('option', { name: 'All eligible users in an instance' }), + ); + + await waitFor(() => + expect( + mock.history.get.filter((r) => r.url === '/admin/instances'), + ).toHaveLength(1), + ); + + // An instance rule has no value until an instance is actually picked. + expect(page.getByRole('button', { name: 'Next' })).toBeDisabled(); + + const combobox = await page.findByRole('combobox', { name: 'Instance' }); + fireEvent.mouseDown(combobox); + fireEvent.click(page.getByRole('option', { name: 'Alpha' })); + + expect(page.getByRole('button', { name: 'Next' })).toBeEnabled(); + fireEvent.click(page.getByRole('button', { name: 'Next' })); + + await page.findByText('Grants access to 3 eligible users'); + expect(JSON.parse(mock.history.post[0].data)).toEqual({ + allowlist_rule: { rule_type: 'instance', instance_id: 2 }, + }); + expect( + mock.history.get.filter((r) => r.url === '/admin/instances'), + ).toHaveLength(1); +}); + +it('clears the entered value when the rule type changes', async () => { + const { page } = renderForm(); + + await userEvent.type( + await page.findByLabelText(EMAIL_DOMAIN_SUBTITLE), + NUS_DOMAIN, + ); + + fireEvent.mouseDown(page.getByLabelText('Rule type')); + fireEvent.click(page.getByRole('option', { name: 'Specific eligible user' })); + + // A domain is not a plausible email, so it must not carry over into the new field. + expect(page.getByLabelText('Eligible user email')).toHaveValue(''); + expect(page.getByRole('button', { name: 'Next' })).toBeDisabled(); +}); + +it('does not submit from step 1', async () => { + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + blockedCount: 0, + openToEveryone: false, + users: [previewUser], + }); + + const { page, onSubmit } = renderForm(); + await fillDomainAndAdvance(page); + + // Next only previews; the rule is created solely by the step 2 confirmation. + await page.findByText(GRANT_ACCESS_TO_STAFF); + expect(onSubmit).not.toHaveBeenCalled(); + expect(page.queryByRole('button', { name: 'Next' })).not.toBeInTheDocument(); +}); + +it('disables Next until a value is entered', async () => { + const { page } = renderForm(); + + expect(await page.findByRole('button', { name: 'Next' })).toBeDisabled(); + + await userEvent.type(page.getByLabelText(EMAIL_DOMAIN_SUBTITLE), NUS_DOMAIN); + + expect(page.getByRole('button', { name: 'Next' })).toBeEnabled(); +}); diff --git a/client/app/bundles/system/admin/admin/components/tables/MarketplaceAllowlistTable.tsx b/client/app/bundles/system/admin/admin/components/tables/MarketplaceAllowlistTable.tsx new file mode 100644 index 00000000000..93b4cf6b2c9 --- /dev/null +++ b/client/app/bundles/system/admin/admin/components/tables/MarketplaceAllowlistTable.tsx @@ -0,0 +1,179 @@ +import { ReactNode } from 'react'; +import { defineMessages } from 'react-intl'; +import { StorefrontOutlined, WarningAmber } from '@mui/icons-material'; +import { Tooltip, Typography } from '@mui/material'; +import { AllowlistRuleData } from 'types/system/marketplaceAllowlist'; + +import DeleteButton from 'lib/components/core/buttons/DeleteButton'; +import Link from 'lib/components/core/Link'; +import Table, { ColumnTemplate } from 'lib/components/table'; +import useTranslation from 'lib/hooks/useTranslation'; + +interface Props { + rules: AllowlistRuleData[]; + onDelete: (id: number) => Promise; + disabled?: boolean; + action?: ReactNode; + /** + * Rule id => number of listed users that rule grants access to. Null until the access list below + * has loaded — an unknown count must NOT render as zero, or every rule flashes a warning on load. + * A loaded map with no entry for a rule means it genuinely matches nobody: that is the warning. + */ + matchCounts?: Map | null; +} + +const translations = defineMessages({ + colType: { + id: 'system.admin.admin.MarketplaceAllowlistTable.colType', + defaultMessage: 'Type', + }, + colTarget: { + id: 'system.admin.admin.MarketplaceAllowlistTable.colTarget', + defaultMessage: 'Grants access to', + }, + colActions: { + id: 'system.admin.admin.MarketplaceAllowlistTable.colActions', + defaultMessage: 'Actions', + }, + typeUser: { + id: 'system.admin.admin.MarketplaceAllowlistTable.typeUser', + defaultMessage: 'User', + }, + typeInstance: { + id: 'system.admin.admin.MarketplaceAllowlistTable.typeInstance', + defaultMessage: 'Instance', + }, + typeEmailDomain: { + id: 'system.admin.admin.MarketplaceAllowlistTable.typeEmailDomain', + defaultMessage: 'Email domain', + }, + deleteConfirm: { + id: 'system.admin.admin.MarketplaceAllowlistTable.deleteConfirm', + defaultMessage: 'Remove this marketplace access rule?', + }, + emptyTitle: { + id: 'system.admin.admin.MarketplaceAllowlistTable.emptyTitle', + defaultMessage: 'No access rules yet', + }, + emptyHint: { + id: 'system.admin.admin.MarketplaceAllowlistTable.emptyHint', + defaultMessage: + 'The marketplace stays hidden from everyone except system administrators. Add a rule to grant access.', + }, + zeroMatchWarning: { + id: 'system.admin.admin.MarketplaceAllowlistTable.zeroMatchWarning', + defaultMessage: + 'No eligible staff currently match this rule, so it grants access to nobody.', + }, +}); + +const MarketplaceAllowlistTable = ({ + rules, + onDelete, + disabled = false, + action, + matchCounts = null, +}: Props): JSX.Element => { + const { t } = useTranslation(); + + const typeLabels: Record = { + user: t(translations.typeUser), + instance: t(translations.typeInstance), + email_domain: t(translations.typeEmailDomain), + }; + + const targetOf = (rule: AllowlistRuleData): string => { + switch (rule.ruleType) { + case 'instance': + return rule.instanceName ?? `#${rule.instanceId}`; + default: + return rule.emailDomain ?? ''; + } + }; + + const renderUserTarget = (rule: AllowlistRuleData): JSX.Element => ( + + + {rule.userName ?? `#${rule.userId}`} + + {rule.userEmail && ` (${rule.userEmail})`} + + ); + + // A loaded map (not null) with no entry for this rule means no listed user is granted by it, i.e. + // it matches nobody. Null is "not loaded yet", which must stay silent. + const matchesNobody = (rule: AllowlistRuleData): boolean => + matchCounts !== null && !matchCounts.has(rule.id); + + const renderTarget = (rule: AllowlistRuleData): JSX.Element => ( + + {matchesNobody(rule) && ( + + + + )} + {rule.ruleType === 'user' ? renderUserTarget(rule) : targetOf(rule)} + + ); + + const columns: ColumnTemplate[] = [ + { + of: 'ruleType', + title: t(translations.colType), + cell: (rule) => typeLabels[rule.ruleType], + }, + { + id: 'target', + title: t(translations.colTarget), + cell: (rule) => renderTarget(rule), + }, + { + id: 'actions', + title: t(translations.colActions), + cell: (rule) => ( + => onDelete(rule.id)} + /> + ), + }, + ]; + + const emptyState = ( +
+ + + + {t(translations.emptyTitle)} + + + + {t(translations.emptyHint)} + +
+ ); + + return ( +
+ {action &&
{action}
} + +
+
rule.id.toString()} + renderEmpty={emptyState} + /> + + + ); +}; + +export default MarketplaceAllowlistTable; diff --git a/client/app/bundles/system/admin/admin/components/tables/__test__/MarketplaceAllowlistTable.test.tsx b/client/app/bundles/system/admin/admin/components/tables/__test__/MarketplaceAllowlistTable.test.tsx new file mode 100644 index 00000000000..1c48b23adfa --- /dev/null +++ b/client/app/bundles/system/admin/admin/components/tables/__test__/MarketplaceAllowlistTable.test.tsx @@ -0,0 +1,99 @@ +import { render } from 'test-utils'; + +import MarketplaceAllowlistTable from '../MarketplaceAllowlistTable'; + +const ZERO_MATCH_WARNING = + 'No eligible staff currently match this rule, so it grants access to nobody.'; + +const DOMAIN_RULE = { + id: 10, + ruleType: 'email_domain' as const, + userId: null, + userName: null, + userEmail: null, + instanceId: null, + instanceName: null, + emailDomain: 'typo.edu.sg', +}; + +const USER_RULE = { + id: 11, + ruleType: 'user' as const, + userId: 7, + userName: 'Jane Tan', + userEmail: 'jane@nus.edu.sg', + instanceId: null, + instanceName: null, + emailDomain: null, +}; + +const INSTANCE_RULE = { + id: 12, + ruleType: 'instance' as const, + userId: null, + userName: null, + userEmail: null, + instanceId: 3, + instanceName: 'NUS', + emailDomain: null, +}; + +const renderTable = ( + matchCounts: Map | null, + rules: (typeof DOMAIN_RULE | typeof USER_RULE | typeof INSTANCE_RULE)[] = [ + DOMAIN_RULE, + ], +): ReturnType => + render( + , + ); + +it('warns on a rule that a loaded access list grants to nobody', async () => { + // Empty map = the list has loaded and this rule has no entry, so it matches nobody. The tooltip + // text is reachable by accessible name (aria-label) without hovering. + const page = renderTable(new Map()); + + expect(await page.findByLabelText(ZERO_MATCH_WARNING)).toBeInTheDocument(); + // The icon only qualifies the target; the value itself is still shown. + expect(page.getByText('typo.edu.sg')).toBeVisible(); +}); + +it('does not warn on a rule that grants access to at least one person', async () => { + const page = renderTable(new Map([[10, 3]])); + + expect(await page.findByText('typo.edu.sg')).toBeVisible(); + expect(page.queryByLabelText(ZERO_MATCH_WARNING)).not.toBeInTheDocument(); +}); + +it('shows no warning before the access list has loaded', async () => { + // Null = unknown, not zero. A warning here would flash an icon on every rule on first paint — + // the regression this guards against. + const page = renderTable(null); + + expect(await page.findByText('typo.edu.sg')).toBeVisible(); + expect(page.queryByLabelText(ZERO_MATCH_WARNING)).not.toBeInTheDocument(); +}); + +it('warns on a zero-match user rule, not only email-domain rules', async () => { + // The condition is matchCounts.has(id), uniform across rule types. Narrowing it to email_domain + // would leave a user rule that manages nobody just as invisible as it is today. + const page = renderTable(new Map(), [USER_RULE]); + + expect(await page.findByLabelText(ZERO_MATCH_WARNING)).toBeInTheDocument(); + expect(page.getByRole('link', { name: 'Jane Tan' })).toBeInTheDocument(); +}); + +it('warns on a zero-match instance rule, completing the three rule types', async () => { + // matchesNobody keys off matchCounts.has(id) and never branches on ruleType, so the instance + // path must warn identically. This also exercises the only otherwise-untested target branch: + // targetOf's instanceName render. + const page = renderTable(new Map(), [INSTANCE_RULE]); + + expect(await page.findByLabelText(ZERO_MATCH_WARNING)).toBeInTheDocument(); + // The icon only qualifies the target; the instance name is still shown. + expect(page.getByText('NUS')).toBeVisible(); +}); diff --git a/client/app/bundles/system/admin/admin/pages/MarketplaceAllowlistIndex.tsx b/client/app/bundles/system/admin/admin/pages/MarketplaceAllowlistIndex.tsx new file mode 100644 index 00000000000..587f631919d --- /dev/null +++ b/client/app/bundles/system/admin/admin/pages/MarketplaceAllowlistIndex.tsx @@ -0,0 +1,174 @@ +import { FC, useEffect, useState } from 'react'; +import { defineMessages, injectIntl, WrappedComponentProps } from 'react-intl'; +import { Typography } from '@mui/material'; +import { AxiosError } from 'axios'; +import { + AllowlistRuleData, + AllowlistRuleFormData, +} from 'types/system/marketplaceAllowlist'; + +import SystemAPI from 'api/system'; +import AddButton from 'lib/components/core/buttons/AddButton'; +import Page from 'lib/components/core/layouts/Page'; +import LoadingIndicator from 'lib/components/core/LoadingIndicator'; +import toast from 'lib/hooks/toast'; + +import MarketplaceAllowlistRuleForm from '../components/forms/MarketplaceAllowlistRuleForm'; +import MarketplaceAllowlistModeBanner from '../components/MarketplaceAllowlistModeBanner'; +import MarketplaceAllowlistTable from '../components/tables/MarketplaceAllowlistTable'; + +type Props = WrappedComponentProps; + +const translations = defineMessages({ + addRule: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.addRule', + defaultMessage: 'Add access rule', + }, + eligibility: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.eligibility', + defaultMessage: + 'Available to course managers & owners (of any course) and instance instructors & administrators (of any instance). They must also match one of the rules below.', + }, + fetchFailure: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.fetchFailure', + defaultMessage: 'Failed to load marketplace access rules.', + }, + createSuccess: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.createSuccess', + defaultMessage: 'Access rule added.', + }, + createFailure: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.createFailure', + defaultMessage: 'Failed to add access rule.', + }, + deleteSuccess: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.deleteSuccess', + defaultMessage: 'Access rule removed.', + }, + deleteFailure: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.deleteFailure', + defaultMessage: 'Failed to remove access rule.', + }, + openSuccess: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.openSuccess', + defaultMessage: 'Marketplace opened to all course managers.', + }, + openFailure: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.openFailure', + defaultMessage: 'Failed to open the marketplace to everyone.', + }, + restrictSuccess: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.restrictSuccess', + defaultMessage: 'Marketplace restricted to the scoped rules.', + }, + restrictFailure: { + id: 'system.admin.admin.MarketplaceAllowlistIndex.restrictFailure', + defaultMessage: 'Failed to restrict the marketplace.', + }, +}); + +const MarketplaceAllowlistIndex: FC = ({ intl }) => { + const [isLoading, setIsLoading] = useState(true); + const [isFormOpen, setIsFormOpen] = useState(false); + const [rules, setRules] = useState([]); + const [everyoneRuleId, setEveryoneRuleId] = useState(null); + + useEffect(() => { + SystemAPI.admin + .indexMarketplaceAllowlistRules() + .then((response) => { + setRules(response.data.rules); + setEveryoneRuleId(response.data.everyoneRuleId ?? null); + }) + .catch(() => toast.error(intl.formatMessage(translations.fetchFailure))) + .finally(() => setIsLoading(false)); + }, []); + + const openToEveryone = everyoneRuleId !== null; + + const handleCreate = async (data: AllowlistRuleFormData): Promise => { + try { + const response = + await SystemAPI.admin.createMarketplaceAllowlistRule(data); + setRules((current) => [...current, response.data]); + toast.success(intl.formatMessage(translations.createSuccess)); + setIsFormOpen(false); + } catch (error) { + // Surface the server's reason (e.g. the duplicate-rule message) — the generic fallback + // would discard exactly the message that was written for this case. + const message = + error instanceof AxiosError ? error.response?.data?.errors : undefined; + toast.error(message ?? intl.formatMessage(translations.createFailure)); + } + }; + + const handleDelete = async (id: number): Promise => { + try { + await SystemAPI.admin.deleteMarketplaceAllowlistRule(id); + setRules((current) => current.filter((rule) => rule.id !== id)); + toast.success(intl.formatMessage(translations.deleteSuccess)); + } catch { + toast.error(intl.formatMessage(translations.deleteFailure)); + } + }; + + const handleOpenToEveryone = async (): Promise => { + try { + const response = await SystemAPI.admin.openMarketplaceToEveryone(); + setEveryoneRuleId(response.data.id); + toast.success(intl.formatMessage(translations.openSuccess)); + } catch { + toast.error(intl.formatMessage(translations.openFailure)); + } + }; + + const handleRestrict = async (): Promise => { + if (everyoneRuleId === null) return; + try { + await SystemAPI.admin.deleteMarketplaceAllowlistRule(everyoneRuleId); + setEveryoneRuleId(null); + toast.success(intl.formatMessage(translations.restrictSuccess)); + } catch { + toast.error(intl.formatMessage(translations.restrictFailure)); + } + }; + + if (isLoading) return ; + + return ( + + + {intl.formatMessage(translations.eligibility)} + + + + setIsFormOpen(true)} + > + {intl.formatMessage(translations.addRule)} + + } + disabled={openToEveryone} + onDelete={handleDelete} + rules={rules} + /> + + setIsFormOpen(false)} + onSubmit={handleCreate} + open={isFormOpen} + /> + + ); +}; + +export default injectIntl(MarketplaceAllowlistIndex); diff --git a/client/app/bundles/system/admin/admin/pages/__test__/MarketplaceAllowlistIndex.test.tsx b/client/app/bundles/system/admin/admin/pages/__test__/MarketplaceAllowlistIndex.test.tsx new file mode 100644 index 00000000000..88de93f4d70 --- /dev/null +++ b/client/app/bundles/system/admin/admin/pages/__test__/MarketplaceAllowlistIndex.test.tsx @@ -0,0 +1,435 @@ +import userEvent from '@testing-library/user-event'; +import { createMockAdapter } from 'mocks/axiosMock'; +import { fireEvent, render, waitFor, within } from 'test-utils'; + +import SystemAPI from 'api/system'; + +import MarketplaceAllowlistIndex from '../MarketplaceAllowlistIndex'; + +const mock = createMockAdapter(SystemAPI.admin.client); +beforeEach(() => { + mock.reset(); +}); + +const INDEX_URL = '/admin/marketplace_allowlist_rules'; +const EMAIL_DOMAIN = 'schools.gov.sg'; +const NUS_DOMAIN = 'nus.edu.sg'; +const EMAIL_DOMAIN_SUBTITLE = 'Email domain (e.g. schools.gov.sg)'; +const OPEN_TO_EVERYONE = 'Open to everyone'; +const ADD_ACCESS_RULE = 'Add access rule'; +const allowlistGetCount = (): number => + mock.history.get.filter((request) => request.url === INDEX_URL).length; +const RULES = [ + { + id: 1, + ruleType: 'email_domain', + userId: null, + userName: null, + instanceId: null, + instanceName: null, + emailDomain: EMAIL_DOMAIN, + }, +]; +const PREVIEW_URL = '/admin/marketplace_allowlist_rules/preview'; +// Step 2's preview is a POST too, so `mock.history.post[0]` is the preview, not the create. +const createPosts = (): typeof mock.history.post => + mock.history.post.filter((request) => request.url === INDEX_URL); + +/** + * Click step 2's "Confirm add". The button is disabled while the preview request is in flight, so + * a click fired the moment it appears is swallowed — wait for it to enable first. + */ +const confirmAdd = async (page: ReturnType): Promise => { + const button = await page.findByRole('button', { name: 'Confirm add' }); + await waitFor(() => expect(button).toBeEnabled()); + fireEvent.click(button); +}; + +it('renders the allow-list rules from the API', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: RULES }); + const page = render(, { at: [INDEX_URL] }); + + // Await the fetch firing before asserting the rendered row, so mount + request and the + // subsequent re-render each get their own waitFor budget (a single window is flaky under load). + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + await waitFor(() => expect(page.getByText(EMAIL_DOMAIN)).toBeVisible()); +}); + +it('creates an email-domain rule from the add dialog', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + mock.onPost(INDEX_URL).reply(200, { + id: 2, + ruleType: 'email_domain', + userId: null, + userName: null, + instanceId: null, + instanceName: null, + emailDomain: NUS_DOMAIN, + }); + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + openToEveryone: false, + users: [], + }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + // Rule type defaults to Email domain; fill the value field. (Search fields need userEvent — + // see client/CLAUDE-testing.md; a plain TextField accepts userEvent.type too.) + await userEvent.type(page.getByLabelText(EMAIL_DOMAIN_SUBTITLE), NUS_DOMAIN); + fireEvent.click(page.getByRole('button', { name: 'Next' })); + await confirmAdd(page); + + await waitFor(() => expect(createPosts()).toHaveLength(1)); + expect(JSON.parse(createPosts()[0].data)).toEqual({ + allowlist_rule: { rule_type: 'email_domain', email_domain: NUS_DOMAIN }, + }); + await waitFor(() => expect(page.getByText(NUS_DOMAIN)).toBeVisible()); +}); + +it('deletes a rule after confirmation', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: RULES }); + mock.onDelete(`${INDEX_URL}/1`).reply(200); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(page.getByText(EMAIL_DOMAIN)).toBeVisible()); + + fireEvent.click(page.getByTestId('DeleteIconButton')); + fireEvent.click(page.getByRole('button', { name: 'Delete' })); + + await waitFor(() => expect(mock.history.delete).toHaveLength(1)); + await waitFor(() => + expect(page.queryByText(EMAIL_DOMAIN)).not.toBeInTheDocument(), + ); +}); + +it('opens the marketplace to everyone from the banner', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: RULES, everyoneRuleId: null }); + mock.onPost(INDEX_URL).reply(200, { id: 99 }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(page.getByText(EMAIL_DOMAIN)).toBeVisible()); + + // Scoped state: the banner switch is off; flipping it on prompts to open. + fireEvent.click(page.getByRole('checkbox', { name: OPEN_TO_EVERYONE })); + + // Confirm inside the dialog (its primary button shares the label, so scope to the dialog). + const dialog = page.getByRole('dialog'); + fireEvent.click( + within(dialog).getByRole('button', { name: OPEN_TO_EVERYONE }), + ); + + await waitFor(() => expect(mock.history.post).toHaveLength(1)); + expect(JSON.parse(mock.history.post[0].data)).toEqual({ + allowlist_rule: { rule_type: 'everyone' }, + }); + await waitFor(() => + expect( + page.getByText( + 'The marketplace is open to all eligible staff: course managers/owners and instance instructors/administrators. The rules below are preserved but inactive.', + ), + ).toBeVisible(), + ); +}); + +it('restricts the marketplace to scoped rules from the banner', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: RULES, everyoneRuleId: 42 }); + mock.onDelete(`${INDEX_URL}/42`).reply(200); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => + expect( + page.getByText( + 'The marketplace is open to all eligible staff: course managers/owners and instance instructors/administrators. The rules below are preserved but inactive.', + ), + ).toBeVisible(), + ); + + // Open state: the banner switch is on; flipping it off prompts to restrict. + fireEvent.click(page.getByRole('checkbox', { name: OPEN_TO_EVERYONE })); + const dialog = page.getByRole('dialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Restrict' })); + + await waitFor(() => expect(mock.history.delete).toHaveLength(1)); + expect(mock.history.delete[0].url).toBe(`${INDEX_URL}/42`); + await waitFor(() => + expect( + page.getByText('Access is limited to the rules below.'), + ).toBeVisible(), + ); +}); + +it('disables adding and removing rules while the marketplace is open to everyone', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: RULES, everyoneRuleId: 42 }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(page.getByText(EMAIL_DOMAIN)).toBeVisible()); + + // Open-to-everyone means the scoped rules are preserved but inactive: no add, no delete. + expect(page.getByRole('button', { name: ADD_ACCESS_RULE })).toBeDisabled(); + expect(page.getByTestId('DeleteIconButton')).toBeDisabled(); +}); + +it('disables Next until a required value is entered', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + + // Default rule type is email_domain → value required → Add disabled while empty. + expect(page.getByRole('button', { name: 'Next' })).toBeDisabled(); + + // Entering the required value enables it. + await userEvent.type(page.getByLabelText(EMAIL_DOMAIN_SUBTITLE), NUS_DOMAIN); + expect(page.getByRole('button', { name: 'Next' })).toBeEnabled(); +}); + +it('creates a user rule from an email', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + mock.onPost(INDEX_URL).reply(200, { + id: 4, + ruleType: 'user', + userId: 7, + userName: 'Teacher', + userEmail: 'teacher@school.edu', + instanceId: null, + instanceName: null, + emailDomain: null, + }); + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + openToEveryone: false, + users: [], + }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + fireEvent.mouseDown(page.getByLabelText('Rule type')); + fireEvent.click(page.getByRole('option', { name: 'Specific eligible user' })); + + await userEvent.type( + page.getByLabelText('Eligible user email'), + 'teacher@school.edu', + ); + fireEvent.click(page.getByRole('button', { name: 'Next' })); + await confirmAdd(page); + + await waitFor(() => expect(createPosts()).toHaveLength(1)); + expect(JSON.parse(createPosts()[0].data)).toEqual({ + allowlist_rule: { rule_type: 'user', email: 'teacher@school.edu' }, + }); + + const link = await page.findByRole('link', { name: 'Teacher' }); + expect(link).toHaveAttribute('href', '/users/7'); + expect(page.getByText('(teacher@school.edu)')).toBeVisible(); +}); + +it('clears the entered value when the rule type changes', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + + // Enter an email domain, then switch the rule type to "Specific eligible user". + await userEvent.type(page.getByLabelText(EMAIL_DOMAIN_SUBTITLE), NUS_DOMAIN); + fireEvent.mouseDown(page.getByLabelText('Rule type')); + fireEvent.click(page.getByRole('option', { name: 'Specific eligible user' })); + + // The new value field must start empty, not carry over NUS_DOMAIN. + expect(page.getByLabelText('Eligible user email')).toHaveValue(''); +}); + +it('shows who is eligible for the marketplace', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + + const page = render(, { at: [INDEX_URL] }); + + expect( + await page.findByText( + 'Available to course managers & owners (of any course) and instance instructors & administrators (of any instance). They must also match one of the rules below.', + ), + ).toBeVisible(); +}); + +it('renders a user rule as a link to the user with their email', async () => { + mock.onGet(INDEX_URL).reply(200, { + rules: [ + { + id: 5, + ruleType: 'user', + userId: 42, + userName: 'Administrator', + userEmail: 'admin@org.sg', + instanceId: null, + instanceName: null, + emailDomain: null, + }, + ], + }); + + const page = render(, { at: [INDEX_URL] }); + + const link = await page.findByRole('link', { name: 'Administrator' }); + expect(link).toHaveAttribute('href', '/users/42'); + expect(page.getByText('(admin@org.sg)')).toBeVisible(); +}); + +it('creates an instance rule by picking an instance from the dropdown', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + mock.onGet('/admin/instances').reply(200, { + instances: [ + { id: 1, name: 'Default', host: 'coursemology.org' }, + { id: 2, name: 'Alpha', host: 'alpha.coursemology.org' }, + ], + }); + mock.onPost(INDEX_URL).reply(200, { + id: 6, + ruleType: 'instance', + userId: null, + userName: null, + userEmail: null, + instanceId: 2, + instanceName: 'Alpha', + emailDomain: null, + }); + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + openToEveryone: false, + users: [], + }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + fireEvent.mouseDown(page.getByLabelText('Rule type')); + fireEvent.click( + page.getByRole('option', { name: 'All eligible users in an instance' }), + ); + + // Selecting the instance rule type lazily fetches the instance list. + await waitFor(() => + expect(mock.history.get.some((r) => r.url === '/admin/instances')).toBe( + true, + ), + ); + + const combobox = await page.findByRole('combobox', { name: 'Instance' }); + fireEvent.mouseDown(combobox); + fireEvent.click(page.getByRole('option', { name: 'Alpha' })); + + fireEvent.click(page.getByRole('button', { name: 'Next' })); + await confirmAdd(page); + + await waitFor(() => expect(createPosts()).toHaveLength(1)); + expect(JSON.parse(createPosts()[0].data)).toEqual({ + allowlist_rule: { rule_type: 'instance', instance_id: 2 }, + }); + await waitFor(() => expect(page.getByText('Alpha')).toBeVisible()); +}); + +it('renders a user rule without an email suffix when none is present', async () => { + mock.onGet(INDEX_URL).reply(200, { + rules: [ + { + id: 8, + ruleType: 'user', + userId: 12, + userName: 'No Email User', + userEmail: null, + instanceId: null, + instanceName: null, + emailDomain: null, + }, + ], + }); + + const page = render(, { at: [INDEX_URL] }); + + const link = await page.findByRole('link', { name: 'No Email User' }); + expect(link).toHaveAttribute('href', '/users/12'); + // Guard: no ` (…)` suffix — the cell's text is exactly the user name. + // (A `/\(.*\)/` regex would false-match the eligibility subtitle's "(of any course)"; + // the exact textContent check is robust and still fails if the guard is dropped, since a + // null email would render "No Email User (null)".) + expect(link.parentElement?.textContent).toBe('No Email User'); +}); + +it('disables Next for an instance rule until an instance is picked', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + mock.onGet('/admin/instances').reply(200, { + instances: [ + { id: 1, name: 'Default', host: 'coursemology.org' }, + { id: 2, name: 'Alpha', host: 'alpha.coursemology.org' }, + ], + }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + fireEvent.mouseDown(page.getByLabelText('Rule type')); + fireEvent.click( + page.getByRole('option', { name: 'All eligible users in an instance' }), + ); + await waitFor(() => + expect(mock.history.get.some((r) => r.url === '/admin/instances')).toBe( + true, + ), + ); + + expect(page.getByRole('button', { name: 'Next' })).toBeDisabled(); + + const combobox = await page.findByRole('combobox', { name: 'Instance' }); + fireEvent.mouseDown(combobox); + fireEvent.click(page.getByRole('option', { name: 'Alpha' })); + + expect(page.getByRole('button', { name: 'Next' })).toBeEnabled(); +}); + +it('keeps the Open to everyone toggle label on a single line', async () => { + // The open-state banner body is long enough to wrap, which used to drag the toggle label with it. + mock.onGet(INDEX_URL).reply(200, { rules: RULES, everyoneRuleId: 42 }); + + const page = render(, { at: [INDEX_URL] }); + + const label = await page.findByText(OPEN_TO_EVERYONE); + expect(label).toHaveClass('whitespace-nowrap'); +}); + +it('surfaces the server message when a rule is rejected as a duplicate', async () => { + mock.onGet(INDEX_URL).reply(200, { rules: [] }); + mock.onPost(PREVIEW_URL).reply(200, { + matchedCount: 1, + newCount: 1, + openToEveryone: false, + users: [], + }); + mock.onPost(INDEX_URL).reply(400, { + errors: 'Email domain already has the same rule.', + }); + + const page = render(, { at: [INDEX_URL] }); + await waitFor(() => expect(allowlistGetCount()).toBe(1)); + + fireEvent.click(page.getByText(ADD_ACCESS_RULE)); + await userEvent.type(page.getByLabelText(EMAIL_DOMAIN_SUBTITLE), NUS_DOMAIN); + fireEvent.click(page.getByRole('button', { name: 'Next' })); + await confirmAdd(page); + + // The specific message, not the generic "Failed to add access rule." + expect( + await page.findByText('Email domain already has the same rule.'), + ).toBeVisible(); +}); diff --git a/client/app/routers/courseless/systemAdmin.tsx b/client/app/routers/courseless/systemAdmin.tsx index 79edf10de6f..2e1bba29aac 100644 --- a/client/app/routers/courseless/systemAdmin.tsx +++ b/client/app/routers/courseless/systemAdmin.tsx @@ -67,6 +67,17 @@ const systemAdminRouter: Translated = (_) => ({ ).default, }), }, + { + path: 'marketplace_allowlist_rules', + lazy: async (): Promise> => ({ + Component: ( + await import( + /* webpackChunkName: 'MarketplaceAllowlistIndex' */ + 'bundles/system/admin/admin/pages/MarketplaceAllowlistIndex' + ) + ).default, + }), + }, { path: 'get_help', lazy: async (): Promise> => ({ diff --git a/client/app/types/system/marketplaceAccess.ts b/client/app/types/system/marketplaceAccess.ts new file mode 100644 index 00000000000..70949eb99a1 --- /dev/null +++ b/client/app/types/system/marketplaceAccess.ts @@ -0,0 +1,19 @@ +export interface MarketplaceRulePreviewUser { + id: number; + name: string; + email: string; + courseCount: number; + instanceRole: 'instructor' | 'administrator' | null; + alreadyHasAccess: boolean; + blocked: boolean; +} + +export interface AllowlistRulePreviewData { + matchedCount: number; + /** Matched users who are neither already cleared by another rule nor blocked. */ + newCount: number; + /** Matched users held back by an individual block, which a rule does not lift. */ + blockedCount: number; + openToEveryone: boolean; + users: MarketplaceRulePreviewUser[]; +} diff --git a/client/app/types/system/marketplaceAllowlist.ts b/client/app/types/system/marketplaceAllowlist.ts new file mode 100644 index 00000000000..bae03b1f717 --- /dev/null +++ b/client/app/types/system/marketplaceAllowlist.ts @@ -0,0 +1,19 @@ +export type AllowlistRuleType = 'user' | 'instance' | 'email_domain'; + +export interface AllowlistRuleData { + id: number; + ruleType: AllowlistRuleType; + userId: number | null; + userName: string | null; + userEmail: string | null; + instanceId: number | null; + instanceName: string | null; + emailDomain: string | null; +} + +export interface AllowlistRuleFormData { + ruleType: AllowlistRuleType; + email?: string; + instanceId?: number; + emailDomain?: string; +} diff --git a/client/locales/en.json b/client/locales/en.json index 0073cd7ca72..0638b06dfec 100644 --- a/client/locales/en.json +++ b/client/locales/en.json @@ -8780,6 +8780,9 @@ "system.admin.admin.AdminNavigator.getHelp": { "defaultMessage": "Get Help" }, + "system.admin.admin.AdminNavigator.marketplace": { + "defaultMessage": "Marketplace Access" + }, "system.admin.admin.AnnouncementsIndex.fetchAnnouncementsFailure": { "defaultMessage": "Unable to fetch announcements" }, @@ -8864,6 +8867,177 @@ "system.admin.admin.InstancesTable.updateSuccess": { "defaultMessage": "Renamed {field} from {prevValue} to {newValue}" }, + "system.admin.admin.MarketplaceAllowlistIndex.addRule": { + "defaultMessage": "Add access rule" + }, + "system.admin.admin.MarketplaceAllowlistIndex.eligibility": { + "defaultMessage": "Available to course managers & owners (of any course) and instance instructors & administrators (of any instance). They must also match one of the rules below." + }, + "system.admin.admin.MarketplaceAllowlistIndex.fetchFailure": { + "defaultMessage": "Failed to load marketplace access rules." + }, + "system.admin.admin.MarketplaceAllowlistIndex.createSuccess": { + "defaultMessage": "Access rule added." + }, + "system.admin.admin.MarketplaceAllowlistIndex.createFailure": { + "defaultMessage": "Failed to add access rule." + }, + "system.admin.admin.MarketplaceAllowlistIndex.deleteSuccess": { + "defaultMessage": "Access rule removed." + }, + "system.admin.admin.MarketplaceAllowlistIndex.deleteFailure": { + "defaultMessage": "Failed to remove access rule." + }, + "system.admin.admin.MarketplaceAllowlistIndex.openSuccess": { + "defaultMessage": "Marketplace opened to all course managers." + }, + "system.admin.admin.MarketplaceAllowlistIndex.openFailure": { + "defaultMessage": "Failed to open the marketplace to everyone." + }, + "system.admin.admin.MarketplaceAllowlistIndex.restrictSuccess": { + "defaultMessage": "Marketplace restricted to the scoped rules." + }, + "system.admin.admin.MarketplaceAllowlistIndex.restrictFailure": { + "defaultMessage": "Failed to restrict the marketplace." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.scopedTitle": { + "defaultMessage": "Access is limited to the rules below." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.everyoneTitle": { + "defaultMessage": "The marketplace is open to all eligible staff: course managers/owners and instance instructors/administrators. The rules below are preserved but inactive." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.toggleLabel": { + "defaultMessage": "Open to everyone" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmTitle": { + "defaultMessage": "Open marketplace to everyone?" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmBody": { + "defaultMessage": "This makes the marketplace visible to all eligible staff: course managers/owners and instance instructors/administrators. You can restrict it again at any time; your scoped rules are kept." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmTitle": { + "defaultMessage": "Restrict to scoped rules?" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmBody": { + "defaultMessage": "The marketplace will again be limited to the rules below. Eligible staff not covered by a rule will lose access." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.confirmOpen": { + "defaultMessage": "Open to everyone" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.confirmRestrict": { + "defaultMessage": "Restrict" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.title": { + "defaultMessage": "Add marketplace access rule" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.ruleType": { + "defaultMessage": "Rule type" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeUser": { + "defaultMessage": "Specific eligible user" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeInstance": { + "defaultMessage": "All eligible users in an instance" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeEmailDomain": { + "defaultMessage": "All eligible users with an email domain" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.userEmail": { + "defaultMessage": "Eligible user email" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.eligibilityHint": { + "defaultMessage": "Eligible users refer to course managers & owners (of any course) and instance instructors & administrators (of any instance)." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.instanceId": { + "defaultMessage": "Instance" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.emailDomain": { + "defaultMessage": "Email domain (e.g. schools.gov.sg)" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.next": { + "defaultMessage": "Next" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.back": { + "defaultMessage": "Back" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.confirmAdd": { + "defaultMessage": "Confirm add" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.counts": { + "defaultMessage": "Grants access to {matched, plural, one {# eligible user} other {# eligible users}}" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsOfMatched": { + "defaultMessage": "Grants access to {granted} of {matched, plural, one {# eligible user} other {# eligible users}}" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsExistingClause": { + "defaultMessage": "{existing} already had access" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsBlockedClause": { + "defaultMessage": "{blocked} blocked individually" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.noMatches": { + "defaultMessage": "This rule matches nobody eligible right now." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.openToEveryone": { + "defaultMessage": "The marketplace is currently open to everyone; this rule takes effect only if you restrict access again." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.previewFailure": { + "defaultMessage": "Could not preview this rule." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerNew": { + "defaultMessage": "New" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerExisting": { + "defaultMessage": "Already has access" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerBlocked": { + "defaultMessage": "Blocked" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.managesCourses": { + "defaultMessage": "Manages {count, plural, one {# course} other {# courses}}" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colName": { + "defaultMessage": "Name" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colEligibleVia": { + "defaultMessage": "Eligible via" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colStatus": { + "defaultMessage": "Status" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.searchPlaceholder": { + "defaultMessage": "Search by name or email" + }, + "system.admin.admin.MarketplaceAllowlistTable.colType": { + "defaultMessage": "Type" + }, + "system.admin.admin.MarketplaceAllowlistTable.colTarget": { + "defaultMessage": "Grants access to" + }, + "system.admin.admin.MarketplaceAllowlistTable.colActions": { + "defaultMessage": "Actions" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeUser": { + "defaultMessage": "User" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeInstance": { + "defaultMessage": "Instance" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeEmailDomain": { + "defaultMessage": "Email domain" + }, + "system.admin.admin.MarketplaceAllowlistTable.deleteConfirm": { + "defaultMessage": "Remove this marketplace access rule?" + }, + "system.admin.admin.MarketplaceAllowlistTable.emptyTitle": { + "defaultMessage": "No access rules yet" + }, + "system.admin.admin.MarketplaceAllowlistTable.emptyHint": { + "defaultMessage": "The marketplace stays hidden from everyone except system administrators. Add a rule to grant access." + }, + "system.admin.admin.MarketplaceAllowlistTable.zeroMatchWarning": { + "defaultMessage": "No eligible staff currently match this rule, so it grants access to nobody." + }, "system.admin.admin.UsersButton.deleteTooltip": { "defaultMessage": "Delete User" }, diff --git a/client/locales/ko.json b/client/locales/ko.json index a035bfb56b8..8127015525a 100644 --- a/client/locales/ko.json +++ b/client/locales/ko.json @@ -8747,6 +8747,9 @@ "system.admin.admin.AdminNavigator.getHelp": { "defaultMessage": "도움 받기" }, + "system.admin.admin.AdminNavigator.marketplace": { + "defaultMessage": "마켓플레이스 접근" + }, "system.admin.admin.AnnouncementsIndex.fetchAnnouncementsFailure": { "defaultMessage": "공지사항을 가져올 수 없습니다." }, @@ -8831,6 +8834,174 @@ "system.admin.admin.InstancesTable.updateSuccess": { "defaultMessage": "{field}이(가) {prevValue}에서 {newValue}로 변경되었습니다." }, + "system.admin.admin.MarketplaceAllowlistIndex.addRule": { + "defaultMessage": "접근 규칙 추가" + }, + "system.admin.admin.MarketplaceAllowlistIndex.eligibility": { + "defaultMessage": "모든 과정의 관리자 및 소유자, 그리고 모든 인스턴스의 강사 및 관리자가 사용할 수 있습니다. 단, 아래 규칙 중 하나와도 일치해야 합니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.fetchFailure": { + "defaultMessage": "마켓플레이스 접근 규칙을 불러오지 못했습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.createSuccess": { + "defaultMessage": "접근 규칙이 추가되었습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.createFailure": { + "defaultMessage": "접근 규칙 추가에 실패했습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.deleteSuccess": { + "defaultMessage": "접근 규칙이 제거되었습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.deleteFailure": { + "defaultMessage": "접근 규칙 제거에 실패했습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.openSuccess": { + "defaultMessage": "마켓플레이스가 모든 과정 관리자에게 공개되었습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.openFailure": { + "defaultMessage": "마켓플레이스를 모두에게 공개하지 못했습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.restrictSuccess": { + "defaultMessage": "마켓플레이스가 범위가 지정된 규칙으로 제한되었습니다." + }, + "system.admin.admin.MarketplaceAllowlistIndex.restrictFailure": { + "defaultMessage": "마켓플레이스를 제한하지 못했습니다." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.scopedTitle": { + "defaultMessage": "접근이 아래 규칙으로 제한됩니다." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.everyoneTitle": { + "defaultMessage": "마켓플레이스가 모든 자격 있는 직원(과정 관리자/소유자 및 인스턴스 강사/관리자)에게 열려 있습니다. 아래 규칙은 유지되지만 비활성 상태입니다." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.toggleLabel": { + "defaultMessage": "모두에게 공개" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmTitle": { + "defaultMessage": "마켓플레이스를 모두에게 공개하시겠습니까?" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmBody": { + "defaultMessage": "이렇게 하면 마켓플레이스가 모든 자격 있는 직원(과정 관리자/소유자 및 인스턴스 강사/관리자)에게 표시됩니다. 언제든지 다시 제한할 수 있으며, 범위가 지정된 규칙은 유지됩니다." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmTitle": { + "defaultMessage": "범위가 지정된 규칙으로 제한하시겠습니까?" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmBody": { + "defaultMessage": "마켓플레이스가 다시 아래 규칙으로 제한됩니다. 규칙에 해당하지 않는 자격 있는 직원은 접근 권한을 잃게 됩니다." + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.confirmOpen": { + "defaultMessage": "모두에게 공개" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.confirmRestrict": { + "defaultMessage": "제한" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.title": { + "defaultMessage": "마켓플레이스 접근 규칙 추가" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.ruleType": { + "defaultMessage": "규칙 유형" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeUser": { + "defaultMessage": "특정 자격 있는 직원" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeInstance": { + "defaultMessage": "인스턴스 내 모든 자격 있는 직원" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeEmailDomain": { + "defaultMessage": "특정 이메일 도메인의 모든 자격 있는 직원" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.userEmail": { + "defaultMessage": "자격 있는 직원 이메일" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.instanceId": { + "defaultMessage": "인스턴스" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.emailDomain": { + "defaultMessage": "이메일 도메인 (예: schools.gov.sg)" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.next": { + "defaultMessage": "다음" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.back": { + "defaultMessage": "뒤로" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.confirmAdd": { + "defaultMessage": "추가 확인" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.counts": { + "defaultMessage": "{matched}명의 자격 있는 직원에게 접근 권한을 부여합니다" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsOfMatched": { + "defaultMessage": "{matched}명의 자격 있는 직원 중 {granted}명에게 접근 권한을 부여합니다" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsExistingClause": { + "defaultMessage": "{existing}명은 이미 접근 권한이 있었습니다" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsBlockedClause": { + "defaultMessage": "{blocked}명은 개별적으로 차단되었습니다" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.noMatches": { + "defaultMessage": "현재 이 규칙과 일치하는 자격 있는 직원이 없습니다." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.openToEveryone": { + "defaultMessage": "마켓플레이스가 현재 모두에게 공개되어 있습니다. 이 규칙은 접근을 다시 제한할 경우에만 적용됩니다." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.previewFailure": { + "defaultMessage": "이 규칙을 미리 볼 수 없습니다." + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerNew": { + "defaultMessage": "신규" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerExisting": { + "defaultMessage": "이미 접근 권한 있음" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerBlocked": { + "defaultMessage": "차단됨" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.managesCourses": { + "defaultMessage": "{count, plural, one {#개 과정} other {#개 과정}} 관리" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colName": { + "defaultMessage": "이름" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colEligibleVia": { + "defaultMessage": "자격 경로" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colStatus": { + "defaultMessage": "상태" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.searchPlaceholder": { + "defaultMessage": "이름 또는 이메일로 검색" + }, + "system.admin.admin.MarketplaceAllowlistTable.colType": { + "defaultMessage": "유형" + }, + "system.admin.admin.MarketplaceAllowlistTable.colTarget": { + "defaultMessage": "접근 권한 대상" + }, + "system.admin.admin.MarketplaceAllowlistTable.colActions": { + "defaultMessage": "작업" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeUser": { + "defaultMessage": "사용자" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeInstance": { + "defaultMessage": "인스턴스" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeEmailDomain": { + "defaultMessage": "이메일 도메인" + }, + "system.admin.admin.MarketplaceAllowlistTable.deleteConfirm": { + "defaultMessage": "이 마켓플레이스 접근 규칙을 제거하시겠습니까?" + }, + "system.admin.admin.MarketplaceAllowlistTable.emptyTitle": { + "defaultMessage": "아직 접근 규칙이 없습니다" + }, + "system.admin.admin.MarketplaceAllowlistTable.emptyHint": { + "defaultMessage": "시스템 관리자를 제외한 모든 사용자에게 마켓플레이스가 숨겨진 상태로 유지됩니다. 규칙을 추가하여 접근 권한을 부여하세요." + }, + "system.admin.admin.MarketplaceAllowlistTable.zeroMatchWarning": { + "defaultMessage": "현재 이 규칙과 일치하는 자격 있는 직원이 없어 아무에게도 접근 권한이 부여되지 않습니다." + }, "system.admin.admin.UsersButton.deleteTooltip": { "defaultMessage": "사용자 삭제" }, diff --git a/client/locales/zh.json b/client/locales/zh.json index 62d7829973e..0b5e231c02b 100644 --- a/client/locales/zh.json +++ b/client/locales/zh.json @@ -8741,6 +8741,9 @@ "system.admin.admin.AdminNavigator.getHelp": { "defaultMessage": "获取帮助" }, + "system.admin.admin.AdminNavigator.marketplace": { + "defaultMessage": "市场访问" + }, "system.admin.admin.AnnouncementsIndex.fetchAnnouncementsFailure": { "defaultMessage": "无法获取公告" }, @@ -8825,6 +8828,174 @@ "system.admin.admin.InstancesTable.updateSuccess": { "defaultMessage": "已将 {field} 从 {prevValue} 重命名为 {newValue}" }, + "system.admin.admin.MarketplaceAllowlistIndex.addRule": { + "defaultMessage": "添加访问规则" + }, + "system.admin.admin.MarketplaceAllowlistIndex.eligibility": { + "defaultMessage": "任何课程的管理员及拥有者,以及任何实例的教师及管理员均可使用,但仍须匹配以下规则之一。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.fetchFailure": { + "defaultMessage": "加载市场访问规则失败。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.createSuccess": { + "defaultMessage": "访问规则已添加。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.createFailure": { + "defaultMessage": "添加访问规则失败。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.deleteSuccess": { + "defaultMessage": "访问规则已移除。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.deleteFailure": { + "defaultMessage": "移除访问规则失败。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.openSuccess": { + "defaultMessage": "市场已向所有课程管理员开放。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.openFailure": { + "defaultMessage": "未能将市场向所有人开放。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.restrictSuccess": { + "defaultMessage": "市场已限制为已设定范围的规则。" + }, + "system.admin.admin.MarketplaceAllowlistIndex.restrictFailure": { + "defaultMessage": "未能限制市场。" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.scopedTitle": { + "defaultMessage": "访问权限仅限于以下规则。" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.everyoneTitle": { + "defaultMessage": "市场目前向所有符合条件的职员开放:课程管理员/拥有者以及实例教师/管理员。以下规则会被保留,但暂不生效。" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.toggleLabel": { + "defaultMessage": "对所有人开放" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmTitle": { + "defaultMessage": "要将市场向所有人开放吗?" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.openConfirmBody": { + "defaultMessage": "这将使市场对所有符合条件的职员可见:课程管理员/拥有者以及实例教师/管理员。你可以随时重新限制访问,已设定范围的规则会被保留。" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmTitle": { + "defaultMessage": "要限制为已设定范围的规则吗?" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.restrictConfirmBody": { + "defaultMessage": "市场将再次仅限于以下规则。未被任何规则覆盖的符合条件职员将失去访问权限。" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.confirmOpen": { + "defaultMessage": "对所有人开放" + }, + "system.admin.admin.MarketplaceAllowlistModeBanner.confirmRestrict": { + "defaultMessage": "限制" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.title": { + "defaultMessage": "添加市场访问规则" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.ruleType": { + "defaultMessage": "规则类型" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeUser": { + "defaultMessage": "特定符合条件的职员" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeInstance": { + "defaultMessage": "某个实例中的所有符合条件职员" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.typeEmailDomain": { + "defaultMessage": "拥有特定邮箱域名的所有符合条件职员" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.userEmail": { + "defaultMessage": "符合条件职员的邮箱" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.instanceId": { + "defaultMessage": "实例" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.emailDomain": { + "defaultMessage": "邮箱域名(例如 schools.gov.sg)" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.next": { + "defaultMessage": "下一步" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.back": { + "defaultMessage": "返回" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.confirmAdd": { + "defaultMessage": "确认添加" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.counts": { + "defaultMessage": "为 {matched} 名符合条件的职员授予访问权限" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsOfMatched": { + "defaultMessage": "在 {matched} 名符合条件职员中,为 {granted} 名授予访问权限" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsExistingClause": { + "defaultMessage": "{existing} 人已拥有访问权限" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.countsBlockedClause": { + "defaultMessage": "{blocked} 人被单独屏蔽" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.noMatches": { + "defaultMessage": "此规则目前未匹配到任何符合条件的职员。" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.openToEveryone": { + "defaultMessage": "市场目前对所有人开放;此规则仅在你重新限制访问后才会生效。" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.previewFailure": { + "defaultMessage": "无法预览此规则。" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerNew": { + "defaultMessage": "新" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerExisting": { + "defaultMessage": "已拥有访问权限" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.markerBlocked": { + "defaultMessage": "已屏蔽" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.managesCourses": { + "defaultMessage": "管理 {count, plural, one {# 门课程} other {# 门课程}}" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colName": { + "defaultMessage": "姓名" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colEligibleVia": { + "defaultMessage": "资格来源" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.colStatus": { + "defaultMessage": "状态" + }, + "system.admin.admin.MarketplaceAllowlistRuleForm.searchPlaceholder": { + "defaultMessage": "按姓名或邮箱搜索" + }, + "system.admin.admin.MarketplaceAllowlistTable.colType": { + "defaultMessage": "类型" + }, + "system.admin.admin.MarketplaceAllowlistTable.colTarget": { + "defaultMessage": "授权对象" + }, + "system.admin.admin.MarketplaceAllowlistTable.colActions": { + "defaultMessage": "操作" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeUser": { + "defaultMessage": "用户" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeInstance": { + "defaultMessage": "实例" + }, + "system.admin.admin.MarketplaceAllowlistTable.typeEmailDomain": { + "defaultMessage": "邮箱域名" + }, + "system.admin.admin.MarketplaceAllowlistTable.deleteConfirm": { + "defaultMessage": "要移除此市场访问规则吗?" + }, + "system.admin.admin.MarketplaceAllowlistTable.emptyTitle": { + "defaultMessage": "尚无访问规则" + }, + "system.admin.admin.MarketplaceAllowlistTable.emptyHint": { + "defaultMessage": "除系统管理员外,市场对所有人保持隐藏。添加规则以授予访问权限。" + }, + "system.admin.admin.MarketplaceAllowlistTable.zeroMatchWarning": { + "defaultMessage": "目前没有符合条件的职员匹配此规则,因此不会授予任何人访问权限。" + }, "system.admin.admin.UsersButton.deleteTooltip": { "defaultMessage": "删除用户" }, diff --git a/spec/controllers/system/admin/marketplace_allowlist_rules_controller_spec.rb b/spec/controllers/system/admin/marketplace_allowlist_rules_controller_spec.rb index 4ef36f310c3..43272af08b1 100644 --- a/spec/controllers/system/admin/marketplace_allowlist_rules_controller_spec.rb +++ b/spec/controllers/system/admin/marketplace_allowlist_rules_controller_spec.rb @@ -278,7 +278,7 @@ def preview(params) expect(response).to have_http_status(:bad_request) # Attribute name omitted: StubbedI18nBackend returns the raw key for # `activerecord.attributes.*`, so full_messages can never render "Email domain" here. - expect(response.parsed_body['errors']).to include('already has a rule.') + expect(response.parsed_body['errors']).to include('already has the same rule.') end it 'denies a non-administrator' do diff --git a/spec/models/course/assessment/marketplace/allowlist_rule_spec.rb b/spec/models/course/assessment/marketplace/allowlist_rule_spec.rb index 17b37957f7c..4de6e87d06b 100644 --- a/spec/models/course/assessment/marketplace/allowlist_rule_spec.rb +++ b/spec/models/course/assessment/marketplace/allowlist_rule_spec.rb @@ -172,7 +172,7 @@ rule_type: :user, user: user) expect(duplicate).not_to be_valid - expect(duplicate.errors[:user_id]).to include('already has a rule.') + expect(duplicate.errors[:user_id]).to include('already has the same rule.') end it 'allows a user rule for a different user' do @@ -189,7 +189,7 @@ rule_type: :instance, instance: other_instance) expect(duplicate).not_to be_valid - expect(duplicate.errors[:instance_id]).to include('already has a rule.') + expect(duplicate.errors[:instance_id]).to include('already has the same rule.') end it 'rejects a second email-domain rule for the same domain' do @@ -199,7 +199,7 @@ rule_type: :email_domain, email_domain: 'dupes.test') expect(duplicate).not_to be_valid - expect(duplicate.errors[:email_domain]).to include('already has a rule.') + expect(duplicate.errors[:email_domain]).to include('already has the same rule.') end it 'treats a differently-cased domain as the same rule' do @@ -209,7 +209,7 @@ rule_type: :email_domain, email_domain: ' DUPES.TEST ') expect(duplicate).not_to be_valid - expect(duplicate.errors[:email_domain]).to include('already has a rule.') + expect(duplicate.errors[:email_domain]).to include('already has the same rule.') end it 'normalizes the stored domain to stripped lowercase' do @@ -220,7 +220,7 @@ # A user rule whose email resolves to nobody keeps user_id NULL, and Rails checks uniqueness # as `user_id IS NULL` — which matches every instance and email-domain rule unless the check - # is scoped to rule_type. Unscoped, the admin gets a bogus "already has a rule." stacked on + # is scoped to rule_type. Unscoped, the admin gets a bogus "already has the same rule." stacked on # top of the real reason. (Verified by mutation: dropping `scope: :rule_type` fails this.) it 'does not report a duplicate for an unresolvable email when other rule types exist' do create(:course_assessment_marketplace_allowlist_rule,