Programmatically created order not sending order receipt email - magento

When I make an order normally through the Magento store, I immediately get an email receipt. When I create an order through my custom code, No email is sent.
Here's my code:
private function _submitOrder($customer, $billing, $shipping, $products, $payment, $coupon, $finalize){
if($coupon && $this->_checkCouponValidity($coupon)){
$quote = Mage::getModel('sales/quote')->setCouponCode($coupon)->load();
}else{
$quote = Mage::getModel('sales/quote');
}
foreach($products as $item) {
if($item['qty']>0){
$product = Mage::getModel('catalog/product');
$productId = Mage::getModel('catalog/product')->getIdBySku($item['sku']);
$product->load($productId);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($product);
$quoteItem->setQuote($quote);
$quoteItem->setQty($item['qty']);
$quote->addItem($quoteItem);
}
}
$quote->getBillingAddress()
->addData($billing);
$quote->getShippingAddress()
->addData($billing)
->setShippingMethod('tablerate_bestway')
->setPaymentMethod('authorizenet')
->setCollectShippingRates(true);
$quote->setCheckoutMethod('guest')
->setCustomerId(null)
->setCustomerEmail($quote->getBillingAddress()->getEmail())
->setCustomerIsGuest(true)
->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
$quote->collectTotals();
$quote->save();
$convertQuote = Mage::getSingleton('sales/convert_quote');
$quotePayment = $quote->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePayment->setMethod('authorizenet');
$order = $convertQuote->addressToOrder($quote->getShippingAddress());
if($finalize){
$orderPayment = $convertQuote->paymentToOrderPayment($quotePayment);
$order->setBillingAddress($convertQuote->addressToOrderAddress($quote->getBillingAddress()));
$order->setShippingAddress($convertQuote->addressToOrderAddress($quote->getShippingAddress()));
$order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
$order->getPayment()->setCcNumber($payment['ccNumber']);
$order->getPayment()->setCcType($payment['ccType']);
$order->getPayment()->setCcExpMonth($payment['ccExpMonth']);
$order->getPayment()->setCcExpYear($payment['ccExpYear']);
$order->getPayment()->setCcLast4($payment['ccLast4']);
}
Mage::log("loop quote items");
foreach ($quote->getAllItems() as $item) {
$orderItem = $convertQuote->itemToOrderItem($item);
if ($item->getParentItem()) {
$orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$order->addItem($orderItem);
}
try {
if($finalize){
$order->place();
$order->save();
if ($order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e){
Mage::log($e->getMessage());
}
}
return $order;
}
else{
return $order;
}
} catch (Exception $e){
return $e->getMessage();
}
}

I figured out the problem.
This line:
$quote->getBillingAddress()->getEmail()
was returning nothing. I wasn't setting a shipping email when creating $billing. Whoops.

Related

Apply Coupon code to QUOTE with external script Magento

i want to apply coupon code from external script, that will set code and discount amount to quote and final result will be saved quote with new total. I have done following but not saving quote.
$quoteid = "53701";
$couponCode = "Discount99";
$oCoupon = Mage::getModel('salesrule/coupon')->load(trim($couponCode), 'code');
$oRule = Mage::getModel('salesrule/rule')->load($oCoupon->getRuleId());
if($oRule->getRuleId() && $oRule->getRuleId() > 0){
try{
$quoteObj = Mage::getModel('sales/quote')->setCouponCode($oCoupon)->load($quoteid);
$quoteObj->setTotalsCollectedFlag(true)
->collectTotals()
->save();
$returndata["success"] = "1";
$returndata["message"] = "Coupon Applied Successfully";
$returndata["data"]["discount_amount"] = $oRule->getDiscountAmount();
}catch (Exception $e){
$returndata["success"] = "0";
$returndata["message"] = "Cart Coupon update Failed";
$returndata["data"] = null;
}
}else{
$returndata["success"] = "0";
$returndata["message"] = "Invalid Coupon";
$returndata["data"] = null;
}
echo json_encode($returndata);
exit;
$quoteid = '53703';
$couponCode = "cvpcode2013";
$oCoupon = Mage::getModel('salesrule/coupon')->load(trim($couponCode), 'code');
$oRule = Mage::getModel('salesrule/rule')->load($oCoupon->getRuleId());
if($oRule->getRuleId() && $oRule->getRuleId() > 0){
try{
$quote = $this->_getQuote($quoteid,Mage::app()->getStore()->getStoreId());
$quote->setCouponCode($couponCode);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$quote->collectTotals();
$quote->save();
}catch (Exception $e){
echo $e->getMessage();
}
}else{
// invalid coupon
}
// create new function
protected function _getQuote($quoteId, $store = null)
{
$quote = Mage::getModel("sales/quote");
if (!(is_string($store) || is_integer($store))) {
$quote->loadByIdWithoutStore($quoteId);
} else {
$storeId = $store;
$quote->setStoreId($storeId)
->load($quoteId);
}
if (is_null($quote->getId())) {
$this->_fault('quote_not_exists');
}
return $quote;
}

