Merge remote-tracking branch 'origin/ticket/r15587-refund-paypal' into develop

This commit is contained in:
Michael RICOIS 2018-02-12 11:58:09 +01:00
commit 6aebf9206a
3 changed files with 383 additions and 233 deletions

View File

@ -463,7 +463,6 @@ class AdminOrders extends AdminTab
exit;
}
/* Change order state, add a new entry in order history and send an e-mail to the customer if needed */
elseif (Tools::isSubmit('submitState') AND ($id_order = (int)(Tools::getValue('id_order'))) AND Validate::isLoadedObject($order = new Order($id_order)))
{
@ -562,8 +561,7 @@ class AdminOrders extends AdminTab
else
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
/* Cancel product from order */
// Cancel product from order
elseif (Tools::isSubmit('cancelProduct') AND Validate::isLoadedObject($order = new Order((int)(Tools::getValue('id_order')))))
{
if ($this->tabAccess['delete'] === '1')
@ -609,6 +607,7 @@ class AdminOrders extends AdminTab
}
}
if ($customizationList)
{
$customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
@ -627,6 +626,7 @@ class AdminOrders extends AdminTab
}
if (!sizeof($this->_errors) AND $productList)
{
foreach ($productList AS $key => $id_order_detail)
{
$qtyCancelProduct = abs($qtyList[$key]);
@ -648,21 +648,20 @@ class AdminOrders extends AdminTab
);
// Reinject product
if (
!$order->hasBeenDelivered()
OR ($order->hasBeenDelivered() AND Tools::isSubmit('reinjectQuantities') AND !$is_philea AND !$is_braderie)
){
if(
(($is_philea || $is_braderie) && !$order->hasBeenShipped() && !$order->hasBeenDelivered())
|| (!$is_philea && !$is_braderie)
){
if (!$order->hasBeenDelivered() || ($order->hasBeenDelivered()
&& Tools::isSubmit('reinjectQuantities')
&& !$is_philea && !$is_braderie) ) {
if ( (($is_philea || $is_braderie) && !$order->hasBeenShipped() && !$order->hasBeenDelivered())
|| (!$is_philea && !$is_braderie) ){
$reinjectableQuantity = (int)($orderDetail->product_quantity) - (int)($orderDetail->product_quantity_reinjected);
$quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct;
if (!Product::reinjectQuantities($orderDetail, $quantityToReinject))
if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) {
$this->_errors[] = Tools::displayError('Cannot re-stock product').' <span class="bold">'.$orderDetail->product_name.'</span>';
else
{
}
else {
$updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int)($orderDetail->product_attribute_id) : NULL;
$newProductQty = Product::getQuantity((int)($orderDetail->product_id), $updProductAttributeID);
$product = get_object_vars(new Product((int)($orderDetail->product_id), false, (int)($cookie->id_lang)));
@ -682,23 +681,29 @@ class AdminOrders extends AdminTab
}
// Delete product
if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct))
if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) {
$this->_errors[] = Tools::displayError('An error occurred during deletion of the product.').' <span class="bold">'.$orderDetail->product_name.'</span>';
}
Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail));
}
if (!sizeof($this->_errors) AND $customizationList)
foreach ($customizationList AS $id_customization => $id_order_detail)
{
$orderDetail = new OrderDetail((int)($id_order_detail));
$qtyCancelProduct = abs($customizationQtyList[$id_customization]);
if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail))
$this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.').' '.$id_customization;
}
// E-mail params
if ((isset($_POST['generateCreditSlip']) OR isset($_POST['generateDiscount']) OR isset($_POST['generateDiscount2'])) AND !sizeof($this->_errors))
{
if (!sizeof($this->_errors) AND $customizationList) {
foreach ($customizationList AS $id_customization => $id_order_detail) {
$orderDetail = new OrderDetail((int)($id_order_detail));
$qtyCancelProduct = abs($customizationQtyList[$id_customization]);
if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) {
$this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.').' '.$id_customization;
}
}
}
// Remboursement, Bon de réduction
if (!sizeof($this->_errors) && (isset($_POST['generateCreditSlip'])
|| isset($_POST['generateDiscount'])
|| isset($_POST['generateDiscount2']))) {
$customer = new Customer((int)($order->id_customer));
$params['{lastname}'] = $customer->lastname;
$params['{firstname}'] = $customer->firstname;
@ -709,10 +714,8 @@ class AdminOrders extends AdminTab
$total_refund = 0;
foreach ($productList as $key => $id_order_detail) {
$details_refund = new OrderDetail($id_order_detail);
$tprice = $details_refund->product_price * (1 - $details_refund->reduction_percent / 100) - $details_refund->reduction_amount;
$tprice = $tprice * ( 1 + $details_refund->tax_rate / 100 );
$products_refund .= "
<tr>
<td>". $details_refund->product_name . "</td>
@ -728,29 +731,29 @@ class AdminOrders extends AdminTab
$params['{total_products}'] = Tools::displayPrice($total_refund);
$fraisport = "";
if(isset($_POST['shippingBack']))
{
if (isset($_POST['shippingBack'])) {
$order = new Order($details_refund->id_order);
Module::hookExec('cancelShipping', array('order' => $order));
$fraisport .= "
<tr style='text-align:right;'>
<td colspan='3' style='background-color:#e2e2e1; padding:0.6em 0.4em;'>Frais de port</td>
<td style='background-color:#e2e2e1; padding:0.6em 0.4em;'>" . Tools::displayPrice($order->total_shipping) . "</td>
</tr>
";
// Remboursement frais de port
Module::hookExec('cancelShipping', array('order' => $order));
}
$params['{fraisport}'] = $fraisport;
}
// Generate voucher
if (isset($_POST['generateDiscount']) AND !sizeof($this->_errors))
{
if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), isset($_POST['shippingBack'])))
if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), isset($_POST['shippingBack']))) {
$this->_errors[] = Tools::displayError('Cannot generate voucher');
else
{
}
else {
// $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
// $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
// $params['{voucher_num}'] = $voucher->name;
@ -758,8 +761,7 @@ class AdminOrders extends AdminTab
// $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL,
// NULL, _PS_MAIL_DIR_, true);
/* MODIF MAIL ANTADIS */
// Modif ANTADIS
$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
$params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
$params['{voucher_num}'] = $voucher->name;
@ -773,10 +775,10 @@ class AdminOrders extends AdminTab
// Generate voucher 2 @Addition Antadis
if (isset($_POST['generateDiscount2']) AND !sizeof($this->_errors))
{
if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), isset($_POST['shippingBack']),0,0,5))
if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), isset($_POST['shippingBack']),0,0,5)) {
$this->_errors[] = Tools::displayError('Cannot generate voucher');
else
{
}
else {
$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
$params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
$params['{voucher_num}'] = $voucher->name;
@ -806,7 +808,7 @@ class AdminOrders extends AdminTab
}
}
// update order state if it's partial
// Update order state if it's partial
if ($order->getCurrentState() == 17) {
$partial = true;
@ -935,20 +937,23 @@ class AdminOrders extends AdminTab
}
}
}
else
else {
$this->_errors[] = Tools::displayError('No product or quantity selected.');
}
// Redirect if no errors
if (!sizeof($this->_errors))
if (!sizeof($this->_errors)) {
Tools::redirectAdmin($currentIndex.'&id_order='.$order->id.'&vieworder&conf=24&token='.$this->token);
}
else
}
else {
$this->_errors[] = Tools::displayError('You do not have permission to delete here.');
}
elseif (isset($_GET['messageReaded']))
{
}
elseif (isset($_GET['messageReaded'])) {
Message::markAsReaded((int)($_GET['messageReaded']), (int)($cookie->id_employee));
}
parent::postProcess();
}

