Actualización de la configuración y los datos de la tabla

Aprenda a actualizar la configuración y los datos de la tabla después de enviar el formulario. En esta lección, te asegurarás de que el formulario funcione correctamente y te prepararás para rellenar datos desde las API REST.

Procedimiento

  1. Enviar el formulario:
    1. Vaya a la página Crear reserva, introduzca los datos y envíe la reserva. Por ejemplo:
      Crear reserva
    2. Después de enviar el formulario, debería aparecer el siguiente mensaje:
      Someter
  2. En un terminal, vaya al directorio src-custom/app/features/create-reservation.
  3. Ejecute el siguiente comando para generar una tabla que permita a los usuarios ver y actualizar los valores de las reservas.
    Este comando utiliza los scripts de generación de código IBM que se incluyen en el kit de herramientas para desarrolladores.
    ng g @buc/schematics:table-component \
    --name create-reservation \
    --extend ClientSidePaginationBaseTableComponent \
    --path packages/inventory-search-results/src-custom/app/features/create-reservation \
    --json-file-path packages/inventory-search-results/src-custom/assets/custom \
    --translation-file-path packages/inventory-search-results/src-custom/assets/custom/i18n
    • --name <nombre de la tabla>,
    • --path <ruta donde desea crear la tabla>
    • --json-file-path <ruta a buc-table-config.json donde se añadirá la configuración de la tabla>
    • --translation-file-path <ruta al archivo JSON de traducción personalizada>
    • --extend <nombre de clase de tabla extensible>
    Para obtener ayuda con el script esquemático, ejecute
    ng g @buc/schematics:table-component --help
  4. Después de ejecutar el script, se crean nuevos archivos en la ubicación que especificaste y el ext-search-module.ts archivo se actualiza con un nuevo componente, CreateReservationTableComponent.
  5. Dado que el componente personalizado que ha generado (CreateReservationTableComponent) necesita utilizar utilidades y bibliotecas de IBM, mueva el componente al app-customization.impl.ts archivo siguiendo los pasos que se indican a continuación.
    1. Edita el archivo src-custom/app/features/ext-search.module.ts con los siguientes cambios.
      • Elimine la instrucción « {CreateReservationTableComponent} ».
      • Elimine CreateReservationTableComponent de la declarations matriz.
      El código resultante tiene este aspecto:
      import { NgModule } from '@angular/core';
      import { CommonModule } from '@angular/common';
      
      @NgModule({
        declarations: [
        ],
        imports: [
          CommonModule
        ]
      })
      export class ExtSearchModule { }
    2. Actualiza el archivo src-custom/app/app-customization.impl.ts con los siguientes cambios.
      • Añade la siguiente declaración de importación.
        import { CreateReservationTableComponent } from './features/create-reservation/create-reservation-table/create-reservation-table.component';
      • Añade CreateReservationTableComponent a la matriz de componentes.
        static readonly components = [CreateReservationComponent, CreateReservationTableComponent];
        
      Una vez compilado correctamente el módulo, se añade una nueva entrada create-reservation-table en el archivo src-custom/assets/custom/buc-table-config.json.
  6. Abre el archivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts y busca el valor del selector.
    En este caso, el valor es buc-create-reservation-table. Debe utilizar este valor en el HTML para mostrar la tabla.
  7. Añade el siguiente código al archivo src-custom/app/features/create-reservation/create-reservation.component.html después del comentario <!–Reservation table -->.
    <buc-create-reservation-table [parentPage]="this"></buc-create-reservation-table>
  8. Vuelve al Order Hub de última generación y vuelve a cargar el marco.
    Vaya a la página Crear reserva para comprobar que se muestra la mesa.
    Captura de pantalla de la página Crear reserva con un cuadro de entrada y una tabla.
  9. Observe que el encabezado incluye una casilla de verificación. Para eliminar la casilla de verificación, siga los siguientes pasos.
    1. Abre el src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.html archivo.
    2. Añade el siguiente código al final del <buc-table> elemento.
      [showSelectionColumn]="false"
      Captura de pantalla de create-reservation-table-component.html con la propiedad showSelectionColumn
  10. Abre el archivo packages/inventory-search-results/src-custom/assets/custom/buc-table-config.json.
  11. Reemplaza la matriz de encabezados de create-reservation-table con el siguiente código para actualizar las cadenas del encabezado de la tabla.
            {
                "name": "Node id",
                "id": "nodeId",
                "sortKey": "nodeId",
                "dataBinding": "shipNode"
             },
             {
              "name": "Available On hand",
              "id": "availableOnHand",
              "sortKey": "availableOnHand",
              "dataBinding": "reservedQuantity"
             },
             {
                "name": "Reserved Total",
                "id": "totalReservedQty",
                "sortKey": "totalReservedQty",
                "dataBinding": "reservedQuantity"
             }
    Después de reemplazar los encabezados, asegúrate de que el código se vea como el siguiente fragmento.
    Captura de pantalla de buc-table-config.json
  12. Actualiza la sección «Table Headers» (Encabezados de tabla) en el create-reservation-table.component.ts archivo.
    Observe que los ID coinciden con los buc-table-config.json valores de esta tabla.
    /* Table Headers */
      public readonly TABLE_HEADERS: any = {
        TH_NODE_ID: 'nodeId',
        TH_AVLBL_ON_HAND: 'availableOnHand',
        TH_TOTAL_RESRV: 'totalReservedQty'
      };
    
  13. Edita el archivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts con los siguientes cambios.
    1. Para rellenar la tabla con datos, puede utilizar los parámetros de consulta de buc-table-config.json y algunas variables que Order Hub almacena en el contexto.
      Añade InventoryContextService y InventoryAvailabilityService como parámetros del constructor.
      private ctx: InventoryContextService,
      private invAvlSvc: InventoryAvailabilityService,
      private reservationService: CreateReservationService
    2. Añade el ID del inquilino, la declaración de importación y el código:
      1. Añade la siguiente variable a la CreateReservationTableComponent clase. Esta variable se utiliza en la llamada a la API.
        public tenantId;
      2. Añade el siguiente código al método ngOninit() para rellenar el tenantId:
        this.tenantId =
        BucSvcAngularStaticAppInfoFacadeUtil.getInventoryTenantId();
      3. Añade la declaración de importación correspondiente:
        import { BucSvcAngularStaticAppInfoFacadeUtil } from '@buc/svc-angular';
      4. Añada el siguiente código:
        getInventoryAvailabilityBreakup() {
        	const searchCriteria = this.ctx.getSearchCriteria();
        	const item = (this.reservationService.itemData?.itemId) ? [this.reservationService.itemData.itemId] : [''];
        	const nodes = searchCriteria.filterCriteria.nodes;
        	this.parentPage.nodesIds = nodes;
        	const data = [];
        	return this.invAvlSvc.getAvailabilityBreakupInventory(item, nodes,
        		[], [searchCriteria.operators.uom.value],
        		[searchCriteria.operators.pc.value], searchCriteria.filterCriteria,
        		searchCriteria.operators.org.value, false, '').pipe(
        		map((response: InventoryBreakupResponse) => {
        			response.nodes.forEach(el => {
        				const colD = {
        					breakup: {},
        					itemId: '',
        					availableOnHand: '',
        					nodeId: '',
        					totalReservedQuantity: ''
        				};
        				colD.breakup = el.breakup;
        				colD.availableOnHand = response.summary?.availToSell;
        				colD.nodeId = el.nodeId;
        				colD.totalReservedQuantity = el.breakup.totalReservedQuantity;
        				data.push(colD);
        			});
        			return data;
        		}),
        		catchError(() => {
        			this.multiModel.totalDataLength = 0;
        			return [];
        		})
        	);
        }
        getReservation() {
        	return this.reservationService.getReservation(this.tenantId,
        		this.reservationService.reservationRef).pipe(
        		catchError(() => {
        			this.multiModel.totalDataLength = 0;
        			return [];
        		})
        	);
        }
    3. Prepara la tabla para obtener los datos de las API:
      1. Reemplaza el fetchTableData() método por el siguiente código para llamar getReservation a y getInventoryAvailabilityBreakup:
        protected fetchTableData(): Observable < any[] > {
        	const observables = [];
        	observables.push(this.getReservation());
        	observables.push(this.getInventoryAvailabilityBreakup());
        	return forkJoin(observables).pipe(map((res) => {
        		const reservationResp: any = res[0];
        		const nodebrkUp: any = res[1];
        		const rows = reservationResp.map((item: any) => ({
        			shipNode: item.shipNode,
        			reservedQuantity: item.reservedQuantity,
        			totalOnhandSupplyQuantity: nodebrkUp.map((data) => data.nodeId ===
        				item.shipNode ? data.breakup.totalOnhandSupplyQuantity[0] : '')
        		}))
        		return rows;
        	}));
        }
      2. Para mostrar la información en la tabla, debe utilizar la API getAvailabilityBreakupInventory existente y getReservation la API del inventory-shared paquete. Por lo tanto, debe añadir las siguientes declaraciones de importación:
        import { InventoryAvailabilityService, InventoryContextService } from '@buc/inventory-shared';
        import { InventoryBreakupResponse } from '@buc/inventory-shared/lib/services/inventory-availability.service';
        import { CreateReservationService } from "../services/create-reservation.service";
        import { map, catchError } from 'rxjs/operators'; import { forkJoin } from 'rxjs';
    4. Añade un método de controlador para mostrar notificaciones de éxito o error. Order Hub dispone de servicios para mostrar notificaciones.
      1. Añadir el BucNotificationService como parámetro del constructor:
        private bucNotificationService: BucNotificationService
      2. Añadir el showNotification método:
        // notification
        showNotification(statusType, message) {
        	const notification = new BucNotificationModel({
        		statusType,
        		statusContent: message
        	});
        	this.bucNotificationService.send([notification]);
        }
      3. Añade la declaración de importación correspondiente:
        import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
  14. Añadir un pie de página con las opciones Cancelar y Crear.
    1. Abre el archivo src-custom/app/features/create-reservation/create-reservation.component.html.
    2. Reemplaza el código existente <div class="screen-footer"> por el siguiente código.
      <div class="screen-footer">
          <!-- button row -->
        <div class="cds--row">
          <div class="cds--col">
            <buc-button [attr.tid]="'create-rule-cancel'" class="padding-right--1rem" [type]="'secondary'"
                (click)="onCancel()" [btnSize]="'normal'">
                {{ 'custom.LABEL_CANCEL' | translate }}
            </buc-button>
            <buc-button id="saveBtn" [attr.tid]="'create-rule-save'" [type]="'primary'" [btnSize]="'normal'"
                (click)="onSave()">
                {{ 'custom.LABEL_CREATE' | translate }}
            </buc-button>
          </div>
        </div>
      </div>
      
    3. Actualiza el archivo src-custom/assets/custom/i18n/en.json con las cadenas de traducción para las etiquetas Cancelar y Crear.
      "custom": {
      	"LABEL_CREATE_RESERVATION": "Create reservation",
      	"SUCCESS_RESERVATION": "Reservation successful",
      	"ERROR_RESERVATION": "Reservation failed:",
      	"LABEL_CREATE": "Create",
      	"LABEL_CANCEL": "Cancel"
      },
  15. Actualiza el archivo src-custom/app/features/create-reservation/create-reservation.component.ts para gestionar las acciones Cancelar y Crear.
    1. En la clase CreateReservationComponent, declare una nueva variable booleana isCancelled.
        public isCancelled: boolean;
    2. En el método constructor, añade el parámetro Router.
      private router: Router
    3. Añade los siguientes métodos para gestionar las acciones Cancelar y Crear.
      onCancel() {
      	this.isCancelled = true;
      	this.router.navigate([Constants.RESULTS_ROUTE]);
      }
      onSave() {}
    4. Añade las siguientes declaraciones de importación.
      import { ActivatedRoute, Router } from '@angular/router';
      import { Constants } from '@buc/inventory-shared';
      
  16. Cree un servicio para llamar a la API Crear reserva desde Sterling™ Intelligent Promising Inventory Visibility para rellenar los datos de disponibilidad.
    1. Abre el archivo src-custom/app/features/create-reservation/services/create-reservation-service.ts.
      Actualiza el archivo con el siguiente código para llamar a la API « Sterling Intelligent Promising » (Obtener API de reservas): Inventory Visibility Get Reservation API:
      getReservation(tenantId, referenceId = 'REF2'): Observable < any > {
      	if (tenantId === undefined || tenantId === null || tenantId === '') {
      		return throwError(new Error('Missing required parameter: tenantId'));
      	}
      	let path = '/{tenant}/v1/reservations?reference={referenceId}';
      	path = path.replace('{tenant}', tenantId).replace('{referenceId}',
      		referenceId);
      	const url = this.domain + path;
      	const obsToReturn$ = this.http.post(url, this.resourceDomain, null,
      		this.options);
      	return obsToReturn$;
      }
  17. Si está suscrito a Global Inventory Visibility, abra el archivo src-custom/app/features/create-reservation/create-reservation.component.ts y añada el siguiente código.
    • Añade un método de controlador para mostrar notificaciones de éxito o error. Order Hub dispone de servicios para mostrar notificaciones.
      • Añadir el BucNotificationService como parámetro del constructor.
            private bucNotificationService: BucNotificationService
      • Añade el método showNotification.
        // notification
          showNotification(statusType, message) {
              const notification = new BucNotificationModel({ statusType, statusContent: message });
              this.bucNotificationService.send([notification]);
          }
        
      • Añade la declaración de importación correspondiente.
        import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
    • Modifique el método « onSave( » según sea necesario.
      async onSave() {
          // Call GIV API here
              try {
            alert('Call GIV API here');
            this.showNotification('success', this.nlsMap['custom.SUCCESS_RESERVATION']);
            this.router.navigate([Constants.RESULTS_ROUTE]);
          } catch (error) {
            this.showNotification('error', this.nlsMap['custom.ERROR_RESERVATION'] + ' ' + error.error_message);
          }
        }
      

Qué hacer a continuación

Implemente su personalización. Para obtener más información, consulte Preparación para implementar personalizaciones en aplicaciones existentes.