Iterating through a table in Gauge - getgauge

I am new to Gauge. I am trying to loop through csv file and save the data on a website. Can any one guide through how to manipulate the table object.
Spec
* dt <table:D:/work/2019/gauge-app/specs/data.csv>
Step Impl (JS)
step("dt <data>", async (data) => {
var row;
for(var i=0;i<data.length;i++){
row=data[i];
await write(row[0].toString(),into(textField({id:"name"})));
await write(row[1],into(inputField({id:"roll"})));
await waitFor(2000);
await press("Enter");
}
});

I got it working with this.
table:D:/work/2019/gauge-app/specs/data.csv
##add members
* write <name> into "principal_search"
* check "membership[user_ids][]"
* check "membership[role_ids][]" value <role>
* click button "commit"

Related

On an afterSubmit when we creating a copy of one inventory item (name with '-c') ,The original ID of item link should come in a field on a copy order

I tried this above, here I am getting a null value only from my previous record.
Kindly give some guidance to solve my questions.
thanks in advance.
/**
*#NApiVersion 2.0
*#NScriptType UserEventScript
*/
define(["N/url", "N/record", "N/runtime"], function (url, record, runtime) {
function afterSubmit(context){
var recordobj = context.newRecord;
var prevItemrecord= context.oldRecord;
var Itemname = recordobj.getValue({fieldId:'itemid'});
var prevItemname = prevItemrecord.getValue({fieldId : 'itemid'});
var Type=context.type;
var checkbox=recordobj.getValue({fieldId:'custitem17'});
if(Type== context.UserEventType.CREATE)
if((Itemname=prevItemname+'-c')&&(checkbox=true))
record.submitFields({
type: recordobj.type,
id: recordobj.id,
values:{custitem_item_link:prevItemname}
});
}
return{
afterSubmit:afterSubmit
}
});
This is my code
On create there is no old record.
Since you are trying to update the same record as was just created you are better off having this in a beforeSubmit event script
if((Itemname=prevItemname+'-c')&&(checkbox=true)) this is an error
if((Itemname == prevItemname+'-c') && checkbox) is more what you need
If you are trying to capture a copy operation you can set that up in the beforeLoad event that you use in the beforeSubmit event.
function beforeLoad(ctx){
if(ctx.type == ctx.UserEventType.COPY){
if(ctx.form){
ctx.form.addField({
id:'custpage_original_item',
label:'Copied Item',
type:ui.FieldType.SELECT,
source:'item'
}).updateDisplayType({
displayType:ui.FieldDisplayType.HIDDEN
}).defaultValue = ctx.request.parameters.id;
// your naming makes me wonder if you are trying to link to the
// source item rather than just saving a reference to the source
// item's name
/*
* Using the original item's name like below is closer to what you
* posted but I think by the time the script runs the itemid field
* has been cleared.
* ctx.form.addField({
* id:'custpage_original_item_name',
* label:'Copied Item Name',
* type:ui.FieldType.TEXT
* }).updateDisplayType({
* displayType:ui.FieldDisplayType.HIDDEN
* }).defaultValue = ctx.newRecord.getValue({fieldId:'itemid'});
*/
}
}
}
function beforeSubmit(ctx){
if(ctx.type == ctx.UserEventType.CREATE){
const itemRec = ctx.newRecord;
if(itemRec.getValue({fieldId:'custitem17'})){
const sourceId = itemRec.getValue({fieldId:'custpage_original_item'})
if(sourceId){
itemRec.setValue({
fieldId:'custitem_item_link:prevItemname',
value:sourceId
});
/* or use a search function to look up the original item's name
* and then test the new item's name.
*/
}
}
}
}

MS Graph API returns 500 when I try to request groups

