How to duplicate an existing order (core, php) with Prestashop 1.6.x in FrontPage from client Account - My Orders? - prestashop

if i use a function in classes\duplicateOrder, found on a previous answer, everytime i refresh the page order-history, all orders from my account->orders are duplicated
the function seems to be ok, so where is the problem?
public function duplicateOrder($id_order)
{
$order = new Order($id_order);
$duplicatedOrder = $order->duplicateObject();
$orderDetailList = $order->getOrderDetailList();
foreach ($orderDetailList as $detail) {
$orderDetail = new orderDetail($detail['id_order_detail']);
$duplicatedOrderDetail = $orderDetail->duplicateObject();
$duplicatedOrderDetail->id_order = $duplicatedOrder->id;
$duplicatedOrderDetail->save();
}
$orderHistoryList = $order->getHistory(Configuration::get('PS_LANG_DEFAULT'));
foreach ($orderHistoryList as $history) {
$orderHistory = new OrderHistory($history['id_order']);
$duplicatedOrderHistory = $orderHistory->duplicateObject();
$duplicatedOrderHistory->id_order = $duplicatedOrder->id;
//$duplicatedOrderHistory->save();
}
}

Where is your call? I think you call it in a foreach that lists the commands.
Regards

in history.tpl I inserted the folowing li option after Reorder button; whenever I press the refresh (F5) the orders are multiplicated (2, 4, 8, 16 and so on)
{l s='Duplicate Order'}
the function was saved in classes\Order\Order.php

Related

Questions regarding update of table on Prestashop

