Create Magento coupons progmatically with expiry dates of 30 days from now - magento

I need to Create Coupons in Magento on Action of account Create.
I have created observer which is executing properly on account Create but i am Struggling with Coupons create. I have fixed coupon names on of fixed amount on applicable on cart subtotal.
I found many ans but none of them has anything about expiry of coupon

No replies yet :(
Though I found the solution.
$customer = $observer->getCustomer()->getData();
$email = $customer['email'];
$email100 = $email.'-100-1';
$datei=date('d/m/Y');
$datee = date('d/m/Y', strtotime('1 day'));
$firstname=$customer['firstname'];
$couponcode1=$email.'100-1';
$data = array(
'product_ids' => null,
'name' => sprintf('coupon-100-1', Mage::getSingleton('customer/session')->getCustomerId()),
'description' => null,
'is_active' => 1,
'website_ids' => array(1),
'customer_group_ids' => array(1),
'coupon_type' => 2,
'coupon_code' => $email100,
'uses_per_coupon' => 1,
'uses_per_customer' => 1,
'from_date' => $datei,
'to_date' => $datee,
'sort_order' => null,
'is_rss' => 1,
'test' => 'test',
'rule' => array(
'conditions' => array(
'1' =>array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
),
'1--1' => array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
),
'1--1--1' =>array(
'type' => 'salesrule/rule_condition_address',
'attribute' => 'base_subtotal',
'operator' => '>=',
'value' => '400'
),
'1--1--2' =>array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 0
),
'1--1--2--1' =>array(
'type' => 'salesrule/rule_condition_product_found',
'value' => 1,
'aggregator' => 'all'
),
'1--1--2--1--1' => array(
'type' => 'salesrule/rule_condition_product',
'attribute' => 'special_price',
'operator' => '>=',
'value' => 0
)
),
'actions' => array(
'1' =>array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => null
),
)
),
'simple_action' => 'cart_fixed',
'discount_amount' => 100,
'discount_qty' => 0,
'discount_step' => null,
'apply_to_shipping' => 0,
'simple_free_shipping' => 0,
'stop_rules_processing' => 0,
'store_labels' => array()
);
$model = Mage::getModel('salesrule/rule');
$validateResult = $model->validateData(new Varien_Object($data));
if ($validateResult !== true) {
foreach($validateResult as $errorMessage) {
// print_r($errorMessage);
$session->addError($errorMessage);
}
}
if (isset($data['rule']['conditions'])) {
$data['conditions'] = $data['rule']['conditions'];
}
if (isset($data['rule']['actions'])) {
$data['actions'] = $data['rule']['actions'];
}
unset($data['rule']);
//print_r($data);
$model->loadPost($data);
$model->save();
Here the name of coupon code is email id followed by -100-1.
$datei and $datee are the initial date and the expiry date. I have customized the coupon code so that it is not being used if the cart contains special price item.
Fixed amount discount is applied on the complete cart subtotal.
In Case of query do respond.

Related

Can't save multiselect attribute on Magento

