Place order, clear Cart in Nop Commerce 4 - shopping-cart

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 });
}

Related

Unit Test for Apex Trigger that Concatenates Fields

I am trying to write a test for a before trigger that takes fields from a custom object and concatenates them into a custom Key__c field.
The trigger works in the Sandbox and now I am trying to get it into production. However, whenever I try and do a System.assert/assertEquals after I create a purchase and perform DML, the value of Key__c always returns null. I am aware I can create a flow/process to do this, but I am trying to solve this with code for my own edification. How can I get the fields to concatenate and return properly in the test? (the commented out asserts are what I have tried so far, and have failed when run)
trigger Composite_Key on Purchases__c (before insert, before update) {
if(Trigger.isBefore)
{
for(Purchases__c purchase : trigger.new)
{
String eventName = String.isBlank(purchase.Event_name__c)?'':purchase.Event_name__c+'-';
String section = String.isBlank(purchase.section__c)?'':purchase.section__c+'-';
String row = String.isBlank(purchase.row__c)?'':purchase.row__c+'-';
String seat = String.isBlank(String.valueOf(purchase.seat__c))?'':String.valueOf(purchase.seat__c)+'-';
String numseats = String.isBlank(String.valueOf(purchase.number_of_seats__c))?'':String.valueOf(purchase.number_of_seats__c)+'-';
String adddatetime = String.isBlank(String.valueOf(purchase.add_datetime__c))?'':String.valueOf(purchase.add_datetime__c);
purchase.Key__c = eventName + section + row + seat + numseats + adddatetime;
}
}
}
#isTest
public class CompositeKeyTest {
public static testMethod void testPurchase() {
//create a purchase to fire the trigger
Purchases__c purchase = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c=1.0,number_of_seats__c='test',add_datetime__c='test');
Insert purchase;
//System.assert(purchases__c.Key__c.getDescribe().getName() == 'testesttest1testtest');
//System.assertEquals('testtesttest1.0testtest',purchase.Key__c);
}
static testMethod void testbulkPurchase(){
List<Purchases__c> purchaseList = new List<Purchases__c>();
for(integer i=0 ; i < 10; i++)
{
Purchases__c purchaserec = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c= i+1.0 ,number_of_seats__c='test',add_datetime__c='test');
purchaseList.add(purchaserec);
}
insert purchaseList;
//System.assertEquals('testtesttest5testtest',purchaseList[4].Key__c,'Key is not Valid');
}
}
You need to requery the records after inserting them to get the updated data from the triggers/database

when I select many row of table and insert breakpoint dont show my list correctly?

when I trace code don't show city list correctly
how I can fix it ?
My code
public ActionResult GetCity(int idCountry)
{
TravelEnterAdminTemplate.Models.LG.MyJsonResult myresult = new Models.LG.MyJsonResult();
var citystable = db.Cities.Where(p => p.CountryId == idCountry).ToList();
if (citystable != null)
{
myresult.Result = true;
myresult.obj = citystable;
}
else
{
myresult.Result = false;
myresult.message = "داده ای یافت نشد";
}
return Json(myresult, JsonRequestBehavior.AllowGet);
}
This is not the error you are getting the data. There were 32 data in cities table . You just click on every node there the detail will visible

NetSuite - error closing return authorization using 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);

Sitecore change rendering datasource

