import { PostgreSQL } from "../types" ; import { is_valid_uuid_string , search_match , search_split , } from "@cocalc/util/misc" ; import { query } from "../query" ; export async function matching_site_licenses ( db , search , limit = 5 ) { if ( is_valid_uuid_string ( search ) ) { return ( await db . async_query ( { cache : true , query : "SELECT id FROM site_licenses WHERE id=$1" , params : [ search ] , } ) ) . rows ; } const licenses = ( await db . async_query ( { query : "SELECT id, id || ' ' || coalesce(lower(title),'') || ' ' || coalesce(lower(description),'') || ' ' || coalesce(lower(info::TEXT),'') AS info, managers FROM site_licenses ORDER BY last_used DESC NULLS LAST" , } ) ) . rows ; const managers = new Set ( ) ; for ( const x of licenses ) { if ( x . managers != null ) { for ( const account_id of x . managers ) { managers . add ( account_id ) ; } } } const accounts = { } ; for ( const row of ( await db . async_query ( { cache : true , query : "SELECT account_id, coalesce(lower(first_name),'') || ' ' || coalesce(lower(last_name),'') || ' ' || coalesce(lower(email_address),'') AS info FROM accounts WHERE account_id=ANY($1)" , params : [ Array . from ( managers ) ] , } ) ) . rows ) { accounts [ row . account_id ] = row . info ; } const v = search_split ( search . toLowerCase ( ) ) ; const matches = [ ] ; for ( const license of licenses ) { let s = license . info ; if ( license . managers ) { for ( const account_id of license . managers ) { s += " " + accounts [ account_id ] ; } } if ( search_match ( s , v ) ) { matches . push ( { id : license . id as string } ) ; } if ( matches . length >= limit ) break ; } return matches ; } export async function manager_site_licenses ( db , account_id ) { const query = "SELECT * FROM site_licenses WHERE $1=ANY(managers)" ; const params = [ account_id ] ; return ( await db . async_query ( { query , params } ) ) . rows ; } export async function is_a_site_license_manager ( db , account_id ) { return ( ( await query ( { db , query : "SELECT COUNT(*) FROM site_licenses WHERE $1=ANY(managers)" , one : true , params : [ account_id ] , } ) ) . count > 0 ) ; }