SET PATH *LIBL ; 

CREATE OR REPLACE FUNCTION SAILPOINT.ES_V2_DISABLE_USER ( 
	AUTHORIZATIONNAME VARCHAR(10) ) 
	RETURNS CLOB(2147483647)   
	LANGUAGE SQL 
	SPECIFIC SAILPOINT.V2_ESDSBLUSR 
	NOT DETERMINISTIC 
	MODIFIES SQL DATA 
	CALLED ON NULL INPUT 
	NOT FENCED 
	SET OPTION  ALWBLK = *ALLREAD , 
	ALWCPYDTA = *OPTIMIZE , 
	COMMIT = *NONE , 
	DBGVIEW = *SOURCE , 
	DECRESULT = (31, 31, 00) , 
	DLYPRP = *NO , 
	DYNDFTCOL = *NO , 
	DYNUSRPRF = *OWNER , 
	SRTSEQ = *HEX   
	BEGIN 
DECLARE CMD_OUTPUT CLOB ( 64 K ) DEFAULT '' ; 
DECLARE CMD_STMT VARCHAR ( 512 ) DEFAULT '' ; 
DECLARE ERROR_RESPONSE CLOB ( 2 G ) DEFAULT '' ; 
DECLARE SQLCODE_VAR INT DEFAULT 0 ; 
DECLARE SQLSTATE_VAR CHAR ( 5 ) DEFAULT '00000' ; 
-- Uniform error handler - returns pre-built error JSON 
DECLARE CONTINUE HANDLER FOR SQLSTATE '38001' RETURN ERROR_RESPONSE ; 
-- Handle QCMD exception (38501 = external routine error) 
DECLARE EXIT HANDLER FOR SQLSTATE '38501' 
RETURN JSON_OBJECT ( 
'data' : JSON_ARRAY ( ) , 
'errors' : JSON_ARRAY ( JSON_OBJECT ( 
'status' : 404 , 
'message' : 'User profile not found or command failed' 
) ) 
) ; 
-- Build the command 
SET CMD_STMT = 'CHGUSRPRF USRPRF(' || TRIM ( AUTHORIZATIONNAME ) || 
') STATUS(*DISABLED)' ; 
-- Execute via QCMD and capture output 
SET CMD_OUTPUT = CISTOOLS . QCMD ( CMD_STMT ) ; 
-- Check if any CPF/CPD errors exist (CPF=failure, CPD=diagnostic, CPC=completio--n/success) 
IF CMD_OUTPUT LIKE '%CPF%' 
OR CMD_OUTPUT LIKE '%CPD%' THEN 
-- Build errors array from all error lines in output 
SET ERROR_RESPONSE = ( 
SELECT JSON_OBJECT ( 
'data' : JSON_ARRAY ( ) , 'errors' : JSON_ARRAYAGG ( 
JSON_OBJECT ( 
'status' : 
CASE 
WHEN FRAGMENT LIKE '%CPF2204%' THEN 404 
WHEN FRAGMENT LIKE '%CPF2213%' THEN 403 
WHEN FRAGMENT LIKE '%CPF2217%' THEN 423 
ELSE 500 
END , 'message' : 
CASE 
WHEN 
FRAGMENT LIKE '%CPF2204%' 
THEN 'User profile not found' 
WHEN FRAGMENT LIKE '%CPF2213%' THEN 
'Not authorized to change user profile' 
WHEN 
FRAGMENT LIKE '%CPF2217%' 
THEN 'Not able to allocate user profile' 
ELSE TRIM ( FRAGMENT ) 
END 
) 
) 
) 
FROM TABLE ( 
CISTOOLS . SPLIT_STRING ( CMD_OUTPUT , X'25' ) 
) AS T 
WHERE FRAGMENT LIKE '%CPF%' 
OR FRAGMENT LIKE '%CPD%' ) ; 
SIGNAL SQLSTATE '38001' ; 
END IF ; 
-- Success - return user info 
RETURN 
( 
SELECT JSON_OBJECT ( 
'data' : JSON_ARRAY ( JSON_OBJECT ( 
'authorizationName' VALUE AUTHORIZATION_NAME , 
'status' VALUE STATUS , 
'lastUsedTimestamp' VALUE LAST_USED_TIMESTAMP 
) ) , 'errors' : JSON_ARRAY ( ) 
) 
FROM QSYS2 . USER_INFO A 
WHERE AUTHORIZATION_NAME = UPPER ( AUTHORIZATIONNAME ) ) ; 
END  ; 

GRANT ALTER , EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.V2_ESDSBLUSR 
TO AMAPICS WITH GRANT OPTION ; 

GRANT EXECUTE   
ON SPECIFIC FUNCTION SAILPOINT.V2_ESDSBLUSR 
TO PUBLIC ; 