Remove 1 qty of product Magento

I'm implementing custom sidebar cart of Magento, which will feature incrementation and decrementaton of products in this cart, refreshed in ajax.
AJAX is possible to work just with HTML, isn't working as return value is whole cart.
I'm adding 1 quantity of product using CartController: /checkout/cart/add/uenc/aHR0cDovL3BsYXkudGhlaGFwcHlwZWFyLm5ldC9zaG9wL2RyaW5rcw,,/product/586/
Is it possible to just remove 1 quantity of product? Do I have to create new custom function in CartController?
Thanks,
Adam
ANSWER:
you can call this link with
/checkout/cart/remove/id/ $ITEMID /uenc/aHR0cDovL3BsYXkudGhlaGFwcHlwZWFyLm5ldC9zaG9w/ (depending on your magento settings link could be different)
Copy into CartController.php
public function removeAction()
{
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
$id = (int) $this->getRequest()->getParam('id');
$items = $cart->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $id) {
if( $item->getQty() == 1 ){
$cart->removeItem($item->getItemId())->save();
}
else if($item->getQty() > 1){
$item->setQty($item->getQty() - 1);
$cart->save();
}
break;
}
}
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()){
//$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
//$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}

How to create cron for partial invoice of an order

I want to create partial invoice for downloadable product of an order based on release date of that product, I have got so many solutions to create partial invoice but it's create the invoice for all product, not for selected one.
Here is the solution but don't forget to change condition according your requirement.
<?php
require_once '../app/Mage.php';
Mage::app('admin');
CapturePayment::createInvoice();
class CapturePayment {
public static function createInvoice() {
$orders = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', array('processing'));
foreach ($orders as $order) {
$orderId = $order->getIncrementId();
try {
if (!$order->getId() || !$order->canInvoice()) {
echo 'Invoice is not allowed for order=>.' . $orderId . "\n";
continue;
}
$items = $order->getAllItems();
$partial = false;
$qtys = array();
foreach ($items as $item) {
/* Check wheter we can create invoice for this item or not */
if (!CapturePayment::canInvoiceItem($item, array())) {
continue;
}
/* Get product id on the basis of order item id */
$productId = $item->getProductId();
/* If product is tablet then don't create invoice for the same */
/* Put your condition here for items you want to create the invoice e.g.*/
/* Load the product to get the release date */
$productDetails = Mage::getModel('catalog/product')->load($productId);
/* create your $qtys array here like */
$qtys['orderItemId'] = 'quantityOrdered';
/* NOTE: But if you don't want to craete invoice for any particular item then pass the '0' quantity for that item and set the value for $partial = true if some product remain in any order*/
}
/* Prepare the invoice to capture/create the invoice */
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($qtys);
if (!$invoice->getTotalQty()) {
continue;
}
$amount = $invoice->getGrandTotal();
if ($partial) {
$amount = $invoice->getGrandTotal();
$invoice->register()->pay();
$invoice->getOrder()->setIsInProcess(true);
$history = $invoice->getOrder()->addStatusHistoryComment('Partial amount of $' . $amount . ' captured automatically.', false);
$history->setIsCustomerNotified(true);
$invoice->sendEmail(true, '');
$order->save();
Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder())
->save();
$invoice->save();
} else {
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(true);
$invoice->getOrder()->setIsInProcess(false);
$invoice->getOrder()->setData('state', "complete");
$invoice->getOrder()->setStatus("complete");
$invoice->sendEmail(true, '');
$order->save();
Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder())
->save();
$invoice->save();
}
} catch (Exception $e) {
echo 'Exception in Order => ' . $orderId . '=>' . $e . "\n";
}
}
}
/* Check the invoice status for an item of an order */
public static function canInvoiceItem($item, $qtys=array()) {
if ($item->getLockedDoInvoice()) {
return false;
}
if ($item->isDummy()) {
if ($item->getHasChildren()) {
foreach ($item->getChildrenItems() as $child) {
if (empty($qtys)) {
if ($child->getQtyToInvoice() > 0) {
return true;
}
} else {
if (isset($qtys[$child->getId()]) && $qtys[$child->getId()] > 0) {
return true;
}
}
}
return false;
} else if ($item->getParentItem()) {
$parent = $item->getParentItem();
if (empty($qtys)) {
return $parent->getQtyToInvoice() > 0;
} else {
return isset($qtys[$parent->getId()]) && $qtys[$parent->getId()] > 0;
}
}
} else {
return $item->getQtyToInvoice() > 0;
}
}
}

How to get carrier by "shipping method" in magento