I created a custom multiselect product attribute through installer. It works and I can save the product if I only select one option from the multiselect values. But if I select 2 values, the product still can be saved but came back up with 1 selected value again. In short, I can't save the attribute with 2 selected values.
$installer = $this;
$installer->startSetup();
$installer->addAttribute('catalog_product', 'attr_id',array(
'label' => 'Frontend Name',
'type' => 'int',
'input' => 'multiselect',
'backend' => 'eav/entity_attribute_backend_array',
'frontend' => '',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'option' => array (
'value' => array(
'0' => array('First Option'),
'1' => array('Second Option'),
'2' => array('Third Option'),
)
),
'visible_on_front' => false,
'visible_in_advanced_search' => false,
'unique' => false
));
$installer->endSetup();
The problem comes from the type of your attribute.
'type'=> 'int',
The values from multiselect attributes are saved concatenated by comma 1,4,6. For this you need the attribute to be varchar or text. I recommend varchar if you are not going to have hundreds of options for the attribute.
The way is configured now, when it's saved, the value 1,4,6 is converted to int and it ends up being 1.
Modify you option array from
'option' => array (
'value' => array(
'0' => array('First Option'),
'1' => array('Second Option'),
'2' => array('Third Option'),
)
),
to
'option' => array (
'value' => array(
'first_option' => array('First Option'),
'second_option' => array('Second Option'),
'third_option' => array('Third Option'),
)
),
Multiselect will accept associated array.
I have found the solution myself .
open app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
on save action after this
$category->setAttributeSetId($category->getDefaultAttributeSetId());
Please change language is your attribute name . you can change attribute name accordingly
$ga = "";
if($data['general']['language']){
foreach($data['general']['language'] as $a){
$ga .= $a.",";
}
$category->setLanguage(substr_replace($ga, "", -1));
}
Please replace language to your attribute name and it works...**
I am using SOAP API for entering products in magento shops. here is the full code
In the case of multiselect custom attribute.
$arrProductTime = explode(',', '136,139');
$result = $client->catalogProductCreate($session, 'simple', $attributeSet->set_id, 'product_sku1234', array(
'categories' => array(36),
'websites' => array(1),
'name' => 'my_pdt1008',
'description' => 'my_pdt1',
'short_description' => 'my_pdt1000',
'weight' => '11',
'status' => '1',
'url_key' => 'product-url-key1',
'url_path' => 'product-url-path1',
'visibility' => '4',
'price' => '100',
'tax_class_id' => 1,
'meta_title' => 'Product meta title1',
'meta_keyword' => 'Product meta keyword1',
'meta_description' => 'Product meta description1',
'stock_data' => array('qty'=>'100','is_in_stock'=>1,'manage_stock'=>1),
'additional_attributes' => array('multi_data' => array(array('key' => 'product_time', 'value' => $arrProductTime)))
));
I have faced a problem in my custom category attribute. It does not save the multiselect value in data base and does not show multiselect values on the category backend admin.
<?php
require_once("app/Mage.php");
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$entityTypeId = $installer->getEntityTypeId('catalog_category');
$attributeSetId = $installer->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $installer->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);
$installer->addAttribute('catalog_category', 'cutomcity', array(
'label' => 'Test Select',
'type' => 'varchar',
'input' => 'multiselect',
'visible' => true,
'user_defined' => true,
'required' => false,
'position' => 80,
'visible_on_front' => false,
'group' => 'General Information',
'input' => 'multiselect',
'backend_model'=>'eav/entity_attribute_backend_array'
'source' => 'GA_Multiattribute_Helper_Testsource'
// eav/entity_attribute_source_table Even if i use this untill it does not show selected value on the Multiselect
));
?>
This is my helper file code
<?php
class GA_Multiattribute_Helper_Multiattributesource extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
protected $_optionsDefault = array();
public function getAllOptions($withEmpty = true, $defaultValues = false)
{
$collection = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('*');;
$customers = array();
foreach($collection as $cust)
{
$fname = $cust->getFirstname();
$lname = $cust->getLastname();
$id = $cust->getId();
$customers[] = array('value'=>"$id$fname", 'label'=>"$fname $lname");
}
return $customers;
}
} ?>

PHPUnit mocks - assert method called

