0

Hola Saludos desde Chile, si bien no tengo errores quisiera mostrar mi tabla productos_vendidos segun la IdVenta y mostrarla mediante un NgFor tal como se muestra, el inconveniente es que el id de la venta cambia en cada factura. Necesito que en este SELECT Solo se muestre los registros segun la id venta y los con otra id no se muestren en la factura.

    SELECT id_venta, cantidad, nombre, precio, subtotal
    FROM productos_vendidos  inner join ventas on productos_vendidos.id_venta = ventas.id 
    WHERE productos_vendidos.id_venta = id_venta

introducir la descripción de la imagen aquí

 app.get("/productos_vendidos", async (req, res) => {
  const venta = await productoVendidoModel.obtener();
  res.json(venta);
});
obtener() {
  return new Promise((resolve, reject) => {
    sql.query(`SELECT id_venta, cantidad, nombre, precio, subtotal
    FROM productos_vendidos  inner join ventas on productos_vendidos.id_venta = ventas.id 
    WHERE productos_vendidos.id_venta = id_venta;`,
      (err, resultados) => {
        if (err) reject(err);
        else resolve(resultados);
      });
  });
}, 

Cambiar este numero ingresado manualmente por un valor dinamico segun a idVenta.

  CREATE TABLE IF NOT EXISTS `carrito`.`productos_vendidos` (
  `id_venta` INT(11) NOT NULL,
  `id_producto` INT(11) NOT NULL,
  `cantidad` numeric(4) NOT NULL,
  `nombre` varchar(255) NOT NULL,
  `precio` numeric(10) NOT NULL,
  `subtotal` numeric(10) NOT NULL,
  INDEX `fk_productos_vendidos_ventas1_idx` (`id_venta` ASC) VISIBLE,
  INDEX `fk_productos_vendidos_productos1_idx` (`id_producto` ASC) VISIBLE,
  CONSTRAINT `fk_productos_vendidos_ventas1`
    FOREIGN KEY (`id_venta`)
    REFERENCES `carrito`.`ventas` (`id`)
    ON UPDATE CASCADE,
  CONSTRAINT `fk_productos_vendidos_productos1`
    FOREIGN KEY (`id_producto`)
    REFERENCES `carrito`.`productos` (`id`)
    ON UPDATE CASCADE)
ENGINE = InnoDB;


    CREATE TABLE IF NOT EXISTS `carrito`.`ventas` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `id_cliente` INT(11) NOT NULL,
  `nombrecompleto` VARCHAR(255) NOT NULL,
  `direccion` VARCHAR(255) NOT NULL,
  `comuna` VARCHAR(255) NOT NULL,
  `contacto` VARCHAR(255) NOT NULL,
  `subtotales` numeric(10) NOT NULL,
  `iva` numeric(10) NOT NULL,
  `total` NUMERIC(10) NOT NULL,
   INDEX `fk_ventas_clientes1_idx` (`id_cliente` ASC) VISIBLE,
    CONSTRAINT `fk_ventas_clientes1`
    FOREIGN KEY (`id_cliente`)
    REFERENCES `carrito`.`clientes` (`id`)
    ON UPDATE CASCADE,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB;

import { Injectable } from '@angular/core';
import { FotoproductoService } from "../servicios/fotoproducto.service";
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Venta } from '../Modelos/venta';
import { Producto } from '../Modelos/producto';
const baseUrl = 'http://localhost:3000/productos_vendidos';

@Injectable({
  providedIn: 'root'
})
export class VentaService {

  constructor(
    private http: HttpClient,
    private _http: FotoproductoService,
  ) { }
  public async obtenerVentas() {
    return await this._http.get("/ventas");
  }

