NetSuite - error closing return authorization using web services - web-services

Within NetSuite when trying to close out Return Authorization line items i receive the following error message:
INSUFFICIENT_PERMISSION
"You do not have permissions to set a value for element item.quantityreceived due to one of the following reasons: 1) The field is read-only; 2) An associated feature is disabled; 3) The field is available either when a record is created or updated, but not in both cases."
Here is the code:
//Pull down the RA in order to work with the line items in question
RecordRef rec = new RecordRef();
rec.internalId = internalId;
rec.type = RecordType.returnAuthorization;
rec.typeSpecified = true;
ReadResponse response = _service.get(rec);
//create the object from the response record returned
ReturnAuthorization ra = (ReturnAuthorization)response.record;
//cancel the order by updating the qty of each item to zero.
WriteResponse res = null;
ReturnAuthorizationItem[] raItemList = ra.itemList.item;
for (int lineCounter = 0; lineCounter < raItemList.Length; lineCounter++)
{
//only if the qty received is zero are we closing out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0)
{
raItemList[lineCounter].quantity = 0;
raItemList[lineCounter].quantitySpecified = true;
}
}
//create a new object and add all the changes in order to update the order lines
ReturnAuthorization updRa = new ReturnAuthorization();
updRa.internalId = internalId;
updRa.itemList = new ReturnAuthorizationItemList();
updRa.itemList.item = new ReturnAuthorizationItem[raItemList.Length];
updRa.itemList.item = raItemList;
res = _service.update(updRa);
I am trying to update the line quantity to zero, which in affect will close the Return Authorization if everything has been zeroed out. Question is how do i correct this permissions issue in order to run this update. I have tried setting other fields on this same call. No matter which field i try and update i get the same error message. This is running under an admin account and all permissions look fine as far as i can see. In fact i am running this very same logic against the SaleOrder object to close out Sales Orders with no issues.
Any help would be much appreciated.
Thanks,
Billy

You can't directly edit that line item field. That field is maintained by Netsuite and reflects Item Receipts received against the RA.
If you want to close the RA without receiving just set the line item column field "Closed" to true.

After looking at this a little closer here is the solution:
Replace the if statement in the loop with this:
//only if the qty received and returned are zero do we close out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0 && raItemList[lineCounter].quantityBilled == 0)
{
raItemList[lineCounter].quantity = 0;
raItemList[lineCounter].quantitySpecified = true;
raItemList[lineCounter].isClosed = true;
raItemList[lineCounter].isClosedSpecified = true;
raItemList[lineCounter].quantityReceivedSpecified = false;
raItemList[lineCounter].quantityBilledSpecified = false;
raItemList[lineCounter].costEstimateSpecified = false;
}
else
{
raItemList[lineCounter].quantityReceivedSpecified = false;
raItemList[lineCounter].quantityBilledSpecified = false;
raItemList[lineCounter].costEstimateSpecified = false;
}
I am guessing that the fields i had to specific as false are fields that cannot be edited, hence the need to disclude them from the update.

This is a better sample. Note the comment re orderline
/Pull down the RA in order to work with the line items in question
RecordRef rec = new RecordRef();
rec.internalId = internalId;
rec.type = RecordType.returnAuthorization;
rec.typeSpecified = true;
ReadResponse response = _service.get(rec);
//create the object from the response record returned
ReturnAuthorization ra = (ReturnAuthorization)response.record;
//cancel the order by updating the qty of each item to zero.
WriteResponse res = null;
ReturnAuthorizationItem[] raItemList = ra.itemList.item;
ReturnAuthorization updRa = new ReturnAuthorization();
updRa.internalId = internalId;
updRa.itemList = new ReturnAuthorizationItemList();
ReturnAuthorizationItem[] updateItems = new ReturnAuthorizationItem[raItemList.Length];
for (int lineCounter = 0; lineCounter < raItemList.Length; lineCounter++)
{
updateItems[lineCounter].line = raItemList[lineCounter].line; // you'll need to test this. Setting only the line should result in no changes to the RA line items that are not to be closed. use the &xml=T view before and after to make sure orderline (hidden) is still populated properly.
//only if the qty received is zero are we closing out the item(setting qty to zero)
if (raItemList[lineCounter].quantityReceived == 0)
{
updateItems[lineCounter].isClosed = true;
// raItemList[lineCounter].quantitySpecified = true; // is quantitySpecified a field? it wasn't as of the 2012.2 endpoint
}
}
//create a new object and add all the changes in order to update the order lines
updRa.itemList.item = updateItems;
res = _service.update(updRa);

Related

Place order, clear Cart in Nop Commerce 4