I'm trying to update ps_stock_available when I modify the product on Prestashop. But it's unsuccessfull. Could you help me please ?
public function hookActionUpdateQuantity(array $params)
{
$id_product = $params['id_product'];
$product = new Product((int)$id_product);
$id_category = $product->id_category_default;
$db = \Db::getInstance();
$request_loc='SELECT location FROM `'._DB_PREFIX_.'category_location` WHERE `id_category` = '.(int)$id_category;
$location = $db->getValue($request_loc);
$request_id_stock='SELECT id_stock_available FROM `'._DB_PREFIX_.'stock_available` WHERE `id_product` = '.(int)$id_product;
$id_stock_available = $db->getValue($request_id_stock);
$result = $db->update('stock_available', array('location' => $location), '`id_stock_available` = '.(int)$id_stock_available);
}
I have written this code but it doesn't seem to work.
in order to accomplish this task I would rely to the native StockAvailable class metehods getStockAvailableIdByProductId() and setLocation() (check the classes/stock/StockAvailable.php file).
Anyway your code seems to be correct, so I would definitely check for undefined variables and/or something not working in the $db->update statement.
In case, you can change it to :
$db->execute('UPDATE '._DB_PREFIX_.'stock_available SET `location` = "'.pSQL($location).'" WHERE id_stock_available = '.(int)$id_stock_available;

Paypal Php Sdk - NotifyUrl is not a fully qualified URL Error

I have this code
$product_info = array();
if(isset($cms['site']['url_data']['product_id'])){
$product_info = $cms['class']['product']->get($cms['site']['url_data']['product_id']);
}
if(!isset($product_info['id'])){
/*
echo 'No product info.';
exit();
*/
header_url(SITE_URL.'?subpage=user_subscription#xl_xr_page_my%20account');
}
$fee = $product_info['yearly_price_end'] / 100 * $product_info['fee'];
$yearly_price_end = $product_info['yearly_price_end'] + $fee;
$fee = ($product_info['setup_price_end'] / 100) * $product_info['fee'];
$setup_price_end = $product_info['setup_price_end'] + $fee;
if(isset($_SESSION['discountcode_amount'])){
$setup_price_end = $setup_price_end - $_SESSION['discountcode_amount'];
unset($_SESSION['discountcode_amount']);
}
$error = false;
$plan_id = '';
$approvalUrl = '';
$ReturnUrl = SITE_URL.'payment/?payment_type=paypal&payment_page=process_agreement';
$CancelUrl = SITE_URL.'payment/?payment_type=paypal&payment_page=cancel_agreement';
$now = $cms['date'];
$now->modify('+5 minutes');
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
$cms['options']['plugin_paypal_clientid'], // ClientID
$cms['options']['plugin_paypal_clientsecret'] // ClientSecret
)
);
use PayPal\Api\ChargeModel;
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
use PayPal\Api\Patch;
use PayPal\Api\PatchRequest;
use PayPal\Common\PayPalModel;
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\ShippingAddress;
// Create a new instance of Plan object
$plan = new Plan();
// # Basic Information
// Fill up the basic information that is required for the plan
$plan->setName($product_info['name'])
->setDescription($product_info['desc_text'])
->setType('fixed');
// # Payment definitions for this billing plan.
$paymentDefinition = new PaymentDefinition();
// The possible values for such setters are mentioned in the setter method documentation.
// Just open the class file. e.g. lib/PayPal/Api/PaymentDefinition.php and look for setFrequency method.
// You should be able to see the acceptable values in the comments.
$setFrequency = 'Year';
//$setFrequency = 'Day';
$paymentDefinition->setName('Regular Payments')
->setType('REGULAR')
->setFrequency($setFrequency)
->setFrequencyInterval("1")
->setCycles("999")
->setAmount(new Currency(array('value' => $yearly_price_end, 'currency' => $cms['session']['client']['currency']['iso_code'])));
// Charge Models
$chargeModel = new ChargeModel();
$chargeModel->setType('SHIPPING')
->setAmount(new Currency(array('value' => 0, 'currency' => $cms['session']['client']['currency']['iso_code'])));
$paymentDefinition->setChargeModels(array($chargeModel));
$merchantPreferences = new MerchantPreferences();
// ReturnURL and CancelURL are not required and used when creating billing agreement with payment_method as "credit_card".
// However, it is generally a good idea to set these values, in case you plan to create billing agreements which accepts "paypal" as payment_method.
// This will keep your plan compatible with both the possible scenarios on how it is being used in agreement.
$merchantPreferences->setReturnUrl($ReturnUrl)
->setCancelUrl($CancelUrl)
->setAutoBillAmount("yes")
->setInitialFailAmountAction("CONTINUE")
->setMaxFailAttempts("0")
->setSetupFee(new Currency(array('value' => $setup_price_end, 'currency' => $cms['session']['client']['currency']['iso_code'])));
$plan->setPaymentDefinitions(array($paymentDefinition));
$plan->setMerchantPreferences($merchantPreferences);
// ### Create Plan
try {
$output = $plan->create($apiContext);
} catch (Exception $ex){
die($ex);
}
echo $output->getId().'<br />';
echo $output.'<br />';
Been working with paypal php sdk for some days now and my code stop working.
So i went back to basic and i am still getting the same damn error.
I am trying to create a plan for subscription but getting the following error:
"NotifyUrl is not a fully qualified URL"
I have no idea how to fix this as i dont use NotfifyUrl in my code?
Could be really nice if anyone had an idea how to fix this problem :)
Thanks
PayPal did a update to their API last night which has caused problem within their SDK.
They are sending back null values in their responses.
I MUST stress the error is not on sending the request to PayPal, but on processing their response.
BUG Report : https://github.com/paypal/PayPal-PHP-SDK/issues/1151
Pull Request : https://github.com/paypal/PayPal-PHP-SDK/pull/1152
Hope this helps, but their current SDK is throwing exceptions.
Use below simple fix.
Replace below function in vendor\paypal\rest-api-sdk-php\lib\PayPal\Api\MerchantPreferences.php
public function setNotifyUrl($notify_url)
{
if(!empty($notify_url)){
UrlValidator::validate($notify_url, "NotifyUrl");
}
$this->notify_url = $notify_url;
return $this;
}
If you get the same error for return_url/cancel_url, add the if condition as above.
Note: This is not a permanent solution, you can use this until getting the update from PayPal.
From the GitHub repo for the PayPal PHP SDK, I see that the error you mentioned is thrown when MerchantPreferences is not given a valid NotifyUrl. I see you're setting the CancelUrl and ReturnUrl, but not the NotifyUrl. You may simply need to set that as well, i.e.:
$NotifyUrl = (some url goes here)
$obj->setNotifyUrl($NotifyUrl);
Reason behind it!
error comes from.
vendor\paypal\rest-api-sdk-php\lib\PayPal\Validation\UrlValidator.php
line.
if (filter_var($url, FILTER_VALIDATE_URL) === false) {
throw new \InvalidArgumentException("$urlName is not a fully qualified URL");
}
FILTER_VALIDATE_URL: according to this php function.
INVALID URL: "http://cat_n.domain.net.in/"; // IT CONTAIN _ UNDERSCORE.
VALID URL: "http://cat-n.domain.net.in/"; it separated with - dash
here you can dump your url.
vendor\paypal\rest-api-sdk-php\lib\PayPal\Validation\UrlValidator.php
public static function validate($url, $urlName = null)
{
var_dump($url);
}
And then check this here: https://www.w3schools.com/PHP/phptryit.asp?filename=tryphp_func_validate_url
you can check here what character will reason for invalid.

