Magento - Cronjob outside magento to update shipment status - magento

I am working on a script which is out of magento framework and will be programmed to get all shipments and tracking number.
After getting these shipments and tracking number i will check with shipping provider and update the status of shipment and order based on if its dispatched / scanned or delivered.
following is half done code and I am stuck,
<?php
require_once 'app/Mage.php';
Mage::app('default');
$myShipment=Mage::getModel('sales/order_shipment');
$shipment=Mage::getResourceModel('sales/order_shipment_collection')
->addAttributeToSelect('*');
$allIds=$shipment->getAllIds();
foreach($allIds as $thisId) {
$myShipment->load($thisId)->getAllTrackings();
echo "<pre>";
print_r($myShipment);
echo "</pre>";
}
Please help,
Thanks and Regards,
Saurabh

Once shipment and invoice are created for an order it is set to a status of "Complete". Not sure what you want to change there, but if you have some custom statuses set up in your magento installation you can use the setStatus() method of the order class.
$myShipment->getOrder()->setStatus("YourCustomStatus");
I don't think shipments have statuses, but you can add a comment to a shipment by calling addComment($comment, $notifyCustomer), where first variable is a string and second is bool.
$myShipment->addComment("01/01/2010 06:55, Out for delivery", true);
You can also add a comment to the order using a similar method:
$myShipment->getOrder()->addComment("01/01/2010 06:55, Out for delivery", true);

You can set shipment status - there's a field for it that's set to NULL for me when you query via the shipment.list API
Here's a dump:
Array
(
[0] => Array
(
[store_id] => 1
[total_weight] =>
[total_qty] => 1.0000
[email_sent] => 1
[order_id] => 3
[customer_id] => 1
[shipping_address_id] => 6
[billing_address_id] => 5
[shipment_status] =>
[increment_id] => 100000001
[created_at] => 2010-11-11 15:41:41
[updated_at] => 2010-11-11 15:44:05
[shipment_id] => 1
)
It doesn't look like you can set it via the WS API, which means that you'll need to include mage.php in your external script and then update the shipment via magento (as silvo has shown above). Sorry, I don't have the syntax to hand but I suspect you would update based on the shipment ID as opposed to the order. This means that you will need to create a shipment first (again, this can be done via the webservices API via the shipment.create method (details on the same page as the prior link).
I hope this sets you on the right path. If anyone has any working code for doing this (which brought me to this post originally) PLEASE feel free to share. :)

Related

add catalog item and category to purchase via transactions api

Im using payment form and square transaction api to retrieve payment but it's showing up uncategorized in square dashboard. Is there an easy way to add the catalog item to the transaction api code i've already written?
can i simply add the link to the new order item under the request_body array?
$request_body = array (
"card_nonce" => $nonce,
)
$txRequest['item_id'] = "my item id";
If anyone has a tutorial that would be much appreciated.
I figured it out.
I had to create and Order with the orders api, then pass the order_id to the charge code. In php it looks like this.
.......create order here using orders api(code not shown)......
...pass order_id to charge(in php)...
mix of variables for nonce, etc...
............
$request_body = array (
"card_nonce" => $nonce,
"buyer_email_address" => $be,
"note" => "online Laser Tag reservation",
"amount_money" => array (
"amount" => $totalCost,
"currency" => "USD")
"order_id" => $my_order_id,
"idempotency_key" => uniqid()
};
...try/catch statements...
You'll want to use CreateOrder to create an order of items. Then you can pass in the order_id to the Transactions API (what you will use after the payment form to call the Charge endpoint). See here: https://docs.connect.squareup.com/payments/transactions/cookbook/itemize-transactions

Custom Promotion for Selected Products When Using Specific Shipping Method

