opencart customer Events, not being called in admin side - opencart

I using OC3, and trying to handle addCustomer event to move the newly created customers to the ERP system. I have created an extension admin/controller/extension/module/erp_integration.php this extension has the registration functionality for the events and the calls for products integration.
class ControllerExtensionModuleErpIntegration extends Controller {
private $error = array();
public function index() {}
public function validate() {}
public function install() {
$this->load->model('setting/event');
$this->model_setting_event->addEvent('product_notification', 'admin/model/catalog/product/addProduct/after', 'extension/module/erp_integration/addProduct');
$this->model_setting_event->addEvent('product_notification', 'admin/model/catalog/product/editProduct/after', 'extension/module/erp_integration/editProduct');
$this->model_setting_event->addEvent('customer_notification', 'catalog/model/account/customer/addCustomer/after', 'extension/module/erp_integration/addCustomer');
$this->model_setting_event->addEvent('customer_notification', 'catalog/model/account/customer/editCustomer/after', 'extension/module/erp_integration/editCustomer');
$this->model_setting_event->addEvent('order_notification', 'catalog/model/checkout/order/addOrder/after', 'extension/module/erp_integration/addOrder');
}
public function uninstall() {
$this->load->model('setting/event');
$this->model_setting_event->deleteEventByCode('product_notification');
$this->model_setting_event->deleteEventByCode('customer_notification');
$this->model_setting_event->deleteEventByCode('order_notification');
}
// admin/model/catalog/product/addProduct/after
public function addProduct(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******ADD PRODUCT**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
// admin/model/catalog/product/editProduct/after
public function editProduct(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******EDIT PRODUCT**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
// catalog/model/account/customer/addCustomer/after
public function addCustomer(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******ADD CUSTOMER from admin**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
}
For the customer part I created another file in catalog/controller/extension/module/erp_integration.php to handle the customer events
<?php
class ControllerExtensionModuleErpIntegration extends Controller {
// catalog/model/account/customer/addCustomer/after
public function addCustomer(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******ADD CUSTOMER**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
// catalog/model/account/customer/editCustomer/after
public function editCustomer(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******EDIT CUSTOMER**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
// catalog/model/checkout/order/addOrder/after
public function addOrder(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******ADD ORDER**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
}
The issue I am facing, the customer events are being called when the user register an account from the user interface. but when I add a new customer from the admin section it is not being triggered.
am I missing something here?

for admin part you should add event to admin/comtroller/extension/module/erp_integration.php this lines
$this->model_setting_event->addEvent('customer_notification_add', 'admin/model/customer/customer/addCustomer/after', 'extension/module/erp_integration/addCustomer');
$this->model_setting_event->addEvent('customer_notification_update', 'admin/model/customer/customer/editCustomer/after', 'extension/module/erp_integration/editCustomer');
also do not forget in this file add this functions:
// catalog/model/account/customer/addCustomer/after
public function addCustomer(&$route, &$args, &$output) {
file_put_contents ( "testing.txt","\n******ADD CUSTOMER**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
// catalog/model/account/customer/editCustomer/after
public function editCustomer(&$route, &$args, &$output) {
//print_r($route); die;
file_put_contents ( "testing.txt","\n******EDIT CUSTOMER**********\n" ,FILE_APPEND );
file_put_contents ( "testing.txt",print_r($args,true) . print_r($output,true) ,FILE_APPEND );
}
Just note events for admin and catalog are separated. So if you need event in admin side, you must add events for admin...

Related

How to associate Kentico changes from REST API or External Application to a staging task group

How to associate Kentico changes from REST API or External Application (like windows console application) to a staging task group
static void Main ( string [ ] args )
{
UserInfo userInfo = UserInfoProvider.GetUserInfo ( "User1" );
using ( new CMSActionContext ( userInfo ) )
{
TreeProvider treeProvider = new TreeProvider ( userInfo );
NodeSelectionParameters nodeSelectionParameters = new NodeSelectionParameters
{
AliasPath = "Path"
};
TreeNode parentPage = treeProvider.SelectSingleNode ( nodeSelectionParameters );
TreeNode newPage = TreeNode.New ( "Class", treeProvider );
newPage.DocumentName = "Test Title";
newPage.DocumentCulture = "en-us";
newPage.DocumentUrlPath = "Path";
newPage.Insert ( parentPage );
}
}
The above code is properly creating the document and the staging tasks with the user context. How can I associate the staging tasks for this document to a staging task group?
First I'd look to make sure that the objects that you are changing are in the list of items supported by content staging. you can see that list here: Content staging - What can be synchronized
So long as you are ultimately using Kentico's API, and Content Staging is enabled, then Kentico should be creating these tasks for you. If you're updating the Kentico database directly without the API, you're probably going to run into trouble and might need to manually create staging tasks or use the API to perform synchronisation.
We can use the SynchronizationActionContext class to associate API changes to a staging task group.
static void Main ( string [ ] args )
{
List<TaskGroupInfo> taskGroups = TaskGroupInfoProvider.GetTaskGroups ( ).WhereEquals ( "TaskGroupCodeName", "MyTaskGroup" ).ToList ( );
using ( new SynchronizationActionContext ( ) { TaskGroups = taskGroups } )
{
UserInfo userInfo = UserInfoProvider.GetUserInfo ( "User1" );
using ( new CMSActionContext ( userInfo ) )
{
TreeProvider treeProvider = new TreeProvider ( userInfo );
NodeSelectionParameters nodeSelectionParameters = new NodeSelectionParameters
{
AliasPath = "Path"
};
TreeNode parentPage = treeProvider.SelectSingleNode ( nodeSelectionParameters );
TreeNode newPage = TreeNode.New ( "Class", treeProvider );
newPage.DocumentName = "Test Title";
newPage.DocumentCulture = "en-us";
newPage.DocumentUrlPath = "Path";
newPage.Insert ( parentPage );
}
}
}

how to have class return mock on new Class()?

In phpunit, I want to test a controller. As part of this I need to return a mock when new Class() is called.
I have tried:
$mockEntity = $this->getMock( 'Vet', array( '__construct', 'setDoctrine', 'setContainer' ) );
$mockForm = $this->getMock( 'VetType', array( 'handleRequest', 'isValid', 'createView' ) );
$mockEntity->expects( $this->once() )->method( '__construct')->willReturn( $this->returnValue( $mockEntity ) );
and also simply:
$mockEntity = $this->getMock( 'Vet', array( 'setDoctrine', 'setContainer' ) );
$mockForm = $this->getMock( 'VetType', array( 'handleRequest', 'isValid', 'createView' ) );
Both return a "Vet" object, not the mock. Is this possible with phpUnit 4.0.20, or do I just need to add a getNewVet() function?
This is a Symfony2 controller

Compiling JSF 2 facelets within a unit test for correctness

I am trying to use the Mojarra JSF 2 compiler programatically with a view to checking the correctness of the xhtml of any pages.
I have got so far but the compiler is not erroring for tags that don't exist in a particular tag library. It does the standard XML namespace checks but if say rich:spacer is present it should error (it got removed in Richfaces 4.x). At runtime this check takes does take place.
Any thoughts? Here is my code:
#RunWith( PowerMockRunner.class )
#PrepareForTest( { WebConfiguration.class, FacesContext.class } )
public class XhtmlValidatorTest
{
#Test
public void test() throws IOException
{
WebConfiguration webConfiguration = PowerMock.createMock( WebConfiguration.class );
PowerMock.mockStatic( WebConfiguration.class );
WebConfiguration.getInstance();
PowerMock.expectLastCall().andReturn( webConfiguration ).anyTimes();
FaceletsConfiguration faceletsConfiguration = PowerMock.createMock( FaceletsConfiguration.class );
webConfiguration.getFaceletsConfiguration();
PowerMock.expectLastCall().andReturn( faceletsConfiguration ).anyTimes();
faceletsConfiguration.isProcessCurrentDocumentAsFaceletsXhtml(EasyMock.isA( String.class ) );
PowerMock.expectLastCall().andReturn(true).anyTimes();
faceletsConfiguration.isConsumeComments( EasyMock.isA( String.class) );
PowerMock.expectLastCall().andReturn(false).anyTimes();
faceletsConfiguration.isConsumeCDATA( EasyMock.isA( String.class ) );
PowerMock.expectLastCall().andReturn(false).anyTimes();
webConfiguration.isOptionEnabled(BooleanWebContextInitParameter.EnableMissingResourceLibraryDetection);
PowerMock.expectLastCall().andReturn( false ).anyTimes();
webConfiguration.isOptionEnabled(BooleanWebContextInitParameter.EnableCoreTagLibraryValidator );
PowerMock.expectLastCall().andReturn( true ).anyTimes();
FacesContext facesContext = PowerMock.createMock( FacesContext.class );
PowerMock.mockStatic( FacesContext.class );
FacesContext.getCurrentInstance();
PowerMock.expectLastCall().andReturn( facesContext ).anyTimes();
facesContext.isProjectStage( ProjectStage.Development );
PowerMock.expectLastCall().andReturn( false ).anyTimes();
Application application = PowerMock.createMock( Application.class );
facesContext.getApplication();
PowerMock.expectLastCall().andReturn( application ).anyTimes();
application.getExpressionFactory();
PowerMock.expectLastCall().andReturn( new org.jboss.el.ExpressionFactoryImpl() ).anyTimes();
PowerMock.replayAll();
long refreshPeriod = -1;
com.sun.faces.facelets.compiler.Compiler compiler = new SAXCompiler();
compiler.setValidating( true );
System.out.println( "Compiler.isValidating() " + compiler.isValidating() );
FaceletCache cache = new UnittestFaceletCacheFactory().getCache( refreshPeriod );
ResourceResolver resolver = new ResourceResolver()
{
#Override
public URL resolveUrl(String path)
{
URL url = null;
try
{
url = new URL( BASE_PATH + path );
}
catch (MalformedURLException e)
{
throw new RuntimeException( e );
}
return url;
}
};
DefaultFaceletFactory defaultFaceletFactory = new DefaultFaceletFactory( compiler, resolver, refreshPeriod, cache );
File file = new File( "WebContent" );
File[] files = file.listFiles();
for( File xhtmlFile : files )
{
if( xhtmlFile.isFile() )
{
String name = xhtmlFile.getName();
if( name.endsWith(".xhtml" ) )
{
System.out.println( "compiling: " + name );
defaultFaceletFactory.getFacelet( name );
}
}
}
}
The facelet cache factory used in the code is a hack:
package com.sun.faces.facelets.impl;
import javax.faces.view.facelets.FaceletCache;
public class UnittestFaceletCacheFactory
{
public FaceletCache getCache( long refreshPeriod )
{
return new DefaultFaceletCache( refreshPeriod );
}
}

Unit testing Monorail's RenderText method

I'm doing some maintenance on an older web application written in Monorail v1.0.3. I want to unit test an action that uses RenderText(). How do I extract the content in my test? Reading from controller.Response.OutputStream doesn't work, since the response stream is either not setup properly in PrepareController(), or is closed in RenderText().
Example Action
public DeleteFoo( int id )
{
var success= false;
var foo = Service.Get<Foo>( id );
if( foo != null && CurrentUser.IsInRole( "CanDeleteFoo" ) )
{
Service.Delete<Foo>( id );
success = true;
}
CancelView();
RenderText( "{ success: " + success + " }" );
}
Example Test (using Moq)
[Test]
public void DeleteFoo()
{
var controller = new FooController ();
PrepareController ( controller );
var foo = new Foo { Id = 123 };
var mockService = new Mock < Service > ();
mockService.Setup ( s => s.Get<Foo> ( foo.Id ) ).Returns ( foo );
controller.Service = mockService.Object;
controller.DeleteTicket ( foo.Id );
mockService.Verify ( s => s.Delete<Foo> ( foo.Id ) );
Assert.AreEqual ( "{success:true}", GetResponse ( Response ) );
}
// response.OutputStream.Seek throws an "System.ObjectDisposedException: Cannot access a closed Stream." exception
private static string GetResponse( IResponse response )
{
response.OutputStream.Seek ( 0, SeekOrigin.Begin );
var buffer = new byte[response.OutputStream.Length];
response.OutputStream.Read ( buffer, 0, buffer.Length );
return Encoding.ASCII.GetString ( buffer );
}
Override BaseControllerTest.BuildResponse() and provide your mock of IMockResponse built with Moq.

Unit testing NHibernate UserTypes

Does anyone have a good approach towards unit testing their UserTypes?
By way of example, I have an object in my model called DateRange, which has a DatePoint start and DatePoint end. In addition to making range type operations available for two DateTimes, these objects let me adjust the precision for the task at hand (i.e., Day, Hour, Minute, etc.). When stored to the db for an application I'm working on, I just need to store the start and end as DateTime, no nulls allowed. I can't think of how to map this without a UserType, so I have:
/// <summary>User type to deal with <see cref="DateRange"/> persistence for time sheet tracking.</summary>
public class TimePeriodType : IUserType
{
public SqlType[] SqlTypes {
get {
var types = new SqlType[2];
types[0] = new SqlType(DbType.DateTime);
types[1] = new SqlType(DbType.DateTime);
return types;
}
}
public Type ReturnedType
{
get { return typeof(DateRange); }
}
/// <summary>Just return <see cref="DateRange.Equals(object)"/></summary>
public new bool Equals(object x, object y)
{
return x != null && x.Equals(y);
}
/// <summary>Just return <see cref="DateRange.GetHashCode"/></summary>
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var start = (DateTime)NHibernateUtil.DateTime.NullSafeGet(rs, names[0]);
var end = (DateTime)NHibernateUtil.DateTime.NullSafeGet(rs, names[1]);
return new DateRange(start, end, TimeSlice.Minute);
}
public void NullSafeSet(IDbCommand cmd, object value, int index) {
Check.RequireNotNull<DateRange>(value);
Check.RequireArgType<DateRange>(value);
var dateRange = ((DateRange)value);
NHibernateUtil.DateTime.NullSafeSet(cmd, dateRange.Start, index);
NHibernateUtil.DateTime.NullSafeSet(cmd, dateRange.End, index);
}
public object DeepCopy(object value) {
Check.RequireNotNull<DateRange>(value);
Check.RequireArgType<DateRange>(value);
var dateRange = ((DateRange) value);
return new DateRange(dateRange.Start, dateRange.End);
}
public bool IsMutable
{
get { return false; }
}
public object Replace(object original, object target, object owner) {
//because it is immutable so we can just return it as is
return original;
}
public object Assemble(object cached, object owner) {
//Used for caching, as it is immutable we can just return it as is
return cached;
}
public object Disassemble(object value) {
//Used for caching, as it is immutable we can just return it as is
return value;
}
}
}
Now I'm looking for a way to prove it works. Thanks in advance!
Cheers,
Berryl
I created a user type for System.Drawing.Color, and here is how I unit tested it with MSTest and Moq.
ColorUserType.cs:
public class ColorUserType : IUserType
{
public object Assemble( object cached, object owner )
{
return cached;
}
public object DeepCopy( object value )
{
return value;
}
public object Disassemble( object value )
{
return value;
}
public new bool Equals( object x, object y )
{
if(ReferenceEquals(x, y ) )
{
return true;
}
if( x == null || y == null )
{
return false;
}
return x.Equals( y );
}
public int GetHashCode( object x )
{
return x == null ? typeof( Color ).GetHashCode() + 473 : x.GetHashCode();
}
public bool IsMutable
{
get
{
return true;
}
}
public object NullSafeGet( IDataReader rs, string[] names, object owner )
{
var obj = NHibernateUtil.String.NullSafeGet( rs, names[0] );
if( obj == null )
{
return null;
}
return ColorTranslator.FromHtml( (string)obj );
}
public void NullSafeSet( IDbCommand cmd, object value, int index )
{
if( value == null )
{
( (IDataParameter)cmd.Parameters[index] ).Value = DBNull.Value;
}
else
{
( (IDataParameter)cmd.Parameters[index] ).Value = ColorTranslator.ToHtml( (Color)value );
}
}
public object Replace( object original, object target, object owner )
{
return original;
}
public Type ReturnedType
{
get
{
return typeof( Color );
}
}
public SqlType[] SqlTypes
{
get
{
return new[] { new SqlType( DbType.StringFixedLength ) };
}
}
}
ColorUserTypeTests.cs
[TestClass]
public class ColorUserTypeTests
{
public TestContext TestContext { get; set; }
[TestMethod]
public void AssembleTest()
{
var color = Color.Azure;
var userType = new ColorUserType();
var val = userType.Assemble( color, null );
Assert.AreEqual( color, val );
}
[TestMethod]
public void DeepCopyTest()
{
var color = Color.Azure;
var userType = new ColorUserType();
var val = userType.DeepCopy( color );
Assert.AreEqual( color, val );
}
[TestMethod]
public void DissasembleTest()
{
var color = Color.Azure;
var userType = new ColorUserType();
var val = userType.Disassemble( color );
Assert.AreEqual( color, val );
}
[TestMethod]
public void EqualsTest()
{
var color1 = Color.Azure;
var color2 = Color.Bisque;
var color3 = Color.Azure;
var userType = new ColorUserType();
var obj1 = (object)color1;
var obj2 = obj1;
Assert.IsFalse( userType.Equals( color1, color2 ) );
Assert.IsTrue( userType.Equals( color1, color1 ) );
Assert.IsTrue( userType.Equals( color1, color3 ) );
Assert.IsFalse( userType.Equals( color1, null ) );
Assert.IsFalse( userType.Equals( null, color1 ) );
Assert.IsTrue( userType.Equals( null, null ) );
Assert.IsTrue( userType.Equals( obj1, obj2 ) );
}
[TestMethod]
public void GetHashCodeTest()
{
var color = Color.Azure;
var userType = new ColorUserType();
Assert.AreEqual( color.GetHashCode(), userType.GetHashCode( color ) );
Assert.AreEqual( typeof( Color ).GetHashCode() + 473, userType.GetHashCode( null ) );
}
[TestMethod]
public void IsMutableTest()
{
var userType = new ColorUserType();
Assert.IsTrue( userType.IsMutable );
}
[TestMethod]
public void NullSafeGetTest()
{
var dataReaderMock = new Mock();
dataReaderMock.Setup( m => m.GetOrdinal( "white" ) ).Returns( 0 );
dataReaderMock.Setup( m => m.IsDBNull( 0 ) ).Returns( false );
dataReaderMock.Setup( m => m[0] ).Returns( "#ffffff" );
var userType = new ColorUserType();
var val = (Color)userType.NullSafeGet( dataReaderMock.Object, new[] { "white" }, null );
Assert.AreEqual( "ffffffff", val.Name, "The wrong color was returned." );
dataReaderMock.Setup( m => m.IsDBNull( It.IsAny() ) ).Returns( true );
Assert.IsNull( userType.NullSafeGet( dataReaderMock.Object, new[] { "black" }, null ), "The color was not null." );
dataReaderMock.VerifyAll();
}
[TestMethod]
public void NullSafeSetTest()
{
const string color = "#ffffff";
const int index = 0;
var mockFactory = new MockFactory( MockBehavior.Default );
var parameterMock = mockFactory.Create();
parameterMock.SetupProperty( p => p.Value, string.Empty );
var parameterCollectionMock = mockFactory.Create();
parameterCollectionMock.Setup( m => m[0] ).Returns( parameterMock.Object );
var commandMock = mockFactory.Create();
commandMock.Setup( m => m.Parameters ).Returns( parameterCollectionMock.Object );
var userType = new ColorUserType();
userType.NullSafeSet( commandMock.Object, ColorTranslator.FromHtml( color ), index );
Assert.AreEqual( 0, string.Compare( (string)( (IDataParameter)commandMock.Object.Parameters[0] ).Value, color, true ) );
userType.NullSafeSet( commandMock.Object, null, index );
Assert.AreEqual( DBNull.Value, ( (IDataParameter)commandMock.Object.Parameters[0] ).Value );
mockFactory.VerifyAll();
}
[TestMethod]
public void ReplaceTest()
{
var color = Color.Azure;
var userType = new ColorUserType();
Assert.AreEqual( color, userType.Replace( color, null, null ) );
}
[TestMethod]
public void ReturnedTypeTest()
{
var userType = new ColorUserType();
Assert.AreEqual( typeof( Color ), userType.ReturnedType );
}
[TestMethod]
public void SqlTypesTest()
{
var userType = new ColorUserType();
Assert.AreEqual( 1, userType.SqlTypes.Length );
Assert.AreEqual( new SqlType( DbType.StringFixedLength ), userType.SqlTypes[0] );
}
}
I was thinking I could mock / fake some of the dependencies here, but wound up deciding the best way to do this was by using a database.
Some things I learned along the way:
1) it's worth the effort when learning NHibernate techniques to have a dedicated set of tools including a way to quickly configure a db and test fixture for it (the same kinds of agile tools you'll need for everything else, really) and a dedicated test lab that you don't have an emotional investment in.
2) mocks do not lend themselves to interfaces you don't own, like IDataReader.
Cheers