Merge branch 'frontend-profileSettings' into 'master'

Frontend profile settings

See merge request saburly/wiaas/new-wiaas!20
This commit was merged in pull request #20.
This commit is contained in:
Almira
2018-09-20 12:27:02 +00:00
24 changed files with 1580 additions and 274 deletions

View File

@@ -0,0 +1,173 @@
<?php
class Wiaas_REST_Customer_API {
/**
* Endpoint namespace.
*
* @var string
*/
private static $namespace = 'wiaas';
public function __construct() {
include_once dirname( __FILE__ ) . '/../user/class-wiaas-customer.php';
include_once dirname( __FILE__ ) . '/helper/class-rest-helper-functions.php';
}
public static function register_routes() {
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/profile-addresses', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_profile_addresses'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/profile-addresses/(?P<address_id>\d+)', array(
'methods' => 'DELETE',
'callback' => array(__CLASS__, 'delete_customer_profile_address'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/billing-addresses', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_billing_addresses'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/billing-addresses/(?P<address_id>\d+)', array(
'methods' => 'DELETE',
'callback' => array(__CLASS__, 'delete_customer_billing_addresses'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/personal-info', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_personal_info'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/company-info', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_company_info'),
'permission_callback' => 'is_user_logged_in'
) );
}
public static function update_customer_profile_addresses(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$new_address = json_decode($params['profile_address']);
if (!Wiaas_Customer::update_customer_profile_addresses($customer_id, $new_address)){
return self::generate_wiaas_response('PROFILE_ADDRESS_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return self::generate_wiaas_response('PROFILE_ADDRESS_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function delete_customer_profile_address(WP_REST_Request $request){
$customer_id = $request['id'];
$address_id = $request['address_id'];
if (!Wiaas_Customer::delete_customer_profile_address($customer_id, $address_id)){
return self::generate_wiaas_response('ADDRESS_ERROR', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
return self::generate_wiaas_response('ADDRESS_REMOVED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function update_customer_billing_addresses(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$new_address = json_decode($params['billing_address']);
if (!Wiaas_Customer::update_customer_billing_addresses($customer_id, $new_address)){
return self::generate_wiaas_response('BILLING_ADDRESS_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return self::generate_wiaas_response('BILLING_ADDRESS_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function delete_customer_billing_addresses(WP_REST_Request $request){
$customer_id = $request['id'];
$address_id = $request['address_id'];
if (!Wiaas_Customer::delete_customer_billing_address($customer_id, $address_id)){
return self::generate_wiaas_response('ADDRESS_ERROR', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
return self::generate_wiaas_response('ADDRESS_REMOVED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function update_customer_personal_info(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$first_name = $params['first_name'];
$last_name = $params['last_name'];
$phone = $params['phone'];
$name = $first_name . ' ' . $last_name;
if (!is_string($name) || strlen($name) === 1){
return self::generate_wiaas_response('ADD_NAME', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!is_string($phone) || strlen($phone) < 1){
return self::generate_wiaas_response('ADD_PHONE_NUMBER', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!Wiaas_Customer::update_customer_profile_info($customer_id, $first_name, $last_name, $phone)){
return self::generate_wiaas_response('PROFILE_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return self::generate_wiaas_response('PROFILE_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function update_customer_company_info(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$company_name = $params['company_name'];
$vat_code = $params['vat_code'];
if (!is_string($company_name) || strlen($company_name) < 1){
return self::generate_wiaas_response('ADD_COMPANY_NAME', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!is_string($vat_code) || strlen($vat_code) < 1){
return self::generate_wiaas_response('ADD_VAT', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!Wiaas_Customer::update_customer_company_info($customer_id, $company_name, $vat_code)){
return self::generate_wiaas_response('COMPANY_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return self::generate_wiaas_response('COMPANY_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
private static function generate_wiaas_response($message, $code, $data = NULL){
$response = array(
'messages' => [
array(
'code' => $code,
'message' => $message
)
],
'data' => $data
);
return new WP_REST_Response($response);
}
}

View File

@@ -0,0 +1,50 @@
<?php
class Wiass_REST_User_API {
/**
* Endpoint namespace.
*
* @var string
*/
private static $namespace = 'wiaas';
public function __construct() {
include_once dirname( __FILE__ ) . '/../class-wiaas-countries.php';
}
public static function register_routes() {
register_rest_route( self::$namespace, 'user/validate-token', array(
'methods' => 'POST',
'callback' => array(__CLASS__, 'validate_token'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'user/get-countries', array(
'methods' => 'GET',
'callback' => array(__CLASS__, 'get_countries'),
'permission_callback' => 'is_user_logged_in'
) );
}
public static function validate_token() {
$user = wp_get_current_user();
return new WP_REST_Response(array(
'userInfo' => array(
'wiaas_id_user' => $user->ID,
'wiaas_is_company_admin' => 1, //TODO: don't hardcode this
'wiaas_user_full_name' => $user->first_name . ' ' . $user->last_name,
'wiaas_user_type' => $user->roles,
'wiaas_username' => $user->data->user_login
)
));
}
public static function get_countries(){
$countries = Wiaas_Countries::get_list_of_countries();
return new WP_REST_Response($countries);
}
}

View File

@@ -34,13 +34,22 @@ class Wiaas_API {
include_once dirname( __FILE__ ) . '/api/class-wiaas-rest-delivery-process-api.php';
include_once dirname( __FILE__ ) . '/api/class-wiaas-cart-api.php';
include_once dirname( __FILE__ ) . '/api/class-wiaas-document-api.php';
#User controller
include_once dirname( __FILE__ ) . '/api/class-wiaas-rest-user-api.php';
#Customer controller
include_once dirname( __FILE__ ) . '/api/class-wiaas-rest-customer.php';
}
public static function register_rest_routes() {
$controllers = array(
'Wiass_REST_Delivery_Process_API',
'Wiaas_Cart_API',
'Wiaas_Document_API'
'Wiaas_Document_API',
'Wiass_REST_User_API',
'Wiaas_REST_Customer_API'
);
foreach ( $controllers as $controller ) {

View File

@@ -17,18 +17,21 @@ class Wiaas_Countries {
*/
private static $available_countries = array(
'Sweden' => array(
'id' => 1,
'name' => 'Sweden',
'code' => 'se',
'vat' => 9 ,
'currency' => 'SEK'
),
'Denmark' => array(
'id' => 2,
'name' => 'Denmark',
'code' => 'dk',
'vat' => 9 ,
'currency' => 'DKK'
),
'Finland' => array(
'id' => 3,
'name' => 'Finland',
'code' => 'fi',
'vat' => 9 ,
@@ -41,6 +44,24 @@ class Wiaas_Countries {
add_action('woocommerce_after_register_taxonomy', array(__CLASS__, 'register_product_countries_taxonomy'));
}
public static function get_list_of_countries(){
$result = [];
foreach(self::$available_countries as $country){
array_push($result, array(
'country_id' => $country['id'],
'country_name' => $country['name']
));
}
return $result;
}
public static function get_country_name_by_id($id){
foreach(self::$available_countries as $country){
if ($country['id'] == $id) return $country['name'];
}
return '';
}
/**
* Registers product taxonomy for avaiable countries
*/

View File

@@ -8,8 +8,14 @@ defined( 'ABSPATH' ) || exit;
class Wiaas_User {
public static function init() {
include_once dirname( __FILE__ ) . '/class-wiaas-countries.php';
include_once dirname( __FILE__ ) . '/user/class-wiaas-customer.php';
add_action('init', array(__CLASS__, 'load_user_organization'));
add_action('plugins_loaded', array(__CLASS__, 'remove_default_user_groups'), 30);
add_filter('woocommerce_rest_prepare_customer', array(__CLASS__, 'transform_rest_customer'), 10, 3);
add_filter('jwt_auth_token_before_dispatch', array(__CLASS__, 'transform_jwt_token_response'), 10, 2);
}
public static function load_user_organization() {
@@ -24,6 +30,47 @@ class Wiaas_User {
remove_action( 'init', 'wp_register_default_user_group_taxonomy' );
remove_action( 'init', 'wp_register_default_user_type_taxonomy' );
}
/**
* Apply wiaas custom transformation on retrieved JSON customer object
*
* @param $response
* @param $order
* @param $request
*
* @return mixed
*/
public static function transform_rest_customer($response, $order, $request) {
$data = $response->get_data();
$user_id = $data['id'];
$customer_info = Wiaas_Customer::get_customer_info($user_id);
return new WP_REST_Response($customer_info);
}
/**
* Apply wiaas custom transformation on JWT token response
*
* @param $data
* @param $user
*
* @return mixed
*/
public static function transform_jwt_token_response($data, $user) {
return new WP_REST_Response(array(
'token' => $data['token'],
'userInfo' => array(
'wiaas_id_user' => $user->ID,
'wiaas_is_company_admin' => 1, //TODO: don't hardcode this
'wiaas_user_full_name' => $user->first_name . ' ' . $user->last_name,
'wiaas_user_type' => $user->roles,
'wiaas_username' => $user->data->user_login
)
));
}
}
Wiaas_User::init();

View File

@@ -0,0 +1,218 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* Class Wiaas_Customer
*/
class Wiaas_Customer {
public function __construct() {
include_once dirname( __FILE__ ) . '/../class-wiaas-countries.php';
}
public static function get_customer_info($customer_id){
$user = get_userdata($customer_id);
$result = array(
'id' => $customer_id,
'company_id' => self::get_customer_company_id($customer_id),
'is_company_admin' => self::get_customer_company_admin_status($customer_id),
'mail' => $user->user_email,
'name' => $user->first_name . ' ' . $user->last_name,
'phone' => self::get_customer_phone_number($customer_id),
'company_name' => self::get_customer_company_name($customer_id),
'vat_code' => self::get_customer_vat_code($customer_id),
'billing_addresses' => self::get_customer_billing_addresses($customer_id),
'profile_addresses' => self::get_customer_profile_addresses($customer_id),
'user_type' => $user->roles
);
return $result;
}
public static function get_customer_profile_addresses($customer_id){
return get_user_meta($customer_id, 'profile_addresses', true) ?: [];
}
public static function get_customer_billing_addresses($customer_id){
return get_user_meta($customer_id, 'billing_addresses', true) ?: [];
}
public static function get_customer_vat_code($customer_id){
return get_user_meta($customer_id, 'vat_code', true) ?: '';
}
public static function get_customer_company_name($customer_id){
return get_user_meta($customer_id, 'company_name', true) ?: '';
}
public static function get_customer_company_id($customer_id){
return 0; //TODO: don't hardocde this
}
public static function get_customer_company_admin_status($customer_id){
return 1; //TODO: don't hardcode this
}
public static function get_customer_phone_number($customer_id){
return get_user_meta($customer_id, 'phone', true) ?: '';
}
public static function update_customer_profile_info($customer_id, $first_name, $last_name, $phone){
$user = array(
'ID' => $customer_id,
'first_name' => $first_name,
'last_name' => $last_name
);
if (is_wp_error(wp_update_user($user))){
return false;
}
update_user_meta( $customer_id, 'phone', $phone);
return true;
}
public static function update_customer_company_info($customer_id, $company_name, $vat_code){
$result1 = update_user_meta( $customer_id, 'company_name', $company_name);
$result2 = update_user_meta( $customer_id, 'vat_code', $vat_code );
return $result1 || $result2;
}
public static function update_customer_billing_addresses($customer_id, $new_address){
if (!self::validate_address($new_address)){
return false;
}
$billing_addresses = self::get_customer_billing_addresses($customer_id);
if ($new_address->id){
$updated = array(
'id' => $new_address->id,
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
foreach($billing_addresses as $key => $address){
if ($address['id'] === $new_address->id){
$billing_addresses[$key] = $updated;
break;
}
}
}else{
$new_billing_address = array(
'id' => time(),
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
array_push($billing_addresses, $new_billing_address);
}
return update_user_meta( $customer_id, 'billing_addresses', $billing_addresses);
}
public static function update_customer_profile_addresses($customer_id, $new_address){
if (!self::validate_address($new_address)){
return false;
}
$profile_addresses = self::get_customer_profile_addresses($customer_id);
if ($new_address->id){
$updated = array(
'id' => $new_address->id,
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
foreach($profile_addresses as $key => $address){
if ($address['id'] === $new_address->id){
$profile_addresses[$key] = $updated;
break;
}
}
}else{
$new_delivery_address = array(
'id' => time(),
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
array_push($profile_addresses, $new_delivery_address);
}
return update_user_meta( $customer_id, 'profile_addresses', $profile_addresses);
}
public static function delete_customer_profile_address($customer_id, $address_id){
$profile_addresses = self::get_customer_profile_addresses($customer_id);
$counter = 0;
foreach($profile_addresses as $key => $address){
if ($address['id'] == $address_id){
array_splice($profile_addresses, $counter, 1);
break;
}
$counter++;
}
return update_user_meta( $customer_id, 'profile_addresses', $profile_addresses);
}
public static function delete_customer_billing_address($customer_id, $address_id){
$billing_addresses = self::get_customer_billing_addresses($customer_id);
$counter = 0;
foreach($billing_addresses as $key => $address){
if ($address['id'] == $address_id){
array_splice($billing_addresses, $counter, 1);
break;
}
$counter++;
}
return update_user_meta( $customer_id, 'billing_addresses', $billing_addresses);
}
/**
* Check if address is valid
*
* @param $address
*
* @return bool
*/
private static function validate_address($address){
if (empty($address->city)){
return false;
}
if (empty($address->detailed_address)){
return false;
}
return is_numeric($address->zip_code);
}
}

View File

@@ -0,0 +1,597 @@
<?php
/**
* Wiaas_Customer_Test
*
* @package Wiaas
*/
class Wiass_REST_Customer_Api_Test extends Wiaas_Unit_Test_Case {
protected $server;
function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new \WP_REST_Server;
do_action( 'rest_api_init' );
}
/**
* @covers Wiass_REST_Customer_API::update_customer_profile_addresses
*/
function test_update_customer_profile_addresses_as_guest() {
wp_set_current_user(0);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/0/profile-addresses');
$request->set_body_params(array(
'profile_address' => $dummy_address
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_profile_addresses
*/
function test_add_customer_profile_addresses_with_valid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/profile-addresses');
$request->set_body_params(array(
'profile_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('profile_addresses', $profile_info);
$this->assertEquals($profile_info['profile_addresses'][0]['city'], $dummy_address['city']);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'PROFILE_ADDRESS_UPDATED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_profile_addresses
*/
function test_add_customer_profile_addresses_with_invalid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$dummy_address['zip_code'] = 'this is not a zip code';
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/profile-addresses');
$request->set_body_params(array(
'profile_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('profile_addresses', $profile_info);
$this->assertEquals($profile_info['profile_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'PROFILE_ADDRESS_NOT_CHANGED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_billing_addresses
*/
function test_update_customer_billing_addresses_as_guest() {
wp_set_current_user(0);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/0/billing-addresses');
$request->set_body_params(array(
'billing_address' => $dummy_address
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_billing_addresses
*/
function test_add_customer_billing_addresses_with_valid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/billing-addresses');
$request->set_body_params(array(
'billing_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('billing_addresses', $profile_info);
$this->assertEquals($profile_info['billing_addresses'][0]['city'], $dummy_address['city']);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'BILLING_ADDRESS_UPDATED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_billing_addresses
*/
function test_add_customer_billing_addresses_with_invalid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$dummy_address['zip_code'] = 'this is not a zip code';
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/billing-addresses');
$request->set_body_params(array(
'billing_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('billing_addresses', $profile_info);
$this->assertEquals($profile_info['billing_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'BILLING_ADDRESS_NOT_CHANGED');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_billing_addresses
*/
function test_delete_customer_billing_addresses_as_guest() {
$address_id = self::insert_dummy_billing_address();
wp_set_current_user(0);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/billing-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_billing_addresses
*/
function test_delete_customer_billing_addresses() {
$address_id = self::insert_dummy_billing_address();
wp_set_current_user(1);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/billing-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('billing_addresses', $profile_info);
$this->assertEquals($profile_info['billing_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADDRESS_REMOVED');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_profile_addresses
*/
function test_delete_customer_delivery_addresses_as_guest() {
$address_id = self::insert_dummy_profile_address();
wp_set_current_user(0);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/profile-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_profile_addresses
*/
function test_delete_customer_profile_addresses() {
$address_id = self::insert_dummy_profile_address();
wp_set_current_user(1);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/profile-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('profile_addresses', $profile_info);
$this->assertEquals($profile_info['profile_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADDRESS_REMOVED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => 'Trunks',
'last_name' => 'Goten',
'phone' => 11111
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info_with_empty_phone() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => 'Trunks',
'last_name' => 'Goten',
'phone' => ''
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('phone', $profile_info);
$this->assertEquals($profile_info['phone'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_PHONE_NUMBER');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info_with_empty_name() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => '',
'last_name' => '',
'phone' => '23232'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('phone', $profile_info);
$this->assertEquals($profile_info['phone'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_NAME');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => 'Trunks',
'last_name' => 'Goten',
'phone' => '3434'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('phone', $profile_info);
$this->assertArrayHasKey('name', $profile_info);
$this->assertEquals($profile_info['phone'], '3434');
$this->assertEquals($profile_info['name'], 'Trunks Goten');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'PROFILE_UPDATED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => 'Saburly',
'vat_code' => '12345'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info_with_empty_company_name() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => '',
'vat_code' => '12345'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('company_name', $profile_info);
$this->assertArrayHasKey('vat_code', $profile_info);
$this->assertEquals($profile_info['company_name'], '');
$this->assertEquals($profile_info['vat_code'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_COMPANY_NAME');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info_with_empty_vat() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => 'Saburly',
'vat_code' => ''
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('company_name', $profile_info);
$this->assertArrayHasKey('vat_code', $profile_info);
$this->assertEquals($profile_info['company_name'], '');
$this->assertEquals($profile_info['vat_code'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_VAT');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => 'Saburly',
'vat_code' => '123'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('company_name', $profile_info);
$this->assertArrayHasKey('vat_code', $profile_info);
$this->assertEquals($profile_info['company_name'], 'Saburly');
$this->assertEquals($profile_info['vat_code'], '123');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'COMPANY_UPDATED');
}
//Helper functions
private function create_dummy_address(){
return array(
'country_name' => 'Sweden',
'delivery_mail' => 'delivery@email.com',
'id_country_selected' => 1,
'city' => 'Stockholm',
'detailed_address' => 'Dummy Street 7',
'zip_code' => 124443,
'first_name' => 'Tester',
'last_name' => 'Retset',
'invoice_mail' => 'invoice@mail.com'
);
}
private function insert_dummy_billing_address(){
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/billing-addresses');
$request->set_body_params(array(
'billing_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
return $response->get_data()['data']['billing_addresses'][0]['id'];
}
private function insert_dummy_profile_address(){
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/profile-addresses');
$request->set_body_params(array(
'profile_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
return $response->get_data()['data']['profile_addresses'][0]['id'];
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Wiaas_Delivery_Process_Step_Test
*
* @package Wiaas
*/
class Wiass_REST_User_Api_Test extends Wiaas_Unit_Test_Case {
protected $server;
function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new \WP_REST_Server;
do_action( 'rest_api_init' );
}
/**
* @covers Wiass_REST_User_API::validate_token
*/
function test_validate_token_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'POST', '/wiaas/user/validate-token');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_User_API::validate_token
*/
function test_validate_token_with_valid_user() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'POST', '/wiaas/user/validate-token');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$user_info = $response->get_data()['userInfo'];
$this->assertNotNull($user_info);
$this->assertTrue(is_array($user_info));
$this->assertArrayHasKey('wiaas_id_user', $user_info);
$this->assertArrayHasKey('wiaas_is_company_admin', $user_info);
$this->assertArrayHasKey('wiaas_user_full_name', $user_info);
$this->assertArrayHasKey('wiaas_user_type', $user_info);
$this->assertArrayHasKey('wiaas_username', $user_info);
$this->assertEquals($user_info['wiaas_id_user'], '1');
$this->assertEquals($user_info['wiaas_is_company_admin'], '1');
$this->assertEquals($user_info['wiaas_username'], 'admin');
}
/**
* @covers Wiass_REST_User_API::get_countries
*/
function test_get_countries_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'GET', '/wiaas/user/get-countries');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_User_API::get_countries
*/
function test_get_countries() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'GET', '/wiaas/user/get-countries');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertNotNull($data);
$this->assertTrue(is_array($data));
$country = $data[0];
$this->assertNotNull($country);
$this->assertTrue(is_array($country));
$this->assertArrayHasKey('country_id', $country);
$this->assertArrayHasKey('country_name', $country);
}
}

View File

@@ -34,56 +34,23 @@ export const validateToken = () => ({
type: VALIDATE_TOKEN
});
export const validateAccessToken = (token) => {
export const validateAccessToken = () => {
return dispatch => {
dispatch(validateToken());
return htmlClient.fetch({
url: `${API_SERVER}/wp-json/jwt-auth/v1/token/validate`,
method: 'post'
})
url: `${API_SERVER}/wp-json/wiaas/user/validate-token`,
method: 'post'
})
.then(response => {
if (response.data && response.data.data.status === 200) {
if (response.data && response.status === 200) {
// TODO: Implement refresh logic on backend as it was on old wias , or find a nother way
// to handle token validation another way
// const serverTime = response.data.serverTime || 1;
dispatch(loggedIn({
accessToken: token,
userInfo: {
"id": 2,
"name": "Customer User",
"mail": "customer@mail.com",
"phone": "",
"userType": "customer",
"vatCode": "556084-6783",
"companyName": "Coor Service Management AB",
"billingAddresses": [
{
"id": 1,
"city": "fsdfcsdfcs",
"countryName": "SE",
"detailedAddress": "sdfcsvfsdf, fdfvds, fdfvds",
"firstName": "Customer",
"lastName": "User",
"zipCode": "323232"
}
],
"profileAddresses": [
{
"id": 1,
"city": "fsdfcsdfcs",
"countryName": "fsdfcsdfcs",
"detailedAddress": "sdfcsvfsdf, fdfvds, fdfvds",
"zipCode": "323232"
}
]
}
}));
dispatch(loggedIn(response.data.userInfo));
// refreshToken = response.data.refreshToken;
// startRefreshTimer(dispatch, serverTime);
// dispatch(setUserAsCompanyAdmin(response.data.userInfo.wiaas_is_company_admin));
dispatch(setUserAsCompanyAdmin(false));
dispatch(setUserAsCompanyAdmin(response.data.userInfo.wiaas_is_company_admin));
} else {
dispatch(loginFail(response.data));
}
@@ -96,7 +63,7 @@ export const validateAccessToken = (token) => {
}
}
export const setUserAsCompanyAdmin = (isCompanyAdmin) => ({type: SET_COMPANY_ADMIN_FLAG, isCompanyAdmin});
export const setUserAsCompanyAdmin = (isCompanyAdmin) => ({ type: SET_COMPANY_ADMIN_FLAG, isCompanyAdmin });
export const validateCredentials = (username, password) => {
return dispatch => {
@@ -113,22 +80,12 @@ export const validateCredentials = (username, password) => {
.then(response => {
if (response.data && response.data.token) {
const decodedAceessToken = jwtDecode(response.data.token);
// TODO : Uncomment code, and fix user type logic after adding customer type to woocommerce backend
// if(decodedAceessToken.data.wiaas_user_type === 'customer'){
localStorage.setItem('accessToken', response.data.token);
localStorage.setItem('username', username);
localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo));
const serverTime = decodedAceessToken.nbf || 1;
// refreshToken = response.data.refreshToken;
startRefreshTimer(dispatch, serverTime);
dispatch(loggedIn(response.data));
// dispatch(setUserAsCompanyAdmin(response.data.userInfo.wiaas_is_company_admin));
dispatch(setUserAsCompanyAdmin(false));
// }else{
// dispatch(loginFail({status: 'fail', errorMessage: 'INVALID_USER_TYPE'}));
// }
dispatch(loggedIn(response.data.userInfo));
dispatch(setUserAsCompanyAdmin(response.data.userInfo.wiaas_is_company_admin));
} else {
dispatch(loginFail(response.data));
}
@@ -145,10 +102,10 @@ const startRefreshTimer = (dispatch, serverTime) => {
const tokenTimeLeft = decodedAceessToken.exp - serverTime;
const refreshTime = tokenTimeLeft ? (tokenTimeLeft - TEN_MINUTES) * 1000 : REFRESH_TIME;
if(refreshTime <= 0){
if (refreshTime <= 0) {
dispatch(validateRefreshToken());
}else{
refreshTimer = setTimeout(()=>{
} else {
refreshTimer = setTimeout(() => {
dispatch(validateRefreshToken());
}, refreshTime);
}
@@ -162,28 +119,28 @@ const validateRefreshToken = () => {
return dispatch => {
dispatch(requestRefreshToken());
return htmlClient.fetch({
url: `${API_SERVER}/login/api/refreshToken`,
method: 'post',
data: {
refreshToken,
lastActivity: authActivity.lastActivity
}
})
.then(response => {
if (response.data.status === 'success') {
localStorage.setItem('accessToken', response.data.accessToken);
const serverTime = response.data.serverTime || 1;
refreshToken = response.data.refreshToken;
dispatch(setUserAsCompanyAdmin(response.data.userInfo.wiaas_is_company_admin));
startRefreshTimer(dispatch, serverTime);
} else {
dispatch(logout(response.data));
dispatch(loginFail(response.data));
url: `${API_SERVER}/login/api/refreshToken`,
method: 'post',
data: {
refreshToken,
lastActivity: authActivity.lastActivity
}
})
.catch(error => {
htmlClient.onError(error, dispatch);
});
.then(response => {
if (response.data.status === 'success') {
localStorage.setItem('accessToken', response.data.accessToken);
const serverTime = response.data.serverTime || 1;
refreshToken = response.data.refreshToken;
dispatch(setUserAsCompanyAdmin(response.data.userInfo.wiaas_is_company_admin));
startRefreshTimer(dispatch, serverTime);
} else {
dispatch(logout(response.data));
dispatch(loginFail(response.data));
}
})
.catch(error => {
htmlClient.onError(error, dispatch);
});
}
}
@@ -193,62 +150,62 @@ export const getModules = () => {
dispatch(requestModules());
let appModules = {
modules: {
modules: [
{
id: '15',
name: 'Terms',
menuName: 'Terms',
url: 'terms',
isInMenu: '0'
},
{
id: '19',
name: 'Cart',
menuName: 'Cart',
url: 'cart',
isInMenu: '0'
},
{
id: '14',
name: 'ProfileSettings',
menuName: 'ProfileSettings',
url: 'profileSettings',
isInMenu: '0'
},
{
id: '23',
name: 'OrderProjects',
menuName: 'OrderProjects',
url: 'orderProjects',
isInMenu: '0'
},
{
id: '1',
name: 'Dashboards',
menuName: 'Overview',
url: 'dashboards',
isInMenu: '1'
},
{
id: '18',
name: 'CoMarket',
menuName: 'Co-Market',
url: 'co-market',
isInMenu: '1'
modules: [
{
id: '15',
name: 'Terms',
menuName: 'Terms',
url: 'terms',
isInMenu: '0'
},
{
id: '19',
name: 'Cart',
menuName: 'Cart',
url: 'cart',
isInMenu: '0'
},
{
id: '14',
name: 'ProfileSettings',
menuName: 'ProfileSettings',
url: 'profileSettings',
isInMenu: '0'
},
{
id: '23',
name: 'OrderProjects',
menuName: 'OrderProjects',
url: 'orderProjects',
isInMenu: '0'
},
{
id: '1',
name: 'Dashboards',
menuName: 'Overview',
url: 'dashboards',
isInMenu: '1'
},
{
id: '18',
name: 'CoMarket',
menuName: 'Co-Market',
url: 'co-market',
isInMenu: '1'
}
],
subModules: {
'co-market': [
{
moduleUrl: 'co-market',
menuName: 'Orders',
name: 'Orders',
url: 'orders'
}
]
}
],
subModules: {
'co-market': [
{
moduleUrl: 'co-market',
menuName: 'Orders',
name: 'Orders',
url: 'orders'
}
]
}
}
}
}
return dispatch(recieveModules(appModules));
// return htmlClient.fetch({
// url: `${API_SERVER}/login/api/getModules`,
@@ -275,6 +232,7 @@ const recieveModules = (json) => ({
export const logout = () => {
localStorage.removeItem('accessToken');
localStorage.removeItem('userInfo');
clearInterval(refreshTimer);
return {
type: LOGOUT,
@@ -283,11 +241,11 @@ export const logout = () => {
}
}
export const loggedIn = (jsonData) => {
export const loggedIn = (userInfo) => {
return {
type: LOGIN_SUCCESS,
isLoggedIn: true
// userInfo: jsonData.userInfo
isLoggedIn: true,
userInfo: userInfo
}
}
@@ -303,13 +261,13 @@ export const generatePassword = (mail) => {
return dispatch => {
dispatch(requestForgotPassword());
return htmlClient.fetch({
url: `${API_SERVER}/login/api/forgotPassword`,
method: 'post',
data: {mail},
header: {}
})
url: `${API_SERVER}/login/api/forgotPassword`,
method: 'post',
data: { mail },
header: {}
})
.then(response => {
if(typeof response.data !== 'undefined' && 'messages' in response.data) {
if (typeof response.data !== 'undefined' && 'messages' in response.data) {
dispatch(forgotPasswordMessage(response.data.messages[0]));
}
})
@@ -319,7 +277,7 @@ export const generatePassword = (mail) => {
}
}
const requestForgotPassword = () => ({
const requestForgotPassword = () => ({
type: REQUEST_FORGOT_PASSWORD,
errorMessage: 'FORGOT_REQUEST_SENT'
});
@@ -350,13 +308,13 @@ export const changePassword = (token, newPassword, confirmPassword) => {
return dispatch => {
dispatch(requestChange());
return htmlClient.fetch({
url: `${API_SERVER}/login/api/changePassword`,
method: 'post',
data: {token, newPassword, confirmPassword},
header: {}
})
url: `${API_SERVER}/login/api/changePassword`,
method: 'post',
data: { token, newPassword, confirmPassword },
header: {}
})
.then(response => {
if(response.data.messages && response.data.messages.length > 0){
if (response.data.messages && response.data.messages.length > 0) {
dispatch(passwordChanged(response.data.messages[0]));
}
})

View File

@@ -9,9 +9,11 @@ import {
REQUEST_SAVE_BILLING_ADDRESS,
profileTexts
} from '../../constants/profileSettingsConstants';
import {fetchProfileInfo} from './profileSettingsActions';
import {updateMessages} from '../notification/notificationActions';
import {setDialogOpenFlag} from '../dialog/dialogActions';
import {recieveProfileInfo} from './profileSettingsActions';
import { fromWiaasProfileInfo } from '../../helpers/ProfileHelper';
import { toWiaasAddress } from '../../helpers/AddressHelper';
const client = new HtmlClient();
@@ -23,17 +25,17 @@ export const saveProfileAddress = (idUser, profileAddress) => {
return dispatch => {
dispatch(requestSaveAddress());
return client.fetch({
url: `${API_SERVER}/profileSettings/api/saveProfileAddress`,
method: 'post',
data: {profileAddress: JSON.stringify(profileAddress)}
url: `${API_SERVER}/wp-json/wiaas/customer/${idUser}/profile-addresses`,
method: 'put',
data: {
'profile_address': JSON.stringify(toWiaasAddress(profileAddress))
}
})
.then(response => {
if(response.data && response.data.messages){
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data.data)));
dispatch(updateMessages(response.data.messages, profileTexts.messages));
if(response.data.messages[0].code === 'success'){
dispatch(fetchProfileInfo(idUser));
dispatch(setDialogOpenFlag(false));
}
dispatch(setDialogOpenFlag(false));
}
})
.catch(error => {
@@ -50,14 +52,13 @@ export const removeProfileAddress = (idUser, idProfileAddress) => {
return dispatch => {
dispatch(requestRemoveAddress());
return client.fetch({
url: `${API_SERVER}/profileSettings/api/removeProfileAddress`,
method: 'post',
data: {idProfileAddress}
url: `${API_SERVER}/wp-json/wiaas/customer/${idUser}/profile-addresses/${idProfileAddress}`,
method: 'delete'
})
.then(response => {
if(response.data && response.data.messages){
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data.data)));
dispatch(updateMessages(response.data.messages, profileTexts.messages));
dispatch(fetchProfileInfo(idUser));
}
})
.catch(error => {
@@ -70,21 +71,21 @@ const requestSaveBillingAddress = () => ({
type: REQUEST_SAVE_BILLING_ADDRESS
});
export const saveBillingAddress = (idUser, idCompany, billingAddress) => {
export const saveBillingAddress = (idUser, billingAddress) => {
return dispatch => {
dispatch(requestSaveBillingAddress());
return client.fetch({
url: `${API_SERVER}/profileSettings/api/saveBillingAddress`,
method: 'post',
data: {idCompany, billingAddress: JSON.stringify(billingAddress)}
url: `${API_SERVER}/wp-json/wiaas/customer/${idUser}/billing-addresses`,
method: 'put',
data: {
'billing_address': JSON.stringify(toWiaasAddress(billingAddress))
}
})
.then(response => {
if(response.data && response.data.messages){
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data.data)));
dispatch(updateMessages(response.data.messages, profileTexts.messages));
if(response.data.messages[0].code === 'success'){
dispatch(fetchProfileInfo(idUser));
dispatch(setDialogOpenFlag(false));
}
dispatch(setDialogOpenFlag(false));
}
})
.catch(error => {
@@ -101,14 +102,14 @@ export const removeBillingAddress = (idUser, idBillingAddress) => {
return dispatch => {
dispatch(requestRemoveBillingAddress());
return client.fetch({
url: `${API_SERVER}/profileSettings/api/removeBillingAddress`,
method: 'post',
data: {idBillingAddress}
url: `${API_SERVER}/wp-json/wiaas/customer/${idUser}/billing-addresses/${idBillingAddress}`,
method: 'delete'
})
.then(response => {
if(response.data && response.data.messages){
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data.data)));
dispatch(updateMessages(response.data.messages, profileTexts.messages));
dispatch(fetchProfileInfo(idUser));
dispatch(setDialogOpenFlag(false));
}
})
.catch(error => {

View File

@@ -12,6 +12,8 @@ import {
profileTexts
} from '../../constants/profileSettingsConstants';
import {updateMessages} from '../notification/notificationActions';
import { fromWiaasProfileInfo} from '../../helpers/ProfileHelper';
import {fromWiaasCountryList} from '../../helpers/CountryHelper';
const client = new HtmlClient();
@@ -29,49 +31,15 @@ export const recieveProfileInfo = (json) => ({
export const fetchProfileInfo = (idUser) => {
return dispatch => {
dispatch(requestProfileInfo());
dispatch(recieveProfileInfo({
"id": 2,
"name": "Customer User",
"mail": "customer@mail.com",
"phone": "",
"userType": "customer",
"vatCode": "556084-6783",
"companyName": "Coor Service Management AB",
"billingAddresses": [
{
"id": 1,
"city": "Göteborg",
"countryName": "SE",
"detailedAddress": "Lilla Bommen 2",
"firstName": "Customer",
"lastName": "User",
"zipCode": "12323"
return client.fetch({
url: `${API_SERVER}/wp-json/wc/v2/customers/${idUser}`,
method: 'get'
})
.then(response => {
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data)));
}
],
"profileAddresses": [
{
"id": 1,
"city": "Göteborg",
"countryName": "Göteborg",
"detailedAddress": "Lilla Bommen 2",
"zipCode": "12323"
}
]
}));
// return client.fetch({
// url: `${API_SERVER}/wp-json/wiaas/cart/customer-info`,
// method: 'get',
// data: {idUser}
// })
// .then(response => {
// if(response.data){
// dispatch(recieveProfileInfo(response.data));
// }
// })
// .catch(error => {
// client.onError(error, dispatch);
// });
});
}
};
@@ -82,15 +50,20 @@ const requestSaveProfile = () => ({
export const saveProfileInfo = (idUser, profile) => {
return dispatch => {
dispatch(requestSaveProfile());
const parsedFullName = profile.name.trim().split(' ');
return client.fetch({
url: `${API_SERVER}/profileSettings/api/saveProfileInfo`,
method: 'post',
data: {idUser, profile: JSON.stringify(profile)}
url: `${API_SERVER}/wp-json/wiaas/customer/${idUser}/personal-info`,
method: 'PUT',
data: {
'first_name': parsedFullName[0],
'last_name': parsedFullName[1],
'phone': profile.phone
}
})
.then(response => {
if(response.data && response.data.messages){
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data.data)));
dispatch(updateMessages(response.data.messages, profileTexts.messages));
dispatch(fetchProfileInfo(idUser));
}
})
.catch(error => {
@@ -107,14 +80,17 @@ export const saveCompanyInfo = (idUser, companyInfo) => {
return dispatch => {
dispatch(requestSaveCompany());
return client.fetch({
url: `${API_SERVER}/profileSettings/api/saveCompanyInfo`,
method: 'post',
data: {companyInfo: JSON.stringify(companyInfo)}
url: `${API_SERVER}/wp-json/wiaas/customer/${idUser}/company-info`,
method: 'put',
data: {
'vat_code': companyInfo.vatCode,
'company_name': companyInfo.companyName
}
})
.then(response => {
if(response.data && response.data.messages){
if(response.data){
dispatch(recieveProfileInfo(fromWiaasProfileInfo(response.data.data)));
dispatch(updateMessages(response.data.messages, profileTexts.messages));
dispatch(fetchProfileInfo(idUser));
}
})
.catch(error => {
@@ -137,32 +113,17 @@ const recieveCountries = (json) => ({
export const fetchCountries = () => {
return dispatch => {
dispatch(requestCountries());
dispatch(recieveCountries([
{
"idCountry": 3,
"countryName": "Denmark"
},
{
"idCountry": 4,
"countryName": "Finland"
},
{
"idCountry": 2,
"countryName": "Sweden"
}
]));
// return client.fetch({
// url: `${API_SERVER}/profileSettings/api/getCoutnries`,
// method: 'get'
// })
// .then(response => {
// if(response.data){
// dispatch(recieveCountries(response.data));
// }
// })
// .catch(error => {
// client.onError(error, dispatch);
// });
return client.fetch({
url: `${API_SERVER}/wp-json/wiaas/user/get-countries`,
method: 'get'
})
.then(response => {
if(response.data){
dispatch(recieveCountries(response.data.map(country => fromWiaasCountryList(country))));
}
})
.catch(error => {
client.onError(error, dispatch);
});
}
};

View File

@@ -35,7 +35,8 @@ export const profileTexts = {
FIRST_NAME: 'First Name',
LAST_NAME: 'Last Name',
DELEGATE: 'Attention',
INVOICE_MAIL: 'Invoice Mail'
INVOICE_MAIL: 'Invoice Mail',
DELIVERY_MAIL: 'Delivery Mail'
},
buttons: {
SAVE: 'Save',
@@ -56,7 +57,7 @@ export const profileTexts = {
PROFILE_NOT_CHANGED: 'No changes!',
NOT_COMPANY_ADMIN: 'You are not allowed to change the company information! Contact your company admin user.',
ADD_VAT: 'The vat code can not be empty!',
ADD_COPMANY_NAME: 'The company name can not be empty!',
ADD_COMPANY_NAME: 'The company name can not be empty!',
COMPANY_UPDATED: 'Company info updated!',
COMPANY_NOT_CHANGED: 'No changes!',
ADD_COMPANY: 'Invalid company!',
@@ -77,6 +78,7 @@ export const profileTexts = {
ADD_FIRST_NAME: 'The first name field can not be empty',
ADD_LAST_NAME: 'The last name field can not be empty',
ADD_INVOICE_MAIL: 'The invoice mail field can not be empty',
INVALID_INVOICE_MAIL: 'Invalid invoice mail address'
INVALID_INVOICE_MAIL: 'Invalid invoice mail address',
INTERNAL_SERVER_ERROR: 'Error occured. Please try again'
}
};

View File

@@ -45,8 +45,7 @@ class CartCustomerDetailsContainer extends Component {
this.props.dispatch(fetchCartItems());
this.props.dispatch(setNextActionFct(this.handleNextAction));
this.props.dispatch(setPrevActionFct(this.handlePrevAction));
//this.props.dispatch(fetchProfileInfo(this.props.userInfo.wiaas_id_user));
this.props.dispatch(fetchProfileInfo());
this.props.dispatch(fetchProfileInfo(this.props.userInfo.wiaas_id_user));
this.props.dispatch(fetchCountries());
}
@@ -192,7 +191,7 @@ class CartCustomerDetailsContainer extends Component {
(profileInfo && !isProfileLoading) &&
<ProfileAddressesContainer
params={{location: 'cart', handleDeliveryChange: this.handleDeliveryChange, idSelectedDeliveryAddress: this.state.delivery.id}}
idUser={0}/>
idUser={this.props.userInfo.wiaas_id_user}/>
}
</Form>
</div>
@@ -206,7 +205,7 @@ class CartCustomerDetailsContainer extends Component {
<BillingAddressesContainer
idCompany={profileInfo.idCompany}
params={{location: 'cart', handleBillingChange: this.handleBillingChange, idSelectedBillingAddress: this.state.billing.id}}
idUser={0}/>
idUser={this.props.userInfo.wiaas_id_user}/>
}
</Form>
</div>

View File

@@ -21,7 +21,16 @@ class SelectDeliveryAddress extends Component {
<div>
<div className="address-text">
<Input id={'delivery-addres-check-' + profileAddress.id} checked={idSelectedDeliveryAddress === profileAddress.id} type="radio" onChange={this.handleOptionChange} name="deliveryAddress" />
{profileAddress.countryName}, {profileAddress.city}, {profileAddress.detailedAddress}, {profileAddress.zipCode}
<div className="small-address-title">
{profileAddress.firstName} {profileAddress.lastName}
{
profileAddress.deliveryMail &&
<span>( {profileAddress.deliveryMail} )</span>
}
</div>
<div>
{profileAddress.countryName}, {profileAddress.city}, {profileAddress.detailedAddress}, {profileAddress.zipCode}
</div>
</div>
<div className="address-icons">
<i className="fa fa-pencil control-icon edit-address-btn"

View File

@@ -226,11 +226,6 @@
.cart-address-box {
margin-top: 2rem;
}
#order-projects .actions-button, .add-address-btn, .address-icons {
opacity: 0.3;
pointer-events: none;
}
}
#cart-customer-main-information-container {

View File

@@ -55,7 +55,7 @@ class LogInForm extends Component {
componentDidMount() {
if (localStorage.accessToken) {
this.props.dispatch(validateAccessToken(localStorage.accessToken));
this.props.dispatch(validateAccessToken());
}
}

View File

@@ -9,6 +9,7 @@ import {profileTexts} from '../../constants/profileSettingsConstants';
import {setDialogContent, setDialogOpenFlag} from '../../actions/dialog/dialogActions';
import {saveBillingAddress, removeBillingAddress} from '../../actions/profileSettings/addressActions';
import './style/AddressesContainer.css';
import { updateMessages } from '../../actions/notification/notificationActions';
class BillingAddressesContainer extends Component {
constructor(props) {
@@ -21,7 +22,30 @@ class BillingAddressesContainer extends Component {
}
saveBillingAddress(address){
this.props.dispatch(saveBillingAddress(this.props.idUser, this.props.idCompany, address));
const messages = [];
if (!address.zipCode){
messages.push({
'code':'error',
'message':'ADD_ZIP'
});
}
if (!address.detailedAddress){
messages.push({
'code':'error',
'message':'ADD_ADDRESS'
});
}
if (!address.city){
messages.push({
'code':'error',
'message':'ADD_CITY'
});
}
if (messages.length > 0){
this.props.dispatch(updateMessages(messages, profileTexts.messages));
}else{
this.props.dispatch(saveBillingAddress(this.props.idUser, address));
}
}
onAddressChange(address){

View File

@@ -9,6 +9,7 @@ import {profileTexts} from '../../constants/profileSettingsConstants';
import {setDialogContent, setDialogOpenFlag} from '../../actions/dialog/dialogActions';
import {saveProfileAddress, removeProfileAddress} from '../../actions/profileSettings/addressActions';
import './style/AddressesContainer.css';
import { updateMessages } from '../../actions/notification/notificationActions';
class ProfileAddressesContainer extends Component {
constructor(props) {
@@ -21,7 +22,30 @@ class ProfileAddressesContainer extends Component {
}
saveProfileAddress(profileAddress){
this.props.dispatch(saveProfileAddress(this.props.idUser, profileAddress));
const messages = [];
if (!profileAddress.zipCode){
messages.push({
'code':'error',
'message':'ADD_ZIP'
});
}
if (!profileAddress.detailedAddress){
messages.push({
'code':'error',
'message':'ADD_ADDRESS'
});
}
if (!profileAddress.city){
messages.push({
'code':'error',
'message':'ADD_CITY'
});
}
if (messages.length > 0){
this.props.dispatch(updateMessages(messages, profileTexts.messages));
}else{
this.props.dispatch(saveProfileAddress(this.props.idUser, profileAddress));
}
}
onAddressChange(address){

View File

@@ -42,6 +42,7 @@ class AddEditBillingAddress extends Component {
<Label for="address-first-name">{profileTexts.labels.FIRST_NAME}</Label>
<Input value={firstName}
onChange={this.handleChange}
autoComplete="nope"
type="text"
name="firstName"
id="address-first-name"
@@ -52,6 +53,7 @@ class AddEditBillingAddress extends Component {
<Label for="address-last-name">{profileTexts.labels.LAST_NAME}</Label>
<Input value={lastName}
onChange={this.handleChange}
autoComplete="nope"
type="text"
name="lastName"
id="address-last-name"
@@ -62,6 +64,7 @@ class AddEditBillingAddress extends Component {
<Label for="address-invoice-mail">{profileTexts.labels.INVOICE_MAIL}</Label>
<Input value={invoiceMail}
onChange={this.handleChange}
autoComplete="nope"
type="text"
name="invoiceMail"
id="address-invoice-mail"
@@ -74,6 +77,7 @@ class AddEditBillingAddress extends Component {
<Input value={idCountrySelected}
type="select"
onChange={this.handleChange}
autoComplete="nope"
name="idCountrySelected"
id="address-country"
placeholder={profileTexts.labels.ADDRESS_COUNTRY}>
@@ -89,6 +93,7 @@ class AddEditBillingAddress extends Component {
<Label for="address-city">{profileTexts.labels.ADDRESS_CITY}<span className="required-icon">*</span></Label>
<Input value={city}
onChange={this.handleChange}
autoComplete="nope"
type="text"
name="city"
id="address-city"
@@ -99,6 +104,7 @@ class AddEditBillingAddress extends Component {
<Label for="address-details">{profileTexts.labels.ADDRESS_DETAILS}<span className="required-icon">*</span></Label>
<Input value={detailedAddress}
onChange={this.handleChange}
autoComplete="nope"
type="textarea"
name="detailedAddress"
id="address-details"
@@ -109,6 +115,7 @@ class AddEditBillingAddress extends Component {
<Label for="address-zip">{profileTexts.labels.ADDRESS_ZIP}<span className="required-icon">*</span></Label>
<Input value={zipCode}
onChange={this.handleChange}
autoComplete="nope"
type="text"
name="zipCode"
id="address-zip"

View File

@@ -12,7 +12,10 @@ class AddEditProfileAddress extends Component {
idCountrySelected: address.idCountrySelected || this.props.params.countries[0].idCountry,
city: address.city || '',
detailedAddress: address.detailedAddress || '',
zipCode: address.zipCode || ''
zipCode: address.zipCode || '',
firstName: address.firstName || '',
lastName: address.lastName || '',
deliveryMail: address.deliveryMail || ''
};
this.props.params.onAddressChange(this.state);
@@ -30,16 +33,52 @@ class AddEditProfileAddress extends Component {
}
render() {
const {idCountrySelected, city, detailedAddress, zipCode} = this.state;
const {idCountrySelected, city, detailedAddress, zipCode, firstName, lastName, deliveryMail} = this.state;
const {countries} = this.props.params;
return (
<div className="address-add-edit-content">
<Form className="address-edit-content">
<h5>{profileTexts.labels.DELEGATE}</h5>
<FormGroup>
<Label for="address-first-name">{profileTexts.labels.FIRST_NAME}</Label>
<Input value={firstName}
autoComplete="nope"
onChange={this.handleChange}
type="text"
name="firstName"
id="address-first-name"
placeholder={profileTexts.labels.FIRST_NAME} />
</FormGroup>
<FormGroup>
<Label for="address-last-name">{profileTexts.labels.LAST_NAME}</Label>
<Input value={lastName}
autoComplete="nope"
onChange={this.handleChange}
type="text"
name="lastName"
id="address-last-name"
placeholder={profileTexts.labels.LAST_NAME} />
</FormGroup>
<FormGroup>
<Label for="address-delivery-mail">{profileTexts.labels.DELIVERY_MAIL}</Label>
<Input value={deliveryMail}
autoComplete="nope"
onChange={this.handleChange}
type="text"
name="deliveryMail"
id="address-delivery-mail"
placeholder={profileTexts.labels.DELIVERY_MAIL} />
</FormGroup>
<h5>{profileTexts.labels.BILLING_ADDRESSES}</h5>
<FormGroup>
<Label for="address-country">{profileTexts.labels.ADDRESS_COUNTRY}<span className="required-icon">*</span></Label>
<Input value={idCountrySelected}
type="select"
autoComplete="nope"
onChange={this.handleChange}
name="idCountrySelected"
id="address-country"
@@ -56,6 +95,7 @@ class AddEditProfileAddress extends Component {
<Label for="address-city">{profileTexts.labels.ADDRESS_CITY}<span className="required-icon">*</span></Label>
<Input value={city}
onChange={this.handleChange}
autoComplete="nope"
type="text"
name="city"
id="address-city"
@@ -65,6 +105,7 @@ class AddEditProfileAddress extends Component {
<FormGroup>
<Label for="address-details">{profileTexts.labels.ADDRESS_DETAILS}<span className="required-icon">*</span></Label>
<Input value={detailedAddress}
autoComplete="nope"
onChange={this.handleChange}
type="textarea"
name="detailedAddress"
@@ -75,6 +116,7 @@ class AddEditProfileAddress extends Component {
<FormGroup>
<Label for="address-zip">{profileTexts.labels.ADDRESS_ZIP}<span className="required-icon">*</span></Label>
<Input value={zipCode}
autoComplete="nope"
onChange={this.handleChange}
type="text"
name="zipCode"

View File

@@ -8,7 +8,16 @@ class ProfileAddress extends Component {
return (
<div className="address-row">
<div className="address-text">
{profileAddress.countryName}, {profileAddress.city}, {profileAddress.detailedAddress}, {profileAddress.zipCode}
<div className="small-address-title">
{profileAddress.firstName} {profileAddress.lastName}
{
profileAddress.deliveryMail &&
<span>( {profileAddress.deliveryMail} )</span>
}
</div>
<div>
{profileAddress.countryName}, {profileAddress.city}, {profileAddress.detailedAddress}, {profileAddress.zipCode}
</div>
</div>
<div className="address-icons">
<i className="fa fa-pencil control-icon edit-address-btn"

View File

@@ -0,0 +1,29 @@
export const fromWiaasAddress = (address) => {
return {
id: address.id,
countryName: address.country_name,
deliveryMail: address.delivery_mail,
idCountrySelected: address.id_country_selected,
city: address.city,
detailedAddress: address.detailed_address,
zipCode: address.zip_code,
firstName: address.first_name,
lastName: address.lastName,
invoiceMail: address.invoice_mail
}
};
export const toWiaasAddress = (address) => {
return {
id: address.id,
country_name: address.countryName,
delivery_mail: address.deliveryMail,
id_country_selected: address.idCountrySelected,
city: address.city,
detailed_address: address.detailedAddress,
zip_code: address.zipCode,
first_name: address.firstName,
last_name: address.lastName,
invoice_mail: address.invoiceMail
}
};

View File

@@ -0,0 +1,6 @@
export const fromWiaasCountryList = (countryList) => {
return {
idCountry: countryList.country_id,
countryName: countryList.country_name
}
}

View File

@@ -0,0 +1,17 @@
import { fromWiaasAddress } from "./AddressHelper";
export const fromWiaasProfileInfo = (profileInfo) => {
return {
id: profileInfo.id,
idCompany: profileInfo.company_id,
companyName: profileInfo.company_name,
vatCode: profileInfo.vat_code,
isCompanyAdmin: profileInfo.is_company_admin,
mail: profileInfo.mail,
name: profileInfo.name,
phone: profileInfo.phone,
billingAddresses: profileInfo.billing_addresses.map(address => fromWiaasAddress(address)),
profileAddresses: profileInfo.profile_addresses.map(address => fromWiaasAddress(address)),
userType: profileInfo.user_type,
}
};