Magento - API not being updated - php

The previous provider killed several kittens by changing the core many times of a Magento 1.6.2.0 distribution.
So, in order to solve an issue in record time, we had to screw and hit the kittens' corspses: we still maintain the modified API: catalog_category.assignProduct.
So far, we have this API for the method:
public function assignProduct($categoryId, $productId, $position = null, $identifierType = null)
{
$datos = explode('|', $categoryId);
$productId = array_shift($datos);
$categorias_actuales = Mage::getModel('catalog/category')
->getCollection()
->addIsActiveFilter()
->addIdFilter($datos)
->addLevelFilter(3)
->getAllIds();
$incat = function($cat) use ($categorias_actuales) {
return in_array($cat, $categorias_actuales);
};
$result = array_combine($datos, array_map($incat, $datos));
try {
$product = Mage::helper('catalog/product')->getProduct($productId, null, $identifierType);
$product->setCategoryIds($categorias_actuales);
$product->save();
} catch (Mage_Core_Exception $e) {
$this->_fault('data_invalid', $e->getMessage());
} catch (Exception $e) {
$this->_fault('internal_error', $e->getMessage());
}
return $result;
}
The intention of the API was to assign many categories at once for a product. However this is a modified version because the previous was prohibitively slow. And the curious fact is that this worked until recently. It's intention was to:
only the first parameter is used, and instead of an integer value, a kitten was killed here and the API now expects a string like "productId|catgId1|catgId2|cargId3|..." where the first value is a product id and the second to last values are categories ids; each of them being integer values. The parameter is broken by pipe character ("|") and the product id is popped. In this way, we have the product id in one var, and the categories array in another var.
get the categories collection keeping only the active ones in level 3 (i.e. depth for the category in the tree) whose ids are among the specified ones. This means: if provided categories are array(3, 5, 7, 8) (e.g. from a "245|3|5|7|8" parameter, being "245" the product id) and one of them does not exist or is not active (e.g. 7 is not active and 8 does not exist), the returned value in $categorias_actuales is [3, 5].
as for debugging porpuse, map each input category to existence and validity. this means: existent&&active&&level=3 categories will have "true" as value, while non-existent or non-active categories will have "false" as value. For the given example, the returned array would be: array(3 => true, 5 => true, 7 => false, 8 => false), since 7 is not active and 8 does not exist.
in the try-catch block: a. retrieve the product; b. set the filtered ids (in the example: [3, 5]) as product categories in the just-fetched product; c. save the product.
However, I have the following issues:
The function returns true, so returning $result would not give me the array $results as return value (my intention was to know in which categories was the product actually inserted).
Changing to false instead of $result in the return statement had no effect at all: the obtained/displayed value from the API call was still true.
Throwing a new Exception("something's going on here") had no effect at all. Still true at output.
dying (die('something's going on here')) neither had effect. Still seeing (guess what?) true at the output.
Edit: Also tried a syntax error!! (guess what? nothing happens).
It's not only that I tried these steps, but also refreshed the cache (System > Cache Management > select all and refresh, and even clicking the "Flush Magento Cache" button).
Questions:
1. given the issues before: how can I debug that API call?
2. what could be causing the product not being saved with their categories? By calling category.level I can see that the given ids (i.e. given in the first parameter to category.assignProduct) exist.
I'm a n00b # magento API and perhaps I'm missing something usually obvious. Any help would be appreciated.

Did you disable compilation? You can do it in one of these two ways.
System -> Tools -> Compilation in admin
Use SSH/shell and navigate to your magento root. Do the following commands:
cd shell
php -f compiler.php disable
Also, if your web server runs PHP APC with apc.stat set to 0 (you can check this by running php -i | grep apc.stat or looking for it at any phpinfo() output), please restart your apache2 web server or if you use php5-fpm -- restart that one, too.
Then, if all else fails, try looking for an equivalent file at app/code/local.
e.g. if your file is somewhere in app/code/core/Mage/Path/ToApiFile.php, look for the local version at app/code/local/Mage/Path/ToApiFile.php.
Finally, a very useful shell command for searching code instances:
$ cd app/code/
$ grep -rin "function assignProduct" *

Related

First query string parameter being ignored by Laravel or Wordpress/WooCommerce?

Tech stack
PHP 7.4.2
Laravel 7
Background
I'm attempting to pull in the active products from our WooCommerce site, one page at a time. These then have required data pulled out and formatted into JSON, and returned to the user (in this case a marketing platform making an API call).
Issue
Whichever query parameter is first in my list is getting either removed before it leaves my system, or ignored by the WC/WP REST API.
Code making the call
function getProducts($page = 1, $per_page = 100, $status = 'publish') {
$query = array(
// 't' => 1, // For testing first parameter bug
'page' => $page,
'per_page' => $per_page,
'status' => $status,
);
$string = http_build_query($query, null, '&', PHP_QUERY_RFC3986);
$url = $this->finalUrl . '/wp-json/wc/v3/products?' . $string;
$json = file_get_contents($url);
return json_decode($json);
}
If I dump $url I get:
https://user:pass#domain.com/wp-json/wc/v3/products?page=5&per_page=100&status=publish
This seems valid as far as I can tell. Putting it into Postman, I get the 5th page of 100 records, as expected. However, if I run it in my system, I get the first page every time.
Then if I swap page and per_page round, I will get the page I want but only 10 records which is the default, not the 100 I ask for. Then of course if I put status first, I get inactive/archived products too.
Additionally if I change the URL to a Pipedream URL, I can see all 3 parameters clearly being listed.
Lastly, I tested by adding the t=1 parameter in first as a dummy parameter, and then the rest of the parameters all work fine, and I would get my 5th page of 100 records no problem.
If anyone can assist or point me in the right direction that will be much appreciated.
Cheers,
Tom
Turns out in this case, there was a stray letter in a uri rewrite rule on the wordpress site, causing the name of the first parameter to be prepended with said letter.
This was found within try_files $uri /index.php?uri=$uri&i$args; rule. Note the i before the $args being appended.
In my above example, page would be renamed ipage before it reache the API.
Removed and it now works.

Magento 404 on Admin Page

About a week ago, I was working in a test environment for a new site. I left for an hour, came back, and now cannot get to the admin page, as in ‘http://magento.localhost.com/admin’ results in a No Route 404. I am the only one with access to this, it is not live in any sense. I am using VBox with Ubuntu to host the environment. In terms of possible fixes, so far I have tried…
Making sure core_store, core_store_group, core_website, and customer_group table ids are set to 0 (as described in this and many other articles - http://www.nude-webdesign.com/fix-for-magento-admin-error-404-page-not-found/)
Playing with the /app/code/core/Mage/Core/Controller/Varien/Front.php method _isAdminFrontNameMatched to display the adminPath (it’s ‘admin’)
Cleared the var folder, emptied browser cache. Site’s caching was and is turned off.
Adding 'index.php' to the url still results in a 404.
As per Magento Admin 404, the file 'app/etc/use_cache.ser' doesn't exist for me.
On the day of this occurring, I was simply playing around with some layout files I had copied to a module I made and the theme’s media queries (all of which were reverted to their original state even before this problem started to occur).
Does anyone have any suggestions as to what is wrong here? Any other possible reasons this could be happening?
Thanks for anything.
EDIT 1:06pm 9/10/2013: In response to Alan Storm's method of retrieving controller names that Standard.php is looking for, I was returned many "missing" controller files. However, after downloading a fresh copy of 1.7.0.2 to find those files, they weren't present in their either. Here is my output from Alan's var_dump suggestion in Standard.php:
..."/public_html/app/code/core/Mage/Index/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Paygate/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Paypal/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Widget/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Oauth/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Authorizenet/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Bundle/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Centinel/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Compiler/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Connect/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Downloadable/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/ImportExport/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Api2/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/PageCache/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/XmlConnect/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/Adminhtml/controllers/Controller.php"
..."/public_html/app/code/community/Phoenix/Moneybookers/controllers/Controller.php"
..."/public_html/app/code/core/Mage/Captcha/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/CurrencySymbol/controllers/Adminhtml/Controller.php"
..."/public_html/app/code/core/Mage/CurrencySymbol/controllers/Adminhtml/IndexController.php"
Resolved 3:39pm 9/10/2013: Ok, it's fixed albeit rather bluntly. I took the output of Alan Storm's var_dump suggestion to mean I had created an error somewhere in the core code pool (which is not something I intended on doing, screwing with the default code that is). Unfortunately for sake of exact learning, I then replaced it all with the default core code pool of 1.7.0.2. This was done before Alan updated his original answer with more suggestions that I never investigated. Thanks Alan, you're rad.
A no route 404 error usually indicates Magento can't find the controller file it thinks it should load (usually due to a misconfiguration)
The easiest way to diagnose this is to hop to _validateControllerClassName
#File: app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
protected function _validateControllerClassName($realModule, $controller)
{
$controllerFileName = $this->getControllerFileName($realModule, $controller);
if (!$this->validateControllerFileName($controllerFileName)) {
return false;
}
$controllerClassName = $this->getControllerClassName($realModule, $controller);
if (!$controllerClassName) {
return false;
}
// include controller file if needed
if (!$this->_includeControllerClass($controllerFileName, $controllerClassName)) {
return false;
}
return $controllerClassName;
}
and drop some logging or var_dumps around the return false statments. This should tell you which files Magento is looking for and can't find — it's usually enough to point to the problem.
if (!$this->validateControllerFileName($controllerFileName)) {
var_dump($controllerFileName);
return false;
}
$controllerClassName = $this->getControllerClassName($realModule, $controller);
if (!$controllerClassName) {
var_dump($controllerClassName);
return false;
}
// include controller file if needed
if (!$this->_includeControllerClass($controllerFileName, $controllerClassName)) {
var_dump("Couldn't include: $controllerFileName");
return false;
}
Update: It's normal for Magento look for the controller file in multiple places — every module that registered as containing adminhtml controller files needs to be checked.
However, almost all the controller files being looked for are named /Controller.php. For the default /admin index page this should be IndexController.php. This makes me think your system thinks it's supposed to look for a controller with a blank name, (likely the default controller value since /admin (and not admin/index) is the URL you're using)
There's myriad reasons this could happen — many revolving around a core file being changed or a configuration node in a module set to the wrong value. If the solutions below don't work for you you'll need to try diff-ing your code base vs. a clean one, disabling every custom module and if that fixing things turn modules back on until the problem module is found, or dive deep into debugging Magento routing code to figure out why your system is unhappy.
One common cause for this behavior is an invalid value (or no value at all) being set for a custom admin path at
System -> Configuration -> Admin -> Admin Base URL -> Use Custom Admin Path
If the value for "custom admin path" is blank, or contains and additional /, this could be interfering with the routing.
Since you can't access the admin, try running the following SQL query
select * from core_config_data where path like '%custom_path%';
...
292 default 0 admin/url/use_custom_path 1
293 default 0 admin/url/custom_path admin/
If you see results similar to the above, or admin/url/custom_path is blank/not-present but admin/url/use_custom_path is still 1 — then that's your problem.
Try deleting these configuration values (admin/url/use_custom_path) and (admin/url/use_custom_path) from core_config_data.
If that doesn't apply to your system, per my blank controller theroy my best guess would be for some unknown reason the code at
#File: app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
public function fetchDefault()
{
// set defaults
$d = explode('/', $this->_getDefaultPath());
$this->getFront()->setDefault(array(
'module' => !empty($d[0]) ? $d[0] : '',
'controller' => !empty($d[1]) ? $d[1] : 'index',
'action' => !empty($d[2]) ? $d[2] : 'index'
));
}
is populating the controller key with a blank value.
In my case, my admin was giving me 404 because there's no store set.
I solved it by running the following query
SET SQL_SAFE_UPDATES=0;
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;
SET SQL_SAFE_UPDATES=1;
You can check if you get the below error logged in var/log/system.log
ERR (3): Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in /.../app/code/core/Mage/Core/Model/App.php on line 634 and defined in /.../app/code/core/Mage/Core/Model/Store.php on line 395
Before anything check your configuration file ( app/etc/local.xml) and make sure that you have "admin" as value for the frontName tag.
ex.:
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
Usually when you try http://yoursite.com/admin it gives you the admin area
Try using an url like that http://yoursite.com/index.php/admin
and if it works probably you need to only modify the rewrite rules or follow the suggestions (see the link below)
I got this problem on a shop with custom admin url www.shop.com/customadminroute/ and System -> Configuration -> Web -> URL options -> Add Store Code to Urls: Enabled
In this case the following module should fix it:
https://github.com/romfr/404adminlogin
Thanks to Blog post of Carmen Bremen:
http://neoshops.de/2012/09/07/magento-404-fehlerseite-beim-admin-login/

Python 2.7, Magento Community 1.8 API connection issues

I am using the python-magento API with little luck making a connection. This API is attempting to use Magento's XML-RPC and connection to Community Magento 1.8...
My local install is Python 2.7 (64) on Windows 8, while Magento is on a PHP 5.4 stack.
After a few alterations and a handful of API's used, this is the primary error with python-magento API, attempting connection from Pycharm and DataNitro...
Traceback (most recent call last):
File "C:/Users/xxx/Documents/PYTHON/magento_test_connect.py", line 2, in <module>
magento = MagentoAPI("xxx.com", 80, "userxxx", "passxxx")
File "C:\Python27\lib\site-packages\magento\__init__.py", line 20, in __init__
self.login()
File "C:\Python27\lib\site-packages\magento\__init__.py", line 59, in login
self._session_id = self._client.login(self._api_user, self._api_key)
File "C:\Python27\lib\xmlrpclib.py", line 1224, in __call__
return self.__send(self.__name, args)
File "C:\Python27\lib\xmlrpclib.py", line 1578, in __request
verbose=self.__verbose
File "C:\Python27\lib\xmlrpclib.py", line 1264, in request
return self.single_request(host, handler, request_body, verbose)
File "C:\Python27\lib\xmlrpclib.py", line 1297, in single_request
return self.parse_response(response)
File "C:\Python27\lib\xmlrpclib.py", line 1473, in parse_response
return u.close()
File "C:\Python27\lib\xmlrpclib.py", line 793, in close
raise Fault(**self._stack[0])
xmlrpclib.Fault: <Fault 2: 'Access denied.'>
Process finished with exit code 1
I was looking for some direction, but now I am going to throw a bounty as I see making a connection to Magento with Python is not documented well on the web.
The code I have scaled down to is...
from magento import *
magento = MagentoAPI("xxx.com", 80, "userxxx", "passxxx")
magento.help() #just to see some results
going to the direct url path (to check on firewall issues), I get...
<methodResponse><fault><value><struct><member><name>faultCode</name><value><int>630</int></value></member><member><name>faultString</name><value><string>Unable to read request</string></value></member></struct></value></fault></methodResponse>
I have entered all of the details into Magento admin and gave full privileges. Thought about using the REST API, but after reading this unanswered question, looks to be having the same issues.
**
Changing up my code a bit...
**
import magento
url = 'xxx.com'
port = 8080
apiuser = 'userxxx'
apipass = 'passxxx'
with magento.MagentoAPI(url, port, apiuser, apipass) as product_api:
order_filter = {'created_at':{'from':'2013-01-15 00:00:00'}}
products = product_api.list(order_filter)
the error...
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I was able to set this up on another Magento install and it worked, showing...
Resources:
cart: create, info, license, order, totals
cart_coupon: add, remove
cart_customer: addresses, set
cart_payment: list, method
cart_product: add, list, moveToCustomerQuote, remove, update
cart_shipping: list, method
catalog_category: assignProduct, assignedProducts, create, currentStore, delete, info, level, move, removeProduct, tree, update, updateProduct
catalog_category_attribute: currentStore, list, options
catalog_product: create, currentStore, delete, getSpecialPrice, info, list, listOfAdditionalAttributes, setSpecialPrice, update
catalog_product_attribute: addOption, create, currentStore, info, list, options, remove, removeOption, types, update
catalog_product_attribute_media: create, currentStore, info, list, remove, types, update
catalog_product_attribute_set: attributeAdd, attributeRemove, create, groupAdd, groupRemove, groupRename, list, remove
catalog_product_attribute_tier_price: info, update
catalog_product_custom_option: add, info, list, remove, types, update
catalog_product_custom_option_value: add, info, list, remove, update
catalog_product_downloadable_link: add, list, remove
catalog_product_link: assign, attributes, list, remove, types, update
catalog_product_tag: add, info, list, remove, update
catalog_product_type: list
cataloginventory_stock_item: list, update
core_magento: info
core_store: info, list
customer: create, delete, info, list, update
customer_address: create, delete, info, list, update
customer_group: list
directory_country: list
directory_region: list
giftmessage: setForQuote, setForQuoteItem, setForQuoteProduct
sales_order: addComment, cancel, hold, info, list, unhold
sales_order_creditmemo: addComment, cancel, create, info, list
sales_order_invoice: addComment, cancel, capture, create, info, list, void
sales_order_shipment: addComment, addTrack, create, getCarriers, info, list, removeTrack, sendInfo
Process finished with exit code 0
After many tests, a 1.7 install worked while the 1.8 remained under block on the same server and configurations. The only conclusion is 1.8 is not completed for API use and this issue is (as of 6/23/13) a 1.8 Magento bug.
Not sure if thread originator is still having an issue but I ran into problems with python-magento and xmlrpc with Magento 1.8.
from magento import *
m = MagentoAPI('mag1', 80, 'user', 'pass')
fails with
<ProtocolError for mag1:80/magento/api/xmlrpc: 404 Not Found>
The default PATH in python-magento is /magento/api/xmlrpc.
Changing this to '/index.php/api/xmlrpc' worked for me:
m = MagentoAPI('mag1', 80, 'user', 'pass', path='/index.php/api/xmlrpc')
succeeds.
Problem caused by new rewrite processing in Magento 1.8. See here for more info:
Magento API error when accessing.
Hope this helps.
Jerry.

PHP LDAP to change Active Directory samAccountName?

Our policy for people who are terminated/separated or who go on leave of absence involves a handful of changes to their AD account for record keeping purposes and security. One of these changes is renaming the account (login name, display name and dn) to a value that includes the original name with the help desk ticket number appended.
I have been able to use ldap_rename() to change the active directory "name" attribute, thus changing the DN. I can change the displayName attribute using either ldap_modify() or ldap_mod_replace(). What I cannot seem to do is change the samAccountName using any of these. Below is the core of the code I'm using. The errors I get are dependent upon which function I use, and are listed below.
I know there are some nuances to using PHP LDAP with Active Directory, but I find it hard to believe that I have been able to do everything up to and including changing passwords and I can't change the samAccountName... help?
<?php
$connection=ldap_connect(domain.local,389);
ldap_set_option($connection,LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($connection,LDAP_OPT_REFERRALS,0);
ldap_start_tls($connection);
ldap_bind($connection,$username,$password);
$accountName=$_POST["accountName"];
$ticketNumber=$_POST["ticketNumber"];
$baseDn="dc=domain,dc=local";
$attribs=array("samaccountname","dn","name","displayname","description","info","memberof");
$search=ldap_search($connection,$baseDn,"(samaccountname=".$accountName.")",$attribs);
$result=ldap_get_entries($connection,$search);
// ldap_modify returns error 80: Internal (implementation specific) error.
foreach ($result as $account) {
$newValues=array("samaccountname"=>$account["samaccountname"][0]."-".$ticketNumber)
ldap_modify($connection,$account["dn"],$newValues);
}
// ldap_mod_replace returns error 80: Internal (implementation specific) error.)
foreach ($result as $account) {
$newValues=array("samaccountname"=>$account["samaccountname"][0]."-".$ticketNumber)
ldap_mod_replace($connection,$account["dn"],$newValues);
}
?>
So yeah, what is it I'm supposed to be doing to make this happen?
The "implementation specific" error message you're receiving means that your sAMAccountName is invalid because it doesn't meet specific AD restrictions on it. The sAMAccountName attribute cannot be more than 20 characters and cannot contain any of the following: " [ ] : ; | = + * ? < > / \ ,. It might be helpful to see an example username with the ticket number appended.

Odd behavior when saving a product model that has tier pricing from a script in Magento

I am finding some odd behavior when I try to save a product model from a script it Magento Enterprise 1.8 that has tier pricing.
Take this code for example:
// This product has a tier price
$product = Mage::getModel('catalog/product')->load(194760);
$product->setName('Changed Product Title');
$product->save();
When saving a get an exception (detailed below). However if I change nothing in the model, I do not get the exception. I have a feeling that this is due to the fact that I did not update anything so Magento does not do as much work.
// Same product, but I changed nothing and it works
$product = Mage::getModel('catalog/product')->load(194760);
$product->save();
The odd part is that I am able to save the product successfully if I am setting or modifying tier price information (pending I do not create anything that is duplicated)
// This works pending the tier price does not already exist
$mud_array = array();
$mud_array[] = array(
'website_id' => 0,
'cust_group' => 32000,
'price_qty' => 5,
'price' => 6
);
$product = Mage::getModel('catalog/product')->load(194760);
$product->setTierPrice($mud_array);
$product->save();
The exception that I am seeing is as follows:
Fatal error: Uncaught exception 'Mage_Eav_Model_Entity_Attribute_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '194760-1-0-5.0000-0' for key 'UNQ_CATALOG_PRODUCT_TIER_PRICE'' in /path/to/magento/app/code/core/Mage/Eav/Model/Entity/Abstract.php:61
So it appears that when a tier price exists in a product, and you try to change anything inside the model, it will attempt to reinsert all the tier price information.
Has anyone seen this before? Is there a way to work around this? Thanks for any help you can provide.
I had the same problem with EE 1.12, but with the "group_price" attribute. Just managed to fix the error by adding at the begging of my script
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Ok so I created a fix for this that seems to work.
In /app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product/Attribute/Backend/Tierprice.php there is a function called savePriceData. From what I can gather this function is responsible for determining if we need to update or insert a tier price.
There is an if block that makes this decision to update or insert based on the information coming from the $priceObject that is passed to the function.
If you are updating a tier price from the admin panel, priceObject has two values value_id and value. These fields both point to columns in the catalog_product_entity_tier_price table. This is what happens in the first part of the if block
If you are creating a new tier price from the admin panel, priceObject has all the columns from the catalog_product_entity_tier_price table (entity_id, all_groups, customer_group_id, qty, value, and website_id). Magento then takes this information and inserts it into the catalog_product_entity_tier_price table.
The actual problem was that when you save a product from a script (aka outside the admin panel) you ALWAYS get a priceObject that contains all the information for an insert. So it will always try to do the insert into the table which if it already exists causes an integrity constraint violation.
So the fix I put together for this was really quite simple. In the second part of the if block, I am doing a check to see if the tier price already is in the table and if it is, I simply do not do the insert. Here is the code:
... first part of if statement
// somehow we need to have this not happen if it already exists
$reader = $this->_getReadAdapter();
$sql = "SELECT * FROM catalog_product_entity_tier_price WHERE ";
foreach($data as $index => $value) {
$sql .= $index . ' = ' . $value . ' AND ';
}
$sql = substr($sql, 0, -4);
$search = $reader->fetchAll($sql);
if(count($search) > 0) {
// It already exists, don't do anything
} else {
$adapter->insert($this->getMainTable(), $data);
}
Obviously, you really should make sure that you copy this file to local before you make this change (or probably better yet, rewrite it in a module). This probably is not the most 100% correct "Magento way" to do this, but I really needed to get a solution for this ASAP.
I am open to better solutions than this, but I wanted to share what I found
(Note: As I am on the Enterprise Edition of Magento, I did not want to share anymore of the source than necessary since it could be a violation of our license agreement)

Categories