ShMethodClass.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. /**
  3. * 用途:配送方式配置业务逻辑类
  4. * 谁用:供货商系统
  5. * 解决什么问题:处理配送方式的查询、保存、默认初始化等业务逻辑
  6. */
  7. namespace bizGhs\order\classes;
  8. use bizGhs\base\classes\BaseClass;
  9. use common\components\dict;
  10. use Yii;
  11. class ShMethodClass extends BaseClass
  12. {
  13. public static $baseFile = '\bizGhs\order\models\ShMethod';
  14. /**
  15. * 获取所有配送方式的排序和别名信息
  16. * @param int $mainId 商户ID
  17. * @return array
  18. */
  19. public static function getSorts($mainId)
  20. {
  21. $list = [];
  22. $aliases = [
  23. 0 => '送货',
  24. 1 => '自取',
  25. 2 => '跑腿',
  26. 3 => '物流',
  27. 4 => '快递'
  28. ];
  29. for ($style = 0; $style <= 4; $style++) {
  30. $config = self::getByCondition(['mainId' => $mainId, 'style' => $style]);
  31. $sort = 0;
  32. $alias = $aliases[$style];
  33. $status = 1;
  34. if (!empty($config)) {
  35. $sort = isset($config['sort']) ? (int)$config['sort'] : 0;
  36. $alias = !empty($config['name']) ? $config['name'] : $aliases[$style];
  37. $status = isset($config['status']) ? (int)$config['status'] : 1;
  38. }
  39. $list[] = [
  40. 'style' => $style,
  41. 'name' => $alias,
  42. 'sort' => $sort,
  43. 'status' => $status
  44. ];
  45. }
  46. return $list;
  47. }
  48. /**
  49. * 获取指定门店和类型的配送方式配置,若不存在则进行默认初始化
  50. * @param int $shopId 门店ID
  51. * @param int $mainId 商户ID
  52. * @param int $style 配送类型 (0: 送货, 1: 自取, 2: 跑腿, 3: 物流, 4: 快递)
  53. * @return array
  54. */
  55. public static function getConfig($shopId, $mainId, $style)
  56. {
  57. // 复杂分支/关键逻辑:优化。后端的查询全部由 shopId 改为 mainId,只根据 mainId 和 style 进行查询。
  58. $config = self::getByCondition(['mainId' => $mainId, 'style' => $style]);
  59. if (empty($config)) {
  60. // 从字典配置中读取对应类型的默认配置
  61. $defaultConfig = dict::getDict('shMethod', $style);
  62. $initData = array_merge([
  63. 'shopId' => $shopId, // shopId 仅作为保存预留字段存入
  64. 'mainId' => $mainId,
  65. 'style' => $style,
  66. ], $defaultConfig);
  67. $config = self::add($initData, true);
  68. $config = $config->toArray();
  69. }
  70. // 获取关联的说明项
  71. $config['explains'] = ShExplainClass::getAllByCondition(
  72. ['methodId' => $config['id']],
  73. 'sort ASC, id ASC'
  74. );
  75. // 如果 is_跑腿 (style为2),获取关联的满减规则
  76. if ($style == 2) {
  77. $config['reduceRules'] = ShReduceRuleClass::getAllByCondition(
  78. ['methodId' => $config['id']],
  79. 'sort ASC, id ASC'
  80. );
  81. } else {
  82. $config['reduceRules'] = [];
  83. }
  84. return $config;
  85. }
  86. /**
  87. * 一次性获取商户所有的5种配送方式配置,减少数据库查询交互。
  88. * 如果数据库里没有对应配置,则自动采用 dict.php 里的默认参数进行填充并完成入库。
  89. * @param int $shopId 门店ID
  90. * @param int $mainId 商户ID
  91. * @return array
  92. */
  93. public static function getAllConfigs($shopId, $mainId)
  94. {
  95. // 1. 一次性从数据库中查询当前商户的所有配送方式配置
  96. $configsMap = self::getAllByCondition(['mainId' => $mainId], 'sort asc', '*', 'style', true);
  97. // 2. 补齐缺失的配送方式,并做初始化入库
  98. for ($style = 0; $style <= 4; $style++) {
  99. if (!isset($configsMap[$style])) {
  100. $defaultConfig = dict::getDict('shMethod', $style);
  101. $initData = array_merge([
  102. 'shopId' => $shopId, // shopId 仅作为保存预留字段存入
  103. 'mainId' => $mainId,
  104. 'style' => $style,
  105. ], $defaultConfig);
  106. $configObj = self::add($initData, true);
  107. $configsMap[$style] = $configObj;
  108. }
  109. }
  110. // 将 ActiveRecord 统一转换为 array,并提取 methodIds 用于批量子表查询
  111. $configsArray = [];
  112. $methodIds = [];
  113. foreach ($configsMap as $style => $configObj) {
  114. $configArr = $configObj instanceof \yii\db\ActiveRecord ? $configObj->toArray() : $configObj;
  115. $configsArray[$style] = $configArr;
  116. $methodIds[] = (int)$configArr['id'];
  117. }
  118. // 3. 批量查询所有的说明项 (xhShExplain) - 仅 1 次查询
  119. $allExplains = [];
  120. if (!empty($methodIds)) {
  121. $allExplains = ShExplainClass::getAllByCondition(['methodId' => ['in', $methodIds]], 'sort ASC, id ASC');
  122. }
  123. $explainsMap = [];
  124. foreach ($allExplains as $exp) {
  125. $explainsMap[(int)$exp['methodId']][] = $exp;
  126. }
  127. // 4. 批量查询所有的跑腿满减规则 (xhShReduceRule) - 仅 1 次查询
  128. $allReduceRules = [];
  129. if (!empty($methodIds)) {
  130. $allReduceRules = ShReduceRuleClass::getAllByCondition(['methodId' => ['in', $methodIds]], 'sort ASC, id ASC');
  131. }
  132. $reduceRulesMap = [];
  133. foreach ($allReduceRules as $rule) {
  134. $reduceRulesMap[(int)$rule['methodId']][] = $rule;
  135. }
  136. // 5. 将批量查出的说明项和规则,合并填充到 5 个配送方式中
  137. $result = [];
  138. for ($style = 0; $style <= 4; $style++) {
  139. $config = $configsArray[$style];
  140. $methodId = (int)$config['id'];
  141. $config['explains'] = $explainsMap[$methodId] ?? [];
  142. $config['reduceRules'] = ($style == 2) ? ($reduceRulesMap[$methodId] ?? []) : [];
  143. $result[] = $config;
  144. }
  145. // 按 sort 升序返回,供 hd/ghs GetAllConfig 等接口展示自定义排序
  146. usort($result, function ($a, $b) {
  147. $sortCompare = (int)($a['sort'] ?? 0) <=> (int)($b['sort'] ?? 0);
  148. if ($sortCompare !== 0) {
  149. return $sortCompare;
  150. }
  151. // sort 相同时按 style 稳定排序,避免顺序抖动
  152. return (int)($a['style'] ?? 0) <=> (int)($b['style'] ?? 0);
  153. });
  154. return $result;
  155. }
  156. /**
  157. * 判断配送方式配置是否未达最低消费(金额或扎数任一不满足即视为未达标)
  158. * 与 hdApp affirm-sh-method-panel.checkShMethodBelowMinimum 规则一致
  159. *
  160. * @param array $config xhShMethod 配置
  161. * @param float $actPrice 实付花材金额
  162. * @param int|float $bigNum 下单扎数
  163. * @return bool
  164. */
  165. /**
  166. * 采购下单后校验 xhShMethod 配送限制
  167. * 供 hd PurchaseController::actionCreateOrder 在 createPurchase 之后调用,与旧版 else 分支门店硬编码限制同级
  168. *
  169. * @param int $shopId 供货商门店 ID
  170. * @param int $mainId 供货商商户 ID
  171. * @param int $sendType 配送方式,与 xhShMethod.style 一致
  172. * @param float $actPrice 下单后实付花材金额
  173. * @param int|float $bigNum 下单扎数
  174. * @param float $packCost 已写入采购单的包装费
  175. * @param float $sendCost 已写入采购单的运费
  176. * @param string $wlName 物流公司名称(style=3 时必填)
  177. * @param int $customId 客户ID,用于判断当天是否已收过
  178. * @param array|object $ghsInfo 客户与该供货商的关系信息(xhGhs)
  179. * @return string 空字符串表示通过,否则为需提示用户的错误文案
  180. */
  181. public static function checkLimit($shopId, $mainId, $sendType, $actPrice, $bigNum, $packCost = 0, $sendCost = 0, $wlName = '', $customId = 0, $ghsInfo = [])
  182. {
  183. $style = (int)$sendType;
  184. if ($style < 0 || $style > 4) {
  185. return '配送方式无效';
  186. }
  187. $config = self::getConfig($shopId, $mainId, $style);
  188. if (empty($config)) {
  189. return '配送方式配置异常';
  190. }
  191. if ($style === 0 && !empty($ghsInfo) && isset($ghsInfo['homeRule']) && $ghsInfo['homeRule'] == 1) {
  192. // 如果 homeRule == 1,特定字段取xhGhs的设置(优先级最高),其余(如name)保留原配置
  193. $config['status'] = $ghsInfo['home'] ?? 0;
  194. $config['minAmount'] = $ghsInfo['homeAmount'] ?? 0;
  195. $config['minNum'] = $ghsInfo['homeNum'] ?? 0;
  196. $config['unMeet'] = $ghsInfo['homeUnMeet'] ?? 0;
  197. $config['unMeetFee'] = $ghsInfo['homeUnFee'] ?? 0;
  198. }
  199. $methodName = !empty($config['name']) ? $config['name'] : '该配送方式';
  200. // 配送方式已禁用,对齐旧逻辑「暂不支持送货上门,请选其它配送方式」
  201. if (isset($config['status']) && (int)$config['status'] === 0) {
  202. return "暂不支持{$methodName},请选其它配送方式";
  203. }
  204. // 物流需填物流公司,与 hdApp validateBeforeSubmit 一致
  205. if ($style === 3 && trim((string)$wlName) === '') {
  206. return '请填选物流';
  207. }
  208. $minAmount = isset($config['minAmount']) ? (float)$config['minAmount'] : 0.00;
  209. $minNum = isset($config['minNum']) ? (int)$config['minNum'] : 0;
  210. // 必须金额和数量同时满足(如果设置了的话),才算“达标”
  211. $isBelowMinimum = false;
  212. if ($minAmount > 0 && $actPrice < $minAmount) {
  213. $isBelowMinimum = true;
  214. }
  215. if ($minNum > 0 && (float)$bigNum < $minNum) {
  216. $isBelowMinimum = true;
  217. }
  218. if (!$isBelowMinimum) {
  219. return '';
  220. }
  221. $unMeet = isset($config['unMeet']) ? (int)$config['unMeet'] : 0;
  222. $unMeetFee = isset($config['unMeetFee']) ? (float)$config['unMeetFee'] : 0;
  223. // 不满最低消费且不允许下单
  224. if ($unMeet === 1) {
  225. if ($minAmount > 0 && (float)$actPrice < $minAmount) {
  226. return "满{$minAmount}元 可{$methodName}";
  227. }
  228. if ($minNum > 0 && (float)$bigNum < $minNum) {
  229. return "满{$minNum}扎 可{$methodName}";
  230. }
  231. return '未达到最低消费,不能下单';
  232. }
  233. // 不满最低消费但允许加收费用时,校验包装费/运费是否已写入采购单,防止前端绕过
  234. if (($unMeet === 0 || $unMeet === 2) && $unMeetFee > 0) {
  235. // unMeet === 0 加收运费, unMeet === 2 加收包装费
  236. $feeToCheck = $unMeet === 2 ? $packCost : $sendCost;
  237. // 如果今天已经收过对应的附加费用,则直接通过校验
  238. if ($unMeet === 2 && self::isPackPaidToday($customId, $style)) {
  239. return '';
  240. }
  241. if ($unMeet === 0 && self::isSendCostPaidToday($customId, $style)) {
  242. return '';
  243. }
  244. if (bccomp((string)$feeToCheck, (string)$unMeetFee, 2) < 0) {
  245. $feeLabel = $unMeet === 2 ? '包装费' : '运费';
  246. return "未达最低消费,需加收{$feeLabel}{$unMeetFee}元";
  247. }
  248. }
  249. return '';
  250. }
  251. /**
  252. * 判断当天是否已经收过附加费(包装费)
  253. * 与其他逻辑共用同一个 Redis Key,保证一天只收一次
  254. * @param int $customId 客户ID
  255. * @param int $sendType 配送方式 (0: 送货, 4: 快递)
  256. * @return bool
  257. */
  258. public static function isPackPaidToday($customId, $sendType = 0)
  259. {
  260. if (empty($customId)) {
  261. return false;
  262. }
  263. $current = date("Y_m_d");
  264. $key = 'ghs_custom_today_has_get_pack_cost_' . $sendType . '_' . $current . '_' . $customId;
  265. $has = \Yii::$app->redis->executeCommand('GET', [$key]);
  266. return (!empty($has) && $has == 1);
  267. }
  268. /**
  269. * 判断当天是否已经收过运费
  270. * @param int $customId 客户ID
  271. * @param int $sendType 配送方式
  272. * @return bool
  273. */
  274. public static function isSendCostPaidToday($customId, $sendType = 0)
  275. {
  276. if (empty($customId)) {
  277. return false;
  278. }
  279. $current = date("Y_m_d");
  280. $key = 'ghs_custom_today_has_get_send_cost_' . $sendType . '_' . $current . '_' . $customId;
  281. $has = \Yii::$app->redis->executeCommand('GET', [$key]);
  282. return (!empty($has) && $has == 1);
  283. }
  284. /**
  285. * 计算采购单应写入的附加费用(不满最低消费时按 unMeet 加收运费或包装费)
  286. * 供 createPurchase 前写入 sendCost 和 packCost,与 hdApp syncPackCostByMethod 一致
  287. *
  288. * @param int $shopId 供货商门店 ID
  289. * @param int $mainId 供货商商户 ID
  290. * @param int $sendType 配送方式
  291. * @param float $itemTotalAmount 花材合计金额(下单前,与前端 commodityPrice 一致)
  292. * @param int|float $bigNum 下单扎数
  293. * @param int $customId 客户ID,用于判断当天是否已收过
  294. * @param array|object $ghsInfo 客户与该供货商的关系信息(xhGhs)
  295. * @return array ['sendCost' => 运费, 'packCost' => 包装费]
  296. */
  297. public static function calcFee($config, $sendType, $itemTotalAmount, $bigNum, $customId = 0, $ghsInfo = [])
  298. {
  299. $costs = ['sendCost' => 0, 'packCost' => 0];
  300. $style = (int)$sendType;
  301. if ($style < 0 || $style > 4) {
  302. return $costs;
  303. }
  304. if (empty($config)) {
  305. return $costs;
  306. }
  307. if ($style === 0 && !empty($ghsInfo) && isset($ghsInfo['homeRule']) && $ghsInfo['homeRule'] == 1) {
  308. // 如果 homeRule == 1,特定字段取xhGhs的设置(优先级最高),其余(如name)保留原配置
  309. $config['status'] = $ghsInfo['home'] ?? 0;
  310. $config['minAmount'] = $ghsInfo['homeAmount'] ?? 0;
  311. $config['minNum'] = $ghsInfo['homeNum'] ?? 0;
  312. $config['unMeet'] = $ghsInfo['homeUnMeet'] ?? 0;
  313. $config['unMeetFee'] = $ghsInfo['homeUnFee'] ?? 0;
  314. }
  315. // 直接合并 isBelowMinimum 的逻辑,方便理解,不再套用额外的方法
  316. $minAmount = isset($config['minAmount']) ? (float)$config['minAmount'] : 0.00;
  317. $minNum = isset($config['minNum']) ? (int)$config['minNum'] : 0;
  318. // 必须金额和数量同时满足(如果设置了的话),才算“达标”
  319. $isBelowMinimum = false;
  320. if ($minAmount > 0 && $itemTotalAmount < $minAmount) {
  321. $isBelowMinimum = true;
  322. }
  323. if ($minNum > 0 && (float)$bigNum < $minNum) {
  324. $isBelowMinimum = true;
  325. }
  326. // 如果已经达标,不收取附加费用
  327. if (!$isBelowMinimum) {
  328. return $costs;
  329. }
  330. $unMeet = isset($config['unMeet']) ? (int)$config['unMeet'] : 0;
  331. $unMeetFee = isset($config['unMeetFee']) ? (float)$config['unMeetFee'] : 0;
  332. if ($unMeetFee > 0) {
  333. // unMeet: 0 加收运费(默认),2 加收包装费
  334. if ($unMeet === 0) {
  335. if (!self::isSendCostPaidToday($customId, $style)) {
  336. $costs['sendCost'] = $unMeetFee;
  337. }
  338. } elseif ($unMeet === 2) {
  339. if (!self::isPackPaidToday($customId, $style)) {
  340. $costs['packCost'] = $unMeetFee;
  341. }
  342. }
  343. }
  344. return $costs;
  345. }
  346. /**
  347. * 保存配送方式配置,包含说明项和满减规则
  348. * @param int $shopId 门店ID
  349. * @param int $mainId 商户ID
  350. * @param array $data 配置数据
  351. * @return bool
  352. * @throws \Exception
  353. */
  354. public static function saveConfig($shopId, $mainId, $data)
  355. {
  356. $id = $data['id'] ?? 0;
  357. $style = $data['style'] ?? 0;
  358. $config = null;
  359. if ($id > 0) {
  360. // 复杂分支/关键逻辑:优化。后端的查询全部由 shopId 改为 mainId。
  361. $config = self::getByCondition(['id' => $id, 'mainId' => $mainId], true);
  362. }
  363. if (empty($config)) {
  364. // 复杂分支/关键逻辑:优化。后端的查询全部由 shopId 改为 mainId。
  365. $config = self::getByCondition(['mainId' => $mainId, 'style' => $style], true);
  366. }
  367. $saveData = [
  368. 'name' => $data['name'] ?? '',
  369. 'calcType' => isset($data['calcType']) ? (int)$data['calcType'] : 0, // 算运费方式 (0: 用跑腿, 1: 用自定义)
  370. 'status' => isset($data['status']) ? (int)$data['status'] : 1,
  371. 'sort' => isset($data['sort']) ? (int)$data['sort'] : 0,
  372. 'minAmount' => isset($data['minAmount']) ? (float)$data['minAmount'] : 0.00,
  373. 'minNum' => isset($data['minNum']) ? (int)$data['minNum'] : 0,
  374. 'unMeet' => isset($data['unMeet']) ? (int)$data['unMeet'] : 0,
  375. 'unMeetFee' => isset($data['unMeetFee']) ? (float)$data['unMeetFee'] : 0.00,
  376. 'startKm' => isset($data['startKm']) ? (float)$data['startKm'] : 0.00,
  377. 'startPrice' => isset($data['startPrice']) ? (float)$data['startPrice'] : 0.00,
  378. 'perKmPrice' => isset($data['perKmPrice']) ? (float)$data['perKmPrice'] : 0.00,
  379. 'changeRate' => isset($data['changeRate']) ? (float)$data['changeRate'] : 0.00,
  380. ];
  381. $transaction = Yii::$app->db->beginTransaction();
  382. try {
  383. if (empty($config)) {
  384. $saveData['shopId'] = $shopId; // shopId 作为保存预留字段存入
  385. $saveData['mainId'] = $mainId;
  386. $saveData['style'] = $style;
  387. $config = self::add($saveData, true);
  388. } else {
  389. self::updateByCondition(['id' => $config->id], $saveData);
  390. }
  391. $methodId = $config->id;
  392. // 1. 保存说明项 (xhShExplain)
  393. ShExplainClass::deleteByCondition(['methodId' => $methodId]);
  394. if (!empty($data['explains']) && is_array($data['explains'])) {
  395. $explainRows = [];
  396. foreach ($data['explains'] as $index => $exp) {
  397. if (empty($exp['explain'])) {
  398. continue;
  399. }
  400. $explainRows[] = [
  401. 'methodId' => $methodId,
  402. 'explain' => $exp['explain'],
  403. 'color' => isset($exp['color']) ? (int)$exp['color'] : 1,
  404. 'fontWeight' => isset($exp['fontWeight']) ? (int)$exp['fontWeight'] : 1,
  405. 'sort' => isset($exp['sort']) ? (int)$exp['sort'] : $index,
  406. ];
  407. }
  408. if (!empty($explainRows)) {
  409. ShExplainClass::batchAdd($explainRows);
  410. }
  411. }
  412. // 2. 保存跑腿满减规则 (xhShReduceRule)
  413. ShReduceRuleClass::deleteByCondition(['methodId' => $methodId]);
  414. if ($style == 2 && !empty($data['reduceRules']) && is_array($data['reduceRules'])) {
  415. $ruleRows = [];
  416. foreach ($data['reduceRules'] as $index => $rule) {
  417. $ruleRows[] = [
  418. 'methodId' => $methodId,
  419. 'meetNum' => isset($rule['meetNum']) ? (int)$rule['meetNum'] : 0,
  420. 'meetAmount' => isset($rule['meetAmount']) ? (float)$rule['meetAmount'] : 0.00,
  421. 'freeKm' => isset($rule['freeKm']) ? (float)$rule['freeKm'] : 0.00,
  422. 'sort' => isset($rule['sort']) ? (int)$rule['sort'] : $index,
  423. ];
  424. }
  425. if (!empty($ruleRows)) {
  426. ShReduceRuleClass::batchAdd($ruleRows);
  427. }
  428. }
  429. $transaction->commit();
  430. return true;
  431. } catch (\Exception $e) {
  432. $transaction->rollBack();
  433. throw $e;
  434. }
  435. }
  436. }