Commit 086d63f1 authored by wanjilong's avatar wanjilong

add: 增加优惠券分摊计算策略

parent 98d1aea6
<?php
namespace Api\PhpUtils\Strategy;
class ShareWorker {
/**
* @param $items = ['sku_1'=>100, 'sku_2'=>85]
* @param $tip = 100
* @throws \ErrorException
* 根据商品价格等比做优惠金额的分摊, 做四舍五入。
*/
public static function coupon($items, $total_tip) {
if(!is_array($items) || $total_tip <= 0) {
throw new \ErrorException('输入分摊条件失败,请确认', '3001');
}
$total = 0;
foreach ($items as $k=>$price) {
if(!is_int($price) || $price < 0) {
throw new \ErrorException('存在金额非法,请核对金额', '3002');
}
$total += $price;
}
$ret = [];
$cleared = $cleared_tip = 0;
foreach ($items as $k=>$price) {
$left = $total - $cleared;
$ret[$k] = intval(round($price/$left * ($total_tip - $cleared_tip)));
$cleared_tip += $ret[$k];
$cleared += $price;
}
return $ret;
}
/**
* @param $mutiArr = [
['goods'=>['a1'=>600, 'a2'=>100, 'a3'=>1300], 'tip'=>100],
['goods'=>['a1'=>600, 'a2'=>600, 'a3'=>600], 'tip'=>4],
];
* @return array = [
['a1' => 30, 'a2' => 5, 'a3' => 65],
['a1' => 1, 'a2' => 2, 'a3' => 1]
];
* @throws \ErrorException
* 批量计算奖励,
*/
public static function batchCoupon($mutiArr) {
$ret = [];
foreach ($mutiArr as $k=>$item) {
$ret[$k] = self::coupon($item['goods'], $item['tip']);
}
return $ret;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment