From b01e169fa3620e262cc50403c0555dcdeb273ff8 Mon Sep 17 00:00:00 2001 From: HachemJ Date: Tue, 3 Nov 2026 09:40:51 -0500 Subject: [PATCH 1/4] Refactor candidate identifier domain models and generation logic --- SQL/0000-00-02-Permission.sql | 2 +- ...09-22-add_candidate_identifiers_tables.sql | 2 +- modules/api/php/views/projects.class.inc | 11 +- modules/new_profile/php/new_profile.class.inc | 10 +- php/libraries/Candidate.class.inc | 243 +++-- .../CandidateIdentifierController.class.inc | 436 +++++++++ .../CandidateIdentifierGenerator.php | 202 ++++ php/libraries/IdentifierGenerator.php | 121 ++- php/libraries/IdentifierType.class.inc | 54 ++ .../IdentifierTypeController.class.inc | 298 ++++++ php/libraries/SiteIDGenerator.php | 272 +++--- .../Candidate/CandidateIdentifier.php | 49 + .../CandidateIdentifierControllerTest.php | 875 ++++++++++++++++++ .../CandidateIdentifierGeneratorTest.php | 727 +++++++++++++++ test/unittests/CandidateTest.php | 245 +++-- .../IdentifierTypeControllerTest.php | 453 +++++++++ .../migrate_candidate_identifiers.php | 2 + 17 files changed, 3696 insertions(+), 306 deletions(-) create mode 100644 php/libraries/CandidateIdentifierController.class.inc create mode 100644 php/libraries/CandidateIdentifierGenerator.php create mode 100644 php/libraries/IdentifierType.class.inc create mode 100644 php/libraries/IdentifierTypeController.class.inc create mode 100644 src/StudyEntities/Candidate/CandidateIdentifier.php create mode 100644 test/unittests/CandidateIdentifierControllerTest.php create mode 100644 test/unittests/CandidateIdentifierGeneratorTest.php create mode 100644 test/unittests/IdentifierTypeControllerTest.php diff --git a/SQL/0000-00-02-Permission.sql b/SQL/0000-00-02-Permission.sql index eba3acd35e..cd871f9188 100644 --- a/SQL/0000-00-02-Permission.sql +++ b/SQL/0000-00-02-Permission.sql @@ -351,7 +351,7 @@ INSERT INTO `candidate_identifier_types` VALUES ( 'PSCID', - '{SITE:ALIAS}{SEQUENCE:4,FORMAT:alphanumeric}', + '{SITE:ALIAS}{SEQUENCE:4,FORMAT:alphanumeric,PADDING:0}', 1, 1, 1, 0 ); diff --git a/SQL/New_patches/2026-09-22-add_candidate_identifiers_tables.sql b/SQL/New_patches/2026-09-22-add_candidate_identifiers_tables.sql index 327f7ac8af..5b8b5af536 100644 --- a/SQL/New_patches/2026-09-22-add_candidate_identifiers_tables.sql +++ b/SQL/New_patches/2026-09-22-add_candidate_identifiers_tables.sql @@ -22,7 +22,7 @@ INSERT INTO `candidate_identifier_types` VALUES ( 'PSCID', - '{SITE:ALIAS}{SEQUENCE:4,FORMAT:alphanumeric}', + '{SITE:ALIAS}{SEQUENCE:4,FORMAT:alphanumeric,PADDING:0}', 1, 1, 1, 0 ); diff --git a/modules/api/php/views/projects.class.inc b/modules/api/php/views/projects.class.inc index a6a878425e..912d949666 100644 --- a/modules/api/php/views/projects.class.inc +++ b/modules/api/php/views/projects.class.inc @@ -45,15 +45,16 @@ class Projects public function toArray(): array { $config = \NDB_Factory::singleton()->config(); + $db = \NDB_Factory::singleton()->database(); $useEDC = $config->getSetting("useEDC"); - $PSCID = $config->getSetting("PSCID"); - $PSCIDFormat = \Candidate::structureToPCRE($PSCID['structure'], "SITE"); + $identifierTypeController = new \LORIS\IdentifierTypeController($db); + $PSCIDType = $identifierTypeController->getIdentifierTypeFromName('PSCID'); - $type = in_array($PSCID['generation'], ['sequential', 'random'], true) - ? 'auto' - : 'prompt'; + $PSCIDFormat = \Candidate::structureToPCRE($PSCIDType->format, "SITE"); + + $type = $PSCIDType->autoGenerate ? 'auto' : 'prompt'; $settings = [ "useEDC" => $useEDC, diff --git a/modules/new_profile/php/new_profile.class.inc b/modules/new_profile/php/new_profile.class.inc index bc252653a9..90cd922a26 100644 --- a/modules/new_profile/php/new_profile.class.inc +++ b/modules/new_profile/php/new_profile.class.inc @@ -88,9 +88,13 @@ class New_Profile extends \NDB_Form [] ); - // Get setting through pscid - $PSCIDsettings = $config->getSetting('PSCID'); - if ($PSCIDsettings['generation'] == 'user') { + // Determine whether PSCID must be entered manually + $identifierTypeController = new \LORIS\IdentifierTypeController( + $factory->database() + ); + $PSCIDType = $identifierTypeController->getIdentifierTypeFromName('PSCID'); + + if (!$PSCIDType->autoGenerate) { $pscidSet = "true"; } diff --git a/php/libraries/Candidate.class.inc b/php/libraries/Candidate.class.inc index d644914007..d20f57ffce 100644 --- a/php/libraries/Candidate.class.inc +++ b/php/libraries/Candidate.class.inc @@ -7,6 +7,7 @@ * @license GPLv3 */ +use LORIS\IdentifierTypeController; use LORIS\StudyEntities\Candidate\CandID; use LORIS\StudyEntities\Candidate\EntityType; use LORIS\StudyEntities\Candidate\Sex; @@ -254,6 +255,7 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, * if available * @param ?ProjectID $registrationProjectID The project ID, if available * @param ?int $registrationCohortID The cohort ID, if available + * @param bool $useGenericIdentifiers Whether to use generic identifiers * * @return CandID $candID candidate id of the new candidate * @throws Exception @@ -266,7 +268,8 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, Sex $sex, ?string $PSCID = null, ?ProjectID $registrationProjectID = null, - ?int $registrationCohortID = null + ?int $registrationCohortID = null, + bool $useGenericIdentifiers = false ): CandID { $factory = NDB_Factory::singleton(); $db = $factory->database(); @@ -296,10 +299,13 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, ); } - // figure out how to generate PSCID - $config = $factory->config(); - $PSCIDSettings = $config->getSetting('PSCID'); - $useEDC = $config->getSetting('useEDC'); + // Get PSCID configuration from the database + $config = $factory->config(); + + $identifierTypeController = new IdentifierTypeController($db); + $PSCIDType = $identifierTypeController->getIdentifierTypeFromName('PSCID'); + + $useEDC = $config->getSetting('useEDC'); // Get expected format from config $dobFormat = $config->getSetting('dobFormat'); @@ -355,7 +361,7 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, } } - if ($PSCIDSettings['generation'] == 'user') { + if ($useGenericIdentifiers || !$PSCIDType->autoGenerate) { // check pscid is specified if (empty($PSCID)) { throw new Exception( @@ -390,8 +396,14 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, $project->getAlias() ) ) { + $expected = Candidate::structureToPattern( + $PSCIDType->format, + $site->getSiteAlias(), + $project->getAlias() + ); + throw new LorisException( - "PSCID has an invalid structure", + "PSCID has an invalid structure. Expected format: $expected", PSCID_INVALID_STRUCTURE ); } @@ -420,7 +432,9 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, 'UserID' => $user->getUsername(), ]; - if ($config->getSetting('useExternalID') === 'true') { + if (!$useGenericIdentifiers + && $config->getSetting('useExternalID') === 'true' + ) { $externalID = (new \ExternalIDGenerator( $site->getSiteAlias(), $project->getAlias() @@ -1032,11 +1046,13 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, ): bool { $factory = NDB_Factory::singleton(); - $config = $factory->config(); + $db = $factory->database(); + + $identifierTypeController = new IdentifierTypeController($db); + $PSCIDType = $identifierTypeController->getIdentifierTypeFromName('PSCID'); - $PSCIDSettings = $config->getSetting('PSCID'); - $regex = self::structureToPCRE( - $PSCIDSettings['structure'], + $regex = self::structureToPCRE( + $PSCIDType->format, $siteAbbrev, $projectAbbrev ); @@ -1220,11 +1236,95 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, return $latestDx['DxEvolutionID'] ?? null; } + /** + * Transforms an identifier template into a human-readable pattern. + * + * @param string $structure the identifier template + * @param string|null $siteAbbrev the site abbreviation + * @param string|null $projectAbbrev the project abbreviation + * + * @return string the human-readable identifier pattern + */ + static function structureToPattern( + string $structure, + ?string $siteAbbrev = null, + ?string $projectAbbrev = null + ): string { + $pattern = str_replace( + ['{SITE:ALIAS}', '{PROJECT:ALIAS}'], + [$siteAbbrev ?? '', $projectAbbrev ?? ''], + $structure + ); + + $description = 'number (0-9)'; + $constraints = []; + + $pattern = preg_replace_callback( + '/\{(SEQUENCE|RANDOM):(\d+)([^}]*)\}/i', + function ($matches) use (&$description, &$constraints) { + $length = intval($matches[2]); + $options = $matches[3]; + + if (preg_match( + '/FORMAT:(numeric|alphanumeric|alpha)/i', + $options, + $type + ) + ) { + switch (strtolower($type[1])) { + case 'alpha': + $description = 'letter (A-Z)'; + break; + + case 'alphanumeric': + $description = 'number (0-9) or letter (A-Z)'; + break; + } + } + + $min = null; + $max = null; + + if (preg_match('/MIN:(\d+)/i', $options, $match)) { + $min = $match[1]; + } + + if (preg_match('/MAX:(\d+)/i', $options, $match)) { + $max = $match[1]; + } + + if ($min !== null && $max !== null) { + $constraints[] = "The value must be between $min and $max."; + } elseif ($min !== null) { + $constraints[] = "The value must be at least $min."; + } elseif ($max !== null) { + $constraints[] = "The value must be at most $max."; + } + + if (!preg_match('/(?:^|,)PADDING:/i', $options)) { + $constraints[] + = "The length must be between 1 and $length characters."; + return '#'; + } + return str_repeat('#', $length); + }, + $pattern + ); + + $result = "$pattern, where # represents a $description."; + + if ($constraints !== []) { + $result .= ' ' . implode(' ', $constraints); + } + + return $result; + } + /** * Transforms a config structure (such as in PSCID) into a * Perl-compatible regex expression for validation * - * @param array $structure the structure root + * @param string $structure the identifier template * @param string|null $siteAbbrev the site abbreviation, sometimes used as * part of the PSCID * @param string|null $projectAbbrev the project abbreviation @@ -1236,76 +1336,79 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, * @cleanup */ static function structureToPCRE( - array $structure, + string $structure, ?string $siteAbbrev = null, ?string $projectAbbrev = null ): string { - $seqs = $structure['seq']; - // handle the situation where there exists only one seq - if (isset($seqs['#'])) { - $seqs = [$seqs]; - } - $regex = ""; - foreach ($seqs AS $seq) { - $unit = ""; + $regex = preg_quote($structure, '/'); - switch ($seq['@']['type']) { - case 'alpha': - $unit .= '[a-z]'; - break; + $regex = str_replace( + preg_quote('{SITE:ALIAS}', '/'), + preg_quote($siteAbbrev ?? '', '/'), + $regex + ); - case 'alphanumeric': - $unit .= '[0-9a-z]'; - break; + $regex = str_replace( + preg_quote('{PROJECT:ALIAS}', '/'), + preg_quote($projectAbbrev ?? '', '/'), + $regex + ); - case 'numeric': - $unit .= '[0-9]'; - break; + $escaped = '\\\\'; - case 'static': - $unit .= '('.$seq['#'].')'; - break; + $regex = preg_replace_callback( + "/{$escaped}\{(SEQUENCE|RANDOM){$escaped}:(\d+)([^}]*){$escaped}\}/i", + function ($matches) use ($escaped) { + $characters = '[0-9]'; - case 'set': - if (strpos($seq['#'], '|') !== false) { - $unit .= '('.$seq['#'].')'; - } else { - $unit .= '['.$seq['#'].']'; + if (preg_match( + "/FORMAT{$escaped}:(numeric|alphanumeric|alpha)/i", + $matches[3], + $type + ) + ) { + switch (strtolower($type[1])) { + case 'alphanumeric': + $characters = '[0-9A-Z]'; + break; + + case 'alpha': + $characters = '[A-Z]'; + break; + } } - break; - - case 'siteAbbrev': - $unit .= $siteAbbrev; - break; - case 'projectAbbrev': - $unit .= $projectAbbrev; - break; - } // end switch - - $length = ""; - if (isset($seq['@']['length'])) { - $length .= $seq['@']['length']; - } elseif (isset($seq['@']['minLength'])) { - $length .= $seq['@']['minLength']; - } else { - $length .= '1'; - } - $length .= ','; + $hasPadding = str_contains( + strtoupper($matches[3]), + 'PADDING' . $escaped[0] . ':' + ); - if (isset($seq['@']['length'])) { - $length .= $seq['@']['length']; - } elseif (isset($seq['@']['maxLength'])) { - $length .= $seq['@']['maxLength']; - } elseif (!isset($seq['@']['length']) - && !isset($seq['@']['minLength']) - ) { - $length .= '1'; - } + $length = $hasPadding + ? $matches[2] + : '1,' . $matches[2]; - $regex .= $unit.'{'.$length.'}'; + return $characters . '{' . $length . '}'; + }, + $regex + ); - } // end foreach seq + $regex = preg_replace_callback( + "/{$escaped}\{(NUMERIC|ALPHANUMERIC|ALPHA)" + . "{$escaped}:(\d+){$escaped}\}/i", + function ($matches) { + $characters = match (strtoupper($matches[1])) { + 'NUMERIC' => '[0-9]', + 'ALPHANUMERIC' => '[0-9A-Z]', + 'ALPHA' => '[A-Z]', + default => throw new \InvalidArgumentException( + 'Unsupported identifier format' + ), + }; + + return $characters . '{' . $matches[2] . '}'; + }, + $regex + ); return '/^'.$regex.'$/i'; } diff --git a/php/libraries/CandidateIdentifierController.class.inc b/php/libraries/CandidateIdentifierController.class.inc new file mode 100644 index 0000000000..2cd461ee56 --- /dev/null +++ b/php/libraries/CandidateIdentifierController.class.inc @@ -0,0 +1,436 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +namespace LORIS; + +use LORIS\StudyEntities\Candidate\CandidateIdentifier; + +/** + * Controller for candidate identifiers + * + * @category Model + * @package CandidateIdentifiers + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class CandidateIdentifierController +{ + /** + * Creates a CandidateIdentifierController + * + * @param \Database $database Database connection + * + * @throws \RuntimeException If the database is not connected + */ + public function __construct( + private readonly \Database $database, + ) { + if (!$database->isConnected()) { + throw new \RuntimeException( + "CandidateIdentifierController - Database not connected" + ); + } + } + + /** + * Gets a candidate identifier by ID + * + * @param int $candidateIdentifierID Candidate identifier ID + * + * @return CandidateIdentifier Candidate identifier associated with the + * supplied ID + * + * @throws \NotFound If the candidate identifier does not exist + */ + public function getCandidateIdentifierFromID( + int $candidateIdentifierID + ): CandidateIdentifier { + $row = $this->database->pselectRow( + "SELECT ci.CandidateIdentifierID, + ci.CandidateID, + ci.CandidateIdentifierTypeID, + ci.Value, + ci.DateAdded, + ci.DateEdited + FROM candidate_identifiers AS ci + WHERE ci.CandidateIdentifierID = :candidateIdentifierID", + ['candidateIdentifierID' => $candidateIdentifierID] + ); + + if (empty($row)) { + throw new \NotFound( + "No candidate identifier found in the database with id: " + . $candidateIdentifierID + ); + } + + $identifierTypeController = new IdentifierTypeController( + $this->database + ); + + return new CandidateIdentifier( + candidateIdentifierID: (int) $row['CandidateIdentifierID'], + candidateID: (int) $row['CandidateID'], + type: $identifierTypeController->getIdentifierTypeFromID( + (int) $row['CandidateIdentifierTypeID'] + ), + value: $row['Value'], + dateAdded: $row['DateAdded'], + dateEdited: $row['DateEdited'], + ); + } + + /** + * Gets all identifiers for a candidate + * + * @param int $candidateID Candidate ID + * + * @return CandidateIdentifier[] Candidate identifiers + */ + public function getCandidateIdentifiers( + int $candidateID + ): array { + $identifierIDs = $this->database->pselectCol( + "SELECT CandidateIdentifierID + FROM candidate_identifiers + WHERE CandidateID = :candidateID + ORDER BY CandidateIdentifierID", + [ + 'candidateID' => $candidateID, + ] + ); + + $identifiers = []; + + foreach ($identifierIDs as $identifierID) { + $identifiers[] = $this->getCandidateIdentifierFromID( + (int) $identifierID + ); + } + + return $identifiers; + } + + /** + * Creates a candidate identifier + * + * @param CandidateIdentifier $candidateIdentifier Candidate identifier to create + * + * @return CandidateIdentifier Created candidate identifier + * + * @throws \InvalidArgumentException If the identifier violates its type rules + */ + public function createCandidateIdentifier( + CandidateIdentifier $candidateIdentifier + ): CandidateIdentifier { + $identifierType = $candidateIdentifier->type; + + $this->_validateFormat($candidateIdentifier); + + if (!$identifierType->allowMultiple) { + $existingIdentifier = $this->database->pselectRow( + "SELECT CandidateIdentifierID + FROM candidate_identifiers + WHERE CandidateID = :candidateID + AND CandidateIdentifierTypeID = :identifierTypeID", + [ + 'candidateID' => $candidateIdentifier->candidateID, + 'identifierTypeID' => + $identifierType->candidateIdentifierTypeID, + ] + ); + + if (!empty($existingIdentifier)) { + throw new \InvalidArgumentException( + 'Candidate already has an identifier of this type' + ); + } + } + + if ($identifierType->isUnique) { + $existingIdentifier = $this->database->pselectRow( + "SELECT CandidateIdentifierID + FROM candidate_identifiers + WHERE CandidateIdentifierTypeID = :identifierTypeID + AND Value = :value", + [ + 'identifierTypeID' => + $identifierType->candidateIdentifierTypeID, + 'value' => $candidateIdentifier->value, + ] + ); + + if (!empty($existingIdentifier)) { + throw new \InvalidArgumentException( + 'Identifier value is already assigned to another candidate' + ); + } + } + + $this->database->insert( + 'candidate_identifiers', + [ + 'CandidateID' => $candidateIdentifier->candidateID, + 'CandidateIdentifierTypeID' => + $identifierType->candidateIdentifierTypeID, + 'Value' => $candidateIdentifier->value, + ] + ); + + $candidateIdentifierID = (int) $this->database->getLastInsertId(); + + return $this->getCandidateIdentifierFromID($candidateIdentifierID); + } + + /** + * Generates and creates a candidate identifier + * + * @param int $candidateID Candidate ID + * @param IdentifierType $identifierType Identifier type + * + * @return CandidateIdentifier Generated candidate identifier + * + * @throws \InvalidArgumentException If automatic generation is not enabled + */ + public function generateCandidateIdentifier( + int $candidateID, + IdentifierType $identifierType + ): CandidateIdentifier { + if (!$identifierType->autoGenerate) { + throw new \InvalidArgumentException( + 'Identifier type is not configured for automatic generation' + ); + } + + $candidate = $this->_getCandidateAliases($candidateID); + + $generator = new \CandidateIdentifierGenerator( + $this->database, + $identifierType, + $candidate['SiteAlias'], + $candidate['ProjectAlias'] + ); + + $candidateIdentifier = new CandidateIdentifier( + candidateIdentifierID: null, + candidateID: $candidateID, + type: $identifierType, + value: $generator->generate(), + ); + + return $this->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Updates a candidate identifier + * + * @param CandidateIdentifier $candidateIdentifier Candidate identifier to update + * + * @return CandidateIdentifier Updated candidate identifier + * + * @throws \NotFound If the candidate identifier does not exist + */ + public function updateCandidateIdentifier( + CandidateIdentifier $candidateIdentifier + ): CandidateIdentifier { + if ($candidateIdentifier->candidateIdentifierID === null) { + throw new \InvalidArgumentException( + 'Cannot update a candidate identifier without an ID' + ); + } + + $candidateIdentifierID = $candidateIdentifier->candidateIdentifierID; + $identifierType = $candidateIdentifier->type; + + $this->_validateFormat($candidateIdentifier); + + if ($identifierType->candidateIdentifierTypeID === null) { + throw new \InvalidArgumentException( + 'Cannot update a candidate identifier without an identifier type ID' + ); + } + + $existingIdentifier = $this->getCandidateIdentifierFromID( + $candidateIdentifierID + ); + + $candidateChanged = $existingIdentifier->candidateID + !== $candidateIdentifier->candidateID; + + $typeChanged = $existingIdentifier->type->candidateIdentifierTypeID + !== $identifierType->candidateIdentifierTypeID; + + if ($candidateChanged || $typeChanged) { + throw new \InvalidArgumentException( + 'Cannot change the candidate or identifier type of an existing' + . ' identifier' + ); + } + + if (!$identifierType->allowMultiple) { + $existingIdentifier = $this->database->pselectRow( + "SELECT CandidateIdentifierID + FROM candidate_identifiers + WHERE CandidateID = :candidateID + AND CandidateIdentifierTypeID = :identifierTypeID + AND CandidateIdentifierID != :candidateIdentifierID", + [ + 'candidateID' => $candidateIdentifier->candidateID, + 'identifierTypeID' => + $identifierType->candidateIdentifierTypeID, + 'candidateIdentifierID' => $candidateIdentifierID, + ] + ); + + if (!empty($existingIdentifier)) { + throw new \InvalidArgumentException( + 'Candidate already has an identifier of this type' + ); + } + } + + if ($identifierType->isUnique) { + $existingIdentifier = $this->database->pselectRow( + "SELECT CandidateIdentifierID + FROM candidate_identifiers + WHERE CandidateIdentifierTypeID = :identifierTypeID + AND Value = :value + AND CandidateIdentifierID != :candidateIdentifierID", + [ + 'identifierTypeID' => + $identifierType->candidateIdentifierTypeID, + 'value' => $candidateIdentifier->value, + 'candidateIdentifierID' => $candidateIdentifierID, + ] + ); + + if (!empty($existingIdentifier)) { + throw new \InvalidArgumentException( + 'Identifier value is already assigned to another candidate' + ); + } + } + + $this->database->update( + 'candidate_identifiers', + [ + 'Value' => $candidateIdentifier->value, + ], + [ + 'CandidateIdentifierID' => $candidateIdentifierID, + ] + ); + + return $this->getCandidateIdentifierFromID($candidateIdentifierID); + } + + /** + * Deletes a candidate identifier + * + * @param int $candidateIdentifierID Candidate identifier ID + * + * @return void + * + * @throws \NotFound If the candidate identifier does not exist + */ + public function deleteCandidateIdentifier( + int $candidateIdentifierID + ): void { + $this->getCandidateIdentifierFromID($candidateIdentifierID); + + $this->database->delete( + 'candidate_identifiers', + [ + 'CandidateIdentifierID' => $candidateIdentifierID, + ] + ); + } + + /** + * Gets the site and project aliases for a candidate + * + * @param int $candidateID Candidate ID + * + * @return array Candidate site and project aliases + * + * @throws \NotFound If the candidate does not exist + */ + private function _getCandidateAliases(int $candidateID): array + { + $candidate = $this->database->pselectRow( + "SELECT p.Alias AS SiteAlias, + pr.Alias AS ProjectAlias + FROM candidate AS c + JOIN psc AS p + ON p.CenterID = c.RegistrationCenterID + JOIN Project AS pr + ON pr.ProjectID = c.RegistrationProjectID + WHERE c.ID = :candidateID", + [ + 'candidateID' => $candidateID, + ] + ); + + if (empty($candidate)) { + throw new \NotFound( + "No candidate found in the database with id: " + . $candidateID + ); + } + + return $candidate; + } + + /** + * Validates a candidate identifier against its type format + * + * Resolves the candidate's site and project aliases so that identifier + * formats containing SITE:ALIAS or PROJECT:ALIAS can be validated. + * + * @param CandidateIdentifier $candidateIdentifier Candidate identifier + * + * @return void + * + * @throws \NotFound If the candidate does not exist + * @throws \InvalidArgumentException If the value does not match the format + */ + private function _validateFormat( + CandidateIdentifier $candidateIdentifier + ): void { + + $candidate = $this->_getCandidateAliases( + $candidateIdentifier->candidateID + ); + + $pattern = \Candidate::structureToPCRE( + $candidateIdentifier->type->format, + $candidate['SiteAlias'], + $candidate['ProjectAlias'] + ); + + if (preg_match($pattern, $candidateIdentifier->value) !== 1) { + $expected = \Candidate::structureToPattern( + $candidateIdentifier->type->format, + $candidate['SiteAlias'], + $candidate['ProjectAlias'] + ); + + throw new \InvalidArgumentException( + "Identifier '{$candidateIdentifier->type->name}' " + . "has an invalid structure. Expected format: $expected" + ); + } + } +} diff --git a/php/libraries/CandidateIdentifierGenerator.php b/php/libraries/CandidateIdentifierGenerator.php new file mode 100644 index 0000000000..3785be1592 --- /dev/null +++ b/php/libraries/CandidateIdentifierGenerator.php @@ -0,0 +1,202 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +use LORIS\IdentifierType; + +/** + * Generates candidate identifiers using an IdentifierType. + * + * @category Main + * @package CandidateIdentifiers + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class CandidateIdentifierGenerator extends IdentifierGenerator +{ + /** + * Constructor for CandidateIdentifierGenerator. + * + * @param Database $database Database connection + * @param IdentifierType $identifierType Identifier type configuration + * @param string $siteAlias Candidate site alias + * @param string $projectAlias Candidate project alias + */ + public function __construct( + private readonly Database $database, + private readonly IdentifierType $identifierType, + string $siteAlias, + string $projectAlias, + ) { + $this->siteAlias = $siteAlias; + $this->projectAlias = $projectAlias; + + $this->_initializeFromFormat(); + } + + /** + * Generates a new candidate identifier + * + * @return string + */ + public function generate(): string + { + return $this->createNewID(); + } + + /** + * Initializes generation settings from the identifier type format + * + * @return void + * + * @throws \ConfigurationException If the generation template is invalid + */ + private function _initializeFromFormat(): void + { + if (preg_match( + '/\{(SEQUENCE|RANDOM):(\d+)([^}]*)\}/i', + $this->identifierType->format, + $generation + ) !== 1 + ) { + throw new \ConfigurationException( + 'Invalid generation template for identifier type ' + . $this->identifierType->name + ); + } + + $this->generationMethod = match (strtoupper($generation[1])) { + 'SEQUENCE' => 'sequential', + 'RANDOM' => 'random', + default => throw new \ConfigurationException( + 'Invalid generation method for identifier type ' + . $this->identifierType->name + ), + }; + + $this->length = intval($generation[2]); + + $this->alphabet = range('0', '9'); + + if (preg_match( + '/(?:^|,)FORMAT:(numeric|alphanumeric|alpha)(?:,|$)/i', + $generation[3], + $format + ) === 1 + ) { + switch (strtolower($format[1])) { + case 'alpha': + $this->alphabet = range('A', 'Z'); + break; + + case 'alphanumeric': + $this->alphabet = array_merge( + range('0', '9'), + range('A', 'Z') + ); + break; + } + } + + $this->minValue = str_repeat($this->alphabet[0], $this->length); + $this->maxValue = str_repeat( + $this->alphabet[count($this->alphabet) - 1], + $this->length + ); + + if (preg_match( + '/(?:^|,)MIN:([^,]+)/i', + $generation[3], + $min + ) === 1 + ) { + $this->minValue = $min[1]; + } + + if (preg_match( + '/(?:^|,)MAX:([^,]+)/i', + $generation[3], + $max + ) === 1 + ) { + $this->maxValue = $max[1]; + } + + if (preg_match( + '/(?:^|,)PADDING:([^,]+)/i', + $generation[3], + $padding + ) === 1 + ) { + $this->padding = $padding[1]; + + if (!in_array($this->padding, $this->alphabet, true)) { + throw new \ConfigurationException( + 'Padding character must be part of the configured alphabet.' + ); + } + } + + $this->validateNumericRange(); + + $generationPosition = strpos( + $this->identifierType->format, + $generation[0] + ); + + if ($generationPosition === false) { + throw new \ConfigurationException( + 'Invalid generation template for identifier type ' + . $this->identifierType->name + ); + } + + $this->prefix = substr( + $this->identifierType->format, + 0, + $generationPosition + ); + + $this->prefix = str_replace( + ['{SITE:ALIAS}', '{PROJECT:ALIAS}'], + [$this->siteAlias, $this->projectAlias], + $this->prefix + ); + } + + /** + * Gets existing values for this identifier type + * + * @return string[] + */ + protected function getExistingIDs(): array + { + if ($this->identifierType->candidateIdentifierTypeID === null) { + throw new \LogicException( + 'Identifier type must be persisted before generating identifiers' + ); + } + + return $this->database->pselectCol( + "SELECT SUBSTRING(Value, LENGTH(:prefix) + 1) + FROM candidate_identifiers + WHERE CandidateIdentifierTypeID = :typeID + AND Value LIKE CONCAT(:prefix, '%')", + [ + 'typeID' => $this->identifierType->candidateIdentifierTypeID, + 'prefix' => $this->prefix, + ] + ); + } +} diff --git a/php/libraries/IdentifierGenerator.php b/php/libraries/IdentifierGenerator.php index 85a4e58a8d..7242208d76 100644 --- a/php/libraries/IdentifierGenerator.php +++ b/php/libraries/IdentifierGenerator.php @@ -27,8 +27,8 @@ */ abstract class IdentifierGenerator { - private const RANGE_FULL = 'Cannot create new identifier because all ' . - ' valid identifiers are in use!'; + private const RANGE_FULL = 'Cannot create new identifier because all' + . ' valid identifiers are in use!'; /** * How the ID will be generated. 'sequential' or 'random'. * @@ -42,6 +42,14 @@ abstract class IdentifierGenerator * range() which is used to generate the alphabet. */ protected $alphabet = []; + + /** + * Character used to pad identifiers to their configured length. + * + * @var string|null + */ + protected ?string $padding = null; + /** * The length of the "suffix" portion of the ID. * e.g. for an ID `MON1234` with prefix `MON`, the suffix is length 4. @@ -92,7 +100,25 @@ abstract class IdentifierGenerator protected function createNewID(): string { // Check that it is possible to create a new ID. + $this->validateNumericRange(); $this->checkIDRangeFull(); + if ($this->padding === null + && $this->generationMethod === 'random' + && $this->alphabet === range('0', '9') + ) { + do { + $id = strval( + random_int( + intval($this->minValue), + intval($this->maxValue) + ) + ); + } while ( + in_array($id, array_map('strval', $this->getExistingIDs()), true) + ); + + return $this->prefix . $id; + } $id = ''; switch ($this->generationMethod) { @@ -130,6 +156,29 @@ protected function createNewID(): string */ protected function generateSequentialID(string $id = ''): string { + if ($this->padding === null + && $this->alphabet === range('0', '9') + ) { + $min = intval($this->minValue); + $max = intval($this->maxValue); + $nextID = $min; + + foreach ($this->getExistingIDs() as $existingID) { + if (ctype_digit(strval($existingID)) + && strval(intval($existingID)) === strval($existingID) + && intval($existingID) >= $min + && intval($existingID) <= $max + ) { + if (intval($existingID) === $max) { + throw new \LorisException(self::RANGE_FULL); + } + + $nextID = max($nextID, intval($existingID) + 1); + } + } + + return strval($nextID); + } // If this is the first ID ever created, return the minimum value. if (count($this->getExistingIDs()) < 1) { if (!is_int($this->length)) { @@ -137,12 +186,7 @@ protected function generateSequentialID(string $id = ''): string "minimum ID length not configured in project/config.xml" ); } - return str_pad( - strval($this->minValue), - $this->length, - "0", - STR_PAD_LEFT - ); + return $this->padID(strval($this->minValue)); } // Create the new ID by incrementing the value of the $id parameter OR // by incrementing the highest existing ID. @@ -207,8 +251,8 @@ protected function generateRandomID(): string abstract protected function getExistingIDs(): array; /** - * Ensure that an ID is the correct length by prepending the first character - * of the alphabet to the ID if the ID's length is shorter than it should be. + * Ensure that an ID is the correct length by prepending the configured + * padding character if the ID's length is shorter than it should be. * * @param string $id The ID to pad. * @@ -216,14 +260,47 @@ abstract protected function getExistingIDs(): array; */ protected function padID(string $id): string { + if ($this->padding === null) { + return $id; + } + return str_pad( $id, $this->length, - strval($this->alphabet[0]), + $this->padding, STR_PAD_LEFT ); } + /** + * Validates the configured range for unpadded numeric identifiers. + * + * @return void + * + * @throws \ConfigurationException + */ + protected function validateNumericRange(): void + { + if ($this->padding !== null + || $this->alphabet !== range('0', '9') + ) { + return; + } + + if (!ctype_digit($this->minValue) + || !ctype_digit($this->maxValue) + || strlen($this->minValue) > $this->length + || strlen($this->maxValue) > $this->length + || $this->minValue > PHP_INT_MAX + || $this->maxValue > PHP_INT_MAX + || intval($this->minValue) > intval($this->maxValue) + ) { + throw new \ConfigurationException( + 'Invalid numeric identifier range.' + ); + } + } + /** * Check that the number of existing IDs does not exceed the range of * possible values (given by the size of the alphabet to the power of @@ -235,6 +312,28 @@ protected function padID(string $id): string */ protected function checkIDRangeFull(): void { + if ($this->padding === null + && $this->alphabet === range('0', '9') + ) { + $min = intval($this->minValue); + $max = intval($this->maxValue); + + $existingIDs = array_filter( + $this->getExistingIDs(), + static function ($id) use ($min, $max): bool { + return ctype_digit(strval($id)) + && strval(intval($id)) === strval($id) + && intval($id) >= $min + && intval($id) <= $max; + } + ); + + if (count(array_unique($existingIDs)) >= $max - $min + 1) { + throw new \LorisException(self::RANGE_FULL); + } + + return; + } // Check that the number of existing IDs does not exceed the range of // possible values (given by the size of the alphabet to the power of // number of characters in the ID). diff --git a/php/libraries/IdentifierType.class.inc b/php/libraries/IdentifierType.class.inc new file mode 100644 index 0000000000..1f259146fc --- /dev/null +++ b/php/libraries/IdentifierType.class.inc @@ -0,0 +1,54 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +namespace LORIS; + +/** + * Representation of a candidate identifier type in LORIS + * + * @category Model + * @package CandidateIdentifiers + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class IdentifierType +{ + /** + * Constructor for IdentifierType + * + * @param int|null $candidateIdentifierTypeID Identifier type ID + * @param string $name Identifier type name + * @param string $format Identifier format + * @param bool $isRequired Whether a value is required + * @param bool $isUnique Whether values must be unique + * @param bool $autoGenerate Whether values are generated + * @param bool $allowMultiple Whether multiple values are + * allowed + * @param \Project[] $projects Associated projects + * @param int|null $permissionID Associated permission ID + */ + public function __construct( + public readonly ?int $candidateIdentifierTypeID, + public string $name, + public string $format, + public bool $isRequired, + public bool $isUnique, + public bool $autoGenerate, + public bool $allowMultiple, + public array $projects = [], + public ?int $permissionID = null, + ) { + } +} diff --git a/php/libraries/IdentifierTypeController.class.inc b/php/libraries/IdentifierTypeController.class.inc new file mode 100644 index 0000000000..5794f98c0f --- /dev/null +++ b/php/libraries/IdentifierTypeController.class.inc @@ -0,0 +1,298 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +namespace LORIS; + +/** + * Controller for candidate identifier types + * + * @category Model + * @package CandidateIdentifiers + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class IdentifierTypeController +{ + /** + * Creates an IdentifierTypeController + * + * @param \Database $database Database connection + * + * @throws \RuntimeException If the database is not connected + */ + public function __construct( + private readonly \Database $database, + ) { + if (!$database->isConnected()) { + throw new \RuntimeException( + "IdentifierTypeController - Database not connected" + ); + } + } + + /** + * Gets all candidate identifier types. + * + * @return IdentifierType[] All identifier types + */ + public function getAllIdentifierTypes(): array + { + $rows = $this->database->pselectCol( + "SELECT CandidateIdentifierTypeID + FROM candidate_identifier_types + ORDER BY Name", + [] + ); + + return array_map( + fn($id) => $this->getIdentifierTypeFromID((int) $id), + $rows + ); + } + + /** + * Gets an identifier type by ID + * + * @param int $candidateIdentifierTypeID Identifier type ID + * + * @return IdentifierType Identifier type associated with the supplied ID + * + * @throws \NotFound If the identifier type does not exist + */ + public function getIdentifierTypeFromID( + int $candidateIdentifierTypeID + ): IdentifierType { + $row = $this->database->pselectRow( + "SELECT cit.CandidateIdentifierTypeID, + cit.Name, + cit.Format, + cit.IsRequired, + cit.IsUnique, + cit.AutoGenerate, + cit.AllowMultiple, + cit.permID + FROM candidate_identifier_types AS cit + WHERE cit.CandidateIdentifierTypeID = :identifierTypeID", + ['identifierTypeID' => $candidateIdentifierTypeID] + ); + + if (empty($row)) { + throw new \NotFound( + "No identifier type found in the database with id: " + . $candidateIdentifierTypeID + ); + } + + return new IdentifierType( + candidateIdentifierTypeID: (int) $row['CandidateIdentifierTypeID'], + name: $row['Name'], + format: $row['Format'], + isRequired: (bool) $row['IsRequired'], + isUnique: (bool) $row['IsUnique'], + autoGenerate: (bool) $row['AutoGenerate'], + allowMultiple: (bool) $row['AllowMultiple'], + projects: $this->_getProjects($candidateIdentifierTypeID), + permissionID: isset($row['permID']) ? (int) $row['permID'] : null, + ); + } + + /** + * Gets an identifier type by name + * + * @param string $name Identifier type name + * + * @return IdentifierType Identifier type associated with the name + * + * @throws \NotFound If the identifier type does not exist + */ + public function getIdentifierTypeFromName(string $name): IdentifierType + { + $identifierTypeID = $this->database->pselectOne( + "SELECT CandidateIdentifierTypeID + FROM candidate_identifier_types + WHERE Name = :name", + ['name' => $name] + ); + + if (empty($identifierTypeID)) { + throw new \NotFound( + "No identifier type found in the database with name: " . $name + ); + } + + return $this->getIdentifierTypeFromID((int) $identifierTypeID); + } + + /** + * Gets the projects associated with an identifier type + * + * @param int $candidateIdentifierTypeID Identifier type ID + * + * @return \Project[] Associated projects + */ + private function _getProjects( + int $candidateIdentifierTypeID + ): array { + $projectIDs = $this->database->pselectCol( + "SELECT ProjectID + FROM candidate_identifier_types_project_rel + WHERE CandidateIdentifierTypeID = :identifierTypeID", + ['identifierTypeID' => $candidateIdentifierTypeID] + ); + + return array_map( + static fn($projectID) => \Project::getProjectFromID( + new \ProjectID(strval($projectID)) + ), + $projectIDs + ); + } + + /** + * Creates an identifier type + * + * @param IdentifierType $identifierType Identifier type to create + * + * @return IdentifierType Created identifier type + */ + public function createIdentifierType(IdentifierType $identifierType) + : IdentifierType + { + $this->database->beginTransaction(); + + try { + $this->database->insert( + 'candidate_identifier_types', + [ + 'Name' => $identifierType->name, + 'Format' => $identifierType->format, + 'IsRequired' => (int) $identifierType->isRequired, + 'IsUnique' => (int) $identifierType->isUnique, + 'AutoGenerate' => (int) $identifierType->autoGenerate, + 'AllowMultiple' => (int) $identifierType->allowMultiple, + 'permID' => $identifierType->permissionID, + ] + ); + + $identifierTypeID = (int) $this->database->getLastInsertId(); + + foreach ($identifierType->projects as $project) { + $this->database->insert( + 'candidate_identifier_types_project_rel', + [ + 'CandidateIdentifierTypeID' => $identifierTypeID, + 'ProjectID' => $project->getId(), + ] + ); + } + + $this->database->commit(); + } catch (\Throwable $e) { + $this->database->rollBack(); + throw $e; + } + + return $this->getIdentifierTypeFromID($identifierTypeID); + } + + /** + * Updates an identifier type + * + * @param IdentifierType $identifierType Identifier type to update + * + * @return IdentifierType Updated identifier type + * + * @throws \NotFound If the identifier type does not exist + */ + public function updateIdentifierType(IdentifierType $identifierType) + : IdentifierType + { + if ($identifierType->candidateIdentifierTypeID === null) { + throw new \InvalidArgumentException( + 'Cannot update an identifier type without an ID' + ); + } + + $identifierTypeID = $identifierType->candidateIdentifierTypeID; + + $this->getIdentifierTypeFromID($identifierTypeID); + + $this->database->beginTransaction(); + + try { + $this->database->update( + 'candidate_identifier_types', + [ + 'Name' => $identifierType->name, + 'Format' => $identifierType->format, + 'IsRequired' => (int) $identifierType->isRequired, + 'IsUnique' => (int) $identifierType->isUnique, + 'AutoGenerate' => (int) $identifierType->autoGenerate, + 'AllowMultiple' => (int) $identifierType->allowMultiple, + 'permID' => $identifierType->permissionID, + ], + [ + 'CandidateIdentifierTypeID' => $identifierTypeID, + ] + ); + + $this->database->delete( + 'candidate_identifier_types_project_rel', + [ + 'CandidateIdentifierTypeID' => $identifierTypeID, + ] + ); + + foreach ($identifierType->projects as $project) { + $this->database->insert( + 'candidate_identifier_types_project_rel', + [ + 'CandidateIdentifierTypeID' => $identifierTypeID, + 'ProjectID' => $project->getId(), + ] + ); + } + + $this->database->commit(); + } catch (\Throwable $e) { + $this->database->rollBack(); + throw $e; + } + + return $this->getIdentifierTypeFromID($identifierTypeID); + } + + /** + * Deletes an identifier type + * + * @param int $candidateIdentifierTypeID Identifier type ID + * + * @return void + * + * @throws \NotFound If the identifier does not exist + */ + public function deleteIdentifierType( + int $candidateIdentifierTypeID + ): void { + $this->getIdentifierTypeFromID($candidateIdentifierTypeID); + + $this->database->delete( + 'candidate_identifier_types', + [ + 'CandidateIdentifierTypeID' => $candidateIdentifierTypeID, + ] + ); + } +} diff --git a/php/libraries/SiteIDGenerator.php b/php/libraries/SiteIDGenerator.php index 95b0d96bc8..4cea03824e 100644 --- a/php/libraries/SiteIDGenerator.php +++ b/php/libraries/SiteIDGenerator.php @@ -36,7 +36,7 @@ class SiteIDGenerator extends IdentifierGenerator /** * Creates a new instance of a SiteIDGenerator to create either PSCIDs or - * ExternalIDs. Relevant properties are extracted from the config.xml file. + * ExternalIDs. Relevant properties are extracted from the database * * @param string $siteAlias To be appended to the ID value. Usually an * abbreviation for the name of a site. @@ -47,12 +47,13 @@ class SiteIDGenerator extends IdentifierGenerator */ public function __construct(string $siteAlias, string $projectAlias) { - // Read config settings from project/config.xml to retrieve the + // Read identifier settings from the database to retrieve the // alphabet, length, and generation method (sequential or random) used // to create new IDs. $this->generationMethod = $this->_getGeneration(); $this->length = $this->_getLength(); $this->alphabet = $this->_getAlphabet(); + $this->padding = $this->_getPadding(); $this->minValue = $this->_getMinValue(); $this->maxValue = $this->_getMaxValue(); @@ -76,13 +77,13 @@ protected function validate(): void if (empty($this->generationMethod) || empty($this->length) || empty($this->alphabet) - || empty($this->minValue) - || empty($this->maxValue) + || $this->minValue === '' + || $this->maxValue === '' || empty($this->prefix) ) { throw new \DomainException( 'Values not configured properly for ' . get_class($this) . '. ' - . 'Please correct your configuration file.' + . 'Please correct the identifier format.' . "Length: `{$this->length}`\n" . "Alphabet: `" . implode($this->alphabet) . "`\n" . "Min: `{$this->minValue}`\n" @@ -145,184 +146,131 @@ protected function getExistingIDs(): array } /** - * Helper function used for extracting the values from the config - * settings relating to the PSCID structure. + * Extracts identifier generation settings from the format + * stored in the database. * * @param string $setting One of: 'generation', 'length', 'alphabet', - * 'min', 'max'. + * 'prefix', 'min', 'max', 'padding'. * * @return array|string|null */ private function _getIDSetting( string $setting ) { - $config = \NDB_Factory::singleton()->config(); - $kind = $config->getSetting($this->kind); - - if (!is_array($kind)) { - throw new \LorisException("Invalid config for $this->kind"); - }; - // The generation setting can be easily extracted and returned. - if ($setting == 'generation') { - return $kind['generation']; - } + $db = \NDB_Factory::singleton()->database(); - // Values other than 'generation' are found within 'seq' elements and - // require more complex processing. - $idStructure = $kind['structure']['seq']; + $identifierTypeController = new \LORIS\IdentifierTypeController($db); + $identifierType = $identifierTypeController + ->getIdentifierTypeFromName( + $this->kind + ); - if (!$idStructure[0]) { - // There's only one seq tag so the param format - // needs to be fixed - $temp = []; - $temp[] = $idStructure; - $idStructure = $temp; - } + $kind = [ + 'structure' => $identifierType->format, + 'generation' => !$identifierType->autoGenerate + ? 'user' + : ( + preg_match('/\{SEQUENCE:\d+/i', $identifierType->format) + ? 'sequential' + : 'random' + ), + ]; - try { - $seqValue = self::getSeqAttribute($idStructure, $setting); - } catch (\ConfigurationException $e) { - /* Throw a new exception so that we can inform developers whether - * the ConfigurationException arose due to ExternalID or PSCID - * settings. - */ - throw new \LorisException( - "Cannot create new candidate because of a configuration " . - "error in settings for {$this->kind} structure. Details: " - . $e->getMessage() + if (preg_match( + '/\{(SEQUENCE|RANDOM):(\d+)([^}]*)\}/i', + $kind['structure'], + $generation + ) !== 1 + ) { + throw new \ConfigurationException( + "Invalid generation template for {$this->kind}." ); } + + if ($setting === 'generation') { + return $kind['generation']; + } + + if ($setting === 'length') { + return $generation[2]; + } + if ($setting === 'alphabet') { - switch ($seqValue) { - case 'alpha': - return range('A', 'Z'); - case 'numeric': - return range('0', '9'); - case 'alphanumeric': - return array_merge(range('0', '9'), range('A', 'Z')); + if (preg_match( + '/(?:^|,)FORMAT:(numeric|alphanumeric|alpha)(?:,|$)/i', + $generation[3], + $match + ) + ) { + switch (strtolower($match[1])) { + case 'alphanumeric': + return array_merge( + range('0', '9'), + range('A', 'Z') + ); + + case 'alpha': + return range('A', 'Z'); + } } + + return range('0', '9'); } if ($setting === 'prefix') { - if ($seqValue === 'static') { - // The 'static' seq attribute must also include a value which - // will be a fixed string prefix to be prepended to IDs in - // LORIS. This must be extracted manually. - foreach ($idStructure as $seq) { - if ($seq['@']['type'] === 'static') { - // This index stores the prefix. - return $seq['#']; - } - } - } elseif ($seqValue === 'siteAbbrev') { - return $this->siteAlias; - } elseif ($seqValue === 'projectAbbrev') { - return $this->projectAlias; - } else { - throw new ConfigurationException( - "Incorrect option $seqValue selected for PSCID generation." + $position = strpos( + $kind['structure'], + $generation[0], + ); + + if ($position === false) { + throw new \ConfigurationException( + "Invalid generation template for {$this->kind}." ); } - } - // The remaining values - min, max, and length - should be returned as - // null if they are not set. - return is_null($seqValue) ? $seqValue: $seqValue; - } - /** - * Iterate over each 'seq' value and return its setting if its value is - * configured. Do error handling to make sure that there is exactly one - * value corresponding to the requested setting. - * - * @param array>> $idStructure Settings concerning ID - * structure extracted from - * project/config.sml - * @param string $setting The name of the variable - * for which we want the - * value. - * - * @throws \ConfigurationException - * - * @return ?string - */ - static function getSeqAttribute( - array $idStructure, - string $setting - ): ?string { - /* Do validation on 'prefix' and 'alphabet' since they both are found in - * 'type' attributes within 'seq' elements. See project/config.xml for - * examples. - */ - switch ($setting) { - case 'alphabet': - $seqAttributes = array_filter( - self::_getSeqAttribute($idStructure, 'type'), - function ($x) { - return $x === 'alpha' - || $x === 'alphanumeric' - || $x === 'numeric'; - } - ); - break; - case 'prefix': - $seqAttributes = array_filter( - self::_getSeqAttribute($idStructure, 'type'), - function ($x) { - return $x === 'static' - || $x === 'siteAbbrev' - || $x === 'projectAbbrev'; - } + $prefix = substr( + $kind['structure'], + 0, + $position ); - break; - default: - /* Other settings (i.e. 'length', 'min', 'max') can be extracted - * directly as they are stored within distinct attributes. - */ - $seqAttributes = self::_getSeqAttribute( - $idStructure, - $setting + + $prefix = str_replace( + ['{SITE:ALIAS}', '{PROJECT:ALIAS}'], + [$this->siteAlias, $this->projectAlias], + $prefix ); - break; + + return $prefix; } - // Validation - if (count($seqAttributes) > 1) { - throw new \ConfigurationException( - 'Too many values found for config setting: ' . $setting - ); + if ($setting === 'min') { + if (preg_match('/(?:^|,)MIN:([^,]+)/i', $generation[3], $match)) { + return $match[1]; + } + return null; } - $val = array_pop($seqAttributes); - if ($val === null) { + if ($setting === 'max') { + if (preg_match('/(?:^|,)MAX:([^,]+)/i', $generation[3], $match)) { + return $match[1]; + } return null; } - return strval($val); - } - /** - * Traverse the $idStructure array and collect all values that exist - * for $setting. - * - * @param array>> $idStructure Settings concerning ID - * structure extracted from - * project/config.xml - * @param string $setting The name of the variable - * for which we want the - * value. - * - * @return array The value(s) corresponding to $setting. - */ - private static function _getSeqAttribute( - array $idStructure, - string $setting - ): array { - $seqAttributes = []; - foreach ($idStructure as $seq) { - if (isset($seq['@'][$setting])) { - $seqAttributes[] = $seq['@'][$setting]; + if ($setting === 'padding') { + if (preg_match( + '/(?:^|,)PADDING:([^,]+)/i', + $generation[3], + $match + ) + ) { + return $match[1]; } + return null; } - return $seqAttributes; + + return null; } /** @@ -425,4 +373,26 @@ private function _getMaxValue(): string ) ); } + + /** + * Returns the padding character, if configured. + * + * @return ?string + */ + private function _getPadding(): ?string + { + $padding = $this->_getIDSetting('padding'); + + if ($padding === null) { + return null; + } + + if (!in_array($padding, $this->alphabet, true)) { + throw new \ConfigurationException( + "Padding character must be part of the configured alphabet." + ); + } + + return $padding; + } } diff --git a/src/StudyEntities/Candidate/CandidateIdentifier.php b/src/StudyEntities/Candidate/CandidateIdentifier.php new file mode 100644 index 0000000000..6fc5ad5dc7 --- /dev/null +++ b/src/StudyEntities/Candidate/CandidateIdentifier.php @@ -0,0 +1,49 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +namespace LORIS\StudyEntities\Candidate; + +use LORIS\IdentifierType; + +/** + * Representation of a candidate identifier in LORIS + * + * @category StudyEntities + * @package CandidateIdentifiers + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class CandidateIdentifier +{ + /** + * Constructor for CandidateIdentifier + * + * @param int|null $candidateIdentifierID Candidate identifier ID + * @param int $candidateID Candidate ID + * @param IdentifierType $type Identifier type + * @param string $value Identifier value + * @param string|null $dateAdded Creation timestamp + * @param string|null $dateEdited Last modification timestamp + */ + public function __construct( + public readonly ?int $candidateIdentifierID, + public readonly int $candidateID, + public readonly IdentifierType $type, + public string $value, + public readonly ?string $dateAdded = null, + public readonly ?string $dateEdited = null, + ) { + } +} diff --git a/test/unittests/CandidateIdentifierControllerTest.php b/test/unittests/CandidateIdentifierControllerTest.php new file mode 100644 index 0000000000..8fba32b93f --- /dev/null +++ b/test/unittests/CandidateIdentifierControllerTest.php @@ -0,0 +1,875 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +require_once __DIR__ . '/../../vendor/autoload.php'; +require_once __DIR__ . '/../../php/libraries/IdentifierType.class.inc'; +require_once __DIR__ . '/../../php/libraries/IdentifierTypeController.class.inc'; +require_once __DIR__ +. '/../../php/libraries/CandidateIdentifierController.class.inc'; +require_once __DIR__ + . '/../../php/libraries/CandidateIdentifierGenerator.php'; + +use PHPUnit\Framework\TestCase; + +/** + * Unit tests for CandidateIdentifierController class + * + * @category Tests + * @package Test + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class CandidateIdentifierControllerTest extends TestCase +{ + protected $factory; + protected $DB; + protected $config; + protected $identifierTypeController; + protected $candidateIdentifierController; + + /** + * This method is called before each test is executed. + * Sets up fixtures: factory, config, database + * + * @return void + */ + protected 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->DB->setFakeTableData( + 'candidate_identifier_types', + [ + [ + 'CandidateIdentifierTypeID' => 1, + 'Name' => 'TestID', + 'Format' => '{SEQUENCE:4,FORMAT:numeric}', + 'IsRequired' => 1, + 'IsUnique' => 1, + 'AutoGenerate' => 1, + 'AllowMultiple' => 0, + 'permID' => null, + ], + ] + ); + + $this->DB->setFakeTableData( + 'candidate_identifier_types_project_rel', + [] + ); + + $this->DB->setFakeTableData( + 'candidate_identifiers', + [ + [ + 'CandidateIdentifierID' => 1, + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => '1234', + 'DateAdded' => '2026-01-01 12:00:00', + 'DateEdited' => null, + ], + ] + ); + + $this->DB->setFakeTableData( + 'candidate', + [ + [ + 'ID' => 1, + 'CandID' => 100001, + 'RegistrationCenterID' => 1, + 'RegistrationProjectID' => 1, + ], + [ + 'ID' => 2, + 'CandID' => 100002, + 'RegistrationCenterID' => 1, + 'RegistrationProjectID' => 1, + ], + ] + ); + + $this->DB->setFakeTableData( + 'psc', + [ + [ + 'CenterID' => 1, + 'Alias' => 'MTL', + ], + ] + ); + + $this->DB->setFakeTableData( + 'Project', + [ + [ + 'ProjectID' => 1, + 'Name' => 'Test Project', + 'Alias' => 'P1', + ], + ] + ); + + $this->identifierTypeController + = new \LORIS\IdentifierTypeController( + $this->DB + ); + + $this->candidateIdentifierController + = new \LORIS\CandidateIdentifierController( + $this->DB + ); + } + + /** + * Tests that a candidate identifier can be retrieved by ID + * + * @return void + * @covers \LORIS\CandidateIdentifierController::getCandidateIdentifierFromID + */ + public function testGetCandidateIdentifierFromID(): void + { + $candidateIdentifier = $this->candidateIdentifierController + ->getCandidateIdentifierFromID(1); + + $this->assertSame( + 1, + $candidateIdentifier->candidateIdentifierID + ); + $this->assertSame(1, $candidateIdentifier->candidateID); + $this->assertSame('1234', $candidateIdentifier->value); + + $this->assertSame( + 1, + $candidateIdentifier->type->candidateIdentifierTypeID + ); + $this->assertSame('TestID', $candidateIdentifier->type->name); + $this->assertSame( + '{SEQUENCE:4,FORMAT:numeric}', + $candidateIdentifier->type->format + ); + $this->assertTrue($candidateIdentifier->type->isRequired); + $this->assertTrue($candidateIdentifier->type->isUnique); + $this->assertTrue($candidateIdentifier->type->autoGenerate); + $this->assertFalse($candidateIdentifier->type->allowMultiple); + $this->assertSame([], $candidateIdentifier->type->projects); + $this->assertNull($candidateIdentifier->type->permissionID); + + $this->assertSame( + '2026-01-01 12:00:00', + $candidateIdentifier->dateAdded + ); + $this->assertNull($candidateIdentifier->dateEdited); + } + + /** + * Tests that retrieving a nonexistent candidate identifier throws NotFound + * + * @return void + * @covers \LORIS\CandidateIdentifierController::getCandidateIdentifierFromID + */ + public function testGetCandidateIdentifierFromIDNotFound(): void + { + $this->expectException(\NotFound::class); + + $this->candidateIdentifierController + ->getCandidateIdentifierFromID(999); + } + + /** + * Tests that a candidate identifier can be created + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifier(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: '5678', + ); + + $created = $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + + $this->assertNotNull($created->candidateIdentifierID); + $this->assertSame(2, $created->candidateID); + $this->assertSame('5678', $created->value); + $this->assertSame( + 1, + $created->type->candidateIdentifierTypeID + ); + } + + /** + * Tests that multiple values cannot be created when they are not allowed + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifierMultipleNotAllowed(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 1, + type: $identifierType, + value: '5678', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a unique value cannot be created for another candidate + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifierDuplicateValue(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: '1234', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a unique identifier value cannot be duplicated + * for the same candidate when multiple values are allowed. + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifierDuplicateValueSameCandidate(): void + { + $this->DB->update( + 'candidate_identifier_types', + ['AllowMultiple' => 1], + ['CandidateIdentifierTypeID' => 1] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 1, + type: $identifierType, + value: '1234', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that an invalid candidate identifier value cannot be created + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifierInvalidFormat(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: '12AB', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a manually entered identifier follows its format + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateManualCandidateIdentifier(): void + { + $this->DB->update( + 'candidate_identifier_types', + [ + 'Format' => '{NUMERIC:4}', + 'AutoGenerate' => 0, + ], + [ + 'CandidateIdentifierTypeID' => 1, + ] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: '5678', + ); + + $created = $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + + $this->assertSame('5678', $created->value); + $this->assertFalse($created->type->autoGenerate); + } + + /** + * Tests that an invalid manually entered identifier is rejected + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateManualCandidateIdentifierInvalidFormat(): void + { + $this->DB->update( + 'candidate_identifier_types', + [ + 'Format' => '{NUMERIC:4}', + 'AutoGenerate' => 0, + ], + [ + 'CandidateIdentifierTypeID' => 1, + ] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: '12AB', + ); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + "Identifier 'TestID' has an invalid structure. " + . "Expected format: {NUMERIC:4}" + ); + + $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that site and project aliases are resolved in the identifier format + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifierWithAliases(): void + { + $this->DB->update( + 'candidate_identifier_types', + [ + 'Format' => '{SITE:ALIAS}-{PROJECT:ALIAS}-' + . '{SEQUENCE:4,FORMAT:numeric}', + ], + [ + 'CandidateIdentifierTypeID' => 1, + ] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: 'MTL-P1-5678', + ); + + $created = $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + + $this->assertSame('MTL-P1-5678', $created->value); + } + + /** + * Tests that an incorrect site alias is rejected + * + * @return void + * @covers \LORIS\CandidateIdentifierController::createCandidateIdentifier + */ + public function testCreateCandidateIdentifierWithInvalidAlias(): void + { + $this->DB->update( + 'candidate_identifier_types', + [ + 'Format' => '{SITE:ALIAS}-{PROJECT:ALIAS}-' + . '{SEQUENCE:4,FORMAT:numeric}', + ], + [ + 'CandidateIdentifierTypeID' => 1, + ] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 2, + type: $identifierType, + value: 'TOR-P1-5678', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->createCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a candidate identifier can be updated + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifier(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 1, + candidateID: 1, + type: $identifierType, + value: '5678', + ); + + $updated = $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + + $this->assertSame(1, $updated->candidateIdentifierID); + $this->assertSame(1, $updated->candidateID); + $this->assertSame('5678', $updated->value); + $this->assertSame( + 1, + $updated->type->candidateIdentifierTypeID + ); + } + + /** + * Tests that an existing identifier cannot be moved to another candidate + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierCannotChangeCandidate(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 1, + candidateID: 2, + type: $identifierType, + value: '5678', + ); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Cannot change the candidate or identifier type of an existing' + . ' identifier' + ); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that an existing identifier cannot change its type + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierCannotChangeType(): void + { + $differentType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 2, + name: 'OtherID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: false, + isUnique: false, + autoGenerate: false, + allowMultiple: true, + ); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 1, + candidateID: 1, + type: $differentType, + value: '5678', + ); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Cannot change the candidate or identifier type of an existing' + . ' identifier' + ); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that multiple values cannot be assigned when they are not allowed + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierMultipleNotAllowed(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => '5678', + ] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 1, + candidateID: 1, + type: $identifierType, + value: '1234', + ); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Candidate already has an identifier of this type' + ); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a unique value cannot be assigned to another candidate + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierDuplicateValue(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 2, + 'CandidateIdentifierTypeID' => 1, + 'Value' => '5678', + ] + ); + + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 1, + candidateID: 1, + type: $identifierType, + value: '5678', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a candidate identifier without an ID cannot be updated + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierWithoutID(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: 1, + type: $identifierType, + value: '5678', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that updating a nonexistent candidate identifier throws NotFound + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierNotFound(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 999, + candidateID: 1, + type: $identifierType, + value: '5678', + ); + + $this->expectException(\NotFound::class); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that an invalid candidate identifier value cannot be updated + * + * @return void + * @covers \LORIS\CandidateIdentifierController::updateCandidateIdentifier + */ + public function testUpdateCandidateIdentifierInvalidFormat(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $candidateIdentifier + = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: 1, + candidateID: 1, + type: $identifierType, + value: '12AB', + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->candidateIdentifierController + ->updateCandidateIdentifier($candidateIdentifier); + } + + /** + * Tests that a candidate identifier can be deleted + * + * @return void + * @covers \LORIS\CandidateIdentifierController::deleteCandidateIdentifier + */ + public function testDeleteCandidateIdentifier(): void + { + $this->candidateIdentifierController + ->deleteCandidateIdentifier(1); + + $this->expectException(\NotFound::class); + + $this->candidateIdentifierController + ->getCandidateIdentifierFromID(1); + } + + /** + * Tests that deleting a nonexistent candidate identifier throws NotFound + * + * @return void + * @covers \LORIS\CandidateIdentifierController::deleteCandidateIdentifier + */ + public function testDeleteCandidateIdentifierNotFound(): void + { + $this->expectException(\NotFound::class); + + $this->candidateIdentifierController + ->deleteCandidateIdentifier(999); + } + + /** + * Tests that a candidate identifier can be generated and created + * + * @return void + * @covers \LORIS\CandidateIdentifierController::generateCandidateIdentifier + */ + public function testGenerateCandidateIdentifier(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $generated = $this->candidateIdentifierController + ->generateCandidateIdentifier( + 2, + $identifierType + ); + + $this->assertNotNull($generated->candidateIdentifierID); + $this->assertSame(2, $generated->candidateID); + $this->assertSame('1235', $generated->value); + $this->assertSame( + 1, + $generated->type->candidateIdentifierTypeID + ); + } + + /** + * Tests that an identifier cannot be generated when automatic generation + * is disabled + * + * @return void + * @covers \LORIS\CandidateIdentifierController::generateCandidateIdentifier + */ + public function testGenerateCandidateIdentifierAutoGenerateDisabled(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: false, + allowMultiple: false, + ); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Identifier type is not configured for automatic generation' + ); + + $this->candidateIdentifierController + ->generateCandidateIdentifier( + 2, + $identifierType + ); + } + + /** + * Tests that all identifiers for a candidate can be retrieved + * + * @return void + * @covers \LORIS\CandidateIdentifierController::getCandidateIdentifiers + */ + public function testGetCandidateIdentifiers(): void + { + $identifiers = $this->candidateIdentifierController + ->getCandidateIdentifiers(1); + + $this->assertCount(1, $identifiers); + $this->assertSame( + 1, + $identifiers[0]->candidateIdentifierID + ); + $this->assertSame(1, $identifiers[0]->candidateID); + $this->assertSame('1234', $identifiers[0]->value); + $this->assertSame( + 1, + $identifiers[0]->type->candidateIdentifierTypeID + ); + } + + /** + * Tears down the fixture and cleans up temporary tables. + * This method is called after a test is executed. + * + * @return void + */ + protected function tearDown(): void + { + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS candidate_identifiers' + ); + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS ' + . 'candidate_identifier_types_project_rel' + ); + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS candidate_identifier_types' + ); + + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS candidate' + ); + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS psc' + ); + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS Project' + ); + + $this->factory->reset(); + + parent::tearDown(); + } +} diff --git a/test/unittests/CandidateIdentifierGeneratorTest.php b/test/unittests/CandidateIdentifierGeneratorTest.php new file mode 100644 index 0000000000..5ff7fdae8c --- /dev/null +++ b/test/unittests/CandidateIdentifierGeneratorTest.php @@ -0,0 +1,727 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +require_once __DIR__ . '/../../vendor/autoload.php'; +require_once __DIR__ . '/../../php/libraries/IdentifierType.class.inc'; +require_once __DIR__ . '/../../php/libraries/IdentifierGenerator.php'; +require_once __DIR__ + . '/../../php/libraries/CandidateIdentifierGenerator.php'; + +use PHPUnit\Framework\TestCase; + +/** + * Unit tests for CandidateIdentifierGenerator class + * + * @category Tests + * @package Test + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class CandidateIdentifierGeneratorTest extends TestCase +{ + protected $factory; + protected $DB; + protected $config; + + /** + * This method is called before each test is executed. + * Sets up fixtures: factory, config, database + * + * @return void + */ + protected 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->DB->setFakeTableData( + 'candidate_identifiers', + [] + ); + } + + /** + * Tests generating the first sequential numeric identifier + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateFirstSequentialNumericIdentifier(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric,PADDING:0}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame('0000', $generator->generate()); + } + + /** + * Tests that automatic generation requires SEQUENCE or RANDOM + * + * @return void + * @covers CandidateIdentifierGenerator::__construct + */ + public function testGenerateRejectsManualOnlyFormat(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{NUMERIC:4}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $this->expectException(\ConfigurationException::class); + $this->expectExceptionMessage( + 'Invalid generation template for identifier type TestID' + ); + + new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + } + + /** + * Tests that the next sequential numeric identifier is generated correctly + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateNextSequentialNumericIdentifier(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => '0099', + ] + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric,PADDING:0}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame('0100', $generator->generate()); + } + + /** + * Tests sequential alpha generation using the default minimum value + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateFirstSequentialAlphaIdentifier(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'ALPHA-{SEQUENCE:4,FORMAT:alpha}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame( + 'ALPHA-AAAA', + $generator->generate() + ); + } + + /** + * Tests sequential alpha generation across a character boundary + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateSequentialAlphaBoundary(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => 'ALPHA-AAAZ', + ] + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'ALPHA-{SEQUENCE:4,FORMAT:alpha}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame( + 'ALPHA-AABA', + $generator->generate() + ); + } + + /** + * Tests sequential alpha generation near the default maximum value + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateAlphaDefaultMax(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => 'ALPHA-ZZZX', + ] + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'ALPHA-{SEQUENCE:4,FORMAT:alpha}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame( + 'ALPHA-ZZZY', + $generator->generate() + ); + } + + /** + * Tests that sequential alpha generation fails at the default maximum + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateAlphaDefaultMaxExceeded(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => 'ALPHA-ZZZY', + ] + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'ALPHA-{SEQUENCE:4,FORMAT:alpha}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->expectException(\LorisException::class); + $this->expectExceptionMessage( + 'Cannot create new identifier because all valid identifiers are in use!' + ); + + $generator->generate(); + } + + /** + * Tests random numeric generation + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateRandomNumericIdentifier(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'RAND-{RANDOM:4,FORMAT:numeric,PADDING:0}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertMatchesRegularExpression( + '/^RAND-[0-9]{4}$/', + $generator->generate() + ); + } + + /** + * Tests random alpha generation + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateRandomAlphaIdentifier(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'RANDALPHA-{RANDOM:4,FORMAT:alpha}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertMatchesRegularExpression( + '/^RANDALPHA-[A-Z]{4}$/', + $generator->generate() + ); + } + + /** + * Tests random alphanumeric generation + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateRandomAlphanumericIdentifier(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'RANDALPHANUM-{RANDOM:4,FORMAT:alphanumeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertMatchesRegularExpression( + '/^RANDALPHANUM-[0-9A-Z]{4}$/', + $generator->generate() + ); + } + + /** + * Tests sequential numeric generation with custom padding + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateNumericPadding(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'PAD-{SEQUENCE:4,FORMAT:numeric,PADDING:2,MIN:1}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame( + 'PAD-2221', + $generator->generate() + ); + } + + /** + * Tests that invalid numeric padding throws an exception + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateInvalidNumericPadding(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'PAD-{SEQUENCE:4,FORMAT:numeric,PADDING:X,MIN:1}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $this->expectException(\ConfigurationException::class); + $this->expectExceptionMessage( + 'Padding character must be part of the configured alphabet.' + ); + + new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + } + + /** + * Tests sequential alpha generation with custom padding + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateAlphaPadding(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'PADALPHA-{SEQUENCE:4,FORMAT:alpha,PADDING:X,MIN:A}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame( + 'PADALPHA-XXXA', + $generator->generate() + ); + } + + /** + * Tests sequential generation with minimum and maximum values + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateMinMax(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => 'MAXTEST-0001', + ] + ); + + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 2, + 'CandidateIdentifierTypeID' => 1, + 'Value' => 'MAXTEST-0002', + ] + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: 'MAXTEST-{SEQUENCE:4,FORMAT:numeric,PADDING:0,MIN:1,MAX:3}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->expectException(\LorisException::class); + $this->expectExceptionMessage( + 'Cannot create new identifier because all valid identifiers are in use!' + ); + + $generator->generate(); + } + + /** + * Tests sequential generation with a site alias + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateSiteAlias(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SITE:ALIAS}{SEQUENCE:4,FORMAT:numeric,PADDING:0}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'DCC', + '' + ); + + $this->assertSame( + 'DCC0000', + $generator->generate() + ); + } + + /** + * Tests sequential generation with a project alias + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateProjectAlias(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{PROJECT:ALIAS}{SEQUENCE:4,FORMAT:numeric,PADDING:0}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + '', + 'PUMP' + ); + + $this->assertSame( + 'PUMP0000', + $generator->generate() + ); + } + + /** + * Tests that an identifier type must be persisted before generating. + * + * @return void + * @covers CandidateIdentifierGenerator::generate + */ + public function testGenerateWithUnpersistedIdentifierType(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: null, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage( + 'Identifier type must be persisted before generating identifiers' + ); + + $generator->generate(); + } + + /** + * Tests unpadded random generation using the legacy CandID range. + * + * @return void + */ + public function testGenerateUnpaddedCandID(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'CandID', + format: '{RANDOM:10,FORMAT:numeric,MIN:100000,MAX:4294967295}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $id = $generator->generate(); + + $this->assertMatchesRegularExpression('/^[1-9][0-9]{5,9}$/', $id); + $this->assertGreaterThanOrEqual(100000, intval($id)); + $this->assertLessThanOrEqual(4294967295, intval($id)); + } + + /** + * Tests unpadded numeric sequential generation. + * + * @return void + */ + public function testGenerateUnpaddedSequentialID(): void + { + $this->DB->insert( + 'candidate_identifiers', + [ + 'CandidateID' => 1, + 'CandidateIdentifierTypeID' => 1, + 'Value' => '9', + ] + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric,MIN:1,MAX:10}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + ); + + $generator = new CandidateIdentifierGenerator( + $this->DB, + $identifierType, + 'MTL', + 'P1' + ); + + $this->assertSame('10', $generator->generate()); + } + + /** + * Tears down the fixture and cleans up temporary tables. + * This method is called after a test is executed. + * + * @return void + */ + protected function tearDown(): void + { + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS candidate_identifiers' + ); + + $this->factory->reset(); + + parent::tearDown(); + } +} diff --git a/test/unittests/CandidateTest.php b/test/unittests/CandidateTest.php index f8865fe845..5a6154428c 100644 --- a/test/unittests/CandidateTest.php +++ b/test/unittests/CandidateTest.php @@ -869,31 +869,27 @@ public function testCandidateExistsReturnsFalseWhenCandidateDoesNotExists() */ public function testValidateProjectPSCID() { - $seq = [ - 'seq' => [ - 0 => [ - '#' => '', - '@' => ['type' => 'projectAbbrev'], - ], - 1 => [ - '#' => '', - '@' => [ - 'type' => 'numeric', - 'length' => '4', - ], - ], - ], - ]; - $this->_configMap = [ - ['PSCID', [ - 'generation' => 'sequential', - 'structure' => $seq, - ] - ], - ]; + $this->_dbMock->expects($this->atLeastOnce()) + ->method('isConnected') + ->willReturn(true); - $this->_configMock->method('getSetting') - ->willReturnMap($this->_configMap); // <-- modern replacement + $this->_dbMock->method('pselectOne') + ->willReturn('1'); + + $this->_dbMock->method('pselectRow') + ->willReturn( + [ + 'CandidateIdentifierTypeID' => 1, + 'Name' => 'PSCID', + 'Format' => + '{PROJECT:ALIAS}{SEQUENCE:4,FORMAT:numeric,PADDING:0}', + 'IsRequired' => 1, + 'IsUnique' => 1, + 'AutoGenerate' => 1, + 'AllowMultiple' => 0, + 'permID' => null, + ] + ); $this->assertEquals( 1, @@ -1137,31 +1133,92 @@ function testIsAccessibleByNoCenter() */ public function testStructureToPCRE() { - $structure = [ - 'seq' => [ - 0 => ['@' => ['type' => 'alpha', - 'minLength' => '1', - 'maxLength' => '5' - ] - ], - 1 => ['@' => ['type' => 'alphanumeric', - 'length' => '2' - ] - ], - 2 => ['@' => ['type' => 'static'], - '#' => '1-3' - ], - 3 => ['@' => ['type' => 'set'], - '#' => '1||3' - ], - 4 => ['@' => ['type' => 'set'], - '#' => '1-3' - ], - ] - ]; $this->assertEquals( - '/^[a-z]{1,5}[0-9a-z]{2,2}(1-3){1,1}(1||3){1,1}[1-3]{1,1}$/i', - Candidate::structureToPCRE($structure) + '/^TEST\-[0-9]{4}$/i', + Candidate::structureToPCRE( + 'TEST-{SEQUENCE:4,PADDING:0}' + ) + ); + + $this->assertEquals( + '/^NUM\-[0-9]{4}$/i', + Candidate::structureToPCRE( + 'NUM-{SEQUENCE:4,FORMAT:numeric,PADDING:0}' + ) + ); + + $this->assertEquals( + '/^ALPHA\-[A-Z]{4}$/i', + Candidate::structureToPCRE( + 'ALPHA-{SEQUENCE:4,FORMAT:alpha,PADDING:A}' + ) + ); + + $this->assertEquals( + '/^ALPHANUM\-[0-9A-Z]{4}$/i', + Candidate::structureToPCRE( + 'ALPHANUM-{SEQUENCE:4,FORMAT:alphanumeric,PADDING:0}' + ) + ); + + $this->assertEquals( + '/^RAND\-[0-9]{4}$/i', + Candidate::structureToPCRE( + 'RAND-{RANDOM:4,FORMAT:numeric,PADDING:0}' + ) + ); + + $this->assertEquals( + '/^RANDALPHA\-[A-Z]{4}$/i', + Candidate::structureToPCRE( + 'RANDALPHA-{RANDOM:4,FORMAT:alpha,PADDING:A}' + ) + ); + + $this->assertEquals( + '/^RANDALPHANUM\-[0-9A-Z]{4}$/i', + Candidate::structureToPCRE( + 'RANDALPHANUM-{RANDOM:4,FORMAT:alphanumeric,PADDING:0}' + ) + ); + + $this->assertEquals( + '/^NUM\-[0-9]{4}$/i', + Candidate::structureToPCRE( + 'NUM-{NUMERIC:4}' + ) + ); + + $this->assertEquals( + '/^ALPHA\-[A-Z]{4}$/i', + Candidate::structureToPCRE( + 'ALPHA-{ALPHA:4}' + ) + ); + + $this->assertEquals( + '/^ALPHANUM\-[0-9A-Z]{6}$/i', + Candidate::structureToPCRE( + 'ALPHANUM-{ALPHANUMERIC:6}' + ) + ); + + // Valid and invalid manually entered values. + $pattern = Candidate::structureToPCRE('NUM-{NUMERIC:4}'); + + $validValue = 'NUM-1234'; + $invalidCharacters = 'NUM-12AB'; + $invalidLength = 'NUM-12345'; + + $this->assertSame(1, preg_match($pattern, $validValue)); + $this->assertSame(0, preg_match($pattern, $invalidCharacters)); + $this->assertSame(0, preg_match($pattern, $invalidLength)); + + $this->assertEquals( + '/^[0-9]{1,10}$/i', + Candidate::structureToPCRE( + '{RANDOM:10,FORMAT:numeric,MIN:100000,MAX:4294967295}' + ) ); } @@ -1173,23 +1230,83 @@ public function testStructureToPCRE() */ public function testStructureToPCREWithAbbreviations() { - $structure = [ - 'seq' => [ - 0 => ['@' => ['type' => 'siteAbbrev', - 'minLength' => '1', - 'maxLength' => '5' - ] - ], - 1 => ['@' => ['type' => 'projectAbbrev', - 'minLength' => '1', - 'maxLength' => '5' - ] - ] - ] - ]; $this->assertEquals( - '/^MTL{1,5}P1{1,5}$/i', - Candidate::structureToPCRE($structure, "MTL", "P1") + '/^MTL[0-9]{4}$/i', + Candidate::structureToPCRE( + '{SITE:ALIAS}{SEQUENCE:4,PADDING:0}', + 'MTL' + ) + ); + + $this->assertEquals( + '/^P1[0-9]{4}$/i', + Candidate::structureToPCRE( + '{PROJECT:ALIAS}{SEQUENCE:4,PADDING:0}', + null, + 'P1' + ) + ); + } + + /** + * Test that structureToPattern returns a human-readable pattern + * for the given identifier structure. + * + * @covers Candidate::structureToPattern + * @return void + */ + public function testStructureToPattern(): void + { + $this->assertSame( + 'TEST-####, where # represents a number (0-9).', + Candidate::structureToPattern( + 'TEST-{SEQUENCE:4,PADDING:0}' + ) + ); + + $this->assertSame( + 'NUM-####, where # represents a number (0-9).', + Candidate::structureToPattern( + 'NUM-{SEQUENCE:4,FORMAT:numeric,PADDING:0}' + ) + ); + + $this->assertSame( + 'ALPHA-####, where # represents a letter (A-Z).', + Candidate::structureToPattern( + 'ALPHA-{SEQUENCE:4,FORMAT:alpha,PADDING:A}' + ) + ); + + $this->assertSame( + 'ALPHANUM-####, where # represents a number (0-9) or letter (A-Z).', + Candidate::structureToPattern( + 'ALPHANUM-{SEQUENCE:4,FORMAT:alphanumeric,PADDING:0}' + ) + ); + + $this->assertSame( + 'RAND-####, where # represents a number (0-9).', + Candidate::structureToPattern( + 'RAND-{RANDOM:4,FORMAT:numeric,PADDING:0}' + ) + ); + + $this->assertSame( + 'TST####, where # represents a number (0-9) or letter (A-Z).', + Candidate::structureToPattern( + '{SITE:ALIAS}{SEQUENCE:4,FORMAT:alphanumeric,PADDING:0}', + 'TST' + ) + ); + + $this->assertSame( + 'P1####, where # represents a number (0-9).', + Candidate::structureToPattern( + '{PROJECT:ALIAS}{SEQUENCE:4,FORMAT:numeric,PADDING:0}', + null, + 'P1' + ) ); } diff --git a/test/unittests/IdentifierTypeControllerTest.php b/test/unittests/IdentifierTypeControllerTest.php new file mode 100644 index 0000000000..607f6933bd --- /dev/null +++ b/test/unittests/IdentifierTypeControllerTest.php @@ -0,0 +1,453 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +require_once __DIR__ . '/../../vendor/autoload.php'; +require_once __DIR__ . '/../../php/libraries/IdentifierType.class.inc'; +require_once __DIR__ . '/../../php/libraries/IdentifierTypeController.class.inc'; + +use PHPUnit\Framework\TestCase; + +/** + * Unit tests for IdentifierTypeController class + * + * @category Tests + * @package Test + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class IdentifierTypeControllerTest extends TestCase +{ + protected $factory; + protected $DB; + protected $config; + protected $identifierTypeController; + + /** + * This method is called before each test is executed. + * Sets up fixtures: factory, config, database + * + * @return void + */ + protected 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->DB->setFakeTableData( + 'candidate_identifier_types', + [ + [ + 'CandidateIdentifierTypeID' => 1, + 'Name' => 'TestID', + 'Format' => '{SEQUENCE:4,FORMAT:numeric}', + 'IsRequired' => 1, + 'IsUnique' => 1, + 'AutoGenerate' => 1, + 'AllowMultiple' => 0, + 'permID' => null, + ], + ] + ); + + $this->DB->setFakeTableData( + 'candidate_identifier_types_project_rel', + [] + ); + + $this->identifierTypeController = new \LORIS\IdentifierTypeController( + $this->DB + ); + } + + /** + * Tests that all identifier types can be retrieved. + * + * @return void + * @covers \LORIS\IdentifierTypeController::getAllIdentifierTypes + */ + public function testGetAllIdentifierTypes(): void + { + $identifierTypes = $this->identifierTypeController + ->getAllIdentifierTypes(); + + $this->assertCount(1, $identifierTypes); + $this->assertInstanceOf( + \LORIS\IdentifierType::class, + $identifierTypes[0] + ); + $this->assertSame( + 1, + $identifierTypes[0]->candidateIdentifierTypeID + ); + $this->assertSame('TestID', $identifierTypes[0]->name); + $this->assertSame([], $identifierTypes[0]->projects); + } + + /** + * Tests that an identifier can be retrieved by ID + * + * @return void + * @covers \LORIS\IdentifierTypeController::getIdentifierTypeFromID + */ + public function testGetIdentifierTypeFromID(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromID(1); + + $this->assertSame(1, $identifierType->candidateIdentifierTypeID); + $this->assertSame('TestID', $identifierType->name); + $this->assertSame( + '{SEQUENCE:4,FORMAT:numeric}', + $identifierType->format + ); + $this->assertTrue($identifierType->isRequired); + $this->assertTrue($identifierType->isUnique); + $this->assertTrue($identifierType->autoGenerate); + $this->assertFalse($identifierType->allowMultiple); + $this->assertSame([], $identifierType->projects); + $this->assertNull($identifierType->permissionID); + } + + /** + * Tests that retrieving a nonexistent identifier throws NotFound + * + * @return void + * @covers \LORIS\IdentifierTypeController::getIdentifierTypeFromID + */ + public function testGetIdentifierTypeFromIDNotFound(): void + { + $this->expectException(\NotFound::class); + + $this->identifierTypeController->getIdentifierTypeFromID(999); + } + + /** + * Tests that an identifier type can be retrieved by name + * + * @return void + * @covers \LORIS\IdentifierTypeController::getIdentifierTypeFromName + */ + public function testGetIdentifierTypeFromName(): void + { + $identifierType = $this->identifierTypeController + ->getIdentifierTypeFromName('TestID'); + + $this->assertSame(1, $identifierType->candidateIdentifierTypeID); + $this->assertSame('TestID', $identifierType->name); + $this->assertSame( + '{SEQUENCE:4,FORMAT:numeric}', + $identifierType->format + ); + } + + /** + * Tests that retrieving a nonexistent identifier type by name + * throws NotFound + * + * @return void + * @covers \LORIS\IdentifierTypeController::getIdentifierTypeFromName + */ + public function testGetIdentifierTypeFromNameNotFound(): void + { + $this->expectException(\NotFound::class); + + $this->identifierTypeController + ->getIdentifierTypeFromName('NonexistentID'); + } + + /** + * Tests that an identifier type can be created + * + * @return void + * @covers \LORIS\IdentifierTypeController::createIdentifierType + */ + public function testCreateIdentifierType(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: null, + name: 'CreatedID', + format: '{SEQUENCE:6,FORMAT:numeric}', + isRequired: false, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + projects: [], + permissionID: null, + ); + + $created = $this->identifierTypeController->createIdentifierType( + $identifierType + ); + + $this->assertNotNull($created->candidateIdentifierTypeID); + $this->assertSame('CreatedID', $created->name); + $this->assertSame( + '{SEQUENCE:6,FORMAT:numeric}', + $created->format + ); + $this->assertFalse($created->isRequired); + $this->assertTrue($created->isUnique); + $this->assertTrue($created->autoGenerate); + $this->assertFalse($created->allowMultiple); + $this->assertSame([], $created->projects); + $this->assertNull($created->permissionID); + } + + /** + * Tests that an identifier type can be created with a project + * + * @return void + * @covers \LORIS\IdentifierTypeController::createIdentifierType + */ + public function testCreateIdentifierTypeWithProject(): void + { + $project = \Project::getProjectFromID( + new \ProjectID('1') + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: null, + name: 'ProjectID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + projects: [$project], + permissionID: null, + ); + + $created = $this->identifierTypeController->createIdentifierType( + $identifierType + ); + + $this->assertCount(1, $created->projects); + $this->assertSame( + '1', + strval($created->projects[0]->getId()) + ); + } + + /** + * Tests that an identifier type can be created with a permission + * + * @return void + * @covers \LORIS\IdentifierTypeController::createIdentifierType + */ + public function testCreateIdentifierTypeWithPermission(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: null, + name: 'PermissionID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + projects: [], + permissionID: 1, + ); + + $created = $this->identifierTypeController->createIdentifierType( + $identifierType + ); + + $this->assertSame(1, $created->permissionID); + } + + /** + * Tests that an identifier type can be updated + * + * @return void + * @covers \LORIS\IdentifierTypeController::updateIdentifierType + */ + public function testUpdateIdentifierType(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'UpdatedID', + format: '{SEQUENCE:8,FORMAT:numeric}', + isRequired: false, + isUnique: false, + autoGenerate: false, + allowMultiple: true, + projects: [], + permissionID: null, + ); + + $updated = $this->identifierTypeController->updateIdentifierType( + $identifierType + ); + + $this->assertSame(1, $updated->candidateIdentifierTypeID); + $this->assertSame('UpdatedID', $updated->name); + $this->assertSame( + '{SEQUENCE:8,FORMAT:numeric}', + $updated->format + ); + $this->assertFalse($updated->isRequired); + $this->assertFalse($updated->isUnique); + $this->assertFalse($updated->autoGenerate); + $this->assertTrue($updated->allowMultiple); + $this->assertSame([], $updated->projects); + $this->assertNull($updated->permissionID); + } + + /** + * Tests that an identifier type's projects can be updated + * + * @return void + * @covers \LORIS\IdentifierTypeController::updateIdentifierType + */ + public function testUpdateIdentifierTypeWithProject(): void + { + $project = \Project::getProjectFromID( + new \ProjectID('1') + ); + + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + projects: [$project], + permissionID: null, + ); + + $updated = $this->identifierTypeController->updateIdentifierType( + $identifierType + ); + + $this->assertCount(1, $updated->projects); + $this->assertSame( + '1', + strval($updated->projects[0]->getId()) + ); + } + + /** + * Tests that an identifier type's permission can be updated + * + * @return void + * @covers \LORIS\IdentifierTypeController::updateIdentifierType + */ + public function testUpdateIdentifierTypeWithPermission(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: 1, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + projects: [], + permissionID: 1, + ); + + $updated = $this->identifierTypeController->updateIdentifierType( + $identifierType + ); + + $this->assertSame(1, $updated->permissionID); + } + + /** + * Tests that an identifier type without an ID cannot be updated + * + * @return void + * @covers \LORIS\IdentifierTypeController::updateIdentifierType + */ + public function testUpdateIdentifierTypeWithoutID(): void + { + $identifierType = new \LORIS\IdentifierType( + candidateIdentifierTypeID: null, + name: 'TestID', + format: '{SEQUENCE:4,FORMAT:numeric}', + isRequired: true, + isUnique: true, + autoGenerate: true, + allowMultiple: false, + projects: [], + permissionID: null, + ); + + $this->expectException(\InvalidArgumentException::class); + + $this->identifierTypeController->updateIdentifierType( + $identifierType + ); + } + + /** + * Tests that an identifier type can be deleted + * + * @return void + * @covers \LORIS\IdentifierTypeController::deleteIdentifierType + */ + public function testDeleteIdentifierType(): void + { + $this->identifierTypeController->deleteIdentifierType(1); + + $this->expectException(\NotFound::class); + + $this->identifierTypeController->getIdentifierTypeFromID(1); + } + + /** + * Tests that deleting a nonexistent identifier type throws NotFound + * + * @return void + * @covers \LORIS\IdentifierTypeController::deleteIdentifierType + */ + public function testDeleteIdentifierTypeNotFound(): void + { + $this->expectException(\NotFound::class); + + $this->identifierTypeController->deleteIdentifierType(2); + } + + /** + * Tears down the fixture and cleans up temporary tables. + * This method is called after a test is executed. + * + * @return void + */ + protected function tearDown(): void + { + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS ' + . 'candidate_identifier_types_project_rel' + ); + $this->DB->run( + 'DROP TEMPORARY TABLE IF EXISTS candidate_identifier_types' + ); + + $this->factory->reset(); + + parent::tearDown(); + } +} diff --git a/tools/single_use/migrate_candidate_identifiers.php b/tools/single_use/migrate_candidate_identifiers.php index 5193a655c4..335debf87b 100644 --- a/tools/single_use/migrate_candidate_identifiers.php +++ b/tools/single_use/migrate_candidate_identifiers.php @@ -88,6 +88,8 @@ function convertIdentifierFormat(array $settings): string ); if ($generation !== null) { + $segment .= ',PADDING:' + . ($attributes['type'] === 'alpha' ? 'A' : '0'); foreach (['min' => 'MIN', 'max' => 'MAX'] as $key => $option) { if (isset($attributes[$key])) { $segment .= ',' . $option . ':' . $attributes[$key]; From 8c7b2626c8bcac0166d29f50d97a0a4ba6dd152d Mon Sep 17 00:00:00 2001 From: HachemJ Date: Tue, 3 Nov 2026 10:26:50 -0500 Subject: [PATCH 2/4] Add candidate identifier REST API endpoints --- .../endpoints/candidate/candidate.class.inc | 19 + .../endpoints/candidate/identifiers.class.inc | 503 ++++++++++++++++++ .../php/views/candidateidentifier.class.inc | 54 ++ modules/api/static/schema-v0.0.4-dev.yml | 177 ++++++ 4 files changed, 753 insertions(+) create mode 100644 modules/api/php/endpoints/candidate/identifiers.class.inc create mode 100644 modules/api/php/views/candidateidentifier.class.inc diff --git a/modules/api/php/endpoints/candidate/candidate.class.inc b/modules/api/php/endpoints/candidate/candidate.class.inc index 3fd38ed8a6..13768a314f 100644 --- a/modules/api/php/endpoints/candidate/candidate.class.inc +++ b/modules/api/php/endpoints/candidate/candidate.class.inc @@ -100,6 +100,25 @@ class Candidate extends Endpoint implements \LORIS\Middleware\ETagCalculator } // Delegate to sub-endpoints + if ($pathparts[0] === 'identifiers') { + array_shift($pathparts); + + $newrequest = $request->withAttribute( + 'pathparts', + $pathparts + ); + + $handler = new Identifiers( + $this->loris, + $this->_candidate + ); + + return $handler->process( + $newrequest, + $handler + ); + } + $visit_label = urldecode(array_shift($pathparts)); $newrequest = $request ->withAttribute('pathparts', $pathparts); diff --git a/modules/api/php/endpoints/candidate/identifiers.class.inc b/modules/api/php/endpoints/candidate/identifiers.class.inc new file mode 100644 index 0000000000..f9975d2234 --- /dev/null +++ b/modules/api/php/endpoints/candidate/identifiers.class.inc @@ -0,0 +1,503 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://github.com/aces/Loris + */ +namespace LORIS\api\Endpoints\Candidate; + +use \Psr\Http\Message\ServerRequestInterface; +use \Psr\Http\Message\ResponseInterface; +use \LORIS\api\Endpoint; + +/** + * A class for handling candidate identifiers + * + * @category API + * @package Loris + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://github.com/aces/Loris + */ +class Identifiers extends Endpoint implements \LORIS\Middleware\ETagCalculator +{ + /** + * The requested Candidate + * + * @var \Candidate + */ + private $_candidate; + + /** + * Permission codes indexed by permission ID. + * + * @var array + */ + private array $_permissionCodes = []; + + /** + * Constructor + * + * @param \LORIS\LorisInstance $loris The LORIS instance to retrieve data + * from. + * @param \Candidate $candidate The requested candidate. + */ + public function __construct( + protected \LORIS\LorisInstance $loris, + \Candidate $candidate + ) { + $this->_candidate = $candidate; + } + + /** + * Return which methods are supported by this endpoint + * + * @return array supported HTTP methods + */ + protected function allowedMethods() : array + { + return ['GET', 'POST', 'PUT', 'DELETE']; + } + + /** + * Versions of the LORIS API which are supported by this endpoint. + * + * @return array a list of supported API versions. + */ + protected function supportedVersions() : array + { + return [ + 'v0.0.4-dev', + ]; + } + + /** + * Handles a request for candidate identifiers + * + * @param ServerRequestInterface $request The incoming PSR7 request + * + * @return ResponseInterface The outgoing PSR7 response + */ + public function handle(ServerRequestInterface $request) : ResponseInterface + { + $pathparts = $request->getAttribute('pathparts'); + + if (count($pathparts) !== 0) { + return new \LORIS\Http\Response\JSON\NotFound(); + } + + switch ($request->getMethod()) { + case 'GET': + return $this->_handleGET($request); + + case 'POST': + return $this->_handlePOST($request); + + case 'PUT': + return $this->_handlePUT($request); + + case 'DELETE': + return $this->_handleDELETE($request); + + case 'OPTIONS': + return (new \LORIS\Http\Response()) + ->withHeader('Allow', $this->allowedMethods()); + + default: + return new \LORIS\Http\Response\JSON\MethodNotAllowed( + $this->allowedMethods() + ); + } + } + + /** + * Checks whether a user can access an identifier type for this candidate. + * + * @param \User $user Requesting user + * @param \LORIS\IdentifierType $identifierType Identifier type + * + * @return bool Whether access is permitted + */ + private function _canAccessIdentifierType( + \User $user, + \LORIS\IdentifierType $identifierType + ): bool { + $projectID = $this->_candidate->getProjectID(); + + if (!empty($identifierType->projects)) { + $projectAllowed = false; + + foreach ($identifierType->projects as $project) { + if ($project->getId() == $projectID) { + $projectAllowed = true; + break; + } + } + + if (!$projectAllowed || !$user->hasProject($projectID)) { + return false; + } + } + + if ($identifierType->permissionID !== null) { + $database = $this->loris->getDatabaseConnection(); + + $permissionID = $identifierType->permissionID; + + if (!array_key_exists($permissionID, $this->_permissionCodes)) { + $permission = $database->pselectRow( + "SELECT code FROM permissions WHERE permID = :permID", + ['permID' => $permissionID] + ); + + $this->_permissionCodes[$permissionID] + = $permission['code'] ?? null; + } + + $permissionCode = $this->_permissionCodes[$permissionID]; + + if ($permissionCode === null + || !$user->hasPermission($permissionCode) + ) { + return false; + } + } + + return true; + } + + /** + * Returns the candidate's identifiers + * + * @param ServerRequestInterface $request The incoming PSR7 request + * + * @return ResponseInterface The outgoing PSR7 response + */ + private function _handleGET( + ServerRequestInterface $request + ): ResponseInterface { + $controller = new \LORIS\CandidateIdentifierController( + $this->loris->getDatabaseConnection() + ); + + $identifiers = $controller->getCandidateIdentifiers( + (int) $this->_candidate->getID() + ); + + $user = $request->getAttribute('user'); + + $data = []; + foreach ($identifiers as $identifier) { + if (!$this->_canAccessIdentifierType($user, $identifier->type)) { + continue; + } + + $data[] = ( + new \LORIS\api\Views\CandidateIdentifier($identifier) + )->toArray(); + } + + return new \LORIS\Http\Response\JsonResponse( + ['Identifiers' => $data] + ); + } + + /** + * Creates a candidate identifier + * + * @param ServerRequestInterface $request The incoming PSR7 request + * + * @return ResponseInterface + */ + private function _handlePOST( + ServerRequestInterface $request + ): ResponseInterface { + $data = json_decode((string) $request->getBody(), true); + + if (!isset($data['Identifier'])) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'There is no Identifier object in the POST data' + ); + } + + if (!isset($data['Identifier']['CandidateIdentifierTypeID'])) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'CandidateIdentifierTypeID is required' + ); + } + + $database = $this->loris->getDatabaseConnection(); + + $typeController = new \LORIS\IdentifierTypeController( + $database + ); + + try { + $identifierType = $typeController->getIdentifierTypeFromID( + (int) $data['Identifier']['CandidateIdentifierTypeID'] + ); + } catch (\NotFound $e) { + return new \LORIS\Http\Response\JSON\BadRequest( + $e->getMessage() + ); + } + + $user = $request->getAttribute('user'); + + if (!$this->_canAccessIdentifierType($user, $identifierType)) { + return new \LORIS\Http\Response\JSON\Forbidden( + 'You cannot add an identifier of this type' + ); + } + + $controller = new \LORIS\CandidateIdentifierController( + $database + ); + + try { + if ($identifierType->autoGenerate) { + $identifier = $controller->generateCandidateIdentifier( + (int) $this->_candidate->getID(), + $identifierType + ); + } else { + if (!isset($data['Identifier']['Value'])) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'Value is required for this identifier type' + ); + } + + $identifier = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: null, + candidateID: (int) $this->_candidate->getID(), + type: $identifierType, + value: $data['Identifier']['Value'], + ); + + $identifier = $controller->createCandidateIdentifier( + $identifier + ); + } + } catch (\InvalidArgumentException | \ConflictException $e) { + return new \LORIS\Http\Response\JSON\BadRequest( + $e->getMessage() + ); + } + + $body = ( + new \LORIS\api\Views\CandidateIdentifier($identifier) + )->toArray(); + + return (new \LORIS\Http\Response\JsonResponse($body)) + ->withStatus(201); + } + + /** + * Updates a candidate identifier + * + * @param ServerRequestInterface $request The incoming PSR7 request + * + * @return ResponseInterface + */ + private function _handlePUT( + ServerRequestInterface $request + ): ResponseInterface { + $data = json_decode((string) $request->getBody(), true); + + if (!isset($data['Identifier']) + || !is_array($data['Identifier']) + ) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'There is no Identifier object in the PUT data' + ); + } + + $identifierData = $data['Identifier']; + + if (!isset($identifierData['CandidateIdentifierID']) + || !isset($identifierData['CandidateIdentifierTypeID']) + || !isset($identifierData['Value']) + ) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'CandidateIdentifierID, CandidateIdentifierTypeID and Value' + . ' are required' + ); + } + + $database = $this->loris->getDatabaseConnection(); + + $controller = new \LORIS\CandidateIdentifierController( + $database + ); + + try { + $existingIdentifier = $controller->getCandidateIdentifierFromID( + (int) $identifierData['CandidateIdentifierID'] + ); + } catch (\NotFound $e) { + return new \LORIS\Http\Response\JSON\NotFound(); + } + + if ($existingIdentifier->candidateID !== (int) $this->_candidate->getID() + ) { + return new \LORIS\Http\Response\JSON\NotFound(); + } + + if ($existingIdentifier->type->name === 'PSCID') { + return new \LORIS\Http\Response\JSON\Forbidden( + 'PSCID identifiers cannot be edited' + ); + } + + $requestedTypeID = (int) $identifierData['CandidateIdentifierTypeID']; + $existingTypeID = $existingIdentifier->type->candidateIdentifierTypeID; + + if ($requestedTypeID !== $existingTypeID) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'CandidateIdentifierTypeID cannot be changed' + ); + } + + $typeController = new \LORIS\IdentifierTypeController( + $database + ); + + try { + $identifierType = $typeController->getIdentifierTypeFromID( + (int) $identifierData['CandidateIdentifierTypeID'] + ); + } catch (\NotFound $e) { + return new \LORIS\Http\Response\JSON\BadRequest( + $e->getMessage() + ); + } + + $user = $request->getAttribute('user'); + + if (!$this->_canAccessIdentifierType($user, $existingIdentifier->type) + || !$this->_canAccessIdentifierType($user, $identifierType) + ) { + return new \LORIS\Http\Response\JSON\Forbidden( + 'You cannot edit an identifier of this type' + ); + } + + $identifier = new \LORIS\StudyEntities\Candidate\CandidateIdentifier( + candidateIdentifierID: $existingIdentifier->candidateIdentifierID, + candidateID: (int) $this->_candidate->getID(), + type: $identifierType, + value: $identifierData['Value'], + ); + + try { + $identifier = $controller->updateCandidateIdentifier( + $identifier + ); + } catch (\InvalidArgumentException | \ConflictException $e) { + return new \LORIS\Http\Response\JSON\BadRequest( + $e->getMessage() + ); + } + + $body = ( + new \LORIS\api\Views\CandidateIdentifier($identifier) + )->toArray(); + + return new \LORIS\Http\Response\JsonResponse($body); + } + + /** + * Deletes an existing candidate identifier. + * + * @param ServerRequestInterface $request The incoming PSR7 request + * + * @return ResponseInterface The outgoing PSR7 response + */ + private function _handleDELETE( + ServerRequestInterface $request + ): ResponseInterface { + $data = json_decode((string) $request->getBody(), true); + + if (!isset($data['Identifier']['CandidateIdentifierID'])) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'CandidateIdentifierID is required' + ); + } + + $candidateIdentifierID = filter_var( + $data['Identifier']['CandidateIdentifierID'], + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + + if ($candidateIdentifierID === false) { + return new \LORIS\Http\Response\JSON\BadRequest( + 'CandidateIdentifierID must be a positive integer' + ); + } + + $database = $this->loris->getDatabaseConnection(); + + $controller = new \LORIS\CandidateIdentifierController( + $database + ); + + try { + $existingIdentifier = $controller->getCandidateIdentifierFromID( + $candidateIdentifierID + ); + } catch (\NotFound $e) { + return new \LORIS\Http\Response\JSON\NotFound(); + } + + if ($existingIdentifier->candidateID !== (int) $this->_candidate->getID() + ) { + return new \LORIS\Http\Response\JSON\NotFound(); + } + + $user = $request->getAttribute('user'); + + if (!$this->_canAccessIdentifierType($user, $existingIdentifier->type)) { + return new \LORIS\Http\Response\JSON\Forbidden( + 'You cannot delete an identifier of this type' + ); + } + + if ($existingIdentifier->type->name === 'PSCID') { + return new \LORIS\Http\Response\JSON\Forbidden( + 'PSCID identifiers cannot be deleted' + ); + } + + if ($existingIdentifier->type->isRequired) { + return new \LORIS\Http\Response\JSON\Forbidden( + 'Required identifiers cannot be deleted' + ); + } + + $controller->deleteCandidateIdentifier($candidateIdentifierID); + + return new \LORIS\Http\Response\JsonResponse( + ['success' => true] + ); + } + + /** + * Implements the ETagCalculator interface. + * + * @param ServerRequestInterface $request The PSR7 incoming request. + * + * @return string etag summarizing value of this request. + */ + public function ETag(ServerRequestInterface $request) : string + { + return md5(json_encode($this->_handleGET($request)->getBody())); + } +} diff --git a/modules/api/php/views/candidateidentifier.class.inc b/modules/api/php/views/candidateidentifier.class.inc new file mode 100644 index 0000000000..ff48d580aa --- /dev/null +++ b/modules/api/php/views/candidateidentifier.class.inc @@ -0,0 +1,54 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ + +namespace LORIS\api\Views; + +use LORIS\StudyEntities\Candidate\CandidateIdentifier as CandidateIdentifierEntity; + +/** + * This class formats a candidate identifier into an array following + * the API specifications + * + * @category ApiViews + * @package Loris + * @author Jad El Hachem + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +class CandidateIdentifier +{ + /** + * Constructor + * + * @param CandidateIdentifierEntity $identifier The identifier to format + */ + public function __construct( + private CandidateIdentifierEntity $identifier + ) { + } + + /** + * Generates the array + * + * @return array + */ + public function toArray() : array + { + return [ + 'CandidateIdentifierID' => $this->identifier->candidateIdentifierID, + 'Type' => $this->identifier->type->name, + 'Value' => $this->identifier->value, + 'DateAdded' => $this->identifier->dateAdded, + 'DateEdited' => $this->identifier->dateEdited, + ]; + } +} diff --git a/modules/api/static/schema-v0.0.4-dev.yml b/modules/api/static/schema-v0.0.4-dev.yml index d5035ef6b9..d777535d00 100644 --- a/modules/api/static/schema-v0.0.4-dev.yml +++ b/modules/api/static/schema-v0.0.4-dev.yml @@ -266,6 +266,161 @@ paths: application/json: schema: $ref: '#/components/schemas/inline_response_200_2' + '/candidates/{id}/identifiers': + get: + tags: + - Candidates + summary: Get all identifiers for a candidate + parameters: + - name: id + in: path + description: The candidate identifier. Either a PSCID or CandID + required: true + style: simple + explode: false + schema: + type: string + responses: + '200': + description: The candidate identifiers + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateIdentifiers' + post: + tags: + - Candidates + summary: Create a candidate identifier + parameters: + - name: id + in: path + description: The candidate identifier. Either a PSCID or CandID + required: true + style: simple + explode: false + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + Identifier: + type: object + required: + - CandidateIdentifierTypeID + properties: + CandidateIdentifierTypeID: + type: integer + Value: + type: string + responses: + '201': + description: The candidate identifier was created + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateIdentifier' + '400': + description: The candidate identifier could not be created + put: + tags: + - Candidates + summary: Update a candidate identifier + parameters: + - name: id + in: path + description: The candidate identifier. Either a PSCID or CandID + required: true + style: simple + explode: false + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - Identifier + properties: + Identifier: + type: object + required: + - CandidateIdentifierID + - CandidateIdentifierTypeID + - Value + properties: + CandidateIdentifierID: + type: integer + description: ID of the existing identifier to update + CandidateIdentifierTypeID: + type: integer + Value: + type: string + responses: + '200': + description: The candidate identifier was updated + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateIdentifier' + '400': + description: Invalid identifier data + '403': + description: Permission denied + '404': + description: Candidate or identifier not found + delete: + tags: + - Candidates + summary: Delete a candidate identifier + parameters: + - name: id + in: path + description: The candidate identifier. Either a PSCID or CandID + required: true + style: simple + explode: false + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - Identifier + properties: + Identifier: + type: object + required: + - CandidateIdentifierID + properties: + CandidateIdentifierID: + type: integer + minimum: 1 + description: ID of the existing identifier to delete + responses: + '200': + description: The candidate identifier was deleted + content: + application/json: + schema: + type: object + properties: + success: + type: boolean + '400': + description: Invalid identifier data + '403': + description: Permission denied + '404': + description: Candidate or identifier not found '/candidates/{id}/{visit}': get: tags: @@ -2128,6 +2283,28 @@ components: - Female - Male - Other + CandidateIdentifiers: + type: object + properties: + Identifiers: + type: array + items: + $ref: '#/components/schemas/CandidateIdentifier' + CandidateIdentifier: + type: object + properties: + CandidateIdentifierID: + type: integer + Type: + type: string + Value: + type: string + DateAdded: + type: string + nullable: true + DateEdited: + type: string + nullable: true NewCandidate: type: object properties: From 37e353ec5bf572629377489cb2011e1ec6c71711 Mon Sep 17 00:00:00 2001 From: HachemJ Date: Tue, 3 Nov 2026 10:30:41 -0500 Subject: [PATCH 3/4] Add candidate identifier type configuration --- .../ajax/updateCandidateIdentifierType.php | 155 +++++ .../jsx/formCandidateIdentifierTypes.tsx | 553 ++++++++++++++++++ modules/configuration/jsx/index.tsx | 14 + .../configuration/locale/configuration.pot | 51 +- .../locale/fr/LC_MESSAGES/configuration.po | 51 +- .../php/candidate_identifier_types.class.inc | 137 +++++ webpack.config.ts | 1 + 7 files changed, 956 insertions(+), 6 deletions(-) create mode 100644 modules/configuration/ajax/updateCandidateIdentifierType.php create mode 100644 modules/configuration/jsx/formCandidateIdentifierTypes.tsx create mode 100644 modules/configuration/php/candidate_identifier_types.class.inc 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 ( + +
+ + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ + + + { + setValues({...defaults}); + setStatus(null); + }} + /> + + {status && ( +
+ +
+ )} +
+
+ ); +} + +/** + * 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'} + )} +

+ + ({ + id: `identifier-type-${id}`, + label: identifierType.name, + })), + ]} + defaultTab="identifier-type-new" + updateURL={false} + > + {Object.entries(identifierTypes).map(([id, identifierType]) => ( + +

+ {identifierType.name} (ID: {id}) +

+
+ + +
+ ))} + + +

+ {props.t( + 'New Identifier Type', + {ns: 'configuration'} + )} +

+
+ + undefined} + t={props.t} + /> +
+
+ + ); +} + +/** + * Load identifier type data and render the manager. + * + * @param props Translation properties + * @return + */ +function IdentifierTypePage( + props: WithTranslation +): React.ReactElement { + const [data, setData] = useState(null); + const [error, setError] = useState(false); + + useEffect(() => { + const dataURL = new URL(window.location.href); + dataURL.searchParams.set('format', 'json'); + + client.get(dataURL.toString()) + .then((responseData: IdentifierTypeData) => { + setData(responseData); + }) + .catch(() => setError(true)); + }, []); + + if (error) { + return ( +

+ {props.t( + 'An error occurred while loading the page.', + {ns: 'loris'} + )} +

+ ); + } + + if (data === null) { + return ; + } + + return ( + + ); +} + +window.addEventListener('load', () => { + i18n.addResourceBundle('ja', 'configuration', jaStrings); + i18n.addResourceBundle('fr', 'configuration', frStrings); + i18n.addResourceBundle('zh', 'configuration', zhStrings); + + const workspace = document.getElementById('lorisworkspace'); + + if (workspace === null) { + throw new Error('Could not find lorisworkspace root'); + } + + const Page = withTranslation( + ['configuration', 'loris'] + )(IdentifierTypePage); + + createRoot(workspace).render(); +}); + +export default withTranslation( + ['configuration', 'loris'] +)(IdentifierTypePage); diff --git a/modules/configuration/jsx/index.tsx b/modules/configuration/jsx/index.tsx index 436d3f5f34..6b3a9ce6fb 100644 --- a/modules/configuration/jsx/index.tsx +++ b/modules/configuration/jsx/index.tsx @@ -171,6 +171,20 @@ function IntroText(props: BaseURLProps): React.ReactElement { ]} />