Hello I would like create special page for private use for where i will be have possibility to change data source value for each rendering item.
I have created next code, but it dos't save any changes to items.
SC.Data.Database master = SC.Configuration.Factory.GetDatabase("master");
SC.Data.Items.Item itm = master.GetItem(tbPath.Text);
if (itm != null)
{
// Get the sublayout to update
//string sublayout_name = txtSublayout.Text.Trim();
//if (!string.IsNullOrEmpty(sublayout_name))
{
// Get the renderings on the item
RenderingReference[] refs = itm.Visualization.GetRenderings(SC.Context.Device, true);
if (refs.Any())
{
//var data = refs.Select(d=>d);
//refs[0].Settings.DataSource
var sb = new StringBuilder();
using (new SC.SecurityModel.SecurityDisabler())
{
itm.Editing.BeginEdit();
foreach (var d in refs)
{
if (d.Settings.DataSource.Contains("/sitecore/content/Site Configuration/"))
{
var newds = d.Settings.DataSource.Replace("/sitecore/content/Site Configuration/", "/sitecore/content/Site Configuration/" + tbLanguage.Text + "/");
// sb.AppendLine(string.Format("{0} old: {1} new: {2}<br/>", d.Placeholder, d.Settings.DataSource, newds));
d.Settings.DataSource = newds;
}
}
itm.Editing.EndEdit();
}
//lblResult.Text = sb.ToString();
}
}
}
how I can change data source ?
thanks
You're mixing up two different things in Sitecore here.
The datasource that is assigned to a rendering at run-time, when Sitecore is rendering a page
The datasource that is assigned to the presentation details of an item
The simplest approach to achieve what I think you're trying to achieve, would be this.
Item itm = database.GetItem("your item");
string presentationXml = itm["__renderings"];
itm.Editing.BeginEdit();
presentationXml.Replace("what you're looking for", "what you want to replace it with");
itm.Editing.EndEdit();
(I've not compiled and run this code, but it should pretty much work as is)
You are not saving the changes to the field.
Use the LayoutDefinitation class to parse the layout field, and foreach all the device definition, and rendering definitions.
And finaly commit the LayoutDifinition to the layout field.
SC.Data.Items.Item itm = master.GetItem(tbPath.Text);
var layoutField = itm.Fields[Sitecore.FieldIDs.LayoutField];
LayoutDefinition layout = LayoutDefinition.Parse(layoutField.Value);
for (int i = 0; i < layout.Devices.Count; i++)
{
DeviceDefinition device = layout.Devices[i] as DeviceDefinition;
for (int j = 0; j < device.Renderings.Count; j++)
{
RenderingDefinition rendering = device.Renderings[j] as RenderingDefinition;
rendering.Datasource = rendering.DataSource.Replace("/sitecore/content/Site Configuration/",
"/sitecore/content/Site Configuration/" + tbLanguage.Text + "/");
}
}
itm.Editing.BeginEdit();
var xml =layout.ToXml()
layoutField.Value = xml;
itm.Editing.EndEdit();
The code is not testet, but are changed from something i have in production to replace datasources on a copy event
If any one looking for single line Linq : (Tested)
var layoutField = item.Fields[Sitecore.FieldIDs.LayoutField];
if (layoutField != null)
{
var layout = LayoutDefinition.Parse(layoutField.Value);
if (layout != null)
{
foreach (var rendering in layout.Devices.Cast<DeviceDefinition>()
.SelectMany
(device => device.Renderings.Cast<RenderingDefinition>()
.Where
(rendering => rendering.ItemID == "RenderingYoulooking")))
{
rendering.Datasource = "IDYouWantToInsert";
}
layoutField.Value = layout.ToXml();
}
}

subsonic 3.0 active record update

I am able to retrieve database values and insert database values, but I can't figure out what the Update() syntax should be with a where statement.
Environment -> ASP.Net, C#
Settings.ttinclude
const string Namespace = "subsonic_db.Data";
const string ConnectionStringName = "subsonic_dbConnectionString";
//This is the name of your database and is used in naming
//the repository. By default we set it to the connection string name
const string DatabaseName = "subsonic_db";
Retreive example
var product = equipment.SingleOrDefault(x => x.id == 1);
Insert Example
equipment my_equipment = new equipment();
try
{
// insert
my_equipment.parent_id = 0;
my_equipment.primary_id = 0;
my_equipment.product_code = product_code.Text;
my_equipment.product_description = product_description.Text;
my_equipment.product_type_id = Convert.ToInt32(product_type_id.SelectedItem.Value);
my_equipment.created_date = DateTime.Now;
my_equipment.serial_number = serial_number.Text;
my_equipment.Save();
}
catch (Exception err)
{
lblError.Text = err.Message;
}
Edit: Think that I was just too tired last night, it is pretty easy to update. Just use the retrieve function and use the Update() on that.
var equip = Equipment.SingleOrDefault(x => x.id == 1);
lblGeneral.Text = equip.product_description;
equip.product_description = "Test";
equip.Update();
Resolved. View answer above.