GhsClass.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. <?php
  2. /**
  3. * GhsClass:供货商(ghs)与客户(花店/ownShop)双向关系建立与维护的核心业务类。
  4. * 主要用途:通过 build() 实现“确保 ghs 记录与 xhGhsCustom 客户记录成对存在”(get-or-create 幂等操作)。
  5. * 调用方:app-hd/controllers/GhsController::actionInfo(高频入口)、app-ghs GhsController 加供货商流程、
  6. * console 初始化/迁移脚本、biz-ghs/custom/services/CustomService 介绍人逻辑、buildNearbyGhsRelations 等十余处。
  7. * 解决的问题:原先“先 getByCondition 为空再 addGhs/addCustom”的 check-then-insert 在并发(多设备、快速刷新、脚本重试等)
  8. * 场景下,会同时看到不存在而双双 INSERT,导致 xhGhsCustom 表唯一索引 'custom'(ownShopId+shopId 组合)触发 1062 Duplicate entry。
  9. * 本次小改:在两个 INSERT 执行点增加 try-add + catch 重复键异常后重新 getByCondition 的防御逻辑,
  10. * 使 build 成为并发安全的幂等方法;不改调用签名、不强制要求外层事务、改动极小。
  11. * 副作用说明:race 恢复时可能重复执行 shop 标记位更新和 newGhsCustomInform 通知,属于可接受的小副作用(通知幂等性由接收端或后续优化保障)。
  12. * 约束:方法本身不开启事务(由调用方在需要强一致时包裹);getByCondition 为普通查询,无 FOR UPDATE。
  13. */
  14. namespace biz\ghs\classes;
  15. use biz\shop\classes\ShopClass;
  16. use biz\shop\classes\ShopAdminClass;
  17. use biz\sj\classes\MerchantAssetClass;
  18. use biz\sj\classes\SjClass;
  19. use biz\wx\classes\WxMessageClass;
  20. use bizGhs\custom\classes\CustomClass;
  21. use common\components\imgUtil;
  22. use common\components\noticeUtil;
  23. use common\components\stringUtil;
  24. use common\components\util;
  25. use biz\base\classes\BaseClass;
  26. use bizHd\purchase\classes\PurchaseClass;
  27. class GhsClass extends BaseClass
  28. {
  29. const DEBT_NO = 1;
  30. const DEBT_YES = 2;
  31. public static $baseFile = '\biz\ghs\models\Ghs';
  32. //补充供货商 ssh 20211028
  33. public static function bcGhs($hdShopId)
  34. {
  35. return false;
  36. }
  37. /**
  38. * 确保供货商与花店的成对关系存在(ghs 表 + xhGhsCustom 表),支持并发幂等创建。
  39. * 干什么:
  40. * - type=1:返回/创建 xhGhs 记录(供货商视角),并确保对方 xhGhsCustom 也存在。
  41. * - type=2:返回/创建 xhGhsCustom 记录(客户视角)。
  42. * 入参业务含义:
  43. * $ghsShopId - 批发店(供货商)shopId
  44. * $hdShopId - 花店(ownShopId,客户归属店)shopId
  45. * $type - 1 返回 ghs,2 返回 custom(默认1)
  46. * $changeName- 可选覆盖名称(用于从分店同步客户名称时)
  47. * 返回:ghs 或 custom 的数组记录(含 id 等)
  48. * 副作用:可能写入 ghs/custom 表、更新 shop.uniGhsId / hasManyGhs、触发 WxMessageClass::newGhsCustomInform 新客户通知。
  49. * 关键边界与本次修改:
  50. * - 内部对 addGhs / addCustom 做了唯一键冲突防御:catch 到重复键(MySQL 1062/23000/Integrity)后,
  51. * 立即重新 getByCondition 返回已存在记录,函数继续执行后续 updateById / 通知等逻辑。
  52. * - 因此 build 现在是“确保存在”语义的幂等方法,不会因并发而向上抛 1062。
  53. * - 不改变调用方任何代码;不强制事务(调用方可在外层包 beginTransaction)。
  54. * 历史:ssh 2021.4.13 初版;2026-06 小改增加并发 duplicate 容错。
  55. */
  56. public static function build($ghsShopId, $hdShopId, $type = 1, $changeName = '')
  57. {
  58. if ($type == 1) {
  59. $ghs = self::getByCondition(['ownShopId' => $hdShopId, 'shopId' => $ghsShopId]);
  60. if (!empty($ghs)) {
  61. return $ghs;
  62. }
  63. } else {
  64. $custom = CustomClass::getByCondition(['ownShopId' => $ghsShopId, 'shopId' => $hdShopId]);
  65. if (!empty($custom)) {
  66. return $custom;
  67. }
  68. }
  69. $ghsShop = ShopClass::getShopInfo($ghsShopId);
  70. $ghsSjId = $ghsShop['sjId'] ?? 0;
  71. $ghsMainId = $ghsShop['mainId'] ?? 0;
  72. $ghsOwnPtStyle = $ghsShop['ptStyle'] ?? 1;
  73. $ghsAvatar = $ghsShop['shortAvatar'] ?? '';
  74. $ghsDefault = $ghsShop['default'] ?? 0;
  75. $allowDebt = $ghsShop['allowDebt'] ?? 0;
  76. $needCheck = $ghsShop['needCheck'] ?? 0;
  77. $home = $ghsShop['home'] ?? 0;
  78. $homeAmount = $ghsShop['homeAmount'] ?? 0;
  79. $homeNum = $ghsShop['homeNum'] ?? 0;
  80. $passStatus = $needCheck == 1 ? 0 : 1;
  81. $live = $ghsShop['live'] ?? 1;
  82. $isHd = $ghsShop['isHd'] ?? 1;
  83. $showStock = $ghsShop['showStock'] ?? 0;
  84. $allowDebtAmount = $ghsShop['allowDebtAmount'] ?? 0;
  85. if ($isHd == 1) {
  86. $giveLevel = 1;
  87. $level = 1;
  88. } else {
  89. $giveLevel = 0;
  90. $level = 0;
  91. }
  92. $name = $ghsDefault == 1 && $ghsShop['shopName'] == '首店' ? $ghsShop['merchantName'] : $ghsShop['merchantName'] . ' ' . $ghsShop['shopName'];
  93. $py = stringUtil::py($name);
  94. $hdShopInfo = ShopClass::getShopInfo($hdShopId);
  95. $hdSjId = $hdShopInfo['sjId'] ?? 0;
  96. $hdMainId = $hdShopInfo['mainId'] ?? 0;
  97. $hdOwnPtStyle = $hdShopInfo['ptStyle'] ?? 1;
  98. $salt = stringUtil::charsShuffleLowerCase(8);
  99. $ghs = self::getByCondition(['ownShopId' => $hdShopId, 'shopId' => $ghsShopId]);
  100. if (empty($ghs)) {
  101. $data = [
  102. 'sjId' => $ghsSjId,
  103. 'shopId' => $ghsShopId,
  104. 'mainId' => $ghsMainId,
  105. 'ownSjId' => $hdSjId,
  106. 'ownShopId' => $hdShopId,
  107. 'ownMainId' => $hdMainId,
  108. 'ownPtStyle' => $hdOwnPtStyle,
  109. 'name' => $name,
  110. 'py' => $py,
  111. 'avatar' => $ghsAvatar,
  112. 'mobile' => $ghsShop['mobile'] ?? '',
  113. 'province' => $ghsShop['province'] ?? '',
  114. 'city' => $ghsShop['city'] ?? '',
  115. 'dist' => $ghsShop['dist'] ?? '',
  116. 'address' => $ghsShop['address'] ?? '',
  117. 'floor' => $ghsShop['floor'] ?? '',
  118. 'fullAddress' => $ghsShop['fullAddress'] ?? '',
  119. 'lat' => $ghsShop['lat'] ?? '',
  120. 'long' => $ghsShop['long'] ?? '',
  121. 'live' => $live,
  122. 'giveLevel' => $giveLevel,
  123. 'showStock' => $showStock,
  124. 'salt' => $salt,
  125. 'passStatus' => $passStatus,
  126. 'home' => $home,
  127. 'homeAmount' => $homeAmount,
  128. 'homeNum' => $homeNum,
  129. ];
  130. try {
  131. $ghs = self::addGhs($data);
  132. } catch (\Exception $e) {
  133. if (self::isDuplicateKeyError($e)) {
  134. // 并发或竞态条件下,另一请求已成功插入相同 (ownShopId, shopId) 的 ghs 记录
  135. // 捕获唯一键冲突(1062 / 23000 / Integrity constraint violation),重新查询返回已存在记录
  136. // 为什么:让 build 成为幂等操作,防止 1062 错误直接暴露给调用方(如 hd actionInfo)
  137. $ghs = self::getByCondition(['ownShopId' => $hdShopId, 'shopId' => $ghsShopId]);
  138. } else {
  139. throw $e;
  140. }
  141. }
  142. }
  143. $ghsId = $ghs['id'] ?? 0;
  144. $shop = ShopClass::getShopInfo($hdShopId);
  145. $hdAvatar = $shop['shortAvatar'] ?? '';
  146. $default = $shop['default'] ?? 0;
  147. $name = $default == 1 && $shop['shopName'] == '首店' ? $shop['merchantName'] : $shop['merchantName'] . ' ' . $shop['shopName'];
  148. //从分店同步客户,客户被修改的名称也要同步过来
  149. $firstName = empty($changeName) ? $name : $changeName;
  150. $py = stringUtil::py($firstName);
  151. $secondName = $name;
  152. $mobile = $shop['mobile'] ?? '';
  153. $uniGhsId = $shop['uniGhsId'] ?? 0;
  154. $hasManyGhs = $shop['hasManyGhs'] ?? 0;
  155. $hdShopPt = intval($shop['pt'] ?? 0);
  156. if ($uniGhsId == 0 && $hasManyGhs == 0) {
  157. ShopClass::updateById($hdShopId, ['uniGhsId' => $ghsId]);
  158. } else {
  159. //从只有一个供货商变成有多个供货商
  160. ShopClass::updateById($hdShopId, ['hasManyGhs' => 1]);
  161. }
  162. $custom = CustomClass::getByCondition(['ownShopId' => $ghsShopId, 'shopId' => $hdShopId]);
  163. if (empty($custom)) {
  164. $customData = [
  165. 'sjId' => $hdSjId,
  166. 'ghsId' => $ghsId,
  167. 'shopId' => $hdShopId,
  168. 'mainId' => $hdMainId,
  169. 'ownSjId' => $ghsSjId,
  170. 'ownShopId' => $ghsShopId,
  171. 'ownMainId' => $ghsMainId,
  172. 'ownPtStyle' => $ghsOwnPtStyle,
  173. 'name' => $firstName,
  174. 'originName' => $secondName,
  175. 'py' => $py,
  176. 'avatar' => $hdAvatar,
  177. 'mobile' => $mobile,
  178. 'province' => $shop['province'] ?? '',
  179. 'city' => $shop['city'] ?? '',
  180. 'dist' => $shop['dist'] ?? '',
  181. 'address' => $shop['address'] ?? '',
  182. 'fullAddress' => $shop['fullAddress'] ?? '',
  183. 'showAddress' => $shop['showAddress'] ?? '',
  184. 'long' => $shop['long'] ?? '',
  185. 'lat' => $shop['lat'] ?? '',
  186. 'debt' => $allowDebt,
  187. 'debtLimit' => $allowDebtAmount,
  188. 'live' => $live,
  189. 'level' => $level,
  190. 'showStock' => $showStock,
  191. 'salt' => $salt,
  192. 'passStatus' => $passStatus,
  193. 'home' => $home,
  194. 'homeAmount' => $homeAmount,
  195. 'homeNum' => $homeNum,
  196. 'pt' => $hdShopPt === 1 ? 1 : 0,
  197. ];
  198. try {
  199. $custom = CustomClass::addCustom($customData);
  200. } catch (\Exception $e) {
  201. if (self::isDuplicateKeyError($e)) {
  202. // 这是导致原 1062 的主路径:xhGhsCustom 表 unique key 'custom'(ownShopId + shopId)
  203. // 并发场景下两个请求同时通过前面的 getByCondition 看到不存在,同时执行 addCustom
  204. // 捕获后重新 get,函数继续走 customId 赋值、update ghs.customId、发通知等
  205. // 为什么采用 catch+reget 而非外层事务+锁:最小改动、兼容现有数十处调用点、不改变事务边界假设
  206. $custom = CustomClass::getByCondition(['ownShopId' => $ghsShopId, 'shopId' => $hdShopId]);
  207. } else {
  208. throw $e;
  209. }
  210. }
  211. }
  212. $customId = $custom['id'] ?? 0;
  213. self::updateById($ghsId, ['customId' => $customId]);
  214. $customSjId = $custom['sjId'] ?? 0;
  215. $customSj = SjClass::getById($customSjId, true);
  216. $parentShopId = $customSj->parentShopId ?? 0;
  217. $introduce = [];
  218. if (!empty($parentShopId)) {
  219. $introduce = CustomClass::getByCondition(['ownShopId' => $ghsShopId, 'shopId' => $parentShopId], true);
  220. }
  221. //有新客户提醒供货商
  222. $ghsShopObj = ShopClass::getById($ghsShopId, true);
  223. $customObj = CustomClass::getById($customId, true);
  224. WxMessageClass::newGhsCustomInform($ghsShopObj, $customObj, $introduce);
  225. //新客户加入app通知
  226. //NoticeClass::newCustomNotice($ghsShop, $custom);
  227. if ($type == 1) {
  228. return $ghs;
  229. }
  230. return $custom;
  231. }
  232. //增加供货商 ssh 2021.3.29
  233. public static function addGhs($data)
  234. {
  235. return self::add($data);
  236. }
  237. /**
  238. * 判断异常是否为数据库唯一键冲突(Duplicate key / 1062 / 23000 / Integrity constraint violation)。
  239. * 干什么:为 build() 等“确保存在”幂等创建逻辑提供统一的重复键识别能力。
  240. * 为什么:项目中已大量使用普通 get+add 模式,且 MySQL 错误信息稳定,通过 message+code 识别即可,
  241. * 避免引入新 use 或依赖具体 Exception 子类(yii\db\IntegrityException 等),保持小改动。
  242. * 识别特征:code===23000 或消息包含 "Duplicate entry" / "Integrity constraint violation"。
  243. * @param \Throwable|\Exception|null $e
  244. * @return bool
  245. */
  246. protected static function isDuplicateKeyError($e)
  247. {
  248. if (empty($e)) {
  249. return false;
  250. }
  251. $msg = $e->getMessage();
  252. $code = $e->getCode();
  253. if ($code === 23000) {
  254. return true;
  255. }
  256. if (strpos($msg, 'Duplicate entry') !== false) {
  257. return true;
  258. }
  259. if (strpos($msg, 'Integrity constraint violation') !== false) {
  260. return true;
  261. }
  262. return false;
  263. }
  264. //供货商列表 ssh 2021.1.24
  265. public static function getGhsList($where)
  266. {
  267. $data = self::getList('*', $where, 'inTurn DESC,addTime ASC');
  268. $data['list'] = self::groupBaseInfo($data['list']);
  269. return $data;
  270. }
  271. //根据xhSupplier的id数组 取供货商信息 ssh 2021.1.18
  272. public static function getGhsByIds($ids)
  273. {
  274. $list = self::getByIds($ids, null, 'id');
  275. if (empty($list)) {
  276. return [];
  277. }
  278. $list = self::groupBaseInfo($list);
  279. return $list;
  280. }
  281. public static function groupBaseInfo($list)
  282. {
  283. if (empty($list)) {
  284. return $list;
  285. }
  286. $ids = array_column($list, 'shopId');
  287. $shopInfo = ShopClass::getByIds($ids, null, 'id');
  288. $mainIds = [];
  289. foreach ($shopInfo as $shop) {
  290. $mainId = $shop['mainId'] ?? 0;
  291. if (!empty($mainId)) {
  292. $mainIds[(int)$mainId] = (int)$mainId;
  293. }
  294. }
  295. $mainIds = array_values($mainIds);
  296. $founderStaffMap = [];
  297. if (!empty($mainIds)) {
  298. $founderStaffList = ShopAdminClass::getAllByCondition(
  299. ['mainId' => ['in', $mainIds], 'founder' => 2, 'delStatus' => 0],
  300. null,
  301. 'id,mainId',
  302. 'mainId',
  303. true
  304. );
  305. foreach ($founderStaffList as $mainId => $founderStaff) {
  306. //分享批发店时,通过这个员工找到相应批发店
  307. $founderStaffMap[$mainId] = intval($founderStaff->id ?? 0);
  308. }
  309. }
  310. foreach ($list as $key => $val) {
  311. $avatar = $val['avatar'] ?? '';
  312. $list[$key]['shortAvatar'] = $avatar;
  313. $list[$key]['avatar'] = imgUtil::groupImg($avatar);
  314. $list[$key]['smallAvatar'] = imgUtil::groupImg($avatar) . "?x-oss-process=image/resize,m_fill,h_80,w_80";
  315. $currentShopId = $val['shopId'] ?? 0;
  316. $currentShop = $shopInfo[$currentShopId] ?? [];
  317. //新人福利和推荐福利
  318. $xrFl = $currentShop['xrFl'] ?? 0;
  319. $xrFlAmount = $currentShop['xrFlAmount'] ?? 0;
  320. $tjFl = $currentShop['tjFl'] ?? 0;
  321. $tjFlAmount = $currentShop['tjFlAmount'] ?? 0;
  322. $list[$key]['xrFl'] = $xrFl;
  323. $list[$key]['xrFlAmount'] = $xrFlAmount;
  324. $list[$key]['tjFl'] = $tjFl;
  325. $list[$key]['tjFlAmount'] = $tjFlAmount;
  326. $list[$key]['miniKilo'] = $currentShop['miniKilo'] ?? 0;
  327. $list[$key]['kiloFee'] = $currentShop['kiloFee'] ?? 0;
  328. $list[$key]['presell'] = $currentShop['presell'] ?? 0;
  329. $isOpen = 0;
  330. if (!empty($currentShop)) {
  331. $isOpen = ShopClass::isOpen($currentShop);
  332. }
  333. //营业状态
  334. $list[$key]['isOpen'] = $isOpen;
  335. $list[$key]['openStartTime'] = $currentShop['openStartTime'] ?? '';
  336. $list[$key]['openEndTime'] = $currentShop['openEndTime'] ?? '';
  337. $list[$key]['meetNum'] = isset($currentShop['meetNum']) ? floatval($currentShop['meetNum']) : 0;
  338. $list[$key]['meetAmount'] = isset($currentShop['meetAmount']) ? floatval($currentShop['meetAmount']) : 0;
  339. $list[$key]['cutAmount'] = isset($currentShop['cutAmount']) ? floatval($currentShop['cutAmount']) : 0;
  340. $list[$key]['cutStyle'] = isset($currentShop['cutStyle']) ? floatval($currentShop['cutStyle']) : 0;
  341. $count = PurchaseClass::getCount(['ghsId' => $val['id'], 'debt' => PurchaseClass::DEBT_YES]);
  342. $list[$key]['debtNum'] = $count;
  343. $telephone = $currentShop['telephone'] ?? '';
  344. $list[$key]['telephone'] = $telephone;
  345. $telephone2 = $currentShop['telephone2'] ?? '';
  346. $list[$key]['telephone2'] = $telephone2;
  347. $balance = $val['balance'] ?? 0;
  348. $debtAmount = $val['debtAmount'] ?? 0;
  349. $remainDebtAmount = bcsub($debtAmount, $balance, 2);
  350. $list[$key]['remainDebtAmount'] = floatval($remainDebtAmount);
  351. //与花神的合作
  352. $openKmCg = $currentShop['openKmCg'] ?? 0;
  353. $kmCgAppId = $currentShop['kmCgAppId'] ?? '';
  354. $kmCgUrl = $currentShop['kmCgUrl'] ?? '';
  355. $list[$key]['openKmCg'] = $openKmCg;
  356. $list[$key]['kmCgAppId'] = $kmCgAppId;
  357. $list[$key]['kmCgUrl'] = $kmCgUrl;
  358. $pfLevel = $currentShop['pfLevel'] ?? 0;
  359. $list[$key]['pfLevel'] = $pfLevel;
  360. $mainId = $currentShop['mainId'] ?? 0;
  361. $list[$key]['ghsShopAdminId'] = !empty($mainId) ? ($founderStaffMap[$mainId] ?? 0) : 0;
  362. if (isset($val['mobile']) == false || empty($val['mobile'])) {
  363. $mobile = $currentShop['mobile'] ?? '';
  364. $list[$key]['mobile'] = $mobile;
  365. }
  366. }
  367. return $list;
  368. }
  369. //根据供货商信息 ssh 2021.1.18
  370. public static function getGhsInfo($id)
  371. {
  372. $info = self::getById($id);
  373. if (empty($info)) {
  374. return [];
  375. }
  376. $list = self::groupBaseInfo([$info]);
  377. return current($list);
  378. }
  379. //待结款列表 ssh 2021.126
  380. public static function getDebtList($where)
  381. {
  382. $sjId = $where['sjId'] ?? 0;
  383. if (empty($sjId)) {
  384. util::fail('没有找到商家');
  385. }
  386. $data = self::getList('*', $where, 'debtAmount DESC');
  387. $data['list'] = self::groupBaseInfo($data['list']);
  388. $asset = MerchantAssetClass::getBySjId($sjId);
  389. $data['debtAmount'] = $asset['cgDebtAmount'] ?? 0.00;
  390. $data['debtNum'] = $asset['cgDebtNum'] ?? 0;
  391. return $data;
  392. }
  393. //验证权限 ssh 2021.4.11
  394. public static function valid($info, $shopId)
  395. {
  396. if (empty($info)) {
  397. util::fail('没有供货商');
  398. }
  399. if ($info['ownShopId'] == $shopId) {
  400. return true;
  401. }
  402. util::fail('找不到供货商');
  403. }
  404. // 建立附近批发店关系
  405. public static function buildNearbyGhsRelations($shopId, $pfShopId, $toLat, $toLnt)
  406. {
  407. if (empty($toLat) || empty($toLnt)) {
  408. noticeUtil::push("批发关系建立失败:目标门店坐标为空,shopId={$shopId}");
  409. return false;
  410. }
  411. if (!self::isValidAmapCoordinate($toLat, $toLnt)) {
  412. noticeUtil::push("批发关系建立失败:目标门店坐标非法,shopId={$shopId},lat={$toLat},lng={$toLnt}");
  413. return false;
  414. }
  415. // 获取除虚拟外的所有批发店
  416. $nearbyShops = ShopClass::getAllByCondition(['ptStyle' => 2, 'live' => 1, 'actTime>=' => strtotime('yesterday')], null, 'id, merchantName, lat, long');
  417. if (empty($nearbyShops)) {
  418. return false;
  419. }
  420. //要排除的批发店,填门店id
  421. $exclude = [95258, 23667, 78556, 64112, 795, 1405, 28051, 62304, 42385, 56611, 38143, 15373, 42946, 15375, 15734, 15736, 15738, 15740, 24132, 29044, 29161, 30902, 44724, 48608, 48642, 82971, 38231, 1105, 3, 154, 208, 23580, 24713, 8249, 16070, 83690, 86726, 1596, 2167, 15007, 88085, 91064, 413, 62421];
  422. foreach ($nearbyShops as $key => $nearbyShop) {
  423. if (in_array($nearbyShop['id'], $exclude)) {
  424. unset($nearbyShops[$key]);
  425. }
  426. }
  427. $nearbyShopOriginPairs = [];
  428. foreach ($nearbyShops as $nearbyShop) {
  429. if ($nearbyShop['id'] == $pfShopId) {
  430. continue;
  431. }
  432. if (!empty($nearbyShop['lat']) && !empty($nearbyShop['long']) && self::isValidAmapCoordinate($nearbyShop['lat'], $nearbyShop['long'])) {
  433. $nearbyShopOriginPairs[] = [
  434. 'shop' => $nearbyShop,
  435. 'origin' => [
  436. 'lat' => $nearbyShop['lat'],
  437. 'lng' => $nearbyShop['long'],
  438. ],
  439. ];
  440. } else {
  441. // 发送钉钉通知
  442. noticeUtil::push('批发商:' . $nearbyShop['merchantName'] . '(' . $nearbyShop['id'] . ')经纬度无效,lat=' . ($nearbyShop['lat'] ?? '') . ',lng=' . ($nearbyShop['long'] ?? ''));
  443. }
  444. }
  445. if (empty($nearbyShopOriginPairs)) {
  446. return false;
  447. }
  448. // 高德批量测距接口最多支持 100 个起点,需分批处理
  449. $chunkPairs = array_chunk($nearbyShopOriginPairs, 100);
  450. $distanceShopPairs = [];
  451. foreach ($chunkPairs as $chunk) {
  452. $chunkOrigins = array_column($chunk, 'origin');
  453. $distances = \common\components\mapUtil::calculateBatchDistance($chunkOrigins, $toLnt, $toLat);
  454. if (empty($distances)) {
  455. noticeUtil::push("批发关系建立失败:高德批量测距返回空结果,shopId={$shopId}");
  456. continue;
  457. }
  458. foreach ($chunk as $index => $pair) {
  459. if (!isset($distances[$index]) || !is_numeric($distances[$index])) {
  460. continue;
  461. }
  462. $distanceShopPairs[] = [
  463. 'distance' => (float)$distances[$index],
  464. 'shop' => $pair['shop'],
  465. ];
  466. }
  467. }
  468. if (empty($distanceShopPairs)) {
  469. noticeUtil::push("批发关系建立失败:没有可用距离数据,shopId={$shopId}");
  470. return false;
  471. }
  472. // 建立关系前按距离从小到大排序
  473. usort($distanceShopPairs, function ($a, $b) {
  474. return $a['distance'] <=> $b['distance'];
  475. });
  476. // 取前6个
  477. $distanceShopPairs = array_slice($distanceShopPairs, 0, 6);
  478. // 建立关系并保存距离
  479. foreach ($distanceShopPairs as $pair) {
  480. $nearbyShop = $pair['shop'];
  481. $ghsShopId = $nearbyShop['id'];
  482. $distance = $pair['distance'] ?? 0;
  483. // 距离大于39公里不建立关系
  484. if ($distance > 39 * 1000) {
  485. continue;
  486. }
  487. // 调用 GhsClass::build 建立关系 (返回的 $ghs 包含 id 和 customId)
  488. $ghs = self::build($ghsShopId, $shopId);
  489. if (!empty($ghs) && $distance > 0) {
  490. $ghsId = $ghs['id'];
  491. $ghsName = $ghs['name'] ?? '';
  492. noticeUtil::push("建立了一个关系:ghsId:" . $ghsId . ' name:' . $ghsName);
  493. self::updateById($ghsId, ['distance' => $distance]);
  494. }
  495. }
  496. return true;
  497. }
  498. /**
  499. * 高德坐标有效性校验(仅保留中国大陆范围坐标)
  500. * @param mixed $lat
  501. * @param mixed $lng
  502. * @return bool
  503. */
  504. private static function isValidAmapCoordinate($lat, $lng)
  505. {
  506. if (!is_numeric($lat) || !is_numeric($lng)) {
  507. return false;
  508. }
  509. $lat = (float)$lat;
  510. $lng = (float)$lng;
  511. if ($lng < 72.004 || $lng > 137.8347) {
  512. return false;
  513. }
  514. if ($lat < 0.8293 || $lat > 55.8271) {
  515. return false;
  516. }
  517. return true;
  518. }
  519. }