Splitting Order is not working in magento - php

This code is not completely splitting my order. Still subtotal and grand total of bill is not split up. This code is splitting order's product fine. Is there any other code that is working well with this. I want to split order on the bases of supplier. The products from one supplier should be in one order and the other one's should be in other. Please suggest me some useful links.
Below is my code. This is an observer of order save.
<?php
class Custom_SplitOrderObserver_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage {
/**
* Create order based on checkout type. Create customer if necessary.
*
* #return Mage_Checkout_Model_Type_Onepage
*/
public function saveOrder() {
$this->validate();
$isNewCustomer = false;
switch ($this->getCheckoutMethod()) {
case self::METHOD_GUEST:
$this->_prepareGuestQuote();
break;
case self::METHOD_REGISTER:
$this->_prepareNewCustomerQuote();
$isNewCustomer = true;
break;
default:
$this->_prepareCustomerQuote();
break;
}
$cart = $this->getQuote();
$key = 0;
foreach ($cart->getAllItems() as $item) {
$key = $key + 1;
$temparray[$key]['product_id'] = $item->getProduct()->getId();
$temparray[$key]['qty'] = $item->getQty();
$cart->removeItem($item->getId());
$cart->setSubtotal(0);
$cart->setBaseSubtotal(0);
$cart->setSubtotalWithDiscount(0);
$cart->setBaseSubtotalWithDiscount(0);
$cart->setGrandTotal(0);
$cart->setBaseGrandTotal(0);
$cart->setTotalsCollectedFlag(false);
$cart->collectTotals();
}
$cart->save();
foreach ($temparray as $key => $item) {
$customer_id = Mage::getSingleton('customer/session')->getId();
$store_id = Mage::app()->getStore()->getId();
$customerObj = Mage::getModel('customer/customer')->load($customer_id);
$quoteObj = $cart;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($item['product_id']);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setBasePrice($productObj->getFinalPrice());
$quoteItem->setPriceInclTax($productObj->getFinalPrice());
$quoteItem->setData('original_price', $productObj->getPrice());
$quoteItem->setData('price', $productObj->getPrice());
$quoteItem->setRowTotal($productObj->getFinalPrice());
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($item['qty']);
$quoteItem->setStoreId($store_id);
$quoteObj->addItem($quoteItem);
$quoteObj->setBaseSubtotal($productObj->getFinalPrice());
$quoteObj->setSubtotal($productObj->getFinalPrice());
$quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
$quoteObj->setGrandTotal($productObj->getFinalPrice());
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->save();
$this->_quote = $quoteObj;
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
if ($isNewCustomer) {
try {
$this->_involveNewCustomer();
} catch (Exception $e) {
Mage::logException($e);
}
}
$this->_checkoutSession->setLastQuoteId($quoteObj->getId())
->setLastSuccessQuoteId($quoteObj->getId())
->clearHelperData();
$order = $service->getOrder();
if ($order) {
Mage::dispatchEvent('checkout_type_onepage_save_order_after', array('order' => $order, 'quote' => $quoteObj));
$quoteObj->removeAllItems();
$quoteObj->setTotalsCollectedFlag(false);
$quoteObj->collectTotals();
}
/**
* a flag to set that there will be redirect to third party after confirmation
* eg: paypal standard ipn
*/
$redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
/**
* we only want to send to customer about new order when there is no redirect to third party
*/
if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
// add order information to the session
$this->_checkoutSession->setLastOrderId($order->getId())
->setRedirectUrl($redirectUrl)
->setLastRealOrderId($order->getIncrementId());
// as well a billing agreement can be created
$agreement = $order->getPayment()->getBillingAgreement();
if ($agreement) {
$this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
}
}
// add recurring profiles information to the session
$profiles = $service->getRecurringPaymentProfiles();
if ($profiles) {
$ids = array();
foreach ($profiles as $profile) {
$ids[] = $profile->getId();
}
$this->_checkoutSession->setLastRecurringProfileIds($ids);
// TODO: send recurring profile emails
}
Mage::dispatchEvent(
'checkout_submit_all_after', array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
);
return $this;
}
}

