How to create a search by Purchase Number search box to search for all the purchases that the customer has made.

Description:

We can use this solution to create a Search by Purchase Number search box to sort the purchase order history based on the user-entered criteria.

JavaScript:

_.extend(OrderHistoryListView.prototype, {
          template: jj_order_history_list_tpl,
          //initilize function is extended to get the purchase history details from the SuiteScript.
          initialize: _.wrap(OrderHistoryListView.prototype.initialize, function (fn) {
            try {
              fn.apply(this, _.toArray(arguments).slice(1));
              let self = this;
              let collectionModel = new OrderHistoryCollection;
              collectionModel.fetch({ data: { page: 'all' } }).then(res => {
                self.searchCollection = res;
              })
            } catch (error) {
              console.error('Error @ initilize fn', error);
            }
          }),
          events: _.extend(OrderHistoryListView.prototype.events, {
            'change [data-action="searchByPO"]': 'searchPONumber',
            'keyup [data-action="searchByPO"]': 'searchPONumber'
          }),
          //searchPONumber will be triggred when the use change the input field in PO search input field.
          searchPONumber: _.debounce(function (e) {
            try {
              this.searchByPO(e);
            } catch (error) {
              console.error('Error @ SearchPONumber fn', error);
            }
          }, 1000),
          //searchByPO is used to call after 1s of user stoped changing the search text.
          searchByPO: function (e) {
            try {
              let self = this;
              let orderNumber = e.target.value;
              if (orderNumber !== '') {
                self.showCustomCollection = true;
                self.sortedCollection = _.filter(self.searchCollection.models, order => order.tranid && order.tranid.indexOf(orderNumber.toUpperCase()) > -1);
              } else {
                self.showCustomCollection = false;
                self.sortedCollection = []
              }
              self.searchOrderNumber = orderNumber;
              self.render();
            } catch (error) {
              console.error('Error @ SearchByPO fn', error);
            }
          },
          //_buildResultsView function is extended from the source code to update the SO search Orders.
          _buildResultsView: function() {
            try {
              const self = this;
              let selectedColumns = [];
              let updatedCollection  = []
              if (self.searchOrderNumber && self.searchOrderNumber !== '') {
                updatedCollection = _.filter(self.searchCollection.models, order => {
                  return (order.tranid).indexOf((self.searchOrderNumber).toUpperCase()) > -1;
                })
              } else {
                updatedCollection = self.collection;
              }
              if (!Configuration.get().transactionListColumns.enableOrderHistory) {
                selectedColumns.push({ label: 'Date', id: 'trandate', type: 'date' });
                selectedColumns.push({
                  label: 'Amount',
                  name: 'amount',
                  id: 'amount_formatted',
                  type: 'currency'
                });
                if (self.isSCISIntegrationEnabled) {
                  selectedColumns.push({ label: 'Origin', id: 'origin' });
                } else {
                  selectedColumns.push({ label: 'Status', id: 'status', type: 'status' });
                }
              } else {
                selectedColumns = Configuration.get().transactionListColumns.orderHistory;
              }
              const records_collection = new Backbone.Collection(
                updatedCollection.map(function(order) {
                  const model = new Backbone.Model({
                      title: new Handlebars.SafeString(
                        Utils.translate('<span class="tranid">$(0)</span>', order.get('tranid'))
                      ),
                      touchpoint: 'customercenter',
                      detailsURL:
                        '/purchases/view/' +
                        order.get('recordtype') +
                        '/' +
                        order.get('internalid'),
                      recordType: order.get('recordtype'),
                      id: order.get('internalid'),
                      internalid: order.get('internalid'),
                      trackingNumbers: order.get('trackingnumbers'),
                      columns: self._buildColumns(selectedColumns, order)
                  });
                  return model;
                })
              );
              return new BackboneCollectionView({
                childView: RecordViewsActionableView,
                collection: records_collection,
                viewsPerRow: 1,
                childViewOptions: {
                  actionView: OrderHistoryListTrackingNumberView,
                  actionOptions: {
                    showContentOnEmpty: true,
                    contentClass: '',
                    collapseElements: true
                  }
                }
              });
            } catch (error) {
              console.error('Error @ _buildResultsView fn', error);
            }
          },
          getContext: _.wrap(OrderHistoryListView.prototype.getContext, function (fn) {
            try {
              let context = fn.apply(this, _.toArray(arguments).slice(1));
              let self = this;
              let currentView = container.getLayout().currentView;
              context.showSearchPO = currentView.el.className === "OrderListView";
              context.showPagination = self.showCustomCollection ? false : context.showPagination; 
              context.customCollectionLength = self.showCustomCollection && self.sortedCollection && self.sortedCollection.length === 0;
              context.collectionLengthGreaterThan0 = context.customCollectionLength ? false : context.collectionLengthGreaterThan0;
              self.on('afterViewRender', () => {
                $('#searchPO').focus();
                $('#searchPO').val(self.searchOrderNumber);
              })
              return context;
            } catch (error) {
              console.error('Error @ getContext fn', error);
            }
          })
        })

