rules_shipping_framework_joomla.php 16.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
/**
 * Shipping by Rules generic helper class (Joomla/VM-specific)
 * Reinhold Kainhofer, Open Tools, office@open-tools.net
 * @copyright (C) 2012-2015 - Reinhold Kainhofer
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/

// defined('_JEXEC') or	 die( 'Direct Access to ' . basename( __FILE__ ) . ' is not allowed.' ) ;

// if (!class_exists( 'VmConfig' )) 
//     require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'config.php');
// VmConfig::loadConfig();

if (!class_exists( 'RulesShippingFramework' )) 
	require_once (dirname(__FILE__) . DS . 'library' . DS . 'rules_shipping_framework.php');

// $test=new asdfasdsf();
class RulesShippingFrameworkJoomla extends RulesShippingFramework {
20
	/* Constructor: Register the available scopings */
21
22
	function __construct() {
		parent::__construct();
23
24
		$this->registerScopings(array(
			"categories"    => 'categories',
25
			"subcategories" => 'subcategories',
26
27
28
29
30
31
			"products"      => 'products',
			"skus"          => 'products',
			"vendors"       => 'vendors',
			"manufacturers" => 'manufacturers',
		));
	}
32
33
34
35
36
37
38
39
40
41
	function getCustomFunctions() {
		// Let other plugins add custom functions! 
		// The onVmShippingRulesRegisterCustomFunctions() trigger is expected to return an array of the form:
		//   array ('functionname1' => 'function-to-be-called',
		//          'functionname2' => array($classobject, 'memberfunc')),
		//          ...);
		JPluginHelper::importPlugin('vmshipmentrules');
		$dispatcher = JDispatcher::getInstance();
		$custfuncdefs = $dispatcher->trigger('onVmShippingRulesRegisterCustomFunctions',array());
		
Reinhold Kainhofer's avatar
Reinhold Kainhofer committed
42
		return $custfuncdefs;
43
44
	}
	
45
	protected function printWarning($message) {
46
47
48
49
50
51
52
53
54
		// Keep track of warning messages, so we don't print them twice:
		global $printed_warnings;
		if (!isset($printed_warnings))
			$printed_warnings = array();
		if (!in_array($message, $printed_warnings)) {
			JFactory::getApplication()->enqueueMessage($message, 'error');
			$printed_warnings[] = $message;
		}
	}
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
	/** @tag public-api
	 *  @function debug()
	 *    Print a debug message (untranslated) in the system-specific way.
	 *  @param $message the debug message to be printed 
	 */
	public function debug($message) {
		vmDebug($message);
	}

	public function __($string) {
		$args = func_get_args();
		if (count($args)>1) {
			return call_user_func_array(array("JText", "sprintf"), $args);
		} else {
			return call_user_func(array("JText", "_"), $string);
		}
	}

	protected function setMethodCosts($method, $match, $costs) {
		$r = $match["rule"];
		// Allow some system-specific code, e.g. setting some members of $method, etc.
		$method->tax_id = $r->ruleinfo['tax_id'];
		// TODO: Shall we include the name of the modifiers, too?
		$method->rule_name = $match["rule_name"];
		$method->cost = $costs;
		$method->includes_tax = $r->includes_tax;
	}
	
83
84
85
86
	protected function getCartProducts($cart, $method) {
		return $cart->products;
	}
	
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
	protected function getMethodId($method) {
		return $method->virtuemart_shipmentmethod_id;
	}

	protected function getMethodName($method) {
		return $method->shipment_name;
	}

	protected function parseMethodRules (&$method) {
		$this->parseMethodRule ($method->rules1, $method->countries1, array('tax_id'=>$method->tax_id1), $method);
		$this->parseMethodRule ($method->rules2, $method->countries2, array('tax_id'=>$method->tax_id2), $method);
		$this->parseMethodRule ($method->rules3, $method->countries3, array('tax_id'=>$method->tax_id3), $method);
		$this->parseMethodRule ($method->rules4, $method->countries4, array('tax_id'=>$method->tax_id4), $method);
		$this->parseMethodRule ($method->rules5, $method->countries5, array('tax_id'=>$method->tax_id5), $method);
		$this->parseMethodRule ($method->rules6, $method->countries6, array('tax_id'=>$method->tax_id6), $method);
		$this->parseMethodRule ($method->rules7, $method->countries7, array('tax_id'=>$method->tax_id7), $method);
		$this->parseMethodRule ($method->rules8, $method->countries8, array('tax_id'=>$method->tax_id8), $method);
	}
105
106
107
108
109
110
111
112

	/**
	 * Functions to calculate the cart variables:
	 *   - getOrderArticles($cart, $products)
	 *   - getOrderProducts
	 *   - getOrderDimensions
	 */
	/** Functions to calculate all the different variables for the given cart and given (sub)set of products in the cart */