Related

Can I edit the Amelia wordpress booking system to create a new customer without booking?

need my customers to be able to log into the site with the same details as they book with, as i can make a customer in amelia that adds itself to the default wordpress user list but when i make a wordpress user with the amelia customer role it does not transfer over across to amelia.
not a clue if this helps but found this in the plugin php.
<?php
namespace AmeliaBooking\Domain\Factory\User;
use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
use AmeliaBooking\Domain\Entity\User\Customer;
use AmeliaBooking\Domain\Entity\User\Manager;
use AmeliaBooking\Domain\Entity\User\Admin;
use AmeliaBooking\Domain\Entity\User\Provider;
use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory;
use AmeliaBooking\Domain\Factory\Google\GoogleCalendarFactory;
use AmeliaBooking\Domain\Factory\Outlook\OutlookCalendarFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodServiceFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodServiceFactory;
use AmeliaBooking\Domain\ValueObjects\DateTime\Birthday;
use AmeliaBooking\Domain\ValueObjects\Gender;
use AmeliaBooking\Domain\ValueObjects\Json;
use AmeliaBooking\Domain\ValueObjects\String\Password;
use AmeliaBooking\Domain\ValueObjects\String\Status;
use AmeliaBooking\Domain\ValueObjects\Picture;
use AmeliaBooking\Domain\ValueObjects\String\Description;
use AmeliaBooking\Domain\ValueObjects\String\Email;
use AmeliaBooking\Domain\ValueObjects\Number\Integer\Id;
use AmeliaBooking\Domain\ValueObjects\String\Name;
use AmeliaBooking\Domain\ValueObjects\String\Phone;
use AmeliaBooking\Domain\Collection\Collection;
use AmeliaBooking\Domain\Factory\Schedule\DayOffFactory;
use AmeliaBooking\Domain\Factory\Schedule\TimeOutFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\WeekDayFactory;
/**
* Class UserFactory
*
* #package AmeliaBooking\Domain\Factory\User
*/
class UserFactory
{
/**
* #param $data
*
* #return Admin|Customer|Manager|Provider
* #throws InvalidArgumentException
*/
public static function create($data)
{
if (!isset($data['type'])) {
$data['type'] = 'customer';
}
switch ($data['type']) {
case 'admin':
$user = new Admin(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'provider':
$weekDayList = [];
$dayOffList = [];
$specialDayList = [];
$serviceList = [];
$appointmentList = [];
if (isset($data['weekDayList'])) {
foreach ((array)$data['weekDayList'] as $weekDay) {
$timeOutList = [];
if (isset($weekDay['timeOutList'])) {
foreach ((array)$weekDay['timeOutList'] as $timeOut) {
$timeOutList[] = TimeOutFactory::create($timeOut);
}
$weekDay['timeOutList'] = $timeOutList;
}
$periodList = [];
if (isset($weekDay['periodList'])) {
foreach ((array)$weekDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = PeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = PeriodFactory::create($period);
}
$weekDay['periodList'] = $periodList;
}
$weekDayList[] = WeekDayFactory::create($weekDay);
}
}
if (isset($data['specialDayList'])) {
foreach ((array)$data['specialDayList'] as $specialDay) {
$periodList = [];
if (isset($specialDay['periodList'])) {
foreach ((array)$specialDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = SpecialDayPeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = SpecialDayPeriodFactory::create($period);
}
$specialDay['periodList'] = $periodList;
}
$specialDayList[] = SpecialDayFactory::create($specialDay);
}
}
if (isset($data['dayOffList'])) {
foreach ((array)$data['dayOffList'] as $dayOff) {
$dayOffList[] = DayOffFactory::create($dayOff);
}
}
if (isset($data['serviceList'])) {
foreach ((array)$data['serviceList'] as $service) {
$serviceList[$service['id']] = ServiceFactory::create($service);
}
}
$user = new Provider(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email']),
new Phone(isset($data['phone']) ? $data['phone'] : null),
new Collection($weekDayList),
new Collection($serviceList),
new Collection($dayOffList),
new Collection($specialDayList),
new Collection($appointmentList)
);
if (!empty($data['password'])) {
$user->setPassword(new Password($data['password']));
}
if (!empty($data['locationId'])) {
$user->setLocationId(new Id($data['locationId']));
}
if (!empty($data['googleCalendar']) && isset($data['googleCalendar']['token'])) {
$user->setGoogleCalendar(GoogleCalendarFactory::create($data['googleCalendar']));
}
if (!empty($data['outlookCalendar']) && isset($data['outlookCalendar']['token'])) {
$user->setOutlookCalendar(OutlookCalendarFactory::create($data['outlookCalendar']));
}
if (!empty($data['zoomUserId'])) {
$user->setZoomUserId(new Name($data['zoomUserId']));
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
break;
case 'manager':
$user = new Manager(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'customer':
default:
$user = new Customer(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'] ?: null),
new Phone(!empty($data['phone']) ? $data['phone'] : null),
new Gender(!empty($data['gender']) ? strtolower($data['gender']) : null)
);
break;
}
if (!empty($data['countryPhoneIso'])) {
$user->setCountryPhoneIso(new Name($data['countryPhoneIso']));
}
if (!empty($data['birthday'])) {
if (is_string($data['birthday'])) {
$user->setBirthday(new Birthday(\DateTime::createFromFormat('Y-m-d', $data['birthday'])));
} else {
$user->setBirthday(new Birthday($data['birthday']));
}
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
if (!empty($data['externalId'])) {
$user->setExternalId(new Id($data['externalId']));
}
if (!empty($data['pictureFullPath']) && !empty($data['pictureThumbPath'])) {
$user->setPicture(new Picture($data['pictureFullPath'], $data['pictureThumbPath']));
}
if (!empty($data['status'])) {
$user->setStatus(new Status($data['status']));
}
if (!empty($data['note'])) {
$user->setNote(new Description($data['note']));
}
return $user;
}
}
Try this. Found it on the support forums.
add_action( 'user_register', 'custom_amelia_registration_save', 10, 1 );
function custom_amelia_registration_save($user_id) {
global $wpdb;
$wpUser = get_user_by('ID', $user_id);
$ameliaUserId = $wpdb->get_col(
"SELECT id FROM wp_amelia_users WHERE email = '{$wpUser->user_email}'"
);
if (!$ameliaUserId && in_array('wpamelia-customer', $wpUser->roles)) {
$ameliaUserFirstName = $wpUser->user_first_name ?: $wpUser->user_nicename;
$ameliaUserLastName = $wpUser->user_last_name ?: $wpUser->user_nicename;
$wpdb->query("
INSERT INTO wp_amelia_users
(
type,
status,
externalId,
firstName,
lastName,
email
) VALUES (
'customer',
'visible',
{$user_id},
'{$ameliaUserFirstName}',
'{$ameliaUserLastName}',
'{$wpUser->user_email}'
)
");
}
}

Magento code need precision

I'm currently checking a Magento extension and I have a slight doubt about a piece of code. I would like you to explain. I understand all of it but not this one :
$customerID == " "
Is there a case where Magento have a customer id like that ( a space?) ?
Thanks a lot for your reply !
Here the entire function.
public function isAvailable(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$method = $event->getMethodInstance(); //$method return the payment method
$result = $event->getResult(); //$result return true if method is active
$quote = $event->getQuote(); //$quote return var from cart
if($method->getCode() == 'custompayment' ){
//$customerGroup = $quote->getCustomerGroupId();
// $customerGroup="";
// $customerID="";
$login = Mage::getSingleton( 'customer/session' )->isLoggedIn(); //Check if User is Logged In
if($login)
{
$customerGroup = Mage::getSingleton('customer/session')->getCustomerGroupId(); //Get Customers Group ID
$customerID = Mage::getSingleton('customer/session')->getCustomerId(); //Get Customers ID
}
$selectedCustomerGroups = Mage::getStoreConfig('payment/custompayment/specificcustomers');
$selectedCustomerGroupsArray = explode(",", $selectedCustomerGroups);
if($selectedCustomerGroups != "" || $customerID == " "){
if(!in_array($customerGroup, $selectedCustomerGroupsArray)) {
$result->isAvailable = false;
}
}
else{
if($result->isAvailable==1){
$result->isAvailable = true;
}
}
}
Answered by adrien54 and JokiRuiz.

Magento add products programmatically and redirect to checkout

I have a external site where you can add products directly from.
So I tried to create a php file which can receive some HTTP POST - but its not working.
First I tried some very basic
<?php
namespace Addtocart;
use Mage;
require __DIR__ . '/app/Mage.php';
/*
if (! isset($_POST, $_POST['data'])) {
exit;
}
*/
$data = array(
//array('id' => 2532, 'qty' => 1, 'attribute' => 92, 'value' => 11), // 002
//array('id' => 1854, 'qty' => 1),
array('id' => '5711914018542', 'qty' => 1)
);
Mage::app();
$product_model = Mage::getModel('catalog/product');
/** #var \Mage_Checkout_Model_Cart $cart */
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$errors = array();
foreach($data as $product) {
try {
$productid = (int)$product_model->getIdBySku($product['id']);
$params = array(
'product' => $productid,
'qty' => $product['qty']
);
if (array_key_exists('attribute', $product)) {
$params['super_attribute'] = array($product['attribute'] => $product['value']);
}
$p = $product_model->load($productid);
$cart->addProduct($p, $params);
} catch (\Exception $e) {
$errors[$product['id']] = $e->getMessage();
continue;
}
}
$cart->save();
$cart->getItems()->setQuote($cart->getQuote());
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
if ($errors) {
var_dump($errors);
exit;
}
header('Location: /checkout/cart/');
But the cart is still empty.
Then I tried looking into the cart var_dump($cart) and found out that all products is actually added, so my guess is the session is changed between Mage::app() and Mage::run() is there any thing I can do to persist the session?
Magento: 1.7.0.2
This code here can be used, it will add multiple products
<?php
namespace Addtocart;
require __DIR__ . '/app/Mage.php';
use Mage;
if (! isset($_GET, $_GET['p'])) {
var_dump($_GET);
exit;
}
Mage::app();
/** #var \Mage_Core_Model_Session */
$coresession = Mage::getSingleton('core/session', array('name'=>'frontend'));
/** #var \Mage_Checkout_Model_Session $session */
$session = Mage::getSingleton('checkout/session');
$session->start();
$session->clear();
/** #var \Mage_Catalog_Model_Product $product_model */
$product_model = Mage::getModel('catalog/product');
/** #var \Mage_Checkout_Model_Cart $cart */
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$cart->truncate();
$errors = array();
foreach($_GET['p'] as $product) {
$product = json_decode($product, true);
try {
$productid = (int)$product_model->getIdBySku(urldecode($product['id']));
$params = array(
'product' => $productid,
'qty' => $product['qty']
);
if (array_key_exists('attribute', $product)) {
$params['super_attribute'] = array($product['attribute'] => $product['value']);
}
$cart->addProduct($productid, $params);
} catch (\Exception $e) {
$errors[$product['id']] = $e->getMessage() . ' (Product: ' . print_r($product, true) . ')';
continue;
}
}
$cart->save();
$session->setCartWasUpdated(true);
if ($errors) {
var_dump($errors);
exit;
}
if ($cart->getQuote()->getHasError()) {
var_dump($cart->getQuote()->getHasError());
exit;
}
header('Location: /checkout/cart/');
And to use it send a GET request to the file with the following
p[]={"id":"<config-sku>","attribute":<attr>,"value":<value>,"qty":<qty>}&p[]={"id":"<simple-sku>","qty":<qty>}
Try using Magento's built in URL system for doing this as a get request from external site.
For simple products: http://www.magentosite.com/checkout/cart/add?product=1001&qty=1
You can also do custom options: http://www.magentosite.com/checkout/cart/add?product=1001&qty=1&options[12]=57&options[15]=32

Add code snippet into a class

I have some function which I use in my cart application:
session_start();
if(!isset($_SESSION['products'], $_SESSION['price'], $_SESSION['product_names'],$_SESSION['product_id'])) {
$_SESSION['products'] = 0;
$_SESSION['price'] = 0;
$_SESSION['product_names'] = array();
$_SESSION['product_id'] = array();
}
if(isset($_POST['add'])) {
$_SESSION['product_names'][] = $_POST['product_name'];
$_SESSION['products']++;
$_SESSION['price'] += $_POST['price'];
}
if(isset($_POST['empty'])) {
session_destroy();
header('Location:index.php');
}
The question is, how can I add this into a class and call it in my view page?
I mean it will still work as <?php echo $_SESSION['price']?>. How can I make this work?
Try this class you're doing in a wrong way.
session_start();
class Shopping {
public function __construct()
{
}
//get cart products
public function getCartProducts()
{
$cart = array();
if(isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
}
return $cart;
}
//add product to cart
public function addToCart($product_details)
{
$cart = $this->getCartProducts();
$product_id = $product_details['product_id'];
$is_quantity = $this->addQuantity($product_id); //check if product already exists in session if then increase the quantity
if(!$is_quantity) {
$product_details = array(
'qty' => $product_details['qty'],
'price' => $product_details['price'],
'product_name' => $product_details['name'],
'product_id' => $product_id
);
array_push($cart, $product_details);
$_SESSION['cart'] = serialize($cart);
}
}
//add quantity if product already exists
private function addQuantity($product_id)
{
$cart = $this->getCartProducts();
$i = 0;
foreach ($cart as $product) {
if($product['product_id'] == $product_id)
{
$product['qty'] += 1;
$cart[$i] = $product;
$_SESSION['cart'] = serialize($cart);
return true;
}
$i++;
}
return false;
}
public function clearCart()
{
unset($_SESSION['cart']);
}
public function removeProduct($product_id)
{
$cart = $this->getCartProducts();
$new_cart = array();
foreach ($cart as $product) {
if($product['product_id'] != $product_id)
array_push($new_cart, $product);
}
$_SESSION['cart'] = serialize($new_cart);
}
}
$shop = new Shopping();
$shop->addToCart(array('product_id'=>1,'name'=>'test 1','price'=>'120.00','qty'=>1));
$shop->addToCart(array('product_id'=>3,'name'=>'test 2','price'=>'120.00','qty'=>1));
This is an example of my approach using session in class. References work pretty well.
class Cart {
private $container ;
public function __construct(&$container){
if (!isset($container) || !is_array($container))
$session['cart'] = array() ;
$this->container = &$container ;
}
public function productExists($id){
return (isset($this->container[$id])) ;
}
}
$cart = new Cart($_SESSION['cart']) ;
At this point all changes in container can be performed in $_SESSION['cart'] . The rest of session array is not affected, that should be safe.

Magento Refund programmatically

Hy,
i'm trying to create a refund programmatically :
//get order magento
$orderMagento = Mage::getModel('sales/order')->loadByIncrementId($realOrderIncrementId );
if($orderMagento->getStatus() == Mage_Sales_Model_Order::STATE_CANCELED){
//création de l'avoir
$convertOrder = new Mage_Sales_Model_Convert_Order ();
$creditMemo = $convertOrder->toCreditmemo ( $orderMagento );
$items = $orderMagento->getAllItems ();
$totalQty = 0;
foreach ( $items as $item ) {
$_eachCreditMemoItem = $convertOrder->itemToCreditmemoItem ( $item );
$_eachCreditMemoItem->setQty ($item->getQtyInvoiced());
$_eachCreditMemoItem->register ();
$creditMemo->addItem ( $_eachCreditMemoItem );
$totalQty += $item->getQtyInvoiced ();
}
$creditMemo->refund();
$creditMemo->setTotalQty ( $totalQty );
$orderCreditMemoStatusCode = Mage_Sales_Model_Order::STATE_CLOSED;
$orderCreditMemoStatusComment = '[OK]Remboursement des article : ';
$saveTransaction = Mage::getModel('core/resource_transaction')->addObject ($creditMemo )->addObject ( $orderMagento )->save ();
$orderMagento->addStatusToHistory ( $orderCreditMemoStatusCode, $orderCreditMemoStatusComment, false );
$orderMagento->save ();
}
This code create a credit memo but all amount are null (BaseGrandTotal = 0.00€, etc...)
So where is the problem ?
Thanks you
First of all thank you, I started implementing creditmemo by programming using your code, and the problem I had was that the credit memom was created but without products. I'll share my code so you can use it.
/*
I think your problem is with the content of the variable data, I'll give you an example:
array(6) {
["items"] => array(2) {
[11] => array(1) {
["qty"] => string(6) "2"
}
[13] => array(1) {
["qty"] => string(1) "0"
}
}
["do_offline"] => string(1) "1"
["comment_text"] => string(0) ""
["shipping_amount"] => string(1) "0"
["adjustment_positive"] => string(1) "0"
["adjustment_negative"] => string(1) "0"
["qtys"] => array(2) {
[11] => int(2)
[13] => int(0)
}
}
*/
/**
*
* #param array $dif array that contains my product information with qty and product_id and item_id
* #param type $info array("order_increment_id" => $order->getIncrementId(), "invoice_id" => $invoiceId);
* #return type
*/
protected function creaDevolucio($dif, $info){
$qtys = array();
foreach ($dif as $item) {
if (isset($item['qty'])) {
$qtys[$item['order_item_id']] = array("qty"=> $item['qty']);
}
if (isset($item['back_to_stock'])) {
$backToStock[$item['order_item_id']] = true;
}
}
$data = array(
"items" => $qtys,
"do_offline" => "1",
"comment_text" => "",
"shipping_amount" => "0",
"adjustment_positive" => "0",
"adjustment_negative" => "0",
);
if (!empty($data['comment_text'])) {
Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
}
try {
$creditmemo = $this->_initCreditmemo($data, $info);
if ($creditmemo) {
if (($creditmemo->getGrandTotal() <=0) && (!$creditmemo->getAllowZeroGrandTotal())) {
Mage::throwException(
$this->__('Credit memo\'s total must be positive.')
);
}
$comment = '';
if (!empty($data['comment_text'])) {
$creditmemo->addComment(
$data['comment_text'],
isset($data['comment_customer_notify']),
isset($data['is_visible_on_front'])
);
if (isset($data['comment_customer_notify'])) {
$comment = $data['comment_text'];
}
}
if (isset($data['do_refund'])) {
$creditmemo->setRefundRequested(true);
}
if (isset($data['do_offline'])) {
$creditmemo->setOfflineRequested((bool)(int)$data['do_offline']);
}
$creditmemo->register();
if (!empty($data['send_email'])) {
$creditmemo->setEmailSent(true);
}
$creditmemo->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
$this->_saveCreditmemo($creditmemo);
$creditmemo->sendEmail(!empty($data['send_email']), $comment);
echo '<br>The credit memo has been created.';
Mage::getSingleton('adminhtml/session')->getCommentText(true);
return;
} else {
//$this->_forward('noRoute');
//return;
}
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
} catch (Exception $e) {
Mage::logException($e);
$this->_getSession()->addError($this->__('Cannot save the credit memo.'));
}
}
/**
*
* #param type $data contains products info to refund
* #param type $info array("order_increment_id" => $order->getIncrementId(), "invoice_id" => $invoiceId);
* #param type $update
* #return boolean
*/
protected function _initCreditmemo($data, $info, $update = false)
{
$creditmemo = false;
$invoice=false;
$creditmemoId = null;//$this->getRequest()->getParam('creditmemo_id');
$orderId = $info['order_increment_id'];//$this->getRequest()->getParam('order_id');
$invoiceId = $data['invoice_id'];
echo "<br>abans if. OrderId: ".$orderId;
if ($creditmemoId) {
$creditmemo = Mage::getModel('sales/order_creditmemo')->load($creditmemoId);
} elseif ($orderId) {
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
if ($invoiceId) {
$invoice = Mage::getModel('sales/order_invoice')
->load($invoiceId)
->setOrder($order);
echo '<br>loaded_invoice_number: '.$invoice->getId();
}
if (!$order->canCreditmemo()) {
echo '<br>cannot create credit memo';
if(!$order->isPaymentReview())
{
echo '<br>cannot credit memo Payment is in review';
}
if(!$order->canUnhold())
{
echo '<br>cannot credit memo Order is on hold';
}
if(abs($order->getTotalPaid()-$order->getTotalRefunded())<.0001)
{
echo '<br>cannot credit memo Amount Paid is equal or less than amount refunded';
}
if($order->getActionFlag('edit') === false)
{
echo '<br>cannot credit memo Action Flag of Edit not set';
}
if ($order->hasForcedCanCreditmemo()) {
echo '<br>cannot credit memo Can Credit Memo has been forced set';
}
return false;
}
$savedData = array();
if (isset($data['items'])) {
$savedData = $data['items'];
} else {
$savedData = array();
}
$qtys = array();
$backToStock = array();
foreach ($savedData as $orderItemId =>$itemData) {
if (isset($itemData['qty'])) {
$qtys[$orderItemId] = $itemData['qty'];
}
if (isset($itemData['back_to_stock'])) {
$backToStock[$orderItemId] = true;
}
}
$data['qtys'] = $qtys;
$service = Mage::getModel('sales/service_order', $order);
if ($invoice) {
$creditmemo = $service->prepareInvoiceCreditmemo($invoice, $data);
} else {
$creditmemo = $service->prepareCreditmemo($data);
}
/**
* Process back to stock flags
*/
foreach ($creditmemo->getAllItems() as $creditmemoItem) {
$orderItem = $creditmemoItem->getOrderItem();
$parentId = $orderItem->getParentItemId();
if (isset($backToStock[$orderItem->getId()])) {
$creditmemoItem->setBackToStock(true);
} elseif ($orderItem->getParentItem() && isset($backToStock[$parentId]) && $backToStock[$parentId]) {
$creditmemoItem->setBackToStock(true);
} elseif (empty($savedData)) {
$creditmemoItem->setBackToStock(Mage::helper('cataloginventory')->isAutoReturnEnabled());
} else {
$creditmemoItem->setBackToStock(false);
}
}
}
return $creditmemo;
}
/**
* Save creditmemo and related order, invoice in one transaction
* #param Mage_Sales_Model_Order_Creditmemo $creditmemo
*/
protected function _saveCreditmemo($creditmemo)
{
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($creditmemo)
->addObject($creditmemo->getOrder());
if ($creditmemo->getInvoice()) {
$transactionSave->addObject($creditmemo->getInvoice());
}
$transactionSave->save();
return $this;
}

Categories