Skip to content

Instantly share code, notes, and snippets.

@ryaan-anthony
Created March 28, 2015 18:00
Show Gist options
  • Select an option

  • Save ryaan-anthony/f8b3baa60a01d105552b to your computer and use it in GitHub Desktop.

Select an option

Save ryaan-anthony/f8b3baa60a01d105552b to your computer and use it in GitHub Desktop.
Volusion -> Magento import. (easy to reformat)
<?php
class Import
{
protected $store;
function __construct(Mage_Core_Model_Store $store)
{
$this->store = $store;
}
public function getWebsiteId()
{
return $this->store->getWebsiteId();
}
public function importData($data, $callback)
{
$data = array_reverse($data);
foreach($data as $i => $row){
try{
$callback($row);
} catch(Exception $e){
var_dump($e->getMessage());
die();
}
}
}
/**
* Map csv file to assoc array
* @param $filename
* @param string $delimiter
* @return array
*/
public function mapCsv($filename, $delimiter = ',')
{
$count = 0;
$columns = [];
$master = [];
$file = fopen($filename, "r");
while ($data = fgetcsv($file, 0, $delimiter)) {
if(!$count++){
$columns = $data;
continue;
}
$results = [];
foreach($data as $key => $item){
if(!isset($columns[$key])) continue;
$col = trim($columns[$key]);
$results[$col] = trim($item);
}
$master[] = $results;
}
fclose($file);
return $master;
}
/**
* Make a Magento Customer
*
* @param string $firstname
* @param string $lastname
* @param string $email
* @param null $password
* @param null $telephone
* @return Mage_Customer_Model_Customer
*/
public function makeCustomer(
$firstname,
$lastname,
$email,
$password = null,
$telephone = null
)
{
/** @var Mage_Customer_Model_Customer $customer */
$customer = Mage::getModel('customer/customer')->addData([
'store' => $this->store,
'website_id' => $this->store->getWebsiteId(),
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email,
'telephone' => $telephone,
'password' => $password,
]);
$customer->save();
}
public function updateCustomerEmail(
$old_email,
$new_email
)
{
/** @var Mage_Customer_Model_Customer $customer */
$customer = Mage::getModel('customer/customer')
->setWebsiteId($this->getWebsiteId())
->loadByEmail($old_email);
if($customer->getId()){
$customer->setEmail($new_email);
$customer->save();
}
}
public function makeGiftcard(
$code,
$balance,
$created,
$expires = null
)
{
$giftcardaccount = Mage::getModel('enterprise_giftcardaccount/giftcardaccount');
$created = new Zend_Date($created);
if($expires){
$expires = new Zend_Date($expires);
$expires = $expires->toString('Y-M-d H:m:s');
}
$giftcardaccount->setData([
'status' => 1,
'store' => $this->store,
'website_id' => $this->store->getWebsiteId(),
'code' => $code,
'balance' => $balance,
'date_created' => $created->toString('Y-M-d H:m:s'),
'date_expires' => $expires,
]);
$giftcardaccount->save();
return $giftcardaccount;
}
public function makeOrder(
$customer,
$billing_address,
$shipping_address,
$products,
$payment_method,
$shipping_method,
$date,
$shipping_amount,
$tax_amount,
$discount_amount,
$total_amount
)
{
try {
// create order
$quote = Mage::getModel('sales/quote')->setStoreId($this->store->getId());
$quote->setIsSuperMode(true);
$quote->assignCustomer($customer);
$billingAddress = $quote->getBillingAddress()->addData($billing_address->getData());
$shippingAddress = $quote->getShippingAddress()->addData($shipping_address->getData());
foreach($products as $product){
$quote->addProduct($product['model'], new Varien_Object($product['buyInfo']));
}
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($shipping_method)
->setPaymentMethod($payment_method);
$quote->getPayment()->importData(['method' => $payment_method]);
$quote->collectTotals()->save();
$shippingAddress->setBaseGrandTotal($total_amount);
$shippingAddress->setGrandTotal($total_amount);
$shippingAddress->setShippingAmount($shipping_amount);
$shippingAddress->setDiscountAmount($discount_amount);
$shippingAddress->setTaxAmount($tax_amount);
/** @var Mage_Sales_Model_Service_Quote $service */
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
if($mage_order = $service->getOrder()){
$date = new Zend_Date($date);
$mage_order->setCreatedAt($date->toString('Y-M-d H:m:s'));
$mage_order->setUpdatedAt($date->toString('Y-M-d H:m:s'));
$mage_order->save();
if(!$mage_order->canInvoice()) Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
$invoice = Mage::getModel('sales/service_order', $mage_order)->prepareInvoice();
if (!$invoice->getTotalQty()) Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
if($mage_order->canShip()){
$itemQty = $mage_order->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $mage_order)->prepareShipment($itemQty);
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment->create($mage_order->getIncrementId());
}
return $mage_order;
}
}
catch (Exception $e) {
print_r($e->getMessage());
die();
}
return false;
}
public function loadProduct($sku)
{
/** @var Mage_Catalog_Model_Product $model */
$model = Mage::getModel('catalog/product');
$product = $model->loadByAttribute('sku', $sku);
if($product && $product->getId()){
return $product;
}
return false;
}
}
<?php
chdir(dirname(__FILE__));
require '../app/Mage.php';
require 'lib/Import.php';
Mage::register('isSecureArea', true);
Mage::app()->setUpdateMode(false);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
ini_set('memory_limit', -1);
// importing into default store
$import = new Import(Mage::app()->getStore(Mage_Core_Model_App::DISTRO_STORE_ID));
/**
* Import Customers
*/
// required headers = customerid, emailaddress, firstname, lastname, phonenumber
$customers = $import->mapCsv('../var/import/customers.csv');
$import->importData($customers, function($row) use ($import){
$customer = Mage::getModel('customer/customer')
->setWebsiteId($import->getWebsiteId())
->loadByEmail($row['emailaddress']);
if(!$customer->getId() && $row['emailaddress'] && $row['firstname'] && $row['lastname']){
$import->makeCustomer(
$row['firstname'],
$row['lastname'],
$row['emailaddress'],
'tempPASSimportFROMoldSYTEM',
$row['phonenumber']
);
}
});
/**
* Import Giftcards
*/
// required headers = giftcardid, giftamount, datecreated
$giftcards = $import->mapCsv('../var/import/giftcards.csv');
$import->importData($giftcards, function($row) use ($import){
$import->makeGiftcard(
$row['giftcardid'],
$row['giftamount'],
$row['datecreated']
);
});
/**
* Import Orders
*/
// required headers = orderid,customerid,billingfirstname,billinglastname,billingaddress1,billingaddress2,billingcity,billingstate,billingpostalcode,billingcountry,billingphonenumber,shipfirstname,shiplastname,shipaddress1,shipaddress2,shipcity,shipstate,shippostalcode,shipcountry,shipphonenumber,paymentamount,orderdate,salestaxrate
$orders = $import->mapCsv('../var/import/orders.csv');
// required headers = orderid, quantity, productcode
$order_items = $import->mapCsv('../var/import/order_items.csv');
$import->importData($orders, function($row) use ($import, $customers, $order_items){
$products = [];
foreach($order_items as $order_item){
if($order_item['orderid'] != $row['orderid']) continue;
if(!$order_item['quantity']) continue;
if($product = $import->loadProduct($order_item['productcode'])){
$products[] = [
'model' => $product,
'buyInfo' => ['qty' => $order_item['quantity']],
];
}
}
if($products){
foreach($customers as $customer){
if($customer['customerid'] == $row['customerid']){
$row['email'] = $customer['emailaddress'];
break;
}
}
// email required
if(!isset($row['email']) || !$row['email']) return;
// set customer
$customer = Mage::getModel('customer/customer')
->setWebsiteId($import->getWebsiteId())
->loadByEmail($row['email']);
if(!$customer->getId()){
$customer = $import->makeCustomer(
$row['billingfirstname'],
$row['billinglastname'],
$row['email'],
'tempPASSimportFROMoldSYTEM',
$row['billingphonenumber']
);
}
if(!$customer || !$customer->getId()) return;
#echo "...assigning customer id ".$customer->getId().PHP_EOL;
// set addresses
$shipping_address = Mage::getModel("customer/address");
$billing_address = Mage::getModel("customer/address");
foreach($customer->getAddresses() as $address){
$street = $address->getStreet(1);
if(strtolower($street) == strtolower($row['billingaddress1'])){
$billing_address = $address;
}
if(strtolower($street) == strtolower($row['billingaddress1'])){
$shipping_address = $address;
}
}
// create address
if(!$billing_address->getId()){
$region = Mage::getModel('directory/region')->loadByCode($row['billingstate'], $row['billingcountry']);
if(!$region_id = $region->getId()){return;}
$billing_address->setCustomerId($customer->getId())
->setFirstname($customer->getFirstname())
->setLastname($customer->getLastname())
->setCountryId($row['billingcountry'])
->setRegionId($region_id)
->setPostcode($row['billingpostalcode'])
->setCity($row['billingcity'])
->setTelephone($row['billingphonenumber'])
->setStreet([$row['billingaddress1'], $row['billingaddress2']])
->setIsDefaultBilling('1')
->setSaveInAddressBook('1');
$billing_address->save();
}
// create address
if(!$shipping_address->getId()){
$region = Mage::getModel('directory/region')->loadByCode($row['shipstate'], $row['shipcountry']);
if(!$region_id = $region->getId()){return;}
$shipping_address->setCustomerId($customer->getId())
->setFirstname($customer->getFirstname())
->setLastname($customer->getLastname())
->setCountryId($row['shipcountry'])
->setRegionId($region_id)
->setPostcode($row['shippostalcode'])
->setCity($row['shipcity'])
->setTelephone($row['shipphonenumber'])
->setStreet([$row['shipaddress1'], $row['shipaddress2']])
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
$shipping_address->save();
}
// create order
$order = $import->makeOrder(
$customer,
$billing_address,
$shipping_address,
$products,
// requires checkmo to be enabled
'checkmo',
// requires flatrate shipping to be enabled
'flatrate_flatrate',
strtotime($row['orderdate']),
$row['totalshippingcost'],
$row['salestaxrate'],
0, // discount
$row['paymentamount']
);
if($order){
// set your own increment id
$order->setIncrementId($row['orderid']);
$order->save();
}
}
});
Mage::unregister('isSecureArea');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment