ShMethodClass.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 === 2) {
  225. // 如果当天该配送方式已成功下过单,不再限制,直接放行
  226. if (self::isPackPaidToday($customId, $style) || self::isSendCostPaidToday($customId, $style)) {
  227. return '';
  228. }
  229. if ($minAmount > 0 && (float)$actPrice < $minAmount) {
  230. return "满{$minAmount}元 可{$methodName}";
  231. }
  232. if ($minNum > 0 && (float)$bigNum < $minNum) {
  233. return "满{$minNum}扎 可{$methodName}";
  234. }
  235. return '未达到最低消费,不能下单';
  236. }
  237. // 不满最低消费但允许加收费用时,校验包装费/运费是否已写入采购单,防止前端绕过
  238. if (($unMeet === 0 || $unMeet === 1) && $unMeetFee > 0) {
  239. // unMeet === 0 加收运费, unMeet === 1 加收包装费
  240. $feeToCheck = $unMeet === 1 ? $packCost : $sendCost;
  241. // 如果今天已经收过对应的附加费用,则直接通过校验
  242. if ($unMeet === 1 && self::isPackPaidToday($customId, $style)) {
  243. return '';
  244. }
  245. if ($unMeet === 0 && self::isSendCostPaidToday($customId, $style)) {
  246. return '';
  247. }
  248. if (bccomp((string)$feeToCheck, (string)$unMeetFee, 2) < 0) {
  249. $feeLabel = $unMeet === 1 ? '包装费' : '运费';
  250. return "未达最低消费,需加收{$feeLabel}{$unMeetFee}元";
  251. }
  252. }
  253. return '';
  254. }
  255. /**
  256. * 判断当天是否已经收过附加费(包装费)
  257. * 与其他逻辑共用同一个 Redis Key,保证一天只收一次
  258. * @param int $customId 客户ID
  259. * @param int $sendType 配送方式 (0: 送货, 4: 快递)
  260. * @return bool
  261. */
  262. public static function isPackPaidToday($customId, $sendType = 0)
  263. {
  264. if (empty($customId)) {
  265. return false;
  266. }
  267. $current = date("Y_m_d");
  268. $key = 'ghs_custom_today_has_get_pack_cost_' . $sendType . '_' . $current . '_' . $customId;
  269. $has = \Yii::$app->redis->executeCommand('GET', [$key]);
  270. return (!empty($has) && $has == 1);
  271. }
  272. /**
  273. * 判断当天是否已经收过运费
  274. * @param int $customId 客户ID
  275. * @param int $sendType 配送方式
  276. * @return bool
  277. */
  278. public static function isSendCostPaidToday($customId, $sendType = 0)
  279. {
  280. if (empty($customId)) {
  281. return false;
  282. }
  283. $current = date("Y_m_d");
  284. $key = 'ghs_custom_today_has_get_send_cost_' . $sendType . '_' . $current . '_' . $customId;
  285. $has = \Yii::$app->redis->executeCommand('GET', [$key]);
  286. return (!empty($has) && $has == 1);
  287. }
  288. /**
  289. * 计算采购单应写入的附加费用(不满最低消费时按 unMeet 加收运费或包装费)
  290. * 供 createPurchase 前写入 sendCost 和 packCost,与 hdApp syncPackCostByMethod 一致
  291. *
  292. * @param int $shopId 供货商门店 ID
  293. * @param int $mainId 供货商商户 ID
  294. * @param int $sendType 配送方式
  295. * @param float $itemTotalAmount 花材合计金额(下单前,与前端 commodityPrice 一致)
  296. * @param int|float $bigNum 下单扎数
  297. * @param int $customId 客户ID,用于判断当天是否已收过
  298. * @param array|object $ghsInfo 客户与该供货商的关系信息(xhGhs)
  299. * @return array ['sendCost' => 运费, 'packCost' => 包装费]
  300. */
  301. public static function calcFee($config, $sendType, $itemTotalAmount, $bigNum, $customId = 0, $ghsInfo = [])
  302. {
  303. $costs = ['sendCost' => 0, 'packCost' => 0];
  304. $style = (int)$sendType;
  305. if ($style < 0 || $style > 4) {
  306. return $costs;
  307. }
  308. if (empty($config)) {
  309. return $costs;
  310. }
  311. if ($style === 0 && !empty($ghsInfo) && isset($ghsInfo['homeRule']) && $ghsInfo['homeRule'] == 1) {
  312. // 如果 homeRule == 1,特定字段取xhGhs的设置(优先级最高),其余(如name)保留原配置
  313. $config['status'] = $ghsInfo['home'] ?? 0;
  314. $config['minAmount'] = $ghsInfo['homeAmount'] ?? 0;
  315. $config['minNum'] = $ghsInfo['homeNum'] ?? 0;
  316. $config['unMeet'] = $ghsInfo['homeUnMeet'] ?? 0;
  317. $config['unMeetFee'] = $ghsInfo['homeUnFee'] ?? 0;
  318. }
  319. // 直接合并 isBelowMinimum 的逻辑,方便理解,不再套用额外的方法
  320. $minAmount = isset($config['minAmount']) ? (float)$config['minAmount'] : 0.00;
  321. $minNum = isset($config['minNum']) ? (int)$config['minNum'] : 0;
  322. // 必须金额和数量同时满足(如果设置了的话),才算“达标”
  323. $isBelowMinimum = false;
  324. if ($minAmount > 0 && $itemTotalAmount < $minAmount) {
  325. $isBelowMinimum = true;
  326. }
  327. if ($minNum > 0 && (float)$bigNum < $minNum) {
  328. $isBelowMinimum = true;
  329. }
  330. // 如果已经达标,不收取附加费用
  331. if (!$isBelowMinimum) {
  332. return $costs;
  333. }
  334. $unMeet = isset($config['unMeet']) ? (int)$config['unMeet'] : 0;
  335. $unMeetFee = isset($config['unMeetFee']) ? (float)$config['unMeetFee'] : 0;
  336. if ($unMeetFee > 0) {
  337. // unMeet: 0 加收运费(默认),1 加收包装费,2 不能下单
  338. if ($unMeet === 0) {
  339. if (!self::isSendCostPaidToday($customId, $style)) {
  340. $costs['sendCost'] = $unMeetFee;
  341. }
  342. } elseif ($unMeet === 1) {
  343. if (!self::isPackPaidToday($customId, $style)) {
  344. $costs['packCost'] = $unMeetFee;
  345. }
  346. }
  347. }
  348. return $costs;
  349. }
  350. /**
  351. * 保存配送方式配置,包含说明项和满减规则
  352. * @param int $shopId 门店ID
  353. * @param int $mainId 商户ID
  354. * @param array $data 配置数据
  355. * @return bool
  356. * @throws \Exception
  357. */
  358. public static function saveConfig($shopId, $mainId, $data)
  359. {
  360. $id = $data['id'] ?? 0;
  361. $style = $data['style'] ?? 0;
  362. $config = null;
  363. if ($id > 0) {
  364. // 复杂分支/关键逻辑:优化。后端的查询全部由 shopId 改为 mainId。
  365. $config = self::getByCondition(['id' => $id, 'mainId' => $mainId], true);
  366. }
  367. if (empty($config)) {
  368. // 复杂分支/关键逻辑:优化。后端的查询全部由 shopId 改为 mainId。
  369. $config = self::getByCondition(['mainId' => $mainId, 'style' => $style], true);
  370. }
  371. $saveData = [
  372. 'name' => $data['name'] ?? '',
  373. 'calcType' => isset($data['calcType']) ? (int)$data['calcType'] : 0, // 算运费方式 (0: 用跑腿, 1: 用自定义)
  374. 'status' => isset($data['status']) ? (int)$data['status'] : 1,
  375. 'sort' => isset($data['sort']) ? (int)$data['sort'] : 0,
  376. 'minAmount' => isset($data['minAmount']) ? (float)$data['minAmount'] : 0.00,
  377. 'minNum' => isset($data['minNum']) ? (int)$data['minNum'] : 0,
  378. 'unMeet' => isset($data['unMeet']) ? (int)$data['unMeet'] : 0,
  379. 'unMeetFee' => isset($data['unMeetFee']) ? (float)$data['unMeetFee'] : 0.00,
  380. 'startKm' => isset($data['startKm']) ? (float)$data['startKm'] : 0.00,
  381. 'startPrice' => isset($data['startPrice']) ? (float)$data['startPrice'] : 0.00,
  382. 'perKmPrice' => isset($data['perKmPrice']) ? (float)$data['perKmPrice'] : 0.00,
  383. 'changeRate' => isset($data['changeRate']) ? (float)$data['changeRate'] : 0.00,
  384. ];
  385. $transaction = Yii::$app->db->beginTransaction();
  386. try {
  387. if (empty($config)) {
  388. $saveData['shopId'] = $shopId; // shopId 作为保存预留字段存入
  389. $saveData['mainId'] = $mainId;
  390. $saveData['style'] = $style;
  391. $config = self::add($saveData, true);
  392. } else {
  393. self::updateByCondition(['id' => $config->id], $saveData);
  394. }
  395. $methodId = $config->id;
  396. // 1. 保存说明项 (xhShExplain)
  397. ShExplainClass::deleteByCondition(['methodId' => $methodId]);
  398. if (!empty($data['explains']) && is_array($data['explains'])) {
  399. $explainRows = [];
  400. foreach ($data['explains'] as $index => $exp) {
  401. if (empty($exp['explain'])) {
  402. continue;
  403. }
  404. $explainRows[] = [
  405. 'methodId' => $methodId,
  406. 'explain' => $exp['explain'],
  407. 'color' => isset($exp['color']) ? (int)$exp['color'] : 1,
  408. 'fontWeight' => isset($exp['fontWeight']) ? (int)$exp['fontWeight'] : 1,
  409. 'sort' => isset($exp['sort']) ? (int)$exp['sort'] : $index,
  410. ];
  411. }
  412. if (!empty($explainRows)) {
  413. ShExplainClass::batchAdd($explainRows);
  414. }
  415. }
  416. // 2. 保存跑腿满减规则 (xhShReduceRule)
  417. ShReduceRuleClass::deleteByCondition(['methodId' => $methodId]);
  418. if ($style == 2 && !empty($data['reduceRules']) && is_array($data['reduceRules'])) {
  419. $ruleRows = [];
  420. foreach ($data['reduceRules'] as $index => $rule) {
  421. $ruleRows[] = [
  422. 'methodId' => $methodId,
  423. 'meetNum' => isset($rule['meetNum']) ? (int)$rule['meetNum'] : 0,
  424. 'meetAmount' => isset($rule['meetAmount']) ? (float)$rule['meetAmount'] : 0.00,
  425. 'freeKm' => isset($rule['freeKm']) ? (float)$rule['freeKm'] : 0.00,
  426. 'sort' => isset($rule['sort']) ? (int)$rule['sort'] : $index,
  427. ];
  428. }
  429. if (!empty($ruleRows)) {
  430. ShReduceRuleClass::batchAdd($ruleRows);
  431. }
  432. }
  433. $transaction->commit();
  434. return true;
  435. } catch (\Exception $e) {
  436. $transaction->rollBack();
  437. throw $e;
  438. }
  439. }
  440. }