How can I Place an order from the cart and clear the cart?
I want to do this in my own controller and not by the checkout page.
I try to use this, but it doesn't work
//place order
var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
if (processPaymentRequest == null)
{
//Check whether payment workflow is required
if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
return RedirectToRoute("CheckoutPaymentInfo");
processPaymentRequest = new ProcessPaymentRequest();
}
GenerateOrderGuid(processPaymentRequest);
processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
processPaymentRequest.PaymentMethodSystemName =
_genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer,
NopCustomerDefaults.SelectedPaymentMethodAttribute,
_storeContext.CurrentStore.Id);
HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo",
processPaymentRequest);
var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
You can use PlaceOrder method in IOrderProcessingService to place an order. CheckoutController also uses this method. For using it, you have to create a ProcessPaymentRequest by yourself. here is a sample code for such a task (I use the code placed in the CheckoutController which doing the same job):
var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
if (processPaymentRequest == null)
{
//Check whether payment workflow is required
if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
return RedirectToRoute("CheckoutPaymentInfo");
processPaymentRequest = new ProcessPaymentRequest();
}
//prevent 2 orders being placed within an X seconds time frame
if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
//place order
processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
SystemCustomerAttributeNames.SelectedPaymentMethod,
_genericAttributeService, _storeContext.CurrentStore.Id);
//____this is main line of code____
var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
if (placeOrderResult.Success)
{
HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", null);
//do payment process:
var postProcessPaymentRequest = new PostProcessPaymentRequest
{
Order = placeOrderResult.PlacedOrder
};
_paymentService.PostProcessPayment(postProcessPaymentRequest);
if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
{
//redirection or POST has been done in PostProcessPayment
return Content("Redirected");
}
return RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id });
}

Alfresco WS Client API - WSSecurityException when using fetchMore method

Can someone tell me what's wrong with my code here... I'm always getting this exception on the first call to contentService.read(...) after the first fetchMore has occurred.
org.apache.ws.security.WSSecurityException: The security token could not be authenticated or authorized
// Here we're setting the endpoint address manually, this way we don't need to use
// webserviceclient.properties
WebServiceFactory.setEndpointAddress(wsRepositoryEndpoint);
AuthenticationUtils.startSession(wsUsername, wsPassword);
// Set the batch size in the query header
int batchSize = 5000;
QueryConfiguration queryCfg = new QueryConfiguration();
queryCfg.setFetchSize(batchSize);
RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();
repositoryService.setHeader(new RepositoryServiceLocator().getServiceName().getNamespaceURI(), "QueryHeader", queryCfg);
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
String luceneQuery = buildLuceneQuery(categories, properties);
// Call the repository service to do search based on category
Query query = new Query(Constants.QUERY_LANG_LUCENE, luceneQuery);
// Execute the query
QueryResult queryResult = repositoryService.query(STORE, query, true);
String querySession = queryResult.getQuerySession();
while (querySession != null) {
ResultSet resultSet = queryResult.getResultSet();
ResultSetRow[] rows = resultSet.getRows();
for (ResultSetRow row : rows) {
// Read the content from the repository
Content[] readResult = contentService.read(new Predicate(new Reference[] { new Reference(STORE, row.getNode().getId(), null) },
STORE, null), Constants.PROP_CONTENT);
Content content = readResult[0];
[...]
}
// Get the next batch of results
queryResult = repositoryService.fetchMore(querySession);
// process subsequent query results
querySession = queryResult.getQuerySession();
}

Command "timing out" during Sitecore automated item creation

