I'm developing an import products cron.
In my code I have:
if ($supplier = Supplier::getIdByName(trim($prodotto['Supplier']['Name']))) {
$product->id_supplier = (int)$supplier;
} else {
$supplier = new Supplier();
$supplier->name = $prodotto['Supplier']['Name'];
$supplier->active = true;
$supplier->add();
$product->id_supplier = (int)$supplier->id;
$supplier->associateTo($product->id_shop_list);
}
The result is:
product created
supplier created
product without supplier
Where am I wrong?
You have to add also a new ProductSupplier, after you saved te new product use this snippet of code (obviously, adapt it to your needs :)):
// Product supplier
if (isset($product->id_supplier) && property_exists($product, 'supplier_reference'))
{
$id_product_supplier = ProductSupplier::getIdByProductAndSupplier((int)$product->id, 0, (int)$product->id_supplier);
if ($id_product_supplier)
$product_supplier = new ProductSupplier((int)$id_product_supplier);
else
$product_supplier = new ProductSupplier();
$product_supplier->id_product = $product->id;
$product_supplier->id_product_attribute = 0;
$product_supplier->id_supplier = $product->id_supplier;
$product_supplier->product_supplier_price_te = $product->wholesale_price;
$product_supplier->product_supplier_reference = $product->supplier_reference;
$product_supplier->save();
}
Related
When added from a third-party product to the cart. I want to change the quantity of goods in the basket. Get alert Product (........ ) is over.
if(is_array($arCartPrice)){
//if($arCartPrice['OPTIONS']['MINIMUM']>1){$QUANTITY=$arCartPrice['OPTIONS']['MINIMUM'];}else{$QUANTITY=1;}
$QUANTITY=$arCartPrice['AVAILABLE_NUM'];
$DefaultCategory = 12;
$DefaultTaxGroup = 0;
$Price = $arCartPrice['PRICE_CONVERTED'];
$PriceVAT = round($Price);
$Reference = $arCartPrice['ARTICLE'].' / '.$arCartPrice['BRAND'];
//Presta init
global $context;
if(!$context){$context = Context::getContext();}
$logged = $context->cookie->__get('logged');
$id_cart = $context->cookie->__get('id_cart');
$id_lang = $context->cookie->__get('id_lang');
$id_guest = $context->cookie->__get('id_guest');
$id_currency = $context->cookie->__get('id_currency');
// Add cart if no cart found
if (!$id_cart){
$context->cart = new Cart();
$context->cart->id_customer = $context->customer->id;
$context->cart->id_currency = $id_currency;
$context->cart->add();
if($context->cart->id){
$context->cookie->id_cart = (int)$context->cart->id;
}
$id_cart = (int)$context->cart->id;
}
$doAdd="Y";
//if(!$logged>0){$doAdd="N"; $TCore->arErrorMessages[] = 'You must be logged in to buy products';}
//if(trim($Reference)=='' OR !$Price>0 OR !$QUANTITY>0){$doAdd="N"; $TCore->arErrorMessages[] = 'Add to cart data is missing!';}
if(!$id_cart>0){$doAdd="N"; ErAdd("Your cookie <b>id_cart</b> is wrong!",1);}
if(!$id_lang>0){$doAdd="N"; ErAdd("Your cookie <b>id_lang</b> is wrong!",1);}
if($doAdd!="N"){
//Check avail. tecdoc item in Presta
$sql = 'SELECT p.`id_product`, pl.`name` FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product`)
WHERE pl.`id_lang` = '.$id_lang.' AND
p.`price` = '.$Price.' AND
p.`reference` = "'.$Reference.'"
';
$arRes = Db::getInstance()->executeS($sql);
if(count($arRes)>0){
$NewTID = $arRes[0]['id_product'];
}else{
//Supplier data (for 1C integration)
$supplierName = $arCartPrice['SUPPLIER_STOCK'];
$supplierId = $suppliers = (Supplier::getIdByName($supplierName));
if (!$supplierId) {
$supplier = new Supplier();
$supplier->name = $supplierName;
$supplier->active = 1;
$supplier->add();
$supplierId = $supplier->id;
}
$obProduct = new Product(false,false,$id_lang);
$obProduct->id_category_default = $DefaultCategory;
$obProduct->unity = $arCartPrice['ADD_URL'];
$obProduct->name = $arCartPrice['ARTICLE'] .' / '.substr($arCartPrice['NAME'],0,400).' / '.$arCartPrice['BRAND'];
$obProduct->description = 'This product is created automatically by ';
$obProduct->description_short = $arCartPrice['SUPPLIER_STOCK'].' ['.$arCartPrice['DAY'].' days]';
$obProduct->price = $Price;
$obProduct->wholesale_price = $arCartPrice['PRICE'];
$obProduct->reference = $Reference;
$obProduct->link_rewrite = $arCartPrice['CPID'];
$obProduct->available_for_order = 1; //true
$obProduct->visibility = 'none';
$obProduct->is_virtual = 0;
//$obProduct->weight = round($arCartPrice['OPTIONS']['WEIGHT']/1000,2);
$obProduct->minimal_quantity = 1;
$obProduct->condition = 'used';
$obProduct->condition = 'refurbished';
$obProduct->available_now = $arCartPrice['AVAILABLE_NUM'];
$obProduct->quantity = $arCartPrice['AVAILABLE_NUM'];
//supplier
$obProduct->supplier_name = $supplierName;
$obProduct->id_supplier = $supplierId;
$obProduct->id_tax_rules_group = $DefaultTaxGroup;
//echo '<br><pre>';print_r($obProduct);echo '</pre>';die();
$obProduct->add();
if($obProduct->id>0){
$NewTID = $obProduct->id;
$obProduct->setWsCategories(Array(Array("id"=>$DefaultCategory)));
//Add image
if($arCartPrice['IMG_SRC']!='' AND $NewTID>0){
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $NewTID;
$image->position = Image::getHighestPosition($NewTID)+1;
$image->cover = true; // or false;
if(($image->validateFields(false, true)) === true && ($image->validateFieldsLang(false, true)) === true && $image->add()){
$image->associateTo($shops);
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
if(Tools::copy($arCartPrice['IMG_SRC'], $tmpfile)){
$path = $image->getPathForCreation();
ImageManager::resize($tmpfile, $path.'.jpg');
}
unlink($tmpfile);
}
}
}else{
ErAdd("Prestashop new Item ID is false",1);
}
unset($obProduct);
}
if($NewTID>0){
//if($arCartPrice['AVAILABLE']>0){StockAvailable::setQuantity($NewTID, false, $arCartPrice['AVAILABLE']);}
StockAvailable::setQuantity($NewTID, 0, (int) $arCartPrice['AVAILABLE']);
$obCart = new Cart($id_cart);
$obCart->id_lang = $id_lang;
$obCart->id_currency = $id_currency;
if($obCart->updateQty((int)$QUANTITY=1, (int)$NewTID)){
Header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); die();
}else{
ErAdd(" Add to Cart is false. NewTID=".$NewTID,1);
}
How to fix the code so you can update the quantity of goods in your cart.
And the number of 10 pieces. 1 piece is added to the cart. I want to add more to my cart. How to implement it? When I add 2 pieces. I receive a message Product (........ ) is over..
enter image description here
First of all, after you created the product, check in the Backoffice if the quantity is well stored (If the newly created product quantity is equal with $arCartPrice['AVAILABLE_NUM'] )
Maybe you can try with enabled "Allow ordering when out of stock" .
How to Update in existing quantity in amazon seller using amazon marketplace web service.when update product then old quantity remove and new quantity add.but I want existing quantity Update. For ex. old Quantity 5 then update 10 more Quantity then total quantity 5+10 = 15.
My Code.
require_once 'vendor/autoload.php';
if ($client->validateCredentials()) {
$product = new MCS\MWSProduct();
$product->sku = $request['ItemSKU'];
$product->price = $request['SalePrice'];
$product->quantity = $request['Qty'];
$product->product_id = $request['ASINNo'];;
$product->product_id_type = $request['ProductType'];;
$product->condition_type = $request['ConditionType'];;
$product->title = $request['Title'];;
$product->sale_price = $request['SalePrice'];
//print_r($product);
if ($product->validate()) {
$result = $client->postProduct($product);
if($result){
$arr['status'] = TRUE;
$arr['submitid'] = $result['FeedSubmissionId'];
$info = $client->GetFeedSubmissionResult($result['FeedSubmissionId']);
}
}
2 . One another code :
$client = new MCS\MWSClient([
'Marketplace_Id' => $Amazon_MarketPlaceId,
'Seller_Id' => $Amazon_SellerId,
'Access_Key_ID' => $Amazon_AWSAccessKeyId,
'Secret_Access_Key' => $Amazon_SecretKey,
'MWSAuthToken' => $Amazon_MWSAuthToken
]);
if ($client->validateCredentials()) {
foreach($request as $key => $value){
$SKU_Prices[$key] = $value;
}
if(!empty($SKU_Prices)){
$result = $client->updatePrice($SKU_Prices);
if($result){
$arr['status'] = TRUE;
$arr['submitid'] = $result['FeedSubmissionId'];
}else{
$arr['status'] = FALSE;
$arr['submitid'] = 0;
}
}
}
Please let me know how to Update.
I'm making a script that should make a copy of an existing order.
I can create the overall order, with this code:
$order = new Order($_GET["id_order"]);
$order->add();
But there's no products in the order - I tried with this:
$order_detail = new OrderDetail($_GET["id_order"]);
$order_detail->add();
What am I doing wrong, how can I copy an existing order?
You can duplicate an order using the duplicateObject() method from the ObjectModel class.
Here is a function that should do the trick :
function duplicateOrder($id_order)
{
$order = new Order($id_order);
$duplicatedOrder = $order->duplicateObject();
$orderDetailList = $order->getOrderDetailList();
foreach ($orderDetailList as $detail) {
$orderDetail = new orderDetail($detail['id_order_detail']);
$duplicatedOrderDetail = $orderDetail->duplicateObject();
$duplicatedOrderDetail->id_order = $duplicatedOrder->id;
$duplicatedOrderDetail->save();
}
$orderHistoryList = $order->getHistory(Configuration::get('PS_LANG_DEFAULT'));
foreach ($orderHistoryList as $history) {
$orderHistory = new OrderHistory($history['id_order']);
$duplicatedOrderHistory = $orderHistory->duplicateObject();
$duplicatedOrderHistory->id_order = $duplicatedOrder->id;
$duplicatedOrderHistory->save();
}
}
I am trying to send the order info from Woocommerce into Netsuite as a sale order, when creating a new order. In order to create a new sale order by PHP toolkit, it is necessary for me to create Assembly Items first.
Is there a way to create a new Item using PHP-toolkit?
Here is a PHP code snippet for creating a new Item myself.
$service = new NetSuiteService();
$ai = new AssemblyItem();
// Rustica Group Item Form - 20
$ai->customForm = new RecordRef();
$ai->customForm->internalId = 20;
$ai->memberList = new ItemMemberList();
$item_member = array();
$itemMember = new ItemMember();
$itemMember->internalId = 186625;
$item_member[] = $itemMember;
$ai->memberList->itemMember = $item_member;
$ai->itemId = 'Hardware' . $data['itemId'];
$ai->displayName = $data['displayName'];
$ai->vendorName = '';
$ai->cost = $data['price'];
$ai->isTaxable = $data['taxable'];
$ai->description = $data['description'];
$request = new AddRequest();
$request->record = $ai;
$addResponse = $service->add($request);
print_r($addResponse);
if (!$addResponse->writeResponse->status->isSuccess) {
return "ADD ERROR";
} else {
return $addResponse->writeResponse->baseRef->internalId;
}
There is no internalid field for ItemMember. Look at the schema
Should look like this...
$itemMember = new ItemMember();
$itemMember->item = new RecordRef();
$itemMember->item->internalId = 186625;
You're missing taxSchedule too..not sure if you are confusing that with isTaxable
$ai->taxSchedule = new RecordRef();
$ai->taxSchedule->internalId = 1; //whatever tax schedule you're using
You should pre-store the item of the product before saving the product that you want to send from Woocommerce into Netsuite.
If you store the item on netsuite, they will return the internal_id of the item.
Then, you can save the item with internal id that they return.
I'm using these two methods to create orders programmatically in Magento.
The first one creates a Quote:
public function prepareCustomerOrder($customerId, array $shoppingCart, array $shippingAddress, array $billingAddress,
$shippingMethod, $couponCode = null)
{
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$storeId = $customerObj->getStoreId();
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeObj = $quoteObj->getStore()->load($storeId);
$quoteObj->setStore($storeObj);
// add products to quote
foreach($shoppingCart as $part) {
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->setStore($storeId)->setStoreId($storeId)->load($part['PartId']);
$productObj->setSkipCheckRequiredOption(true);
try{
$quoteItem = $quoteObj->addProduct($productObj);
$quoteItem->setPrice(20);
$quoteItem->setQty(3);
$quoteItem->setQuote($quoteObj);
$quoteObj->addItem($quoteItem);
} catch (exception $e) {
return false;
}
$productObj->unsSkipCheckRequiredOption();
$quoteItem->checkData();
}
// addresses
$quoteShippingAddress = new Mage_Sales_Model_Quote_Address();
$quoteShippingAddress->setData($shippingAddress);
$quoteBillingAddress = new Mage_Sales_Model_Quote_Address();
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setShippingAddress($quoteShippingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);
// coupon code
if(!empty($couponCode)) $quoteObj->setCouponCode($couponCode);
// shipping method an collect
$quoteObj->getShippingAddress()->setShippingMethod($shippingMethod);
$quoteObj->getShippingAddress()->setCollectShippingRates(true);
$quoteObj->getShippingAddress()->collectShippingRates();
$quoteObj->collectTotals(); // calls $address->collectTotals();
$quoteObj->setIsActive(0);
$quoteObj->save();
return $quoteObj->getId();
}
And the second one uses that Quote to create Order:
public function createOrder($quoteId, $paymentMethod, $paymentData)
{
$quoteObj = Mage::getModel('sales/quote')->load($quoteId); // Mage_Sales_Model_Quote
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
// set payment method
$quotePaymentObj = $quoteObj->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
// convert quote to order
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
// convert quote addresses
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
// set payment options
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if ($paymentData) {
$orderObj->getPayment()->setCcNumber($paymentData->ccNumber);
$orderObj->getPayment()->setCcType($paymentData->ccType);
$orderObj->getPayment()->setCcExpMonth($paymentData->ccExpMonth);
$orderObj->getPayment()->setCcExpYear($paymentData->ccExpYear);
$orderObj->getPayment()->setCcLast4(substr($paymentData->ccNumber,-4));
}
// convert quote items
foreach ($items as $item) {
// #var $item Mage_Sales_Model_Quote_Item
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options) {
$orderItem->setProductOptions($options);
}
if ($item->getParentItem()) {
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$orderObj->setCanShipPartiallyItem(false);
try {
$orderObj->place();
} catch (Exception $e){
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
}
$orderObj->save();
//$orderObj->sendNewOrderEmail();
return $orderObj->getId();
}
The process works fine, no errors, and the order is created. But the total is 0 and there are no products in it no matter what I put.
I've traced it and I can confirm that the rows are added to the sales_flat_quote and sales_flat_quote_item tables, so that is ok. But when running the createOrder and calling
$items = $quoteObj->getAllItems();
an empty array is always returned, and I have no idea why. I have configurable and simple products in my shop. This happens when I add simple, when I add configurable the error appears as the method
$quoteItem = $quoteObj->addProduct($productObj);
returns null.
It seems to me, you didn't load product collection, therefore, the cart always return empty. Try this link, it will give you more clear help. Create order programmatically
// this is get only one product, you can refactor the code
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'Some value here...')
->addAttributeToSelect('*')
->getFirstItem();
// load product data
$this->_product->load($this->_product->getId());
This code worked for me,
public function createorder(array $orderdata)
{
$quoteId = $orderdata['quoteId'];
$paymentMethod = $orderdata['paymentMethod'];
$paymentData = $orderdata['paymentData'];
$quoteObj = Mage::getModel('sales/quote')->load($quoteId);
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
$quotePaymentObj = $quoteObj->getPayment();
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
foreach ($items as $item)
{
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()))
{
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options'))
{
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options)
{
$orderItem->setProductOptions($options);
}
if ($item->getParentItem())
{
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$quoteObj->collectTotals();
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
$orderObj->setCanShipPartiallyItem(false);
try
{
$last_order_increment_id = Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId();
return $last_order_increment_id;
}
catch (Exception $e)
{
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
return "Exception:".$e;
} }
I had the same problem and delved into the API to find a solution. I changed the way that I loaded a product by using :
$productEntityId = '123456';
$store_code = 'my_store_code';
$product = Mage::helper('catalog/product')->getProduct($productEntityId,Mage::app()->getStore($store_code)->getId());
I found this tutorial to be very useful too :
http://www.classyllama.com/content/unravelling-magentos-collecttotals
If you are looking for a script on order creation this is a very good start :
http://pastebin.com/8cft4d8v
Hope that this helps someone ;)