SELECT ORG_CODE organizationcode, ORG_DESC organizationdescription
FROM r5userorganization u, r5organization o 
LEFT OUTER JOIN r5stores s
ON (s.str_org = o.org_code AND s.str_code = <parameter.store>)
WHERE o.org_code=u.uog_org  
AND u.uog_user = <parameter.r5user> 
AND (u.uog_common = '+' OR u.uog_org = CASE WHEN <parameter.store> IS NOT NULL THEN s.str_org WHEN <parameter.locationorg> IS NOT NULL THEN <parameter.locationorg> ELSE u.uog_org END)
AND EXISTS 
(
SELECT 1 FROM r5functions f
LEFT OUTER JOIN r5permissions p
ON (p.prm_function = f.fun_code)
INNER JOIN r5users ur
ON (p.prm_group = ur.usr_group AND ur.usr_code = <parameter.r5user>)
WHERE COALESCE(f.fun_application, f.fun_code) = <parameter.function> 
AND CASE WHEN p.prm_function IS NULL THEN f.fun_insert ELSE p.prm_insert END = '+' 
AND <parameter.mos> = '+' AND (p.prm_function IS NOT NULL OR f.fun_public = '!'))
