diff --git a/convex/machines.ts b/convex/machines.ts index 3ceed28..7b6a342 100644 --- a/convex/machines.ts +++ b/convex/machines.ts @@ -521,11 +521,13 @@ export const register = mutation({ const now = Date.now() const metadataPatch = args.metadata && typeof args.metadata === "object" ? (args.metadata as Record) : undefined + // Busca 1: fingerprint exato (tenant + slug + hostname + MACs hash) let existing = await ctx.db .query("machines") .withIndex("by_tenant_fingerprint", (q) => q.eq("tenantId", tenantId).eq("fingerprint", fingerprint)) .first() + // Busca 2: por email + validacao de hardware (fallback se fingerprint mudou mas email igual) if (!existing) { const collaboratorEmail = extractCollaboratorEmail(metadataPatch ?? args.metadata) if (collaboratorEmail) { @@ -539,6 +541,40 @@ export const register = mutation({ } } + // Busca 3: por hostname + validacao de hardware (fallback se o usuario mudou mas e a mesma maquina fisica) + // Isso garante que o historico de tickets da maquina seja preservado independente do usuario + if (!existing) { + const hostnameLower = args.hostname.trim().toLowerCase() + const candidates = await ctx.db + .query("machines") + .withIndex("by_tenant_hostname", (q) => q.eq("tenantId", tenantId).eq("hostname", args.hostname)) + .collect() + // Procura uma maquina com hostname igual E hardware compativel (MAC ou serial) + for (const candidate of candidates) { + if (matchesExistingHardware(candidate, identifiers, args.hostname)) { + existing = candidate + break + } + } + // Se nao encontrou por hostname exato, tenta busca mais ampla por hardware + if (!existing) { + // Busca maquinas do mesmo tenant e verifica se alguma tem MAC/serial compativel + const allMachines = await ctx.db + .query("machines") + .withIndex("by_tenant", (q) => q.eq("tenantId", tenantId)) + .collect() + for (const candidate of allMachines) { + // Verifica se compartilha MAC ou serial (hardware fisico) + const sharedMac = candidate.macAddresses.some((mac) => identifiers.macs.includes(mac)) + const sharedSerial = candidate.serialNumbers.some((serial) => identifiers.serials.includes(serial)) + if (sharedMac || sharedSerial) { + existing = candidate + break + } + } + } + } + let machineId: Id<"machines"> if (existing) { diff --git a/convex/schema.ts b/convex/schema.ts index e119888..7589ba0 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -647,6 +647,7 @@ export default defineSchema({ .index("by_tenant_company", ["tenantId", "companyId"]) .index("by_tenant_fingerprint", ["tenantId", "fingerprint"]) .index("by_tenant_assigned_email", ["tenantId", "assignedUserEmail"]) + .index("by_tenant_hostname", ["tenantId", "hostname"]) .index("by_auth_email", ["authEmail"]), usbPolicyEvents: defineTable({