FullPiece.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2018/5/23
  6. * Time: 下午3:55
  7. */
  8. namespace app\frontend\modules\order\discount;
  9. use app\common\facades\Setting;
  10. use app\common\modules\orderGoods\models\PreOrderGoods;
  11. class FullPiece extends BaseDiscount
  12. {
  13. protected $code = 'fullPiece';
  14. protected $name = '满件优惠';
  15. /**
  16. * 获取总金额
  17. * @return int|mixed
  18. * @throws \app\common\exceptions\AppException
  19. */
  20. protected function _getAmount()
  21. {
  22. $settings = Setting::get('shop.fullPieceNew');
  23. if(!$settings['open']){
  24. return 0;
  25. }
  26. //只有商城订单参加 益生插件订单
  27. if(!in_array($this->order->plugin_id,[0,61])){
  28. return 0;
  29. }
  30. if (empty($settings['fullPiece'])) {
  31. return 0;
  32. }
  33. $fullPieces = [];
  34. foreach ($settings['fullPiece'] as $k=>$v) {
  35. $fullPieces[$k] = $v;
  36. $fullPieces[$k]['goods'] = [];
  37. if (empty($v['goods'])) {
  38. continue;
  39. }
  40. foreach ($this->order->orderGoods as $orderGoods) {
  41. if (in_array($orderGoods->goods_id,$v['goods'])) {
  42. $fullPieces[$k]['goods'][] = $orderGoods->goods_id;
  43. }
  44. }
  45. }
  46. $result = $this->totalAmount($fullPieces);
  47. return $result;
  48. }
  49. /**
  50. * @param $fullPieces
  51. * @return mixed
  52. * @throws \app\common\exceptions\AppException
  53. */
  54. private function totalAmount($fullPieces)
  55. {
  56. // 求和所属订单中指定goods_id的订单商品支付金额
  57. $discount = 0;
  58. foreach ($fullPieces as $fullPiece) {
  59. if (empty($fullPiece['goods'])) {
  60. continue;
  61. }
  62. $goods_count = $this->order->orderGoods->whereIn('goods_id', $fullPiece['goods'])->sum('total');
  63. $rules = collect($fullPiece['rules']);
  64. $rules = $rules->sortByDesc(function ($rule) {
  65. return $rule['enough'];
  66. });
  67. $amount = $this->order->orderGoods->whereIn('goods_id', $fullPiece['goods'])->sum(function (PreOrderGoods $preOrderGoods) {
  68. return $preOrderGoods->getPriceBefore($this->getCode());
  69. });
  70. foreach ($rules as $rule) {
  71. if ($goods_count < $rule['enough']) {
  72. continue;
  73. }
  74. if ($fullPiece['discount_type']) {//折扣
  75. $reduce = bcsub(10,$rule['reduce'],2);
  76. $discount += bcmul(bcdiv($reduce,10,2),$amount,2);
  77. break;
  78. } else {//立减
  79. $discount += $rule['reduce'];
  80. break;
  81. }
  82. }
  83. }
  84. return min($discount,$this->order->getPriceBefore($this->getCode()));
  85. }
  86. }