Skip to content
Snippets Groups Projects
Commit 3304c127 authored by Reinhold Kainhofer's avatar Reinhold Kainhofer
Browse files

First working version of the plugin...

parent 2a0f2a4a
Branches
Tags
No related merge requests found
......@@ -11,8 +11,8 @@ table.rules_shipping_methods.widefat {
div.shipping_rules_ruleset {
background: #f8f8f8;
border: #D0D0D0 1px solid;
margin-bottom: 10px;
margin-top: 10px;
margin-bottom: 20px;
margin-top: 20px;
}
#shipping_rules_rulesets .ruleset_openclose {
......@@ -26,7 +26,7 @@ div.shipping_rules_ruleset {
}
#shipping_rules_rulesets .shipping_rules_ruleset.closed .ruleset_openclose:before {
content: '\f141';
content: '\f140';
}
#shipping_rules_rulesets .shipping_rules_ruleset .ruleset_openclose:before {
content: '\f142';
......
media="all"
.woocommerce_page_wc-settings .rules_shipping_methods .add.button:before {
content: "";
}
\ No newline at end of file
......@@ -67,14 +67,6 @@ function render_meta_box_shipping_rules_single_ruleset ($post, $nr, $ruleset) {
/** Rules */
$option_value = isset($ruleset['rules'])?$ruleset['rules']:'';
// $option_value='Name=Whatever; Amount>35; Shipping=5
// Name=2; contains_only(SKUs, "asdf"); Shipping=33
// State2=="AZ"; NoShipping
// Amount<5; Shipping=333
// ZIP==4321; Shipping=3
// ZIP==9999; Shipping=15
// Shipping=0
// ';
$nrrules = count(explode("\n", $option_value));
$value = array(
'id' => $id.'[rules]',
......@@ -82,7 +74,7 @@ function render_meta_box_shipping_rules_single_ruleset ($post, $nr, $ruleset) {
'type' => 'textarea',
'css' => '',
'class' => 'shipping_rules_rule_textarea',
'placeholder' => __('Rules of the form:\nName="Rule name"; Amount>100; [...Conditions...]; Shipping=3', 'opentools-shippingrules'),
'placeholder' => __('Rules of the form: Name="Rule name"; Amount>100; [...Conditions...]; Shipping=3', 'opentools-shippingrules'),
);
$custom_attributes = array(
'rows="'.absint(max($nrrules,5)).'"',
......
......@@ -18,7 +18,7 @@ function render_meta_box_shipping_rules_rulesets ($post, $rulesets) {
wp_nonce_field( 'shipping_rules_rulesets_meta_box', 'shipping_rules_rulesets_meta_box_nonce' );
?><div class='shipping_rules shipping_rules_rulesets shipping_rules_meta_box shipping_rules_rulesets_meta_box'>
?><div class='shipping_rules shipping_rules_rulesets shipping_rules_meta_box shipping_rules_rulesets_meta_box ui-sortable'>
<pre><?php //print_r($rulesets); ?></pre>
<?php
require_once plugin_dir_path( __FILE__ ) . 'meta-box-field-ruleset.php';
......@@ -33,6 +33,7 @@ wp_nonce_field( 'shipping_rules_rulesets_meta_box', 'shipping_rules_rulesets_met
jQuery(document).ready(function($){
// $( '.shipping_rules .chzn-select' ).chosen();
$('.shipping_rules .select2').select2();
$('.shipping_rules_rulesets_meta_box.ui-sortable').sortable();
});
</script>
......
......@@ -8,7 +8,7 @@
* License: GPLv3+
*/
class WC_Shipping_by_Rules extends WC_Shipping_Method {
class Shipping_by_Rules extends WC_Shipping_Method {
protected $helper = null;
/**
* Constructor for your shipping class
......@@ -21,7 +21,6 @@ class WC_Shipping_by_Rules extends WC_Shipping_Method {
require_once( plugin_dir_path( __FILE__ ) . '/rules_shipping_framework_woocommerce.php');
}
$this->helper = RulesShippingFrameworkWooCommerce::getHelper();
$this->shipping_rules_option = 'woocommerce_shipping_rules_ordering';
$this->id = 'shipping_by_rules'; // Id for your shipping method. Should be uunique.
$this->title = $this->helper->__( 'Shipping By Rules <small>(displayed title changes according to configured methods)</small>');
......@@ -38,8 +37,6 @@ class WC_Shipping_by_Rules extends WC_Shipping_Method {
* @return void
*/
function init() {
// $this->get_rule_shipping_methods();
$this->init_form_fields();
$this->init_settings();
......@@ -50,26 +47,6 @@ class WC_Shipping_by_Rules extends WC_Shipping_Method {
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_shipping_rules_sorting' ) );
}
/**
* get_shipping_rules_methods function.
*/
public function get_rule_shipping_methods() {
$unsortedmethods = get_posts (array ('posts_per_page' => '-1', 'post_type' => 'shipping_rules'));
$ordering = get_option( $this->shipping_rules_option );
$methods = array();
foreach ($ordering as $o) {
foreach ($unsortedmethods as $key=>$m) {
if ($m->ID == $o) {
$methods[$o] = $m;
unset($unsortedmethods[$key]);
break;
}
}
}
$methods = $methods + $unsortedmethods;
return $methods;
}
/**
* Initialise Gateway Settings Form Fields
*
......@@ -121,12 +98,9 @@ class WC_Shipping_by_Rules extends WC_Shipping_Method {
*/
public function process_shipping_rules_sorting() {
$ordering = isset($_POST[ 'rules_method_order']) ? array_map( 'wc_clean', $_POST[ 'rules_method_order'] ) : array();
update_option( $this->shipping_rules_option, $ordering );
$this->get_rule_shipping_methods();
$this->helper->set_method_ordering($ordering);
}
/**
* calculate_shipping function.
......@@ -136,18 +110,24 @@ class WC_Shipping_by_Rules extends WC_Shipping_Method {
* @return void
*/
public function calculate_shipping( $package ) {
$cost = $this->helper->getCosts($package, $this);
// TODO!
// print("<pre>Helper: ".print_r($helper,1)."</pre>");
// print($t);
// $rate = array(
// 'id' => $this->id,
// 'label' => "Test rule",
// 'cost' => '11.99',
// 'calc_tax' => 'per_item'
// );
// Register the rate
// $this->add_rate( $rate );
$methods = $this->helper->get_rule_shipping_methods();
foreach ($methods as $method) {
$rates = $this->helper->getCosts($package, $method);
foreach ($rates as $r) {
$label = $r['name'];
if (isset($r['rulename']) && !empty($r['rulename'])) {
$label .= ' (' . $r['rulename'] . ')';
}
$rate = array(
'id' => $r['method'],
'label' => $label,
'cost' => $r['cost'],
// 'calc_tax' => 'per_item',
);
// Register the rate
$this->add_rate( $rate );
}
}
}
}
......@@ -5,7 +5,7 @@ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
*
* Initialize the Shipping by Rules post type (to configure the .
*
* @class
* @class Shipping_Rules_post_type
* @author Reinhold Kainhofer
* @package WooCommerce (Advanced) Shipping By Rules
* @version 1.0.0
......@@ -14,31 +14,6 @@ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
* Based in part on WAFS_post_type (WooCommerce Advanced Free Shipping plugin)
* (C) Jeroen Sormani, Licensed under the GPL V3+
*/
/*global $notices;
$notices = array();
function my_add_notice($message, $type) {
global $notices;
$notices[] = array('type'=>$type, 'message'=>$message);
}
function print_notices() {
global $notices;
?>
<div class="error"><pre><?php print_r($notices); ?></pre></div>
<?php
foreach ($notices as $msg) {
file_put_contents("/vagrant/httpdocs/test.log",$msg['message'], FILE_APPEND);
?>
<div class="updated">
<p><?php echo $msg["message"]; ?></p>
</div>
<?php
}
$notices = array();
}
add_action('admin_notices', 'print_notices');
*/
class Shipping_Rules_post_type {
......@@ -160,6 +135,15 @@ class Shipping_Rules_post_type {
return $messages;
}
public static function get_rulesets($post) {
$rulesets = get_post_meta( $post->ID, '_rules_shipping_ruleset', true );
if (!is_array($rulesets)) {
$rulesets = array();
}
return $rulesets;
}
/**
* Add meta boxes.
......@@ -191,10 +175,8 @@ class Shipping_Rules_post_type {
* @since 1.0.0
*/
public function render_shipping_rulesets($post, $metabox) {
$rulesets = $this->get_rulesets($post);
require_once plugin_dir_path( __FILE__ ) . 'admin/settings/meta-box-rulesets.php';
$rulesets = get_post_meta( $post->ID, '_rules_shipping_ruleset', true );
// file_put_contents("/vagrant/httpdocs/test.log","render_shipping_rulesets called, id=$post->ID, rulesets=".print_r($rulesets,1)."\n\n\n\n\n", FILE_APPEND);
render_meta_box_shipping_rules_rulesets ($post, $rulesets);
}
......@@ -241,9 +223,6 @@ class Shipping_Rules_post_type {
* @since 1.0.0
*/
public function shipping_rules_save_rulesets_meta( $post_id ) {
// my_add_notice( "shipping_rules_save_rulesets_meta called", 'info');
// file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_meta called, id=$post_id\n", FILE_APPEND);
if ( ! isset( $_POST['shipping_rules_rulesets_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['shipping_rules_rulesets_meta_box_nonce'], 'shipping_rules_rulesets_meta_box' ) ) :
return $post_id;
endif;
......@@ -256,19 +235,14 @@ class Shipping_Rules_post_type {
return $post_id;
endif;
// file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_meta, id=$post_id, checks passed\n", FILE_APPEND);
$shipping_method_rulesets = $_POST['_rules_shipping_ruleset'];
$shipping_method_ordering = $_POST['_rules_shipping_ordering'];
// file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_meta, id=$post_id, ordering: ".print_r($shipping_method_ordering,1)."\n\n\n\n", FILE_APPEND);
// file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_meta, id=$post_id, ruleset: ".print_r($shipping_method_rulesets,1)."\n\n\n\n", FILE_APPEND);
$rulesets = array();
foreach ($shipping_method_ordering as $o) {
$rulesets[] = $shipping_method_rulesets[$o];
}
file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_meta, id=$post_id, Sorted rulesets: ".print_r($shipping_method_rulesets,1)."\n\n\n\n", FILE_APPEND);
update_post_meta( $post_id, '_rules_shipping_ruleset', $rulesets );
}
......@@ -282,7 +256,6 @@ file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_met
* @since 1.0.0
*/
public function shipping_rules_save_meta( $post_id ) {
// my_add_notice( "shipping_rules_save_meta called", 'info');
if ( ! isset( $_POST['shipping_rules_settings_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['shipping_rules_settings_meta_box_nonce'], 'shipping_rules_settings_meta_box' ) ) :
return $post_id;
......@@ -312,20 +285,13 @@ file_put_contents("/vagrant/httpdocs/test.log","shipping_rules_save_rulesets_met
* @since 1.0.0
*/
public function shipping_rules_redirect_after_trash() {
$screen = get_current_screen();
if( 'edit-shipping_rules' == $screen->id ) :
if( isset( $_GET['trashed'] ) && intval( $_GET['trashed'] ) > 0 ) :
if ('edit-shipping_rules' == $screen->id ) {
if (isset( $_GET['trashed'] ) && intval( $_GET['trashed'] ) > 0 ) {
wp_redirect( admin_url( '/admin.php?page=wc-settings&tab=shipping&section=shipping_by_rules' ) );
exit();
endif;
endif;
}
}
}
......
......@@ -12,10 +12,11 @@ if ( !defined( 'ABSPATH' ) ) {
require_once( plugin_dir_path( __FILE__ ) . '/../library/rules_shipping_framework.php');
class RulesShippingFrameworkWooCommerce extends RulesShippingFramework {
protected static $_method_ordering = 'woocommerce_shipping_rules_ordering';
function _construct() {
parent::_construct();
load_plugin_textdomain('opentools-shippingrules', false, basename( dirname( __FILE__ ) ) . '/languages' );
}
static function getHelper() {
static $helper = null;
......@@ -79,45 +80,26 @@ class RulesShippingFrameworkWooCommerce extends RulesShippingFramework {
}
}
protected function setMethodCosts($method, $match, $costs) {
// Allow some system-specific code, e.g. setting some members of $method, etc.
$title = $method->title;
if ($match["rule_name"]) {
$title .= " (".$match["rule_name"].")";
}
$rate = array(
'id' => $method->id,
'label' => $title,
'cost' => $costs,
// 'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
protected function getCartProducts($package, $method) {
return $package['contents'];
}
protected function getMethodId($method) {
return $method->id;
return $method->ID;
}
protected function getMethodName($method) {
// Shall we use title or method_title?
return $method->title;
return $method->post_title;
}
protected function parseMethodRules (&$method) {
if (!isset($method->settings) || !isset($method->settings->rulesets)) {
return;
}
foreach ($method->settings->rulesets as $ruleset) {
$this->parseMethodRule($ruleset->rule,
$method->countries /* TODO: or use a custom setting of $ruleset? */,
array(),
$method);
$rulesets = Shipping_Rules_post_type::get_rulesets($method);
foreach ($rulesets as $ruleset) {
$this->parseMethodRule(
/* Rules */ isset($ruleset['rules'])?$ruleset['rules']:'',
/* Countries */isset($ruleset['countries'])?$ruleset['countries']:array(),
/* Rule info */array(),
/* Method */ $method);
}
}
......@@ -251,6 +233,8 @@ class RulesShippingFrameworkWooCommerce extends RulesShippingFramework {
$data['fax'] = isset($address['fax'])?$address['fax']:'';
$data['email'] = isset($address['email'])?$address['email']:'';
*/
// The country check needs the countryid variable, so duplicate from country:
$data['countryid'] = $data['country'];
return $data;
}
......@@ -302,4 +286,32 @@ class RulesShippingFrameworkWooCommerce extends RulesShippingFramework {
return $result;
}
/**
* get_shipping_rules_methods function.
*/
static public function get_rule_shipping_methods() {
$unsortedmethods = get_posts (array ('posts_per_page' => '-1', 'post_type' => 'shipping_rules'));
$ordering = get_option( self::$_method_ordering );
$methods = array();
foreach ($ordering as $o) {
foreach ($unsortedmethods as $key=>$m) {
if ($m->ID == $o) {
$methods[$o] = $m;
unset($unsortedmethods[$key]);
break;
}
}
}
$methods = $methods + $unsortedmethods;
return $methods;
}
static public function set_method_ordering($ordering) {
update_option( self::$_method_ordering, $ordering );
}
protected function createMethodRule ($r, $countries, $ruleinfo) {
return new ShippingRule_Advanced($this, $r, $countries, $ruleinfo);
}
}
......@@ -279,8 +279,6 @@ class RulesShippingFramework {
* defines shipping costs (or uses NoShipping). If a modifier or definition is encountered,
* its effect is stored, but the loop continues */
protected function evaluateMethodRules ($cart, $method) {
// print("<pre>Inside evaluateMethodRules: ".print_r($cart,1)."</pre>");
// $this->warning("<pre>Inside evaluateMethodRules: ".print_r($cart,1)."</pre>");
$id = $this->getMethodId($method);
// $this->match will cache the matched rule and the modifiers
if (isset($this->match[$id])) {
......@@ -288,7 +286,6 @@ class RulesShippingFramework {
} else {
// Evaluate all rules and find the matching ones (including modifiers and definitions!)
$cartvals = $this->getCartValues ($cart, $this->getCartProducts($cart, $method), $method);
$this->warning("<pre>Cart Values: ".print_r($cartvals,1)."</pre>");
$result = array(
"rule" => Null,
"rule_name" => "",
......@@ -303,7 +300,7 @@ $this->warning("<pre>Cart Values: ".print_r($cartvals,1)."</pre>");
};
if (isset($this->rules[$id])) {
foreach ($this->rules[$id] as $r) {
if ($r->matches($cartvals, $cart->products, $cartvals_callback)) {
if ($r->matches($cartvals, $this->getCartProducts($cart, $method), $cartvals_callback)) {
$rtype = $r->getType();
switch ($rtype) {
case 'shipping':
......@@ -336,6 +333,18 @@ $this->warning("<pre>Cart Values: ".print_r($cartvals,1)."</pre>");
return NULL;
}
protected function handleNoShipping($match, $method) {
if ($match['rule']->isNoShipping()) {
if (!empty($match["rule_name"]))
$this->warning('OTSHIPMENT_RULES_NOSHIPPING_MESSAGE', $match["rule_name"]);
$name = $this->getMethodName($method);
$this->debug('checkConditions '.$name.' indicates NoShipping for this method, specified by rule "'.$match["rule_name"].'" ('.$match['rule']->rulestring.').');
return true;
} else {
return false;
}
}
/**
* @param $cart
* @param int $method
......@@ -346,19 +355,16 @@ $this->warning("<pre>Cart Values: ".print_r($cartvals,1)."</pre>");
$name = $this->getMethodName($method);
if (!isset($this->rules[$id]))
$this->parseMethodRules($method);
// TODO: This needs to be redone sooner or later!
$match = $this->evaluateMethodRules ($cart, $method);
if ($match && !is_null ($match['rule'])) {
$this->setMethodCosts($method, $match, null);
// If NoShipping is set, this method should NOT offer any shipping at all, so return FALSE, otherwise TRUE
// If the rule has a name, print it as warning (otherwise don't print anything)
if ($match['rule']->isNoShipping()) {
if (!empty($match["rule_name"]))
$this->warning('OTSHIPMENT_RULES_NOSHIPPING_MESSAGE', $match["rule_name"]);
$this->debug('checkConditions '.$name.' indicates NoShipping for this method, specified by rule "'.$match["rule_name"].'" ('.$match['rule']->rulestring.').');
if ($this->handleNoShipping($match, $method)) {
return FALSE;
} else {
return TRUE;
}
return TRUE;
}
$this->debug('checkConditions '.$name.' does not fulfill all conditions, no rule matches');
return FALSE;
......@@ -377,12 +383,16 @@ $this->warning("<pre>Cart Values: ".print_r($cartvals,1)."</pre>");
* @return int
*/
function getCosts ($cart, $method) {
// TODO: Return an array with the method/rule name etc.
$results = array();
$id = $this->getMethodId($method);
if (!isset($this->rules[$id]))
$this->parseMethodRules($method);
$match = $this->evaluateMethodRules ($cart, $method);
if ($match) {
if ($this->handleNoShipping($match, $method)) {
return $results;
}
$r = $match["rule"];
$this->debug('Rule ' . $match["rule_name"] . ' ('.$r->rulestring.') matched.');
......@@ -398,11 +408,20 @@ $this->warning("<pre>Cart Values: ".print_r($cartvals,1)."</pre>");
}
$this->setMethodCosts($method, $match, $cost);
return $cost;
$res = array(
'method' => $id,
'name' => $this->getMethodName($method),
// 'rulesetname'=>$match['ruleset_name'],
'rulename' => $match["rule_name"],
'cost' => $cost,
);
$results[] = $res;
}
$this->debug('getCosts '.$this->getMethodName($method).' does not return shipping costs');
return 0;
if (empty($results)) {
$this->debug('getCosts '.$this->getMethodName($method).' does not return shipping costs');
}
return $results;
}
public function getRuleName($methodid) {
......@@ -539,7 +558,6 @@ class ShippingRule {
// Split at all operators:
$atoms = $this->tokenize_expression ($rulepart);
/* Starting from here, the advanced plugin is different! */
$operators = array('<', '<=', '=', '>', '>=', '=>', '=<', '<>', '!=', '==');
if (count($atoms)==1) {
......
......@@ -95,13 +95,10 @@ class WooCommerce_Shipping_By_Rules {
* @return object Instance of the class.
*/
public static function instance() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
......@@ -113,19 +110,11 @@ class WooCommerce_Shipping_By_Rules {
* @since 1.0.0
*/
public function init() {
// Add hooks/filters
$this->hooks();
// Load textdomain
$this->load_textdomain();
// Updater
$this->update();
/**
* Require file with shipping_by_rules post type definition.
*/
// Shipping method post type definition:
require_once plugin_dir_path( __FILE__ ) . 'includes/rules-shipping-post-type.php';
$this->post_type = new Shipping_Rules_post_type();
......@@ -202,7 +191,7 @@ class WooCommerce_Shipping_By_Rules {
*/
public function shipping_by_rules_init() {
require_once plugin_dir_path( __FILE__ ) . 'includes/rules-shipping-method.php';
$this->was_method = new WC_Shipping_by_Rules();
$this->rule_shipping_method = new Shipping_by_Rules();
}
......@@ -215,8 +204,8 @@ class WooCommerce_Shipping_By_Rules {
* @since 1.0.0
*/
public function shipping_by_rules_add_shipping_method( $methods ) {
if ( class_exists( 'WC_Shipping_by_Rules' ) ) :
$methods[] = 'WC_Shipping_by_Rules';
if ( class_exists( 'Shipping_by_Rules' ) ) :
$methods[] = 'Shipping_by_Rules';
endif;
// TODO: Figure out a way to add each shipping by rules method as a
// separate WooCommerce shipping method (ie. their order can be
......@@ -237,7 +226,6 @@ class WooCommerce_Shipping_By_Rules {
// For some strange reason, WC does not define the select2.css style...
$assets_path = str_replace( array( 'http:', 'https:' ), '', WC()->plugin_url() ) . '/assets/';
wp_enqueue_style( 'select2', $assets_path . 'css/select2.css' );
// wp_enqueue_style( 'chosen', $assets_path . 'css/chosen.css' );
wp_enqueue_style( 'shipping_by_rules-style', plugins_url( 'assets/css/admin-styles.css', __FILE__ ), array('select2'), $this->version );
wp_enqueue_script( 'shipping-by-rules-config', plugins_url( 'assets/js/shipping-by-rules-config.js', __FILE__ ), array( 'jquery', 'jquery-ui-sortable', 'select2', 'wc-enhanced-select' ), $this->version, true );
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment