-- Slice 8M-PricingVue · perms
-- Read (pricingSnapshotAj): same audience as other pricing reads (CRM + PM + PC + FM + Exec + Procurement + Admin).
-- Write (pricingSeedFromItemsAj): whoever can add lines gets to seed.

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

INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'Tenders', 'pricingSeedFromItemsAj', 0, NOW()
FROM user_groups g, (SELECT DISTINCT user_group_id FROM user_groups_perms
                     WHERE controller_allowed='Tenders' AND action_allowed='pricingAddLineAj') w
WHERE g.c0d = w.user_group_id
  AND NOT EXISTS (
    SELECT 1 FROM user_groups_perms p
    WHERE p.user_group_id = g.c0d
      AND p.controller_allowed = 'Tenders'
      AND p.action_allowed     = 'pricingSeedFromItemsAj'
  );