i'm new to phpunit and have read the documentation on mock objects but it isn't very clear.
I am trying to write a simple test that asserts a method within a class is called. With the following code, i am testing that when the Client::exchangeArray is called, a call is made to Client::getInputFilter.
class Client implements InputFilterAwareInterface
{
public function getInputFilter() {
if(!$this->_inputFilter){
$inputFactory = new InputFactory();
$inputFilter = new InputFilter();
$inputFilter->add($inputFactory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array(
'name' => 'Int'
)
)
)));
$inputFilter->add($inputFactory->createInput(array(
'name' => 'name',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
),
array(
'name' => 'StripNewLines'
),
array(
'name' => 'Alpha'
)
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 100
)
)
)
)));
$inputFilter->add($inputFactory->createInput(array(
'name' => 'surname',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
)
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 100
)
)
)
)));
$inputFilter->add($inputFactory->createInput(array(
'name' => 'email',
'required' => false,
'filters' => array(
array(
'name' => 'StripTags'
),
array(
'name' => 'StringTrim'
)
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 150
)
),
array(
'name' => 'EmailAddress'
)
)
)));
$this->_inputFilter = $inputFilter;
}
return $this->_inputFilter;
}
public function exchangeArray($data){
$inputFilter = $this->getInputFilter();
$inputFilter->setData($data);
if(!$inputFilter->isValid()){
throw new \Exception('Invalid client data');
}
$cleanValues = $inputFilter->getValues();
$this->_id = (isset($cleanValues['id']) ? $cleanValues['id'] : null);
$this->_name = (isset($cleanValues['name']) ? $cleanValues['name'] : null);
$this->_surname = (isset($cleanValues['surname']) ? $cleanValues['surname'] : null);
$this->_email = (isset($cleanValues['email']) ? $cleanValues['email'] : null);
}
}
Here is my test case:
public function testExchangeArrayCallsInputFilter(){
$data = array('id' => 54,
'name' => 'john',
'surname' => 'doe',
'email' => 'john.doe#domain.com'
);
$mock = $this->getMock('Client', array('exchangeArray'));
$mock->expects($this->once())
->method('getInputFilter');
$mock->exchangeArray($data);
}
...and i'm getting the following error:
Expectation failed for method name is equal to
when invoked 1 time(s). Method was expected to be called 1 times,
actually called 0 times.
Where am i going wrong?
It all depends on what you want test and what you want mock. Basing on the name of your test I assume that you want test exchangeArray method.
The getMock method takes as second argument names of methods that you want mock. It means that they will never be called.
So, if you want to test exchangeArray method and mock getInputFilter you should pass "getInputFilter" in second argument, like below:
$mock = $this->getMock('Client', array('getInputFilter'));
$mock->expects($this->once())
->method('getInputFilter');
$mock->exchangeArray($data);
But be careful. You didn't tell your mock to return anything, so it will return null value. That means that you'll get a fatal error on the second line of exchangeArray method (trying to call a method on a non-object). You should prepare some faked filter object to deal with that, eg:
// $preparedFilterObject = ...
$mock = $this->getMock('Client', array('getInputFilter'));
$mock->expects($this->once())
->method('getInputFilter')
->will($this->returnValue($preparedFilterObject);
$mock->exchangeArray($data);
And if you want to invoke the "real" getInputFilter method - then you just can't mock this method.

Specifying actions for programmatically created coupon code

Based off information found in a couple of posts online (http://www.magentocommerce.com/boards/viewthread/178767/ and http://marius-strajeru.blogspot.co.uk/2010/04/create-bulk-discount-rules.html), I am putting some code together to generate some coupon codes.
One piece I am stuck on is how to write the code to specify the "actions" specific conditions for the coupons use. That would be specified in the "Apply the rule only to cart items matching the following conditions" section of the Actions tab in the Magento admin system.
In the Magento admin system, I would build the following line:
Category is not one of 10,20,30
What I need to know is how to replicate this in code.
I currently have the following, which doesn't appear to be working - at least, when I check the generated coupon code, the action values I require are missing.
$actions = array();
$actions[1] = array(
'type' => 'salesrule/rule_condition_category',
'aggregator' => 'all',
'value' => 1,
'new_child' => ''
);
$actions['1--1'] = array(
'type' => 'salesrule/rule_condition_category',
'attribute' => 'category_ids',
'operator' => '!()',
'value' => '932,341,800',
'is_value_processed' => 0,
);
$model->setData('actions',$actions);
I am assuming that the code is simply wrong, although not tripping up the system.
How I might achieve what I need?
Here's what I ended up with, which works great!
$conditions = array(
"1" => array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => false
),
"1--1" => array(
'type' => 'salesrule/rule_condition_product_found',
'value' => 1,
'aggregator' => 'all',
'new_child' => false
),
"1--1--1" => array(
'type' => 'salesrule/rule_condition_product',
'attribute' => 'category_ids',
'operator' => '!()',
'value' => '10,20,30'
)
);
$actions = array(
"1" => array(
"type" => "salesrule/rule_condition_product",
"aggregator" => "all",
"value" => "1",
"new_child" => false
),
"1--1" => array(
"type" => "salesrule/rule_condition_product",
"attribute" => "category_ids",
'operator' => '!()',
'value' => '10,20,30'
)
);
$rule->setData('conditions',$conditions);
$rule->setData("actions",$actions);

CakePHP: validation( ) fails

My validation fails, so my test for this message throws an ValidationException every time.
"Not all fields are filled out correct". Why? Analoguosly, it works for users (another method).
MODEL:
public $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Name can not be empty',
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name is already used.',
),
),
'address' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Address can not be empty',
),
...
public function saveNewInstitution($institutionData, $userId) {
$institutionData[$this->alias]['is_active'] = 1;
$institutionData[$this->alias]['user_id'] = $userId;
$this->create();
$this->set($institutionData);
if ($this->validates()) {
return $this->save();
} else {
throw new ValidationException('Not all fields are filled out correct');
}
}
TESTclass:
public function testSaveNewInstitution() {
$data = array(
'Institution' => array(
'name' => 'Spitex Staufen',
'address' => 'Hauptweg 4',
'postcode' => '1234',
'city' => 'huuh',
'phone_number' => '123 456 78 90',
'email' => 'staufen#spitex.huuh',
'comment' => '',
'institution_type_id' => 5
));
$expected = array(
'Institution' => array(
'id' => 2,
'name' => 'Spitex Staufen',
'address' => 'Hauptweg 4',
'postcode' => '1234',
'city' => 'huuh',
'phone_number' => '123 456 78 90',
'email' => 'staufen#spitex.huuh',
'comment' => '',
'is_active' => TRUE,
'user_id' => 2,
'institution_type_id' => 5
));
$result = $this->Institution->saveNewInstitution($data, 2);
$this->assertEqual($result, $expected);
}
and all the Exceptionhandling methods like this:
public function testSaveNewInstitutionExceptionName() {
$this->setExpectedException('ValidationException');
$this->Institution->saveNewInstitution($this->__nameEmpty, 2);
}
I don't know if i got it really - is your Testclass failing or is the saveNewInstitution() function making you troubles? Did you try to check if the saveNewInstitution() is working correct by hand - put some data in a form an pass it to your function?
Maybe it's just a small thing and you have an entry with id=2 in your database an you got a duplicate key exception overwritten by your own exception method testSaveNewInstitutionExceptionName().