+

+ click here.'} + components={[ + , + ]} + /> +

); } 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 here." msgstr "" +msgid "To configure candidate identifier types <0>click here." +msgstr "" + msgid "To configure the diagnosis trajectory of the study <0>click here." 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 ici." msgid "To configure study projects <0>click here." msgstr "Pour configurer les projets de l'étude, <0>cliquez ici." +msgid "To configure candidate identifier types <0>click here." +msgstr "Pour configurer les types d'identifiants de candidats, <0>cliquez ici." + msgid "To configure the diagnosis trajectory of the study <0>click here." msgstr "Pour configurer la trajectoire diagnostique de l'étude, <0>cliquez ici." @@ -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/webpack.config.ts b/webpack.config.ts index 762f805600..5847e46f7c 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -22,6 +22,7 @@ const lorisModules: Record = { 'formCohort', 'formProject', 'index', + 'formCandidateIdentifierTypes', ], conflict_resolver: ['conflict_resolver', 'CandidateConflictsWidget'], battery_manager: ['batteryManagerIndex'], From 5a709caa04f4fb903ae1bf6396757a109c08f700 Mon Sep 17 00:00:00 2001 From: HachemJ Date: Tue, 3 Nov 2026 10:40:51 -0500 Subject: [PATCH 4/4] Add candidate identifiers module --- Makefile | 3 + SQL/0000-00-01-Modules.sql | 1 + ...10-27-add_candidate_identifiers_module.sql | 2 + modules/candidate_identifiers/README.md | 47 +++ .../help/candidate_identifiers.md | 9 + .../jsx/addIdentifierForm.tsx | 202 ++++++++++ .../jsx/candidateIdentifiersIndex.tsx | 369 ++++++++++++++++++ .../jsx/editIdentifierForm.tsx | 191 +++++++++ .../locale/candidate_identifiers.pot | 82 ++++ .../fr/LC_MESSAGES/candidate_identifiers.po | 83 ++++ .../php/candidate_identifiers.class.inc | 133 +++++++ .../php/candidateidentifierrow.class.inc | 72 ++++ ...andidateidentifierrowprovisioner.class.inc | 134 +++++++ .../php/module.class.inc | 62 +++ .../candidate_identifiers/test/TestPlan.md | 21 + webpack.config.ts | 1 + 16 files changed, 1412 insertions(+) create mode 100644 SQL/New_patches/2026-10-27-add_candidate_identifiers_module.sql create mode 100644 modules/candidate_identifiers/README.md create mode 100644 modules/candidate_identifiers/help/candidate_identifiers.md create mode 100644 modules/candidate_identifiers/jsx/addIdentifierForm.tsx create mode 100644 modules/candidate_identifiers/jsx/candidateIdentifiersIndex.tsx create mode 100644 modules/candidate_identifiers/jsx/editIdentifierForm.tsx create mode 100644 modules/candidate_identifiers/locale/candidate_identifiers.pot create mode 100644 modules/candidate_identifiers/locale/fr/LC_MESSAGES/candidate_identifiers.po create mode 100644 modules/candidate_identifiers/php/candidate_identifiers.class.inc create mode 100644 modules/candidate_identifiers/php/candidateidentifierrow.class.inc create mode 100644 modules/candidate_identifiers/php/candidateidentifierrowprovisioner.class.inc create mode 100644 modules/candidate_identifiers/php/module.class.inc create mode 100644 modules/candidate_identifiers/test/TestPlan.md diff --git a/Makefile b/Makefile index af0a150a17..d28c9962d6 100755 --- a/Makefile +++ b/Makefile @@ -149,3 +149,6 @@ dicom_archive: $(filter modules/dicom_archive/%,$(MOFILES)) $(filter modules/dic configuration: $(filter modules/configuration/%,$(MOFILES)) $(filter modules/configuration/%,$(I18NJSONFILES)) target=configuration npm run compile + +candidate_identifiers: $(filter modules/candidate_identifiers/%,$(MOFILES)) $(filter modules/candidate_identifiers/%,$(I18NJSONFILES)) + target=candidate_identifiers npm run compile \ No newline at end of file diff --git a/SQL/0000-00-01-Modules.sql b/SQL/0000-00-01-Modules.sql index f43cd5648e..71c85aaf91 100644 --- a/SQL/0000-00-01-Modules.sql +++ b/SQL/0000-00-01-Modules.sql @@ -14,6 +14,7 @@ INSERT INTO modules (Name, Active) VALUES ('biobank', 'N'); INSERT INTO modules (Name, Active) VALUES ('brainbrowser', 'N'); INSERT INTO modules (Name, Active) VALUES ('bvl_feedback', 'N'); INSERT INTO modules (Name, Active) VALUES ('candidate_list', 'N'); +INSERT INTO modules (Name, Active) VALUES ('candidate_identifiers', 'N'); INSERT INTO modules (Name, Active) VALUES ('candidate_parameters', 'N'); INSERT INTO modules (Name, Active) VALUES ('candidate_profile', 'N'); INSERT INTO modules (Name, Active) VALUES ('configuration', 'Y'); diff --git a/SQL/New_patches/2026-10-27-add_candidate_identifiers_module.sql b/SQL/New_patches/2026-10-27-add_candidate_identifiers_module.sql new file mode 100644 index 0000000000..754e2f284f --- /dev/null +++ b/SQL/New_patches/2026-10-27-add_candidate_identifiers_module.sql @@ -0,0 +1,2 @@ +INSERT INTO modules (Name, Active) +VALUES ('candidate_identifiers', 'N'); \ No newline at end of file diff --git a/modules/candidate_identifiers/README.md b/modules/candidate_identifiers/README.md new file mode 100644 index 0000000000..4d89433e5a --- /dev/null +++ b/modules/candidate_identifiers/README.md @@ -0,0 +1,47 @@ +# Candidate Identifiers + +## Purpose + +The `candidate_identifiers` module allows users to view and manage +identifiers associated with candidates in LORIS. + +## Intended Users + +The module is intended for data entry staff and other authorized users +who need to manage candidate identifiers. + +## Scope + +The module provides a filterable table of candidate identifiers, +including identifier type, value, and dates added or edited. + +Users can add, edit, and delete candidate identifiers. + +## Permissions + +Access to the module requires either the `access_all_profiles` permission +or the `data_entry` permission with an assigned study site. + +Users with `access_all_profiles` can access candidates across sites. +Users with `data_entry` are subject to LORIS's existing site-permission +filtering. + +## Configurations + +Candidate identifier types are managed through the Configuration module. + +Each identifier type has settings indicating whether it is required +or automatically generated. The `candidate_identifiers` module retrieves +these settings for use in its identifier forms. + +## Interactions with LORIS + +The module displays candidate identifiers in a filterable data table. +Users can filter identifiers by type, value, date added, and date edited. + +Users can add new identifiers, edit existing identifiers, and delete +identifiers through the module's interface. + +Identifier types and their settings are retrieved from the Configuration +module. Candidate visibility is controlled by LORIS's existing site +permissions and project filtering. \ No newline at end of file diff --git a/modules/candidate_identifiers/help/candidate_identifiers.md b/modules/candidate_identifiers/help/candidate_identifiers.md new file mode 100644 index 0000000000..1d905ab9d1 --- /dev/null +++ b/modules/candidate_identifiers/help/candidate_identifiers.md @@ -0,0 +1,9 @@ +# Candidate Identifiers + +This module is used to view and manage identifiers associated with candidates in LORIS. + +Use the table filters to search for identifiers by identifier type, identifier value, date added, or date edited. + +Click **Add Identifier** to add a new identifier to a candidate. Select an existing identifier to edit it, or use the **Delete** action to remove it. + +Available identifier types are configured through the Configuration module. \ No newline at end of file diff --git a/modules/candidate_identifiers/jsx/addIdentifierForm.tsx b/modules/candidate_identifiers/jsx/addIdentifierForm.tsx new file mode 100644 index 0000000000..78077d7884 --- /dev/null +++ b/modules/candidate_identifiers/jsx/addIdentifierForm.tsx @@ -0,0 +1,202 @@ +import React, {useState} from 'react'; + +import { + withTranslation, + WithTranslation, +} from 'react-i18next'; + +import {Errors} from 'jslib'; + +import { + FormElement, + TextboxElement, + SelectElement, + ButtonElement, +} from 'jsx/Form'; + +import {client} from 'jslib/http'; + +type IdentifierType = { + value: string | number; + label: string; + autoGenerate?: boolean; +}; + +type AddIdentifierFormProps = { + identifierTypes: IdentifierType[]; + onSuccess: () => void; + t: WithTranslation['t']; +}; + +/** + * Form for adding a candidate identifier. + * + * @param props Component properties + * @return React component + */ +function AddIdentifierForm(props: AddIdentifierFormProps) { + const {t} = props; + + const [values, setValues] = useState({ + CandID: '', + CandidateIdentifierTypeID: '', + Value: '', + }); + + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + + const selectedType = props.identifierTypes.find( + (type) => Number(type.value) === Number(values.CandidateIdentifierTypeID) + ); + + const autoGenerate = selectedType?.autoGenerate ?? false; + + /** + * 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 add a candidate identifier. + * + * @param event Submit event + */ + const submit = async (event: React.SyntheticEvent) => { + event.preventDefault(); + + if (saving) { + return; + } + + setError(null); + + const candid = values.CandID.trim(); + const identifierTypeID = Number(values.CandidateIdentifierTypeID); + + if (!candid || !identifierTypeID) { + setError( + t('CandID and Identifier Type are required.', + {ns: 'candidate_identifiers'}) + ); + return; + } + + const identifier: { + CandidateIdentifierTypeID: number; + Value?: string; + } = { + CandidateIdentifierTypeID: identifierTypeID, + }; + + if (!autoGenerate && values.Value.trim()) { + identifier.Value = values.Value.trim(); + } + + setSaving(true); + + try { + await client.post( + `api/v0.0.4-dev/candidates/${encodeURIComponent(candid)}/identifiers`, + {Identifier: identifier} + ); + + 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('Candidate not found.', { + ns: 'candidate_identifiers', + })); + break; + default: + setError(t('Unable to add identifier.', { + ns: 'candidate_identifiers', + })); + } + } finally { + setSaving(false); + } + }; + + return ( + +
+ + + [type.value, type.label]) + )} + emptyOption={true} + autoSelect={false} + /> + + {selectedType && !autoGenerate && ( + + )} + + {error && ( +
+ {error} +
+ )} + + +
+
+ ); +} + +export default withTranslation()(AddIdentifierForm); diff --git a/modules/candidate_identifiers/jsx/candidateIdentifiersIndex.tsx b/modules/candidate_identifiers/jsx/candidateIdentifiersIndex.tsx new file mode 100644 index 0000000000..eb388bc013 --- /dev/null +++ b/modules/candidate_identifiers/jsx/candidateIdentifiersIndex.tsx @@ -0,0 +1,369 @@ +import {createRoot} from 'react-dom/client'; +import React, {useEffect, useState} from 'react'; +import Modal from 'Modal'; +import swal from 'sweetalert2'; + +import i18n from 'I18nSetup'; + +import { + withTranslation, + WithTranslation, +} from 'react-i18next'; + +import {client} from 'jslib/http'; + +import Loader from 'Loader'; +import FilterableDataTable from 'FilterableDataTable'; + +import fetchDataStream from 'jslib/fetchDataStream'; + +import AddIdentifierForm from './addIdentifierForm'; +import EditIdentifierForm from './editIdentifierForm'; + +import frStrings from '../locale/fr/LC_MESSAGES/candidate_identifiers.json'; + +declare const loris: { + BaseURL: string; +}; + +type CandidateIdentifier = { + CandID: string; + PSCID: string; + IdentifierType: string; + IdentifierValue: string; + DateAdded: string; + DateEdited: string; + CandidateIdentifierID: number | string; + CandidateIdentifierTypeID: number | string; + [key: string]: string | number; +}; + +type IdentifierType = { + value: string | number; + label: string; + isRequired: boolean; + autoGenerate: boolean; +}; + +type IdentifierTypesResponse = { + fieldOptions: { + identifierTypes: IdentifierType[]; + }; +}; + +type CandidateIdentifiersIndexProps = { + dataURL: string; + baseURL: string; + t: WithTranslation['t']; +}; + +/** + * Candidate Identifiers + * + * Displays candidate identifiers in a filterable table. + * + * @param props Component properties + */ +function CandidateIdentifiersIndex( + props: CandidateIdentifiersIndexProps +): React.ReactElement { + const [data, setData] = useState([]); + const [isLoaded, setIsLoaded] = useState(false); + const [showAddForm, setShowAddForm] = useState(false); + const [identifierTypes, setIdentifierTypes] = useState([]); + const [editingIdentifier, setEditingIdentifier] = + useState(null); + + /** + * Load candidate identifiers. + */ + useEffect(() => { + fetchData(); + + client.get('candidate_identifiers/?format=json') + .then((result) => { + setIdentifierTypes(result.fieldOptions.identifierTypes || []); + }) + .catch((error) => { + console.error(error); + }); + }, []); + + /** + * Retrieve identifier rows from the data framework. + */ + const fetchData = () => { + const rows: string[][] = []; + + setIsLoaded(false); + + fetchDataStream( + props.dataURL, + (row: string[]) => { + rows.push(row); + }, + () => setData([...rows]), + () => { + setData([...rows]); + setIsLoaded(true); + }, + 'GET' + ); + }; + + /** + * Format candidate links and date values. + * + * @param column Column name + * @param cell Cell value + * @param row Candidate identifier row + * @return Formatted table cell + */ + const formatColumn = ( + column: string, + cell: React.ReactNode, + row: CandidateIdentifier, + ): React.ReactElement => { + if (column === 'PSCID') { + const url = props.baseURL + '/' + row.CandID + '/'; + + return
{cell}; + } + + if (column === props.t('Identifier Value', + {ns: 'candidate_identifiers'})) { + return ( + + { + event.preventDefault(); + setEditingIdentifier({ + ...row, + IdentifierType: String( + row[props.t('Identifier Type', { + ns: 'candidate_identifiers', + })] ?? '' + ), + IdentifierValue: String( + row[props.t('Identifier Value', { + ns: 'candidate_identifiers', + })] ?? '' + ), + }); + }} + > + {cell} + + + ); + } + + if (column === props.t('Delete', {ns: 'candidate_identifiers'})) { + const identifierType = identifierTypes.find( + (type) => Number(type.value) === Number(row.CandidateIdentifierTypeID) + ); + + return ( + + {identifierType && !identifierType.isRequired && ( + confirmDelete(row)} + > + {props.t('Delete', {ns: 'candidate_identifiers'})} + + )} + + ); + } + + return {cell}; + }; + + /** + * Confirm and delete a candidate identifier. + * + * @param row Identifier row + */ + const confirmDelete = (row: CandidateIdentifier) => { + const {t} = props; + swal.fire({ + title: t('Are you sure?', {ns: 'loris'}), + text: t('Delete identifier "{{value}}"?', { + ns: 'candidate_identifiers', + value: row[props.t('Identifier Value', {ns: 'candidate_identifiers'})], + }), + type: 'warning', + showCancelButton: true, + confirmButtonText: t('Yes, delete it!', {ns: 'candidate_identifiers'}), + cancelButtonText: t('Cancel', {ns: 'loris'}), + }).then((result) => { + if (!result.value) { + return; + } + + client.request<{success: boolean}>( + `api/v0.0.4-dev/candidates/` + + `${encodeURIComponent(row.CandID)}/identifiers`, + { + method: 'DELETE', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ + Identifier: { + CandidateIdentifierID: Number(row.CandidateIdentifierID), + }, + }), + } + ).then((data) => { + if (!data.success) { + throw new Error('Unable to delete identifier'); + } + + fetchData(); + swal.fire( + t('Deleted!', {ns: 'candidate_identifiers'}), + t('Identifier deleted successfully.', {ns: 'candidate_identifiers'}), + 'success' + ); + }) + .catch((error) => { + console.error(error); + swal.fire( + t('Error', {ns: 'loris'}), + t('Unable to delete identifier.', {ns: 'candidate_identifiers'}), + 'error' + ); + }); + }); + }; + + /** + * Render the candidate identifiers table. + * + * @return {object} React component + */ + const {t} = props; + + if (!isLoaded) { + return ; + } + + const fields: React.ComponentProps['fields'] = [ + { + label: 'CandID', + show: true, + filter: {name: 'CandID', type: 'text'}, + }, + { + label: 'PSCID', + show: true, + filter: {name: 'PSCID', type: 'text'}, + }, + { + label: t('Identifier Type', {ns: 'candidate_identifiers'}), + show: true, + filter: {name: 'IdentifierType', type: 'text'}, + }, + { + label: t('Identifier Value', {ns: 'candidate_identifiers'}), + show: true, + filter: {name: 'IdentifierValue', type: 'text'}, + }, + { + label: t('Date Added', {ns: 'candidate_identifiers'}), + show: true, + filter: {name: 'DateAdded', type: 'date'}, + }, + { + label: t('Date Edited', {ns: 'candidate_identifiers'}), + show: true, + filter: {name: 'DateEdited', type: 'date'}, + }, + { + label: 'CandidateIdentifierID', + show: false, + }, + { + label: 'CandidateIdentifierTypeID', + show: false, + }, + { + label: t('Delete', {ns: 'candidate_identifiers'}), + show: true, + }, + ]; + + const actions = [ + { + label: t('Add Identifier', {ns: 'candidate_identifiers'}), + /** + * + */ + action: () => setShowAddForm(true), + name: 'addIdentifier', + }, + ]; + + return ( +
+ setShowAddForm(false)} + > + { + setShowAddForm(false); + fetchData(); + }} + /> + + setEditingIdentifier(null)} + > + {editingIdentifier && ( + { + setEditingIdentifier(null); + fetchData(); + }} + /> + )} + + + ['actions']} + getFormattedCell={formatColumn as unknown as React.ComponentProps< + typeof FilterableDataTable + >['getFormattedCell']} + /> +
+ ); +} + +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 ( + +
+ undefined} + /> + + undefined} + /> + + + + {error && ( +
+ {error} +
+ )} + + +
+
+ ); +} + +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..cab8ebd658 --- /dev/null +++ b/modules/candidate_identifiers/locale/candidate_identifiers.pot @@ -0,0 +1,82 @@ +# 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 "" 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..82bae35d7b --- /dev/null +++ b/modules/candidate_identifiers/locale/fr/LC_MESSAGES/candidate_identifiers.po @@ -0,0 +1,83 @@ +# 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." 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/module.class.inc b/modules/candidate_identifiers/php/module.class.inc new file mode 100644 index 0000000000..76e5d7bf45 --- /dev/null +++ b/modules/candidate_identifiers/php/module.class.inc @@ -0,0 +1,62 @@ + + * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 + * @link https://www.github.com/aces/Loris/ + */ +namespace LORIS\candidate_identifiers; + +/** + * 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"); + } +} diff --git a/modules/candidate_identifiers/test/TestPlan.md b/modules/candidate_identifiers/test/TestPlan.md new file mode 100644 index 0000000000..69ad405b52 --- /dev/null +++ b/modules/candidate_identifiers/test/TestPlan.md @@ -0,0 +1,21 @@ +# 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. \ No newline at end of file diff --git a/webpack.config.ts b/webpack.config.ts index 5847e46f7c..97a3ace004 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -31,6 +31,7 @@ const lorisModules: Record = { biobank: ['biobankIndex'], create_timepoint: ['createTimepointIndex'], candidate_list: ['openProfileForm', 'candidateListIndex'], + candidate_identifiers: ['candidateIdentifiersIndex'], datadict: ['dataDictIndex'], dataquery: ['index'], data_release: ['dataReleaseIndex'],