Source: tree/matchObjects/checkPersonListMember.js

import {query, HEX2uuid, UUID2hex} from '@commtool/sql-query'
import { matchObjectsLists } from './matchObjectsLists.js'
import { checkEntries } from './checkEntries.js'
import { errorLoggerUpdate } from '../../utils/requestLogger.js'
import { getOrganizationForObject } from '../../utils/organizationUtils.js'

/**
 * Asynchronously checks if a person is a member of specific lists/dynamic lists dlist) and performs related operations.
 * This is clled, when an objet has been updated or created, to check if any dynamic list has to be updated
 * 
 * This function retrieves all groups (sources) that the object identified by the given UID is a member of,
 * matches the object against those lists, by checking all object filters attached to the sources/groups, if they pass the filters
 * and performs necessary updates to the entries of the dynamic lists attached to these filters
 * In a second step it checks, if therre are entries which do not match the filters anymore and removes them from the dlist
 * 
 * @async
 * @function checkPersonListMember
 * @param {string|Buffer} UID - The unique identifier of the object to check membership for.
 * @param {string} UIDOrga - The unique identifier of the organization.
 * @returns {Promise<void>} Resolves when the operations are completed.
 * @throws Will log an error if any operation fails during execution.
 */
export const checkPersonListMember=async (UID, UIDOrga = null)=>
{
   try {
        // Get organization for the person if not provided
      
        UID=UUID2hex(UID)
        
        // we have now to get all groups (the sources we have to check) the object is member of
        const sources=await query(`
            SELECT Links.UIDTarget AS UID
            FROM ObjectBase
            INNER JOIN Links ON (Links.UID=ObjectBase.UID AND Links.Type IN ('member','memberA','memberG'))
            WHERE ObjectBase.UID=?
            GROUP BY Links.UIDTarget
        `,[UID])
        await matchObjectsLists(UID,sources.map(s=>s.UID), UIDOrga)
        await checkEntries(UID, UIDOrga)
    }
    catch(e)
    {
        errorLoggerUpdate(e)
    }

}