import { v } from 'convex/values'; import { mutation, query } from './_generated/server'; import { getCurrentUserFunction } from './auth'; export const list = query({ args: {}, handler: async (ctx) => { return await ctx.db.query('objetos').collect(); } }); export const search = query({ args: { query: v.string() }, handler: async (ctx, args) => { return await ctx.db .query('objetos') .withSearchIndex('search_nome', (q) => q.search('nome', args.query)) .take(10); } }); export const create = mutation({ args: { nome: v.string(), valorEstimado: v.string(), tipo: v.union(v.literal('material'), v.literal('servico')), codigoEfisco: v.string(), codigoCatmat: v.optional(v.string()), codigoCatserv: v.optional(v.string()), unidade: v.string(), atas: v.optional(v.array(v.id('atas'))) }, handler: async (ctx, args) => { const user = await getCurrentUserFunction(ctx); if (!user) throw new Error('Unauthorized'); const objetoId = await ctx.db.insert('objetos', { nome: args.nome, valorEstimado: args.valorEstimado, tipo: args.tipo, codigoEfisco: args.codigoEfisco, codigoCatmat: args.codigoCatmat, codigoCatserv: args.codigoCatserv, unidade: args.unidade, criadoPor: user._id, criadoEm: Date.now() }); if (args.atas) { for (const ataId of args.atas) { await ctx.db.insert('atasObjetos', { ataId, objetoId }); } } return objetoId; } }); export const update = mutation({ args: { id: v.id('objetos'), nome: v.string(), valorEstimado: v.string(), tipo: v.union(v.literal('material'), v.literal('servico')), codigoEfisco: v.string(), codigoCatmat: v.optional(v.string()), codigoCatserv: v.optional(v.string()), unidade: v.string(), atas: v.optional(v.array(v.id('atas'))) }, handler: async (ctx, args) => { const user = await getCurrentUserFunction(ctx); if (!user) throw new Error('Unauthorized'); await ctx.db.patch(args.id, { nome: args.nome, valorEstimado: args.valorEstimado, tipo: args.tipo, codigoEfisco: args.codigoEfisco, codigoCatmat: args.codigoCatmat, codigoCatserv: args.codigoCatserv, unidade: args.unidade }); if (args.atas !== undefined) { // Remove existing links const existingLinks = await ctx.db .query('atasObjetos') .withIndex('by_objetoId', (q) => q.eq('objetoId', args.id)) .collect(); for (const link of existingLinks) { await ctx.db.delete(link._id); } // Add new links for (const ataId of args.atas) { await ctx.db.insert('atasObjetos', { ataId, objetoId: args.id }); } } } }); export const getAtas = query({ args: { objetoId: v.id('objetos') }, handler: async (ctx, args) => { const links = await ctx.db .query('atasObjetos') .withIndex('by_objetoId', (q) => q.eq('objetoId', args.objetoId)) .collect(); const atas = await Promise.all(links.map((link) => ctx.db.get(link.ataId))); return atas.filter((ata) => ata !== null); } }); export const remove = mutation({ args: { id: v.id('objetos') }, handler: async (ctx, args) => { const user = await getCurrentUserFunction(ctx); if (!user) throw new Error('Unauthorized'); await ctx.db.delete(args.id); } });