View File

@ -537,88 +537,98 @@ class Paybox extends PaymentModule
}
}
public function hookcancelShipping($params) {
/**
* Refund shipping
* @param array $params
* @return void|boolean
*/
public function hookCancelShipping($params)
{
global $cookie;
if (Tools::getValue('noCancelHook')) {
return;
return false;
}
// if(Tools::isSubmit('generateDiscount'))
// return false;
if($params['order']->module != $this->name)
return false;
if(!($order = $params['order']) OR !Validate::isLoadedObject($order))
if (!in_array($cookie->profile, array(1,7,14,11))) {
return false;
}
if (!($order = $params['order']) || !Validate::isLoadedObject($order)) {
return false;
}
if ($order->module != $this->name) {
return false;
}
if (strtolower($order->payment) != "paybox") {
return false;
}
if($cookie->profile == 1
|| $cookie->profile == 7
|| $cookie->profile == 14
|| $cookie->profile == 11) {
if (!$order->hasBeenPaid()) {
// mail('thibault@antadis.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('karen@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('doreen@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('contact@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
} else {
if ($order->payment == "Paybox") {
return false;
}
$this->refundShipping($order);
}
}
}
}
public function hookcancelProduct($params) {
/**
* Refund product(s)
* @param array $params
* @return boolean
*/
public function hookcancelProduct($params)
{
global $cookie;
// if(Tools::isSubmit('generateDiscount')) {
// return FALSE;
// }
if($params['order']->module != $this->name) {
return FALSE;
if (!Tools::isSubmit('generateCreditSlip')) {
return false;
}
if(!($order_detail = new OrderDetail((int)($params['id_order_detail'])))
|| !Validate::isLoadedObject($order_detail)) {
return FALSE;
if (!in_array($cookie->profile, array(1,7,14,11))) {
return false;
}
$employee = new Employee((int) $cookie->id_employee);
if(!Validate::isLoadedObject($employee)) {
return FALSE;
if (!($order = $params['order']) || !Validate::isLoadedObject($order)) {
return false;
}
if (Tools::isSubmit('generateCreditSlip')) {
if($cookie->profile == 1
|| $cookie->profile == 7
|| $cookie->profile == 14
|| $cookie->profile == 11) {
if ($order->module != $this->name) {
return false;
}
$order = new Order($order_detail->id_order);
if (strtolower($order->payment) != "paybox") {
return false;
}
if ($order->payment == "Paybox") {
if (!$order->hasBeenPaid()) {
// mail('thibault@antadis.com', 'Erreur remboursement la commande nest pas valide pour etre rembourse', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('karen@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('doreen@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('contact@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
} else {
return false;
}
$order_detail = new OrderDetail((int)$params['id_order_detail']);
if (!$order_detail || !Validate::isLoadedObject($order_detail)) {
return false;
}
$this->refundProduct($params['id_order_detail']);
}
}
}
}
}
/**
* Rembourse un Order Detail
* @param int $id_order_detail Numéro de ligne de commande à refund
**/
public function refundProduct($id_order_detail) {
* @return boolean
*/
public function refundProduct($id_order_detail)
{
global $cookie;
$order_detail = new OrderDetail($id_order_detail);
@ -629,18 +639,12 @@ class Paybox extends PaymentModule
return false;
} else {
$products = $order->getProducts();
// quantite deja envoye
$send_quantity = (int) Db::getInstance()->getValue('
SELECT `quantity`
FROM `'._DB_PREFIX_.'lapostews`
WHERE `id_order_detail` = '. (int) $order_detail->id
);
$quantity_available = $order_detail->product_quantity;
// $quantity_available = $order_detail->product_quantity - (($send_quantity - $order_detail->product_quantity_return));
$cancel_quantity = Tools::getValue('cancelQuantity');
if ( $_POST['cancelQuantity'][(int) $order_detail->id] <= $quantity_available) {
if ($cancel_quantity[(int) $order_detail->id] <= $quantity_available) {
// Frais de port
$total_shipping = (int) Db::getInstance()->getValue('
SELECT `shipping_cost`
FROM `'._DB_PREFIX_.'order_slip`
@ -648,6 +652,7 @@ class Paybox extends PaymentModule
AND `shipping_cost` = 1
');
// Déjà remboursé
$total_refunded = (float) Db::getInstance()->getValue('
SELECT SUM(ROUND((product_price * (1 - reduction_percent / 100) - reduction_amount) * (1 - group_reduction / 100) * (1 + tax_rate / 100), 2) * product_quantity_refunded)
FROM `'._DB_PREFIX_.'order_detail`
@ -655,9 +660,10 @@ class Paybox extends PaymentModule
AND `id_order_detail` != '.(int) $order_detail->id.'
');
$amt = $products[(int) $order_detail->id]['product_price_wt'] * (int) ($_POST['cancelQuantity'][(int) $order_detail->id]);
$amt = $products[(int) $order_detail->id]['product_price_wt'] * (int) ($cancel_quantity[(int) $order_detail->id]);
$montant = min($amt, $order->total_paid_real - ((int) $total_shipping * $order->total_shipping) - $total_refunded);
// Call Paybox and make the refund - shipping refund is made outside
$refund = $this->sendRefundPaybox($montant, 978, $transaction['num_transaction'], $order->id_cart, $transaction['num_appel']);
if (!$refund) {
@ -681,8 +687,10 @@ class Paybox extends PaymentModule
/**
* Remboursement des frais de port d'une commande
* @param Object $order
**/
public function refundShipping($order) {
* @return boolean
*/
public function refundShipping($order)
{
global $cookie;
$total_refunded = (float) Db::getInstance()->getValue('
@ -703,7 +711,6 @@ class Paybox extends PaymentModule
$refund = $this->sendRefundPaybox($montant, 978, $transaction['num_transaction'], $order->id_cart, $transaction['num_appel']);
if (!$refund) {
// mail('thibault@antadis.com', 'Erreur dans le remboursement des shippings', 'Erreur remboursement échoué pour la commande ' . $order->id);
mail('karen@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order->id);
mail('doreen@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order->id);
mail('contact@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order->id);
@ -714,7 +721,6 @@ class Paybox extends PaymentModule
}
}
/**
* Génére un remboursement PAYBOX
* @param float $montant Montant à rembourser
@ -722,8 +728,10 @@ class Paybox extends PaymentModule
* @param int $num_transaction Numéro unique de transaction retourné par Paybox au paiement initial
* @param int $reference Numéro de référence de la commande (id_cart)
* @param int $num_appel Numéro d'appel retourné par Paybox au paiement initial
**/
public function sendRefundPaybox($montant, $devise, $num_transaction, $reference, $num_appel) {
* @return boolean
*/
public function sendRefundPaybox($montant, $devise, $num_transaction, $reference, $num_appel)
{
$curl = curl_init('https://ppps.paybox.com/PPPS.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
@ -768,8 +776,7 @@ class Paybox extends PaymentModule
$code_reponse = explode('CODEREPONSE=', $data[6]);
// refund success
if ( $code_reponse[1] == "00000"
|| $code_reponse[0] == "00000") {
if ( $code_reponse[1] == "00000" || $code_reponse[0] == "00000") {
return true;
} else {
// mail('thibault@antadis.com', 'Soucis remboursement reponse globale', json_encode($response));
@ -779,15 +786,15 @@ class Paybox extends PaymentModule
}
}
/**
* Save refund transaction in BDD when its OK
* @param int $id_order
* @param int $id_order_detail
* @param int $montant
* @param int $id_employee
**/
protected function refundSave($id_order, $id_order_detail = 0, $montant, $id_employee) {
*/
protected function refundSave($id_order, $id_order_detail = 0, $montant, $id_employee)
{
Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'refund_transaction`
(`id_order`, `id_order_detail`, `amount`, `date`, `id_employee`)
@ -801,13 +808,13 @@ class Paybox extends PaymentModule
);
}
/**
* Load les informations d'une transaction paybox
* @param int $id_cart Numéro du panier à charger
* @return array Les informations de transaction
**/
public function loadTransaction($id_cart) {
*/
public function loadTransaction($id_cart)
{
return Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.'paybox_transaction`
@ -815,13 +822,13 @@ class Paybox extends PaymentModule
);
}
/**
* Recupere la liste des remboursements effectués sur un id cmomande
* @param int $order_id id de la commande
* @return array
**/
public static function getAllRefundbyOrder($order_id) {
*/
public static function getAllRefundbyOrder($order_id)
{
return Db::getInstance()->executeS('
SELECT e.`email`, r.`date`, r.`amount`, r.`id_order_detail`, d.`product_name`
FROM `'._DB_PREFIX_.'refund_transaction` r

View File

@ -693,41 +693,153 @@ class PayPal extends PaymentModule
}
}
public function hookCancelProduct($params)
/**
* Refund shipping
* @param array $params
* @return void|boolean
*/
public function hookCancelShipping($params)
{
// if (Tools::isSubmit('generateDiscount') || !$this->isPayPalAPIAvailable())
// return false;
// // delete test sur la génération d'avoir
if (!$this->isPayPalAPIAvailable())
return false;
elseif ($params['order']->module != $this->name || !($order = $params['order']) || !Validate::isLoadedObject($order))
return false;
elseif (!$order->hasBeenPaid())
return false;
global $cookie;
$order_detail = new OrderDetail((int)$params['id_order_detail']);
if (!$order_detail || !Validate::isLoadedObject($order_detail))
if (Tools::getValue('noCancelHook')) {
return;
}
if (!in_array($cookie->profile, array(1,7,14,11))) {
return false;
}
if (!$this->isPayPalAPIAvailable()) {
return false;
}
if (!($order = $params['order']) || !Validate::isLoadedObject($order)) {
return false;
}
if ($order->module != $this->name) {
return false;
}
if (strtolower($order->payment) != "paypal") {
return false;
}
if (!$order->hasBeenPaid()) {
mail('karen@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('doreen@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
mail('contact@bebeboutik.com', 'Erreur remboursement', 'Erreur de remboursement sur la commande ' . $order_detail->id_order . ' la commande n\'a pas été payée.');
return false;
}
$paypal_order = PayPalOrder::getOrderById((int)$order->id);
if (!$paypal_order)
if (!$paypal_order) {
return false;
}
// Get product amount to refund
$amount = $order->total_shipping;
if ($amount > 0){
$refund = $this->_makeRefund($paypal_order['id_transaction'], (int)$order->id, $amount);
if (!$refund) {
mail('karen@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order_detail->id_order);
mail('doreen@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order_detail->id_order);
mail('contact@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order_detail->id_order);
} else {
$this->refundSave($order->id, 0, $amount, $cookie->id_employee);
}
}
}
public function hookCancelProduct($params)
{
global $cookie;
if (!in_array($cookie->profile, array(1,7,14,11))) {
return false;
}
if (!$this->isPayPalAPIAvailable()) {
return false;
}
if (!($order = $params['order']) || !Validate::isLoadedObject($order)) {
return false;
}
if ($order->module != $this->name) {
return false;
}
if (strtolower($order->payment) != "paypal") {
return false;
}
if (!$order->hasBeenPaid()) {
return false;
}
$paypal_order = PayPalOrder::getOrderById((int)$order->id);
if (!$paypal_order) {
return false;
}
$order_detail = new OrderDetail((int)$params['id_order_detail']);
if (!$order_detail || !Validate::isLoadedObject($order_detail)) {
return false;
}
$products = $order->getProducts();
$cancel_quantity = Tools::getValue('cancelQuantity');
$message = $this->l('Cancel products result:').'<br>';
// Get product amount to refund
$amount = (float)($products[(int)$order_detail->id]['product_price_wt'] * (int)$cancel_quantity[(int)$order_detail->id]);
if ($amount > 0){
$refund = $this->_makeRefund($paypal_order['id_transaction'], (int)$order->id, $amount);
if (!$refund) {
mail('karen@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order_detail->id_order);
mail('doreen@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order_detail->id_order);
mail('contact@bebeboutik.com', 'Erreur dans le remboursement', 'Erreur remboursement échoué pour la commande ' . $order_detail->id_order);
} else {
$this->refundSave($order_detail->id_order, $order_detail->id, $amount, $cookie->id_employee);
}
} else {
$refund = array();
$message .= $this->l('Transaction error because of the amount of the cancel product!').'<br>';
}
$this->formatMessage($refund, $message);
$this->_addNewPrivateMessage((int)$order->id, $message);
}
/**
* Save refund transaction in BDD when its OK
* @param int $id_order
* @param int $id_order_detail
* @param int $montant
* @param int $id_employee
*/
protected function refundSave($id_order, $id_order_detail = 0, $montant, $id_employee)
{
Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'refund_transaction`
(`id_order`, `id_order_detail`, `amount`, `date`, `id_employee`)
VALUES (
'. (int)$id_order .',
'. (int)$id_order_detail .',
'. $montant * 100 .',
"'. date('Y-m-d H:i:s') .'",
'. (int)$id_employee .'
)'
);
}
public function hookBackOfficeHeader()
{
if ((strcmp(Tools::getValue('configure'), $this->name) === 0) ||
@ -1097,22 +1209,33 @@ class PayPal extends PaymentModule
private function _makeRefund($id_transaction, $id_order, $amt = false)
{
if (!$this->isPayPalAPIAvailable())
if (!$this->isPayPalAPIAvailable()) {
die(Tools::displayError('Fatal Error: no API Credentials are available'));
elseif (!$id_transaction)
}
elseif (!$id_transaction) {
die(Tools::displayError('Fatal Error: id_transaction is null'));
}
if (!$amt)
$params = array('TRANSACTIONID' => $id_transaction, 'REFUNDTYPE' => 'Full');
else
{
// No amount make a total refund
if (!$amt) {
$params = array(
'TRANSACTIONID' => $id_transaction,
'REFUNDTYPE' => 'Full'
);
}
else {
$iso_currency = Db::getInstance()->getValue('
SELECT `iso_code`
FROM `'._DB_PREFIX_.'orders` o
LEFT JOIN `'._DB_PREFIX_.'currency` c ON (o.`id_currency` = c.`id_currency`)
WHERE o.`id_order` = '.(int)$id_order);
$params = array('TRANSACTIONID' => $id_transaction, 'REFUNDTYPE' => 'Partial', 'AMT' => (float)$amt, 'CURRENCYCODE' => Tools::strtoupper($iso_currency));
$params = array(
'TRANSACTIONID' => $id_transaction,
'REFUNDTYPE' => 'Partial',
'AMT' => (float)$amt,
'CURRENCYCODE' => Tools::strtoupper($iso_currency)
);
}
$paypal_lib = new PaypalLib();
@ -1138,53 +1261,67 @@ class PayPal extends PaymentModule
return $new_message->add();
}
public function generateTotalRefund($id_order){
public function generateTotalRefund($id_order)
{
$this->_doTotalRefund($id_order);
}
private function _doTotalRefund($id_order)
{
$paypal_order = PayPalOrder::getOrderById((int)$id_order);
if (!$this->isPayPalAPIAvailable() || !$paypal_order)
if (!$this->isPayPalAPIAvailable() || !$paypal_order) {
return false;
}
$order = new Order((int)$id_order);
if (!Validate::isLoadedObject($order))
if (!Validate::isLoadedObject($order)) {
return false;
}
$products = $order->getProducts();
$currency = new Currency((int)$order->id_currency);
if (!Validate::isLoadedObject($currency))
if (!Validate::isLoadedObject($currency)) {
$this->_errors[] = $this->l('Not a valid currency');
}
if (count($this->_errors))
if (count($this->_errors)) {
return false;
}
$decimals = (is_array($currency) ? (int)$currency['decimals'] : (int)$currency->decimals) * _PS_PRICE_DISPLAY_PRECISION_;
// Amount for refund
$amt = 0.00;
foreach ($products as $product)
// Add product price * ( quantity total - quantity already refunded )
foreach ($products as $product) {
$amt += (float)($product['product_price_wt']) * ($product['product_quantity'] - $product['product_quantity_refunded']);
}
// Add shipping, add wrapping, remove discount
$amt += (float)($order->total_shipping) + (float)($order->total_wrapping) - (float)($order->total_discounts);
if ($amt > 0) {
// check if total or partial
if (Tools::ps_round($order->total_paid_real, $decimals) == Tools::ps_round($amt, $decimals))
if (Tools::ps_round($order->total_paid_real, $decimals) == Tools::ps_round($amt, $decimals)) {
$response = $this->_makeRefund($paypal_order['id_transaction'], $id_order);
else
}
else {
$response = $this->_makeRefund($paypal_order['id_transaction'], $id_order, (float)($amt));
}
$message = $this->l('Refund operation result:').'<br>';
foreach ($response as $key => $value)
foreach ($response as $key => $value) {
$message .= $key.': '.$value.'<br>';
}
if (array_key_exists('ACK', $response) && $response['ACK'] == 'Success' && $response['REFUNDTRANSACTIONID'] != '')
{
$message .= $this->l('PayPal refund successful!');
if (!Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'paypal_order` SET `payment_status` = \'Refunded\' WHERE `id_order` = '.(int)$id_order))
if (!Db::getInstance()->Execute(
'UPDATE `'._DB_PREFIX_.'paypal_order` SET `payment_status` = \'Refunded\'
WHERE `id_order` = '.(int)$id_order)) {
die(Tools::displayError('Error when updating PayPal database'));
}
$history = new OrderHistory();
$history->id_order = (int)$id_order;
@ -1192,8 +1329,9 @@ class PayPal extends PaymentModule
$history->addWithemail();
$history->save();
}
else
else {
$message .= $this->l('Transaction error!');
}
} else {
$message = $this->l('Refund operation result:').'<br>';
$message .= $this->l('Transaction error because of the amount (amt)!');