113
	protected function getOrderCounts ($cart, $products, $method) {
114
115
116
		$counts = array(
			'articles' => 0,
			'products' => count($products),
117
			'quantity' => 0,
118
119
120
			'minquantity' => 9999999999,
			'maxquantity' => 0,
		);
121

122
		foreach ($products as $product) {
123
124
125
			$counts['articles']   += $product->quantity;
			$counts['maxquantity'] = max ($counts['maxquantity'], $product->quantity);
			$counts['minquantity'] = min ($counts['minquantity'], $product->quantity);
126
		}
127
128
		$counts['quantity'] = $counts['articles'];
		
129
		return $counts;
130
131
	}

132
	protected function getOrderDimensions ($cart, $products, $method) {
133
134
135
136
137
138
139
140
141
		/* Cache the value in a static variable and calculate it only once! */
		$dimensions=array(
			'volume' => 0,
			'maxvolume' => 0, 'minvolume' => 9999999999,
			'maxlength' => 0, 'minlength' => 9999999999, 'totallength' => 0,
			'maxwidth'  => 0, 'minwidth' => 9999999999,  'totalwidth'  => 0,
			'maxheight' => 0, 'minheight' => 9999999999, 'totalheight' => 0,
			'maxpackaging' => 0, 'minpackaging' => 9999999999, 'totalpackaging' => 0,
		);
142
		$length_dimension = $method->length_unit;
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
		foreach ($products as $product) {
	
			$l = ShopFunctions::convertDimensionUnit ($product->product_length, $product->product_lwh_uom, $length_dimension);
			$w = ShopFunctions::convertDimensionUnit ($product->product_width, $product->product_lwh_uom, $length_dimension);
			$h = ShopFunctions::convertDimensionUnit ($product->product_height, $product->product_lwh_uom, $length_dimension);

			$volume = $l * $w * $h;
			$dimensions['volume'] += $volume * $product->quantity;
			$dimensions['maxvolume'] = max ($dimensions['maxvolume'], $volume);
			$dimensions['minvolume'] = min ($dimensions['minvolume'], $volume);
				
			$dimensions['totallength'] += $l * $product->quantity;
			$dimensions['maxlength'] = max ($dimensions['maxlength'], $l);
			$dimensions['minlength'] = min ($dimensions['minlength'], $l);
			$dimensions['totalwidth'] += $w * $product->quantity;
			$dimensions['maxwidth'] = max ($dimensions['maxwidth'], $w);
			$dimensions['minwidth'] = min ($dimensions['minwidth'], $w);
			$dimensions['totalheight'] += $h * $product->quantity;
			$dimensions['maxheight'] = max ($dimensions['maxheight'], $h);
			$dimensions['minheight'] = min ($dimensions['minheight'], $h);
			$dimensions['totalpackaging'] += $product->product_packaging * $product->quantity;
			$dimensions['maxpackaging'] = max ($dimensions['maxpackaging'], $product->product_packaging);
			$dimensions['minpackaging'] = min ($dimensions['minpackaging'], $product->product_packaging);
		}

		return $dimensions;
	}
	
171
172
	protected function getOrderWeights ($cart, $products, $method) {
		$weight_unit = $method->weight_unit;
173
174
175
176
177
178
179
180
181
182
183
184
185
		$dimensions=array(
			'weight' => 0,
			'maxweight' => 0, 'minweight' => 9999999999,
		);
		foreach ($products as $product) {
			$w = ShopFunctions::convertWeigthUnit ($product->product_weight, $product->product_weight_uom, $weight_unit);
			$dimensions['maxweight'] = max ($dimensions['maxweight'], $w);
			$dimensions['minweight'] = min ($dimensions['minweight'], $w);
			$dimensions['weight'] += $w * $product->quantity;
		}
		return $dimensions;
	}
	
186
	protected function getOrderListProperties ($cart, $products, $method) {
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
		$categories = array();
		$vendors = array();
		$skus = array();
		$manufacturers = array();
		foreach ($products as $product) {
			$skus[] = $product->product_sku;
			$categories = array_merge ($categories, $product->categories);
			$vendors[] = $product->virtuemart_vendor_id;
			if (is_array($product->virtuemart_manufacturer_id)) {
				$manufacturers = array_merge($manufacturers, $product->virtuemart_manufacturer_id);
			} elseif ($product->virtuemart_manufacturer_id) {
				$manufacturers[] = $product->virtuemart_manufacturer_id;
			}
		}
		$skus = array_unique($skus);
		$vendors = array_unique($vendors);
		$categories = array_unique($categories);
		$manufacturers = array_unique($manufacturers);
		return array ('skus'=>$skus, 
			      'categories'=>$categories,
			      'vendors'=>$vendors,
			      'manufacturers'=>$manufacturers,
		);
	}
	
