fix: align company data with machines
This commit is contained in:
parent
40e92cf2b9
commit
5de8b2bf7f
3 changed files with 124 additions and 22 deletions
|
|
@ -641,3 +641,68 @@ export const importPrismaSnapshot = mutation({
|
|||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const syncMachineCompanyReferences = mutation({
|
||||
args: {
|
||||
tenantId: v.optional(v.string()),
|
||||
dryRun: v.optional(v.boolean()),
|
||||
},
|
||||
handler: async (ctx, { tenantId, dryRun }) => {
|
||||
const effectiveDryRun = Boolean(dryRun)
|
||||
|
||||
const machines = tenantId && tenantId.trim().length > 0
|
||||
? await ctx.db
|
||||
.query("machines")
|
||||
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
|
||||
.collect()
|
||||
: await ctx.db.query("machines").collect()
|
||||
|
||||
const slugCache = new Map<string, Id<"companies"> | null>()
|
||||
const summary = {
|
||||
total: machines.length,
|
||||
updated: 0,
|
||||
skippedMissingSlug: 0,
|
||||
skippedMissingCompany: 0,
|
||||
alreadyLinked: 0,
|
||||
}
|
||||
|
||||
for (const machine of machines) {
|
||||
const slug = machine.companySlug ?? null
|
||||
if (!slug) {
|
||||
summary.skippedMissingSlug += 1
|
||||
continue
|
||||
}
|
||||
|
||||
const cacheKey = `${machine.tenantId}::${slug}`
|
||||
let companyId = slugCache.get(cacheKey)
|
||||
if (companyId === undefined) {
|
||||
const company = await ctx.db
|
||||
.query("companies")
|
||||
.withIndex("by_tenant_slug", (q) => q.eq("tenantId", machine.tenantId).eq("slug", slug))
|
||||
.unique()
|
||||
companyId = company?._id ?? null
|
||||
slugCache.set(cacheKey, companyId)
|
||||
}
|
||||
|
||||
if (!companyId) {
|
||||
summary.skippedMissingCompany += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (machine.companyId === companyId) {
|
||||
summary.alreadyLinked += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (!effectiveDryRun) {
|
||||
await ctx.db.patch(machine._id, { companyId })
|
||||
}
|
||||
summary.updated += 1
|
||||
}
|
||||
|
||||
return {
|
||||
dryRun: effectiveDryRun,
|
||||
...summary,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue