Update the transaction history of parent customer in my-account

In SCA setup, only the transactions of the customer who is logged in are displayed by default. By customization we can update the transactions displayed on my-account pages to include the most transactions of sub-customers also along with transactions of login parent customer.

To update the transaction history, we have to update the filter used in the source code. Instead of using the customer internal is entity, we have to use an array of the sub customers internal id

Entry point file

_.extend(TransactionHistoryListView.prototype, {




                    initialize: function (options) {

                        let page = '1';




                        if (options.routerArguments && options.routerArguments[0]) {

                            const params = Utils.parseUrlOptions(options.routerArgument);




                            if (params.page) {

                                page = params.page.toString();

                            }

                        }




                        this.options.page = page;




                        this.application = options.application;

                        this.collection = new JJTransactionHistoryModel();          

                        this.profileModel = ProfileModel.getInstance();

                        this.listenCollection();




                        this.collection.on('reset', this.showContent, this);




                        const today = new Date();

                        const isoDate = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;




                        this.rangeFilterOptions = {

                            fromMin: '1800-01-02',

                            fromMax: isoDate,

                            toMin: '1800-01-02',

                            toMax: isoDate

                        };




                        this.listHeader = new ListHeaderView({

                            view: this,

                            application: this.application,

                            collection: this.collection,

                            filters: this.filterOptions,

                            sorts: this.sortOptions,

                            rangeFilter: 'date',

                            rangeFilterLabel: Utils.translate('From'),

                            hidePagination: true,

                            allowEmptyBoundaries: true

                        });

                    },

                    childViews: {

                        'ListHeader.View': function () {

                            return this.listHeader;

                        },

                        'Records.Collection': function () {

                            var self = this;

                            var records_collection = new Backbone.Collection(this.collection.map(function (transaction_history) {

                                var model = new Backbone.Model({

                                    touchpoint: 'customercenter',

                                    title: new Handlebars.SafeString(

                                        Utils.translate(

                                            `${self.getTypeLabel(transaction_history.recordtype)} #<span class="tranid">$(0)</span>`,

                                            transaction_history.get('tranid')

                                        )

                                    ),

                                    detailsURL: self.getTypeUrl(transaction_history.recordtype, transaction_history.internalid),




                                    id: transaction_history.id,

                                    internalid: transaction_history.id,




                                    columns: [

                                        {

                                            label: Utils.translate('Date:'),

                                            type: 'date',

                                            name: 'date',

                                            value: transaction_history.get('trandate')

                                        },

                                        {

                                            label: Utils.translate('Amount:'),

                                            type: 'currency',

                                            name: 'amount',

                                            value: transaction_history.get('amount_formatted')

                                        },

                                        {

                                            label: Utils.translate('Status:'),

                                            type: 'status',

                                            name: 'status',

                                            value: transaction_history.get('status') ? transaction_history.get('status').name : ""

                                        }

                                    ]

                                });

                                return model;

                            })

                            );

                            return new BackboneCollectionView({

                                childView: RecordViewsView,

                                collection: records_collection,

                                viewsPerRow: 1

                            });

                        },

                        'GlobalViews.Pagination': function () {

                            return new GlobalViewsPaginationView(

                                _.extend(

                                    {

                                        totalPages: Math.ceil(

                                            this.collection.totalRecordsFound / this.collection.recordsPerPage

                                        )

                                    },

                                    Configuration.defaultPaginationSettings

                                )

                            );

                        }

                    },




                    getTypeLabel: function (recordtype) {

                        var type;




                        switch (recordtype) {

                            case 'creditmemo':

                                type = _('Credit Memo').translate();

                                break;

                            case 'customerpayment':

                                type = _('Payment').translate();

                                break;

                            case 'customerdeposit':

                                type = _('Deposit').translate();

                                break;

                            case 'depositapplication':

                                type = _('Deposit Application').translate();

                                break;

                            case 'invoice':

                                type = _('Invoice').translate();

                                break;

                            case 'cashsale':

                                type = _('Cash Receipt').translate();

                                break;

                        }




                        return type;

                    }

                    , getTypeUrl: function (recordtype, internalid) {

                        var type = recordtype

                            , record_root_url = 'transactionhistory/' + type;




                        if (type === 'invoice') {

                            record_root_url = 'invoices';

                        }

                        else if (type === 'returnauthorization') {

                            record_root_url = 'returns';

                        }




                        return record_root_url + '/' + internalid;

                    },




                })