212
	protected function getOrderAddress ($cart, $method) {
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
		$address = (($cart->ST == 0 || $cart->STsameAsBT == 1) ? $cart->BT : $cart->ST);
		$zip = isset($address['zip'])?trim($address['zip']):'';
		$data = array('zip'=>$zip,
			'zip1'=>substr($zip,0,1),
			'zip2'=>substr($zip,0,2),
			'zip3'=>substr($zip,0,3),
			'zip4'=>substr($zip,0,4),
			'zip5'=>substr($zip,0,5),
			'zip6'=>substr($zip,0,6),
			'city'=>isset($address['city'])?trim($address['city']):'',
			'countryid' => 0, 'country' => '', 'country2' => '', 'country3' => '',
			'stateid'   => 0, 'state'   => '', 'state2'   => '', 'state3'   => '',
		);
		$data['company'] = isset($address['company'])?$address['company']:'';
		$data['title'] = isset($address['title'])?$address['title']:'';
		$data['first_name'] = isset($address['title'])?$address['title']:'';
		$data['middle_name'] = isset($address['middle_name'])?$address['middle_name']:'';
		$data['last_name'] = isset($address['last_name'])?$address['last_name']:'';
		$data['address1'] = isset($address['address_1'])?$address['address_1']:'';
		$data['address2'] = isset($address['address_2'])?$address['address_2']:'';
		$data['city'] = isset($address['city'])?$address['city']:'';
		$data['phone1'] = isset($address['phone_1'])?$address['phone_1']:'';
		$data['phone2'] = isset($address['phone_2'])?$address['phone_2']:'';
		$data['fax'] = isset($address['fax'])?$address['fax']:'';
		$data['email'] = isset($address['email'])?$address['email']:'';
		
		// Country and State variables:
		$countriesModel = VmModel::getModel('country');
		if (isset($address['virtuemart_country_id'])) {
			$data['countryid'] = $address['virtuemart_country_id'];
			// The following is a workaround to make sure the cache is invalidated
			// because if some other extension meanwhile called $countriesModel->getCountries,
			// the cache will be modified, but the model's id will not be changes, so the
			// getData call will return the wrong cache.
			$countriesModel->setId(0); 
			$countriesModel->setId($address['virtuemart_country_id']);
			$country = $countriesModel->getData($address['virtuemart_country_id']);
			if (!empty($country)) {
				$data['country'] = $country->country_name;
				$data['country2'] = $country->country_2_code;
				$data['country3'] = $country->country_3_code;
			}
		}
		
		$statesModel = VmModel::getModel('state');
		if (isset($address['virtuemart_state_id'])) {
			$data['stateid'] = $address['virtuemart_state_id'];
			// The following is a workaround to make sure the cache is invalidated
			// because if some other extension meanwhile called $countriesModel->getCountries,
			// the cache will be modified, but the model's id will not be changes, so the
			// getData call will return the wrong cache.
			$statesModel->setId(0); 
			$statesModel->setId($address['virtuemart_state_id']);
			$state = $statesModel->getData($address['virtuemart_state_id']);
			if (!empty($state)) {
				$data['state'] = $state->state_name;
				$data['state2'] = $state->state_2_code;
				$data['state3'] = $state->state_3_code;
			}
		}
		
		return $data;
	}
	