I'm a trying to create a module in Magento that will allow the admin to select products and categories that are eligible for a discount on shipping when using a specific shipping method.
I began by making a custom section in System->Config and adding an enable/disable option using the system.xml file for each product individually. When the rate for the shipping method is calculated, I would scan the items in the cart and if one was enabled in the admin, the discount would be applied.
My problem is that this method is only really feasible for stores with a small amount of products. I suspect that there is a better way to solve this problem within Magento, but I have not had much luck finding any information on the topic so far. Is there a better way to accomplish this task?
1) Create an attribute 'eligible_for_discount' with options Yes/No
2) Create a CSV file having product_id and assign attribute 'eligible_for_discount' with values 'Yes/No' (i.e. 1 or 0) to whichever products you want to have discount applied.
3) Import the CSV file from Magento Admin.
4) On the cart page you can check if the product contains the attribute value for 'eligible_for_discount' and if Yes, then apply discount.
While the other answer was great as a guide, there were a couple of things that gave me some trouble that I want to try and clarify. I decided to create a product attribute using an install script. I placed the following code in my mysql4-install-0.1.0.php file:
$entity = $this->getEntityTypeId('catalog_product');
$this->addAttribute($entity, 'reduced_shipping', array(
'type' => 'varchar',
'input' => 'boolean',
'label' => 'Product Qualified For Free Shipping',
'visible' => true,
'default' => '0',
'required' => true,
'used_in_forms' => array(
'adminhtml_checkout',
'adminhtml_customer',
'admin_html_customer_address',
'checkout_register',
'customer_account_create',
'customer_account_edit',
'customer_address_edit',
'customer_register_address',
)
));
While boolean is a valid form of input when creating attributes, it looks like it cannot be used to store the attribute type. This can be solved by using varchar instead. After the setup script has been run, the admin can go to Catalog->Manage Products, where they can select Yes or No for the Free Shipping attribute on each item.
Finally, I used the following in the collectRates() method of the Carrier that I created to cycle through the items in the customer's cart and see if the admin has selected them for free shipping.
$quote = Mage::getModel('checkout/session')->getQuote();
$itemList = $quote->getAllVisibleItems();
foreach($itemList as $item)
{
$product = Mage::getModel('catalog/product')->load($item->getProductId());
if($product->getReducedShipping() == 1)
{
//update the price of shipping here
}
}
I've skimmed over a couple things to keep this answer from getting too long, so let me know if there is any part that I can clarify.

Custom Magento Report for Taxable/Non-Taxable sales

Let me preface by saying I'm new to Magento as well as Data Collections in general (only recently begun working with OOP/frameworks).
I've followed the excellent tutorial here and I'm familiar with Alan Storm's overviews on the subject. My aim is to create a custom Magento report which, given a start/end date, will return the following totals:
Taxable Net (SUM subtotal for orders with tax)
Non-Taxable Net (SUM subtotal for orders without tax)
*Total Gross Sales (Grand total)
*Total Net Sales (Grand subtotal)
*Total Shipping
*Total Tax
*For these figures, I realize they are available in existing separate reports or can be manually calculated from them, however the purpose of this report is to give our store owner a single page to visit and file to export to send to his accountant for tax purposes.
I have the basic report structure already in place in Adminhtml including the date range, and I'm confident I can include additional filters if needed for order status/etc. Now I just need to pull the correct Data collection and figure out how to retrieve the relevant data.
My trouble is I can't make heads or tails of how the orders data is stored, what Joins are necessary (if any), how to manipulate the data once I have it, or how they interface with the Grid I've set up. The existing tutorials on the subject that I've found are all specifically dealing with product reports, as opposed to the aggregate sales data I need.
Many thanks in advance if anyone can point me in the right direction to a resource that can help me understand how to work with Magento sales data, or offer any other insight.
I have been working on something extremely similar and I used that tutorial as my base.
Expanding Orders Join Inner
Most of the order information you need is located in sales_flat_order with relates to $this->getTable('sales/order')
This actually already exists in her code but the array is empty so you need to populate it with the fields you want, here for example is mine:
->joinInner(
array('order' => $this->getTable('sales/order')),
implode(' AND ', $orderJoinCondition),
array(
'order_id' => 'order.entity_id',
'store_id' => 'order.store_id',
'currency_code' => 'order.order_currency_code',
'state' => 'order.state',
'status' => 'order.status',
'shipping_amount' => 'order.shipping_amount',
'shipping_tax_amount' => 'order.shipping_tax_amount',
'shipping_incl_tax' => 'base_shipping_incl_tax',
'subtotal' => 'order.subtotal',
'subtotal_incl_tax' => 'order.subtotal_incl_tax',
'total_item_count' => 'order.total_item_count',
'created_at' => 'order.created_at',
'updated_at' => 'order.updated_at'
))
To find the fields just desc sales_flat_order in mysql.
Adding additional Join Left
Ok so if you want information from other tables you need to add an ->joinLeft() for example I needed the shipment tracking number:
Create the Join condition:
$shipmentJoinCondition = array(
$orderTableAliasName . '.entity_id = shipment.order_id'
);
Perform the join left:
->joinLeft(
array('shipment' => $this->getTable('sales/shipment_track')),
implode(' AND ', $shipmentJoinCondition),
array(
'track_number' => 'shipment.track_number'
)
)
Sorry I couldn't go into more depth just dropping the snippet for you here.
Performing Calculations
To modify the data returned to the grid you have to change addItem(Varien_Object $item) in your model, basically whatever is returned from here get put in the grid, and well I am not 100% sure how it works and it seems a bit magical to me.
Ok first things first $item is an object, whatever you do to this object will stay with the object (sorry terrible explanation): Example, I wanted to return each order on a separate line and for each have (1/3, 2/3, 3/3), any changes I made would happen globally to the order object so they would all show (3/3). So keep this in mind, if funky stuff starts happening use PHP Clone.
$item_array = clone $item;
So now onto your logic, you can add any key you want to the array and it will be accessible in Grid.php
For example(bad since subtotal_incl_tax exists) :
$item_array['my_taxable_net_calc'] = $item['sub_total'] + $item['tax'];
Then at the end do:
$this->_items[] = $item_array;
return $this->_items;
You can also add more rows based on the existing by just adding more data to $this->_items[];
$this->_items[] = $item_array;
$this->_items[] = $item_array;
return $this->_items;
Would return same item on two lines.
Sorry I have started to lose the plot, if something doesn't make sense just ask, hope this helped.
Oh and to add to Block/Adminhtml/namespace/Grid.php
$this->addColumn('my_taxable_net_calc', array(
'header' => Mage::helper('report')->__('Taxable Net'),
'sortable' => false,
'filter' => false,
'index' => 'my_taxable_net_calc'
));