So I am developing a sharepoint webpart where I need to check if a user is in an AD group. Now here is the odd part the MS Graph query I need to you for that is:
https://graph.microsoft.com/v1.0/me/transitiveMemberOf/microsoft.graph.group?$count=true
And that is the exact Query that my WP sends out, but it returns a 500 error message. Now I thought I had permissions missing, but the Explorer says I do not need any.
Here is my GraphService that handles MS Graph:
import { MSGraphClient } from '#microsoft/sp-http';
import * as MicrosoftGraph from '#microsoft/microsoft-graph-types';
import { WebPartContext } from "#microsoft/sp-webpart-base";
/**
* The class that handles the MS Graph API calls
*/
export default class GraphService {
/**
* The MS Graph client with does the calls
*/
private _client:MSGraphClient;
/**
* Sets the client for the Graph API, needs to be called before the class can be used
* #param context The context of the WP
*/
public async setClient(context:WebPartContext) {
this._client = await context.msGraphClientFactory.getClient();
}
/**
* Checks to see if a user belongs in a user group or not
* #param groupName The group name with we want to check
*/
public async checkCurrentUserGroup(groupName:string) {
const rawData = await this._client.api('/me/transitiveMemberOf/microsoft.graph.group').count(true).get();
const arr = rawData.value.filter(i => i.displayName == groupName);
return !!arr.length;
}
/**
* Returns the users from AD who have a manager and whom companyName is a specific company name
* #param companyName The company name to whom the users need to belong to
*/
public async getUsers(companyName:string):Promise<any[]> {
const rawData = await this._client.api('/users').filter('accountEnabled eq true').expand('manager').select('displayName,companyName,mail,department,jobTitle').get();
//need to do manual filtering, becuase you can't user filter on the "companyName" field and you can't search and expand at the same time without returing everything
const filteredData = rawData.value.filter(i => i.companyName == companyName && i.manager);
//remaps the data to IUserModel
const ret:any[] = filteredData.map(i => <any>{
name: i.displayName,
id: 0,
email: i.mail,
manager: i.manager.displayName,
managerEmail: i.manager.mail,
managerId: 0,
hasDiscussionForm: false,
department: i.department,
position: i.jobTitle
});
return ret;
}
}
The problem then is that the method checkCurrentUserGroup returns 500.
I've given the following permissions to the wp:
Group.Read.All
Directory.Read.All
User.Read
The getUsers method works as expected.
In the MS Graph Explorer the query works just fine. What am I missing?
According to the document the request header must have ConsistencyLevel and eventual header and please make sure to pass the request header and please refer to this document for more information
let res = await client.api('/users/{id}/transitiveMemberOf/microsoft.graph.group')
.header('ConsistencyLevel','eventual')
.search('displayName:tier')
.select('displayName,id')
.orderby('displayName ')
.get();

"SuiteScript 2.0 entry point scripts must implement one script type function" Error

I'm trying to upload this code to NetSuite
/**
* #NApiVersion 2.0
* #NScriptType ClientScript
* #NModuleScope SameAccount
*/
define(['N/ui/dialog'],
function(dialog){
/**
* Validation function to be executed when sublist line is committed.
*
* #param {Object} context
* #param {Record} context.currentRecord - Current form record
* #param {string} context.sublistId - Sublist name
*
* #returns {boolean} Return true if sublist line is valid
*
* #since 2015.2
*/
function validadeRate(context){
try{
var currentRecord = context.currentRecord
var sublistName = context.sublistId
if(sublistname ==='expense'){
var categ = CurrentRecord.getCurrentSublistValue({
sublistId: sublistName,
fieldId: 'category'
})
if ((categ = 259) && (rate != 0.819)){
var currIndex = currentRecord.getCurrentSublistIndex({
sublistId: sublistName
})
currIndex +=1
var options = {
title : 'Rate Incorreto!',
message:'Por favor, verifique o valor informado no campo Rate na linha ' + currIndex + '.',
}
dialog.alert(options).then(function (result) { }).catch(function(result){})
return false
}
}
return true
}
catch(ex){
log.error('validateLine: ', ex.message)
}
}
return {
validadeRate : validadeRate
}
});
But I'm getting this error when I'm trying to upload to file to Netsuite:
Notice
SuiteScript 2.0 entry point scripts must implement one script type function.*
This is part of a function that will validade the rate for one expense category.
How can I solve this?
thanks in advance!
This is NetSuite's 'Entry Point Script Validation' saying that the script is invalid because it doesn't include one of the predefined entry point (event) functions. These functions are:
fieldChanged
lineInit
pageInit
postSourcing
saveRecord
sublistChanged
validateDelete
validateField
validateInsert
validateLine
You can work around this validation and upload the script by adding one of those entry points, even if it does nothing. For example, inside your function (dialog) function you can add a pageInit() function:
function pageInit(scriptContext) {}
and change your return block to:
return {
validadeRate : validadeRate,
pageInit: pageInit
}
Now it has a valid entry point and the validation should pass.
However, there may be an even easier way. It appears (going by the JSDoc block), that your validadeRate function is supposed to be triggered each time a sublist line is added. This is exactly what the validateLine entry point is for. So you could just change the key in your return block to "validateLine"
return {
validateLine: validadeRate
}
and NetSuite would know to call validadeRate each time a line is added.
You have specified this as a Client Script module, but have not assigned a handler to any of the Client Script entry points. Read the Help document SuiteScript 2.0 Client Script Entry Points and API, and implement any one of the entry points in your module.
Change return function as below. and test once.
return
{
validateLine : validadeRate
}

