-- Slice 8Y · Polish the contract handoff.
-- 1) FM_VERIFY step now also requires the EXECUTIVE assignment (so FM explicitly picks
--    which Exec to hand over to). Engine already fans out to the whole Executive group,
--    but users want to see + choose. Slot is optional at the engine level (FM can pick
--    any Executive user); the pick is stored in step_payload_json for audit.
-- 2) Grant returnToOriginatorAj perm to Finance Manager, Executive, Administrator so
--    FM/Exec can bounce a contract back to CRM without breaking the chain semantics.
-- 3) submitContractAj perm mirror (CRM originators need this even without contract
--    editing perms — belt + suspenders after slice 8X grants).

-- ── 1. Extend FM_VERIFY required_assignments ─────────────────────────────
UPDATE fin_chain_steps
   SET required_assignments = 'ACCOUNTANT,PROCUREMENT,EXECUTIVE',
       edited_on = NOW()
 WHERE chain_id = (SELECT c0d FROM fin_chain_defs WHERE chain_key='TENDER_CONTRACT_APPROVAL')
   AND step_key = 'FM_VERIFY'
   AND deleted = 0;

-- ── 2. returnToOriginatorAj perm — FM + Exec + Admin ─────────────────────
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'FinChains', 'returnToOriginatorAj', 0, NOW()
FROM user_groups g
WHERE g.user_group_name IN ('Finance Manager','Executive','Administrator')
  AND NOT EXISTS (
    SELECT 1 FROM user_groups_perms p
    WHERE p.user_group_id = g.c0d
      AND p.controller_allowed = 'FinChains'
      AND p.action_allowed = 'returnToOriginatorAj'
);
