ExpressService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace app\store\service;
  3. use think\Db;
  4. /**
  5. * 商城邮费服务
  6. * Class ExpressService
  7. * @package app\store\service
  8. */
  9. class ExpressService
  10. {
  11. /**
  12. * 订单邮费计算
  13. * @param string $province 配送省份
  14. * @param string $number 计费数量
  15. * @param string $amount 订单金额
  16. * @return array
  17. * @throws \think\db\exception\DataNotFoundException
  18. * @throws \think\db\exception\ModelNotFoundException
  19. * @throws \think\exception\DbException
  20. */
  21. public static function price($province, $number, $amount)
  22. {
  23. // 读取对应的模板规则
  24. $map = [['is_default', 'eq', '0'], ['rule', 'like', "%{$province}%"]];
  25. $rule = Db::name('StoreExpressTemplate')->where($map)->find();
  26. if (!empty($rule)) return self::buildData($rule, '普通模板', $number, $amount);
  27. $rule = Db::name('StoreExpressTemplate')->where(['is_default' => '1'])->find();
  28. return self::buildData($rule, '默认模板', $number, $amount);
  29. }
  30. /**
  31. * 生成邮费数据
  32. * @param array $rule 模板规则
  33. * @param string $type 模板类型
  34. * @param integer $number 计费件数
  35. * @param double $amount 订单金额
  36. * @return array
  37. */
  38. protected static function buildData($rule, $type, $number, $amount)
  39. {
  40. // 异常规则
  41. if (empty($rule)) return [
  42. 'express_price' => 0.00, 'express_type' => '未知模板', 'express_desc' => '未匹配到邮费模板',
  43. ];
  44. // 满减免邮
  45. if ($rule['order_reduction_state'] && $amount >= $rule['order_reduction_price']) {
  46. return [
  47. 'express_price' => 0.00, 'express_type' => $type,
  48. 'express_desc' => "订单总金额满{$rule['order_reduction_price']}元减免全部邮费",
  49. ];
  50. }
  51. // 首重计费
  52. if ($number <= $rule['first_number']) return [
  53. 'express_price' => $rule['first_price'], 'express_type' => $type,
  54. 'express_desc' => "首件计费,{$rule['first_number']}件及{$rule['first_number']}以内计费{$rule['first_price']}元",
  55. ];
  56. // 续重计费
  57. list($price1, $price2) = [$rule['first_price'], 0];
  58. if ($rule['next_number'] > 0 && $rule['next_price'] > 0) {
  59. $price2 = $rule['next_price'] * ceil(($number - $rule['first_number']) / $rule['next_number']);
  60. }
  61. return [
  62. 'express_price' => $price1 + $price2, 'express_type' => $type,
  63. 'express_desc' => "续件计费,超出{$rule['first_number']}件,首件费用{$rule['first_price']}元 + 续件费用{$price2}元",
  64. ];
  65. }
  66. }