EPiServer 9 - Add block to new page programmatically

I have found some suggestions on how to add a block to a page, but can't get it to work the way I want, so perhaps someone can help out.
What I want to do is to have a scheduled job that reads through a file, creating new pages with a certain pagetype and in the new page adding some blocks to a content property. The blocks fields will be updated with data from the file that is read.
I have the following code in the scheduled job, but it fails at
repo.Save((IContent) newBlock, SaveAction.Publish);
giving the error
The page name must contain at least one visible character.
This is my code:
public override string Execute()
{
//Call OnStatusChanged to periodically notify progress of job for manually started jobs
OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
//Create Person page
PageReference parent = PageReference.StartPage;
//IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
//var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//var slaegtPage = repository.GetDefault<SlaegtPage>(ContentReference.StartPage);
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
SlaegtPage slaegtPage = contentRepository.GetDefault<SlaegtPage>(parent, contentTypeRepository.Load("SlaegtPage").ID);
if (slaegtPage.MainContentArea == null) {
slaegtPage.MainContentArea = new ContentArea();
}
slaegtPage.PageName = "001 Kim";
//Create block
var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
var newBlock = repo.GetDefault<SlaegtPersonBlock1>(ContentReference.GlobalBlockFolder);
newBlock.PersonId = "001";
newBlock.PersonName = "Kim";
newBlock.PersonBirthdate = "01 jan 1901";
repo.Save((IContent) newBlock, SaveAction.Publish);
//Add block
slaegtPage.MainContentArea.Items.Add(new ContentAreaItem
{
ContentLink = ((IContent) newBlock).ContentLink
});
slaegtPage.URLSegment = UrlSegment.CreateUrlSegment(slaegtPage);
contentRepository.Save(slaegtPage, EPiServer.DataAccess.SaveAction.Publish);
_stopSignaled = true;
//For long running jobs periodically check if stop is signaled and if so stop execution
if (_stopSignaled) {
return "Stop of job was called";
}
return "Change to message that describes outcome of execution";
}
You can set the Name by
((IContent) newBlock).Name = "MyName";

fetch gmail calendar events in mvc 4 application

