Autoship (Flow-2): Autoship Generation

Solution documented here: https://jobinandjismi.in/wp-admin/post.php?post=26914&action=edit

/**
 *@NApiVersion 2.x
 *@NScriptType MapReduceScript
 *Date Created: 01/02/2023
 * 
 * REVISION HISTORY
 * ************************************************************************************************
 * Revision 1.0 ${01/02/2023} : - Create Second set of line records copying primary which has SO ref,
 *                              - Script is powered of by a saved search created in UI
 *                              - Set processed status on primary line records
 *                              - Establish connection b/w primary and secondary line records
 *                              - Task #184002607
 * 
 * ************************************************************************************************
 */
define( [ 'N/search', 'N/record', 'N/runtime', './moment.js' ], function ( search, record, runtime, moment )
{

    const _TYPE_AUTO_SHIP_LINE = 'customrecord_vv_autoship_record';
    const _SAVED_SEARCH_ID = 'customsearch_vv_second_generatn_autoship';

    /* CUSTOM RECORD FIELDS */
    const _CR_STATUS = "custrecord_vv_autoship_status"
    const _CR_ITEM = "custrecord_vv_autoship_item"
    const _CR_SO_REF = "custrecord_vv_autoship_soref"
    const _CR_NEXT_SHIP_DATE = "custrecord_vv_autoship_nextshipdate"
    const _CR_INTERVAL = "custrecord_vv_autoship_interval"
    const _CR_FREQUENCY = "custrecord_vv_autoship_freq"
    const _CR_IS_AUTOSHIP_ITEM = "custrecord_vv_is_autoship_item";
    const _CR_LINE_UNIQUE_KEY = "custrecord_vv_autoship_line_unique_key";
    const _CR_RX_ORDER_STATUS = "custrecord_vv_autoship_rxorderstatus"
    const _CR_PRESCRIPTION = "custrecord_vv_autoship_prescription"
    const _CR_AUTO_SHIP_DATE = "custrecord_vv_autoship_date"
    const _CR_SECOND_GENERATION = "custrecord_vv_autoship_second_generation"
    /* CUSTOM RECORD FIELDS */

    /* LIST STATUS FIELD VALUE */
    const _LIST_INELIGIBLE = 5;
    const _LIST_PROCESSED = 4
    /* LIST STATUS FIELD VALUE */

    /* LIST VALUES */
    const _DAYS = "1"
    const _WEEKS = "2";
    const _MONTHS = "3";
    const _QUARTERS = "4";
    const _YEARS = "5";
    /* LIST VALUES */

    function getInputData ()
    {
        var searchId = search.load( { id: _SAVED_SEARCH_ID } );  // SEARCH NAME: Second Generation Auto-Ship Creation Search(**DO NOT DELETE - USED IN SCRIPT**)

        return searchId;
    }

    function reduce ( context )
    {

        var firstIterationLineRecID = context.key;
        log.debug( "firstIterationLineRecID", firstIterationLineRecID )

        try
        {
            if ( firstIterationLineRecID )
            {
                //LOAD AND GET VALUES FROM PRIMARY LINE RECORDS

                var autoShipRec = record.load( {
                    type: _TYPE_AUTO_SHIP_LINE,
                    id: firstIterationLineRecID
                } )

                var soRef = autoShipRec.getValue( { fieldId: _CR_SO_REF } )
                log.debug( "so Ref", soRef )

                if ( soRef )
                {
                    var dtSecondAutoshipDate = autoShipRec.getValue( { fieldId: _CR_NEXT_SHIP_DATE } )
                    var strInterval = autoShipRec.getValue( { fieldId: _CR_INTERVAL } )
                    var intFrequency = parseInt( autoShipRec.getValue( { fieldId: _CR_FREQUENCY } ) )
                    var boolIsAutoShip = autoShipRec.getValue( { fieldId: _CR_IS_AUTOSHIP_ITEM } )


                    // -------- COPY ACTION : START -------- //
                    //Similar to make a copy action in UI

                    var copyRecord = record.copy( {
                        type: _TYPE_AUTO_SHIP_LINE,
                        id: firstIterationLineRecID,
                        isDynamic: true
                    } );

                    //autoship line should contain an interval, frequency, and should be autoship = T

                    if ( strInterval && intFrequency && boolIsAutoShip )
                    {
                        //Undergo Calculation for Next ship date and set the field on the seconday record

                        var dtSecondNextshipDate = calculateNextShipDate( dtSecondAutoshipDate, strInterval, intFrequency )
                        log.debug( "dtSecondNextshipDate", dtSecondNextshipDate )//N2

                        var secondNextShipDate = moment( dtSecondNextshipDate ).format( "MM/DD/YYYY" )
                        log.debug( "secondNextShipDate", secondNextShipDate )

                        if ( secondNextShipDate != null )
                        {
                            copyRecord.setValue( { fieldId: _CR_NEXT_SHIP_DATE, value: new Date( secondNextShipDate ) } );

                        } else
                        {
                            copyRecord.setValue( { fieldId: _CR_NEXT_SHIP_DATE, value: null } );
                        }
                    } else
                    {
                        copyRecord.setValue( { fieldId: _CR_NEXT_SHIP_DATE, value: null } );
                    }
                }

                //Set the second iteration line record's "Autoship date" same as Nextship date 
                copyRecord.setValue( { fieldId: _CR_AUTO_SHIP_DATE, value: new Date( dtSecondAutoshipDate ) } );

                //Nullify unncessary field values that are copied from original to copy line records
                copyRecord.setValue( { fieldId: _CR_SO_REF, value: null } );
                copyRecord.setValue( { fieldId: _CR_LINE_UNIQUE_KEY, value: null } );
                copyRecord.setValue( { fieldId: _CR_RX_ORDER_STATUS, value: null } );
                copyRecord.setValue( { fieldId: _CR_PRESCRIPTION, value: null } );

                //Stoes ID of created new copy of line record
                var submitCopyRecordId = copyRecord.save( {
                    enableSourcing: true,
                    ignoreMandatoryFields: true
                } );
                log.debug( "submitCopyRecordId", submitCopyRecordId )

                // ---COPY ACTION COMPLETED--- //


                //set primary autoship status to processed and link the generated seconday line record to primary (connection point)

                autoShipRec.setValue( { fieldId: _CR_STATUS, value: _LIST_PROCESSED } );

                if ( submitCopyRecordId )
                {
                    autoShipRec.setValue( { fieldId: _CR_SECOND_GENERATION, value: submitCopyRecordId } );
                }

                autoShipRec.save();
            }


        } catch ( Err )
        {
            log.debug( "Error @map on record save", Err )
            log.error( "Error @map on record save", Err )
        }

    }

    function summarize ( summary )
    {
        log.debug( "EXECUTION FINISHED", "TIME ELAPSED = " + ( summary.seconds / 60 ) + " min(s)" );
    }

    function calculateNextShipDate ( dtTrandate, strInterval, intFrequency )
    {
        try
        {
            switch ( strInterval )
            {
                case _DAYS:
                    return moment( dtTrandate ).add( intFrequency, "days" )

                case _WEEKS:
                    return moment( dtTrandate ).add( intFrequency, "weeks" )

                case _MONTHS:
                    return moment( dtTrandate ).add( intFrequency, "months" )

                case _QUARTERS:
                    return moment( dtTrandate ).add( intFrequency * 3, "months" )

                case _YEARS:
                    return moment( dtTrandate ).add( intFrequency, "years" )

                default: return null
            }
        } catch ( e )
        {
            log.debug( "Error", e )
            log.error( "Error", e )
        }
    }


    return {
        getInputData: getInputData,
        reduce: reduce,
        summarize: summarize
    }
} );

Leave a comment

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