Template:

{{#if showBackToAccount}}
  <a href="/" class="order-history-list-button-back">
    <i class="order-history-list-button-back-icon"></i>
    {{translate 'Back to Account'}}
  </a>
{{/if}}
<section class="order-history-list">
  <header class="order-history-list-header">
    <h2>{{pageHeader}}</h2>
  </header>
  <div class="order-history-list-header-nav">
    <div class="order-history-list-header-button-group">
      {{#if openIsActive}}
      <span class="order-history-list-header-button-open-active">{{translate 'Open'}}</span>
      {{else}}
      <a href="/open-purchases" class="order-history-list-header-button-open">{{translate 'Open'}}</a>
      {{/if}}
      {{#if isSCISIntegrationEnabled}}
      {{#if inStoreIsActive}}
      <span class="order-history-list-header-button-instore-active">{{translate 'In Store'}}</span>
      {{else}}
      <a href="/instore-purchases" class="order-history-list-header-button-instore">{{translate 'In Store'}}</a>
      {{/if}}
      {{/if}}
      {{#if allIsActive}}
      <span class="order-history-list-header-button-all-active">{{translate 'All'}}</span>
      {{else}}
      <a href="/purchases" class="order-history-list-header-button-all">{{translate 'All'}}</a>
      {{/if}}
    </div>
  </div>
  <div data-view="ListHeader" {{#if openIsActive}}style="display:none;"{{/if}}></div>
  {{#if showSearchPO}}
  <div class="list-header-view-searchPO">
    <div class="list-header-view-sorts">
      <div class="list-header-view-filters">
        <div class="list-header-view-datepicker-container-input">
          <input class="list-header-view-accordion-body-input" data-action="searchByPO"
            class="list-header-view-searchPO" id="searchPO" 
            placeholder="Serach orders by Purchase No" />
        </div>
      </div>
    </div>
  </div>
  {{/if}}
  {{#if collectionLengthGreaterThan0}}
  <div class="order-history-list-recordviews-container">
    <table class="order-history-list-recordviews-actionable-table">
      <thead class="order-history-list-recordviews-actionable-header">
      <tr>
        <th class="order-history-list-recordviews-actionable-title-header">
          <span>{{translate 'Purchase No.'}}</span>
        </th>
        {{#each columns}}
        <th class="order-history-list-recordviews-actionable-{{type}}-header">
          <span>{{label}}</span>
        </th>
        {{/each}}
        <th class="order-history-list-recordviews-actionable-actions-header">
          <span>{{translate 'Track Items'}}</span>
        </th>
      </tr>
      </thead>
      <tbody class="order-history-list" data-view="Order.History.Results"></tbody>
    </table>
  </div>
  {{else}}
  {{#if isLoading}}
    <p class="order-history-list-empty">{{translate 'Loading...'}}</p>
  {{else}}
  <div class="order-history-list-empty-section">
    {{#if customCollectionLength}}
    <h5>{{translate 'There are no purchases found related to your search'}}</h5>
    {{else}}
    <h5>{{translate 'You don't have any purchases in your account right now'}}</h5>
    {{/if}}
    {{#unless allIsActive}}
      <h5>{{translate 'To see a list of all your past purchases, you can go to the tab <a href="/purchases" class="">All</a>'}}</h5>
    {{/unless}}
    {{#if isSCISIntegrationEnabled}}
    {{#if openIsActive}}
      <h5>{{translate 'If you are looking to review some past purchases made in one of our brick and mortar stores, please check the tab <a href="/instore-purchases" class="">In Store</a>'}}</h5>
    {{/if}}
    {{/if}}
  </div>
  {{/if}}
  {{/if}}
  {{#if showPagination}}
    <div class="order-history-list-case-list-paginator">
      <div data-view="GlobalViews.Pagination"></div>
        {{#if showCurrentPage}}
      <div data-view="GlobalViews.ShowCurrentPage"></div>
        {{/if}}
    </div>
  {{/if}}
</section>




{{!----
Use the following context variables when customizing this template:


pageHeader (String)
collectionLengthGreaterThan0 (Boolean)
isLoading (Boolean)
showPagination (Boolean)
showBackToAccount (Boolean)
isSCISIntegrationEnabled (Boolean)
allIsActive (Boolean)
openIsActive (Boolean)
inStoreIsActive (Boolean)


----}}


Screenshot:

Leave a comment

Your email address will not be published. Required fields are marked *