I am working on mvc 4 web application. I want to implement a functionality wherein the scenario is as follows-
There will be gmail id as input for ex: abc#gmail.com. When user will enter this, application should fetch all the calendar events of that respective email id and display them.
I have gone through this-
http://msdn.microsoft.com/en-us/library/live/hh826523.aspx#cal_rest
https://developers.google.com/google-apps/calendar/v2/developers_guide_protocol
I am new to this and i have searched a lot but not got any solution. Please help! Thanks in advance!
Got the solution . Just refer this.
https://github.com/nanovazquez/google-calendar-sample
Please check the steps below.
Add Google Data API SDK.
Try this code.. I wrote this code for one project but I removed some codes that are not related to Google Calender. If you don't want to use SDK, you can simply do http-get or http-post to your calender link based on spec.
CalendarService service = new CalendarService("A.Name");
const string GOOGLE_CALENDAR_FEED = "https://www.google.com/calendar/feeds/";
const string GOOGLE_CALENDAR_DEFAULT_ALL_CALENDAR_FULL = "default/allcalendars/full";
const string GOOGLE_CALENDAR_ALL_PRIVATE_FULL = "private/full";
private void SetUserCredentials() {
var userName = ConfigurationManager.AppSettings["GoogleUserName"];
var passWord = Security.DecryptString(ConfigurationManager.AppSettings["GooglePasswrod"]).ToInsecureString();
if (userName != null && userName.Length > 0) {
service.setUserCredentials(userName, passWord);
}
}
private CalendarFeed GetCalendarsFeed() {
CalendarQuery calendarQuery = new CalendarQuery();
calendarQuery.Uri = new Uri(GOOGLE_CALENDAR_FEED + GOOGLE_CALENDAR_DEFAULT_ALL_CALENDAR_FULL);
CalendarFeed resultFeed = (CalendarFeed)service.Query(calendarQuery);
return resultFeed;
}
private TherapistTimeSlots GetTimeSlots(CalendarEntry entry2) {
string feedstring = entry2.Id.AbsoluteUri.Substring(63);
var postUristring = string.Format("{0}{1}/{2}", GOOGLE_CALENDAR_FEED, feedstring, GOOGLE_CALENDAR_ALL_PRIVATE_FULL);
EventFeed eventFeed = GetEventFeed(postUristring);
slot.Events = new List<Event>();
if (eventFeed != null) {
var orderEventList = (from entity in eventFeed.Entries
from timeslot in ((EventEntry)entity).Times
orderby timeslot.StartTime
select entity).ToList();
}
return slot;
}
private EventFeed GetEventFeed(string postUristring) {
var eventQuery = new EventQuery();
eventQuery.Uri = new Uri(postUristring);
var h = Convert.ToInt32(DateTime.Now.ToString("HH", System.Globalization.DateTimeFormatInfo.InvariantInfo));
eventQuery.StartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, h, 0, 0);
eventQuery.EndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, h + 2, 0, 0);
try {
EventFeed eventFeed = service.Query(eventQuery) as EventFeed;
return eventFeed;
}
catch (Exception ex) {
/*
* http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/1c1309d9e6bd9be7
*
* Unfortunately, the calendar API will always issue a redirect to give you a
gsessionid that will optimize your subsequent requests on our servers.
Using the GData client library should be transparent for you as it is taking
care of handling those redirect; but there might some times where this error
occurs as you may have noticed.
The best way to work around this is to catche the Exception and re-send the
request as there is nothing else you can do on your part.
*/
return null;
}
}

How to use Twitter Api To Get more than 20 list Members in a single request?

i want to get more than 20 users using the the twitter api in a single request
is there any parameter that specifies it?
i am using this api
http://api.twitter.com/1/Barelyme/Politics/members.xml?cursor=-1
According to the Twitter List API Docs:
http://apiwiki.twitter.com/Twitter-REST-API-Method:-GET-list-members
You cant get more than 20 in a single request.
If you're using twitteroauth by abraham, you can iterate through the pages of list members (this example assumes $connection is already defined by a functional implementation of twitteroauth):
$user = $connection->get('account/verify_credentials'); //Gets/Tests credentials
$listmembers = $connection->get("{$user->screen_name}/LISTNAMEORID/members"); //Gets first page of list members; MUST edit "LISTNAMEORID"
$pagevalue = ""; //Set page value for later use
if($listmembers->next_cursor == 0){ //There is only one page of followers
for ($j=0, $k=count($listmembers->users); $j<$k; $j++){
//Your actions here
//print_r($listmembers); //Displays the page of list members
}
} else { //There are multiple pages of followers
while ($pagevalue!=$listmembers->next_cursor){
for ($j=0, $k=count($listmembers->users); $j<$k; $j++){
//Your actions here
//print_r($listmembers); //Displays the page of list members
}
$pagevalue = $listmembers->next_cursor; //Increment the 'Next Page' link
$listmembers = $connection->get("{$user->screen_name}/LISTNAMEORID/members", array('cursor' => $pagevalue)); //Gets next page of list members; MUST edit "LISTNAMEORID"
}
}
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$listmembers = $connection->get("MexicoTimes/mexicanpoliticians/members");
$members = array();
while ($listmembers->next_cursor_str != "0") {
foreach($listmembers->users as $user)
$members[] = $user;
$cursor = $listmembers->next_cursor_str;
$listmembers = $connection->get("MexicoTimes/mexicanpoliticians/members", array('cursor' => $cursor));
}
This one worked for me with Abraham's Twitteroauth
Probably not though, you can poll multiple times > 1 for more data.
Given that twitter said you can't do it, you Probably can't