Best JavaScript code snippet using wpt
GetProductVirtualMatrixFromQuery.js
Source:GetProductVirtualMatrixFromQuery.js
1'use strict'2let GetProductVirtualMatrixFromQuery = function(ncUtil, channelProfile, flowContext, payload, callback) {3 const _ = require('lodash');4 const soap = require('strong-soap/src/soap');5 const nc = require('../util/common');6 const matrix = require('../util/matrixHelper');7 let soapClient = null;8 let out = {9 ncStatusCode: null,10 payload: {}11 };12 let parentIDs = [];13 if (!callback) {14 throw new Error("A callback function was not provided");15 } else if (typeof callback !== 'function') {16 throw new TypeError("callback is not a function")17 }18 validateFunction().then(() => {19 if (payload.pagingContext) {20 // Check for a pagingContext object21 // Contains the parent/child matrix IDs from the initial search22 createSoapClient()23 .then(createGetListRequest)24 .then(callNetsuite)25 .then(buildResponse)26 .catch(handleError)27 .then(() => callback(out))28 .catch(error => {29 logError(`The callback function threw an exception: ${error}`);30 setTimeout(() => {31 throw error;32 });33 });34 } else {35 // Initial search for parents/child by IDs36 createSoapClient()37 .then(async () => {38 // Search Virtual Matrix Parent Products39 let searchPayload = createRequest("matrix");40 return await matrix.getMatrixProducts(searchPayload, soapClient, channelProfile, "matrix");41 })42 .then(async (result) => {43 // Combine Parent IDs - The lodash method 'union' joins and removes duplicates44 parentIDs = _.union(result, parentIDs);45 // Search Virtual Matrix Child Products46 let searchPayload = createRequest("matrixChild");47 return await matrix.getMatrixProducts(searchPayload, soapClient, channelProfile,"matrixChild");48 })49 .then(async (result) => {50 let parentObjects = [];51 // Combine Parent IDs - The lodash method 'union' joins and removes duplicates52 parentIDs = _.union(result, parentIDs);53 // Create initial objects for each virtual matrix parent54 parentIDs.forEach(function (parentID) {55 parentObjects.push({ "parent": parentID, "children": [] });56 });57 if (parentObjects.length > 0) {58 // Process products if we have parent IDs59 let searchPayload = createRequest("full", parentIDs);60 await matrix.getMatrixProducts(searchPayload, soapClient, channelProfile, "full", parentObjects)61 .then(createGetListRequest)62 .then(callNetsuite)63 .then(buildResponse)64 .catch(handleError)65 .then(() => callback(out))66 .catch(error => {67 logError(`The callback function threw an exception: ${error}`);68 setTimeout(() => {69 throw error;70 });71 });72 } else {73 // If no products were returned from the searches, build the response with a 204 ncStatusCode74 return buildResponse()75 .catch(handleError)76 .then(() => callback(out))77 .catch(error => {78 logError(`The callback function threw an exception: ${error}`);79 setTimeout(() => {80 throw error;81 });82 });83 }84 })85 .catch((err) => {86 handleError(err)87 .then(() => callback(out))88 .catch(error => {89 logError(`The callback function threw an exception: ${error}`);90 setTimeout(() => {91 throw error;92 });93 });94 })95 }96 })97 .catch((err) => {98 handleError(err)99 .then(() => callback(out))100 .catch(error => {101 logError(`The callback function threw an exception: ${error}`);102 setTimeout(() => {103 throw error;104 });105 });106 })107 function logInfo(msg) {108 nc.log(msg, "info");109 }110 function logWarn(msg) {111 nc.log(msg, "warn");112 }113 function logError(msg) {114 nc.log(msg, "error");115 }116 async function validateFunction() {117 let invalidMsg;118 if (!ncUtil)119 invalidMsg = "ncUtil was not provided";120 else if (!channelProfile)121 invalidMsg = "channelProfile was not provided";122 else if (!channelProfile.channelSettingsValues)123 invalidMsg = "channelProfile.channelSettingsValues was not provided";124 else if (!channelProfile.channelSettingsValues.namespaces)125 invalidMsg = "channelProfile.channelSettingsValues.namespaces was not provided";126 else if (!channelProfile.channelSettingsValues.wsdl_uri)127 invalidMsg = "channelProfile.channelSettingsValues.api_uri was not provided";128 else if (!channelProfile.channelAuthValues)129 invalidMsg = "channelProfile.channelAuthValues was not provided";130 else if (!channelProfile.channelAuthValues.account)131 invalidMsg = "channelProfile.channelAuthValues.account was not provided";132 else if (!channelProfile.channelAuthValues.consumerKey)133 invalidMsg = "channelProfile.channelAuthValues.consumerKey was not provided";134 else if (!channelProfile.channelAuthValues.consumerSecret)135 invalidMsg = "channelProfile.channelAuthValues.consumerSecret was not provided";136 else if (!channelProfile.channelAuthValues.tokenID)137 invalidMsg = "channelProfile.channelAuthValues.tokenID was not provided";138 else if (!channelProfile.channelAuthValues.tokenSecret)139 invalidMsg = "channelProfile.channelAuthValues.tokenSecret was not provided";140 else if (!channelProfile.productBusinessReferences)141 invalidMsg = "channelProfile.productBusinessReferences was not provided";142 else if (!nc.isArray(channelProfile.productBusinessReferences))143 invalidMsg = "channelProfile.productBusinessReferences is not an array";144 else if (!nc.isNonEmptyArray(channelProfile.productBusinessReferences))145 invalidMsg = "channelProfile.productBusinessReferences is empty";146 else if (!payload)147 invalidMsg = "payload was not provided";148 else if (!payload.doc)149 invalidMsg = "payload.doc was not provided";150 else if (!payload.doc.remoteIDs && !payload.doc.searchFields && !payload.doc.modifiedDateRange)151 invalidMsg = "either payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange must be provided";152 else if (payload.doc.remoteIDs && (payload.doc.searchFields || payload.doc.modifiedDateRange))153 invalidMsg = "only one of payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange may be provided";154 else if (payload.doc.remoteIDs && (!Array.isArray(payload.doc.remoteIDs) || payload.doc.remoteIDs.length === 0))155 invalidMsg = "payload.doc.remoteIDs must be an Array with at least 1 remoteID";156 else if (payload.doc.searchFields && (!Array.isArray(payload.doc.searchFields) || payload.doc.searchFields.length === 0))157 invalidMsg = "payload.doc.searchFields must be an Array with at least 1 key value pair: {searchField: 'key', searchValues: ['value_1']}";158 else if (payload.doc.searchFields) {159 for (let i = 0; i < payload.doc.searchFields.length; i++) {160 if (!payload.doc.searchFields[i].searchField || !Array.isArray(payload.doc.searchFields[i].searchValues) || payload.doc.searchFields[i].searchValues.length === 0) {161 invalidMsg = "payload.doc.searchFields[" + i + "] must be a key value pair: {searchField: 'key', searchValues: ['value_1']}";162 break;163 }164 }165 }166 else if (payload.doc.modifiedDateRange && !(payload.doc.modifiedDateRange.startDateGMT || payload.doc.modifiedDateRange.endDateGMT))167 invalidMsg = "at least one of payload.doc.modifiedDateRange.startDateGMT or payload.doc.modifiedDateRange.endDateGMT must be provided";168 else if (payload.doc.modifiedDateRange && payload.doc.modifiedDateRange.startDateGMT && payload.doc.modifiedDateRange.endDateGMT && (payload.doc.modifiedDateRange.startDateGMT > payload.doc.modifiedDateRange.endDateGMT))169 invalidMsg = "startDateGMT must have a date before endDateGMT";170 if (invalidMsg) {171 logError(invalidMsg);172 out.ncStatusCode = 400;173 throw new Error(`Invalid request [${invalidMsg}]`);174 }175 logInfo("Function is valid.");176 }177 function createSoapClient(search) {178 return new Promise((resolve, reject) => {179 logInfo("Creating NetSuite Client...");180 soap.createClient(channelProfile.channelSettingsValues.wsdl_uri, {}, function(err, client) {181 if (!err) {182 // Add namespaces to the wsdl183 _.assign(client.wsdl.definitions.xmlns, channelProfile.channelSettingsValues.namespaces);184 client.wsdl.xmlnsInEnvelope = client.wsdl._xmlnsMap();185 soapClient = client;186 resolve(search);187 } else {188 reject(err);189 }190 });191 });192 }193 function createRequest(type = "matrix", parentIDs = null) {194 logInfo(`Building NetSuite Request. Type: ${type}`);195 let searchPayload = {196 "searchRecord": {197 "$attributes": {198 "$xsiType": {199 "xmlns": channelProfile.channelSettingsValues.namespaces.listAcct,200 "type": "ItemSearch"201 }202 },203 "basic":{204 "type": {205 "$attributes": {206 "operator": "anyOf"207 },208 "$value": {209 "searchValue": "inventoryItem"210 }211 },212 "matrix": {213 "searchValue": false214 },215 "matrixChild": {216 "searchValue": false217 }218 }219 }220 };221 if (flowContext) {222 // Flow Context Criteria Filters223 if (flowContext.filterField && flowContext.filterCriteria) {224 let fieldName = flowContext.filterField;225 let customField = fieldName.startsWith("custitem");226 if (customField) {227 searchPayload["searchRecord"]["basic"]["customFieldList"] = {228 "customField": []229 }230 let obj = {231 "$attributes": {232 "$xsiType": {233 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,234 "type": "SearchBooleanCustomField"235 },236 "scriptId": flowContext.filterField237 },238 "searchValue": flowContext.filterCriteria239 }240 if (flowContext.filterCompare) {241 obj["$attributes"]["operator"] = flowContext.filterCompare;242 }243 searchPayload["searchRecord"]["basic"]["customFieldList"]["customField"].push(obj);244 } else {245 searchPayload["searchRecord"]["basic"][fieldName] = {246 "searchValue": flowContext.filterCriteria247 }248 if (flowContext.filterCompare) {249 searchPayload["searchRecord"]["basic"][fieldName]["$attributes"] = {250 "operator": flowContext.filterCompare251 }252 }253 }254 }255 if (!searchPayload["searchRecord"]["basic"]["customFieldList"]) {256 searchPayload["searchRecord"]["basic"]["customFieldList"] = {257 "customField": []258 }259 }260 // Set a filter to include a custom field referencing if a product is a virtual matrix parent261 if (flowContext.virtualMatrixParentFlag && flowContext.virtualMatrixParentFlagCriteria && type === "matrix") {262 let obj = {263 "$attributes": {264 "$xsiType": {265 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,266 "type": "SearchBooleanCustomField"267 },268 "operator": flowContext.virtualMatrixParentFlagCompare,269 "scriptId": flowContext.virtualMatrixParentFlag270 },271 "searchValue": flowContext.virtualMatrixParentFlagCriteria272 }273 if (flowContext.virtualMatrixParentFlagCompare === "") {274 delete obj.$attributes.operator;275 }276 searchPayload["searchRecord"]["basic"]["customFieldList"]["customField"].push(obj);277 }278 // Set a filter to include a custom field referencing a parent on the child product - Returns child products where this field is not empty279 if (flowContext.parentIdField && type === "matrixChild") {280 searchPayload["searchRecord"]["basic"]["customFieldList"]["customField"].push({281 "$attributes": {282 "$xsiType": {283 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,284 "type": "SearchStringCustomField"285 },286 "operator": "notEmpty",287 "scriptId": flowContext.parentIdField288 }289 });290 }291 }292 if (payload.doc.searchFields) {293 payload.doc.searchFields.forEach(function (searchField) {294 let fieldName = searchField.searchField;295 searchPayload["searchRecord"]["basic"][fieldName] = {296 "$attributes": {297 "operator": "anyOf"298 },299 "searchValue": searchField.searchValues300 }301 });302 } else if (payload.doc.remoteIDs && type !== "full") {303 let values = [];304 payload.doc.remoteIDs.forEach(function (remoteID) {305 values.push({ "$attributes": { "internalId": remoteID } });306 });307 searchPayload["searchRecord"]["basic"]["internalId"] = {308 "$attributes": {309 "operator": "anyOf"310 },311 "searchValue": values312 }313 } else if (payload.doc.modifiedDateRange) {314 let obj = {};315 if (payload.doc.modifiedDateRange.startDateGMT && !payload.doc.modifiedDateRange.endDateGMT) {316 obj = {317 "$attributes": {318 "operator": "onOrAfter"319 },320 "searchValue": new Date(Date.parse(payload.doc.modifiedDateRange.startDateGMT) - 1).toISOString()321 }322 } else if (payload.doc.modifiedDateRange.endDateGMT && !payload.doc.modifiedDateRange.startDateGMT) {323 obj = {324 "$attributes": {325 "operator": "onOrBefore"326 },327 "searchValue": new Date(Date.parse(payload.doc.modifiedDateRange.endDateGMT) + 1).toISOString()328 }329 } else if (payload.doc.modifiedDateRange.startDateGMT && payload.doc.modifiedDateRange.endDateGMT) {330 obj = {331 "$attributes": {332 "operator": "within"333 },334 "searchValue": new Date(Date.parse(payload.doc.modifiedDateRange.startDateGMT) - 1).toISOString(),335 "searchValue2": new Date(Date.parse(payload.doc.modifiedDateRange.endDateGMT) + 1).toISOString()336 }337 }338 searchPayload["searchRecord"]["basic"]["lastModifiedDate"] = obj;339 }340 // If current search is to get the full matrix product341 if (type === "full" && parentIDs != null) {342 let values = [];343 parentIDs.forEach(function (parentID) {344 values.push({ "$attributes": { "internalId": parentID } });345 });346 searchPayload["searchRecord"]["parentJoin"] = {347 "internalId": {348 "$attributes": {349 "operator": "anyOf"350 },351 "$value": {352 "searchValue": values353 }354 }355 }356 }357 return searchPayload;358 }359 function createGetListRequest(parentObjects) {360 if (!payload.pagingContext) {361 payload.pagingContext = {362 parentObjects: parentObjects363 }364 }365 let parentObject = payload.pagingContext.parentObjects[0];366 let getListPayload = {367 "record": []368 };369 let matrixProduct = {370 parentObject: parentObject371 }372 // Push parent and child products into the 'getList' operation373 getListPayload.record.push({374 "$attributes":{375 "$xsiType":{376 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,377 "type": "RecordRef"378 },379 "internalId": parentObject.parent,380 "type": "inventoryItem"381 }382 });383 parentObject.children.forEach(function (childId) {384 getListPayload.record.push({385 "$attributes":{386 "$xsiType":{387 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,388 "type": "RecordRef"389 },390 "internalId": childId,391 "type": "inventoryItem"392 }393 });394 });395 matrixProduct.getListPayload = getListPayload;396 return matrixProduct;397 }398 function callNetsuite(matrixProduct) {399 return new Promise((resolve, reject) => {400 logInfo("Calling NetSuite...");401 let operation = "getList"402 soapClient.clearSoapHeaders();403 let headers = nc.generateHeaders(channelProfile);404 soapClient.addSoapHeader(headers);405 soapClient[operation](matrixProduct.getListPayload, function(err, result) {406 if (!err) {407 delete matrixProduct.getListPayload;408 matrixProduct.result = result;409 resolve(matrixProduct);410 } else {411 reject(err);412 }413 });414 });415 }416 async function buildResponse(matrixProduct) {417 logInfo("Processing Response...");418 if (typeof matrixProduct !== 'undefined' && matrixProduct) {419 if (nc.isObject(matrixProduct.result)) {420 if (matrixProduct.result.readResponseList && matrixProduct.result.readResponseList.readResponse) {421 if (matrixProduct.result.readResponseList.status.$attributes.isSuccess === "true") {422 let docs = [];423 if (matrixProduct.result.readResponseList.readResponse.length > 0) {424 let childRecords = [];425 let product = { "record": {} };426 for (let i = 0; i < matrixProduct.result.readResponseList.readResponse.length; i++) {427 if (matrixProduct.result.readResponseList.readResponse[i].record.$attributes.internalId == matrixProduct.parentObject.parent) {428 product = {429 record: matrixProduct.result.readResponseList.readResponse[i].record430 };431 } else {432 childRecords.push( { "record" : matrixProduct.result.readResponseList.readResponse[i].record });433 }434 if (i == matrixProduct.result.readResponseList.readResponse.length - 1) {435 product.record.matrixChildren = childRecords;436 }437 }438 docs.push({439 doc: product,440 productRemoteID: matrixProduct.result.readResponseList.readResponse[0].record.$attributes.internalId,441 productBusinessReference: nc.extractBusinessReference(channelProfile.productBusinessReferences, matrixProduct.result.readResponseList.readResponse[0])442 });443 if (docs.length == 0) {444 out.ncStatusCode = 204;445 } else {446 out.payload = docs;447 payload.pagingContext.parentObjects.splice(0, 1);448 if (payload.pagingContext.parentObjects.length > 0) {449 out.ncStatusCode = 206;450 } else {451 out.ncStatusCode = 200;452 }453 }454 } else {455 out.ncStatusCode = 204;456 }457 } else {458 if (matrixProduct.result.searchResult.status.statusDetail) {459 out.ncStatusCode = 400;460 out.payload.error = matrixProduct.result.searchResult.status.statusDetail;461 } else {462 out.ncStatusCode = 400;463 out.payload.error = matrixProduct.result;464 }465 }466 } else {467 out.ncStatusCode = 500;468 out.payload.error = matrixProduct.result;469 }470 } else {471 out.ncStatusCode = 204;472 }473 } else {474 out.ncStatusCode = 204;475 }476 }477 async function handleError(error) {478 if (error.response) {479 let err = String(error.response.body);480 if (err.indexOf("soapenv:Fault") !== -1) {481 if (err.indexOf("platformFaults:exceededConcurrentRequestLimitFault") !== -1) {482 logError(`Concurrency Request Limit Exceeded: ${err}`);483 out.ncStatusCode = 429;484 out.payload.error = error;485 } else if (err.indexOf("platformFaults:exceededRequestLimitFault") !== -1) {486 logError(`Request Limit Exceeded: ${err}`);487 out.ncStatusCode = 429;488 out.payload.error = error;489 } else {490 logError(`SOAP Fault Found: ${err}`);491 out.ncStatusCode = 400;492 out.payload.error = error;493 }494 } else {495 out.ncStatusCode = 500;496 out.payload.error = error;497 }498 } else {499 out.payload.error = error;500 out.ncStatusCode = out.ncStatusCode || 500;501 }502 }503}...
GetProductMatrixFromQuery.js
Source:GetProductMatrixFromQuery.js
1'use strict'2let GetProductMatrixFromQuery = function(ncUtil, channelProfile, flowContext, payload, callback) {3 const _ = require('lodash');4 const soap = require('strong-soap/src/soap');5 const nc = require('../util/common');6 const matrix = require('../util/matrixHelper');7 let soapClient = null;8 let out = {9 ncStatusCode: null,10 payload: {}11 };12 let parentIDs = [];13 let cache = false;14 if (!callback) {15 throw new Error("A callback function was not provided");16 } else if (typeof callback !== 'function') {17 throw new TypeError("callback is not a function")18 }19 validateFunction().then(() => {20 if (payload.pagingContext) {21 // Check for a pagingContext object22 // Contains the parent/child matrix IDs from the initial search23 createSoapClient()24 .then(createGetListRequest)25 .then(callNetsuite)26 .then(buildResponse)27 .catch(handleError)28 .then(() => callback(out))29 .catch(error => {30 logError(`The callback function threw an exception: ${error}`);31 setTimeout(() => {32 throw error;33 });34 });35 } else {36 // Initial search for parents/child by IDs37 createSoapClient()38 .then(async () => {39 // Search Matrix Parent Products40 let searchPayload = createRequest("matrix");41 return await matrix.getMatrixProducts(searchPayload, soapClient, channelProfile, "matrix");42 })43 .then(async (result) => {44 // Combine Parent IDs - The lodash method 'union' joins and removes duplicates45 parentIDs = _.union(result, parentIDs);46 // Search Matrix Child Products47 let searchPayload = createRequest("matrixChild");48 return await matrix.getMatrixProducts(searchPayload, soapClient, channelProfile,"matrixChild");49 })50 .then(async (result) => {51 let parentObjects = [];52 // Combine Parent IDs - The lodash method 'union' joins and removes duplicates53 parentIDs = _.union(result, parentIDs);54 // Create initial objects for each virtual matrix parent55 parentIDs.forEach(function (parentID) {56 parentObjects.push({ "parent": parentID, "children": [] });57 });58 if (parentObjects.length > 0) {59 // Process products if we have parent IDs60 let searchPayload = createRequest("full", parentIDs);61 await matrix.getMatrixProducts(searchPayload, soapClient, channelProfile, "full", parentObjects)62 .then(createGetListRequest)63 .then(callNetsuite)64 .then(buildResponse)65 .catch(handleError)66 .then(() => callback(out))67 .catch(error => {68 logError(`The callback function threw an exception: ${error}`);69 setTimeout(() => {70 throw error;71 });72 });73 } else {74 // If no products were returned from the searches, build the response with a 204 ncStatusCode75 return buildResponse()76 .catch(handleError)77 .then(() => callback(out))78 .catch(error => {79 logError(`The callback function threw an exception: ${error}`);80 setTimeout(() => {81 throw error;82 });83 });84 }85 })86 .catch((err) => {87 handleError(err)88 .then(() => callback(out))89 .catch(error => {90 logError(`The callback function threw an exception: ${error}`);91 setTimeout(() => {92 throw error;93 });94 });95 })96 }97 })98 .catch((err) => {99 handleError(err)100 .then(() => callback(out))101 .catch(error => {102 logError(`The callback function threw an exception: ${error}`);103 setTimeout(() => {104 throw error;105 });106 });107 })108 function logInfo(msg) {109 nc.log(msg, "info");110 }111 function logWarn(msg) {112 nc.log(msg, "warn");113 }114 function logError(msg) {115 nc.log(msg, "error");116 }117 async function validateFunction() {118 let invalidMsg;119 if (!ncUtil)120 invalidMsg = "ncUtil was not provided";121 else if (!channelProfile)122 invalidMsg = "channelProfile was not provided";123 else if (!channelProfile.channelSettingsValues)124 invalidMsg = "channelProfile.channelSettingsValues was not provided";125 else if (!channelProfile.channelSettingsValues.namespaces)126 invalidMsg = "channelProfile.channelSettingsValues.namespaces was not provided";127 else if (!channelProfile.channelSettingsValues.wsdl_uri)128 invalidMsg = "channelProfile.channelSettingsValues.api_uri was not provided";129 else if (!channelProfile.channelAuthValues)130 invalidMsg = "channelProfile.channelAuthValues was not provided";131 else if (!channelProfile.channelAuthValues.account)132 invalidMsg = "channelProfile.channelAuthValues.account was not provided";133 else if (!channelProfile.channelAuthValues.consumerKey)134 invalidMsg = "channelProfile.channelAuthValues.consumerKey was not provided";135 else if (!channelProfile.channelAuthValues.consumerSecret)136 invalidMsg = "channelProfile.channelAuthValues.consumerSecret was not provided";137 else if (!channelProfile.channelAuthValues.tokenID)138 invalidMsg = "channelProfile.channelAuthValues.tokenID was not provided";139 else if (!channelProfile.channelAuthValues.tokenSecret)140 invalidMsg = "channelProfile.channelAuthValues.tokenSecret was not provided";141 else if (!channelProfile.productBusinessReferences)142 invalidMsg = "channelProfile.productBusinessReferences was not provided";143 else if (!nc.isArray(channelProfile.productBusinessReferences))144 invalidMsg = "channelProfile.productBusinessReferences is not an array";145 else if (!nc.isNonEmptyArray(channelProfile.productBusinessReferences))146 invalidMsg = "channelProfile.productBusinessReferences is empty";147 else if (!payload)148 invalidMsg = "payload was not provided";149 else if (!payload.doc)150 invalidMsg = "payload.doc was not provided";151 else if (!payload.doc.remoteIDs && !payload.doc.searchFields && !payload.doc.modifiedDateRange)152 invalidMsg = "either payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange must be provided";153 else if (payload.doc.remoteIDs && (payload.doc.searchFields || payload.doc.modifiedDateRange))154 invalidMsg = "only one of payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange may be provided";155 else if (payload.doc.remoteIDs && (!Array.isArray(payload.doc.remoteIDs) || payload.doc.remoteIDs.length === 0))156 invalidMsg = "payload.doc.remoteIDs must be an Array with at least 1 remoteID";157 else if (payload.doc.searchFields && (!Array.isArray(payload.doc.searchFields) || payload.doc.searchFields.length === 0))158 invalidMsg = "payload.doc.searchFields must be an Array with at least 1 key value pair: {searchField: 'key', searchValues: ['value_1']}";159 else if (payload.doc.searchFields) {160 for (let i = 0; i < payload.doc.searchFields.length; i++) {161 if (!payload.doc.searchFields[i].searchField || !Array.isArray(payload.doc.searchFields[i].searchValues) || payload.doc.searchFields[i].searchValues.length === 0) {162 invalidMsg = "payload.doc.searchFields[" + i + "] must be a key value pair: {searchField: 'key', searchValues: ['value_1']}";163 break;164 }165 }166 }167 else if (payload.doc.modifiedDateRange && !(payload.doc.modifiedDateRange.startDateGMT || payload.doc.modifiedDateRange.endDateGMT))168 invalidMsg = "at least one of payload.doc.modifiedDateRange.startDateGMT or payload.doc.modifiedDateRange.endDateGMT must be provided";169 else if (payload.doc.modifiedDateRange && payload.doc.modifiedDateRange.startDateGMT && payload.doc.modifiedDateRange.endDateGMT && (payload.doc.modifiedDateRange.startDateGMT > payload.doc.modifiedDateRange.endDateGMT))170 invalidMsg = "startDateGMT must have a date before endDateGMT";171 if (invalidMsg) {172 logError(invalidMsg);173 out.ncStatusCode = 400;174 throw new Error(`Invalid request [${invalidMsg}]`);175 }176 logInfo("Function is valid.");177 }178 function createSoapClient(search) {179 return new Promise((resolve, reject) => {180 logInfo("Creating NetSuite Client...");181 soap.createClient(channelProfile.channelSettingsValues.wsdl_uri, {}, function(err, client) {182 if (!err) {183 // Add namespaces to the wsdl184 _.assign(client.wsdl.definitions.xmlns, channelProfile.channelSettingsValues.namespaces);185 client.wsdl.xmlnsInEnvelope = client.wsdl._xmlnsMap();186 soapClient = client;187 resolve(search);188 } else {189 reject(err);190 }191 });192 });193 }194 function createRequest(type = "matrix", parentIDs = null) {195 logInfo(`Building NetSuite Request. Type: ${type}`);196 let searchPayload = {197 "searchRecord": {198 "$attributes": {199 "$xsiType": {200 "xmlns": channelProfile.channelSettingsValues.namespaces.listAcct,201 "type": "ItemSearch"202 }203 },204 "basic":{205 "type": {206 "$attributes": {207 "operator": "anyOf"208 },209 "$value": {210 "searchValue": "inventoryItem"211 }212 }213 }214 }215 };216 // Flow Context Criteria Filters217 if (flowContext) {218 if (flowContext.filterField && flowContext.filterCriteria) {219 let fieldName = flowContext.filterField;220 let customField = fieldName.startsWith("custitem");221 if (customField) {222 searchPayload["searchRecord"]["basic"]["customFieldList"] = {223 "customField": []224 }225 let obj = {226 "$attributes": {227 "$xsiType": {228 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,229 "type": "SearchBooleanCustomField"230 },231 "scriptId": flowContext.filterField232 },233 "searchValue": flowContext.filterCriteria234 }235 if (flowContext.filterCompare) {236 obj["$attributes"]["operator"] = flowContext.filterCompare;237 }238 searchPayload["searchRecord"]["basic"]["customFieldList"]["customField"].push(obj);239 } else {240 searchPayload["searchRecord"]["basic"][fieldName] = {241 "searchValue": flowContext.filterCriteria242 }243 if (flowContext.filterCompare) {244 searchPayload["searchRecord"]["basic"][fieldName]["$attributes"] = {245 "operator": flowContext.filterCompare246 }247 }248 }249 }250 }251 if (payload.doc.searchFields) {252 payload.doc.searchFields.forEach(function (searchField) {253 let fieldName = searchField.searchField;254 searchPayload["searchRecord"]["basic"][fieldName] = {255 "$attributes": {256 "operator": "anyOf"257 },258 "searchValue": searchField.searchValues259 }260 });261 } else if (payload.doc.remoteIDs && type !== "full") {262 let values = [];263 payload.doc.remoteIDs.forEach(function (remoteID) {264 values.push({ "$attributes": { "internalId": remoteID } });265 });266 searchPayload["searchRecord"]["basic"]["internalId"] = {267 "$attributes": {268 "operator": "anyOf"269 },270 "searchValue": values271 }272 } else if (payload.doc.modifiedDateRange) {273 let obj = {};274 if (payload.doc.modifiedDateRange.startDateGMT && !payload.doc.modifiedDateRange.endDateGMT) {275 obj = {276 "$attributes": {277 "operator": "onOrAfter"278 },279 "searchValue": new Date(Date.parse(payload.doc.modifiedDateRange.startDateGMT) - 1).toISOString()280 }281 } else if (payload.doc.modifiedDateRange.endDateGMT && !payload.doc.modifiedDateRange.startDateGMT) {282 obj = {283 "$attributes": {284 "operator": "onOrBefore"285 },286 "searchValue": new Date(Date.parse(payload.doc.modifiedDateRange.endDateGMT) + 1).toISOString()287 }288 } else if (payload.doc.modifiedDateRange.startDateGMT && payload.doc.modifiedDateRange.endDateGMT) {289 obj = {290 "$attributes": {291 "operator": "within"292 },293 "searchValue": new Date(Date.parse(payload.doc.modifiedDateRange.startDateGMT) - 1).toISOString(),294 "searchValue2": new Date(Date.parse(payload.doc.modifiedDateRange.endDateGMT) + 1).toISOString()295 }296 }297 searchPayload["searchRecord"]["basic"]["lastModifiedDate"] = obj;298 }299 // If current search is for matrix parent products300 if (type === "matrix") {301 searchPayload["searchRecord"]["basic"]["matrix"] = {302 "searchValue": "true"303 }304 }305 // If current search is for matrix child products306 if (type === "matrixChild") {307 searchPayload["searchRecord"]["basic"]["matrixChild"] = {308 "searchValue": "true"309 }310 }311 // If current search is to get the full matrix product312 if (type === "full" && parentIDs != null) {313 let values = [];314 parentIDs.forEach(function (parentID) {315 values.push({ "$attributes": { "internalId": parentID } });316 });317 searchPayload["searchRecord"]["parentJoin"] = {318 "internalId": {319 "$attributes": {320 "operator": "anyOf"321 },322 "$value": {323 "searchValue": values324 }325 }326 }327 }328 return searchPayload;329 }330 function createGetListRequest(parentObjects) {331 if (!payload.pagingContext) {332 payload.pagingContext = {333 parentObjects: parentObjects334 }335 }336 let parentObject = payload.pagingContext.parentObjects[0];337 let getListPayload = {338 "record": []339 };340 let matrixProduct = {341 parentObject: parentObject342 }343 // Push parent and child products into the 'getList' operation344 getListPayload.record.push({345 "$attributes":{346 "$xsiType":{347 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,348 "type": "RecordRef"349 },350 "internalId": parentObject.parent,351 "type": "inventoryItem"352 }353 });354 parentObject.children.forEach(function (childId) {355 getListPayload.record.push({356 "$attributes":{357 "$xsiType":{358 "xmlns": channelProfile.channelSettingsValues.namespaces.platformCore,359 "type": "RecordRef"360 },361 "internalId": childId,362 "type": "inventoryItem"363 }364 });365 });366 matrixProduct.getListPayload = getListPayload;367 return matrixProduct;368 }369 function callNetsuite(matrixProduct) {370 return new Promise((resolve, reject) => {371 logInfo("Calling NetSuite...");372 let operation = "getList"373 soapClient.clearSoapHeaders();374 let headers = nc.generateHeaders(channelProfile);375 soapClient.addSoapHeader(headers);376 soapClient[operation](matrixProduct.getListPayload, function(err, result) {377 if (!err) {378 delete matrixProduct.getListPayload;379 matrixProduct.result = result;380 resolve(matrixProduct);381 } else {382 reject(err);383 }384 });385 });386 }387 async function buildResponse(matrixProduct) {388 logInfo("Processing Response...");389 if (typeof matrixProduct !== 'undefined' && matrixProduct) {390 if (nc.isObject(matrixProduct.result)) {391 if (matrixProduct.result.readResponseList && matrixProduct.result.readResponseList.readResponse) {392 if (matrixProduct.result.readResponseList.status.$attributes.isSuccess === "true") {393 let docs = [];394 if (matrixProduct.result.readResponseList.readResponse.length > 0) {395 let childRecords = [];396 let product = { "record": {} };397 for (let i = 0; i < matrixProduct.result.readResponseList.readResponse.length; i++) {398 if (matrixProduct.result.readResponseList.readResponse[i].record.$attributes.internalId == matrixProduct.parentObject.parent) {399 product = {400 record: matrixProduct.result.readResponseList.readResponse[i].record401 };402 } else {403 childRecords.push( { "record" : matrixProduct.result.readResponseList.readResponse[i].record });404 }405 if (i == matrixProduct.result.readResponseList.readResponse.length - 1) {406 product.record.matrixChildren = childRecords;407 }408 }409 docs.push({410 doc: product,411 productRemoteID: matrixProduct.result.readResponseList.readResponse[0].record.$attributes.internalId,412 productBusinessReference: nc.extractBusinessReference(channelProfile.productBusinessReferences, matrixProduct.result.readResponseList.readResponse[0])413 });414 if (docs.length == 0) {415 out.ncStatusCode = 204;416 } else {417 out.payload = docs;418 payload.pagingContext.parentObjects.splice(0, 1);419 if (payload.pagingContext.parentObjects.length > 0) {420 out.ncStatusCode = 206;421 } else {422 out.ncStatusCode = 200;423 }424 }425 } else {426 out.ncStatusCode = 204;427 }428 } else {429 if (matrixProduct.result.searchResult.status.statusDetail) {430 out.ncStatusCode = 400;431 out.payload.error = matrixProduct.result.searchResult.status.statusDetail;432 } else {433 out.ncStatusCode = 400;434 out.payload.error = matrixProduct.result;435 }436 }437 } else {438 out.ncStatusCode = 500;439 out.payload.error = matrixProduct.result;440 }441 } else {442 out.ncStatusCode = 204;443 }444 } else {445 out.ncStatusCode = 204;446 }447 }448 async function handleError(error) {449 if (error.response) {450 let err = String(error.response.body);451 if (err.indexOf("soapenv:Fault") !== -1) {452 if (err.indexOf("platformFaults:exceededConcurrentRequestLimitFault") !== -1) {453 logError(`Concurrency Request Limit Exceeded: ${err}`);454 out.ncStatusCode = 429;455 out.payload.error = error;456 } else if (err.indexOf("platformFaults:exceededRequestLimitFault") !== -1) {457 logError(`Request Limit Exceeded: ${err}`);458 out.ncStatusCode = 429;459 out.payload.error = error;460 } else {461 logError(`SOAP Fault Found: ${err}`);462 out.ncStatusCode = 400;463 out.payload.error = error;464 }465 } else {466 out.ncStatusCode = 500;467 out.payload.error = error;468 }469 } else {470 out.payload.error = error;471 out.ncStatusCode = out.ncStatusCode || 500;472 }473 }474}...
smr.js
Source:smr.js
1var MatrixProduct;2var Regression3var multiply;4var numeric = require('numeric')5function MatrixProduct(options) {6 this.product = new Array(options.numRows)7 for(var r = 0; r < options.numRows; r++) {8 var row = new Array(options.numColumns)9 this.product[r] = row10 for(var c = 0; c < options.numColumns; c++)11 row[c] = 012 }13}14MatrixProduct.prototype.addRowAndColumn = function(options) {15 for(var c = 0; c < options.lhsColumn.length; c++)16 for(var r = 0; r < options.rhsRow.length; r++)17 this.product[c][r] += options.lhsColumn[c] * options.rhsRow[r]18}19MatrixProduct.prototype.push = MatrixProduct.prototype.addRowAndColumn20function Regression(options) {21 if(!options)22 throw new Error('missing options')23 if(!('numX' in options))24 throw new Error(25 'you must give the width of the X dimension as the property numX')26 if(!('numY' in options))27 throw new Error(28 'you must give the width of the X dimension as the property numY')29 this.transposeOfXTimesX = new MatrixProduct({30 numRows: options.numX,31 numColumns: options.numX32 })33 this.transposeOfXTimesY = new MatrixProduct({34 numRows: options.numX,35 numColumns: options.numY36 })37}38Regression.prototype.addObservation = function(options) {39 if(!(options.x instanceof Array) || !(options.y instanceof Array))40 throw new Error('x and y must be given as arrays')41 this.transposeOfXTimesX.addRowAndColumn({42 lhsColumn: options.x,43 rhsRow: options.x44 })45 this.transposeOfXTimesY.addRowAndColumn({46 lhsColumn: options.x,47 rhsRow: options.y48 })49 // Adding an observation invalidates our coefficients.50 delete this.coefficients51}52Regression.prototype.push = Regression.prototype.addObservation53Regression.prototype.calculateCoefficients = function() {54 var xTx = this.transposeOfXTimesX.product55 var xTy = this.transposeOfXTimesY.product56 var inv = numeric.inv(xTx)57 return this.coefficients = numeric.dot(inv, xTy)58}59Regression.prototype.calculate = Regression.prototype.calculateCoefficients60// Hypothesize a particular row of dependent variables61// from a row of independent variables.62// Lazily recalculate coefficients if necessary.63Regression.prototype.hypothesize = function(options) {64 if(!options)65 throw new Error('missing options')66 if(!(options.x instanceof Array))67 throw new Error('x property must be given as an array')68 if(!this.coefficients) this.calculateCoefficients()69 var hypothesis = []70 for(var x = 0; x < this.coefficients.length; x++) {71 var coefficientRow = this.coefficients[x]72 for(var y = 0; y < coefficientRow.length; y++)73 hypothesis[y] = (hypothesis[y] || 0) + coefficientRow[y] * options.x[x]74 }75 return hypothesis76}77function multiply(lhs, rhs) {78 var options = { numRows: lhs.length, numColumns: rhs[0].length }79 var streamingProduct = new MatrixProduct(options)80 for(var x = 0; x < rhs.length; x++) {81 var lhsColumn = []82 // Get the xth column of lhs.83 for(var r = 0; r < lhs.length; r++)84 lhsColumn.push(lhs[r][x])85 // Get the xth row of rhs.86 var rhsRow = rhs[x]87 streamingProduct.addRowAndColumn({88 lhsColumn: lhsColumn,89 rhsRow: rhsRow90 })91 }92 return streamingProduct.product...
Using AI Code Generation
1var wptools = require('wptools');2var matrix1 = [[1,2,3],[4,5,6],[7,8,9]];3var matrix2 = [[1,2,3],[4,5,6],[7,8,9]];4var matrix3 = wptools.matrixProduct(matrix1, matrix2);5console.log(matrix3);6### matrixProduct(matrix1, matrix2)7var wptools = require('wptools');8var matrix1 = [[1,2,3],[4,5,6],[7,8,9]];9var matrix2 = [[1,2,3],[4,5,6],[7,8,9]];10var matrix3 = wptools.matrixProduct(matrix1, matrix2);11console.log(matrix3);12### matrixTranspose(matrix)13var wptools = require('wptools');14var matrix = [[1,2,3],[4,5,6],[7,8,9]];15var matrix1 = wptools.matrixTranspose(matrix);16console.log(matrix1);17### matrixInverse(matrix)18var wptools = require('wptools');19var matrix = [[1,2,3],[4,5,6],[7,8,9]];20var matrix1 = wptools.matrixInverse(matrix);21console.log(matrix1);22### matrixDeterminant(matrix)23var wptools = require('wptools');24var matrix = [[1,2,3],[4,5,6],[7,8,9]];25var matrix1 = wptools.matrixDeterminant(matrix);26console.log(matrix1);
Using AI Code Generation
1var wpt = require('wpt.js');2var matrix1 = [[1,2],[3,4]];3var matrix2 = [[5,6],[7,8]];4var matrix = wpt.matrixProduct(matrix1,matrix2);5var matrix = wpt.matrixTranspose(matrix1);6var matrix = wpt.matrixInverse(matrix1);7var det = wpt.matrixDeterminant(matrix1);8var matrix = wpt.matrixGaussianElimination(matrix1);9var matrix = wpt.matrixGaussianEliminationWithPivoting(matrix1);10var matrix = wpt.matrixLUDecomposition(matrix1);11var matrix = wpt.matrixCholeskyDecomposition(matrix1);12var matrix = wpt.matrixQRDecomposition(matrix1);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!