-- Slice 8c-Close · closeAj perms
--
-- The model's canClose() guards additionally restrict close to PC/PM/Admin roles by
-- $userGroup, so read-only roles picking up the JSON endpoint will get 'Only PC / PM /
-- Admin can close a CR' back. But we still gate at the perm layer for defence-in-depth.

INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'WorksCrs', 'closeAj', 0, NOW()
FROM user_groups g
WHERE g.user_group_name IN ('Projects Coordinator','Project Manager','Administrator')
  AND NOT EXISTS (
    SELECT 1 FROM user_groups_perms p
    WHERE p.user_group_id = g.c0d
      AND p.controller_allowed = 'WorksCrs'
      AND p.action_allowed     = 'closeAj'
  );

INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'WorksPhases', 'closeAj', 0, NOW()
FROM user_groups g
WHERE g.user_group_name IN ('Projects Coordinator','Project Manager','Administrator')
  AND NOT EXISTS (
    SELECT 1 FROM user_groups_perms p
    WHERE p.user_group_id = g.c0d
      AND p.controller_allowed = 'WorksPhases'
      AND p.action_allowed     = 'closeAj'
  );
