Added Connectwise Compnay Syncing

This commit is contained in:
2026-01-26 17:09:18 -06:00
parent 4524c0258a
commit 7748e6171b
19 changed files with 1783 additions and 9 deletions
+27
View File
@@ -0,0 +1,27 @@
import { Collection } from "@discordjs/collection";
import { connectWiseApi } from "../../constants";
import { Company } from "../../types/ConnectWiseTypes";
export const fetchAllCwCompanies = async (): Promise<
Collection<string, Company>
> => {
let allCompanies = new Collection<string, Company>();
const pageCount = 1000;
const count = (await connectWiseApi.get("/company/companies/count")).data
.count;
const totalPages = Math.ceil(count / pageCount);
for (let page = 0; page < totalPages; page++) {
const response = await connectWiseApi.get(
`/company/companies?page=${page + 1}&pageSize=${pageCount}`,
);
const companies = response.data;
for (const company of companies) {
allCompanies.set(company.id, company);
}
}
return allCompanies;
};
+40
View File
@@ -0,0 +1,40 @@
import { connectWiseApi, prisma } from "../../constants";
import { events } from "../globalEvents";
import { fetchAllCwCompanies } from "./fetchAllCompanies";
export const refreshCompanies = async () => {
events.emit("cw:companies:refreshed:check");
// Dynamically import to avoid circular dependency
const internalCompanyCount = await prisma.company.count();
const externalCompanyCount =
(await connectWiseApi.get("/company/companies/count")).data.count - 1;
if (internalCompanyCount !== externalCompanyCount) {
console.log(
`Company count mismatch detected. Internal: ${internalCompanyCount}, External: ${externalCompanyCount}. Refreshing...`,
);
const allCompanies = await fetchAllCwCompanies();
await Promise.all(
allCompanies.map(async (company) => {
return await prisma.company.upsert({
where: { cw_CompanyId: company.id },
create: {
cw_CompanyId: company.id,
cw_Identifier: company.identifier,
name: company.name,
},
update: {
name: company.name,
},
});
}),
);
events.emit("cw:companies:refreshed", {
internalCompaniesCount: internalCompanyCount,
externalCompaniesCount: externalCompanyCount,
});
}
};
+6 -1
View File
@@ -53,6 +53,11 @@ interface EventTypes {
err: Error;
role: RoleController;
}) => void;
"cw:companies:refreshed:check": () => void;
"cw:companies:refreshed": (data: {
internalCompaniesCount: number;
externalCompaniesCount: number;
}) => void;
}
export const events = new Eventra<EventTypes>();
@@ -61,4 +66,4 @@ export function setupEventDebugger() {
events.any((eventName, ...args) => {
console.log(`[ Event Debugger ] (${eventName})`);
});
}
}