277
	protected function getOrderPrices ($cart, $products, /*$cart_prices, */$method) {
278
279
280
281
282
283
284
285
286
287
288
289
290
		$data = array(
			'amount' => 0, 
			'amountwithtax' => 0, 
			'amountwithouttax' => 0, 
			'baseprice' => 0, 
			'basepricewithtax' => 0, 
			'discountedpricewithouttax' => 0, 
			'salesprice' => 0, 
			'taxamount' => 0, 
			'salespricewithdiscount' => 0, 
			'discountamount' => 0, 
			'pricewithouttax' => 0,
		);
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// 		if (!empty($cart_prices)) {
// 			// get prices for the whole cart -> simply user the cart_prices
// 			$data['amount']                 = $cart_prices['salesPrice'];
// 			$data['amountwithtax']          = $cart_prices['salesPrice'];
// 			$data['amountwithouttax']       = $cart_prices['priceWithoutTax'];
// 			$data['baseprice']              = $cart_prices['basePrice'];
// 			$data['basepricewithtax']       = $cart_prices['basePriceWithTax'];
// 			$data['discountedpricewithouttax'] = $cart_prices['discountedPriceWithoutTax'];
// 			$data['salesprice']             = $cart_prices['salesPrice'];
// 			$data['taxamount']              = $cart_prices['taxAmount'];
// 			$data['salespricewithdiscount'] = $cart_prices['salesPriceWithDiscount'];
// 			$data['discountamount']         = $cart_prices['discountAmount'];
// 			$data['pricewithouttax']        = $cart_prices['priceWithoutTax'];
// 		} else {
305
306
307
			// Calculate the prices from the individual products!
			// Possible problems are discounts on the order total
			foreach ($products as $product) {
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// 				$prices = isset($product->allPrices)?($product->allPrices[$product->selectedPrice]):($product->prices);
				$prices = $product->prices;
				$quant = $product->quantity;
				$data['amount']                    += $quant * $prices['salesPrice'];
				$data['amountwithtax']             += $quant * $prices['salesPrice'];
				$data['amountwithouttax']          += $quant * $prices['priceWithoutTax'];
				$data['baseprice']                 += $quant * $prices['basePrice'];
				$data['basepricewithtax']          += $quant * $prices['basePriceWithTax'];
				$data['discountedpricewithouttax'] += $quant * $prices['discountedPriceWithoutTax'];
				$data['salesprice']                += $quant * $prices['salesPrice'];
				$data['taxamount']                 += $quant * $prices['taxAmount'];
				$data['salespricewithdiscount']    += $quant * $prices['salesPriceWithDiscount'];
				$data['discountamount']            += $quant * $prices['discountAmount'];
				$data['pricewithouttax']           += $quant * $prices['priceWithoutTax'];
// JFactory::getApplication()->enqueueMessage("<pre>prices: ".print_r($prices,1)."</pre>", 'error');
// JFactory::getApplication()->enqueueMessage("<pre>product: ".print_r($product,1)."</pre>", 'error');
				
325
			}
326
// 		}
327
328
329
330
331
		return $data;
	}

	/** Allow child classes to add additional variables for the rules or modify existing one
	 */
332
	protected function addCustomCartValues ($cart, $products, $method, &$values) {
333
	}
334
	protected function addPluginCartValues($cart, $products, $method, &$values) {
335
336
		// Finally, call the triger of vmshipmentrules plugins to let them add/modify variables
		JPluginHelper::importPlugin('vmshipmentrules');
337
		JDispatcher::getInstance()->trigger('onVmShippingRulesGetCartValues',array(&$values, $cart, $products, $method));
338
339
340
341
	}

	/** Filter the given array of products and return only those that belong to the categories, manufacturers, 
	*  vendors or products given in the $filter_conditions. The $filter_conditions is an array of the form:
342
	*     array( 'products'=>array(....), 'categories'=>array(1,2,3,42), 'manufacturers'=>array(77,78,83), 'vendors'=>array(1,2))
343
344
345
346
347
	*  Notice that giving an empty array for any of the keys means "no restriction" and is exactly the same 
	*  as leaving out the entry altogether
	*/
	public function filterProducts($products, $filter_conditions) {
		$result = array();
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
		
		// For the subcategories scoping we need all subcategories of the conditions:
		$subcategories = array();
		if (isset($filter_conditions['subcategories']) && !empty($filter_conditions['subcategories'])) {
			$catmodel = VmModel::getModel('category');
			foreach ($filter_conditions['subcategories'] as $catid) {
				$subcategories[] = $catid;
				// Get all child categories from the category model
				$categories = $catmodel->getCategoryTree($catid,0,/*onlyPublished=*/false);
				foreach ($categories as $subcat) {
					$subcategories[] = $subcat->virtuemart_category_id;
				}
			}
			$subcategories = array_unique($subcategories);
JFactory::getApplication()->enqueueMessage("<pre>Subcategories: ".print_r($subcategories,1)."</pre>", 'error');
			
		}
		

367
		foreach ($products as $p) {
368
			if (!empty($filter_conditions['products']) && !in_array($p->product_sku, $filter_conditions['products']))
369
370
371
				continue;
			if (!empty($filter_conditions['categories']) && count(array_intersect($filter_conditions['categories'], $p->categories))==0)
				continue;
372
373
			if (!empty($filter_conditions['subcategories']) && count(array_intersect($subcategories, $p->categories))==0)
				continue;
374
375
376
377
378
379
380
381
382
383
			if (!empty($filter_conditions['manufacturers']) && count(array_intersect($filter_conditions['manufacturers'], $p->virtuemart_manufacturer_id))==0)
				continue;
			if (!empty($filter_conditions['vendors']) && !in_array($p->virtuemart_vendor_id, $filter_conditions['vendors']))
				continue;
			$result[] = $p;
		}
		return $result;
	}
	
}