Untitled
unknown
plain_text
7 months ago
1.8 kB
0
Indexable
Never
const { PrismaClient } = require('@prisma/client') const prisma = new PrismaClient() async function createPedidoWithDetallePedidos(userId, pedidoData, detallePedidosData) { // Create a new Pedido record const pedido = await prisma.pedido.create({ data: { usuarioId: userId, ...pedidoData, }, }) // Create DetallePedido records and associate them with the new Pedido record const detallePedidos = await Promise.all( detallePedidosData.map(async (detallePedidoData) => { const productoId = detallePedidoData.productoId const producto = await prisma.producto.findUnique({ where: { id: productoId } }) return prisma.detallePedido.create({ data: { pedidoId: pedido.id, productoId, cantidad: detallePedidoData.cantidad, precio: producto.precio, }, }) }) ) // Calculate and update the Pedido total based on the DetallePedido records const subtotal = detallePedidos.reduce((acc, detallePedido) => { return acc + detallePedido.cantidad * detallePedido.precio }, 0) const impuestos = subtotal * 0.18 // 18% taxes const total = subtotal + impuestos - (pedido.descuento || 0) await prisma.pedido.update({ where: { id: pedido.id }, data: { subtotal, impuestos, total }, }) return pedido }