Atualizando a configuração e dados da tabela

Aprenda como atualizar a configuração e os dados da tabela após o formulário ter sido enviado Nesta lição, você assegura que o formulário funcione corretamente e se prepara para preencher dados de APIs REST.

Procedimento

  1. Envie o formulário:
    1. acesse a página Criar reserva e insira e envie uma reserva. Por exemplo:
      Criar reserva
    2. Depois de enviar o formulário, você deverá ver a seguinte mensagem:
      Enviar
  2. Em um terminal, vá para o diretório src-custom/app/features/create-reservation .
  3. Execute o comando a seguir para gerar uma tabela para os usuários visualizarem e atualizarem os valores de reserva.
    Esse comando usa os scripts de geração de códigos da IBM que estão incluídos no kit de ferramentas do desenvolvedor
    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 <nome da tabela>,
    • --path <caminho para onde você deseja criar a tabela>
    • --json-file-path <caminho parabuc-table-config.json onde a configuração da tabela será adicionada>
    • --translation-file-path <caminho para o arquivo JSON de tradução personalizada>
    • --extend <nome da classe de tabela extensível>
    Para obter ajuda com o script esquemático, execute
    ng g @buc/schematics:table-component --help
  4. Depois de executar o script, novos arquivos serão criados no local especificado e o arquivoext-search-module.ts arquivo é atualizado com um novo componente, CreateReservationTableComponent.
  5. Como o componente customizado gerado (CreateReservationTableComponent) precisa usar utilitários e bibliotecas da IBM , mova o componente para o arquivo app-customization.impl.ts concluindo as etapas a seguir.
    1. Editar o arquivo src-custom/app/features/ext-search.module.ts com as mudanças a seguir.
      • Exclua a instrução import {CreateReservationTableComponent} .
      • Excluir CreateReservationTableComponent dedeclarations variedade.
      O código resultante é semelhante a este:
      import { NgModule } from '@angular/core';
      import { CommonModule } from '@angular/common';
      
      @NgModule({
        declarations: [
        ],
        imports: [
          CommonModule
        ]
      })
      export class ExtSearchModule { }
    2. Atualize o arquivo src-custom/app/app-customization.impl.ts com as mudanças a seguir.
      • Inclua a seguinte instrução de importação.
        import { CreateReservationTableComponent } from './features/create-reservation/create-reservation-table/create-reservation-table.component';
      • Adicionar CreateReservationTableComponent para a matriz de componentes.
        static readonly components = [CreateReservationComponent, CreateReservationTableComponent];
        
      Depois que o módulo for compilado com êxito, uma nova entrada create-reservation-table será incluída no arquivo src-custom/assets/custom/buc-table-config.json
  6. Abra o arquivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts e localize o valor selector .
    Nesse caso, o valor é buc-create-reservation-table. Deve-se usar esse valor no HTML para exibir a tabela.
  7. Inclua o seguinte código no arquivo src-custom/app/features/create-reservation/create-reservation.component.html após o comentário <! -Reservation table -->.
    <buc-create-reservation-table [parentPage]="this"></buc-create-reservation-table>
  8. Volte para Order Hub e recarregue o quadro.
    Acesse a página Criar Reserva para verificar se a tabela é exibida
    Captura de tela da página Criar reserva com uma caixa de entrada e uma tabela
  9. Observe que o cabeçalho inclui uma caixa de seleção.. Para remover a caixa de seleção, conclua as seguintes etapas.
    1. Abra o arquivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.html .
    2. Inclua o código a seguir no final do elemento <buc-table> .
      [showSelectionColumn]="false"
      Captura de tela do create-reservation-table-component.html com o showSelectionColumn propriedade
  10. Abra o arquivo packages/inventory-search-results/src-custom/assets/custom/buc-table-config.json .
  11. Substitua a matriz cabeçalhos do criar-reserva-tabelapelo código a seguir para atualizar as sequências de cabeçalhos da tabela
            {
                "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"
             }
    Após substituir os cabeçalhos, assegure-se de que o código seja semelhante ao fragmento a seguir.
    Captura de tela do buc-table-config.json
  12. Atualize a seção Cabeçalhos da tabela no arquivo create-reservation-table.component.ts .
    Observe que os IDs correspondem aos valores buc-table-config.json para essa tabela.
    /* Table Headers */
      public readonly TABLE_HEADERS: any = {
        TH_NODE_ID: 'nodeId',
        TH_AVLBL_ON_HAND: 'availableOnHand',
        TH_TOTAL_RESRV: 'totalReservedQty'
      };
    
  13. Edite o arquivo src-custom/app/features/create-reservation/create-reservation-table/create-reservation-table.component.ts com as seguintes mudanças.
    1. Para preencher a tabela com dados, é possível usar os parâmetros de consulta do buc-table-config.json e algumas variáveis que o Order Hub armazena no contexto.
      Adicione o InventoryContextService e InventoryAvailabilityService como parâmetros do construtor.
      private ctx: InventoryContextService,
      private invAvlSvc: InventoryAvailabilityService,
      private reservationService: CreateReservationService
    2. Inclua o ID do locatário, a declaração de importação e o código:
      1. Inclua a seguinte variável na classe CreateReservationTableComponent . Essa variável é usada na chamada de API.
        public tenantId;
      2. Adicione o seguinte código aongOninit() método para preencher o tenantId:
        this.tenantId =
        BucSvcAngularStaticAppInfoFacadeUtil.getInventoryTenantId();
      3. Inclua a instrução de importação correspondente:
        import { BucSvcAngularStaticAppInfoFacadeUtil } from '@buc/svc-angular';
      4. Inclua o código a seguir:
        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. Prepare a tabela para obter os dados de APIs:
      1. Substitua o método fetchTableData() pelo seguinte código para chamar getReservation e 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 exibir informações na tabela, é necessário usar a API getAvailabilityBreakupInventory e a API getReservation existentes do pacote inventory-shared . Portanto, é necessário incluir as instruções de importação a seguir:
        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. Inclua um método manipulador para mostrar notificações de sucesso ou erro. O Order Hub tem serviços para mostrar notificações.
      1. Inclua o parâmetro BucNotificationService como construtor:
        private bucNotificationService: BucNotificationService
      2. Inclua o método showNotification :
        // notification
        showNotification(statusType, message) {
        	const notification = new BucNotificationModel({
        		statusType,
        		statusContent: message
        	});
        	this.bucNotificationService.send([notification]);
        }
      3. Inclua a instrução de importação correspondente:
        import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
  14. Inclua um rodapé com opções Cancelar e Criar .
    1. Abra o arquivo src-custom/app/features/create-reservation/create-reservation.component.html ..
    2. Substitua o <div class="screen-footer"> existente pelo código a seguir:
      <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. Atualize o arquivo src-custom/assets/custom/i18n/en.json com sequências de tradução para os rótulos Cancelar e Criar.
      "custom": {
      	"LABEL_CREATE_RESERVATION": "Create reservation",
      	"SUCCESS_RESERVATION": "Reservation successful",
      	"ERROR_RESERVATION": "Reservation failed:",
      	"LABEL_CREATE": "Create",
      	"LABEL_CANCEL": "Cancel"
      },
  15. Atualize o arquivo src-custom/app/features/create-reservation/create-reservation.component.ts para manipular as ações Cancelar e Criar .
    1. Em classe CreateReservationComponent, declare uma nova variável booleana isCancelled.
        public isCancelled: boolean;
    2. No método construtor , inclua o parâmetro Router.
      private router: Router
    3. Inclua os métodos a seguir para manipular as ações Cancelar e Criar .
      onCancel() {
      	this.isCancelled = true;
      	this.router.navigate([Constants.RESULTS_ROUTE]);
      }
      onSave() {}
    4. Inclua as instruções de importação a seguir:
      import { ActivatedRoute, Router } from '@angular/router';
      import { Constants } from '@buc/inventory-shared';
      
  16. Crie um serviço para chamar a API Criar reserva do Sterling™ Intelligent Promising Inventory Visibility para preencher os dados de disponibilidade.
    1. Abra o arquivo src-custom/app/features/create-reservation/services/create-reservation-service.ts ..
      Atualize o arquivo com o código a seguir para chamar a API de obtenção de reserva do Sterling Intelligent Promising Inventory Visibility :
      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. Se você estiver inscrito em Global Inventory Visibility, abra o arquivo src-custom/app/features/create-reservation/create-reservation.component.ts e inclua o código a seguir.
    • Inclua um método manipulador para mostrar notificações de sucesso ou erro. O Order Hub tem serviços para mostrar notificações
      • Adicione o BucNotificationService como parâmetro do construtor.
            private bucNotificationService: BucNotificationService
      • Inclua o método showNotification ..
        // notification
          showNotification(statusType, message) {
              const notification = new BucNotificationModel({ statusType, statusContent: message });
              this.bucNotificationService.send([notification]);
          }
        
      • Inclua a instrução de importação correspondente.
        import { BucNotificationModel, BucNotificationService} from '@buc/common-components';
    • Modifique o onSave() método conforme necessário.
      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);
          }
        }