  public async obtenerDetalleDeVenta(idVenta) {
    return await this._http.get("/detalle_venta?id=".concat(idVenta));
  }
  async terminarCompra(idCliente: number, NombreCompleto: String, Direccion: String, Comuna: String, Contacto: String, Subtotales:number, Iva:number, TotalCompra:number) {
    return await this._http.post("/ventas", {
      id: idCliente,
      nombrecompleto: NombreCompleto,
      direccion: Direccion,
      comuna: Comuna,
      contacto: Contacto,
      subtotales : Subtotales,
      iva : Iva,
      totalcompra : TotalCompra,
    });
  }
  obtenerProductosVendidos(): Observable<Venta[]> {
    return this.http.get<Venta[]>(baseUrl);
  }
  
  public async obtenerDetalleDeProductoVendido(idVenta) {
    return await this._http.get("/factura?id=".concat(idVenta));
  }
}


import { Component, OnInit} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { VentaService} from "../../../servicios/venta.service";


@Component({
  selector: 'app-factura',
  templateUrl: './factura.component.html',
  styleUrls: ['./factura.component.css']
})
export class FacturaComponent implements OnInit {

  public venta= {
    id: 0,
    nombrecompleto: "",
    direccion: "",
    comuna: "",
    contacto: "",
    cantidad:"",
    nombre:"",
    precio:0,
    subtotal:0,
    total:0,
    subtotales:0,
    iva:0,
    totalcompra: 0,
  };
  productos: any[] = [];

  constructor(
    private activatedRoute: ActivatedRoute,
    private ventasService:VentaService
  ) { }

  async ngOnInit() {
    const id = this.activatedRoute.snapshot.paramMap.get("id");
    this.venta = await this.ventasService.obtenerDetalleDeVenta(id);
    this.refrescarEstado();
    this.obtenerProductos();
  }
  async refrescarEstado() {
    const id = this.venta.id;
  }
  obtenerProductos(): void {
    this.ventasService.obtenerProductosVendidos().subscribe(
      data => {
        this.productos = data as string[];
        const id = this.venta.id;
        this.productos.forEach(value => {
          if(id === value["id_venta"]){
            this.productos = data as string[];  
            const cantidad = value["cantidad"]
            const nombre =value["nombre"]
            const precio = value["precio"]
            const subtotal = value["subtotal"]
            console.log(value)
            console.log(cantidad)
            console.log(nombre)
            console.log(precio)
            console.log(subtotal)
            console.log(this.productos)
            console.log("Son lo mismo")
          }
        })
      },
      (error) => console.log(error),
      () => console.log("Complete")
    )
  }
}
    
