Creación de la sección "Añadir nota" en el modal Planificar

Aprenda a añadir series de traducción personalizadas para el texto de la interfaz de usuario y cree la sección "Añadir nota" en el modal Planificar.

Procedimiento

  1. Configurar series de conversión y configuraciones de entorno.
    1. Cree una carpeta activos en devtoolkit_docker/orderhub-code/buc-app-order/packages/order-search-result/src-custom.
    2. Copie los activos del módulo order-shared en la carpeta de activos que ha creado.
      Mostrar la estructura de carpetas después de copiar la carpeta de activos
    3. Abra el archivo devtoolkit_docker/orderhub-code/buc-app-order/angular.json .
    4. Sustituya el contenido actual de los proyectos > order-search-result > arquitecto > build > configuraciones > fusionado > activos matriz con las entradas siguientes. La finalidad de este paso es indicar al módulo que utilice los archivos de elementos personalizados en lugar de los archivos de /order-shared.
                      {
                        "glob": "**",
                        "input": "packages/order-search-result/src-merged/assets",
                        "output": "assets"
                      },  
                      {
                        "glob": "*.json",
                        "input": "packages/order-search-result/src-merged/assets/buc-app-order",
                        "output": "assets/order-search-result"
                      },
                      {
                        "glob": "**",
                        "input": "node_modules/@buc/svc-angular/assets",
                        "output": "assets"
                      },
                      {
                        "glob": "**",
                        "input": "node_modules/@buc/common-components/assets",
                        "output": "assets"
                      }
      
    5. Sustituya también el contenido de la matriz projects > order-search-result > Architect > build > configuraciones > fusionada-prod > activos .
    6. Copie la carpeta environments de 'buc-app-order/packages/order-search-result/src' en 'buc-app-order/packages/order-search-result/src-custom'.
    7. Vaya al directorio buc-app-order/packages/order-search-result/src-custom/environments .
    8. Añada la línea siguiente al final de los archivos environment.ts y envrionment.prod.ts .
      environment.customization = true;
    9. Detenga y reinicie el servidor para que los cambios en los archivos angular.json y overrides.json entren en vigor.
      Detenga el trabajo en el terminal. A continuación, ejecute:
      yarn stop-app
      yarn start-app
    10. Cree una carpeta personalizada bajo 'buc-app-order/packages/order-search-result/src-custom/assets'.
    11. Cree una carpeta i18n bajo 'buc-app-order/packages/order-search-result/src-custom/assets/custom'.
    12. Cree un archivo en.json bajo 'buc-app-order/packages/order-search-result/src-custom/assets/custom/i18n.
      El archivo en.json incluye las series literales en inglés que se van a visualizar en la interfaz de usuario. Puede añadir series traducidas creando otros archivos JSON. Asigne un nombre a los archivos basándose en los códigos de idioma ISO-639 . Por ejemplo, fr.json para series en francés.
    13. Pegar el siguiente contenido JSON.
      {
          "CUSTOM_ORDER_SEARCH_RESULT": {
              "NOTE": {
                  "LABEL_ADD_NOTE": "Add Note",
                  "LABEL_DATE": "Date",
                  "LABEL_FIELD_REQUIRED": "Required.",
                  "LABEL_USER": "User",
                  "LABEL_NOTE": "Note",
                  "LABEL_REASON_OPTIONAL": "Reason (optional)",
                  "LABEL_CONTACT_TYPE_OPTIONAL": "Contact type (optional)",
                  "LABEL_CONTACT_REFERENCE_OPTIONAL": "Contact reference (optional)",
                  "MSG_SUCCESS_ADD_NOTES": "Notes added successfully.",
                  "MSG_ERROR_ADD_NOTES": "Notes was not added. Try again later."
              }
          }
      }
      
  2. Cree una carpeta personalizada en buc-app-order/packages/order-search-result/src-custom/app'.
  3. Cree una carpeta data-services bajo 'buc-app-order/packages/order-search-result/src-custom/app/custom'.
  4. Cree un archivo de servicio add-notes-data.service.ts bajo la carpeta data-services y pegue el siguiente fragmento de código. Este servicio llama al 'modifyFulfillmentOptions' API de OMS para guardar la nota.
    import { Injectable } from '@angular/core';
    import { BucCommOmsRestAPIService } from '@buc/svc-angular';
    
    @Injectable({
        providedIn: 'root'
    })
    export class AddNotesDataService {
        constructor(private bucCommOmsRestAPIService: BucCommOmsRestAPIService) {
        }
    
        // Below method fetches the list of reason codes to display in 'Reason' dropdown
        getCommonCodeListForReasonCode(enterpriseCode: string, docType: string) {
            const Input = {
                CallingOrganizationCode: enterpriseCode,
                CodeType: 'NOTES_REASON',
                DocumentType: docType,
            };
            return this.bucCommOmsRestAPIService.invokeOMSRESTApi('getCommonCodeList', Input, {});
        }
    
        // Below method fetches the list of contact types to display in 'Contact type' dropdown
        getCommonCodeListForContactType(enterpriseCode: string) {
            const Input = {
                CallingOrganizationCode: enterpriseCode,
                CodeType: 'CONTACT_TYPE'
            };
            return this.bucCommOmsRestAPIService.invokeOMSRESTApi('getCommonCodeList', Input, {});
        }
    
        // Below method saves the notes data by calling modifyFulfillmentOptions OMS API
        changeOrder(order: any) {
            return this.bucCommOmsRestAPIService.invokeOMSRESTApi('modifyFulfillmentOptions', order, {});
        }
    }
    
  5. Cree un componente add-notes nuevo y su estructura de archivos y, a continuación, realice los cambios en el archivo.
    Para ello, cree primero la siguiente estructura de archivos:
    1. Cree un directorio denominado add-notes en src-custom/app/custom.
    2. Cree los archivos siguientes en el directorio add-notes : add-notes.component.html, add-notes.component.scssy add-notes.component.ts.

    A continuación, realice los siguientes cambios en el archivo:

    1. add-notes.component.html
      
      <div class="cds--row">
          <div class="cds--col-lg-16">
              <buc-checkbox [checked]="isAddNoteChecked"
                  [attr.tid]="componentId + '-add-note'"
                  (change)="onIsAddNoteCheckedChange($event)">
                  {{'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_ADD_NOTE' | translate}}
              </buc-checkbox>
          </div>
      </div>
      
      <div class="screen notes-section bx--modal-content" *ngIf="isScreenInitialized && isAddNoteChecked">
          <p class="title">
              {{ 'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_ADD_NOTE' | translate }}
          </p>
          <div class="cds--row status">
              <div class="combo-box cds--col-md-4">
                  <div class="d--flex-ai-flex-end">
                      <buc-date-picker label="{{'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_DATE' | translate}}"
                          [placeholder]="i18nDatePlaceholder" [dateFormat]="flatpickrDateFormat" [language]="curLocale"
                          [value]="contactDate" (valueChange)="onDateChange($event)">
                      </buc-date-picker>
                      <div class="oms-spacer8"></div>
                      <buc-time-picker [disabled]="false" [theme]="'light'" [time]="contactTime?.time"
                          [period]="contactTime?.period" (valueChange)="timeChange($event)">
                      </buc-time-picker>
                  </div>
                  <div *ngIf="savePressed && isDateValid" class="d--flex buc-warning cds--form-requirement">
                      {{'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_FIELD_REQUIRED' | translate}}
                  </div>
              </div>
              <div class="cds--col-md-4">
                  <buc-label class="size--sm" [theme]="'light'" [label]="'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_USER' | translate"
                      placeholder="" [(inputValue)]="currentUserId" (inputValueChange)="onText($event, 'conUser')">
                  </buc-label>
                  <div *ngIf="savePressed && !currentUserId" class="d--flex buc-warning cds--form-requirement">
                      {{'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_FIELD_REQUIRED' | translate}}
                  </div>
              </div>
          </div>
      
          <div class="cds--row">
              <div class="combo-box cds--col-md-4">
                  <p class="cds--label">{{'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_NOTE' | translate}}</p>
              </div>
              <div class="combo-box cds--col-md-4">
                  <p class="pull-right">{{ notesText.length }}/{{ 2000 }}</p>
              </div>
          </div>
          <div class="combo-box cds--col-md-12 status">
              <textarea [(ngModel)]="notesText" (inputValueChange)="onText($event, 'notesTxt')" ibmTextArea
                  [attr.tid]="componentId + ''" [rows]=2 class="cds--text-area" aria-label="textarea" maxlength="2000">
                                              </textarea>
              <div *ngIf="savePressed && !notesText" class="d--flex buc-warning cds--form-requirement">
                  {{'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_FIELD_REQUIRED' | translate}}
              </div>
          </div>
      
          <div class="cds--row status">
              <div class="combo-box cds--col-md-4">
                  <buc-dropdown placeholder="" [cozy]="true" [theme]="'dark'" [disabled]="false"
                      [label]="'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_REASON_OPTIONAL' | translate" [items]="reasonCodeList"
                      (selected)="reasonCodeOnSelection($event)">
                  </buc-dropdown>
              </div>
              <div class="combo-box cds--col-md-4">
                  <buc-dropdown placeholder="" [cozy]="true" [theme]="'dark'" [disabled]="false"
                      [label]="'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_CONTACT_TYPE_OPTIONAL' | translate" [items]="contactTypeList"
                      (selected)="contactTypeOnSelection($event)">
                  </buc-dropdown>
              </div>
          </div>
          <div class="cds--row status">
              <div class="combo-box cds--col-md-4">
                  <buc-label class="size--sm" [theme]="'light'"
                      [label]="'CUSTOM_ORDER_SEARCH_RESULT.NOTE.LABEL_CONTACT_REFERENCE_OPTIONAL' | translate" placeholder=""
                      [(inputValue)]="contactRef" (inputValueChange)="onText($event, 'conRef')">
                  </buc-label>
              </div>
          </div>
      </div>
      
    2. add-notes.component.scss:
      
      .bx--modal-content {
          padding-right: 1rem;
      }
      
      .notes-section {
          border-top: 1px solid grey;
          padding-top: 1rem;
          margin-top: 1rem;
      }
      
      .bx--modal-content {
          padding: 1rem 1rem 0 1rem;
      
          .title,
          .subtitle,
          .type-switch,
          form,
          .delivery-type,
          .status,
          .alert-severity,
          .exclusion {
              margin-bottom: 24px;
          }
      
          .status:last-child {
              margin-bottom: 0;
          }
      
          .within-text,
          .within-text-only {
              display: flex;
              align-items: center;
          }
      }
      
      .pull-right {
          text-align: right;
          font-size: 0.75rem;
      }
      
      .oms-spacer8 {
          padding-top: 0.5rem;
          padding-left: 0.1rem;
          background-repeat: no-repeat;
      }
      
      buc-time-picker {
          ::ng-deep ibm-timepicker .bx--time-picker {
              ibm-timepicker-select.bx--time-picker__select {
                  height: 2rem;
                  background-color: white;
              }
          }
      }
      
      ::ng-deep .bx--time-picker__input {
          height: 2rem;
      }
      
    3. add-notes.component.ts:
      
      import { CommonService, Constants, DocTypes, handleOMSErrors, OrderListDataService } from '@buc/order-shared';
      import { BucNotificationService, getCurrentLocale, getCurrentLocaleDateFormat, getFlatPickrDateFormat } from '@buc/common-components';
      import { BucSvcAngularStaticAppInfoFacadeUtil } from '@buc/svc-angular';
      import moment from 'moment';
      import * as momentTime from 'moment-timezone';
      import flatpickr from 'flatpickr';
      import { AddNotesDataService } from '../data-services/add-notes-data.service';
      import { Component, EventEmitter, Inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChange } from '@angular/core';
      import { TranslateService } from '@ngx-translate/core';
      import { ModalService } from 'carbon-components-angular';
      import { SimpleChanges } from '@angular/core';
      
      @Component({
          selector: 'buc-add-notes',
          templateUrl: './add-notes.component.html',
          styleUrls: ['./add-notes.component.scss']
      })
      
      export class AddNotesComponent implements OnInit, OnChanges {
      
          nlsMap = {
              'CUSTOM_ORDER_SEARCH_RESULT.NOTE.MSG_SUCCESS_ADD_NOTES': '',
              'CUSTOM_ORDER_SEARCH_RESULT.NOTE.MSG_ERROR_ADD_NOTES': '',
          }
          bucNotificationService: BucNotificationService;
          @Input() scheduleOrderClicked: boolean;
          @Input() componentId: boolean;
          @Input() modalData: any;
          @Output() cancel: EventEmitter<any> = new EventEmitter();
          @Output() onAddNoteCheckedChange: EventEmitter<any> = new EventEmitter();
      
          constructor(
              protected modalService: ModalService,
              public orderListDataService: OrderListDataService,
              public translate: TranslateService,
              public commonSvc: CommonService,
              public notesDataService: AddNotesDataService
          ) {
              this.bucNotificationService = new BucNotificationService();
          }
      
          isAddNoteChecked = false;
          isScreenInitialized = false;
          displayData: any;
          reasonCodeList = [];
          contactTypeList = [];
          curLocale: string;
          public i18nDatePlaceholder;
          public flatpickrDateFormat;
      
          reasonCodeValue: any;
          contactTypeValue: any;
          getReasonValue: any;
          getContactValue: any;
          contactRef = '';
          notesText = '';
          contactDateTime;
          contactDate;
          contactTime;
          invalidDate = false;
          currentUserId;
          savePressed = false;
          isDateValid = false;
      
          // To gather all the data required for notes section on opening the modal like dropdown list data, date picker placeholder 
          async initializeNotesSection() {
              this.savePressed = false;
              this.currentUserId = BucSvcAngularStaticAppInfoFacadeUtil.getOmsUserLoginId();
              await this._initTranslations();
              await this.getReasonCodeList();
              await this.getContactTypeList();
              this.isScreenInitialized = true;
              this.setDate();
              this.curLocale = getCurrentLocale();
              if (this.curLocale.startsWith('zh-')) {
                  this.curLocale = 'zh';
              }
              this.i18nDatePlaceholder = getCurrentLocaleDateFormat();
              this.flatpickrDateFormat = getFlatPickrDateFormat();
          }
      
          // To get the list of reason codes to display in 'Reason' dropdown
          async getReasonCodeList() {
              const enterpriseCode = this.displayData.enterpriseCode;
              const documentType = this.displayData.docType;
              const commonCodeList = await this.notesDataService.getCommonCodeListForReasonCode(enterpriseCode, documentType).toPromise();
              if (commonCodeList.CommonCode) {
                  commonCodeList.CommonCode.forEach(element => {
                      this.reasonCodeList.push({
                          content: element.CodeShortDescription ? element.CodeShortDescription :
                              element.CodeValue, value: element.CodeValue
                      });
                  });
              }
          }
      
          // To get the list of contact types to display in 'Contact type' dropdown
          async getContactTypeList() {
              const enterpriseCode = this.displayData.enterpriseCode;
              const commonCodeList = await this.notesDataService.getCommonCodeListForContactType(enterpriseCode).toPromise();
              if (commonCodeList.CommonCode) {
                  commonCodeList.CommonCode.forEach(element => {
                      this.contactTypeList.push({
                          content: element.CodeShortDescription ? element.CodeShortDescription :
                              element.CodeValue, value: element.CodeValue
                      });
                  });
              }
          }
      
          onIsAddNoteCheckedChange(event) {
              this.isAddNoteChecked = event.checked;
              this.onAddNoteCheckedChange.emit();
          }
      
          async addNotes() {
              this.savePressed = true;
              this.orderAddNotes();
          }
      
          // To save the notes on click of 'Schedule' button
          async orderAddNotes() {
              const convertTimestamp = new Date(this.contactDateTime);
              if (this.notesText.length > 0 && this.currentUserId.length > 0 && !this.invalidDate && this.isDateValid === false) {
                  this.reasonCodeValue = this.getReasonValue ? this.reasonCodeList.find(r => r.value === this.getReasonValue).value : '';
                  this.contactTypeValue = this.getContactValue ? this.contactTypeList.find(c => c.value === this.getContactValue).value : '';
      
                  Promise.all(this.modalData.orders.map(async (element) => {
                      const body: any = {
                          OrderHeaderKey: element.OrderHeaderKey,
                          Notes: {
                              Note: [
                                  {
                                      ContactReference: this.contactRef,
                                      ContactTime: convertTimestamp,
                                      ContactType: this.contactTypeValue,
                                      ContactUser: this.currentUserId,
                                      NoteText: this.notesText,
                                      ReasonCode: this.reasonCodeValue
                                  }
                              ]
                          }
                      };
                      if (this.displayData.hasOwnProperty('recordChanges') &&
                          this.displayData.recordChanges === false) {
                          await this.notesDataService.changeOrder(body).toPromise();
                      } else {
                          if (this.displayData.docType === DocTypes.SalesOrder) {
                              const pendingChanges = { PendingChanges: { RecordPendingChanges: 'N' } };
                              Object.assign(body, pendingChanges);
                          }
                          await this.notesDataService.changeOrder(body).toPromise();
                      }
                  })).then(() => {
                      if (this.displayData.showSuccessMsg) {
                          CommonService.notify('success', this.nlsMap['CUSTOM_ORDER_SEARCH_RESULT.NOTE.MSG_SUCCESS_ADD_NOTES']);
                      }
                      this.onCancel();
                  }).catch(async (err) => {
                      const errorMsg = this.nlsMap['CUSTOM_ORDER_SEARCH_RESULT.NOTE.MSG_ERROR_ADD_NOTES'];
                      await handleOMSErrors(err, this.translate, this.bucNotificationService, errorMsg);
                      this.onCancel();
                  });
              }
          }
      
          // To set the date and time picker to current date and time
          setDate() {
              const currentDate = new Date();
              this.contactDateTime = moment(currentDate).format(Constants.DATETIME_FORMAT);
              this.contactDate = flatpickr.formatDate(moment(currentDate).toDate(), 'Z');
              this.contactTime = {
                  time: momentTime(currentDate).format(Constants.TIME_FORMAT),
                  period: momentTime(currentDate).format(Constants.TIME_PERIOD)
              };
          }
      
          // Event that triggers when user changes the date
          onDateChange(event) {
              this.isDateValid = event.length === 0;
              if (event.length) {
                  const newDate = moment(event[0]).format(Constants.DATE_FORMAT);
                  this.contactDateTime = this.contactDateTime.replace(this.contactDateTime.split(' ')[0], newDate);
                  this.contactDate = flatpickr.formatDate(moment(this.contactDateTime).toDate(), 'Z');
              }
          }
      
          // Event that triggers when user changes the time
          timeChange(event) {
              const dateTime = this.contactDateTime.split(' ');
      
              if (this.contactTime.time && event.time) {
                  let invalidTime = false;
                  const tm = event.time.split(':');
                  let hours = Number(tm[0]);
                  const minutes = (tm[1] && Number(tm[1])) || 0;
                  if (this.contactTime.period === 'PM') {
                      if (hours > 12 && hours <= 24) {
                          hours = hours - 12;
                      } else if (hours > 24) {
                          invalidTime = true;
                      }
                  }
                  if (minutes && minutes > 59) {
                      invalidTime = true;
                  }
                  if (!invalidTime) {
                      const h = hours < 10 ? `0${hours}` : `${hours}`;
                      const m = minutes < 10 ? `0${minutes}` : `${minutes}`;
                      dateTime[1] = `${h}:${m}`;
                  }
              } else if (this.contactTime.period && event.timePeriod) {
                  dateTime[2] = event.timePeriod;
              }
      
              const tempDate = new Date(dateTime.join(' '));
              if (tempDate.toString() === 'Invalid Date') {
                  this.invalidDate = true;
              } else {
                  this.invalidDate = false;
                  this.contactDateTime = dateTime.join(' ');
                  this.contactTime = {
                      time: momentTime(tempDate).format(Constants.TIME_FORMAT),
                      period: momentTime(tempDate).format(Constants.TIME_PERIOD)
                  };
              }
          }
      
          async reasonCodeOnSelection(event) {
              this.getReasonValue = event.item.value;
          }
          async contactTypeOnSelection(event) {
              this.getContactValue = event.item.value;
          }
      
          // Event that gets trigger on clicking cancel button
          onCancel() {
              if (this.displayData.parentPage) {
                  this.displayData.parentPage.disableAdd = false;
              }
            this.cancel.emit();
          }
      
          async ngOnInit() {
              await this._initTranslations();
              this.initializeNotesSection();
          }
      
          async ngOnChanges(changes: SimpleChanges) {
              if(changes.scheduleOrderClicked?.currentValue) {
                  if (this.isAddNoteChecked) {
                      await this.addNotes();
                  }
              }
              if (changes.modalData?.currentValue && changes.modalData.currentValue !== changes.modalData.previousValue  && Object.keys(changes.modalData.currentValue).length > 0) {
                  this.displayData = {
                      docType: this.modalData.orders[0].DocumentType,
                      enterpriseCode: this.modalData.orders[0].enterpriseCode,
                      OrderHeaderKey: this.modalData.orders[0].OrderHeaderKey,
                      showSuccessMsg: true
                  };
              }
      
          }
      
          protected async _initTranslations() {
              const keys = Object.keys(this.nlsMap);
              const json = await this.translate.get(keys).toPromise();
              keys.forEach(k => this.nlsMap[k] = json[k]);
          }
      
      }
      
  6. Añadir un servicio de extensión: buc-app-order/packages/order-search-result/src-custom/app/custom/data-services/add-notes-extension.service.ts
    
    import { Injectable } from '@angular/core';
    import { ExtensionService } from '@buc/common-components';
    
    @Injectable()
    
    export class AddNotesExtensionService extends ExtensionService {
    
        userInputs = {
            scheduleOrderClicked: false,
            componentId: '',
            modalData: {}
        };
        originalScheduleOrderFunc;
    
        constructor() {
            super();
        }
    
        createInput() {
            if (!this.parentContext.scheduleOrder) {
                this.userInputs.scheduleOrderClicked = false;
                this.originalScheduleOrderFunc = null;
            }
            if (this.parentContext.componentId !== this.userInputs.componentId) {
                this.userInputs.componentId = this.parentContext.componentId;
    
            }
            if (this.parentContext.modalData !== this.userInputs.modalData) {
                this.userInputs.modalData = this.parentContext.modalData;
            }
            this.userInputObs$.next(this.userInputs);
            this.overrideMethods();
        }
    
        handleOutput() {
            this.userOutputs = {
                cancel: this.onCancel.bind(this),
                onAddNoteCheckedChange: this.onAddNoteCheckedChange.bind(this)
            };
            this.userOutputObs$.next(this.userOutputs);
        }
    
        overrideMethods() {
            if (!this.originalScheduleOrderFunc && this.parentContext.scheduleOrder) {
                this.originalScheduleOrderFunc = this.parentContext.scheduleOrder.bind(this.parentContext);
                this.parentContext.scheduleOrder = (event) => {
                    this.userInputs.scheduleOrderClicked = true;
                    this.userInputObs$.next(this.userInputs);
                    this.originalScheduleOrderFunc(event);
                }
            }
    
        }
    
        onAddNoteCheckedChange() {
            this.userInputs.modalData = this.userInputs.modalData;
            this.userInputObs$.next(this.userInputs);
        }
    
        onCancel() {
    
            this.parentContext.closeModal();
        }
    
    }
    
  7. Registre el nuevo componente y el servicio de extensión en /packages/order-search-result/src-custom/app/app-customization.impl.ts:
    
    import { ExtensionModule } from "@buc/common-components";
    import { SharedExtensionConstants } from "@buc/order-shared";
    import { AddNotesComponent } from "./custom/add-notes/add-notes.component";
    import { AddNotesExtensionService } from "./custom/data-services/add-notes-extension.service";
    
    export class AppCustomizationImpl {
        static readonly components = [AddNotesComponent];
    
        static readonly providers = [];
    
        static readonly imports = [
            ExtensionModule.forRoot([
                {
                    id: SharedExtensionConstants.SCHEDULE_MODAL_SHARED_BOTTOM,
                    component: AddNotesComponent,
                    service: AddNotesExtensionService
                }
            ]),
        ];
    
    }
    
  8. Cree una carpeta features bajo 'buc-app-order/packages/order-search-result/src-custom/app'.
  9. En la carpeta features , cree un archivo ext-order.module.ts (buc-app-order/packages/order-search-result/src-custom/app/features/ext-order.module.ts) y, a continuación, pegue el contenido siguiente.
    
    import { NgModule } from "@angular/core";
    import { CommonModule } from "@angular/common";
    import { TranslateModule } from "@ngx-translate/core";
    import { AddNotesDataService } from "../custom/data-services/add-notes-data.service";
    @NgModule({
      declarations: [],
      imports: [CommonModule, TranslateModule],
      providers: [AddNotesDataService],
      exports: [],
    })
    export class ExtOrderModule {}
    
    Observe el objeto de proveedor en el código con la señal CUSTOM_ACTIONS. Order Hub proporciona dos señales de inyección. 'CUSTOM_ACTIONS' y 'CUSTOM_FEATURE_ACTIONS' para alterar temporalmente las acciones existentes o para proporcionar acciones personalizadas.

    El valor de la señal de inyección es una matriz donde cada elemento es un objeto que contiene dos propiedades:

    • name-El nombre de la acción.
    • action-El servicio que maneja o implementa la acción. En este tutorial, ScheduleActionService es una acción predeterminada que debe anular, por lo que también debe agregar laScheduleActionService en la misma matriz de proveedores.

    El punto de inyección debe definirse en el módulo ext-NNN.module.ts porque garantiza que el TranslateService que se inyecta en la acción tenga todos los paquetes cargados por el módulo de característica. Cada módulo de cada aplicación de ruta tiene este módulo en /src/app/features/ext-NNN.module.ts. Este archivo no existe en la carpeta src-custom , por lo tanto, debe crear el archivo.

    Nota: La implementación de la acción se separa por componente, de modo que la personalización de la acción existente se limita al archivo de servicio en lugar de modificar cada componente que asigna la acción. Al realizar estos cambios, la aplicación buc-app-order utiliza el servicio recién añadido siempre que se asigna la acción Planificar .
  10. Renueve la interfaz de usuario de Order Hub y pase por un flujo de planificación para ver los cambios en el modal de orden de planificación.
    1. Inicie sesión en Order Hub.
    2. Vaya a Pedidos > Salida (modalidad DEV).
    3. Buscar un pedido.
    4. En la tabla de resultados de búsqueda de pedidos, pulse el recuadro de selección situado junto a un pedido y, a continuación, pulse Planificar.
    5. Pulse Añadir nota para exponer campos en los que puede añadir información.
    6. Añada texto a la sección "Notas" y modifique otras propiedades según sea necesario.
    7. Haga clic en Planificar.
      Aparece un mensaje para confirmar que la nota se ha añadido correctamente y que el pedido se ha planificado.
    8. Pulse el número de pedido que ha planificado para ir a la página Detalles del pedido .
    9. Pulse la pestaña Notas . Asegúrese de que la tabla de notas incluye la nota que ha añadido.
      Captura de pantalla de la pestaña Notas. El separador muestra la entrada de nota que ha especificado el usuario.

Resultados

Ha personalizado correctamente el modal Planificar orden para incluir una sección "Añadir notas".

Complete la siguiente lección para aprender a desplegar las personalizaciones en los entornos para que otros usuarios puedan utilizar las personalizaciones. Hasta ahora, las personalizaciones sólo están disponibles localmente.