Refactor removeUserNotRelatedToJob logic to improve SQL clarity and handle edge cases

We remove the user from the group if the user is deactivated, or of the user does not have any job_history line currently, or if the userjob_id is null in the job_history.
This commit is contained in:
Julien Fastré 2025-06-18 11:34:32 +02:00
parent 51168ac3c4
commit 81b6ae193c
Signed by: julienfastre
GPG Key ID: BDE2190974723FCB

View File

@ -77,24 +77,38 @@ final readonly class UserGroupRelatedToUserJobSync implements UserGroupRelatedTo
return $counter;
}
private function removeUserNotRelatedToJob(Connection $connection): int
{
$sql = <<<'SQL'
DELETE FROM chill_main_user_group_user
USING users AS u, chill_main_user_group ug, chill_main_user_job_history jh
WHERE
chill_main_user_group_user.usergroup_id = ug.id
AND chill_main_user_group_user.user_id = u.id
AND jh.user_id = u.id AND tsrange(jh.startdate, jh.enddate) @> localtimestamp
-- only when the user's jobid is different than the user_group id
-- or where the user.enabled is null
AND ((ug.userjob_id IS NOT NULL AND jh.job_id <> ug.userjob_id) OR u.enabled IS NULL)
SQL;
private function removeUserNotRelatedToJob(Connection $connection): int
{
$sql = <<<'SQL'
DELETE FROM chill_main_user_group_user
USING users AS u, chill_main_user_group ug
WHERE
chill_main_user_group_user.usergroup_id = ug.id
AND chill_main_user_group_user.user_id = u.id
-- only where user_group.userjob_id is set (we ignore groups not automatically created)
AND ug.userjob_id IS NOT NULL
AND (
-- Case 1: User has no job history records matching the time period
NOT EXISTS (
SELECT 1 FROM chill_main_user_job_history jh
WHERE jh.user_id = u.id
AND tsrange(jh.startdate, jh.enddate) @> localtimestamp
)
OR
-- Case 2: User has job history but with different job_id or user is disabled
EXISTS (
SELECT 1 FROM chill_main_user_job_history jh
WHERE jh.user_id = u.id
AND tsrange(jh.startdate, jh.enddate) @> localtimestamp
AND (jh.job_id <> ug.userjob_id OR u.enabled IS FALSE OR jh.job_id IS NULL)
)
)
SQL;
$result = $connection->executeQuery($sql);
$result = $connection->executeQuery($sql);
return $result->rowCount();
}
return $result->rowCount();
}
private function createNewAssociations(Connection $connection): int
{
@ -102,8 +116,8 @@ final readonly class UserGroupRelatedToUserJobSync implements UserGroupRelatedTo
INSERT INTO chill_main_user_group_user (usergroup_id, user_id)
SELECT cmug.id, jh.user_id
FROM chill_main_user_group cmug
JOIN chill_main_user_job_history jh ON jh.job_id = cmug.userjob_id AND tsrange(jh.startdate, jh.enddate) @> localtimestamp
JOIN users u ON u.id = jh.user_id
JOIN chill_main_user_job_history jh ON jh.job_id = cmug.userjob_id AND tsrange(jh.startdate, jh.enddate) @> localtimestamp
JOIN users u ON u.id = jh.user_id
WHERE cmug.userjob_id IS NOT NULL AND u.enabled IS TRUE
ON CONFLICT DO NOTHING
SQL;