I have a command that I've added to a "national" node in the Sitecore Editor. The command generates a list of the 50 state nodes beneath it. It then goes through the state nodes (1 at a time) and generates a list of local nodes under each state node. Within the lists of local nodes, I iterate through them and check if the new item exists - if it does not, I add (create) it as a child under the local node. Ultimately, there are nearly 300 local items that are being added during the course of this command.
Is there a more efficient way to do this (fast query to get the 300 local nodes into one list, then check if the item exists, and create it)? If so, I'm not sure how to do that...
I'm not sure what is the most costly part of the operation. Ultimately, I'm still doing up to 300 separate queries to check if it's there, followed by insert statements, so that may still take a while to run. If so, which setting in web config will increase the applicable "timeout" setting in Sitecore? The sample structure is as follows:
//Derive the template from the name of the item (page) that was passed in - this assumes that the template name and the item name are the same
Sitecore.Data.Database database = Sitecore.Data.Database.GetDatabase("master");
TemplateItem contentPageTemplate = database.SelectSingleItem("fast:/sitecore/Templates/User Defined/Home/Pages/Local Site/" + newPage);
Sitecore.Data.Items.Item[] stateNodes = null;
Sitecore.Data.Items.Item[] localNodes = null;
Item localHomePage = null;
Item newLocalPage = null;
int webBusinessID = 0;
string ID = "";
WebBusiness business;
//Get all of the immediate child nodes (state pages) under the "parent" node ("National Locations") - and put them into a list or array
stateNodes = database.SelectItems("fast:/sitecore/content/Home/National Locations/*");
for (int i = 0; i < stateNodes.Length; i++)
{
if (stateNodes[i].Children.Count > 0)
{
localNodes = database.SelectItems("fast:/sitecore/content/Home/National Locations/" + stateNodes[i].Fields["State Abbreviation"].ToString() + "/*");
}
else
{
//Do nothing
}
for (int j = 0; j < localNodes.Length; j++)
{
localHomePage = localNodes[j];
if (localHomePage.Publishing.IsPublishable(DateTime.Now, false) == true)
{
//If the new page does not exist, create it
if (localHomePage.Children[newPage] == null)
{
newLocalPage = localHomePage.Add(newPage, contentPageTemplate);
counter = counter + 1;
}
else
{
//Additional business logic
}
}
}
}
Unless I'm missing logic/code you don't have there, I think you can simply trim this down to one query to get to the local nodes by changing the XPath:
localNodes = database.SelectItems("fast:/sitecore/content/Home/National Locations/*/*");
The change is to get all immediate sub-items of the immediate sub-items of "National Locations"

Dynamics GP Web Services: SalesInvoice Creation with Lot Allocation

I'm trying to use the following code to create a new SalesInvoice based on an existing SalesOrder:
SalesInvoice invoice = new SalesInvoice();
invoice.DocumentTypeKey = new SalesDocumentTypeKey { Type = SalesDocumentType.Invoice };
invoice.CustomerKey = originalOrder.CustomerKey;
invoice.BatchKey = originalOrder.BatchKey;
invoice.Terms = new SalesTerms { DiscountTakenAmount = new MoneyAmount { Value = 0, Currency = "USD", DecimalDigits = 2 }, DiscountAvailableAmount = new MoneyAmount { Value = 0, Currency = "USD", DecimalDigits = 0 } };
invoice.OriginalSalesDocumentKey = originalOrder.Key;
List<SalesInvoiceLine> lineList = new List<SalesInvoiceLine>();
for (int i = 0; i < originalOrder.Lines.Length; i++)
{
SalesInvoiceLine line = new SalesInvoiceLine();
line.ItemKey = originalOrder.Lines[i].ItemKey;
line.Key = new SalesLineKey { LineSequenceNumber = originalOrder.Lines[i].Key.LineSequenceNumber; }
SalesLineLot lot = new SalesLineLot();
lot.LotNumber = originalOrder.Lines[i].Lots[0].LotNumber;
lot.Quantity = new Quantity { Value = 2200 };
lot.Key = new SalesLineLotKey { SequenceNumber = originalOrder.Lines[i].Lots[0].Key.SequenceNumber };
line.Lots = new SalesLineLot[] { lot };
line.Quantity = new Quantity { Value = 2200 };
lineList.Add(line);
}
invoice.Lines = lineList.ToArray();
DynamicsWS.CreateSalesInvoice(invoice, DynamicsContext, DynamicsWS.GetPolicyByOperation("CreateSalesInvoice", DynamicsContext));
When executed, I receive the following error:
SQL Server Exception: Operation expects a parameter which was not supplied.
And the more detailed exception from the Exception Console in Dynamics:
Procedure or function 'taSopLotAuto' expects parameter '#I_vLNITMSEQ',
which was not supplied.
After a considerable amount of digging through Google, I discovered a few things.
'taSopLotAuto' is an eConnect procedure within the Sales Order Processing component that attempts to automatically fill lots. I do not want the lots automatically filled, which is why I try to fill them manually in the code. I've also modified the CreateSalesInvoice policy from Automatic lot fulfillment to Manual lot fulfillment for the GP web services user, but that didn't change which eConnect procedure was called.
'#I_vLNITMSEQ' refers to the LineSequenceNumber. The LineSequenceNumber and SequenceNumber (of the Lot itself) must match. In my case they are both the default: 16384. Not only is this parameter set in the code above, but it also appears in the SOAP message that the server attempted to process - hardly "not supplied."
I can create an invoice sans line items without a hitch, but if I add line items it fails. I do not understand why I am receiving an error for a missing parameter that is clearly present.
Any ideas on how to successfully create a SalesInvoice through Dynamics GP 10.0 Web Services?
Maybe you mess to add the line key to the lot:
lot.Key = new SalesLineKey();
lot.Key.SalesDocumentKey = new SalesDocumentKey();
lot.Key.SalesDocumentKey.Id = seq.ToString();

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.