I have the following script : ```/** *@NApiVersio...
# suitescript
v
I have the following script :
Copy code
/**
 *@NApiVersion 2.x
 *@NScriptType MapReduceScript
 */
define(["N/record", "N/search", "N/runtime"], function (
  record,
  search,
  runtime
) {
  function getInputData() {
    try {
      var scriptObj = runtime.getCurrentScript();
      var recordId = scriptObj.getParameter("custscript_recordid");
      var picked = scriptObj.getParameter("custscript_picked_status");
      var packed = scriptObj.getParameter("custscript_packed_status");
      var shipped = scriptObj.getParameter("custscript_shipped_status");
      log.debug(
        "statuses",
        " picked: " + picked + " packed: " + packed + " shipped: " + shipped
      );
   


      var salesOrderid = recordId;
      log.debug("recordid", salesOrderid);
      var salesorderSearchObj = search.create({
        type: "salesorder",
        filters: [
          ["type", "anyof", "SalesOrd"],
          "AND",
          ["internalid", "anyof", [salesOrderid]],
          "AND",
          ["shipping", "is", "F"],
          "AND",
          ["taxline", "is", "F"],
          "AND",
          ["mainline", "is", "F"],
          "AND",
          [
            [
              "formulanumeric: {quantitypacked}-{quantitybilled}",
              "greaterthan",
              "0",
            ],
            "OR",
            [
              "formulanumeric: {quantitypicked}-{quantitybilled}",
              "greaterthan",
              "0",
            ],
            "OR",
            [
              "formulanumeric: {quantityshiprecv}-{quantitybilled}",
              "greaterthan",
              "0",
            ],
          ],
        ],
      
        columns: [
          search.createColumn({ name: "internalid", label: "Internal ID" }),
          search.createColumn({ name: "source", label: "Source" }),
          search.createColumn({ name: "salesrep", label: "Sales Rep" }),
          search.createColumn({ name: "trandate", label: "Date" }),
          search.createColumn({ name: "postingperiod", label: "Period" }),
          search.createColumn({ name: "type", label: "Type" }),
          search.createColumn({
            name: "tranid",
            sort: search.Sort.DESC,
            label: "Document Number",
          }),
          search.createColumn({ name: "entity", label: "Name" }),
          search.createColumn({ name: "account", label: "Account" }),
          search.createColumn({ name: "memo", label: "Memo" }),
          search.createColumn({ name: "amount", label: "Amount" }),
          search.createColumn({ name: "item", label: "Item" }),
          search.createColumn({ name: "rate", label: "Item Rate" }),
          search.createColumn({ name: "fxrate", label: "Item Rate" }),
          search.createColumn({ name: "line", label: "Line ID" }),
          search.createColumn({ name: "quantity", label: "Quantity" }),
          search.createColumn({
            name: "quantitybilled",
            label: "Quantity Billed",
          }),
          search.createColumn({
            name: "quantitycommitted",
            label: "Quantity Committed",
          }),
          search.createColumn({
            name: "quantityshiprecv",
            label: "Quantity Fulfilled/Received",
          }),
          search.createColumn({
            name: "quantitypacked",
            label: "Quantity Packed",
          }),
          search.createColumn({
            name: "quantitypicked",
            label: "Quantity Picked",
          }),
          search.createColumn({ name: "taxcode", label: "Tax Item" }),
          search.createColumn({
            name: "formulanumeric",
            formula: "{quantitypacked}-{quantitybilled}",
            label: "Qty_to_invoice",
          }),
        ],
      });
return salesorderSearchObj



    } catch (error) {
      log.error({
        title: "get input data error",
        details: error.message + " line id: " + error.lineNumber,
      });
    }
  }
  /**
   * @param {MapReduceContext.map} context
   */
  function map(context) {
    try {
      var scriptObj = runtime.getCurrentScript();

      // Access the custom script parameters
      var picked = scriptObj.getParameter("custscript_picked");
      var packed = scriptObj.getParameter("custscript_packed");
      var shipped = scriptObj.getParameter("custscript_shipped");
      log.debug("picked, packed, shipped", picked+packed+shipped)
      var result = JSON.parse(context.value);
      var resultObj = JSON.stringify(context.values);
      log.debug("map-result:", JSON.stringify(result));
      var internalId = result.id;
      log.debug("internalId", internalId);
      var lineId = result.values.line;
      var itemRate = result.values.rate;
      var soItem = result.values.item;
      var description = result.values.memo;
      var quantityPicked = result.values["quantitypicked"];
      var quantityPacked = result.values["quantitypacked"];
      var quantityBilled = result.values["quantitybilled"];
      var quantityShipRecv = result.values["quantityshiprecv"];
try {    // Calculate quantity based on checkboxes
  var quantity = 0;

  if (picked) {
    quantity += quantityPicked;
    log.debug("picked qty", quantity);
  }
  if (packed) {
    quantity += quantityPacked;
    log.debug("packed qty", quantity);
  }
  if (shipped) {
    quantity += quantityShipRecv;
    log.debug("shipped qty", quantity);
  }

  quantity -= quantityBilled;
  
} catch (error) {
  log.error("error for picked, packed,shipped", error.message)
}
  

      // var quantity = quantityPacked - quantityBilled;

      var lineData = {
        line: lineId,
        item: soItem,
        rate: itemRate,
        quantity: quantity,
        memo: description,
      };

      log.debug("lineData", lineData);

      var lineDataString = JSON.stringify(lineData);

      // Pass the JSON string as the value in context.write()
      context.write({
        key: internalId,
        value: lineDataString,
      });

      log.debug("context-end of map", context);
    } catch (error) {
      log.error("map error", error.message + "  lineID: " + error.lineNumber);
    }
  }
  /**
   * @param {MapReduceContext.reduce} context
   */
  function reduce(context) {
    try {
      var mapData = context.values;

      log.debug("mapData", mapData);
      log.debug("internalID", context.key);

      var invoiceRecord = record.transform({
        fromType: record.Type.SALES_ORDER,
        fromId: context.key,
        toType: record.Type.INVOICE,
        isDynamic: true,
      });

      var lineCount = invoiceRecord.getLineCount({ sublistId: "item" });
      log.debug("lineCount", lineCount);

      // Create an object to store line data using line IDs as keys
      var lineDataMap = {};

      // Iterate through the mapData to organize line data by line ID
      mapData.forEach(function (value) {
        var lineData = JSON.parse(value);
        var lineId = lineData.line;
        lineDataMap[lineId] = lineData;
      });

      // Iterate through the lines in the invoice record
      for (var lineIndex = 0; lineIndex < lineCount; lineIndex++) {
        // Get the line ID of the current line in the invoice record
        var lineId = invoiceRecord.getSublistValue({
          sublistId: "item",
          fieldId: "line",
          line: lineIndex,
        });

        // Check if the line ID is found in the lineDataMap
        if (lineDataMap[lineId]) {
          var lineData = lineDataMap[lineId];

          // Set the updated values for the retained line
          invoiceRecord.selectLine({ sublistId: "item", line: lineIndex });
          invoiceRecord.setCurrentSublistValue({
            sublistId: "item",
            fieldId: "item",
            value: lineData.item.value,
          });
          invoiceRecord.setCurrentSublistValue({
            sublistId: "item",
            fieldId: "quantity",
            value: lineData.quantity,
          });
          invoiceRecord.setCurrentSublistValue({
            sublistId: "item",
            fieldId: "rate",
            value: lineData.rate,
          });
          invoiceRecord.commitLine({ sublistId: "item" });
        } else {
          // Remove lines that are not found in the lineDataMap
          invoiceRecord.removeLine({ sublistId: "item", line: lineIndex });
          // Decrement lineCount as you are removing a line
          lineCount--;
          // Decrement lineIndex to correctly process the next line
          lineIndex--;
        }
      }

      // Save the updated invoice record
      var updatedInvoiceId = invoiceRecord.save();

      log.debug("invoiceRecord", "invoice record: " + updatedInvoiceId);

      // Emit the updated invoiceRecord data as a key-value pair
      context.write({
        key: "InvoiceRecord_" + updatedInvoiceId,
        value: JSON.stringify({
          type: "InvoiceRecord",
          data: {
            /* Your invoiceRecord data */
          },
        }),
      });

      log.debug("reduce-context after write", context);
    } catch (error) {
      log.error("error-reduce", error.message + " lineId: " + error.lineNumber);
    }
  }
  /**
   * @param {MapReduceContext.summarize} context
   */
  function summarize(summary) {}
  return {
    getInputData: getInputData,
    map: map,
    reduce: reduce,
    summarize: summarize,
  };
});
I am trying to retrieve the scriptparameter field values for 'custscript_picked', 'custscript_packed' and 'custscript_shipped' to use in the map processing stage For example, if the custscript_picked is set to true, then the column var quantity=quantityPicked=quantityBilled The debug log in the map stage returns a value of "0" for all the script parameters though Can script parameter values be retrieved during the Map stage of a map reduce? thanks
b
if
Copy code
var x = true + false + false
what is the value in x
a
1?
the only way that logs 0 is if they're all false ... based on what they've said they shouldn't all be false
so the question is... can you get scriptParams in the map stage - I would suggest the answer is no based on this evidence
I'd log the scriptObj in the map stage and see what you're actually getting... and the "x+y+z" log isn't great, I'm not sure why you wouldn't just copy/paste the same log as you have in the get input stage. If you really can't get the script params in the map stage then You can probably work around this using the
N/cache
module, alternatively you can preprocess in the getinput stage and add your script params as an object to each result... kinda ugly but might be easier if you've not worked with cache before.
👍 1
btw
Copy code
var x = null + null + null // 0
oh and for future reference @Vernita just write a short message first, and reply in thread with your giant codeblock 🙂
😂 1
d
even better, use a snippet
👍 3
v
Thanks @Anthony OConnor. I don't really know my way around Slack so will keep that in mind.
a
that's ok @David B is our resident slack guru, just ask him he has all the answers
😆 2
v
This is what the debug log (after adjusting it) is returning in the map stage: picked: null packed: null shipped: null the debug log for the getinput stage: picked: false packed: true shipped: false
d
stupid question time, I take it
custscript_picked_status
and
custscript_picked
are actually different script parameters and it's not a typo?
❤️ 1
😂 1
👀 1
v
@David B You are awesome! I can't believe I missed that (well, actually I can--this script was written at 1am while experiencing hours of frustration at other parts of the script) That actually solved that part! Thank you
🥳 1
a
happens to us all
☝️ 1
❤️ 1
v
Thanks for the understanding I am very new to scripting (trying to learn scripting--don't have experience with it at all) so am making all kinds of amateur mistakes
a
yeah... that's how you learn
👍 1
d
glad we could help here, take this: rubber duck debugging
👍 1
rubber duck debugging 1
s
I would have said right off that YES you can read a script param during execution - it's a mechanism I use to abort execution
💯 3
d
great technique for bailing early out of what could otherwise be a death spiral 😙👌
a
oh wow... @Shawn Talbert that's pretty freaking cool
s
Aye, just a checkbox allows a dev or functional person to abort things as long as the code checks that parameter once in a while (e.g. once per stage invocation)
🙌 1