magento add last login to customer grid

I am new to Magento. I am trying to add a last login value displaying on customer grid. it returns a null value. I have read other tutorials, but it does not help much. The Magento version is 1.7. Here is my code:
$customer = Mage::getSingleton('customer/session')->getCustomer();
$logCustomer = Mage::getModel('log/customer')->load($customer ->getId());
$lastVisited = $logCustomer->getLoginAt();
$this->addColumn('$lastVisited', array(
'header' => Mage::helper('customer')->__('Last Login'),
'type' => 'datetime',
'align' => 'center',
'index' => '$lastVisited',
'gmtoffset' => true
));
Magento stores the login time in the following table:
log_customer
But also, this data is cleaned periodically (see: Mage_Log_Model_Resource_Log::_cleanCustomers which is triggered via Magento cron).
There are different ways to approach your task.
1) Non-persistent - I am just interested to see recent data (I can ignore that log_customer is cleaned periodically)
In this case you can just rely on the data from log_customer and display it in Manage Customers Grid.
Extend Mage_Adminhtml_Block_Customer_Grid and in _prepareCollection add the following:
$collection->getSelect()->columns(array('last_login_at' => new Zend_Db_Expr ("(SELECT login_at
FROM `log_customer`
WHERE customer_id =e.entity_id
ORDER BY log_id DESC
LIMIT 1)")));
before: $this->setCollection($collection);
Note: use the proper Magento function to get log_customer table name, my query is just for example
2) Persistent - I want to always to see the data
add a new attribute to the customer entity called: last_login_at
(datetime).
add an observer to custom_login event to update this
attribute.
use addColumn function in the grid to display this new attribute.
#user1414056
Regarding your code:
bixe made a fair point related to '$lastVisited' (this just shows
lack of experience in php programming
you seem to also be new to programming (in general) because the addColumn is called only once... do how do you expect your code to make sense?
With a better understanding of Zend Framework and OOP Programming in general you will be able to actually work and get things done with Magento.
Your '$lastVisited' can't work : in php variables are evaluated in a String only when they're in a double quote.
EDIT:
Ok the column system of magento only display value when they're available in the collection linked to the grid..
You'll have to add the log information you want to display in the grid collection.
For an example, take a look at Mage_Adminhtml_Block_Customer_Online_Grid::_prepareCollection()
When it's done, you will add your column with :
$this->addColumn('login_at', array(
'header' => Mage::helper('customer')->__('Last Login'),
'type' => 'datetime',
'align' => 'center',
'index' => 'login_at',
'gmtoffset' => true
));

Magento: Display tier prices at category listing page

I'm trying to display all tier prices on category listing page (catalog/product/list.phtml) but only getting the basic price for a single product.
print_r($_product->getTierPrice());
returns:
Array
(
[0] => Array
(
[price] => 0.5000
[website_price] => 0.5000
[price_qty] => 1
[cust_group] => 32000
)
)
for each product. On the product info page it works w/o problems. Please advise.
ver. 1.5.0.1
UPDATE:
Here is the solution for the problem inspired with the answer below:
$resource = Mage::getSingleton('core/resource');
$query = 'SELECT * FROM ' . $resource->getTableName('catalog/product') . '_tier_price';
$_tier_prices = $resource->getConnection('core_read')->fetchAll($query);
var_dump($_tier_prices);
This is another way to get the tier prices
Mage::getResourceModel('catalog/product_attribute_backend_tierprice')
->loadPriceData($product_id,Mage::app()->getWebsite()->getId());
The response is array with prices
[0] => Array
(
[price_id] => 7
[website_id] => 0
[all_groups] => 1
[cust_group] => 0
[price] => 32.0000
[price_qty] => 6.0000
)
[1] => Array
(
[price_id] => 8
[website_id] => 0
[all_groups] => 1
[cust_group] => 0
[price] => 31.0000
[price_qty] => 12.0000
)
If you are looking for a Magento way:
$attribute = $_product->getResource()->getAttribute('tier_price');
if ($attribute) {
$attribute->getBackend()->afterLoad($_product);
$tierPrices = $_product->getTierPrice();
}
From /app/code/core/Mage/Catalog/Model/Product/Type/Price.php getTierPrice()
It's been a while since this was asked/answered, but I just needed to do this and found a better way, so as to not use direct database access.
As mentioned before, the $_product object by default doesn't contain the $_tierPrices on the product list page ... but if you set the tier_price value to null, it retrieves the actual values from the database and populates the object. So, wherever you need the tier prices, add:
$_product->setData('tier_price',null);
$_tierPrices = $this->getTierPrices($_product);
This should ensure the tier prices are populated in the object, so you can use it on any page.
Just keep in mind this does still incur the same performance hit as the direct db access.
All objects in Magento can potentially be created differently on different pages, and have different data in them. It might seem unintuitive at first. It happens that the db query that loads the data into the $_product object on the Item page has pretty much "all" the data in it. But for optimization purposes the $_product used on the category page only has some of the data - and if I remember correctly, it even pulls from different db tables. For example, the the query on the category page joins against the catalogindex* tables for some of the data that would normally be retrieved from the regular eav table.
I don't have any specifics to give to you but you can look at querying directly against the catalog_product_entity_tier_price table, which has all the tier pricing. At least that is the table name in my version of magento, which isn't 1.5. Side effect would be that the category page will take longer to load due to the extra query/queries.
I've tried the answers above and some others online and none of them worked so I put together a few hacks into 1 and this is how you can get it to work anywhere. I even have a custom Home Page Carousel that is pulling it like this.
1. You start off by making a connection somewhere near the top outside of the loop
$wh_resource = Mage::getSingleton('core/resource');
$wh_readConnection = $wh_resource->getConnection('core_read');
2. Get the customer id
$wh_customer = Mage::getSingleton('customer/session')->getCustomer();
$wh_id = $wh_customer->getGroupId();
3. Next we go into the loop where you have your price echo
Note: below im using a hard code of 2 because Wholesale is 2 by default. You can build your own if/else & queries
if($wh_id == 2){
//get id
$_eid = $_helper->productAttribute($_product, $_product->getId(), 'entity_id');
$wh_query = 'SELECT * FROM catalog_product_entity_group_price WHERE entity_id = '.$_eid.' LIMIT 1';
$wh_results = $wh_readConnection->fetchAll($wh_query);
//var_dump($wh_results);
/* var dump would look like this
array(1) { [0]=>
array(6) {
["value_id"]=> string(1) "1"
["entity_id"]=> string(1) "3"
["all_groups"]=> string(1) "0"
["customer_group_id"]=> string(1) "2"
["value"]=> string(6) "9.5000"
["website_id"]=> string(1) "0"
}
}
*/
$wh_price = substr($wh_results[0]["value"], 0, -2); // this damn database gives us extra 00
echo '<div class="price-box"><span class="regular-price"><span class="price">$'.$wh_price.'</span></span></div>';
} else {
//not wholesale
echo $this->getPriceHtml($_product, true);
}
Well, that's how I did it. Feel free to contact me if you need any help
Inside app/design/frontend/your_theme/default/template/catalog/product/list.phtml
add this inside the foreach loops for grid and/or list
<?php $this->setProduct(Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($_product->getId()))?>
<?php echo $this->getTierPriceHtml() ?>
Go to the Manage Attributes and edit the attributes that you want to appear.
Maybe the products don't appear in the product listing because they wasn't configured to do that, so, in the edit attribute page, check if this is activated:
Used in Product Listing

Resources