-- Slice 8b-T · Work Templates + Instances perms
-- WorkTemplates authoring: Administrator + Executive only
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'WorkTemplates', a.act, 0, NOW()
FROM (
    SELECT 'index' AS act UNION ALL SELECT 'edit'
    UNION ALL SELECT 'createAj' UNION ALL SELECT 'newVersionAj' UNION ALL SELECT 'deactivateAj'
    UNION ALL SELECT 'updateHeaderAj' UNION ALL SELECT 'addItemAj' UNION ALL SELECT 'updateItemAj' UNION ALL SELECT 'deleteItemAj'
) a
CROSS JOIN user_groups g
WHERE g.user_group_name IN ('Administrator','Executive')
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'WorkTemplates' AND p.action_allowed = a.act);

-- WorkTemplates read-only: Finance Manager, Project Manager
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'WorkTemplates', a.act, 0, NOW()
FROM (SELECT 'index' AS act UNION ALL SELECT 'edit') a
CROSS JOIN user_groups g
WHERE g.user_group_name IN ('Finance Manager','Project Manager')
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'WorkTemplates' AND p.action_allowed = a.act);

-- WorkInstances: every operational role (they're either assignees or reviewers)
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'WorkInstances', a.act, 0, NOW()
FROM (
    SELECT 'myQueue' AS act UNION ALL SELECT 'view'
    UNION ALL SELECT 'createAj' UNION ALL SELECT 'claimAj' UNION ALL SELECT 'reassignAj'
    UNION ALL SELECT 'saveResultAj' UNION ALL SELECT 'submitAj'
    UNION ALL SELECT 'approveAj' UNION ALL SELECT 'rejectAj'
    UNION ALL SELECT 'reopenAj' UNION ALL SELECT 'cancelAj'
) a
CROSS JOIN user_groups g
WHERE g.user_group_name IN (
    'Executive','Finance Manager','Accountant','Project Manager','Projects Coordinator',
    'Field Supervisor','Procurement','Administrator','Stores'
)
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'WorkInstances' AND p.action_allowed = a.act);
