+ );
+}
+
+i18n.addResourceBundle('fr', 'candidate_identifiers', frStrings);
+
+window.addEventListener('load', () => {
+ const TranslatedCandidateIdentifiersIndex = withTranslation()(
+ CandidateIdentifiersIndex
+ );
+
+ createRoot(document.getElementById('lorisworkspace') as HTMLElement).render(
+
+ );
+});
diff --git a/modules/candidate_identifiers/jsx/editIdentifierForm.tsx b/modules/candidate_identifiers/jsx/editIdentifierForm.tsx
new file mode 100644
index 0000000000..26c55582de
--- /dev/null
+++ b/modules/candidate_identifiers/jsx/editIdentifierForm.tsx
@@ -0,0 +1,191 @@
+import React, {useState} from 'react';
+
+import {
+ withTranslation,
+ WithTranslation,
+} from 'react-i18next';
+
+import {Errors} from 'jslib';
+
+import {
+ FormElement,
+ TextboxElement,
+ ButtonElement,
+} from 'jsx/Form';
+
+import {client} from 'jslib/http';
+
+type CandidateIdentifier = {
+ CandID: string;
+ CandidateIdentifierID: number | string;
+ CandidateIdentifierTypeID: number | string;
+ IdentifierType: string;
+ IdentifierValue: string;
+};
+
+type EditIdentifierFormProps = {
+ identifier: CandidateIdentifier;
+ onSuccess: () => void;
+ t: WithTranslation['t'];
+};
+
+/**
+ * Form for editing an existing candidate identifier.
+ *
+ * @param props Component properties
+ * @return React component
+ */
+function EditIdentifierForm(props: EditIdentifierFormProps) {
+ const {t} = props;
+
+ const [values, setValues] = useState({
+ Value: props.identifier.IdentifierValue || '',
+ });
+
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(null);
+
+ const editingDisabled = props.identifier.IdentifierType === 'PSCID';
+
+ /**
+ * Update a form field.
+ *
+ * @param name Field name
+ * @param value New value
+ */
+ const updateValue = (name: string, value: string) => {
+ setValues((previous) => ({
+ ...previous,
+ [name]: value,
+ }));
+ };
+
+ /**
+ * Submit the form to update a candidate identifier.
+ *
+ * @param event Submit event
+ */
+ const submit = async (event: React.SyntheticEvent) => {
+ event.preventDefault();
+
+ if (saving || editingDisabled) {
+ return;
+ }
+
+ setError(null);
+
+ const value = values.Value.trim();
+
+ if (!value) {
+ setError(
+ t('Identifier Value is required.', {ns: 'candidate_identifiers'})
+ );
+ return;
+ }
+
+ setSaving(true);
+
+ try {
+ await client.put(
+ `api/v0.0.4-dev/candidates/` +
+ `${encodeURIComponent(props.identifier.CandID)}/identifiers`,
+ {
+ Identifier: {
+ CandidateIdentifierID: Number(
+ props.identifier.CandidateIdentifierID
+ ),
+ CandidateIdentifierTypeID: Number(
+ props.identifier.CandidateIdentifierTypeID
+ ),
+ Value: value,
+ },
+ }
+ );
+
+ props.onSuccess();
+ } catch (err) {
+ const status = err instanceof Errors.ApiResponse
+ ? err.response?.status
+ : undefined;
+
+ switch (status) {
+ case 400:
+ setError(t('Invalid or duplicate identifier value.', {
+ ns: 'candidate_identifiers',
+ }));
+ break;
+ case 403:
+ setError(t('Permission denied.', {
+ ns: 'candidate_identifiers',
+ }));
+ break;
+ case 404:
+ setError(t('Identifier or candidate not found.', {
+ ns: 'candidate_identifiers',
+ }));
+ break;
+ default:
+ setError(t('Unable to update identifier.', {
+ ns: 'candidate_identifiers',
+ }));
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+
+
+
+ );
+}
+
+export default withTranslation()(EditIdentifierForm);
diff --git a/modules/candidate_identifiers/locale/candidate_identifiers.pot b/modules/candidate_identifiers/locale/candidate_identifiers.pot
new file mode 100644
index 0000000000..a0ed11b2ff
--- /dev/null
+++ b/modules/candidate_identifiers/locale/candidate_identifiers.pot
@@ -0,0 +1,85 @@
+# Default LORIS strings to be translated (English).
+# Copy this to a language specific file and add translations to the
+# new file.
+# Copyright (C) 2025
+# This file is distributed under the same license as the LORIS package.
+# Dave MacFarlane , 2025.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: LORIS 29\n"
+"Report-Msgid-Bugs-To: https://github.com/aces/Loris/issues\n"
+"POT-Creation-Date: 2025-04-08 14:37-0400\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME \n"
+"Language-Team: LANGUAGE \n"
+"Language: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+
+msgid "Candidate Identifiers"
+msgstr ""
+
+msgid "Add Identifier"
+msgstr ""
+
+msgid "Edit Identifier"
+msgstr ""
+
+msgid "Identifier Type"
+msgstr ""
+
+msgid "Identifier Value"
+msgstr ""
+
+msgid "Date Added"
+msgstr ""
+
+msgid "Date Edited"
+msgstr ""
+
+msgid "Yes, delete it!"
+msgstr ""
+
+msgid "Delete"
+msgstr ""
+
+msgid "CandID and Identifier Type are required."
+msgstr ""
+
+msgid "Unable to add identifier."
+msgstr ""
+
+msgid "Identifier Value is required."
+msgstr ""
+
+msgid "Unable to update identifier."
+msgstr ""
+
+msgid "Delete identifier \"{{value}}\"?"
+msgstr ""
+
+msgid "Deleted!"
+msgstr ""
+
+msgid "Identifier deleted successfully."
+msgstr ""
+
+msgid "Unable to delete identifier."
+msgstr ""
+
+msgid "Invalid or duplicate identifier value."
+msgstr ""
+
+msgid "Permission denied."
+msgstr ""
+
+msgid "Identifier or candidate not found."
+msgstr ""
+
+msgid "Candidate not found."
+msgstr ""
+
+msgid "No identifiers found"
+msgstr ""
diff --git a/modules/candidate_identifiers/locale/fr/LC_MESSAGES/candidate_identifiers.po b/modules/candidate_identifiers/locale/fr/LC_MESSAGES/candidate_identifiers.po
new file mode 100644
index 0000000000..86a1052c1d
--- /dev/null
+++ b/modules/candidate_identifiers/locale/fr/LC_MESSAGES/candidate_identifiers.po
@@ -0,0 +1,86 @@
+# Default LORIS strings to be translated (English).
+# Copy this to a language specific file and add translations to the
+# new file.
+# Copyright (C) 2025
+# This file is distributed under the same license as the LORIS package.
+# Dave MacFarlane , 2025.
+#
+msgid ""
+msgstr ""
+"Project-Id-Version: LORIS 29\n"
+"Report-Msgid-Bugs-To: https://github.com/aces/Loris/issues\n"
+"POT-Creation-Date: 2025-04-08 14:37-0400\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME \n"
+"Language-Team: LANGUAGE \n"
+"Language: fr\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+
+msgid "Candidate Identifiers"
+msgstr "Identifiants des candidats"
+
+msgid "Add Identifier"
+msgstr "Ajouter un identifiant"
+
+msgid "Edit Identifier"
+msgstr "Modifier un identifiant"
+
+msgid "Identifier Type"
+msgstr "Type d'identifiant"
+
+msgid "Identifier Value"
+msgstr "Valeur de l'identifiant"
+
+msgid "Date Added"
+msgstr "Date d'ajout"
+
+msgid "Date Edited"
+msgstr "Date de modification"
+
+msgid "Yes, delete it!"
+msgstr "Oui, le supprimer !"
+
+msgid "Delete"
+msgstr "Supprimer"
+
+msgid "CandID and Identifier Type are required."
+msgstr "Le CandID et le type d'identifiant sont obligatoires."
+
+msgid "Unable to add identifier."
+msgstr "Impossible d'ajouter l'identifiant."
+
+msgid "Identifier Value is required."
+msgstr "La valeur de l'identifiant est obligatoire."
+
+msgid "Unable to update identifier."
+msgstr "Impossible de modifier l'identifiant."
+
+msgid "Delete identifier \"{{value}}\"?"
+msgstr "Supprimer l'identifiant « {{value}} » ?"
+
+msgid "Deleted!"
+msgstr "Supprimé !"
+
+msgid "Identifier deleted successfully."
+msgstr "L'identifiant a été supprimé avec succès."
+
+msgid "Unable to delete identifier."
+msgstr "Impossible de supprimer l'identifiant."
+
+msgid "Invalid or duplicate identifier value."
+msgstr "La valeur de l'identifiant est invalide ou existe déjà."
+
+msgid "Permission denied."
+msgstr "Permission refusée."
+
+msgid "Identifier or candidate not found."
+msgstr "Identifiant ou candidat introuvable."
+
+msgid "Candidate not found."
+msgstr "Candidat introuvable."
+
+msgid "No identifiers found"
+msgstr "Aucun identifiant trouvé"
diff --git a/modules/candidate_identifiers/php/candidate_identifiers.class.inc b/modules/candidate_identifiers/php/candidate_identifiers.class.inc
new file mode 100644
index 0000000000..a45c9b8b28
--- /dev/null
+++ b/modules/candidate_identifiers/php/candidate_identifiers.class.inc
@@ -0,0 +1,133 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+namespace LORIS\candidate_identifiers;
+
+/**
+ * Implements the Candidate Identifiers menu.
+ *
+ * @category Main
+ * @package Candidate_Identifiers
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+class Candidate_Identifiers extends \DataFrameworkMenu
+{
+ /**
+ * Check whether the user can access this page.
+ *
+ * @param \User $user The user whose access is being checked.
+ *
+ * @return bool Whether the user can access this page
+ */
+ #[\Override]
+ public function isAccessibleBy(\User $user) : bool
+ {
+ return (
+ $user->hasPermission('access_all_profiles')
+ || ($user->hasStudySite() && $user->hasPermission('data_entry'))
+ );
+ }
+
+ /**
+ * Allow the data framework to use the existing site permission filter.
+ *
+ * @return ?array Permissions that grant access across sites
+ */
+ public function allSitePermissionNames() : ?array
+ {
+ return ['access_all_profiles'];
+ }
+
+ /**
+ * Enable the existing project filter.
+ *
+ * @return bool Whether to use project filtering
+ */
+ public function useProjectFilter() : bool
+ {
+ return true;
+ }
+
+ /**
+ * Return the data provisioner for the identifier table.
+ *
+ * @return \LORIS\Data\Provisioner
+ */
+ public function getBaseDataProvisioner() : \LORIS\Data\Provisioner
+ {
+ return new CandidateIdentifierRowProvisioner($this->loris);
+ }
+
+ /**
+ * Return filter options for the data table.
+ *
+ * @return array Filter options
+ */
+ protected function getFieldOptions(): array
+ {
+ $controller = new \LORIS\IdentifierTypeController(
+ \NDB_Factory::singleton()->database()
+ );
+
+ $identifierTypes = [];
+
+ foreach ($controller->getAllIdentifierTypes() as $identifierType) {
+ $identifierTypes[] = [
+ 'value' => $identifierType->candidateIdentifierTypeID,
+ 'label' => $identifierType->name,
+ 'autoGenerate' => $identifierType->autoGenerate,
+ 'isRequired' => $identifierType->isRequired,
+ ];
+ }
+
+ return [
+ 'identifierTypes' => $identifierTypes,
+ ];
+ }
+
+ /**
+ * Include the JavaScript required to render the table.
+ *
+ * @return array JavaScript dependencies
+ */
+ public function getJSDependencies() : array
+ {
+ $factory = \NDB_Factory::singleton();
+ $baseURL = $factory->settings()->getBaseURL();
+ $deps = parent::getJSDependencies();
+
+ return array_merge(
+ $deps,
+ [
+ $baseURL . "/candidate_identifiers/js/candidateIdentifiersIndex.js",
+ ]
+ );
+ }
+
+ /**
+ * Generate the breadcrumb trail for this page.
+ *
+ * @return \LORIS\BreadcrumbTrail
+ */
+ public function getBreadcrumbs() : \LORIS\BreadcrumbTrail
+ {
+ return new \LORIS\BreadcrumbTrail(
+ new \LORIS\Breadcrumb(
+ dgettext("candidate_identifiers", "Candidate Identifiers"),
+ "/$this->name"
+ )
+ );
+ }
+}
diff --git a/modules/candidate_identifiers/php/candidateidentifierrow.class.inc b/modules/candidate_identifiers/php/candidateidentifierrow.class.inc
new file mode 100644
index 0000000000..66f023a6d8
--- /dev/null
+++ b/modules/candidate_identifiers/php/candidateidentifierrow.class.inc
@@ -0,0 +1,72 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+namespace LORIS\candidate_identifiers;
+
+/**
+ * A candidate identifier row with site and project information.
+ *
+ * @category Main
+ * @package Candidate_Identifiers
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+class CandidateIdentifierRow implements
+ \LORIS\Data\DataInstance,
+ \LORIS\StudyEntities\SiteHaver
+{
+ /**
+ * Initialize the candidate identifier row.
+ *
+ * @param array $row Database row
+ * @param \CenterID $cid Candidate registration site
+ * @param \ProjectID $pid Candidate registration project
+ */
+ public function __construct(
+ protected array $row,
+ protected \CenterID $cid,
+ protected \ProjectID $pid
+ ) {
+ }
+
+ /**
+ * Return the row data for serialization.
+ *
+ * @return array
+ */
+ public function jsonSerialize(): array
+ {
+ return $this->row;
+ }
+
+ /**
+ * Return the candidate's registration site.
+ *
+ * @return \CenterID
+ */
+ public function getCenterID(): \CenterID
+ {
+ return $this->cid;
+ }
+
+ /**
+ * Return the candidate's registration project.
+ *
+ * @return \ProjectID
+ */
+ public function getProjectID(): \ProjectID
+ {
+ return $this->pid;
+ }
+}
diff --git a/modules/candidate_identifiers/php/candidateidentifierrowprovisioner.class.inc b/modules/candidate_identifiers/php/candidateidentifierrowprovisioner.class.inc
new file mode 100644
index 0000000000..3b0b9c0a6f
--- /dev/null
+++ b/modules/candidate_identifiers/php/candidateidentifierrowprovisioner.class.inc
@@ -0,0 +1,134 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+namespace LORIS\candidate_identifiers;
+
+/**
+ * Retrieves candidate identifier rows for the data framework.
+ *
+ * @category Main
+ * @package Candidate_Identifiers
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+class CandidateIdentifierRowProvisioner extends
+ \LORIS\Data\Provisioners\DBRowProvisioner
+{
+ /**
+ * Create the data provisioner.
+ *
+ * @param \LORIS\LorisInstance $loris The LORIS instance
+ */
+ public function __construct(protected \LORIS\LorisInstance $loris)
+ {
+ $user = \User::singleton();
+
+ /*
+ * Build the list of permissions available to the current user.
+ *
+ * A type with no associated permission is visible.
+ * A type with a permission is visible only when the user has it.
+ */
+ $database = $loris->getDatabaseConnection();
+
+ $permissions = $database->pselect(
+ "SELECT permID, code FROM permissions",
+ []
+ );
+
+ $allowedPermissionIDs = [];
+
+ foreach ($permissions as $permission) {
+ if ($user->hasPermission($permission['code'])) {
+ $allowedPermissionIDs[] = (int) $permission['permID'];
+ }
+ }
+
+ /*
+ * We use permission IDs only after converting them to integers.
+ * This avoids introducing untrusted values into the SQL.
+ */
+ $permissionFilter = "cit.permID IS NULL";
+
+ if (!empty($allowedPermissionIDs)) {
+ $permissionFilter .= " OR cit.permID IN ("
+ . implode(',', $allowedPermissionIDs)
+ . ")";
+ }
+
+ /*
+ * Retrieve identifiers while enforcing identifier-type restrictions.
+ */
+ $sql = "
+ SELECT
+ c.CandID,
+ c.PSCID,
+ cit.Name AS IdentifierType,
+ ci.Value AS IdentifierValue,
+ ci.DateAdded,
+ ci.DateEdited,
+ ci.CandidateIdentifierID,
+ ci.CandidateIdentifierTypeID,
+ c.RegistrationCenterID,
+ c.RegistrationProjectID
+ FROM candidate_identifiers ci
+ JOIN candidate c
+ ON c.ID = ci.CandidateID
+ JOIN candidate_identifier_types cit
+ ON cit.CandidateIdentifierTypeID =
+ ci.CandidateIdentifierTypeID
+ WHERE c.Active = 'Y'
+ AND c.RegistrationProjectID IS NOT NULL
+ AND ($permissionFilter)
+ AND (
+ NOT EXISTS (
+ SELECT 1
+ FROM candidate_identifier_types_project_rel citpr
+ WHERE citpr.CandidateIdentifierTypeID =
+ cit.CandidateIdentifierTypeID
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM candidate_identifier_types_project_rel citpr
+ WHERE citpr.CandidateIdentifierTypeID =
+ cit.CandidateIdentifierTypeID
+ AND citpr.ProjectID = c.RegistrationProjectID
+ )
+ )
+ ORDER BY c.PSCID ASC
+ ";
+
+ parent::__construct($this->loris, $sql, []);
+ }
+
+ /**
+ * Convert a database row into a CandidateIdentifierRow.
+ *
+ * @param array $row Database row
+ *
+ * @return \LORIS\Data\DataInstance
+ */
+ public function getInstance($row): \LORIS\Data\DataInstance
+ {
+ $cid = \CenterID::singleton($row['RegistrationCenterID']);
+ $pid = \ProjectID::singleton($row['RegistrationProjectID']);
+
+ unset(
+ $row['RegistrationCenterID'],
+ $row['RegistrationProjectID']
+ );
+
+ return new CandidateIdentifierRow($row, $cid, $pid);
+ }
+}
diff --git a/modules/candidate_identifiers/php/identifierdictionaryitem.class.inc b/modules/candidate_identifiers/php/identifierdictionaryitem.class.inc
new file mode 100644
index 0000000000..f0b1a75385
--- /dev/null
+++ b/modules/candidate_identifiers/php/identifierdictionaryitem.class.inc
@@ -0,0 +1,68 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+
+namespace LORIS\candidate_identifiers;
+
+use LORIS\Data\Scope;
+use LORIS\Data\Type;
+use LORIS\Data\Cardinality;
+use LORIS\Data\Dictionary\DictionaryItem;
+
+/**
+ * Describes a dictionary item for a configurable candidate identifier.
+ *
+ * Extends DictionaryItem to enforce identifier-specific permissions.
+ *
+ * @category LORIS
+ * @package LORIS
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+class IdentifierDictionaryItem extends DictionaryItem
+{
+ /**
+ * Construct an IdentifierDictionaryItem.
+ *
+ * @param string $name The field name
+ * @param string $desc The field description
+ * @param Scope $scope The data scope
+ * @param Type $type The data type
+ * @param Cardinality $cardinality The data cardinality
+ * @param string|null $permissionCode Required permission code
+ */
+ public function __construct(
+ string $name,
+ string $desc,
+ Scope $scope,
+ Type $type,
+ Cardinality $cardinality,
+ protected ?string $permissionCode
+ ) {
+ parent::__construct($name, $desc, $scope, $type, $cardinality);
+ }
+
+ /**
+ * Check whether the user can access this identifier type.
+ *
+ * @param \User $user The user requesting access
+ *
+ * @return bool Whether the user has access
+ */
+ public function isAccessibleBy(\User $user): bool
+ {
+ return $this->permissionCode === null
+ || $user->hasPermission($this->permissionCode);
+ }
+}
diff --git a/modules/candidate_identifiers/php/module.class.inc b/modules/candidate_identifiers/php/module.class.inc
new file mode 100644
index 0000000000..bc5eb32d59
--- /dev/null
+++ b/modules/candidate_identifiers/php/module.class.inc
@@ -0,0 +1,143 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+
+namespace LORIS\candidate_identifiers;
+
+use LORIS\candidate_profile\CandidateWidget;
+
+/**
+ * Class module implements the basic LORIS module functionality
+ *
+ * @category Behavioural
+ * @package Main
+ * @subpackage Behavioural
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://www.github.com/aces/Loris/
+ */
+class Module extends \Module
+{
+ /**
+ * {@inheritDoc}
+ *
+ * @param \User $user The user whose access is being checked.
+ *
+ * @return bool Whether access is granted
+ */
+ public function hasAccess(\User $user): bool
+ {
+ return parent::hasAccess($user) &&
+ $user->hasAnyPermission(['data_entry', 'access_all_profiles']);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return ?\LORIS\GUI\MenuCategory
+ */
+ public function getMenuCategory(): ?\LORIS\GUI\MenuCategory
+ {
+ return \LORIS\GUI\MenuCategory::singleton("Candidate");
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return string The human-readable module name
+ */
+ public function getLongName(): string
+ {
+ return dgettext("candidate_identifiers", "Candidate Identifiers");
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @param string $type Widget type
+ * @param \User $user Current user
+ * @param array $options Widget options
+ *
+ * @return \LORIS\GUI\Widget[]
+ */
+ public function getWidgets(string $type, \User $user, array $options): array
+ {
+ if ($type !== 'candidate') {
+ return [];
+ }
+
+ $candidate = $options['candidate'] ?? null;
+
+ if ($candidate === null || !$this->hasAccess($user)) {
+ return [];
+ }
+
+ $controller = new \LORIS\CandidateIdentifierController(
+ \NDB_Factory::singleton()->database()
+ );
+
+ $identifiers = $controller->getCandidateIdentifiers(
+ (int) $candidate->getID()
+ );
+
+ $data = [];
+
+ $typeController = new \LORIS\IdentifierTypeController(
+ \NDB_Factory::singleton()->database()
+ );
+
+ foreach ($identifiers as $identifier) {
+ $identifierType = $identifier->type;
+
+ if (!$typeController->canAccessIdentifierType(
+ $user,
+ $identifierType,
+ $candidate
+ )
+ ) {
+ continue;
+ }
+
+ $data[] = [
+ 'ID' => $identifier->candidateIdentifierID,
+ 'Type' => $identifierType->name,
+ 'Value' => $identifier->value,
+ ];
+ }
+
+ $baseURL = \NDB_Factory::singleton()->settings()->getBaseURL();
+
+ return [
+ new CandidateWidget(
+ dgettext("candidate_identifiers", "Candidate Identifiers"),
+ $baseURL . "/candidate_identifiers/js/CandidateIdentifiersWidget.js",
+ "lorisjs.candidate_identifiers.CandidateIdentifiersWidget.default",
+ ['Identifiers' => $data],
+ 1,
+ 1,
+ ),
+ ];
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return \LORIS\Data\Query\QueryEngine[]
+ */
+ public function getQueryEngines(): iterable
+ {
+ return [new QueryEngine($this->loris)];
+ }
+}
diff --git a/modules/candidate_identifiers/php/queryengine.class.inc b/modules/candidate_identifiers/php/queryengine.class.inc
new file mode 100644
index 0000000000..3e9939255d
--- /dev/null
+++ b/modules/candidate_identifiers/php/queryengine.class.inc
@@ -0,0 +1,203 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+
+namespace LORIS\candidate_identifiers;
+
+use LORIS\Data\Scope;
+use LORIS\Data\Cardinality;
+use LORIS\Data\Dictionary\Category;
+use LORIS\Data\Dictionary\DictionaryItem;
+use LORIS\Data\Types\StringType;
+
+/**
+ * QueryEngine for configurable candidate identifiers.
+ *
+ * Exposes candidate identifier types to Data Query.
+ *
+ * @category LORIS
+ * @package LORIS
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+class QueryEngine extends \LORIS\Data\Query\SQLQueryEngine
+{
+ /**
+ * Return the candidate identifier data dictionary.
+ *
+ * @return Category[]
+ */
+ public function getDataDictionary(): iterable
+ {
+ $scope = new Scope(Scope::CANDIDATE);
+
+ $identifiers = new Category(
+ "Identifiers",
+ dgettext("candidate_identifiers", "Candidate Identifiers")
+ );
+
+ $db = $this->loris->getDatabaseConnection();
+
+ $types = $db->pselect(
+ "SELECT
+ cit.CandidateIdentifierTypeID,
+ cit.Name,
+ cit.AllowMultiple,
+ cit.permID,
+ p.code AS PermissionCode
+ FROM candidate_identifier_types cit
+ LEFT JOIN permissions p ON cit.permID = p.permID
+ ORDER BY cit.Name",
+ []
+ );
+
+ $items = [];
+
+ foreach ($types as $type) {
+ // A missing permission code must not grant access
+ // when the identifier type requires a permission.
+ $permissionCode = null;
+
+ if ($type['permID'] !== null) {
+ $permissionCode = $type['PermissionCode'];
+
+ if ($permissionCode === null) {
+ continue;
+ }
+ }
+
+ $items[] = new IdentifierDictionaryItem(
+ "Identifier_" . $type['CandidateIdentifierTypeID'],
+ $type['Name'],
+ $scope,
+ new StringType(255),
+ new Cardinality(
+ $type['AllowMultiple']
+ ? Cardinality::MANY
+ : Cardinality::OPTIONAL
+ ),
+ $permissionCode
+ );
+ }
+
+ return [$identifiers->withItems($items)];
+ }
+
+ /**
+ * Candidate identifiers are not session-scoped.
+ *
+ * @param Category $category The dictionary category
+ * @param DictionaryItem $item The dictionary item
+ *
+ * @return string[]
+ */
+ public function getVisitList(
+ Category $category,
+ DictionaryItem $item
+ ): iterable {
+ return [];
+ }
+
+ /**
+ * Extract the identifier type ID from a dictionary item.
+ *
+ * @param DictionaryItem $item The dictionary item
+ *
+ * @return int
+ */
+ private function _getIdentifierTypeID(DictionaryItem $item): int
+ {
+ $name = $item->getName();
+
+ if (!preg_match('/^Identifier_([1-9][0-9]*)$/', $name, $matches)) {
+ throw new \InvalidArgumentException(
+ "Unknown candidate identifier field: " . $name
+ );
+ }
+
+ return (int) $matches[1];
+ }
+
+ /**
+ * Register the identifier join and return its SQL alias.
+ *
+ * @param DictionaryItem $item The dictionary item
+ *
+ * @return string
+ */
+ private function _getIdentifierAlias(
+ DictionaryItem $item
+ ): string {
+ $typeID = $this->_getIdentifierTypeID($item);
+ $alias = "ci_" . $typeID;
+
+ $this->addTable(
+ "LEFT JOIN candidate_identifiers $alias "
+ . "ON ($alias.CandidateID = c.ID "
+ . "AND $alias.CandidateIdentifierTypeID = $typeID "
+ . "AND ("
+ . "NOT EXISTS ("
+ . "SELECT 1 FROM candidate_identifier_types_project_rel cipr "
+ . "WHERE cipr.CandidateIdentifierTypeID = $typeID"
+ . ") "
+ . "OR EXISTS ("
+ . "SELECT 1 FROM candidate_identifier_types_project_rel cipr "
+ . "WHERE cipr.CandidateIdentifierTypeID = $typeID "
+ . "AND cipr.ProjectID = c.RegistrationProjectID"
+ . ")"
+ . "))"
+ );
+
+ return $alias;
+ }
+
+ /**
+ * Return the SQL expression for an identifier field.
+ *
+ * @param DictionaryItem $item The dictionary item
+ *
+ * @return string
+ */
+ protected function getFieldNameFromDict(
+ DictionaryItem $item
+ ): string {
+ return $this->_getIdentifierAlias($item) . ".Value";
+ }
+
+ /**
+ * Return the key field type for multivalued identifiers.
+ *
+ * @param DictionaryItem $item The dictionary item
+ *
+ * @return string
+ */
+ public function getCorrespondingKeyFieldType(
+ DictionaryItem $item
+ ): string {
+ return "Candidate Identifier ID";
+ }
+
+ /**
+ * Return the SQL key for multivalued identifiers.
+ *
+ * @param DictionaryItem $item The dictionary item
+ *
+ * @return string
+ */
+ public function getCorrespondingKeyField(
+ DictionaryItem $item
+ ): string {
+ return $this->_getIdentifierAlias($item) . ".CandidateIdentifierID";
+ }
+}
diff --git a/modules/candidate_identifiers/test/TestPlan.md b/modules/candidate_identifiers/test/TestPlan.md
new file mode 100644
index 0000000000..b18e6ca454
--- /dev/null
+++ b/modules/candidate_identifiers/test/TestPlan.md
@@ -0,0 +1,42 @@
+# Candidate Identifiers Test Plan
+
+1. Access the "Candidate Identifiers" page and ensure that it renders.
+2. Verify that either `data_entry` or `access_all_profiles` permission is required to access the page.
+3. Verify that users with only `data_entry` permission can view identifiers belonging to candidates at their assigned study sites.
+4. Verify that users with `access_all_profiles` permission can view identifiers across study sites.
+5. Test each table filter individually:
+ [ ] Identifier Type
+ [ ] Identifier Value
+ [ ] Date Added
+ [ ] Date Edited
+6. Verify that the table columns can be sorted.
+7. Click "Add Identifier" and verify that the form opens.
+8. Add a valid identifier and verify that it appears in the table.
+9. Edit an existing identifier and verify that the updated value is displayed.
+10. Delete an identifier and verify that a confirmation dialog appears.
+11. Confirm deletion and verify that the identifier is removed from the table.
+12. Cancel deletion and verify that the identifier remains unchanged.
+13. Verify that available identifier types match those configured in the Configuration module.
+14. Verify that required and automatically generated identifier types are handled according to their configuration.
+15. Verify that invalid identifier values are rejected with an appropriate error message.
+
+## Widgets
+
+1. Access a candidate in the `candidate_profile` module.
+
+### Candidate Identifiers Widget
+
+1. Verify that the "Candidate Identifiers" card appears for users
+ with access to the module.
+2. Verify that the identifier types and values displayed match
+ those stored for the candidate.
+3. Verify that identifiers are displayed in a read-only table.
+4. Verify that "No identifiers found" is displayed when the
+ candidate has no accessible identifiers.
+5. Verify that identifiers requiring a specific permission are
+ only displayed to users with that permission.
+6. Verify that project-restricted identifiers are only displayed
+ when the candidate's registration project matches an allowed
+ project and the user has access to that project.
+7. Verify that the widget labels and empty-state message are
+ correctly translated when switching between English and French.
\ No newline at end of file
diff --git a/modules/candidate_identifiers/test/candidateIdentifiersQueryEngineTest.php b/modules/candidate_identifiers/test/candidateIdentifiersQueryEngineTest.php
new file mode 100644
index 0000000000..13f7eb82c4
--- /dev/null
+++ b/modules/candidate_identifiers/test/candidateIdentifiersQueryEngineTest.php
@@ -0,0 +1,669 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+
+use PHPUnit\Framework\TestCase;
+
+use LORIS\StudyEntities\Candidate\CandID;
+use LORIS\Data\Query\QueryTerm;
+
+use LORIS\Data\Query\Criteria\Equal;
+use LORIS\Data\Query\Criteria\NotEqual;
+use LORIS\Data\Query\Criteria\In;
+
+use LORIS\Data\Query\Criteria\GreaterThanOrEqual;
+use LORIS\Data\Query\Criteria\GreaterThan;
+use LORIS\Data\Query\Criteria\LessThanOrEqual;
+use LORIS\Data\Query\Criteria\LessThan;
+
+use LORIS\Data\Query\Criteria\IsNull;
+use LORIS\Data\Query\Criteria\NotNull;
+
+use LORIS\Data\Query\Criteria\StartsWith;
+use LORIS\Data\Query\Criteria\EndsWith;
+use LORIS\Data\Query\Criteria\Substring;
+
+/**
+ * Tests all operations of the Candidate Identifiers Query Engine.
+ *
+ * @category Tests
+ * @package LORIS
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+class CandidateIdentifiersQueryEngineTest extends TestCase
+{
+ protected \LORIS\candidate_identifiers\QueryEngine $engine;
+ protected $factory;
+ protected $config;
+ protected $DB;
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return void
+ */
+ function setUp() : void
+ {
+ $this->factory = NDB_Factory::singleton();
+ $this->factory->reset();
+
+ $this->config = $this->factory->Config(CONFIG_XML);
+ $database = $this->config->getSetting('database');
+
+ putenv("LORIS_{$database['database']}_USERNAME={$database['username']}");
+ putenv("LORIS_{$database['database']}_PASSWORD={$database['password']}");
+ putenv("LORIS_{$database['database']}_HOST={$database['host']}");
+
+ $this->DB = $this->factory->database();
+ $this->factory->setDatabase($this->DB);
+
+ $this->DB->setFakeTableData(
+ "candidate",
+ [
+ [
+ 'ID' => 1,
+ 'CandID' => "123456",
+ 'PSCID' => "test1",
+ 'RegistrationProjectID' => '1',
+ 'RegistrationCenterID' => '1',
+ 'Active' => 'Y',
+ 'DoB' => '1920-01-30',
+ 'DoD' => '1950-11-16',
+ 'Sex' => 'Male',
+ 'EDC' => null,
+ 'Entity_type' => 'Human',
+ ],
+ [
+ 'ID' => 2,
+ 'CandID' => "123457",
+ 'PSCID' => "test2",
+ 'RegistrationProjectID' => '1',
+ 'RegistrationCenterID' => '2',
+ 'Active' => 'Y',
+ 'DoB' => '1930-05-03',
+ 'DoD' => null,
+ 'Sex' => 'Female',
+ 'EDC' => '1930-04-01',
+ 'Entity_type' => 'Human',
+ ],
+ [
+ 'ID' => 3,
+ 'CandID' => "123458",
+ 'PSCID' => "test3",
+ 'RegistrationProjectID' => '1',
+ 'RegistrationCenterID' => '3',
+ 'Active' => 'N',
+ 'DoB' => '1940-01-01',
+ 'Sex' => 'Other',
+ 'EDC' => '1930-04-01',
+ 'Entity_type' => 'Human',
+ ],
+ ]
+ );
+
+ $this->DB->setFakeTableData(
+ "candidate_identifier_types",
+ [
+ [
+ 'CandidateIdentifierTypeID' => 1,
+ 'Name' => 'PSCID',
+ 'Format' => '{SITE:ALIAS}'
+ . '{SEQUENCE:4,FORMAT:alphanumeric,PADDING:0}',
+ 'AllowMultiple' => 0,
+ 'permID' => null,
+
+ 'IsRequired' => 1,
+ 'IsUnique' => 1,
+ 'AutoGenerate' => 1,
+ ],
+ [
+ 'CandidateIdentifierTypeID' => 2,
+ 'Name' => 'ExternalID',
+ 'Format' => '{ALPHANUMERIC:8}',
+ 'AllowMultiple' => 0,
+ 'permID' => null,
+ 'IsRequired' => 0,
+ 'IsUnique' => 1,
+ 'AutoGenerate' => 0,
+ ],
+ [
+ 'CandidateIdentifierTypeID' => 3,
+ 'Name' => 'AlternateID',
+ 'Format' => '{ALPHANUMERIC:8}',
+ 'AllowMultiple' => 1,
+ 'permID' => null,
+ 'IsRequired' => 0,
+ 'IsUnique' => 0,
+ 'AutoGenerate' => 0,
+ ],
+ ]
+ );
+
+ $this->DB->setFakeTableData(
+ "candidate_identifiers",
+ [
+ [
+ 'CandidateIdentifierID' => 1,
+ 'CandidateID' => 1,
+ 'CandidateIdentifierTypeID' => 1,
+ 'Value' => 'test1',
+ ],
+ [
+ 'CandidateIdentifierID' => 2,
+ 'CandidateID' => 2,
+ 'CandidateIdentifierTypeID' => 1,
+ 'Value' => 'test2',
+ ],
+ [
+ 'CandidateIdentifierID' => 3,
+ 'CandidateID' => 1,
+ 'CandidateIdentifierTypeID' => 2,
+ 'Value' => 'EXT001',
+ ],
+ [
+ 'CandidateIdentifierID' => 4,
+ 'CandidateID' => 2,
+ 'CandidateIdentifierTypeID' => 2,
+ 'Value' => 'EXT002',
+ ],
+ [
+ 'CandidateIdentifierID' => 5,
+ 'CandidateID' => 1,
+ 'CandidateIdentifierTypeID' => 3,
+ 'Value' => 'ALT001',
+ ],
+ [
+ 'CandidateIdentifierID' => 6,
+ 'CandidateID' => 1,
+ 'CandidateIdentifierTypeID' => 3,
+ 'Value' => 'ALT002',
+ ],
+ ]
+ );
+
+ $this->DB->setFakeTableData(
+ "candidate_identifier_types_project_rel",
+ []
+ );
+
+ // Ensure tests are run using this module directory with no overrides.
+ // We are in test, so .. brings us to candidate_parameters and ../../ brings
+ // us to modules for the LorisInstance config.
+ $lorisinstance = new \LORIS\LorisInstance(
+ $this->DB,
+ $this->config,
+ [__DIR__ . "/../../"]
+ );
+
+ $engine = $lorisinstance->getModule(
+ 'candidate_identifiers'
+ )->getQueryEngines()[0];
+
+ assert($engine instanceof \LORIS\candidate_identifiers\QueryEngine);
+
+ $this->engine = $engine;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return void
+ */
+ function tearDown() : void
+ {
+ $this->DB->run("DROP TEMPORARY TABLE IF EXISTS candidate");
+ $this->DB->run("DROP TEMPORARY TABLE IF EXISTS candidate_identifiers");
+ $this->DB->run("DROP TEMPORARY TABLE IF EXISTS candidate_identifier_types");
+ $this->DB->run(
+ "DROP TEMPORARY TABLE IF EXISTS candidate_identifier_types_project_rel"
+ );
+ }
+
+ /**
+ * Test that matching configurable identifier values returns
+ * the correct CandIDs.
+ *
+ * @return void
+ */
+ public function testIdentifierMatches()
+ {
+ $candiddict = $this->_getDictItem("Identifier_1");
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new Equal("test1"))
+ )
+ );
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+
+ // 123456 is equal, and 123458 is Active='N', so we should only get 123457
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new NotEqual("test1"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new In("test2"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new In("test2", "test1"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new GreaterThanOrEqual("test1"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new GreaterThan("test1"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new LessThanOrEqual("test2"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new LessThan("test2"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new IsNull())
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(0, count($result));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new NotNull())
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new StartsWith("test"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new StartsWith("EXT"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(0, count($result));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new StartsWith("test1"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new EndsWith("1"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+
+ // No configured identifier ends with "3".
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new EndsWith("3"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(0, count($result));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new Substring("est"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+ }
+
+ /**
+ * Test that matching PSCID fields matches the correct
+ * CandIDs.
+ *
+ * @return void
+ */
+ public function testExternalIdentifierMatches()
+ {
+ $candiddict = $this->_getDictItem("Identifier_2");
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new Equal("EXT001"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new NotEqual("EXT001"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new In("EXT001"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new StartsWith("EXT"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new EndsWith("002"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new Substring("XT"))
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new IsNull())
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(0, count($result));
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new NotNull())
+ )
+ );
+ $this->assertTrue(is_array($result));
+ assert(is_array($result)); // for phan to know the type
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+
+ // No LessThan/GreaterThan/etc since PSCID is a string
+ }
+
+ /**
+ * Test retrieval of configurable candidate identifiers.
+ *
+ * @return void
+ */
+ function testGetCandidateData()
+ {
+ $results = iterator_to_array(
+ $this->engine->getCandidateData(
+ [
+ $this->_getDictItem("Identifier_1"),
+ $this->_getDictItem("Identifier_2"),
+ ],
+ [new CandID("123456")],
+ null
+ )
+ );
+
+ $this->assertEquals(
+ [
+ '123456' => [
+ 'Identifier_1' => 'test1',
+ 'Identifier_2' => 'EXT001',
+ ],
+ ],
+ $results
+ );
+ }
+
+ /**
+ * Test retrieval of multiple values for a candidate identifier.
+ *
+ * @return void
+ */
+ public function testGetMultipleCandidateIdentifiers()
+ {
+ $results = iterator_to_array(
+ $this->engine->getCandidateData(
+ [$this->_getDictItem("Identifier_3")],
+ [new CandID("123456")],
+ null
+ )
+ );
+
+ $this->assertArrayHasKey('123456', $results);
+
+ $candidateData = $results['123456'];
+
+ if (!is_array($candidateData)) {
+ $this->fail('Expected candidate data to be an array.');
+ }
+
+ $this->assertArrayHasKey('Identifier_3', $candidateData);
+
+ $identifier = $candidateData['Identifier_3'];
+
+ $this->assertEquals(
+ 'Candidate Identifier ID',
+ $identifier['keytype']
+ );
+
+ $this->assertEquals(
+ [
+ 5 => 'ALT001',
+ 6 => 'ALT002',
+ ],
+ $identifier['values']
+ );
+ }
+
+ /**
+ * Assert that nothing matched in a result.
+ *
+ * @param iterable $result The result of getCandidateMatches
+ *
+ * @return void
+ */
+ protected function assertMatchNone($result)
+ {
+ if (!is_array($result)) {
+ $result = iterator_to_array($result);
+ }
+ $this->assertTrue(is_array($result));
+ $this->assertEquals(0, count($result));
+ }
+
+ /**
+ * Assert that exactly 1 result matched and it was $candid
+ *
+ * @param iterable $result The result of getCandidateMatches
+ * @param string $candid The expected CandID
+ *
+ * @return void
+ */
+ protected function assertMatchOne($result, $candid)
+ {
+ if (!is_array($result)) {
+ $result = iterator_to_array($result);
+ }
+ $this->assertTrue(is_array($result));
+ $this->assertEquals(1, count($result));
+ $this->assertEquals($result[0], new CandID($candid));
+ }
+
+ /**
+ * Assert that a query matched all candidates from the test.
+ *
+ * @param iterable $result The result of getCandidateMatches
+ *
+ * @return void
+ */
+ protected function assertMatchAll($result)
+ {
+ if (!is_array($result)) {
+ $result = iterator_to_array($result);
+ }
+ $this->assertTrue(is_array($result));
+ $this->assertEquals(2, count($result));
+ $this->assertEquals($result[0], new CandID("123456"));
+ $this->assertEquals($result[1], new CandID("123457"));
+ }
+
+ /**
+ * Test that identifier project restrictions are respected.
+ *
+ * @return void
+ */
+ public function testIdentifierProjectRestrictions()
+ {
+ $this->DB->run(
+ "INSERT INTO candidate_identifier_types_project_rel
+ (CandidateIdentifierTypeID, ProjectID)
+ VALUES (2, 2)"
+ );
+
+ $candiddict = $this->_getDictItem("Identifier_2");
+
+ $result = iterator_to_array(
+ $this->engine->getCandidateMatches(
+ new QueryTerm($candiddict, new Equal("EXT001"))
+ )
+ );
+
+ $this->assertEquals(0, count($result));
+ }
+
+ /**
+ * Gets a dictionary item named $name, in any
+ * category.
+ *
+ * @param string $name The dictionary item name
+ *
+ * @return \LORIS\Data\Dictionary\DictionaryItem
+ */
+ private function _getDictItem(string $name)
+ {
+ $categories = $this->engine->getDataDictionary();
+ foreach ($categories as $category) {
+ $items = $category->getItems();
+ foreach ($items as $item) {
+ if ($item->getName() == $name) {
+ return $item;
+ }
+ }
+ }
+ throw new \Exception("Could not get dictionary item");
+ }
+}
diff --git a/modules/candidate_parameters/locale/candidate_parameters.pot b/modules/candidate_parameters/locale/candidate_parameters.pot
index b906187b17..18a07c1a8c 100644
--- a/modules/candidate_parameters/locale/candidate_parameters.pot
+++ b/modules/candidate_parameters/locale/candidate_parameters.pot
@@ -321,6 +321,9 @@ msgstr ""
msgid "The project for which this candidate was initially registered"
msgstr ""
+msgid "Legacy Candidate Identifiers"
+msgstr ""
+
# Widgets
msgid "Consent Summary"
msgstr ""
diff --git a/modules/candidate_parameters/locale/fr/LC_MESSAGES/candidate_parameters.po b/modules/candidate_parameters/locale/fr/LC_MESSAGES/candidate_parameters.po
index 59bcd78452..2c07ca9383 100644
--- a/modules/candidate_parameters/locale/fr/LC_MESSAGES/candidate_parameters.po
+++ b/modules/candidate_parameters/locale/fr/LC_MESSAGES/candidate_parameters.po
@@ -304,6 +304,9 @@ msgstr "Site où ce candidat a été initialement enregistré"
msgid "The project for which this candidate was initially registered"
msgstr "Projet pour lequel ce candidat a été initialement enregistré"
+msgid "Legacy Candidate Identifiers"
+msgstr "Anciens identifiants des candidats"
+
# Widgets
msgid "Consent Summary"
msgstr "Résumé du consentement"
diff --git a/modules/candidate_parameters/php/candidatequeryengine.class.inc b/modules/candidate_parameters/php/candidatequeryengine.class.inc
index 78d9febcf9..543096cc6c 100644
--- a/modules/candidate_parameters/php/candidatequeryengine.class.inc
+++ b/modules/candidate_parameters/php/candidatequeryengine.class.inc
@@ -29,7 +29,7 @@ class CandidateQueryEngine extends \LORIS\Data\Query\SQLQueryEngine
$ids = new \LORIS\Data\Dictionary\Category(
"Identifiers",
- dgettext("candidate_parameters", "Candidate Identifiers")
+ dgettext("candidate_parameters", "Legacy Candidate Identifiers")
);
$ids = $ids->withItems(
diff --git a/modules/configuration/ajax/updateCandidateIdentifierType.php b/modules/configuration/ajax/updateCandidateIdentifierType.php
new file mode 100644
index 0000000000..2610a8ac8e
--- /dev/null
+++ b/modules/configuration/ajax/updateCandidateIdentifierType.php
@@ -0,0 +1,155 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+
+$user = \User::singleton();
+if (!$user->hasPermission('config')) {
+ header("HTTP/1.1 403 Forbidden");
+ exit(0);
+}
+
+header('Content-Type: application/json');
+
+$client = new NDB_Client();
+$client->makeCommandLine();
+$client->initialize();
+
+$factory = NDB_Factory::singleton();
+$db = $factory->database();
+$controller = new \LORIS\IdentifierTypeController($db);
+
+$identifierTypeID = $_POST['CandidateIdentifierTypeID'] ?? null;
+$name = trim($_POST['Name'] ?? '');
+$format = trim($_POST['Format'] ?? '');
+$projectIDs = $_POST['ProjectIDs'] ?? [];
+
+if (empty($name)
+ || empty($format)
+ || ($identifierTypeID !== 'new'
+ && filter_var($identifierTypeID, FILTER_VALIDATE_INT) === false)
+ || ($identifierTypeID !== 'new'
+ && (int) $identifierTypeID <= 0)
+ || !is_array($projectIDs)
+) {
+ http_response_code(400);
+ echo json_encode(['error' => 'Bad Request']);
+ exit(0);
+}
+
+foreach ($projectIDs as $projectID) {
+ if (filter_var($projectID, FILTER_VALIDATE_INT) === false
+ || (int) $projectID <= 0
+ ) {
+ http_response_code(400);
+ echo json_encode(['error' => 'Invalid ProjectID']);
+ exit(0);
+ }
+}
+
+$isRequired = ($_POST['IsRequired'] ?? '0') === '1';
+$isUnique = ($_POST['IsUnique'] ?? '0') === '1';
+$autoGenerate = ($_POST['AutoGenerate'] ?? '0') === '1';
+$allowMultiple = ($_POST['AllowMultiple'] ?? '0') === '1';
+
+try {
+ $existingType = null;
+
+ try {
+ $existingType = $controller->getIdentifierTypeFromName($name);
+ } catch (\NotFound $e) {
+ // No identifier type with this name exists.
+ }
+
+ if ($existingType !== null
+ && ($identifierTypeID === 'new'
+ || $existingType->candidateIdentifierTypeID !== (int) $identifierTypeID)
+ ) {
+ http_response_code(409);
+ echo json_encode(
+ ['error' => 'Failed to save, identifier type name already exists!']
+ );
+ exit(0);
+ }
+
+ $projects = array_map(
+ function ($projectID) {
+ return \Project::getProjectFromID(
+ \ProjectID::singleton((int) $projectID)
+ );
+ },
+ $projectIDs
+ );
+
+ if ($identifierTypeID === 'new') {
+ $identifierType = new \LORIS\IdentifierType(
+ null,
+ $name,
+ $format,
+ $isRequired,
+ $isUnique,
+ $autoGenerate,
+ $allowMultiple,
+ $projects
+ );
+
+ if ($autoGenerate) {
+ new \CandidateIdentifierGenerator($db, $identifierType, '', '');
+ }
+
+ $controller->createIdentifierType($identifierType);
+ } else {
+ $identifierType = $controller->getIdentifierTypeFromID(
+ (int) $identifierTypeID
+ );
+
+ if ($identifierType->name === 'PSCID' && $name !== 'PSCID') {
+ http_response_code(400);
+ echo json_encode(
+ ['error' => 'The PSCID identifier type cannot be renamed.']
+ );
+ exit(0);
+ }
+
+ $identifierType->name = $name;
+ $identifierType->format = $format;
+ $identifierType->isRequired = $isRequired;
+ $identifierType->isUnique = $isUnique;
+ $identifierType->autoGenerate = $autoGenerate;
+ $identifierType->allowMultiple = $allowMultiple;
+ $identifierType->projects = $projects;
+
+ if ($autoGenerate) {
+ new \CandidateIdentifierGenerator($db, $identifierType, '', '');
+ }
+
+ $controller->updateIdentifierType($identifierType);
+ }
+} catch (\ConfigurationException $e) {
+ http_response_code(400);
+ echo json_encode(['error' => $e->getMessage()]);
+ exit(0);
+} catch (\NotFound $e) {
+ http_response_code(404);
+ echo json_encode(['error' => 'Not Found']);
+ exit(0);
+} catch (\Throwable $e) {
+ error_log($e->getMessage());
+ http_response_code(500);
+ echo json_encode(['error' => 'Internal Server Error']);
+ exit(0);
+}
+
+http_response_code(200);
+echo json_encode(['ok' => 'Success']);
+exit(0);
diff --git a/modules/configuration/jsx/formCandidateIdentifierTypes.tsx b/modules/configuration/jsx/formCandidateIdentifierTypes.tsx
new file mode 100644
index 0000000000..482816caa6
--- /dev/null
+++ b/modules/configuration/jsx/formCandidateIdentifierTypes.tsx
@@ -0,0 +1,553 @@
+import React, {useEffect, useState} from 'react';
+import {createRoot} from 'react-dom/client';
+import {
+ withTranslation,
+ WithTranslation,
+} from 'react-i18next';
+
+import {Errors} from 'jslib';
+import i18n from 'I18nSetup';
+import Loader from 'Loader';
+import {TabPane, VerticalTabs} from 'Tabs';
+import {
+ FormElement,
+ TextboxElement,
+ SelectElement,
+ CheckboxElement,
+ ButtonElement,
+} from 'jsx/Form';
+
+import {client} from 'jslib/http';
+import * as StudyEntity from './studyEntities';
+
+import jaStrings from '../locale/ja/LC_MESSAGES/configuration.json';
+import frStrings from '../locale/fr/LC_MESSAGES/configuration.json';
+import zhStrings from '../locale/zh/LC_MESSAGES/configuration.json';
+
+type IdentifierType = {
+ candidateIdentifierTypeID: number,
+ name: string,
+ format: string,
+ isRequired: boolean,
+ isUnique: boolean,
+ autoGenerate: boolean,
+ allowMultiple: boolean,
+ projectIDs: string[],
+};
+
+type IdentifierTypeData = {
+ identifierTypes: Record,
+ projects: Record,
+};
+
+type IdentifierTypeValues = {
+ name: string,
+ format: string,
+ isRequired: boolean,
+ isUnique: boolean,
+ autoGenerate: boolean,
+ allowMultiple: boolean,
+ projectIDs: string[],
+};
+
+type SaveStatus = {
+ message: string,
+ type: 'error' | 'success',
+} | null;
+
+type IdentifierTypeManagerProps = {
+ data: IdentifierTypeData,
+ t: WithTranslation['t'],
+};
+
+type IdentifierTypeFormProps = {
+ identifierType: IdentifierType,
+ identifierTypeID: string,
+ isNew: boolean,
+ projects: Record,
+ onSaved: (id: string, values: IdentifierTypeValues) => void,
+ t: WithTranslation['t'],
+};
+
+const EMPTY_IDENTIFIER_TYPE: IdentifierType = {
+ candidateIdentifierTypeID: 0,
+ name: '',
+ format: '',
+ isRequired: false,
+ isUnique: false,
+ autoGenerate: false,
+ allowMultiple: false,
+ projectIDs: [],
+};
+
+/**
+ * Convert server data into controlled form values.
+ *
+ * @param identifierType Identifier type
+ * @return
+ */
+function formValues(
+ identifierType: IdentifierType
+): IdentifierTypeValues {
+ return {
+ name: identifierType.name,
+ format: identifierType.format,
+ isRequired: identifierType.isRequired,
+ isUnique: identifierType.isUnique,
+ autoGenerate: identifierType.autoGenerate,
+ allowMultiple: identifierType.allowMultiple,
+ projectIDs: identifierType.projectIDs.map(String),
+ };
+}
+
+/**
+ * Create or edit one candidate identifier type.
+ *
+ * @param props Form properties
+ * @return
+ */
+function IdentifierTypeForm(
+ props: IdentifierTypeFormProps
+): React.ReactElement {
+ const [defaults, setDefaults] = useState(
+ () => formValues(props.identifierType)
+ );
+ const [values, setValues] = useState(defaults);
+ const [status, setStatus] = useState(null);
+ const [saving, setSaving] = useState(false);
+
+ /**
+ * Update one controlled form field.
+ *
+ * @param name Field name
+ * @param value New value
+ */
+ const updateValue = (
+ name: string,
+ value: string | string[] | boolean
+ ) => {
+ setValues((current) => ({
+ ...current,
+ [name]: value,
+ }));
+ setStatus(null);
+ };
+
+ /**
+ * Validate required fields.
+ *
+ * @return Error message or null
+ */
+ const validationError = (): string | null => {
+ if (!values.name.trim()) {
+ return props.t(
+ 'Failed to save, must enter an identifier type name!',
+ {ns: 'configuration'}
+ );
+ }
+
+ if (!values.format.trim()) {
+ return props.t(
+ 'Failed to save, must enter an identifier format!',
+ {ns: 'configuration'}
+ );
+ }
+
+ return null;
+ };
+
+ /**
+ * Submit the form to the existing AJAX endpoint.
+ *
+ * @param event Submit event
+ */
+ const submit = async (event: React.SyntheticEvent) => {
+ event.preventDefault();
+
+ const error = validationError();
+
+ if (error !== null) {
+ setStatus({
+ message: error,
+ type: 'error',
+ });
+ return;
+ }
+
+ setSaving(true);
+ setStatus(null);
+
+ const body = new URLSearchParams({
+ CandidateIdentifierTypeID: props.identifierTypeID,
+ Name: values.name.trim(),
+ Format: values.format.trim(),
+ IsRequired: values.isRequired ? '1' : '0',
+ IsUnique: values.isUnique ? '1' : '0',
+ AutoGenerate: values.autoGenerate ? '1' : '0',
+ AllowMultiple: values.allowMultiple ? '1' : '0',
+ });
+
+ values.projectIDs.forEach((projectID) => {
+ body.append('ProjectIDs[]', projectID);
+ });
+
+ try {
+ await StudyEntity.save(
+ 'configuration/ajax/updateCandidateIdentifierType.php',
+ body
+ );
+
+ setDefaults({...values});
+
+ setStatus({
+ message: props.t(
+ 'Successfully saved',
+ {ns: 'configuration'}
+ ),
+ type: 'success',
+ });
+
+ if (props.isNew) {
+ window.setTimeout(() => window.location.reload(), 1000);
+ } else {
+ props.onSaved(props.identifierTypeID, values);
+ }
+ } catch (error) {
+ const conflict = error instanceof Errors.ApiResponse
+ && error.response?.status === 409;
+ setStatus({
+ message: error instanceof Error && !conflict
+ ? error.message
+ : props.t(
+ 'Failed to save, same name already exist!',
+ {ns: 'configuration'}
+ ),
+ type: 'error',
+ });
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const fieldPrefix = props.isNew
+ ? 'new-identifier-type'
+ : `identifier-type-${props.identifierTypeID}`;
+
+ return (
+
+
+
+ );
+}
+
+/**
+ * React candidate identifier type manager.
+ *
+ * @param props Page properties
+ * @return
+ */
+function IdentifierTypeManager(
+ props: IdentifierTypeManagerProps
+): React.ReactElement {
+ const [identifierTypes, setIdentifierTypes] = useState(
+ props.data.identifierTypes
+ );
+
+ /**
+ * Update the displayed name after saving.
+ *
+ * @param id Identifier type ID
+ * @param values Updated form values
+ */
+ const updateIdentifierType = (
+ id: string,
+ values: IdentifierTypeValues
+ ) => {
+ setIdentifierTypes((current) => ({
+ ...current,
+ [id]: {
+ ...current[id],
+ ...values,
+ },
+ }));
+ };
+
+ return (
+ <>
+
+ {props.t(
+ 'Use this page to manage the configuration of existing candidate'
+ + ' identifier types, or to add a new one.',
+ {ns: 'configuration'}
+ )}
+
);
}
diff --git a/modules/configuration/locale/configuration.pot b/modules/configuration/locale/configuration.pot
index fff2be46a8..f8bf58e063 100644
--- a/modules/configuration/locale/configuration.pot
+++ b/modules/configuration/locale/configuration.pot
@@ -60,9 +60,6 @@ msgstr ""
msgid "Please enter the various configuration variables into the fields below. For information on how to configure LORIS, please refer to the Help section and/or the Developer's guide."
msgstr ""
-msgid "To configure study cohorts"
-msgstr ""
-
msgid "click here"
msgstr ""
@@ -72,6 +69,9 @@ msgstr ""
msgid "To configure study projects <0>click here0>."
msgstr ""
+msgid "To configure candidate identifier types <0>click here0>."
+msgstr ""
+
msgid "To configure the diagnosis trajectory of the study <0>click here0>."
msgstr ""
@@ -266,3 +266,48 @@ msgstr ""
msgid "Conflict!"
msgstr ""
+
+msgid "Use this page to manage the configuration of existing candidate identifier types, or to add a new one."
+msgstr ""
+
+msgid "New Identifier Type"
+msgstr ""
+
+msgid "Name"
+msgstr ""
+
+msgid "Format"
+msgstr ""
+
+msgid "Required"
+msgstr ""
+
+msgid "Unique"
+msgstr ""
+
+msgid "Auto Generate"
+msgstr ""
+
+msgid "Allow Multiple"
+msgstr ""
+
+msgid "Identifier name, e.g. PSCID or ExternalID"
+msgstr ""
+
+msgid "Template used to generate or validate identifier values."
+msgstr ""
+
+msgid "Whether candidates using this identifier type must have at least one value"
+msgstr ""
+
+msgid "Whether identifier values must be unique across candidates"
+msgstr ""
+
+msgid "Whether LORIS generates the value automatically from the format"
+msgstr ""
+
+msgid "Whether a candidate can have more than one value of this type"
+msgstr ""
+
+msgid "Projects in which this identifier type can be used. An identifier type can be associated with multiple projects."
+msgstr ""
diff --git a/modules/configuration/locale/fr/LC_MESSAGES/configuration.po b/modules/configuration/locale/fr/LC_MESSAGES/configuration.po
index c9559f8d70..b888e51017 100644
--- a/modules/configuration/locale/fr/LC_MESSAGES/configuration.po
+++ b/modules/configuration/locale/fr/LC_MESSAGES/configuration.po
@@ -61,9 +61,6 @@ msgstr "Après l'ajout d'une nouvelle cohorte, les libellés de visite de cette
msgid "Please enter the various configuration variables into the fields below. For information on how to configure LORIS, please refer to the Help section and/or the Developer's guide."
msgstr "Veuillez saisir les différentes variables de configuration dans les champs ci-dessous. Pour savoir comment configurer LORIS, consultez la section Aide et/ou le guide du développeur."
-msgid "To configure study cohorts"
-msgstr "Pour configurer les cohortes de l'étude"
-
msgid "click here"
msgstr "cliquez ici"
@@ -73,6 +70,9 @@ msgstr "Pour configurer les cohortes de l'étude, <0>cliquez ici0>."
msgid "To configure study projects <0>click here0>."
msgstr "Pour configurer les projets de l'étude, <0>cliquez ici0>."
+msgid "To configure candidate identifier types <0>click here0>."
+msgstr "Pour configurer les types d'identifiants de candidats, <0>cliquez ici0>."
+
msgid "To configure the diagnosis trajectory of the study <0>click here0>."
msgstr "Pour configurer la trajectoire diagnostique de l'étude, <0>cliquez ici0>."
@@ -225,3 +225,48 @@ msgstr "Valeur correspondante"
msgid "Conflict!"
msgstr "Conflit !"
+
+msgid "Use this page to manage the configuration of existing candidate identifier types, or to add a new one."
+msgstr "Utilisez cette page pour gérer la configuration des types d’identifiants de candidats existants ou pour en ajouter un nouveau."
+
+msgid "New Identifier Type"
+msgstr "Nouveau type d'identifiant"
+
+msgid "Name"
+msgstr "Nom"
+
+msgid "Format"
+msgstr "Format"
+
+msgid "Required"
+msgstr "Obligatoire"
+
+msgid "Unique"
+msgstr "Unique"
+
+msgid "Auto Generate"
+msgstr "Génération automatique"
+
+msgid "Allow Multiple"
+msgstr "Autoriser plusieurs valeurs"
+
+msgid "Identifier name, e.g. PSCID or ExternalID"
+msgstr "Nom de l'identifiant, p. ex. PSCID ou ExternalID"
+
+msgid "Template used to generate or validate identifier values."
+msgstr "Modèle utilisé pour générer ou valider les valeurs des identifiants."
+
+msgid "Whether candidates using this identifier type must have at least one value"
+msgstr "Indique si les candidats utilisant ce type d'identifiant doivent avoir au moins une valeur"
+
+msgid "Whether identifier values must be unique across candidates"
+msgstr "Indique si les valeurs des identifiants doivent être uniques parmi les candidats"
+
+msgid "Whether LORIS generates the value automatically from the format"
+msgstr "Indique si LORIS génère automatiquement la valeur à partir du format"
+
+msgid "Whether a candidate can have more than one value of this type"
+msgstr "Indique si un candidat peut avoir plusieurs valeurs de ce type"
+
+msgid "Projects in which this identifier type can be used. An identifier type can be associated with multiple projects."
+msgstr "Projets dans lesquels ce type d'identifiant peut être utilisé. Un type d'identifiant peut être associé à plusieurs projets."
diff --git a/modules/configuration/php/candidate_identifier_types.class.inc b/modules/configuration/php/candidate_identifier_types.class.inc
new file mode 100644
index 0000000000..0dbc2bf49b
--- /dev/null
+++ b/modules/configuration/php/candidate_identifier_types.class.inc
@@ -0,0 +1,137 @@
+
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+
+namespace LORIS\configuration;
+
+/**
+ * Candidate_Identifier_Types Class
+ *
+ * This class is used to configure candidate identifier types.
+ *
+ * @category Behavioural
+ * @package Main
+ * @author Jad El Hachem
+ * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
+ * @link https://github.com/aces/Loris
+ */
+class Candidate_Identifier_Types extends \NDB_Form
+{
+ /**
+ * Render the candidate identifier type manager with React.
+ *
+ * @var bool
+ */
+ public $skipTemplate = true;
+
+ /**
+ * Determine whether the user can configure identifier types.
+ *
+ * @param \User $user The user whose access is being checked
+ *
+ * @return bool
+ */
+ #[\Override]
+ public function isAccessibleBy(\User $user) : bool
+ {
+ return $user->hasPermission('config');
+ }
+
+ /**
+ * Load candidate identifier types and available projects.
+ *
+ * @return void
+ */
+ function setup()
+ {
+ parent::setup();
+
+ $factory = \NDB_Factory::singleton();
+ $controller = new \LORIS\IdentifierTypeController(
+ $factory->database()
+ );
+
+ $identifierTypes = [];
+
+ foreach ($controller->getAllIdentifierTypes() as $identifierType) {
+ $id = $identifierType->candidateIdentifierTypeID;
+
+ $identifierTypes[$id] = [
+ 'candidateIdentifierTypeID' => $id,
+ 'name' => $identifierType->name,
+ 'format' => $identifierType->format,
+ 'isRequired' => $identifierType->isRequired,
+ 'isUnique' => $identifierType->isUnique,
+ 'autoGenerate' => $identifierType->autoGenerate,
+ 'allowMultiple' => $identifierType->allowMultiple,
+ 'projectIDs' => array_map(
+ static fn($project) => strval($project->getId()),
+ $identifierType->projects
+ ),
+ ];
+ }
+
+ $this->tpl_data['identifierTypes'] = $identifierTypes;
+ $this->tpl_data['projects'] = \Utility::getProjectList();
+ }
+
+ /**
+ * Return the identifier type manager data for the React page.
+ *
+ * @return array
+ */
+ #[\Override]
+ function toArray(): array
+ {
+ return [
+ 'identifierTypes' => $this->tpl_data['identifierTypes'] ?? [],
+ 'projects' => $this->tpl_data['projects'] ?? [],
+ ];
+ }
+
+ /**
+ * Include the configuration stylesheet.
+ *
+ * @return array CSS dependencies
+ */
+ #[\Override]
+ function getCSSDependencies(): array
+ {
+ $factory = \NDB_Factory::singleton();
+ $baseURL = $factory->settings()->getBaseURL();
+ $deps = parent::getCSSDependencies();
+
+ return array_merge(
+ $deps,
+ [$baseURL . '/configuration/css/configuration.css']
+ );
+ }
+
+ /**
+ * Add the React entry point for the identifier type manager.
+ *
+ * @return array JavaScript dependencies
+ */
+ #[\Override]
+ function getJSDependencies(): array
+ {
+ $factory = \NDB_Factory::singleton();
+ $baseURL = $factory->settings()->getBaseURL();
+ $deps = parent::getJSDependencies();
+
+ return array_merge(
+ $deps,
+ [$baseURL . '/configuration/js/formCandidateIdentifierTypes.js']
+ );
+ }
+}
diff --git a/modules/dataquery/jsx/viewdata.tsx b/modules/dataquery/jsx/viewdata.tsx
index 2754644c86..fe33d37a93 100644
--- a/modules/dataquery/jsx/viewdata.tsx
+++ b/modules/dataquery/jsx/viewdata.tsx
@@ -499,6 +499,38 @@ function ViewData(props: {
;
}
+/**
+ * Formats multiple values for a candidate-level field.
+ *
+ * @param cell - JSON-encoded cell value
+ * @param dictionary - Field dictionary item
+ * @param module - Module providing the field
+ * @param separator - Separator between values
+ * @returns - Formatted values, or null if parsing fails
+ */
+function formatCandidateManyValues(
+ cell: string,
+ dictionary: FieldDictionary,
+ module: string,
+ separator = ';'
+): string | null {
+ try {
+ const values = JSON.parse(cell || '{}').values || {};
+
+ return Object.keys(values)
+ .map((key) => {
+ if (dictionary.type === 'URI' ||
+ module === 'candidate_identifiers') {
+ return values[key];
+ }
+ return key + '=' + values[key];
+ })
+ .join(separator);
+ } catch (e) {
+ return null;
+ }
+}
+
/**
* Organize the session data into tabular data based on
* the visit organization settings
@@ -627,6 +659,14 @@ function organizeData(
default:
throw new Error('Too many visit values');
}
+ } else if (dictionary?.scope === 'candidate' &&
+ dictionary.cardinality === 'many' &&
+ candidaterow[i]) {
+ dataRow.push(formatCandidateManyValues(
+ candidaterow[i] as string,
+ dictionary,
+ fields[i].module
+ ));
} else {
dataRow.push(candidaterow[i]);
}
@@ -748,7 +788,17 @@ function expandLongitudinalCells(
switch (fielddict.scope) {
case 'candidate':
if (fielddict.cardinality == 'many') {
- throw new Error('Candidate cardinality many not implemented');
+ const display = formatCandidateManyValues(
+ value || '{}',
+ fielddict,
+ fieldobj.module
+ );
+
+ if (display === null) {
+ console.error('Internal error parsing: "' + value + '"');
+ }
+
+ return [{value: display, dictionary: fielddict}];
}
return [{value: value, dictionary: fielddict}];
case 'session':
@@ -830,9 +880,9 @@ function expandLongitudinalCells(
* @param enumDisplay - The format to display
* enum values
* @param t - useTranslation
-
+ *
* @returns - the appropriate column formatter for
- this data organization
+ * this data organization
*/
function organizedFormatter(
resultData: string[][],
@@ -889,8 +939,20 @@ function organizedFormatter(
return
{t('(No data)', {ns: 'dataquery'})}
;
}
switch (fielddict.cardinality) {
- case 'many':
- return