Model file

// Model.js

// -----------------------

// @module Case

define("JJ.Transaction.History.Model", ["Utils", "Transaction.Collection"], function (

    Utils,

    TransactionCollection

) {

    "use strict";




    return TransactionCollection.extend({




        url: Utils.getAbsoluteUrl(getExtensionAssetsPath("services/searchbar.Service.ss")),




        parse: function parse(response) {

            this.totalRecordsFound = response.totalRecordsFound;

            this.recordsPerPage = response.recordsPerPage;

            this.page = response.page;

            return response.records;

        },




        update: function (options) {

            var range = options.range || {};          

            const data = {

                filter: this.customFilters || (options.filter && options.filter.value),

                sort: options.sort.value,

                order: options.order,

                from: range.from,

                to: range.to,

                page: options.page,

                searchKeyword: options.searchKeyword

            };  

            this.fetch({

                data: data,

                reset: true,

                killerId: options.killerId

            });

        }

     

     




    });

});






Service controller

    _validatePermission: function () {

      const permissions = Application.getPermissions().transactions;

      if (

        !(

          permissions.tranFind > 0 &&

          (permissions.tranCustInvc > 0 ||

            permissions.tranCustCred > 0 ||

            permissions.tranCustPymt > 0 ||

            permissions.tranCustDep > 0 ||

            permissions.tranDepAppl > 0)

        )

      ) {

        throw forbiddenError;

      }

    },




    get: function get() {

      try {      

      

          this._validatePermission();




          return JJTransactionHistoryCustomModel.list({

            filter: this.request.getParameter('filter'),

            order: this.request.getParameter('order'),

            sort: this.request.getParameter('sort'),

            from: this.request.getParameter('from'),

            to: this.request.getParameter('to'),

            page: this.request.getParameter('page') || 1,

            types: this.request.getParameter('types'),

            createdfrom: this.request.getParameter('createdfrom')

          });

        

      } catch (e) {

        console.error("error @ controller", e);

      }

    },

Suitescript model file

// JJ.TransactionHistory.Custom.Model.js
// Load all your starter dependencies in backend for your extension here
// ----------------


define('JJ.TransactionHistory.Custom.Model'
    , [
        'Transaction.Model'
    ]
    , function (
        TransactionModel
    ) {
        'use strict';
        return TransactionModel.extend({


            setExtraListFilters: _.wrap(TransactionModel.setExtraListFilters, function setExtraListFilters(fn) {
                try {
                    var self = this;
                    fn.apply(this, _.toArray(arguments).slice(1)); 


                    var customerId = nlapiGetContext().getUser();
                    var subCustomerIds = this.getSubCustomerIds(customerId);
                    if (subCustomerIds && subCustomerIds.length > 1) {
                        self.filters.entity = ['entity', 'anyof', subCustomerIds]
                    }
 
                    this.filters.types_operator = 'and';
                    this.filters.types = ['type', 'anyof', this.data.filter.split(',')];
                } catch (e) {
                    console.error('error@setExtraListFilters', e)
                }
            }),


            getSubCustomerIds: function (customerId) {
                try {
                    var customerInternalId = JSON.stringify(customerId);


                    var subCustomerIdArray = [customerInternalId];


                    var searchFilters = [
                        ["internalid", "anyof", customerId]
                    ];
                    var searchColumns = [
                        new nlobjSearchColumn("internalid", "subCustomer", null),
                    ]


                    var subcustomerObj = Application.getAllSearchResults('customer', searchFilters, searchColumns) || {};


                    var result = JSON.stringify(subcustomerObj);


                    result = JSON.parse(result);


                    if (result.length > 0) {
                        _.each(result, function (eachResult) {
                            var columnresult = JSON.stringify(eachResult)
                            var internalid = JSON.parse(columnresult).columns.internalid ? JSON.parse(columnresult).columns.internalid.internalid : "";
                            subCustomerIdArray.push(internalid);
                        });
                    }


                    return subCustomerIdArray;


                } catch (e) {
                    console.error('error@getSubCustomerIds', e)
                }
            }


        });
    });


Leave a comment

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