Added Connectwise Compnay Syncing
This commit is contained in:
@@ -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;
|
||||
};
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user