Apply Coupon code to QUOTE with external script Magento - 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;
}

Related

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

Programmatically created order not sending order receipt email

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.

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 final_price,min_price,max_price wrong values insertion

Hi
i have problem with the final_price,min_price,max_price in the catalog_product_index_price table its is wrongly inserting the values after function save() during import.
The file is app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php
The control goes to finish() function
public function finish()
{
Mage::dispatchEvent('catalog_product_import_after', array());
$entity = new Varien_Object();
Mage::getSingleton('index/indexer')->processEntityAction(
$entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
);
}
where is the insert statement to insert the value in the catalog_product_index_price table?
How this can be resolved?
My saveRow fucnction to populate database.My excel sheet contains the following additional row
Price Type:radio:1
Unit Price:absolute:2691|Case Price:absolute:12420
Unit Price:absolute:762|Case Price:absolute:7029
The save database function is
public function saveRow(array $importData)
{
$product = $this->getProductModel()
->reset();
if (empty($importData['store'])) {
if (!is_null($this->getBatchParams('store'))) {
$store = $this->getStoreById($this->getBatchParams('store'));
} else {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'store');
Mage::throwException($message);
}
}
else {
$store = $this->getStoreByCode($importData['store']);
}
if ($store === false) {
$message = Mage::helper('catalog')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
Mage::throwException($message);
}
if (empty($importData['sku'])) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
Mage::throwException($message);
}
$product->setStoreId($store->getId());
$productId = $product->getIdBySku($importData['sku']);
if ($productId) {
$product->load($productId);
}
else {
$productTypes = $this->getProductTypes();
$productAttributeSets = $this->getProductAttributeSets();
/**
* Check product define type
*/
if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
$value = isset($importData['type']) ? $importData['type'] : '';
$message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
Mage::throwException($message);
}
$product->setTypeId($productTypes[strtolower($importData['type'])]);
/**
* Check product define attribute set
*/
if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
$message = Mage::helper('catalog')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
Mage::throwException($message);
}
$product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
foreach ($this->_requiredFields as $field) {
$attribute = $this->getAttribute($field);
if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
Mage::throwException($message);
}
}
}
$this->setProductTypeInstance($product);
if (isset($importData['category_ids'])) {
$product->setCategoryIds($importData['category_ids']);
}
foreach ($this->_ignoreFields as $field) {
if (isset($importData[$field])) {
unset($importData[$field]);
}
}
if ($store->getId() != 0) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
if (!in_array($store->getWebsiteId(), $websiteIds)) {
$websiteIds[] = $store->getWebsiteId();
}
$product->setWebsiteIds($websiteIds);
}
if (isset($importData['websites'])) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
$websiteCodes = explode(',', $importData['websites']);
foreach ($websiteCodes as $websiteCode) {
try {
$website = Mage::app()->getWebsite(trim($websiteCode));
if (!in_array($website->getId(), $websiteIds)) {
$websiteIds[] = $website->getId();
}
}
catch (Exception $e) {}
}
$product->setWebsiteIds($websiteIds);
unset($websiteIds);
}
$custom_options = array();
foreach ($importData as $field => $value) {
if (in_array($field, $this->_inventoryFields)) {
continue;
}
if (in_array($field, $this->_imageFields)) {
continue;
}
$attribute = $this->getAttribute($field);
if (!$attribute) {
/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) {
$values=explode('|',$value);
if(count($values)>0) {
#list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);
foreach($values as $v) {
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price_type = $parts[1];
} else {
$price_type = 'fixed';
}
if(count($parts)>2) {
$price = $parts[2];
} else {
$price =0;
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}
switch($type) {
case 'file':
/* TODO */
break;
case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;
/* NO BREAK */
case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;
case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}
/* END CUSTOM OPTION CODE */
continue;
}
$isArray = false;
$setValue = $value;
if ($attribute->getFrontendInput() == 'multiselect') {
$value = explode(self::MULTI_DELIMITER, $value);
$isArray = true;
$setValue = array();
}
if ($value && $attribute->getBackendType() == 'decimal') {
$setValue = $this->getNumber($value);
}
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
if ($isArray) {
foreach ($options as $item) {
if (in_array($item['label'], $value)) {
$setValue[] = $item['value'];
}
}
} else {
$setValue = false;
foreach ($options as $item) {
if ($item['label'] == $value) {
$setValue = $item['value'];
}
}
}
}
$product->setData($field, $setValue);
}
if (!$product->getVisibility()) {
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
}
$stockData = array();
$inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
: array();
foreach ($inventoryFields as $field) {
if (isset($importData[$field])) {
if (in_array($field, $this->_toNumber)) {
$stockData[$field] = $this->getNumber($importData[$field]);
}
else {
$stockData[$field] = $importData[$field];
}
}
}
$product->setStockData($stockData);
$imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}
foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
}
catch (Exception $e) {}
}
$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);
$product->save();
/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) {
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}
/* Add the custom options specified in the CSV import file */
if(count($custom_options)) {
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}
}
return true;
}
This section of the code has been quite well tested, so it's unlikely (though conceivable) that this is a bug that you need to correct in the indexer. Can you provide more detail about the discrepancy that you are seeing?
There is a very good chance that you are seeing unexpected results because of some product being enabled/disabled, etc etc.

Resources