File

src/app/components/layout/pages/venta/venta.component.ts

Implements

OnInit

Metadata

Index

Properties
Methods

Constructor

constructor(_productoServ: ProductoService, _ventaServ: VentaService, _fb: FormBuilder, _utilidadServ: UtilidadService)
Parameters :
Name Type Optional
_productoServ ProductoService No
_ventaServ VentaService No
_fb FormBuilder No
_utilidadServ UtilidadService No

Methods

agregarProductoVenta
agregarProductoVenta()
Returns : void
eliminarProducto
eliminarProducto(detalleV: DetalleVenta)
Parameters :
Name Type Optional
detalleV DetalleVenta No
Returns : void
mostrarProducto
mostrarProducto(producto: Producto)
Parameters :
Name Type Optional
producto Producto No
Returns : string
ngOnInit
ngOnInit()
Returns : void
productoParaVenta
productoParaVenta(event: any)
Parameters :
Name Type Optional
event any No
Returns : void
productosFiltro
productosFiltro(busqueda: any)
Parameters :
Name Type Optional
busqueda any No
Returns : Producto[]
registrarVenta
registrarVenta()
Returns : void

Properties

bloquearBotonRegistrar
Type : boolean
Default value : false
columnasTabla
Type : string[]
Default value : ['producto','cantidad','precio','total','accion']
datosDetalleVenta
Default value : new MatTableDataSource(this.listaProductosParaVenta)
formularioProductoVenta
Type : FormGroup
listaProductos
Type : Producto[]
Default value : []
listaProductosFiltro
Type : Producto[]
Default value : []
listaProductosParaVenta
Type : DetalleVenta[]
Default value : []
productoSeleccionado
Type : Producto
tipoPago
Type : string
Default value : 'Efectivo'
totalPagar
Type : number
Default value : 0
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatTableDataSource } from '@angular/material/table';
import { ProductoService } from '../../../../services/producto.service';
import { VentaService } from '../../../../services/venta.service';
import { Producto } from '../../../../interfaces/producto';
import { DetalleVenta } from 'src/app/interfaces/detalle-venta';
import { UtilidadService } from 'src/app/shared/utilidad.service';
import { Venta } from 'src/app/interfaces/venta';
import Swal from 'sweetalert2';

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

  listaProductos: Producto[] = [];
  listaProductosFiltro: Producto[] = [];
  listaProductosParaVenta: DetalleVenta[] = [];
  bloquearBotonRegistrar: boolean = false;
  productoSeleccionado!: Producto;
  tipoPago: string = 'Efectivo';
  totalPagar: number = 0;
  formularioProductoVenta: FormGroup;
  columnasTabla: string[] = ['producto','cantidad','precio','total','accion'];
  datosDetalleVenta = new MatTableDataSource(this.listaProductosParaVenta);

  productosFiltro(busqueda: any):Producto[]{
    const valorBuscado = typeof busqueda === "string" ? busqueda.toLocaleLowerCase() : busqueda.nombre.toLocaleLowerCase();
    
    return this.listaProductos.filter(item => item.nombre.toLocaleLowerCase().includes(valorBuscado));
  }

  constructor(
    private _productoServ: ProductoService,
    private _ventaServ: VentaService,
    private _fb: FormBuilder,
    private _utilidadServ: UtilidadService){
      
      this.formularioProductoVenta = this._fb.group({
        producto: ["", Validators.required],
        cantidad: ["", Validators.required]
      });

      this._productoServ.lista().subscribe({
        next: (data) => {
          if(data.status){
            const lista = data.value as Producto[];
            this.listaProductos = lista.filter(p => p.esActivo == 1 && p.stock > 0);
          }
        },
        error: (e) => {
          this._utilidadServ.mostrarAlerta(`Ah ocurrido un error inesperado: ${e.message}`, 'Opps! ❌');
        }
      });

      this.formularioProductoVenta.get('producto')?.valueChanges.subscribe(value => {
        this.listaProductosFiltro = this.productosFiltro(value);
      });

  }
  
  ngOnInit(): void { }

  mostrarProducto(producto: Producto): string{
    return producto.nombre;
  }

  productoParaVenta(event: any){
    this.productoSeleccionado = event.option.value;
  }

  agregarProductoVenta(){
    const _cantidad: number = this.formularioProductoVenta.value.cantidad;
    const _precio: number = parseFloat(this.productoSeleccionado.precio);
    const _total: number = _cantidad * _precio;
    this.totalPagar = this.totalPagar + _total;

    this.listaProductosParaVenta.push({
      idProducto: this.productoSeleccionado.idProducto,
      descripcionProducto: this.productoSeleccionado.nombre,
      cantidad: _cantidad,
      precioTexto: String(_precio.toFixed(2)),
      totalTexto: String(_total.toFixed(2))
    });

    this.datosDetalleVenta = new MatTableDataSource(this.listaProductosParaVenta);

    this.formularioProductoVenta.patchValue({
      producto: '',
      cantidad: ''
    });
  }

  eliminarProducto(detalleV: DetalleVenta){
    this.totalPagar = this.totalPagar - parseFloat(detalleV.totalTexto);
    this.listaProductosParaVenta = this.listaProductosParaVenta.filter(p => p.idProducto != detalleV.idProducto);

    this.datosDetalleVenta = new MatTableDataSource(this.listaProductosParaVenta);

  }

  registrarVenta(){
    if(this.listaProductosParaVenta.length > 0){
      this.bloquearBotonRegistrar = true;
      const request: Venta = {
        tipoPago: this.tipoPago,
        totalTexto: String(this.totalPagar.toFixed(2)),
        detalleVenta: this.listaProductosParaVenta
      };

      this._ventaServ.registrar(request).subscribe({
        next: (data) => {
          if(data.status){
            this.totalPagar = 0.00;
            this.listaProductosParaVenta = [];
            this.datosDetalleVenta = new MatTableDataSource(this.listaProductosParaVenta);

            Swal.fire({
              icon: 'success',
              title: 'Venta registrada correctamente!',
              text: `Número de venta ${data.value.numeroDocumento}`,
              showConfirmButton: false,
              showCancelButton: false,
              timer: 4000,
              allowOutsideClick: false,
              timerProgressBar: true,
            });
          }else{
            this._utilidadServ.mostrarAlerta('No se pudo registrar la venta. Por favor intente de nuevo', 'Opps ❌')
          }
        },
        complete:() => {
            this.bloquearBotonRegistrar = false;
        },
        error:(err) => {
          this._utilidadServ.mostrarAlerta(`Ah ocurrido un error inesperado: ${err.message}`, 'Opps! ❌');  
        },
      });
    } 
  }

}
<h1 style="margin: 20px 0px 0px 40px;" class="animate__animated animate__fadeIn">Nueva Venta</h1>
<mat-card style="margin: 20px 40px 40px 40px;" class="animate__animated animate__fadeIn">
    <mat-card-content>
        <form [formGroup]="formularioProductoVenta" (ngSubmit)="agregarProductoVenta()">
            <mat-grid-list cols="4" rowHeight="80px">
                <mat-grid-tile [colspan]="2">
                    <mat-form-field class="fullwidth" appearance="fill">
                        <mat-label>Producto</mat-label>
                        <input matInput type="text" placeholder="Buscar..." [matAutocomplete]="auto" formControlName="producto">
                        <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="productoParaVenta($event)" [displayWith]="mostrarProducto">
                            <mat-option *ngFor="let producto of listaProductosFiltro" [value]="producto">
                                {{producto.nombre}}
                            </mat-option>
                        </mat-autocomplete>
                    </mat-form-field>
                </mat-grid-tile>
                <mat-grid-tile>
                    <mat-form-field class="fullwidth" appearance="fill" style="margin-left: 40px;">
                        <mat-label>Cantidad</mat-label>
                        <input matInput type="number" formControlName="cantidad" placeholder="Cantidad de productos">
                    </mat-form-field>
                </mat-grid-tile>
                <mat-grid-tile>
                    <button mat-raised-button color="primary" style="width: 80%" [disabled]="formularioProductoVenta.invalid">
                        <mat-icon mat-list-icon>add</mat-icon> Agregar
                    </button>
                </mat-grid-tile>
            </mat-grid-list>
        </form>
        <mat-grid-list cols="4" rowHeight="80px">
            <mat-grid-tile [colspan]="2"></mat-grid-tile>
            <mat-grid-tile>
                <mat-form-field class="fullwidth" style="margin-left: 40px;" appearance="fill">
                    <mat-label>Tipo de pago</mat-label>
                    <mat-select [(value)]="tipoPago">
                        <mat-option value="Efectivo">Efectivo</mat-option>
                        <mat-option value="Tarjeta">Tarjeta</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-grid-tile>
            <mat-grid-tile>
                <button mat-raised-button color="accent" style="width: 80%">
                    Total: $ {{totalPagar.toFixed(2)}}
                </button>
            </mat-grid-tile>
        </mat-grid-list>
        <div class="mat-elevation-z2">
            <table mat-table [dataSource]="datosDetalleVenta">
                <ng-container matColumnDef="producto">
                    <th mat-header-cell *matHeaderCellDef>Producto</th>
                    <td mat-cell *matCellDef="let element">{{element.descripcionProducto}}</td>
                </ng-container>
                <ng-container matColumnDef="cantidad">
                    <th mat-header-cell *matHeaderCellDef>Cantidad</th>
                    <td mat-cell *matCellDef="let element">{{element.cantidad}}</td>
                </ng-container>
                <ng-container matColumnDef="precio">
                    <th mat-header-cell *matHeaderCellDef>Precio</th>
                    <td mat-cell *matCellDef="let element">{{element.precioTexto}}</td>
                </ng-container>
                <ng-container matColumnDef="total">
                    <th mat-header-cell *matHeaderCellDef>Total</th>
                    <td mat-cell *matCellDef="let element">{{element.totalTexto}}</td>
                </ng-container>
                <ng-container matColumnDef="accion">
                    <th mat-header-cell *matHeaderCellDef style="width: 80px;"></th>
                    <td mat-cell *matCellDef="let element">
                        <button matTooltip="Eliminar de esta venta" mat-icon-button color="warn" (click)="eliminarProducto(element)">
                            <mat-icon>delete</mat-icon>
                        </button>
                    </td>
                </ng-container>
                <tr mat-header-row *matHeaderRowDef="columnasTabla"></tr>
                <tr mat-row *matRowDef="let row; columns: columnasTabla;"></tr>
            </table>
        </div>
        <mat-grid-list cols="4" rowHeight="80px">
            <mat-grid-tile [colspan]="3"></mat-grid-tile>
            <mat-grid-tile>
                <button mat-raised-button color="primary" (click)="registrarVenta()" style="width: 90%;" [disabled]="listaProductosParaVenta.length < 1 || bloquearBotonRegistrar">
                    <mat-icon>new_label</mat-icon>Registrar venta
                </button>
            </mat-grid-tile>
        </mat-grid-list>
    </mat-card-content>
</mat-card>

./venta.component.css

.fullwidth{
    width: 100%;
}

table{
    width: 100%;
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""