OrderPackageReceivedSyncService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. namespace App\Services;
  3. use App\Jobs\LogisticAliJiSuSync;
  4. use App\Jobs\LogisticSFSync;
  5. use App\Jobs\LogisticYDSync;
  6. use App\Jobs\LogisticYTOSync;
  7. use App\Jobs\LogisticZopSync;
  8. use App\OrderPackage;
  9. use Carbon\Carbon;
  10. use Exception;
  11. use Illuminate\Database\Eloquent\Collection;
  12. class OrderPackageReceivedSyncService
  13. {
  14. protected $logisticSFService;
  15. protected $logisticZopService;
  16. /**
  17. * 同步快递信息
  18. * 1 如果当前时间大于初始化时间 每日执行一次,更新order_packages中创建时间大于初始化时间,没有异常,用户未收货的全部订单的快递路由状态
  19. * 2 如果当前时间小于等于初始化时间,执行初始化脚本,将数据库中全部小于等于初始化时间的数据更新
  20. * @throws Exception
  21. */
  22. public function syncLogisticRoute($is_to_init = false)
  23. {
  24. ini_set('max_execution_time', 2 * 60 * 60);
  25. ini_set('memory_limit', '1024M');
  26. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法", '');
  27. $query = OrderPackage::query()
  28. ->select(['logistic_number', 'order_id', 'id'])
  29. ->with(['order' => function ($query) {
  30. return $query->select(['id', 'logistic_id'])->with('logistic:id,name,code');
  31. }]);
  32. if ($is_to_init) {//当前时间小于等于初始化时间
  33. $initDate = Carbon::parse(config('api_logistic.init_date'));
  34. //初始化查询一个月的数据,exception为否
  35. $query = $query->where('sent_at', '>=', $initDate)
  36. ->whereNull('received_at');
  37. } else {//查询20天以内的数据
  38. $query = $query->where('sent_at', '>=', now()->subDays(config('api_logistic.querying_days'))->startOfDay())
  39. ->whereNull('received_at');
  40. }
  41. $query->chunkById(1000, function ($orderPackages) {
  42. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法", json_encode(data_get($orderPackages, '*.logistic_number')));
  43. $logisticNumbers = $this->buildData($orderPackages);
  44. //sf
  45. if (array_key_exists('SF', $logisticNumbers)) {
  46. $SFLogisticNumbers = $logisticNumbers['SF'];
  47. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-SF", json_encode($SFLogisticNumbers));
  48. foreach ($SFLogisticNumbers as $logisticNumber) {
  49. LogService::log(OrderPackageReceivedSyncService::class, "同步SF快递单号", $logisticNumber);
  50. LogisticSFSync::dispatch($logisticNumber);
  51. }
  52. }
  53. //更新中通
  54. if (array_key_exists('ZTO', $logisticNumbers)) {
  55. $ZTOLogisticNumbers = $logisticNumbers['ZTO'];
  56. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-ZTO", json_encode($ZTOLogisticNumbers));
  57. foreach ($ZTOLogisticNumbers as $logisticNumber) {
  58. LogService::log(OrderPackageReceivedSyncService::class, "同步ZTO快递单号", $logisticNumber);
  59. LogisticZopSync::dispatch($logisticNumber);
  60. }
  61. }
  62. //更新韵达
  63. if (array_key_exists('YUNDA', $logisticNumbers)) {
  64. $YDLogisticNumbers = $logisticNumbers['YUNDA'];
  65. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YUNDA", json_encode($YDLogisticNumbers));
  66. foreach ($YDLogisticNumbers as $logistic_number) {
  67. LogService::log(OrderPackageReceivedSyncService::class, "同步YUNDA快递单号", $logisticNumber);
  68. LogisticYDSync::dispatch($logistic_number);
  69. }
  70. }
  71. //更新圆通
  72. if (array_key_exists('YTO', $logisticNumbers)) {
  73. $YTOLogisticNumbers = $logisticNumbers['YTO'];
  74. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YTO", json_encode($YTOLogisticNumbers));
  75. foreach ($YTOLogisticNumbers as $logistic_number) {
  76. if ($logistic_number)LogisticYTOSync::dispatch($logistic_number);
  77. }
  78. }
  79. });
  80. }
  81. public function syncLogisticRouteByAliJiSu()
  82. {
  83. ini_set('max_execution_time', 2 * 60 * 60);
  84. $query = OrderPackage::query()
  85. ->select(['logistic_number', 'order_id'])
  86. ->whereIn('order_id', function ($query) {
  87. $query->from('orders')->selectRaw('id')->whereIn('logistic_id', function ($builder) {
  88. $builder->from('logistics')->selectRaw('id')->where('type', '!=', '物流')->whereNotIn('belong_company', ['顺丰', '中通', '韵达', '圆通', '京东']);
  89. });
  90. });
  91. $query = $query->where('sent_at', '>=', now()->subDays(config('api_logistic.querying_days')))
  92. ->whereNull('received_at');
  93. $query->chunkById(200, function ($orderPackages) {
  94. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-阿里公用接口", json_encode($orderPackages));
  95. foreach ($orderPackages as $orderPackage) {
  96. if ($orderPackage && $orderPackage->logistic_number) LogisticAliJiSuSync::dispatch($orderPackage->logistic_number);
  97. }
  98. });
  99. $this->syncLogisticRouteJD();
  100. }
  101. public function syncLogisticRouteJD()
  102. {
  103. ini_set('max_execution_time', 60);
  104. $query = OrderPackage::query()
  105. ->select(['logistic_number', 'order_id'])
  106. ->whereIn('order_id', function ($query) {
  107. $query->from('orders')->selectRaw('id')->whereIn('logistic_id', function ($builder) {
  108. $builder->from('logistics')->selectRaw('id')->where('type', '!=', '物流')->where('belong_company', '京东');
  109. });
  110. });
  111. $query = $query->where('created_at', '>=', now()->subDays(20))
  112. ->whereNull('received_at')->where('logistic_number', 'like', 'JD%');
  113. $query->chunk(200, function ($orderPackages) {
  114. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-JD", json_encode($orderPackages));
  115. foreach ($orderPackages as $orderPackage) {
  116. if ($orderPackage && $orderPackage->logistic_number) LogisticAliJiSuSync::dispatch($orderPackage->logistic_number);
  117. }
  118. });
  119. }
  120. public function syncLogisticRouteYTO()
  121. {
  122. ini_set('max_execution_time', 120);
  123. $query = OrderPackage::query()
  124. ->select(['logistic_number', 'order_id'])
  125. ->whereIn('order_id', function ($query) {
  126. $query->from('orders')->selectRaw('id')->whereIn('logistic_id', function ($builder) {
  127. $builder->from('logistics')->selectRaw('id')->where('type', '!=', '物流')->where('belong_company', '圆通');
  128. });
  129. });
  130. $query = $query->where('sent_at', '>=', now()->subDays(20))
  131. ->whereNull('received_at');
  132. $query->chunk(1000, function ($orderPackages) {
  133. LogService::log(OrderPackageReceivedSyncService::class, "同步快递信息定时方法-YTO", json_encode($orderPackages));
  134. foreach ($orderPackages as $orderPackage) {
  135. if ($orderPackage && $orderPackage->logistic_number) LogisticYTOSync::dispatch($orderPackage->logistic_number);
  136. }
  137. });
  138. }
  139. /**
  140. * 根据传递的承运商与快递单号更新快递信息
  141. * @param array $logisticNumbers 快递单号
  142. * example: ['SF' => ['SF1038651915891', 'SF1038651413847', 'SF1038611050071'],'ZT'=>['75424148714142','548464120822', '75424147834290']....]
  143. * @throws Exception 快递接口调用或者返回的信息有误,无法更新指定的快递路由信息
  144. */
  145. public function syncLogisticRouteApi(array $logisticNumbers)
  146. {
  147. $this->update($this->getLogisticRoutes($logisticNumbers));
  148. }
  149. /**
  150. * 获取快件揽收信息
  151. * @param array $request [
  152. * 'SF' => ['SF1038651915891', 'SF1038651413847', 'SF1038611050071'],
  153. * 'ZT'=>['75424148714142','548464120822', '75424147834290']
  154. * ]
  155. * @return array
  156. * @throws Exception
  157. */
  158. public function getLogisticRoutes(array $request): array
  159. {
  160. $this->logisticSFService = new LogisticSFService();
  161. $resultSF = [];
  162. $resultYD = [];
  163. $resultYT = [];
  164. $resultOther = [];
  165. foreach ($request as $key => $logisticNums) {
  166. switch ($key) {
  167. case "SF":
  168. $resultSF = $this->logisticSFService->get($logisticNums);
  169. break;
  170. case "YD":
  171. $resultYD = [];
  172. break;
  173. case "YT":
  174. $resultYT = [];
  175. break;
  176. default:
  177. $resultOther = [];
  178. break;
  179. }
  180. }
  181. return array_merge($resultSF, $resultYD, $resultYT, $resultOther);
  182. }
  183. /**
  184. * 根据快递单号更新状态
  185. * @param array $logisticResponses
  186. */
  187. public function update(array $logisticResponses)
  188. {
  189. foreach ($logisticResponses as $logisticResponse) {
  190. if (empty($logisticResponse)) continue;
  191. $orderPackage = OrderPackage::query()->where('logistic_number', $logisticResponse['logistic_number'])->first();
  192. try {
  193. if ($orderPackage->order && $orderPackage->order->issue) {
  194. unset($logisticResponse['exception_type']);
  195. unset($logisticResponse['exception']);
  196. }
  197. } catch (Exception $e) {
  198. LogService::log(OrderPackageReceivedSyncService::class, "标记问题件不需要更新异常状态失败", $logisticResponse['logistic_number'] . '-' . json_encode($e));
  199. }
  200. //如果已经收货,将异常更新为正常
  201. if ($logisticResponse['received_at']??false) {
  202. $logisticResponse['exception_type'] = '无';
  203. $logisticResponse['exception'] = '否';
  204. }
  205. if (isset($logisticResponse['status'])) $orderPackage->status = $logisticResponse['status'];
  206. if (isset($logisticResponse['received_at'])) $orderPackage->received_at = $logisticResponse['received_at'];
  207. if (isset($logisticResponse['exception'])) $orderPackage->exception = $logisticResponse['exception'];
  208. if (isset($logisticResponse['transfer_status']) && !empty($logisticResponse['transfer_status'])) $orderPackage->transfer_status = $logisticResponse['transfer_status'];
  209. if (isset($logisticResponse['exception_type'])) $orderPackage->exception_type = $logisticResponse['exception_type'];
  210. $orderPackage->save();
  211. }
  212. }
  213. /**
  214. * 将orderPackage集合分类并摘取指定数据
  215. * @param Collection $orderPackages
  216. * @return array
  217. */
  218. private function buildData(Collection $orderPackages): array
  219. {
  220. $data = [];
  221. foreach ($orderPackages as $orderPackage) {
  222. try {
  223. $logisticCode = $orderPackage->order->logistic->code;
  224. } catch (Exception $e) {
  225. LogService::log(OrderPackageReceivedSyncService::class, "快递同步按照承运商分组异常", json_encode($orderPackage ?? []));
  226. continue;
  227. }
  228. $key = config('api_logistic.logistic.' . $logisticCode);
  229. if (!isset($data[$key])) {
  230. $data[$key] = [];
  231. }
  232. $data[$key][] = $orderPackage->logistic_number;
  233. }
  234. return $data;
  235. }
  236. /**
  237. * @param array $data
  238. * @param $lastRouteDate
  239. * @return array
  240. */
  241. public function setExceptionType(array $data, $lastRouteDate): array
  242. {
  243. //设置默认异常为否
  244. $data['exception_type'] = '无';
  245. $data['exception'] = '否';
  246. $logistic_number = $data['logistic_number'];
  247. /** @var OrderPackage $orderPackage */
  248. $orderPackage = OrderPackage::query()->with('order')->where('logistic_number', $logistic_number)->first();
  249. $delivered_duration = now()->diffInHours(Carbon::parse($orderPackage['sent_at']));
  250. $last_routed_duration = now()->diffInHours(Carbon::parse($lastRouteDate));
  251. $VALID_HOURS = 4;
  252. $SHORT_RESPONSE_HOURS = (function ($province) {
  253. switch ($province) {
  254. case '浙江省':
  255. case '江苏省':
  256. case '上海':
  257. case '安徽省':
  258. return 24;
  259. case '北京':
  260. case '天津':
  261. case '江西省':
  262. case '湖北省':
  263. case '湖南省':
  264. case '广东省':
  265. case '福建省':
  266. case '山东省':
  267. case '河北省':
  268. case '河南省':
  269. case '山西省':
  270. case '四川省':
  271. case '陕西省':
  272. case '重庆':
  273. case '广西壮族自治区':
  274. case '贵州省':
  275. case '云南省':
  276. case '海南省':
  277. case '吉林省':
  278. case '黑龙江省':
  279. case '辽宁省':
  280. return 72;
  281. case '青海省':
  282. case '宁夏回族自治区':
  283. case '甘肃省':
  284. case '内蒙古自治区':
  285. case '新疆维吾尔自治区':
  286. case '西藏自治区':
  287. return 120;
  288. default:
  289. return 24;
  290. }
  291. })($orderPackage->order->province);
  292. $LONG_RESPONSE_HOURS = (function ($province) {
  293. switch ($province) {
  294. case '浙江省':
  295. case '江苏省':
  296. case '上海':
  297. case '安徽省':
  298. return 72;
  299. case '北京':
  300. case '天津':
  301. case '江西省':
  302. case '湖北省':
  303. case '湖南省':
  304. case '广东省':
  305. case '福建省':
  306. case '山东省':
  307. case '河北省':
  308. case '河南省':
  309. case '山西省':
  310. case '四川省':
  311. case '陕西省':
  312. case '重庆':
  313. case '广西壮族自治区':
  314. case '贵州省':
  315. case '云南省':
  316. case '海南省':
  317. case '吉林省':
  318. case '黑龙江省':
  319. case '辽宁省':
  320. return 120;
  321. case '青海省':
  322. case '宁夏回族自治区':
  323. case '甘肃省':
  324. case '内蒙古自治区':
  325. case '新疆维吾尔自治区':
  326. case '西藏自治区':
  327. return 168;
  328. default:
  329. return 72;
  330. }
  331. })($orderPackage->order->province);
  332. $SENDING_RESPONSE_HOURS = 48;
  333. $HAVEN_SECOND_GOT_HOURS = 24;
  334. $IS_ROUTED = 1; //0000 0001 有路由信息
  335. $IS_IN_VALID_TIME = 2; //0000 0010 大于4小时
  336. $IS_WEIGHED = 4; //0000 0100 称重过
  337. $IS_RECEIVED = 8; //0000 1000 已经收货
  338. $IS_SENDING = 16; //0001 0000 正在派送
  339. $IS_SHORT_NO_RESPONSE = 32; //0010 0000 中转异常
  340. $IS_LONG_NO_RESPONSE = 64; //0010 0000 疑似丢件
  341. $IS_SENDING_NO_RESPONSE = 128; //0010 0000 派送异常
  342. $IS_SECOND_ROUTE_HAVE = 256; //0100 0000 揽件异常
  343. $conclusion = (function () use (
  344. $data, $delivered_duration, $last_routed_duration,
  345. $VALID_HOURS, $IS_ROUTED, $IS_IN_VALID_TIME, $IS_WEIGHED, $IS_RECEIVED, $IS_SENDING, $IS_SHORT_NO_RESPONSE, $IS_LONG_NO_RESPONSE, $IS_SENDING_NO_RESPONSE,
  346. $SHORT_RESPONSE_HOURS, $LONG_RESPONSE_HOURS, $SENDING_RESPONSE_HOURS, $HAVEN_SECOND_GOT_HOURS, $IS_SECOND_ROUTE_HAVE,
  347. $orderPackage
  348. ) {
  349. $conclusion = 0;
  350. $conclusion |= !empty($data['transfer_status']) ? $IS_ROUTED : 0;
  351. $conclusion |= ($delivered_duration > $VALID_HOURS) ? $IS_IN_VALID_TIME : 0;
  352. $conclusion |= ($orderPackage->weighed_at) ? $IS_WEIGHED : 0;
  353. $conclusion |= ($data['status'] == '已收件') ? $IS_RECEIVED : 0;
  354. $conclusion |= ($data['status'] == '派送中') ? $IS_SENDING : 0;//
  355. $conclusion |= ($last_routed_duration > $SHORT_RESPONSE_HOURS && $last_routed_duration < $LONG_RESPONSE_HOURS) ? $IS_SHORT_NO_RESPONSE : 0;
  356. $conclusion |= ($last_routed_duration > $LONG_RESPONSE_HOURS) ? $IS_LONG_NO_RESPONSE : 0;
  357. $conclusion |= ($last_routed_duration > $SENDING_RESPONSE_HOURS && $data['status'] == '派送中') ? $IS_SENDING_NO_RESPONSE : 0;
  358. $conclusion |= ($delivered_duration > $HAVEN_SECOND_GOT_HOURS && $data['routes_length'] < 3) ? $IS_SECOND_ROUTE_HAVE : 0;//和出库时间比较 超过指定时间,路由信息小于三条
  359. return $conclusion;
  360. })();
  361. switch ($conclusion) {
  362. case $IS_IN_VALID_TIME:
  363. $data['exception_type'] = '疑似库内丢件';
  364. break;
  365. case $IS_IN_VALID_TIME | $IS_WEIGHED:
  366. $data['exception_type'] = '揽件异常';
  367. break;
  368. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_SHORT_NO_RESPONSE:
  369. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_SHORT_NO_RESPONSE | $IS_WEIGHED:
  370. $data['exception_type'] = '中转异常';
  371. break;
  372. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_LONG_NO_RESPONSE:
  373. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_LONG_NO_RESPONSE | $IS_WEIGHED:
  374. $data['exception_type'] = '疑似丢件';
  375. break;
  376. default:
  377. break;
  378. }
  379. if ($conclusion
  380. == ($conclusion | $IS_ROUTED | $IS_IN_VALID_TIME | $IS_SENDING | $IS_SENDING_NO_RESPONSE)) {
  381. $data['exception_type'] = '派件异常';
  382. }
  383. if ($conclusion
  384. == ($conclusion | $IS_SECOND_ROUTE_HAVE)) {
  385. $data['exception_type'] = '揽件异常';
  386. $data['exception'] = '是';
  387. }
  388. switch ($conclusion) {
  389. case $IS_IN_VALID_TIME:
  390. case $IS_IN_VALID_TIME | $IS_WEIGHED:
  391. case $IS_ROUTED | $IS_SHORT_NO_RESPONSE:
  392. case $IS_LONG_NO_RESPONSE:
  393. $data['exception'] = '是';
  394. break;
  395. default:
  396. break;
  397. }
  398. return [
  399. 'exception_type' => array_key_exists('exception_type', $data) ? $data['exception_type'] : null,
  400. 'exception' => array_key_exists('exception', $data) ? $data['exception'] : null,
  401. ];
  402. }
  403. }