Skip to content

Commit

Permalink
Merge pull request #22 from pagantis/Improvements
Browse files Browse the repository at this point in the history
Improvements
  • Loading branch information
pgarcess authored Aug 7, 2019
2 parents bf6bef0 + 2786580 commit e006209
Show file tree
Hide file tree
Showing 3 changed files with 200 additions and 15 deletions.
117 changes: 104 additions & 13 deletions WC_Pagantis.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Plugin Name: Pagantis
* Plugin URI: http://www.pagantis.com/
* Description: Financiar con Pagantis
* Version: 8.1.2
* Version: 8.1.3
* Author: Pagantis
*/

Expand All @@ -29,6 +29,9 @@ class WcPagantis
/** Concurrency tablename */
const CONCURRENCY_TABLE = 'pagantis_concurrency';

/** Config tablename */
const ORDERS_TABLE = 'posts';

public $defaultConfigs = array('PAGANTIS_TITLE'=>'Instant Financing',
'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pgSDK.simulator.types.SIMPLE',
'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pgSDK.simulator.skins.BLUE',
Expand Down Expand Up @@ -58,8 +61,6 @@ public function __construct()

$this->template_path = plugin_dir_path(__FILE__).'/templates/';

$this->pagantisActivation();

$this->extraConfig = $this->getExtraConfig();

load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
Expand All @@ -71,6 +72,7 @@ public function __construct()
add_action('wp_enqueue_scripts', 'add_pagantis_widget_js');
add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
register_activation_hook(__FILE__, array($this, 'pagantisActivation'));
}

/*
Expand Down Expand Up @@ -116,6 +118,44 @@ public function pagantisActivation()

require_once(ABSPATH.'wp-admin/includes/upgrade.php');
dbDelta($sql);
} else {
//Updated value field to adapt to new length < v8.0.1
$query = "select COLUMN_TYPE FROM information_schema.COLUMNS where TABLE_NAME='$tableName' AND COLUMN_NAME='value'";
$results = $wpdb->get_results($query, ARRAY_A);
if ($results['0']['COLUMN_TYPE'] == 'varchar(100)') {
$sql = "ALTER TABLE $tableName MODIFY value varchar(1000)";
$wpdb->query($sql);
}

//Adapting selector to array < v8.1.1
$query = "select * from $tableName where config='PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'
or config='PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'";
$dbCurrentConfig = $wpdb->get_results($query, ARRAY_A);
foreach ($dbCurrentConfig as $item) {
if ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR') {
$css_price_selector = $this->preparePriceSelector($item['value']);
if ($item['value'] != $css_price_selector) {
$wpdb->update(
$tableName,
array('value' => stripslashes($css_price_selector)),
array('config' => 'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'),
array('%s'),
array('%s')
);
}
} elseif ($item['config'] == 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR') {
$css_quantity_selector = $this->prepareQuantitySelector($item['value']);
if ($item['value'] != $css_quantity_selector) {
$wpdb->update(
$tableName,
array('value' => stripslashes($css_quantity_selector)),
array('config' => 'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'),
array('%s'),
array('%s')
);
}
}
}
}

$dbConfigs = $wpdb->get_results("select * from $tableName", ARRAY_A);
Expand Down Expand Up @@ -165,15 +205,13 @@ public function pagantisAddProductSimulator()
return;
}

$css_quantity_selector = $this->prepareQuantitySelector();
$css_price_selector = $this->preparePriceSelector();
$template_fields = array(
'total' => is_numeric($product->price) ? $product->price : 0,
'public_key' => $cfg['pagantis_public_key'],
'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
'positionSelector' => $this->extraConfig['PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'],
'quantitySelector' => unserialize($css_quantity_selector),
'priceSelector' => unserialize($css_price_selector),
'quantitySelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR']),
'priceSelector' => unserialize($this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR']),
'totalAmount' => is_numeric($product->price) ? $product->price : 0,
'locale' => $locale
);
Expand Down Expand Up @@ -268,7 +306,7 @@ public function readLogs($data)
$from = $filters['from'];
$to = $filters['to'];
$cfg = get_option('woocommerce_pagantis_settings');
$privateKey = isset($cfg['secret_key']) ? $cfg['secret_key'] : null;
$privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
$tableName = $wpdb->prefix.self::LOGS_TABLE;
$query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
$results = $wpdb->get_results($query);
Expand Down Expand Up @@ -310,7 +348,7 @@ public function updateExtraConfig($data)
if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
$wpdb->update(
$tableName,
array('value' => $value),
array('value' => stripslashes($value)),
array('config' => $config),
array('%s'),
array('%s')
Expand Down Expand Up @@ -343,6 +381,45 @@ public function updateExtraConfig($data)
exit();
}

/**
* Read logs
*/
public function readApi($data)
{
global $wpdb;
$filters = ($data->get_params());
$response = array('timestamp'=>time());
$secretKey = $filters['secret'];
$from = ($filters['from']) ? date_create($filters['from']) : date("Y-m-d", strtotime("-7 day"));
$to = ($filters['to']) ? date_create($filters['to']) : date("Y-m-d", strtotime("+1 day"));
$method = ($filters['method']) ? ($filters['method']) : 'Pagantis';
$cfg = get_option('woocommerce_pagantis_settings');
$privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
$tableName = $wpdb->prefix.self::ORDERS_TABLE;
$tableNameInner = $wpdb->prefix.'postmeta';
$query = "select * from $tableName tn INNER JOIN $tableNameInner tn2 ON tn2.post_id = tn.id
where tn.post_type='shop_order' and tn.post_date>'".$from->format("Y-m-d")."'
and tn.post_date<'".$to->format("Y-m-d")."' order by tn.post_date desc";
$results = $wpdb->get_results($query);

if (isset($results) && $privateKey == $secretKey) {
foreach ($results as $result) {
$key = $result->ID;
$response['message'][$key]['timestamp'] = $result->post_date;
$response['message'][$key]['order_id'] = $key;
$response['message'][$key][$result->meta_key] = $result->meta_value;
}
} else {
$response['result'] = 'Error';
}
$response = json_encode($response);
header("HTTP/1.1 200", true, 200);
header('Content-Type: application/json', true);
header('Content-Length: '.strlen($response));
echo($response);
exit();
}