NetSuite Create Transfer Order from Sales Order

I am trying to write a script that will create a new transfer order from a sales order, copying all of the lines in the process. I have the script written, but I am getting an error that "define" is not defined. This script is modified from another script, so it is possible that I missed something. I am new to scripting, so I would appreciate any help and could do without criticism (even if my script is complete garbage).
/**
***************** ALEM ********************
* After Submit User Event script running on Sales Orders. Generates a TO.
* Version Date Author Remarks
* 1.0 9 Jan madams Initial Create
*/
/**
* #NApiVersion 2.0
* #NScriptType UserEventScript
* #NModuleScope Public
*
*/
define(['N/record',], function (record) {
function afterSubmit(context) {
if(context.type == 'delete'){
log.debug('Exiting script', '...');
return;
}
try{
var so = record.load({
type:'salesorder',
id:context.newRecord.id
});
var so_items = so.getLineCount({sublistId:'item'});
// Create new Transfer Order if Record is On Create.
var to_record = record.create({
type:'transferorder',
isDynamic:true
});
to_record.setValue({fieldId:'customform', value:136});
to_record.setValue({fieldId:'class', value:so.getValue('class')});
to_record.setValue({fieldId:'transferlocation',
value:so.getValue('location')});
setLineItemsOnTO(so_items, to_record, so);
to_record.setValue({fieldId:'custbody_related_record',
value:context.newRecord.id});
so.setValue({fieldId:'custbody_related_record',
value:to_record.save()});
so.setValue({fieldId:'orderstatus',value:'B'});
so.save({ignoreMandatoryFields:true});
} catch(e){
log.debug('Error Loading Record' + context.newRecord.id, e);
return;
}
}
return {
afterSubmit: afterSubmit
}
function setLineItemsOnTO(so_items, to_record, so){
for(var i=0; i<so_items; i++){
to_record.selectNewLine({sublistId:'item'});
to_record.setCurrentSublistValue({
sublistId:'item',
fieldId:'item',
value:so.getSublistValue({
sublistId:'item',
fieldId:'item',
line:i
})
});
to_record.setCurrentSublistValue({
sublistId:'item',
fieldId:'quantity',
value:so.getSublistValue({
sublistId:'item',
fieldId:'quantity',
line:i
})
});
to_record.commitLine({sublistId:'item'});
}
}
});
Did NetSuite import the script as SuiteScript 2.0? It probably imported the script as SS1.0.
The comment block containing #NApiVersion 2.0 needs to be the first comment block in the file. NetSuite looks for that block only at the top of the file to identify SS2.0 scripts.

Delete Documents from CosmosDB based on condition through Query Explorer