Why doesn't the view use the database table I defined in hook_views_data()?

I have a problem with my module views integration. I need to provide information about user who added video and timestamp. Video field is a CCK Embedded Media Field and it stores in content_field_3d_party_video table.
The schema is defined from the following code.
function MODULE_schema() {
$schema = array();
$schema['video_data'] = array(
'description' => t('Users and timestamps for video field'),
'fields' => array(
'value' => array(
'description' => t('Emfield value'),
'type' => 'varchar',
'length' => '255',
'not null' => TRUE,
'default' => '',
),
'uid' => array(
'description' => t('User id'),
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
'timestamp' => array(
'description' => t('Timestamp'),
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
),
'primary key' => array('value'),
'indexes' => array(
'timestamp' => array('timestamp'),
'uid' => array('uid'),
),
);
return $schema;
}
The hook_views_data() implementation is the following.
function MODULE_views_data() {
$data = array();
$data['video_data']['table']['group'] = t('Video Data');
$data['video_data']['table']['join'] = array(
'node' => array(
'left_table' => 'content_field_3d_party_video',
'left_field' => 'field_3d_party_video_value',
'field' => 'value',
),
'users' => array(
'left_field' => 'uid',
'field' => 'uid',
),
);
$data['video_data']['value'] = array(
'title' => t('Video value'),
'relationship' => array(
'base' => 'content_field_3d_party_video',
'base field' => 'field_3d_party_video_value',
'field' => 'value',
'handler' => 'views_handler_relationship',
'label' => t('Video value'),
),
);
$data['video_data']['uid'] = array(
'title' => t('User id'),
'relationship' => array(
'base' => 'users',
'base field' => 'uid',
'field' => 'uid',
'handler' => 'views_handler_relationship',
'label' => t('User id'),
),
);
$data['video_data']['timestamp'] = array(
'title' => t('Timestamp field'),
'field' => array(
'handler' => 'views_handler_field_date',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort_date',
),
'filter' => array(
'handler' => 'views_handler_filter_date',
),
);
return $data;
}
The table isn't included in the SQL query generated for the view.
SELECT node.nid AS nid,
node.title AS node_title,
node.language AS node_language,
node_data_field_3d_party_video.field_3d_party_video_embed AS node_data_field_3d_party_video_field_3d_party_video_embed,
node_data_field_3d_party_video.field_3d_party_video_value AS node_data_field_3d_party_video_field_3d_party_video_value,
...
node.type AS node_type,
node.vid AS node_vid
FROM node node
LEFT JOIN content_field_3d_party_video content_field_3d_party_video_video_data ON value = content_field_3d_party_video_video_data.field_3d_party_video_value
LEFT JOIN users users_video_data ON uid = users_video_data.uid
LEFT JOIN content_field_3d_party_video node_data_field_3d_party_video ON node.vid = node_data_field_3d_party_video.vid
WHERE ...
May you help me?
This is the solution the OP previously posted in the question.
To correctly join the table used for a CCK field, we must specify node_data_field_3d_party_video as left_table, instead of content_field_3d_party_video.
$data['video_data']['table']['join'] = array(
'node' => array(
'left_table' => 'node_data_field_3d_party_video',
'left_field' => 'field_3d_party_video_value',
'field' => 'value',
),
'users' => array(
'left table' => 'users',
'left_field' => 'uid',
'field' => 'uid',
),
);

Resources