/**
* ENDPOINT - Read logs -> Hook: rest_api_init
* @return mixed
Expand Down Expand Up @@ -372,6 +449,18 @@ public function pagantisRegisterEndpoint()
),
true
);

register_rest_route(
'pagantis/v1',
'/api/(?P<secret>\w+)/(?P<from>\w+)/(?P<to>\w+)',
array(
'methods' => 'GET',
'callback' => array(
$this,
'readApi')
),
true
);
}

/**
Expand All @@ -391,11 +480,12 @@ private function getExtraConfig()
}

/**
* @param $css_quantity_selector
*
* @return mixed|string
*/
private function prepareQuantitySelector()
private function prepareQuantitySelector($css_quantity_selector)
{
$css_quantity_selector = $this->extraConfig['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
if ($css_quantity_selector == 'default' || $css_quantity_selector == '') {
$css_quantity_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'];
} elseif (!unserialize($css_quantity_selector)) { //in the case of a custom string selector, we keep it
Expand All @@ -406,11 +496,12 @@ private function prepareQuantitySelector()
}

/**
* @param $css_price_selector
*
* @return mixed|string
*/
private function preparePriceSelector()
private function preparePriceSelector($css_price_selector)
{
$css_price_selector = $this->extraConfig['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
if ($css_price_selector == 'default' || $css_price_selector == '') {
$css_price_selector = $this->defaultConfigs['PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'];
} elseif (!unserialize($css_price_selector)) { //in the case of a custom string selector, we keep it
Expand Down
94 changes: 93 additions & 1 deletion test/selenium/buy/AbstractBuy.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Test\Selenium\PagantisWoocommerceTest;
use Pagantis\SeleniumFormUtils\SeleniumHelper;
use Httpful\Request;
use Httpful\Mime;

/**
* Class AbstractBuy
Expand Down Expand Up @@ -51,10 +52,25 @@ abstract class AbstractBuy extends PagantisWoocommerceTest
const LOGO_FILE = 'logo.png';

/**
* Logout URL
* Notification folder
*/
const NOTIFICATION_FOLDER = '/?wc-api=wcpagantisgateway';

/**
* Config folder
*/
const CONFIG_FOLDER = '/?rest_route=/pagantis/v1/configController/';

/**
* Log folder
*/
const LOG_FOLDER = '/?rest_route=/pagantis/v1/logs/';

/**
* Api folder
*/
const API_FOLDER = '/?rest_route=/pagantis/v1/api/';

/**
* Notification param1
*/
Expand Down Expand Up @@ -105,6 +121,25 @@ abstract class AbstractBuy extends PagantisWoocommerceTest
*/
public $notifyUrl;

/**
* @var array $configs
*/
protected $configs = array(
"PAGANTIS_TITLE",
"PAGANTIS_SIMULATOR_DISPLAY_TYPE",
"PAGANTIS_SIMULATOR_DISPLAY_SKIN",
"PAGANTIS_SIMULATOR_DISPLAY_POSITION",
"PAGANTIS_SIMULATOR_START_INSTALLMENTS",
"PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR",
"PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION",
"PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR",
"PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR",
"PAGANTIS_FORM_DISPLAY_TYPE",
"PAGANTIS_DISPLAY_MIN_AMOUNT",
"PAGANTIS_URL_OK",
"PAGANTIS_URL_KO",
);

/**
* @return mixed
*/
Expand Down Expand Up @@ -373,4 +408,61 @@ protected function checkAlreadyProcessed()
$this->assertNotEmpty($response->body->result);
$this->assertContains(JsonSuccessResponse::RESULT, $response->body->result, "PR51=>".$response->body->result);
}

/**
* @throws \Httpful\Exception\ConnectionErrorException
*/
protected function checkExtraConfig()
{
$configUrl = $this->woocommerceUrl.self::CONFIG_FOLDER.$this->configuration['secretKey'];
$response = Request::get($configUrl)->expects('json')->send();
$content = $response->body;
foreach ($this->configs as $config) {
$this->assertArrayHasKey($config, (array) $content, "PR61=>".print_r($content, true));
}

$requestTitle = 'changed';
$body = array('PAGANTIS_TITLE' => $requestTitle);
$response = Request::post($configUrl)
->body($body, Mime::FORM)
->expectsJSON()
->send();
$title = $response->body->PAGANTIS_TITLE;
$this->assertEquals($requestTitle, $title, "PR62=>".$configUrl." => ".$requestTitle ."!=".$title);
$requestTitle = 'Instant Financing';
$body = array('PAGANTIS_TITLE' => $requestTitle);
$response = Request::post($configUrl)
->body($body, Mime::FORM)
->expectsJSON()
->send();
$title = $response->body->PAGANTIS_TITLE;
$this->assertEquals($requestTitle, $title, "PR62b=>".$configUrl." => ".$requestTitle ."!=".$title);
}

/**
* @throws \Httpful\Exception\ConnectionErrorException
*/
protected function checkApi()
{
$dateFrom = date("Ymd", strtotime("-1 day"));
$dateTo = date("Ymd", strtotime("+1 day"));
$apiUrl = $this->woocommerceUrl.self::API_FOLDER.$this->configuration['secretKey']."/$dateFrom/$dateTo";
$response = Request::get($apiUrl)->expects('json')->send();
$this->assertNotEmpty($response->body->message);
$numberOfPurchases = count((array)$response->body->message);
$this->assertEquals(1, $numberOfPurchases, "PR63=>$apiUrl = $numberOfPurchases");
}

/**
* @throws \Httpful\Exception\ConnectionErrorException
*/
protected function checkLogs()
{
$dateFrom = date("Ymd", strtotime("-1 day"));
$dateTo = date("Ymd", strtotime("+1 day"));
$logUrl = $this->woocommerceUrl.self::LOG_FOLDER.$this->configuration['secretKey']."/$dateFrom/$dateTo";
$response = Request::get($logUrl)->expects('json')->send();
$this->assertEquals(2, count($response->body), "PR60=>".$logUrl." = ".count($response->body));
}

}
4 changes: 3 additions & 1 deletion test/selenium/buy/BuyWc3Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ public function testBuy()
$this->prepareCheckout();
$this->makeCheckoutAndPagantis();
$this->makeValidation();
$this->checkNotificationException();
$this->checkExtraConfig();
$this->checkLogs();
$this->checkApi();
$this->quit();
}
}

0 comments on commit e006209

Please sign in to comment.