<div class="container">
    <div class="row factura">
      <div class="col s12">
        <div class="card">
          <div class="card-content hoverable">
                <div id="pdf" #pdfTable style="padding-top: 15px;">
                  <table class="container" style="border:hidden"  cellpadding="0" cellspacing="0">
                        <tr>
                            <td style="border:hidden"><p style="border:hidden; position:relative; padding-left:30px;">FERRETERIA NOMBRE</p>
                          </td>
                        </tr>
                        <tr>
                        <td style="border:hidden"><p>GIRO: INSTALACIÓN DE INSUMOS</p></td>
                        </tr>
                        <tr>
                         <td style="border:hidden"><p style="position:relative; padding-left:15px;">COMBARBALA #345 CALDERA</p></td>
                        </tr>
                      </table>
                      <br>
                      <div class="container">
                        <div class="logo col s6 center-align offset-s6" style="border-top: black 1px solid;border-left: black 1px solid; border-right: black 1px solid; border-bottom:black 1px solid;">
                          <span  class="flow-text" style="font-weight: bold">R.U.T : 76.789.987-K</span><br>
                          <span  class="flow-text" style="font-weight: bold">FACTURA ELECTRÓNICA</span><br>
                          <span  class="flow-text" style="font-weight: bold">N°{{venta.id}}</span><br>
                        </div><br>
                      </div><br>
                <table class="container">
                  <tr>
                      <td style="border-top: black 1px solid;">SEÑOR(ES):<label style="padding-left: 240px;">{{venta.nombrecompleto}}</label></td>
                  </tr>
                  <tr>
                      <td>R.U.T:<label style="padding-left: 279px;">181419482</label></td>
                  </tr>
                  <tr>
                    <td>GIRO:</td>
                </tr>
                <tr>
                    <td>DIRECCIÓN:<label style="padding-left: 240px;">{{venta.direccion}}</label></td>
                </tr>
                <tr>
                    <td>COMUNA:<label style="padding-left: 252px;">{{venta.comuna}}</label></td>
                </tr>
                <tr>
                    <td>CONTACTO:<label style="padding-left: 240px;">{{venta.contacto}}</label></td>
                </tr>
              </table>                   
                        <br><br>
                      <table class="container">
                       <tr class="brown white-text">
                        <th class="detalle" >Cantidad</th>
                        <th class="detalle" >Descripción</th>
                        <th class="detalle" >Precio</th>
                        <th class="detalle" >Total</th>
                       </tr>
                       <tr *ngFor="let producto of productos">
                        <td class="cantidad" style="border-right: black 1px solid;border-bottom: black 1px solid">{{producto.cantidad}}</td>
                        <td class="descripcion" style="border-right: black 1px solid;border-bottom: black 1px solid">{{producto.nombre}}</td>
                        <td class="dinero" style="border-right: black 1px solid;border-bottom: black 1px solid">{{producto.precio |currency:'CLP':'symbol-narrow'}}</td>
                        <td class="dinero" style="border-bottom: black 1px solid;">{{producto.subtotal |currency:'CLP':'symbol-narrow'}}</td>
                       </tr>
                       <tr>
                        <td class="costos" colspan="3" style="border-right: black 1px solid;border-bottom: black 1px solid;">Monto Neto</td>
                        <td class="dinero"style="border-bottom: black 1px solid;"> {{venta.subtotales |currency:'CLP':'symbol-narrow'}}</td>
                       </tr> 
                       <tr>
                        <td class="costos" colspan="3" style="border-right: black 1px solid;border-bottom: black 1px solid">I.V.A 19%</td>
                        <td class="dinero" style="border-bottom: black 1px solid;"> {{venta.iva |currency:'CLP':'symbol-narrow'}}</td>
                       </tr> 
                       <tr>
                        <td class="costos" colspan="3" style="border-right: black 1px solid;">Total</td>
                        <td class="dinero" > {{venta.total |currency:'CLP':'symbol-narrow'}}</td>
                       </tr>
                      </table>
                </div>
                <br>
                <div class="center-align"><button  class="btn-large grey darken-2">Descargar Factura en PDF
                  <i class="material-icons left">archive</i>
                </button></div><br>
          </div>
        </div>
      </div>
  </div>
  </div>

Trate de ingresar los datos de la tabla por la id en angular sin ngfor y solo me mostrara 1 item de los 2 productos si bien era el item correcto, la idea es que muestre el detalle de los productos comprados. Estare atenta sus respuestas Gracias.

6
  • Querida compatriota, considera incluir el código o snippet para poder replicar lo que te pasa, incluyendo tu HTML. Las imágenes se deben evitar en lo posible. Además no explicas si falla algo, tienes un error, o parecido. el 2 sep. 2021 a las 21:15
  • Bienvenida a SOes te recomiendo que hagas el recorrido para que sepas como funciona el sitio y también obtengas tu primera medalla! también lee Cómo preguntar para que tu pregunta sea mejor recibida. Las imágenes mostrando código no son bien recibidas, por favor edita tu pregunta
    – John Doe
    el 2 sep. 2021 a las 22:46
  • Por favor, aclara tu problema específico o proporciona detalles adicionales para resaltar exactamente lo que necesitas. Tal como está escrito, es difícil saber exactamente qué estás preguntando.
    – Comunidad Bot
    el 2 sep. 2021 a las 22:47
  • Ok como les decia soy novata disculpen las molestias :) el 3 sep. 2021 a las 0:49
  • No veo donde le estas pasando como parámetro el idVenta que necesitas. Ese Id debes enviarlo en el objeto request de tu endpoint, ya sea por parámetro, query o body el 4 sep. 2021 a las 23:56

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.