What's the query or some other quick way to delete all the documents matching the where condition in a collection?
I want something like DELETE * FROM c WHERE c.DocumentType = 'EULA' but, apparently, it doesn't work.
Note: I'm not looking for any C# implementation for this.
This is a bit old but just had the same requirement and found a concrete example of what #Gaurav Mantri wrote about.
The stored procedure script is here:
https://social.msdn.microsoft.com/Forums/azure/en-US/ec9aa862-0516-47af-badd-dad8a4789dd8/delete-multiple-docdb-documents-within-the-azure-portal?forum=AzureDocumentDB
Go to the Azure portal, grab the script from above and make a new stored procedure in the database->collection you need to delete from.
Then right at the bottom of the stored procedure pane, underneath the script textarea is a place to put in the parameter. In my case I just want to delete all so I used:
SELECT c._self FROM c
I guess yours would be:
SELECT c._self FROM c WHERE c.DocumentType = 'EULA'
Then hit 'Save and Execute'. Viola, some documents get deleted. After I got it working in the Azure Portal I switched over the Azure DocumentDB Studio and got a better view of what was happening. I.e. I could see I was throttled to deleting 18 a time (returned in the results). For some reason I couldn't see this in the Azure Portal.
Anyway, pretty handy even if limited to a certain amount of deletes per execution. Executing the sp is also throttled so you can't just mash the keyboard. I think I would just delete and recreate the Collection unless I had a manageable number of documents to delete (thinking <500).
Props to Mimi Gentz #Microsoft for sharing the script in the link above.
HTH
I want something like DELETE * FROM c WHERE c.DocumentType = 'EULA'
but, apparently, it doesn't work.
Deleting documents this way is not supported. You would need to first select the documents using a SELECT query and then delete them separately. If you want, you can write the code for fetching & deleting in a stored procedure and then execute that stored procedure.
I wrote a script to list all the documents and delete all the documents, it can be modified to delete the selected documents as well.
var docdb = require("documentdb");
var async = require("async");
var config = {
host: "https://xxxx.documents.azure.com:443/",
auth: {
masterKey: "xxxx"
}
};
var client = new docdb.DocumentClient(config.host, config.auth);
var messagesLink = docdb.UriFactory.createDocumentCollectionUri("xxxx", "xxxx");
var listAll = function(callback) {
var spec = {
query: "SELECT * FROM c",
parameters: []
};
client.queryDocuments(messagesLink, spec).toArray((err, results) => {
callback(err, results);
});
};
var deleteAll = function() {
listAll((err, results) => {
if (err) {
console.log(err);
} else {
async.forEach(results, (message, next) => {
client.deleteDocument(message._self, err => {
if (err) {
console.log(err);
next(err);
} else {
next();
}
});
});
}
});
};
var task = process.argv[2];
switch (task) {
case "listAll":
listAll((err, results) => {
if (err) {
console.error(err);
} else {
console.log(results);
}
});
break;
case "deleteAll":
deleteAll();
break;
default:
console.log("Commands:");
console.log("listAll deleteAll");
break;
}
And if you want to do it in C#/Dotnet Core, this project may help: https://github.com/lokijota/CosmosDbDeleteDocumentsByQuery. It's a simple Visual Studio project where you specify a SELECT query, and all the matches will be a) backed up to file; b) deleted, based on a set of flags.
create stored procedure in collection and execute it by passing select query with condition to delete. The major reason to use this stored proc is because of continuation token which will reduce RUs to huge extent and will cost less.
##### Here is the python script which can be used to delete data from Partitioned Cosmos Collection #### This will delete documents Id by Id based on the result set data.
Identify the data that needs to be deleted before below step
res_list = "select id from id_del"
res_id = [{id:x["id"]}
for x in sqlContext.sql(res_list).rdd.collect()]
config = {
"Endpoint" : "Use EndPoint"
"Masterkey" : "UseKey",
"WritingBatchSize" : "5000",
'DOCUMENTDB_DATABASE': 'Database',
'DOCUMENTDB_COLLECTION': 'collection-core'
};
for row in res_id:
# Initialize the Python DocumentDB client
client = document_client.DocumentClient(config['Endpoint'], {'masterKey': config['Masterkey']})
# use a SQL based query to get documents
## Looping thru partition to delete
query = { 'query': "SELECT c.id FROM c where c.id = "+ "'" +row[id]+"'" }
print(query)
options = {}
options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 1000
result_iterable = client.QueryDocuments('dbs/Database/colls/collection-core', query, options)
results = list(result_iterable)
print('DOCS TO BE DELETED : ' + str(len(results)))
if len(results) > 0 :
for i in range(0,len(results)):
# print(results[i]['id'])
docID = results[i]['id']
print("docID :" + docID)
options = {}
options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 1000
options['partitionKey'] = docID
client.DeleteDocument('dbs/Database/colls/collection-core/docs/'+docID,options=options)
print ('deleted Partition:' + docID)

Resources