diff --git a/src/components/map-projects/ConfigurationForm.jsx b/src/components/map-projects/ConfigurationForm.jsx index 7c0fd0e7..72794e3d 100644 --- a/src/components/map-projects/ConfigurationForm.jsx +++ b/src/components/map-projects/ConfigurationForm.jsx @@ -75,7 +75,7 @@ const getSuggestedRepos = () => (window.REPO_SUGGESTIONS || process.env.REPO_SUG .filter(([owner, id]) => owner && id) .map(([owner, id]) => ({id, short_code: id, name: id, owner, ownerType: 'Organization', type: 'Source', url: `/orgs/${owner}/sources/${id}/`})) -const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showTargetRepoVersionError, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => { +const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, name, setName, description, setDescription, repo, onRepoChange, repoVersion, setRepoVersion, showRequiredErrors, versions, mappedSources, targetSourcesFromRows, algosSelected, setAlgosSelected, sx, algos, validColumns, columns, isValidColumnValue, updateColumn, configure, setConfigure, columnVisibilityModel, setColumnVisibilityModel, onSave, isSaving, candidatesScore, onScoreChange, includeDefaultFilter, setIncludeDefaultFilter, filters, setFilters, locales, setAIAssistantColumns, AIAssistantColumns, inAIAssistantGroup, lookupConfig, setLookupConfig, encoderModel, setEncoderModel, isCoreUser, requestLimits, canSelectAIModel, canSetAIOutputLocale, canBridge, canScispacy, canUseOrgProjects=true, canUseCustomAlgorithms=true, promptTemplates, promptTemplate, onPromptTemplateChange, AIModels, AIModel, setAIModel, namespace, setNamespace, promptOutputLocale, setPromptOutputLocale, inputLocale, setInputLocale, oclLocales, useLexicalVariants, setUseLexicalVariants }) => { const { t } = useTranslation(); // A read-only project's settings are shown, not changed: every field that // changes them is disabled (OpenConceptLab/ocl_online#424). @@ -135,7 +135,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n const configErrors = getProjectConfigErrors(algosSelected) const hasConfigErrors = configErrors.length > 0 const hasTargetRepoVersion = hasSelectedTargetRepoVersion(repoVersion) - const isTargetRepoVersionInError = Boolean(showTargetRepoVersionError && !hasTargetRepoVersion) + const isTargetRepoVersionInError = Boolean(showRequiredErrors && !hasTargetRepoVersion) const getAlgos = () => getPreviewAlgorithmOptions({ algos, algosSelected, @@ -186,6 +186,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n disabled={locked} sx={{marginTop: '12px'}} label={t('common.name')} + error={Boolean(showRequiredErrors && !name?.trim())} value={name} onChange={event => setName(event.target.value || '')} /> @@ -221,10 +222,11 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n disabled={locked || Boolean(project?.id && project.input_file_name)} > { - file?.name ? file.name : t('map_project.upload_file') + file?.name ? file.name : <>{t('map_project.upload_file')} } @@ -273,7 +275,7 @@ const ConfigurationForm = ({ project, handleFileUpload, file, owner, setOwner, n - onRepoChange(item)} value={repo} suggested={getSuggestedRepos()} sx={{marginTop: '12px'}} disabled={locked}/> + onRepoChange(item)} value={repo} suggested={getSuggestedRepos()} sx={{marginTop: '12px'}} disabled={locked} error={isTargetRepoVersionInError && !repo?.url}/> : } onClick={onSave} - disabled={locked || !name || !file?.name || !owner || hasConfigErrors || hasAccessErrors} + disabled={locked || hasConfigErrors || hasAccessErrors} loading={isSaving} loadingPosition="start" > diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 5db29a09..9a9ae16f 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -49,7 +49,6 @@ import chunk from 'lodash/chunk' import get from 'lodash/get' import omit from 'lodash/omit' import omitBy from 'lodash/omitBy' -import reject from 'lodash/reject' import uniq from 'lodash/uniq' import compact from 'lodash/compact' import keyBy from 'lodash/keyBy' @@ -85,7 +84,7 @@ import { buildPanelPayload } from './openConceptPanel' import LoaderDialog from '../common/LoaderDialog' import Error403 from '../errors/Error403' import { HEADERS, SEMANTIC_SEARCH_HEADERS, ROW_STATES, VIEWS, DECISION_TABS, ROW_STAGES, PROMPTS_KEY_DEFAULT, PROMPTS_ACTION_TYPE_DEFAULT, SCORES_COLOR } from './constants' -import { updateColumnState, resuggestColumns, applyTemplateColumns } from './columnSuggestions' +import { updateColumnState, resuggestColumns, applyTemplateColumns, getMissingColumns } from './columnSuggestions' import MapProjectDeleteConfirmDialog from './MapProjectDeleteConfirmDialog'; import ConfigurationForm from './ConfigurationForm' import Controls from './Controls' @@ -95,6 +94,7 @@ import { aiOnByDefault, getMaxRunRows, getMapperSettings } from '@openconceptlab import { createAutosaveScheduler, createLatestSender, isToldOnLeave, recordReadOnlyRefusal, saveOnLeave, sendAfter, trackSave, whenSaved, installUnloadGuard, SAVE_SKIPPED } from './autosave' import { blockLeaving, continueLeaving, createEditTracker, createRunClosers, getRunLeaveMessageKey, isUnsavedNewProject, shouldAskBeforeLeaving, shouldWarnBeforeUnload } from './leaveGuard' import { editProposed, getColumnsSnapshot } from './unsavedEdits' +import { getAlgosForRelease, toSelectedAlgo } from './selectedAlgos' import MatchSummaryCard from './MatchSummaryCard' import MappingDecisionResult from './MappingDecisionResult' import DecisionSelector from './DecisionSelector' @@ -233,6 +233,9 @@ const MapProject = () => { const [appliedFacets, setAppliedFacets] = React.useState({}); const [searchResponse, setSearchResponse] = React.useState({}); const [algosSelected, setAlgosSelected] = React.useState([]) + // Once the algorithms are someone's choice, OCL Semantic is no longer selected by + // default (OpenConceptLab/ocl_online#841). A saved or copied project's already are. + const algosChosenRef = React.useRef(Boolean(params.projectId || templateFromProjectURL)) const [notes, setNotes] = React.useState({}) const [mapTypes, setMapTypes] = React.useState({}) const [proposed, setProposed] = React.useState({}) @@ -548,8 +551,9 @@ const MapProject = () => { // repo state const [repo, setRepo] = React.useState(false) const [repoVersion, setRepoVersion] = React.useState(false) - // Version shows its error only after a save without one. - const [showTargetRepoVersionError, setShowTargetRepoVersionError] = React.useState(false) + // A required field that's empty shows its error after a save it refused, + // until a save goes through. + const [showRequiredErrors, setShowRequiredErrors] = React.useState(false) const [mappedSources, setMappedSources] = React.useState([]) const [bridgeMappedSources, setBridgeMappedSources] = React.useState({}) // One read of each version's list, shared by the target and the bridge probe. @@ -1773,25 +1777,44 @@ const MapProject = () => { }) } + // What's missing for a save, in the form's order, as the messages it's + // refused with (OpenConceptLab/ocl_online#841). A save needs the version, not + // the repository's details, so Repository counts only when the version is + // missing too. + const getMissingRequired = isVersionMissing => { + const fields = compact([ + !owner && t('map_project.project_owner'), + !name?.trim() && t('common.name'), + !file?.name && t('map_project.upload_file'), + isVersionMissing && !repo?.url && t('map_project.repository'), + isVersionMissing && t('common.version') + ]) + const missingColumns = file?.name ? getMissingColumns(columns) : [] + return compact([ + fields.length && t('map_project.missing_required_field', {count: fields.length, names: fields.join(', ')}), + missingColumns.length && t('map_project.missing_required_column_mapping', {names: missingColumns.join(', ')}) + ]) + } + const onSave = (options = {}) => { const isAutoSave = options.source === 'auto' if(isAutoSave && (!project?.id || readOnlyRef.current)) return - if(!isAutoSave) - autosaveSchedulerRef.current.cancel() - if(!repoVersion?.version_url || !selectedTargetRepoVersion) { + // Only a missing version refuses an autosave, and a saved project keeps its + // work whatever else its settings lack. A refusal names all that's missing. + const isVersionMissing = !repoVersion?.version_url || !selectedTargetRepoVersion + const errors = getMissingRequired(isVersionMissing) + if(isVersionMissing || (!isAutoSave && errors.length)) { setConfigure(true) - setShowTargetRepoVersionError(true) - setAlert({ - message: t( - 'map_project.target_repo_version_required', - 'Select a target repository version before saving.' - ), - severity: 'error', - duration: 8 - }) + setShowRequiredErrors(true) + setAlert({message: errors.join(' '), severity: 'error', duration: 8, isRefusedSave: true}) return } + // After the checks, so a refused save leaves a pending autosave to run. + if(!isAutoSave) { + autosaveSchedulerRef.current.cancel() + setAlert(prev => prev?.isRefusedSave ? false : prev) + } const rowLogsForSave = options.logs || logsRef.current const projectLogsForSave = options.projectLogs || projectLogsRef.current const editsInSave = editTrackerRef.current.saving() @@ -1882,6 +1905,7 @@ const MapProject = () => { const status = response?.response?.status || response?.status const errorData = response?.response?.data || (response?.data?.id ? null : response?.data) if(response?.data?.id) { + setShowRequiredErrors(false) const saveLog = { action: isAutoSave ? 'Auto Saved' : (isUpdate ? 'Updated' : 'Created'), description: isAutoSave ? t('map_project.auto_saved_changes') : undefined, @@ -2325,30 +2349,34 @@ const MapProject = () => { }) } - const onRepoVersionChange = version => { + const onRepoVersionChange = (version, isRestored=false) => { setRepoVersion(version || false) - setShowTargetRepoVersionError(false) // A slower read of an earlier version doesn't overwrite this one's list. stopTargetMappedSourcesRef.current() stopTargetMappedSourcesRef.current = () => {} if(version?.version_url) { setLocales(getDeclaredLocales(version)) stopTargetMappedSourcesRef.current = readMappedSources(version.version_url, setMappedSources) - updateAlgosByRepoVersion(version) + updateAlgosByRepoVersion(version, isRestored) } else { setMappedSources([]) setLocales([]) } } - const updateAlgosByRepoVersion = version => { - const isLLMAlgoAllowed = version?.match_algorithms?.includes('llm') - const index = algos.findIndex(algo => algo.type === 'ocl-semantic') - if(index > -1) { - if(find(algosSelected, {type: 'ocl-semantic'}) && !isLLMAlgoAllowed) { - setAlgosSelected(reject(algosSelected, {type: 'ocl-semantic'})) - } - } + // The versions can load after the algorithms change, so this works on the + // list as it is then. + const updateAlgosByRepoVersion = (version, isRestored) => { + const defaultAlgo = algosChosenRef.current || projectIdRef.current ? null : + toSelectedAlgo(find(algos, {type: 'ocl-semantic'}), requestLimits) + setAlgosSelected(prev => getAlgosForRelease(prev, version, {defaultAlgo, isRestored})) + } + + // The form's changes: only adding or removing an algorithm changes how many there are. + const onAlgosSelectedChange = next => { + if(Array.isArray(next) && next.length !== algosSelected.length) + algosChosenRef.current = true + setAlgosSelected(next) } const getFilters = () => { @@ -3225,7 +3253,10 @@ const MapProject = () => { setVersions(fetchedVersions || []) setVersionsStatus(fetchedVersions ? null : 'failed') noteTargetReadThrottle(response) - onRepoVersionChange(savedVersion === undefined ? getDefaultTargetRepoVersion(fetchedVersions) : getSavedTargetRepoVersion(fetchedVersions, savedVersion)) + if(savedVersion === undefined) + onRepoVersionChange(getDefaultTargetRepoVersion(fetchedVersions)) + else + onRepoVersionChange(getSavedTargetRepoVersion(fetchedVersions, savedVersion), true) }) } @@ -3338,6 +3369,11 @@ const MapProject = () => { event.stopPropagation() event.preventDefault() setAutoMatchScope(getSelectedRowIndexes().length ? 'selected' : (rowStatuses.unmapped.length ? 'unmapped' : 'all')) + applyAutoMatchAIDefault() + setMatchDialog(true) + } + + const applyAutoMatchAIDefault = () => { if(inAIAssistantGroup) { const { runAI, applied } = getAutoMatchAIOnOpen({ current: autoRunAIAnalysis, @@ -3349,7 +3385,19 @@ const MapProject = () => { autoMatchAIDefaultAppliedRef.current = applied setAutoRunAIAnalysis(runAI) } - setMatchDialog(true) + } + + // The project's logs, and the user's access to the OCL AI Assistant, can load + // after the dialog opened. The box takes its default then, unless the user + // has already changed it. + React.useEffect(() => { + if(matchDialog && !autoMatchAIDefaultAppliedRef.current) + applyAutoMatchAIDefault() + }, [projectLogs, inAIAssistantGroup]) + + const onAutoRunAIAnalysisChange = runAI => { + autoMatchAIDefaultAppliedRef.current = true + setAutoRunAIAnalysis(runAI) } const onAutoMatchConfigure = () => { @@ -6500,13 +6548,13 @@ const MapProject = () => { onRepoChange={onRepoChange} repoVersion={repoVersion} setRepoVersion={onRepoVersionChange} - showTargetRepoVersionError={showTargetRepoVersionError} + showRequiredErrors={showRequiredErrors} mappedSources={mappedSources} targetSourcesFromRows={targetSourcesFromRows} versions={versions} algos={algos} algosSelected={algosSelected} - setAlgosSelected={setAlgosSelected} + setAlgosSelected={onAlgosSelectedChange} validColumns={headers} columns={columns} isValidColumnValue={isValidColumnValue} @@ -6611,6 +6659,30 @@ const MapProject = () => { loadingProject && } + + setAlert(false)} + > + + + } + sx={{ width: '100%' }} + > + {alert?.message} + + { onSearchTextChange={setSearchText} searchValue={headerRowSearch} /> - - setAlert(false)} - > - - - } - sx={{ width: '100%' }} - > - {alert?.message} - -
{ setAutoMatchScope, selectedRowCount: selectedRowsCount, autoRunAIAnalysis, - setAutoRunAIAnalysis, + setAutoRunAIAnalysis: onAutoRunAIAnalysisChange, AIModels, AIModel, setAIModel, diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index 4ccd009f..80fa940f 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -41,7 +41,7 @@ import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } fr import { getRequestLimits, getRequestSettings } from './requestLimits' import { dropVersion } from '../../common/utils' import { LockedFields, useEditLock } from '../common/NoticeLock' -import { patchSelected, customCheckReply } from './selectedAlgos' +import { patchSelected, customCheckReply, toSelectedAlgo } from './selectedAlgos' import { applyBridgeCanonical, getDefaultBridgeRepoVersion, @@ -357,14 +357,7 @@ export default function MultiAlgoSelector({ id = `${id}-1` name = `${name}-1` } - const defaults = { - ...omit(algo, ['getIcon', 'disabled', 'description', 'url']), - id: id, - name: name, - batch_size: getRequestSettings(algo, requestLimits).batchSize, - concurrent_requests: getRequestSettings(algo, requestLimits).concurrentRequests, - __key: Math.random(100).toString() - }; + const defaults = {...toSelectedAlgo(algo, requestLimits), id, name}; commitValue([...(latestValueRef.current || []), defaults]); setExpanded((prev) => { diff --git a/src/components/map-projects/__tests__/columnSuggestions.test.js b/src/components/map-projects/__tests__/columnSuggestions.test.js index 6b23610c..ac58223c 100644 --- a/src/components/map-projects/__tests__/columnSuggestions.test.js +++ b/src/components/map-projects/__tests__/columnSuggestions.test.js @@ -7,7 +7,7 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { suggestColumnLabels, isCodeLikeHeader, updateColumnState, resuggestColumns, applyTemplateColumns } from '../columnSuggestions.js' +import { suggestColumnLabels, isCodeLikeHeader, updateColumnState, resuggestColumns, applyTemplateColumns, getMissingColumns } from '../columnSuggestions.js' const BASE = [ {label: 'ID'}, @@ -35,6 +35,35 @@ test('suggestColumnLabels: Name goes to the strongest header, not the first', () ) }) +test('suggestColumnLabels: clinical headers suggest Name (OpenConceptLab/ocl_online#841)', () => { + const headers = ['Diagnosis', 'Diagnoses', 'Procedure', 'Drug', 'Medication', 'Condition', 'Primary diagnosis', 'generic_drug'] + headers.forEach(header => assert.deepEqual(suggestColumnLabels([header], BASE), ['Name'], header)) + assert.deepEqual(suggestColumnLabels(['Local Code', 'Diagnosis', 'Group'], BASE), [null, 'Name', null]) +}) + +test('suggestColumnLabels: a clinical word that only describes another one suggests nothing', () => { + const headers = [ + 'Diagnosis Date', 'Drug Dose', 'Procedure Code', 'Medication Route', 'Drug class', 'Conditional', + 'Year of diagnosis', 'Age at Diagnosis', 'Reason for procedure', 'Number of drugs', 'Code/ID - Diagnosis' + ] + headers.forEach(header => assert.deepEqual(suggestColumnLabels([header], BASE), [null], header)) + assert.deepEqual(suggestColumnLabels(['Description of diagnosis'], BASE), ['Name']) +}) + +test('suggestColumnLabels: a date column never takes Name from the column that holds names', () => { + assert.deepEqual(suggestColumnLabels(['Test Date', 'Date of Diagnosis', 'Diagnosis'], BASE), [null, null, 'Name']) + const dates = ['Test Date/Time', 'Test (Date/Time)', 'Test (date)', 'Test datetime'] + dates.forEach(header => assert.deepEqual(suggestColumnLabels([header, 'Diagnosis'], BASE), [null, 'Name'], header)) + assert.deepEqual(suggestColumnLabels(['Test update'], BASE), ['Name']) + assert.deepEqual(suggestColumnLabels(['Test Date', 'Diagnosis_Date'], BASE), [null, null]) +}) + +test('suggestColumnLabels: a clinical word only takes Name when no other header has one of the general words', () => { + assert.deepEqual(suggestColumnLabels(['Drug', 'Drug Name'], BASE), [null, 'Name']) + assert.deepEqual(suggestColumnLabels(['Diagnosis', 'Diagnosis Description'], BASE), [null, 'Name']) + assert.deepEqual(suggestColumnLabels(['Drug Name/Strength', 'Generic Drug Name'], BASE), [null, 'Name']) +}) + test('suggestColumnLabels: exact matches are left alone', () => { assert.deepEqual(suggestColumnLabels(['Name', 'Description'], BASE), [null, null]) }) @@ -182,3 +211,19 @@ test('applyTemplateColumns leaves unmatched columns as suggestions and ignores a assert.equal(applyTemplateColumns(uploaded, []), uploaded) assert.deepEqual(applyTemplateColumns(uploaded, [{label: 'Name', original: 'Component'}]), uploaded) }) + +test('getMissingColumns: a save needs a column mapped to Name', () => { + const missing = headers => getMissingColumns(upload(headers)) + assert.deepEqual(missing(['Local Code', 'Diagnosis']), []) + assert.deepEqual(missing(['Name']), []) + assert.deepEqual(missing(['name']), []) + assert.deepEqual(missing(['Local Code', 'Synonyms']), ['Name']) + assert.deepEqual(getMissingColumns(updateColumnState(upload(['Diagnosis']), 0, null)), ['Name']) + assert.deepEqual(getMissingColumns([]), ['Name']) + assert.deepEqual(getMissingColumns([{label: undefined}]), ['Name']) +}) + +test('getMissingColumns: any other column can be required too', () => { + const columns = upload(['Local Code', 'Diagnosis']) + assert.deepEqual(getMissingColumns(columns, ['Name', 'Synonyms', 'Property: SYSTEM']), ['Synonyms', 'Property: SYSTEM']) +}) diff --git a/src/components/map-projects/__tests__/selectedAlgos.test.js b/src/components/map-projects/__tests__/selectedAlgos.test.js index 1b277b2e..75d9f1ae 100644 --- a/src/components/map-projects/__tests__/selectedAlgos.test.js +++ b/src/components/map-projects/__tests__/selectedAlgos.test.js @@ -8,7 +8,7 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { patchSelected, isStaleReply, customCheckReply } from '../selectedAlgos.js' +import { patchSelected, isStaleReply, customCheckReply, toSelectedAlgo, getAlgosForRelease } from '../selectedAlgos.js' const custom = { __key: 'a', type: 'custom', url: 'https://algo.example/a', id: '', name: '' } const search = { __key: 'b', type: 'ocl-search', id: 'ocl-search', name: 'Search' } @@ -72,3 +72,54 @@ test('customCheckReply: the URL or token changed while pending only stops loadin assert.equal(customCheckReply({ list: [{ ...custom, url: 'https://algo.example/b' }], key: 'a', sent, checkId: 1, latestCheckId: 1 }), 'clear') assert.equal(customCheckReply({ list: [{ ...custom, token: 'new' }], key: 'a', sent, checkId: 1, latestCheckId: 1 }), 'clear') }) + +// OCL Semantic by default in a new project (OpenConceptLab/ocl_online#841) + +const SEMANTIC_RELEASE = {version_url: '/orgs/Org/sources/Source/2/', match_algorithms: ['es', 'llm']} +const KEYWORD_RELEASE = {version_url: '/orgs/Org/sources/Source/1/', match_algorithms: ['es']} +const semantic = { __key: 'c', type: 'ocl-semantic', id: 'ocl-semantic', name: 'OCL Semantic' } + +test('getAlgosForRelease: a release with semantic search starts with the default algorithm', () => { + assert.deepEqual(getAlgosForRelease([], SEMANTIC_RELEASE, {defaultAlgo: semantic}), [semantic]) +}) + +test('getAlgosForRelease: a release without semantic search selects nothing', () => { + const none = [] + assert.equal(getAlgosForRelease(none, KEYWORD_RELEASE, {defaultAlgo: semantic}), none) +}) + +test('getAlgosForRelease: without a default (chosen, removed, saved or copied), nothing is added', () => { + const none = [] + assert.equal(getAlgosForRelease(none, SEMANTIC_RELEASE), none) +}) + +test('getAlgosForRelease: a list that already has an algorithm is kept, whatever the default', () => { + const chosen = [search] + assert.equal(getAlgosForRelease(chosen, SEMANTIC_RELEASE), chosen) + assert.equal(getAlgosForRelease(chosen, SEMANTIC_RELEASE, {defaultAlgo: semantic}), chosen) + const selected = [semantic] + assert.equal(getAlgosForRelease(selected, SEMANTIC_RELEASE, {defaultAlgo: {...semantic, __key: 'd'}}), selected) +}) + +test('getAlgosForRelease: choosing a release without semantic search takes OCL Semantic out and keeps the rest', () => { + assert.deepEqual(getAlgosForRelease([semantic, custom], KEYWORD_RELEASE), [custom]) +}) + +test('getAlgosForRelease: a project loading its own release keeps OCL Semantic, so the form can warn', () => { + const saved = [semantic] + assert.equal(getAlgosForRelease(saved, KEYWORD_RELEASE, {isRestored: true}), saved) +}) + +test('toSelectedAlgo: keeps what a project saves, with the settings within the limits', () => { + const algo = { + id: 'ocl-semantic', type: 'ocl-semantic', name: 'OCL Semantic', provider: 'ocl', batch_size: 50, concurrent_requests: 4, + query_params: {semantic: true}, getIcon: () => null, disabled: true, description: 'Example', url: '/example/', + } + const selected = toSelectedAlgo(algo, {batchSize: 10, concurrentRequests: 2, capped: true}) + assert.ok(selected.__key) + assert.deepEqual({...selected, __key: 'k'}, { + __key: 'k', id: 'ocl-semantic', type: 'ocl-semantic', name: 'OCL Semantic', provider: 'ocl', batch_size: 10, concurrent_requests: 2, + query_params: {semantic: true}, + }) + assert.notEqual(toSelectedAlgo(algo).__key, selected.__key) +}) diff --git a/src/components/map-projects/columnSuggestions.js b/src/components/map-projects/columnSuggestions.js index 415020f6..2964b2d1 100644 --- a/src/components/map-projects/columnSuggestions.js +++ b/src/components/map-projects/columnSuggestions.js @@ -16,15 +16,29 @@ const CODE_TOKENS = ['code', 'codes', 'id', 'ids', 'uuid', 'identifier'] +// These say what the row is only as the header's last word, and not beside "of", +// "at", "for" or a code word: "Primary diagnosis" holds names, "Diagnosis code" +// and "Age at diagnosis" don't (OpenConceptLab/ocl_online#841). +const CLINICAL_TOKENS = [ + 'diagnosis', 'diagnoses', 'condition', 'conditions', 'procedure', 'procedures', + 'drug', 'drugs', 'medication', 'medications' +] + const SUGGESTION_RULES = [ - {label: 'Name', tokens: ['name', 'term', 'test', 'description']}, + {label: 'Name', tokens: ['name', 'term', 'test', 'description', ...CLINICAL_TOKENS]}, {label: 'Synonyms', tokens: ['synonym', 'synonyms']}, {label: 'Property: SYSTEM', tokens: ['specimen', 'system', 'sample']}, ] const tokenize = header => String(header || '').toLowerCase().split(/[\s_-]+/).filter(Boolean) +const dropDescribingWords = tokens => { + const namesRow = !tokens.join('/').split('/').some(word => ['of', 'at', 'for', ...CODE_TOKENS].includes(word)) + return tokens.filter((token, idx) => !CLINICAL_TOKENS.includes(token) || (namesRow && idx === tokens.length - 1)) +} + export const isCodeLikeHeader = header => tokenize(header).some(token => CODE_TOKENS.includes(token)) +const isDateHeader = header => /(^|[^a-z])date(s|time)?([^a-z]|$)/i.test(header || '') /** * Returns one suggested label per header, aligned with `headers`, or null @@ -48,16 +62,16 @@ export const suggestColumnLabels = (headers, validColumns, reserved = []) => { const matches = headers.map((header, idx) => { const alreadyRecognised = String(header || '').toLowerCase().includes('class') - if(isExact(header) || alreadyRecognised || isCodeLikeHeader(header)) + if(isExact(header) || alreadyRecognised || isCodeLikeHeader(header) || isDateHeader(header)) return null - const tokens = tokenize(header) + const tokens = dropDescribingWords(tokenize(header)) const rule = SUGGESTION_RULES.find(rule => tokens.some(token => rule.tokens.includes(token))) return rule ? {idx, rule, rank: rule.tokens.findIndex(token => tokens.includes(token))} : null }) // A field goes to the column with its strongest word ("name" before "test"), - // then the first such column, so "Test Name" wins over an earlier "Test Date". + // then the first such column, so "Test Name" wins over an earlier "Test". const suggestions = headers.map(() => null) matches.filter(Boolean).sort((a, b) => a.rank - b.rank || a.idx - b.idx).forEach(({idx, rule}) => { const target = findValid(rule.label) @@ -69,6 +83,13 @@ export const suggestColumnLabels = (headers, validColumns, reserved = []) => { return suggestions } +// The fields that need a column before someone can save a project's settings: +// AutoMatch compares names (OpenConceptLab/ocl_online#841). +const REQUIRED_COLUMNS = ['Name'] + +export const getMissingColumns = (columns, required = REQUIRED_COLUMNS) => + required.filter(label => !columns.some(column => column.label?.toLowerCase() === label.toLowerCase())) + /** * Returns a new columns array with one column's mapping changed. A change * without a key is a mapping choice: it ends any suggestion, and clearing it diff --git a/src/components/map-projects/selectedAlgos.js b/src/components/map-projects/selectedAlgos.js index 8b335848..67f116c9 100644 --- a/src/components/map-projects/selectedAlgos.js +++ b/src/components/map-projects/selectedAlgos.js @@ -1,3 +1,7 @@ +import omit from 'lodash/omit.js' +import { getRequestSettings } from './requestLimits.js' +import { isLLMBridgeRepoVersion } from './projectTargetRepo.js' + // Edits to the selected algorithm list (ocl_online#786). // // A reply that arrives after a request (a custom algorithm check, a bridge @@ -25,3 +29,28 @@ export const customCheckReply = ({ list, key, sent, checkId, latestCheckId }) => return 'ignore' return isStaleReply(list, key, sent) ? 'clear' : 'apply' } + +// An algorithm as a project keeps it once selected, with the request settings +// it starts with. +export const toSelectedAlgo = (algo, requestLimits) => { + const { batchSize, concurrentRequests } = getRequestSettings(algo, requestLimits) + return { + ...omit(algo, ['getIcon', 'disabled', 'description', 'url']), + batch_size: batchSize, + concurrent_requests: concurrentRequests, + __key: Math.random().toString() + } +} + +// The selected algorithms once the target release is `version`. `defaultAlgo` +// (OCL Semantic) is passed only while a new project's algorithms are still +// nobody's choice. A release chosen without semantic search takes OCL Semantic +// out; a project loading its own release (isRestored) keeps what it saved, and +// the form warns (OpenConceptLab/ocl_online#841). +export const getAlgosForRelease = (list, version, { defaultAlgo, isRestored } = {}) => { + if(isLLMBridgeRepoVersion(version)) + return defaultAlgo && !list.length ? [defaultAlgo] : list + if(isRestored || !list.some(algo => algo.type === 'ocl-semantic')) + return list + return list.filter(algo => algo.type !== 'ocl-semantic') +} diff --git a/src/components/repos/RepoSearchAutocomplete.jsx b/src/components/repos/RepoSearchAutocomplete.jsx index 42eae55e..d28eebb8 100644 --- a/src/components/repos/RepoSearchAutocomplete.jsx +++ b/src/components/repos/RepoSearchAutocomplete.jsx @@ -10,7 +10,7 @@ import GroupHeader from '../common/GroupHeader' import GroupItems from '../common/GroupItems' -const RepoSearchAutocomplete = ({onChange, label, id, required, minCharactersForSearch, size, suggested, sx, value, repoType, ownRepo, autoFocus, disabled}) => { +const RepoSearchAutocomplete = ({onChange, label, id, required, minCharactersForSearch, size, suggested, sx, value, repoType, ownRepo, autoFocus, disabled, error}) => { const { t } = useTranslation(); const minLength = minCharactersForSearch || 2; const [input, setInput] = React.useState('') @@ -120,6 +120,7 @@ const RepoSearchAutocomplete = ({onChange, label, id, required, minCharactersFor autoFocus={autoFocus} value={input || ''} required + error={Boolean(error)} label={label || t('map_project.source')} variant="outlined" fullWidth diff --git a/src/i18n/locales/en/translations.json b/src/i18n/locales/en/translations.json index d2d86ef1..97dffc8e 100644 --- a/src/i18n/locales/en/translations.json +++ b/src/i18n/locales/en/translations.json @@ -277,6 +277,9 @@ "field_configuration": "Field Configuration", "field_configuration_description": "Associate fields in the input data to fields that the matching algorithms are able to understand. Assign input fields that contain concept codes or mappings to specific repositories. <0>Learn more", "column_suggested": "Suggested from column name. Change it if it's wrong.", + "missing_required_field_one": "Missing required field: {{names}}.", + "missing_required_field_other": "Missing required fields: {{names}}.", + "missing_required_column_mapping": "Missing required column mapping: {{names}}.", "input_column": "Input Column", "mapped_field": "Mapped Field", "field": "Field", diff --git a/src/i18n/locales/es/translations.json b/src/i18n/locales/es/translations.json index 74768eec..999edabf 100644 --- a/src/i18n/locales/es/translations.json +++ b/src/i18n/locales/es/translations.json @@ -258,6 +258,9 @@ "field_configuration": "Configuración de Campo", "field_configuration_description": "Asocie campos en los datos de entrada con campos que los algoritmos de coincidencia puedan entender. Asigne campos de entrada que contengan códigos de concepto o mapeos a repositorios específicos. <0>Aprenda más", "column_suggested": "Sugerido a partir del nombre de la columna. Cámbielo si es incorrecto.", + "missing_required_field_one": "Falta un campo obligatorio: {{names}}.", + "missing_required_field_other": "Faltan campos obligatorios: {{names}}.", + "missing_required_column_mapping": "Falta una asignación de columna obligatoria: {{names}}.", "input_column": "Columna de Entrada", "mapped_field": "Campo Mapeado", "field": "Campo", diff --git a/src/i18n/locales/pt-BR/translations.json b/src/i18n/locales/pt-BR/translations.json index 72362fee..e7344513 100644 --- a/src/i18n/locales/pt-BR/translations.json +++ b/src/i18n/locales/pt-BR/translations.json @@ -277,6 +277,9 @@ "field_configuration": "Configuração de Campo", "field_configuration_description": "Associe campos nos dados de entrada a campos que os algoritmos de mapeamento são capazes de entender. Atribua campos de entrada que contenham códigos de conceito ou mapeamentos a repositórios específicos. <0>Saiba mais", "column_suggested": "Sugerido pelo nome da coluna. Altere se estiver errado.", + "missing_required_field_one": "Falta um campo obrigatório: {{names}}.", + "missing_required_field_other": "Faltam campos obrigatórios: {{names}}.", + "missing_required_column_mapping": "Falta um mapeamento de coluna obrigatório: {{names}}.", "input_column": "Coluna de Entrada", "mapped_field": "Campo Mapeado", "field": "Campo", diff --git a/src/i18n/locales/zh/translations.json b/src/i18n/locales/zh/translations.json index 1ca75730..4c6390d0 100644 --- a/src/i18n/locales/zh/translations.json +++ b/src/i18n/locales/zh/translations.json @@ -270,6 +270,8 @@ "field_configuration": "字段配置", "field_configuration_description": "将输入数据中的字段与匹配算法能够理解的字段关联。将包含概念代码或映射的输入字段分配给特定存储库。<0>了解更多", "column_suggested": "根据列名建议。如有误请更改。", + "missing_required_field_other": "缺少必填字段:{{names}}。", + "missing_required_column_mapping": "缺少必需的列映射:{{names}}。", "input_column": "输入列", "mapped_field": "映射字段", "field": "字段",