PluginProbe
MyRewards / trunk
MyRewards vtrunk
5.7.8 5.7.7 5.7.6 trunk 1.2.2 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.0.7 2.1.1 2.2.0 2.3.0 2.4.0 2.4.1 2.5.0 2.6.4 2.6.6 3.0.0.0 3.1.0 3.1.2 3.1.2.1 3.10.4 3.10.9 All 165 releases
woorewards / include / events / orderamount.php

orderamount.php in MyRewards trunk, at include/events/orderamount.php

364 lines 11.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace LWS\WOOREWARDS\Events;
3
4 // don't call the file directly
5 if( !defined( 'ABSPATH' ) ) exit();
6
7 /** Earn points for each money spend on an order. */
8 class OrderAmount extends \LWS\WOOREWARDS\Abstracts\Event
9 {
10 use \LWS\WOOREWARDS\Events\T_SponsorshipOrigin;
11
12 protected $eventPriority = 99;
13 protected $afterDiscount = false;
14 protected $includeShipping = false;
15 protected $includeFees = false;
16 protected $thresholdEffect = true;
17 protected $denominator = 1.00;
18
19 function getInformation()
20 {
21 return array_merge(parent::getInformation(), array(
22 'icon' => 'lws-icon-coins',
23 'short' => __("The customer will receive points depending on the amount spent on the order", 'woorewards-lite'),
24 'help' => __("Most used method on MyRewards. Lots of options", 'woorewards-lite'),
25 ));
26 }
27
28 function getData()
29 {
30 $prefix = $this->getDataKeyPrefix();
31 $data = parent::getData();
32 $data[$prefix . 'after_discount'] = $this->getAfterDiscount() ? 'on' : '';
33 $data[$prefix.'denominator'] = $this->getDenominator();
34 $data[$prefix.'include_shipping'] = $this->getShipping() ? 'on' : '';
35 $data[$prefix.'include_fees'] = $this->getFees() ? 'on' : '';
36 $data[$prefix.'event_priority'] = $this->getEventPriority();
37 $data = $this->filterSponsorshipData($data, $prefix);
38 return $data;
39 }
40
41 function getForm($context='editlist')
42 {
43 $prefix = $this->getDataKeyPrefix();
44 $form = parent::getForm($context);
45
46 $label = _x("Money spent", "Order Amount Event money diviser", 'woorewards-lite');
47 $value = \esc_attr($this->getDenominator());
48 $str = "<div class='lws-$context-opt-title label pts-earning'>$label</div>"
49 . "<div class='lws-$context-opt-input value pts-earning'>"
50 . "<input type='text' id='{$prefix}denominator' name='{$prefix}denominator' value='$value' placeholder='1' pattern='\\d*' size='5' />"
51 . "</div>";
52 $pht1 = $this->getFieldsetPlaceholder(true, 1);
53 $form = str_replace($pht1, $pht1.$str, $form);
54
55 // just hidden since we do not want to reset the value on save
56 $noPri = (\get_option('lws_woorewards_show_loading_order_and_priority') ? '' : ' style="display: none;"');
57 $label = __("Priority", 'woorewards-lite');
58 $tooltip = __("Customer orders will run by ascending priority value.", 'woorewards-lite');
59 $str = "<div class='field-help'{$noPri}>$tooltip</div>"
60 . "<div class='lws-$context-opt-title label'{$noPri}>$label<div class='bt-field-help'>?</div></div>"
61 . "<div class='lws-$context-opt-input value'{$noPri}>"
62 . "<input type='text' id='{$prefix}event_priority' name='{$prefix}event_priority' placeholder='10' size='5' />"
63 . "</div>";
64
65 $phb0 = $this->getFieldsetPlaceholder(false, 0);
66 $form = str_replace($phb0, $str.$phb0, $form);
67
68 $form .= $this->getFieldsetBegin(2, __("Options", 'woorewards-lite'));
69
70 // compute points after discount
71 $label = _x("Use amount after discount", "Order Amount Event", 'woorewards-lite');
72 $form .= "<div class='lws-$context-opt-title label'>$label</div>";
73 $toggle = \LWS\Adminpanel\Pages\Field\Checkbox::compose($prefix . 'after_discount', array(
74 'id' => $prefix . 'after_discount',
75 'layout' => 'toggle',
76 ));
77 $form .= "<div class='lws-$context-opt-input value'>{$toggle}</div>";
78
79 $form .= $this->getFieldsetEnd(2);
80
81 return $this->filterSponsorshipForm($form, $prefix, $context, 10);
82 }
83
84 function submit($form=array(), $source='editlist')
85 {
86 $prefix = $this->getDataKeyPrefix();
87 $values = \apply_filters('lws_adminpanel_arg_parse', array(
88 'post' => ($source == 'post'),
89 'values' => $form,
90 'format' => array(
91 $prefix . 'after_discount' => 's',
92 $prefix . 'denominator' => 'F',
93 $prefix . 'include_shipping' => 's',
94 $prefix . 'include_fees' => 's',
95 $prefix . 'event_priority' => 'd',
96 ),
97 'defaults' => array(
98 $prefix . 'after_discount' => '',
99 $prefix . 'denominator' => '1',
100 $prefix . 'include_shipping' => '',
101 $prefix . 'include_fees' => '',
102 $prefix . 'event_priority' => $this->getEventPriority(),
103 ),
104 'labels' => array(
105 $prefix . 'after_discount' => __("After Discount", 'woorewards-lite'),
106 $prefix . 'event_priority' => __("Event Priority", 'woorewards-lite'),
107 )
108 ));
109 if( !(isset($values['valid']) && $values['valid']) )
110 return isset($values['error']) ? $values['error'] : false;
111
112 $valid = parent::submit($form, $source);
113 if ($valid === true)
114 $valid = $this->optSponsorshipSubmit($prefix, $form, $source);
115 if( $valid === true )
116 {
117 $this->setDenominator ($values['values'][$prefix.'denominator']);
118 $this->setShipping (boolval($values['values'][$prefix.'include_shipping']));
119 $this->setFees (boolval($values['values'][$prefix.'include_fees']));
120 $this->setEventPriority ($values['values'][$prefix.'event_priority']);
121 $this->setAfterDiscount (boolval($values['values'][$prefix . 'after_discount']));
122 }
123 return $valid;
124 }
125
126 /** Compute points on final order amount,
127 * after fees and discounts applied.
128 * @return bool */
129 public function getAfterDiscount()
130 {
131 return $this->afterDiscount;
132 }
133
134 public function setAfterDiscount($yes = true)
135 {
136 $this->afterDiscount = $yes;
137 return $this;
138 }
139
140 /** @return bool */
141 public function getShipping()
142 {
143 return $this->includeShipping;
144 }
145
146 public function setShipping($yes=true)
147 {
148 $this->includeShipping = $yes;
149 return $this;
150 }
151
152 /** @return bool */
153 public function getFees()
154 {
155 return $this->includeFees;
156 }
157
158 public function setFees($yes=true)
159 {
160 $this->includeFees = $yes;
161 return $this;
162 }
163
164 /** @return bool */
165 public function getThresholdEffect()
166 {
167 return $this->thresholdEffect;
168 }
169
170 /** Points computed proportionaly or for each complet amount of money.
171 * Does we apply ceil. */
172 public function setThresholdEffect($yes=true)
173 {
174 $this->thresholdEffect = $yes;
175 return $this;
176 }
177
178 /** @return int */
179 public function getDenominator()
180 {
181 return $this->denominator;
182 }
183
184 /** amount is divided by denominator before point earning. */
185 public function setDenominator($value=1.00)
186 {
187 $this->denominator = max($value, 0);
188 return $this;
189 }
190
191 public function getDisplayType()
192 {
193 return _x("Spend money", "getDisplayType", 'woorewards-lite');
194 }
195
196 protected function _fromPost(\WP_Post $post)
197 {
198 $this->setAfterDiscount(boolval(\get_post_meta($post->ID, 'wre_event_after_discount', true)));
199 $this->setShipping (boolval(\get_post_meta($post->ID, 'wre_event_include_shipping', true)));
200 $this->setFees (boolval(\get_post_meta($post->ID, 'wre_event_include_fees', true)));
201 $this->setThresholdEffect(boolval(\get_post_meta($post->ID, 'wre_event_threshold_effect', true)));
202 $this->setDenominator (floatval(\get_post_meta($post->ID, 'wre_event_denominator', true)));
203 $this->setEventPriority($this->getSinglePostMeta($post->ID, 'wre_event_priority', $this->getEventPriority()));
204 $this->optSponsorshipFromPost($post);
205 return $this;
206 }
207
208 protected function _save($id)
209 {
210 \update_post_meta($id, 'wre_event_after_discount', $this->getAfterDiscount());
211 \update_post_meta($id, 'wre_event_include_shipping', $this->getShipping());
212 \update_post_meta($id, 'wre_event_include_fees', $this->getFees());
213 \update_post_meta($id, 'wre_event_threshold_effect', $this->getThresholdEffect()?'on':'');
214 \update_post_meta($id, 'wre_event_denominator', $this->getDenominator());
215 \update_post_meta($id, 'wre_event_priority', $this->getEventPriority());
216 $this->optSponsorshipSave($id);
217 return $this;
218 }
219
220 function getEventPriority()
221 {
222 return \intval($this->eventPriority);
223 }
224
225 public function setEventPriority($priority)
226 {
227 $this->eventPriority = \intval($priority);
228 return $this;
229 }
230
231 protected function _install()
232 {
233 \add_filter('lws_woorewards_wc_order_done_'.$this->getPoolName(), array($this, 'orderDone'), $this->getEventPriority()); // priority later to let other use some order lines
234 }
235
236 function orderDone($order)
237 {
238 if (!($userId = $this->getPointsRecipient($order->order)))
239 return $order;
240 if (!$this->isValidOriginByOrder($order->order, $this->isGuestAllowed()))
241 return $order;
242
243 $amount = $this->getOrderAmount($order);
244 $points = $this->getPointsForAmount($amount);
245
246 if ($points > 0)
247 {
248 if ($points = \apply_filters('trigger_' . $this->getType(), $points, $this, $order->order))
249 {
250 $this->addPoint($this->getGainInfo(array(
251 'user' => $userId,
252 'order' => $order->order,
253 ), $order), $this->getPointsReason($order->order, $amount), $points);
254 }
255 }
256 return $order;
257 }
258
259 /** @param $order (\WC_Order)
260 * @return (int) user ID */
261 function getPointsRecipient($order)
262 {
263 return \LWS\Adminpanel\Tools\Conveniences::getCustomerId(false, $order);
264 }
265
266 /** @param $info (array) */
267 protected function getGainInfo($info, $order)
268 {
269 return $info;
270 }
271
272 /** @param $order (\WC_Order)
273 * @param $amount (float) computed amount
274 * @return (\LWS\WOOREWARDS\Core\Trace) a reason for history */
275 function getPointsReason($order, $amount)
276 {
277 $price = \wp_kses(\wc_price($amount, array('currency' => $order->get_currency())), array());
278 return \LWS\WOOREWARDS\Core\Trace::byOrder($order)
279 ->setProvider($order->get_customer_id('edit'))
280 ->setReason(array('Spent %1$s from order #%2$s', $price, $order->get_order_number()), 'woorewards-lite');
281 }
282
283 /** Never call, only to have poedit/wpml able to extract the sentance. */
284 private function poeditDeclare()
285 {
286 /* translators: %1$s: amount spent, %2$s: order number */
287 __('Spent %1$s from order #%2$s', 'woorewards-lite');
288 }
289
290 function roundPrice($price)
291 {
292 return \wc_format_decimal(\floatval($price), \wc_get_price_decimals());
293 }
294
295 function getPointsForAmount($amount)
296 {
297 $points = 0;
298 if( $amount > 0 )
299 {
300 $points = $amount / floatval($this->getDenominator());
301 if ($this->getThresholdEffect()) $points = \floor($points);
302 }
303 return $points;
304 }
305
306 function getOrderAmount(&$order, $round=true)
307 {
308 $amount = $order->amount; // subtotal (with or without tax - option) before discount
309
310 if ($this->getAfterDiscount()) {
311 $amount -= $order->order->get_discount_total();
312 if ($order->inc_tax)
313 $amount -= $order->order->get_discount_tax();
314 }
315
316 if ($this->getShipping())
317 {
318 $amount += floatval($order->order->get_shipping_total('edit'));
319 if( $order->inc_tax )
320 $amount += floatval($order->order->get_shipping_tax('edit'));
321 }
322
323 if ($this->getFees())
324 {
325 $amount += floatval($order->order->get_total_fees());
326 }
327
328 $amount = max(0, $amount);
329 return $round ? $this->roundPrice($amount) : $amount;
330 }
331
332 protected function shapeGain($value)
333 {
334 $amount = $this->getDenominator();
335 $amount = \LWS\Adminpanel\Tools\Conveniences::isWC() ? \wc_price($amount) : \number_format_i18n($amount, 2);
336 if ('=' == substr($value, 0, 1)) {
337 /* translators: %1$s: expression formula, %2$s: money amount */
338 $value = sprintf(_x('[%1$s] / %2$s', "Point per money spent", 'woorewards-lite'), $value, $amount);
339 } elseif (\is_numeric($value) && $value > 0) {
340 $points = \LWS_WooRewards::formatPointsWithSymbol($value, $this->getPoolName());
341 /* translators: %1$s: points value, %2$s: money amount */
342 $value = sprintf(_x('%1$s / %2$s', "Point per money spent", 'woorewards-lite'), $points, $amount);
343 } else {
344 $value = \str_replace('[spent]', $amount, $value);
345 }
346 return parent::shapeGain($value);
347 }
348
349 /** Event categories, used to filter out events from pool options.
350 * @return array with category_id => category_label. */
351 public function getCategories()
352 {
353 return array_merge(parent::getCategories(), array(
354 'woocommerce' => __("WooCommerce", 'woorewards-lite'),
355 'money' => __("Money", 'woorewards-lite'),
356 'order' => __("Order", 'woorewards-lite')
357 ));
358 }
359
360 function isGuestAllowed()
361 {
362 return false;
363 }
364 }