Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

import { AfterViewInit, Component, OnDestroy, OnInit } from ‘@angular/core’; import {…

  1. User

    import { AfterViewInit, Component, OnDestroy, OnInit } from ‘@angular/core’; import { AlmacenService } from ‘…/…/almacen/services/almacen.service’; import { Config } from ‘datatables.net’; import { ADTSettings } from ‘angular-datatables/src/models/settings’; import { Subject } from ‘rxjs’; import { Almacen } from ‘…/…/models/almacen.model’;

    @Component({ selector: ‘app-inventario-almacen’, templateUrl: ‘./inventario-almacen.component.html’, styleUrl: ‘./inventario-almacen.component.css’ }) export class InventarioAlmacenComponent implements AfterViewInit, OnInit, OnDestroy {

    dtOptions: Config = {}; dtTrigger = new Subject(); detalleSeccion: Record<string, any>[] = []; almacenes: Almacen[] = []; idalmacen: number | null = null; iconClass: string = ‘’;

    constructor(private almacenService: AlmacenService) {}

    ngOnInit(): void { this.configDataTable(); this.listarAlmacenes(); }

    ngAfterViewInit(): void { this.initDataTable(); setTimeout(() => { this.dtTrigger.next(this.dtOptions); }, 200); }

    configDataTable(): void { this.dtOptions = { language: { url: ‘https://cdn.datatables.net/plug-ins/2.0.8/i18n/es-ES.json’, paginate: { first: ‘<i class=“bi bi-chevron-double-left”>’, last: ‘<i class=“bi bi-chevron-double-right”>’, next: ‘<i class=“bi bi-chevron-right”>’, previous: ‘<i class=“bi bi-chevron-left”>’, }, },

    responsive: true, columnDefs: [ { responsivePriority: 1, targets: -1 }, { responsivePriority: 2, targets: 1 }, ],

    layout: { top2Start: ‘buttons’, topStart: ‘pageLength’, topEnd: ‘search’, },

    buttons: { dom: { button: { tag: ‘button’, className: ‘btn’, }, }, buttons: [ { extend: ‘excelHtml5’, className: ‘btn btn-outline-success’, text: ‘<i class=“bi bi-file-earmark-excel”>’, titleAttr: ‘Excel’, }, { extend: ‘pdfHtml5’, className: ‘btn btn-outline-danger’, text: ‘<i class=“bi bi-file-earmark-pdf”>’, titleAttr: ‘PDF’, }, ], }, }; }

    initDataTable(): void { const that = this; this.dtOptions = { …this.dtOptions, ajax: (dataTablesParameters: any, callback) => { this.listar(callback); },

    columns: [ { title: ‘ID’, data: ‘idproducto’ }, { title: ‘Descripcion’, data: ‘nombre_producto’ }, { title: ‘Seccion’, data: ‘nombre_categoria’ }, { title: ‘Capacidad’, data: ‘stock’ }, ], }; }

    listarAlmacenes(): void { this.almacenService.listarAlmacenes().subscribe({ next: (almacenes) => { this.almacenes = almacenes; this.idalmacen = this.almacenes[0].idalmacen; this.obtenerDetallesSeccion(this.idalmacen) }, error: (error) => { console.error(‘Error al obtener almacenes’, error); }, }); }

    obtenerDetallesSeccion(idalmacen: number): void { this.almacenService.obtenerDetalleSeccion(idalmacen).subscribe({ next: (detalles: Record<string, any>[]) => { this.detalleSeccion = detalles; }, error: (error) => { console.error(‘Error al obtener detalles de la sección’, error); }, }); }

    alertClass(cantProd: number, capdAlmc: number): string { const espacio = cantProd / capdAlmc; if (espacio < 0.6) { this.iconClass = ‘bi-check-circle-fill’; return ‘alert-success’; } else if (espacio < 0.85) { this.iconClass = ‘bi-exclamation-triangle-fill’; return ‘alert-warning’; } else { this.iconClass = ‘bi-exclamation-octagon-fill’; return ‘alert-danger’; } }

    listar(callback: any): void { this.almacenService.listarProductosPorAlmacen(this.idalmacen!).subscribe({ next: (almacenes: Record<string, any>[]) => { callback({ data: almacenes, }); }, error: (error) => { console.error(‘Error a listar almacén’, error); }, }); }

    filtrarProductosPorAlmacen(id: number): void { this.idalmacen = id; this.obtenerDetallesSeccion(this.idalmacen); this.refreshTable(); }

    refreshTable() { const tabla = $(‘#tablaInventarioAlmacen’).DataTable(); if (tabla) { tabla.ajax.reload(); } }

    ngOnDestroy(): void { this.dtTrigger.unsubscribe(); }

    }

    • tengo este componente en angular y lleno un listado con ajax datatble, quiero saber si hay una forma de qeu al momento de imporimir en excel o pdf tome este div - Almacén
  2. Assistant

    Para agregar el título del almacén “Almacén” y su contenido en la exportación a Excel o PDF usando DataTables y su integración con Angular, puedes hacer uso de la opción messageTop de DataTables.

    Aquí está el código relevante para configurar messageTop en las opciones de exportación:

    import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
    import { AlmacenService } from '…/…/almacen/services/almacen.service';
    import { Config } from 'datatables.net';
    import { ADTSettings } from 'angular-datatables/src/models/settings';
    import { Subject } from 'rxjs';
    import { Almacen } from '…/…/models/almacen.model';
    
    @Component({
      selector: 'app-inventario-almacen',
      templateUrl: './inventario-almacen.component.html',
      styleUrl: './inventario-almacen.component.css'
    })
    export class InventarioAlmacenComponent implements AfterViewInit, OnInit, OnDestroy {
    
      dtOptions: Config = {};
      dtTrigger = new Subject<ADTSettings>();
      detalleSeccion: Record<string, any>[] = [];
      almacenes: Almacen[] = [];
      idalmacen: number | null = null;
      iconClass: string = '';
    
      constructor(private almacenService: AlmacenService) {}
    
      ngOnInit(): void {
        this.configDataTable();
        this.listarAlmacenes();
      }
    
      ngAfterViewInit(): void {
        this.initDataTable();
        setTimeout(() => {
          this.dtTrigger.next(this.dtOptions);
        }, 200);
      }
    
      configDataTable(): void {
        this.dtOptions = {
          language: {
            url: 'https://cdn.datatables.net/plug-ins/2.0.8/i18n/es-ES.json',
            paginate: {
              first: '<i class="bi bi-chevron-double-left"></i>',
              last: '<i class="bi bi-chevron-double-right"></i>',
              next: '<i class="bi bi-chevron-right"></i>',
              previous: '<i class="bi bi-chevron-left"></i>',
            },
          },
          responsive: true,
          columnDefs: [
            { responsivePriority: 1, targets: -1 },
            { responsivePriority: 2, targets: 1 },
          ],
          layout: {
            top2Start: 'buttons',
            topStart: 'pageLength',
            topEnd: 'search',
          },
          buttons: {
            dom: {
              button: {
                tag: 'button',
                className: 'btn',
              },
            },
            buttons: [
              {
                extend: 'excelHtml5',
                className: 'btn btn-outline-success',
                text: '<i class="bi bi-file-earmark-excel"></i>',
                titleAttr: 'Excel',
                messageTop: () => this.generateExportMessage(),
              },
              {
                extend: 'pdfHtml5',
                className: 'btn btn-outline-danger',
                text: '<i class="bi bi-file-earmark-pdf"></i>',
                titleAttr: 'PDF',
                messageTop: () => this.generateExportMessage(),
              },
            ],
          },
        };
      }
    
      generateExportMessage(): string {
        let message = "<h2>Almacén</h2>";
        message += `
          <div class="mt-3">
            <div class="btn-group" role="group" aria-label="Almacenes">
        `;
    
        this.almacenes.forEach(almacen => {
          message += `
            <button class="btn btn-primary" type="button">
              ${almacen.seccion}
            </button>
          `;
        });
    
        message += '</div></div>';
    
        this.detalleSeccion.forEach(det => {
            message += `
              <div class="alert d-flex align-items-center justify-content-between ${this.alertClass(det['cantidad_producto'], det['capacidad'])}">
                <div>
                  <p><strong>ID Almacén: </strong> ${det['idalmacen']}</p>
                  <p><strong>Descripción: </strong> ${det['descripcion']}</p>
                  <p><strong>Sección: </strong> ${det['seccion']}</p>
                  <p><strong>Capacidad: </strong> ${det['capacidad']}</p>
                  <p><strong>Cantidad de productos: </strong> ${det['cantidad_producto']}</p>
                  <p><strong>${det['espacio_disponible']}</strong></p>
                </div>
                <i class="${this.iconClass} bi flex-shrink-0 ms-2" style="font-size: 24px;"></i>
              </div>
            `;
        });
    
        return message;
      }
    
      initDataTable(): void {
        const that = this;
        this.dtOptions = {
          ...this.dtOptions,
          ajax: (dataTablesParameters: any, callback) => {
            this.listar(callback);
          },
          columns: [
            { title: 'ID', data: 'idproducto' },
            { title: 'Descripcion', data: 'nombre_producto' },
            { title: 'Seccion', data: 'nombre_categoria' },
            { title: 'Capacidad', data: 'stock' },
          ],
        };
      }
    
      listarAlmacenes(): void {
        this.almacenService.listarAlmacenes().subscribe({
          next: (almacenes) => {
            this.almacenes = almacenes;
            this.idalmacen = this.almacenes[0]?.idalmacen;
            this.obtenerDetallesSeccion(this.idalmacen);
          },
          error: (error) => {
            console.error('Error al obtener almacenes', error);
          },
        });
      }
    
      obtenerDetallesSeccion(idalmacen: number): void {
        this.almacenService.obtenerDetalleSeccion(idalmacen).subscribe({
          next: (detalles: Record<string, any>[]) => {
            this.detalleSeccion = detalles;
          },
          error: (error) => {
            console.error('Error al obtener detalles de la sección', error);
          },
        });
      }
    
      alertClass(cantProd: number, capdAlmc: number): string {
        const espacio = cantProd / capdAlmc;
        if (espacio < 0.6) {
          this.iconClass = 'bi-check-circle-fill';
          return 'alert-success';
        } else if (espacio < 0.85) {
          this.iconClass = 'bi-exclamation-triangle-fill';
          return 'alert-warning';
        } else {
          this.iconClass = 'bi-exclamation-octagon-fill';
          return 'alert-danger';
        }
      }
    
      listar(callback: any): void {
        this.almacenService.listarProductosPorAlmacen(this.idalmacen!).subscribe({
          next: (almacenes: Record<string, any>[]) => {
            callback({
              data: almacenes,
            });
          },
          error: (error) => {
            console.error('Error a listar almacén', error);
          },
        });
      }
    
      filtrarProductosPorAlmacen(id: number): void {
        this.idalmacen = id;
        this.obtenerDetallesSeccion(this.idalmacen);
        this.refreshTable();
      }
    
      refreshTable() {
        const tabla = document.getElementById('tablaInventarioAlmacen').DataTable();
        if (tabla) {
          tabla.ajax.reload();
        }
      }
    
      ngOnDestroy(): void {
        this.dtTrigger.unsubscribe();
      }
    
    }
    

    Asegúrate de ajustar las importaciones y las rutas de los módulos de acuerdo a tu proyecto. Además, tienes que tener DataTables correctamente configurado en tu proyecto Angular para usar las opciones de exportación correctamente.