74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
import { Collection } from "@discordjs/collection";
|
|
import { connectWiseApi } from "../../../constants";
|
|
|
|
export interface CWMember {
|
|
id: number;
|
|
identifier: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
officeEmail: string;
|
|
inactiveFlag: boolean;
|
|
_info: Record<string, string>;
|
|
}
|
|
|
|
/**
|
|
* Fetch All CW Members
|
|
*
|
|
* Fetches every member from ConnectWise using pagination and returns them
|
|
* in a Collection keyed by their identifier (e.g. "jroberts").
|
|
*
|
|
* @param opts.conditions - Optional CW conditions string to filter members
|
|
* @returns {Promise<Collection<string, CWMember>>} Collection of CW members keyed by identifier
|
|
*/
|
|
export const fetchAllCwMembers = async (opts?: {
|
|
conditions?: string;
|
|
}): Promise<Collection<string, CWMember>> => {
|
|
const members = new Collection<string, CWMember>();
|
|
const pageSize = 1000;
|
|
const conditionsParam = opts?.conditions
|
|
? `&conditions=${encodeURIComponent(opts.conditions)}`
|
|
: "";
|
|
|
|
const { data: countData } = await connectWiseApi.get(
|
|
`/system/members/count${conditionsParam ? `?${conditionsParam.slice(1)}` : ""}`,
|
|
);
|
|
const totalPages = Math.ceil(countData.count / pageSize);
|
|
|
|
for (let page = 0; page < totalPages; page++) {
|
|
const { data } = await connectWiseApi.get<CWMember[]>(
|
|
`/system/members?page=${page + 1}&pageSize=${pageSize}${conditionsParam}`,
|
|
);
|
|
|
|
for (const member of data) {
|
|
members.set(member.identifier, member);
|
|
}
|
|
}
|
|
|
|
return members;
|
|
};
|
|
|
|
/**
|
|
* Find CW Member Identifier by Email
|
|
*
|
|
* Looks up a ConnectWise member whose `officeEmail` matches the provided
|
|
* email address (case-insensitive) and returns their `identifier` string
|
|
* (e.g. "jroberts"). Returns `null` if no match is found.
|
|
*
|
|
* @param email - The email address to search for
|
|
* @param members - Optional pre-fetched member collection to search against (avoids extra API call)
|
|
* @returns {Promise<string | null>} The CW identifier or null
|
|
*/
|
|
export const findCwIdentifierByEmail = async (
|
|
email: string,
|
|
members?: Collection<string, CWMember>,
|
|
): Promise<string | null> => {
|
|
const allMembers = members ?? (await fetchAllCwMembers());
|
|
const normalised = email.toLowerCase();
|
|
|
|
const match = allMembers.find(
|
|
(m) => m.officeEmail?.toLowerCase() === normalised,
|
|
);
|
|
|
|
return match?.identifier ?? null;
|
|
};
|