Skip to content
Draft
11 changes: 8 additions & 3 deletions src/common/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { SERVER_CONFIGS } from './serverConfigs';
import { legacyHashRoute, isSameSitePath } from './history';
import { resolveV3URL, resolveIntegratedV3URL } from './appUrls';
import { getAIAssistantUsage, keepAIAssistantUsage, refreshAIAssistantUsage } from './aiAssistantUsage';
import { getAvailableOwner } from '../components/common/ownerAccess';

export const currentPath = () => window.location.pathname;

Expand Down Expand Up @@ -1206,8 +1207,9 @@ export const toCamelCase = str => {
export const hasCapability = (user, capability) => Boolean((user || getCurrentUser())?.permissions?.includes(capability))

// `projectId`: the map project whose OCL AI Assistant report to include.
export const getMapperPreview = ({projectId} = {}) => {
const user = getCurrentUser()
// `user`: the signed-in person as they are on a map project (ownerAccess.js),
// else on their own.
export const getMapperPreview = ({projectId, user = getCurrentUser()} = {}) => {
const capabilities = user?.capabilities || []
const toMeter = key => {
const entry = capabilities.find(c => c.name === key) || {}
Expand Down Expand Up @@ -1237,10 +1239,13 @@ export const getMapperPreview = ({projectId} = {}) => {
}
}

export const getNewProjectBlockReason = (preview = getMapperPreview()) => {
// `projectOwners`: which organizations can own a new project of theirs, when
// the API says (ownerAccess.js). Their own projects don't matter for those.
export const getNewProjectBlockReason = (preview = getMapperPreview(), projectOwners = null) => {
if(isAdminUser())
return null
if(!preview.hasAccess) return 'access'
if(getAvailableOwner(projectOwners)) return null
const { projects } = preview
if(projects.limit === null || projects.limit === undefined) return 'projects_not_entitled'
if(!projects.unlimited && projects.remaining <= 0) return 'projects'
Expand Down
80 changes: 69 additions & 11 deletions src/components/common/NamespaceDropdown.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,102 @@ import ListItem from '@mui/material/ListItem'
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import InputAdornment from '@mui/material/InputAdornment';
import Box from '@mui/material/Box'
import Link from '@mui/material/Link'
import Tooltip from '@mui/material/Tooltip'
import useMediaQuery from '@mui/material/useMediaQuery'
import { visuallyHidden } from '@mui/utils'
import GlobalIcon from '@mui/icons-material/Language';
import filter from 'lodash/filter';
import { getCurrentUser, getCurrentUserOrgs } from '../../common/utils';
import UserIcon from '../users/UserIcon';
import OrgIcon from '../orgs/OrgIcon';
import { LockMark } from './NoticeLock'
import { withProjectOwners } from './ownerAccess'


const OwnerOption = ({ option, selected, ...rest }) => {
return (
<ListItem id={option.id} selected={selected} {...rest}>
<ListItemIcon sx={{minWidth: 'auto', marginRight: '16px'}}>
// An owner that can't be chosen is listed, locked, with why on hover, on tap and
// when the arrow keys reach it (`isReached`: the focus stays in the field). MUI
// turns a disabled option's pointer events off, which would stop the tooltip, so
// they're back on here and the option takes no click.
const OwnerOption = ({ option, selected, isReached, onClick, sx, ...rest }) => {
const { unavailable } = option
const { reason, link } = unavailable || {}
const isNarrow = useMediaQuery(theme => theme.breakpoints.down('md'))
const [isPointedAt, setIsPointedAt] = React.useState(false)
const item = (
<ListItem
id={option.id}
selected={selected}
{...rest}
onClick={unavailable ? undefined : onClick}
sx={unavailable ? {...sx, '&.MuiAutocomplete-option[aria-disabled="true"]': {opacity: 1, pointerEvents: 'auto', cursor: 'default'}} : sx}
>
<ListItemIcon sx={{minWidth: 'auto', marginRight: '16px', opacity: unavailable ? 0.38 : 1}}>
{option.icon}
</ListItemIcon>
<ListItemText primary={option.id} secondary={option.name} />
<ListItemText primary={option.id} secondary={option.name} sx={unavailable ? {opacity: 0.38, flex: '0 1 auto'} : undefined} />
{
unavailable &&
<Box component='span' sx={{display: 'inline-flex', fontSize: '16px', marginLeft: '8px'}}><LockMark /></Box>
}
{reason && <span style={visuallyHidden}>{reason}</span>}
</ListItem>
)
return reason ? (
<Tooltip
describeChild
open={isPointedAt || isReached}
onOpen={() => setIsPointedAt(true)}
onClose={() => setIsPointedAt(false)}
placement={isNarrow ? 'top-start' : 'right'}
enterTouchDelay={0}
leaveTouchDelay={6000}
title={
<React.Fragment>
{reason}
{
link &&
<Box component='span' sx={{display: 'block', marginTop: '4px'}}>
<Link href={link.url} target='_blank' rel='noopener noreferrer' color='inherit'>{link.label}</Link>
</Box>
}
</React.Fragment>
}
>
{item}
</Tooltip>
) : item
}


const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner, personalOnly, size, disabled, sx, helperText}) => {
// `orgAvailability` ({organization url: {available, reason, link}}): which of the
// person's organizations can be chosen. Each is listed, whatever
// `personalOnly` says; without it, `personalOnly` leaves them out.
const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner, personalOnly, orgAvailability, size, disabled, sx, helperText}) => {
const { t } = useTranslation()
const user = getCurrentUser()
const [ownerOptions, setOwnerOptions] = React.useState([])
const [reachedURL, setReachedURL] = React.useState(null)
const prepareOwnerOptions = () => {
const global = {url: '/', id: t('url_registry.global_registry'), type: '', name: t('url_registry.global_registry'), icon: <GlobalIcon />, group: '' }
let options = [
{url: user?.url, id: user?.username, type: user?.type, name: user?.username, icon: <UserIcon authenticated user={user} logoClassName='user-img-xsmall' />, group: ''},
]
if(!asOwner)
options = [global, ...options]
if(!personalOnly) {
getCurrentUserOrgs().forEach(org => {
options.push({url: org.url, id: org.id, type: org.type, name: org.name, icon: <OrgIcon noLink strict logoClassName='user-img-xsmall' org={org} />, group: t('org.my')})
if(orgAvailability || !personalOnly) {
withProjectOwners(getCurrentUserOrgs(), orgAvailability).forEach(org => {
const unavailable = orgAvailability && !orgAvailability[org.url]?.available ? (orgAvailability[org.url] || {}) : null
options.push({url: org.url, id: org.id, type: org.type, name: org.name, icon: <OrgIcon noLink strict logoClassName='user-img-xsmall' org={org} />, group: t('org.my'), unavailable})
})
}
setOwnerOptions(options)
}

React.useEffect(() => {
prepareOwnerOptions()
}, [personalOnly, asOwner])
}, [personalOnly, orgAvailability, asOwner])

const filterOptions = (options, { inputValue }) => inputValue ? filter(options, option => option.id.toLowerCase().includes(inputValue.toLowerCase()) || option.name.toLowerCase().includes(inputValue.toLowerCase())) : options;
const selectedOption = ownerOptions.find(value => value?.url === owner) || ''
Expand All @@ -61,10 +116,13 @@ const NamespaceDropdown = ({onChange, label, id, owner, backgroundColor, asOwner
blurOnSelect
id={id}
options={ownerOptions}
getOptionDisabled={option => Boolean(option.unavailable)}
disabledItemsFocusable
onHighlightChange={(event, option, reason) => setReachedURL(reason === 'keyboard' && option ? option.url : null)}
value={selectedOption}
groupBy={option => option.group}
getOptionLabel={option => option.id || ''}
renderOption={(props, option, { selected }) => <OwnerOption key={option.id} option={option} dense={size === 'small'} {...props} selected={selected} />}
renderOption={(props, option, { selected }) => <OwnerOption key={option.id} option={option} dense={size === 'small'} {...props} selected={selected} isReached={Boolean(option.url) && option.url === reachedURL} />}
onChange={onChange}
renderInput={
params => {
Expand Down
89 changes: 89 additions & 0 deletions src/components/common/__tests__/ownerAccess.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import test from 'node:test'
import assert from 'node:assert/strict'

const {
getAvailableOwner, getOwnerAccessRequest, getProjectOwnersRequest, toOwnerAccess, toProjectOwners,
withOwnerAccess, withProjectOwners,
} = await import('../ownerAccess.js')

const API = {baseURL: 'https://api.example.org/', token: 'personal-token'}
const headers = {Authorization: 'Token personal-token'}

test('asks about an organization\'s content, never a person\'s', () => {
assert.deepEqual(getOwnerAccessRequest({...API, owner: '/orgs/Example/'}), {
url: 'https://api.example.org/capabilities/orgs/Example/', params: undefined, headers,
})
for(const owner of ['/users/someone/', '/orgs/Example/sources/', '/orgs//', '', null, undefined])
assert.equal(getOwnerAccessRequest({...API, owner}), null, owner)
assert.equal(getOwnerAccessRequest({...API, token: '', owner: '/orgs/Example/'}), null)
assert.equal(getOwnerAccessRequest({...API, baseURL: '', owner: '/orgs/Example/'}), null)
})

test('the person has what the API says on that content, and stays themselves', () => {
const user = {username: 'someone', url: '/users/someone/', auth_groups: ['a'], capabilities: [{name: 'x', limit: 1}], permissions: ['p']}
const access = toOwnerAccess({capabilities: [{name: 'x', limit: 15}], permissions: ['p', 'q'], other: 1})
assert.deepEqual(withOwnerAccess(user, access, true), {
...user, capabilities: [{name: 'x', limit: 15}], permissions: ['p', 'q'], ownerAccess: access
})
for(const none of [null, undefined])
assert.equal(withOwnerAccess(user, none, true), user)
assert.equal(withOwnerAccess(null, access, true), null)
})

test('until the project is saved, what its requests use is the person\'s own', () => {
const own = [{name: 'mapper.match_operations', limit: 100}, {name: 'ai_assistant.calls', limit: 5}, {name: 'mapper.rows_per_project', limit: 25}]
const owners = [{name: 'mapper.match_operations', limit: 1250}, {name: 'mapper.rows_per_project', limit: 2000}]
const access = {capabilities: owners, permissions: []}
const limits = user => Object.fromEntries(user.capabilities.map(({ name, limit }) => [name, limit]))
assert.deepEqual(limits(withOwnerAccess({capabilities: own}, access, false)), {
'mapper.rows_per_project': 2000, 'mapper.match_operations': 100, 'ai_assistant.calls': 5
})
assert.deepEqual(limits(withOwnerAccess({}, access, false)), {'mapper.rows_per_project': 2000})
assert.deepEqual(limits(withOwnerAccess({capabilities: own}, access, true)), {
'mapper.rows_per_project': 2000, 'mapper.match_operations': 1250
})
})

test('only a whole answer counts', () => {
for(const data of [null, undefined, '', 'text', [], {}, {capabilities: []}, {permissions: []}, {capabilities: {}, permissions: []}])
assert.equal(toOwnerAccess(data), null, JSON.stringify(data))
})

test('asks which organizations can own a new project, in the UI language', () => {
assert.deepEqual(getProjectOwnersRequest({...API, lang: 'pt-BR'}), {
url: 'https://api.example.org/capabilities/mapper.projects/owners/', params: {lang: 'pt-BR'}, headers,
})
assert.equal(getProjectOwnersRequest({...API, token: ''}), null)
})

test('an organization is available only when the API says so, and the reason is the API\'s', () => {
const link = {label: 'Read more', url: 'https://example.org/more'}
assert.deepEqual(toProjectOwners({owners: {
'/orgs/A/': {available: true, reason: 'x', link},
'/orgs/B/': {available: false, reason: ' Not this one ', link},
'/orgs/C/': {available: 'yes', reason: 3, link: {label: 'Bad', url: 'javascript:alert(1)'}},
'/orgs/D/': null,
'/users/someone/': {available: true},
}}), {
'/orgs/A/': {available: true, reason: null, link: null},
'/orgs/B/': {available: false, reason: 'Not this one', link},
'/orgs/C/': {available: false, reason: null, link: null},
'/orgs/D/': {available: false, reason: null, link: null},
})
for(const data of [null, undefined, 'text', {}, {owners: null}, {owners: []}])
assert.equal(toProjectOwners(data), null, JSON.stringify(data))
})

test('the first organization that can own one', () => {
assert.equal(getAvailableOwner({'/orgs/A/': {available: false}, '/orgs/B/': {available: true}, '/orgs/C/': {available: true}}), '/orgs/B/')
for(const owners of [null, undefined, {}, {'/orgs/A/': {available: false}}])
assert.equal(getAvailableOwner(owners), null)
})

test('an organization joined since signing in is listed too', () => {
const orgs = [{url: '/orgs/A/', id: 'A', name: 'First'}]
assert.deepEqual(withProjectOwners(orgs, {'/orgs/A/': {available: true}, '/orgs/B/': {available: true}}), [
...orgs, {url: '/orgs/B/', id: 'B', name: 'B', type: 'Organization'}
])
assert.deepEqual(withProjectOwners(orgs, undefined), orgs)
})
79 changes: 79 additions & 0 deletions src/components/common/ownerAccess.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// What the API may say about who owns a map project (OpenConceptLab/ocl_online#654,
// #716): what the signed-in person can use on an organization's content, and
// which of their organizations can own a new map project. Open code uses only
// what it's sent. An API without these routes sends nothing, and the person's
// own limits and permissions then apply everywhere.
const ORG_URL = /^\/orgs\/[^/]+\/$/

const toRequest = (baseURL, token, path, params) => baseURL && token ? {
url: `${baseURL.replace(/\/+$/, '')}/capabilities${path}`,
params,
headers: {Authorization: `Token ${token}`},
} : null

// A person's own content goes by their own user detail, so only an
// organization's is asked about.
export const isAskedAbout = owner => ORG_URL.test(owner || '')

export const getOwnerAccessRequest = ({baseURL, token, owner}) =>
isAskedAbout(owner) ? toRequest(baseURL, token, owner) : null

// `capabilities` and `permissions` as the user detail gives a person's own.
// Only a whole answer counts.
export const toOwnerAccess = data =>
Array.isArray(data?.capabilities) && Array.isArray(data?.permissions) ? data : null

// What a request uses counts as the person's own until the project is saved:
// before that, no request can name it.
const COUNTED_BY_REQUEST = ['mapper.match_operations', 'ai_assistant.calls']
const isCounted = ({ name }) => COUNTED_BY_REQUEST.includes(name)

// The person as they are on that content. `ownerAccess` is the API's whole
// answer, for the checkpoints (autoMatchCheck.js).
export const withOwnerAccess = (user, ownerAccess, isSaved) => user && ownerAccess ? {
...user,
capabilities: isSaved ?
ownerAccess.capabilities :
[...ownerAccess.capabilities.filter(item => !isCounted(item)), ...(user.capabilities || []).filter(isCounted)],
permissions: ownerAccess.permissions,
ownerAccess
} : user

export const getProjectOwnersRequest = ({baseURL, token, lang}) =>
toRequest(baseURL, token, '/mapper.projects/owners/', {lang})

const toText = value => typeof value === 'string' && value.trim() ? value.trim() : null

// Only an http(s) link with a label is shown.
const toLink = link => {
const label = toText(link?.label)
return label && /^https?:\/\//.test(link.url) ? {label, url: link.url} : null
}

// {organization url: {available, reason, link}}. `reason` and `link` say why one
// that isn't available can't be chosen, and where to read more.
export const toProjectOwners = data => {
const owners = data?.owners
if(!owners || typeof owners !== 'object' || Array.isArray(owners))
return null
return Object.fromEntries(Object.entries(owners).filter(([url]) => isAskedAbout(url)).map(([url, owner]) => {
const available = owner?.available === true
return [url, {available, reason: available ? null : toText(owner?.reason), link: available ? null : toLink(owner?.link)}]
}))
}

// The signed-in person's organizations, as they were when they signed in, and
// any the answer has that they joined since.
export const withProjectOwners = (orgs, owners) => {
const known = new Set(orgs.map(({ url }) => url))
return [
...orgs,
...Object.keys(owners || {}).filter(url => !known.has(url)).map(url => {
const id = url.split('/')[2]
return {url, id, name: id, type: 'Organization'}
})
]
}

export const getAvailableOwner = owners =>
Object.keys(owners || {}).find(url => owners[url].available) || null
55 changes: 55 additions & 0 deletions src/components/common/useOwnerAccess.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React from 'react'
import axios from 'axios'
import { useTranslation } from 'react-i18next'

import { currentUserToken, getAPIURL } from '../../common/utils'
import { getOwnerAccessRequest, getProjectOwnersRequest, isAskedAbout, toOwnerAccess, toProjectOwners } from './ownerAccess'

// The API's answer for `key`: undefined while it's being asked, null when there
// is nothing to ask or the API gives none. A new `version` asks again and keeps
// the last answer until the next, also when asking fails. axios directly, not
// APIService, so a missing route or a refusal skips its sign-out and throttling
// handling.
const useAnswer = (key, request, toAnswer, version) => {
const [state, setState] = React.useState({key: null, answer: null})
React.useEffect(() => {
if(!key)
return undefined
// only the latest request's reply
let current = true
const keepOr = answer => current && setState(prev => answer || prev.key !== key ? {key, answer} : prev)
if(request)
axios.get(request.url, {params: request.params, headers: request.headers, timeout: 10000})
.then(response => keepOr(toAnswer(response.data)))
.catch(() => keepOr(null))
else
keepOr(null)
return () => {
current = false
}
}, [key, version])

if(!key)
return null
return state.key === key ? state.answer : undefined
}

// What the person can use on `owner`'s content, or null when it's their own
// that applies (ownerAccess.js).
export const useOwnerAccess = (owner, version) => useAnswer(
isAskedAbout(owner) ? owner : null,
getOwnerAccessRequest({baseURL: getAPIURL(), token: currentUserToken(), owner}),
toOwnerAccess,
version
)

// Which of the person's organizations can own a new map project of theirs.
export const useProjectOwners = version => {
const { i18n } = useTranslation()
return useAnswer(
i18n.language,
getProjectOwnersRequest({baseURL: getAPIURL(), token: currentUserToken(), lang: i18n.language}),
toProjectOwners,
version
)
}
Loading
Loading