Typical magento's order has shipping_method. For example, in my case, it is "flatrate_flatrate".
How to bind carrier ("flatrate") with shipping_method?
Thanks for response.
public function getShippingMethodsList($quoteId, $store=null)
{
$quote = $this->_getQuote($quoteId, $store);
$quoteShippingAddress = $quote->getShippingAddress();
if (is_null($quoteShippingAddress->getId())) {
$this->_fault("shipping_address_is_not_set");
}
try {
$quoteShippingAddress->collectShippingRates()->save();
$groupedRates = $quoteShippingAddress->getGroupedAllShippingRates();
$ratesResult = array();
foreach ($groupedRates as $carrierCode => $rates ) {
$carrierName = $carrierCode;
if (!is_null(Mage::getStoreConfig('carriers/'.$carrierCode.'/title'))) {
$carrierName = Mage::getStoreConfig('carriers/'.$carrierCode.'/title');
}
foreach ($rates as $rate) {
$rateItem = $this->_getAttributes($rate, "quote_shipping_rate");
$rateItem['carrierName'] = $carrierName;
$ratesResult[] = $rateItem;
unset($rateItem);
}
}
} catch (Mage_Core_Exception $e) {
$this->_fault('shipping_methods_list_could_not_be_retrived', $e->getMessage());
}
return $ratesResult;
}

Magento: Adminhtml form “Image” Field

I have set an input field of type “Image” in an admin form using the code below:
<?php
// Tab Form
// File: app/code/local/MyCompany/Mymodule/Block/Adminhtml/Items/Edit/Tab/Form.php
class MyCompany_Mymodule_Block_Adminhtml_Items_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('mymodule_form', array('legend'=>Mage::helper('mymodule')->__('Item information')));
$fieldset->addField('photo', 'image', array(
'label' => Mage::helper('mymodule')->__('Photo'),
'required' => false,
'name' => 'photo',
));
if ( Mage::getSingleton('adminhtml/session')->getMymoduleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getMymoduleData());
Mage::getSingleton('adminhtml/session')->setMymoduleData(null);
} elseif ( Mage::registry('mymodule_data') ) {
$form->setValues(Mage::registry('mymodule_data')->getData());
}
return parent::_prepareForm();
}
}
And then, inside the controller save the image using:
public function saveAction()
{
if($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('mymodule/speakers');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
$model->setKeynote($this->getRequest()->getParam('keynote'));
// Save photo
if(isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('photo');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS;
// Upload the image
$uploader->save($media_path, $_FILES['photo']['name']);
$data['photo'] = $media_path . $_FILES['photo']['name'];
}
catch (Exception $e) {
print_r($e);
die;
}
}
else {
if(isset($data['photo']['delete']) && $data['photo']['delete'] == 1) {
$data['photo'] = '';
}
else {
unset($data['photo']);
}
}
if(isset($data['photo'])) $model->setPhoto($data['photo']);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('mymodule')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('mymodule')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
Long story short: When I save the item (using Save or Save and Continue Edit) in backend it saves well one time. Then the next time it gives the next error:
Notice: Array to string conversion in
/home/wwwadmin/public_html/aaa.bbb.ccc/public/lib/Zend/Db/Statement/Pdo.php
on line 232
The next saves ok. The next: error. The next ok… You know what I mean…
I was looking some code to see how this input type is used. But nothing yet. Neither inside the magento code. This is the only thing I’ve found: http://www.magentocommerce.com/wiki/how_to/how_to_create_pdf_upload_in_backend_for_own_module
Any ideas?
Thanks
When this line is runs:
$model->setData($data)->setId($this->getRequest()->getParam('id'));<br/>
$model->_data['image'] will be set to array('image'=>'[YOUR path]')<br/>
you should call method setData() after all manipulations with data['image'];
Try below code for save action in your controller
if ($data = $this->getRequest()->getPost()) {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('your_model')->load($id);
if (isset($data['image']['delete'])) {
Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
}
$image = Mage::helper('your_helper')->uploadBannerImage();
if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
$data['image'] = $image;
} else {
unset($data['image']);
}
$model->setData($data)
->setId($id);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess('Your request Save.');
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('your_helper')->__('Unable to find your request to save'));
$this->_redirect('*/*/');
}
In your helper
public function uploadBannerImage() {
$path = Mage::getBaseDir('media') . DS . 'images';
$image = "";
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array(
'jpg', 'jpeg', 'gif', 'png'
));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->save($path, $uploader->getCorrectFileName($_FILES['image']['name']));
$image = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError($e->getMessage());
}
}
return $image;
}
public function deleteImageFile($image) {
if (!$image) {
return;
}
try {
$img_path = Mage::getBaseDir('media') . "/" . $image;
if (!file_exists($img_path)) {
return;
}
unlink($img_path);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}

Resources