diff --git a/mvp/b2c/src/db/pricing-queries.ts b/mvp/b2c/src/db/pricing-queries.ts new file mode 100644 index 0000000..f05aeeb --- /dev/null +++ b/mvp/b2c/src/db/pricing-queries.ts @@ -0,0 +1,54 @@ +import { eq } from 'drizzle-orm'; +import { db } from './index'; +import { pricingConfig, catalogItems, tenants } from './schema'; +import { TENANT_SLUG } from '@/lib/funnel'; +import type { PricingConfig, CatalogItem, ManoObraKey } from '@/budget/types'; + +async function getTenantId(): Promise { + const [tenant] = await db.select().from(tenants).where(eq(tenants.slug, TENANT_SLUG)).limit(1); + if (!tenant) throw new Error(`Tenant "${TENANT_SLUG}" no existe. ¿Has corrido npm run db:seed?`); + return tenant.id; +} + +const MANO_OBRA_DEFAULT: Record = { + demolicion: 0, + fontaneria: 0, + electricidad: 0, + mano_de_obra: 0, +}; + +export async function getPricingConfig(): Promise { + const tenantId = await getTenantId(); + const [row] = await db + .select() + .from(pricingConfig) + .where(eq(pricingConfig.tenantId, tenantId)) + .limit(1); + + if (!row) { + return { alturaTechoDefault: 2.5, factorZona: {}, manoObra: { ...MANO_OBRA_DEFAULT } }; + } + return { + alturaTechoDefault: row.alturaTechoDefault, + factorZona: row.factorZona, + manoObra: { ...MANO_OBRA_DEFAULT, ...(row.manoObra as Record) }, + }; +} + +export async function getCatalog(): Promise { + const tenantId = await getTenantId(); + const rows = await db.select().from(catalogItems).where(eq(catalogItems.tenantId, tenantId)); + return rows.map((r) => ({ + id: r.id, + categoria: r.categoria, + nombre: r.nombre, + calidad: r.calidad, + precioUnit: r.precioUnit, + unidad: r.unidad, + descriptorRender: r.descriptorRender, + esDefault: r.esDefault, + sku: r.sku, + })); +} + +export { getTenantId };