U8SettleInventory.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Model\SyncTempRecordProduct;
  4. use App\Service\U8ThirtyPartyDatabaseServerService;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Facades\Cache;
  9. class U8SettleInventory extends Command
  10. {
  11. /**
  12. * The name and signature of the console command.
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'command:u8_settle_inventory';
  17. /**
  18. * The console command description.
  19. *
  20. * @var string
  21. */
  22. protected $description = 'Command description';
  23. /**
  24. * Create a new command instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. }
  32. public function handle()
  33. {
  34. try {
  35. $time = time();
  36. //生成需要增删改的存货数据
  37. $this->settle($time);
  38. echo '第一步完成------' . PHP_EOL;
  39. //处理存货数据
  40. $this->productInsert($time);
  41. echo '第二步完成------' . PHP_EOL;
  42. }catch (\Exception $exception){
  43. Log::channel('apiLog')->info('存货异常', ['msg' => $exception->getMessage()]);
  44. }
  45. }
  46. public function settle($time){
  47. $service = new U8ThirtyPartyDatabaseServerService();
  48. $tasks = [
  49. 'product' => [
  50. 'whereRaw' => "",
  51. 'limit' => 100,
  52. ]
  53. ];
  54. foreach ($tasks as $name => $config) {
  55. $currentU8Nos = [];
  56. $lastCode = ""; // 分页依据:存货编码
  57. while (true) {
  58. list($status, $items) = $service->getInventoryData($config, $lastCode);
  59. if (!$status || empty($items)) break;
  60. $nos = collect($items)->pluck('product_code')->toArray();
  61. $currentU8Nos = array_merge($currentU8Nos, $nos);
  62. // 获取本地快照(注意:快照表的 ufts 字段需要是字符串类型)
  63. $snapshots = DB::table('sync_snapshot_product')
  64. ->whereIn('code', $nos)
  65. ->get()
  66. ->keyBy('code');
  67. foreach ($items as $item) {
  68. $no = $item['product_code'];
  69. $u8Ufts = $item['ufts_str']; // 拿到的是 '0x000000000005AD12' 这种
  70. $snapshot = $snapshots->get($no);
  71. $opType = null;
  72. if (!$snapshot) {
  73. $opType = SyncTempRecordProduct::opt_zero;
  74. } elseif (strtolower($u8Ufts) !== strtolower($snapshot->ufts)) {
  75. $opType = SyncTempRecordProduct::opt_one;
  76. }
  77. // if (!$snapshot) {
  78. // // 本地无记录 -> 新增
  79. // $opType = SyncTempRecordProduct::opt_zero;
  80. // } elseif ($u8Ufts !== $snapshot->ufts) {
  81. // // 本地 ufts 字符串与 U8 不一致 -> 修改
  82. // $opType = SyncTempRecordProduct::opt_one;
  83. // }
  84. if ($opType !== null) {
  85. $this->createSyncTask($no, $item, $opType, $u8Ufts, $time);
  86. }
  87. }
  88. // 分页标识:取本批次最后一个编码
  89. $lastCode = end($items)['product_code'];
  90. }
  91. // --- 第二步:处理删除 ---
  92. DB::table('sync_snapshot_product')->orderBy('code')->chunk(1000, function ($snapshots) use ($currentU8Nos, $time) {
  93. $localNos = $snapshots->pluck('code')->toArray();
  94. $deletedNos = array_diff($localNos, $currentU8Nos);
  95. if (! empty($deletedNos)) {
  96. foreach ($deletedNos as $no) {
  97. $this->createSyncTask($no, ['product_code' => $no], SyncTempRecordProduct::opt_two, "", $time);
  98. }
  99. }
  100. });
  101. }
  102. }
  103. public function productInsert($time)
  104. {
  105. DB::table('sync_temp_records_product')
  106. ->where('crt_time', $time)
  107. ->where('status', SyncTempRecordProduct::status_zero) // 只处理待处理的数据
  108. ->orderBy('id')
  109. ->chunkById(100, function ($records) {
  110. $batchData = [];
  111. $record_ids = [];
  112. $processedItems = []; // 用于批量维护快照
  113. foreach ($records as $record) {
  114. $u8Data = is_array($record->payload)
  115. ? $record->payload
  116. : json_decode($record->payload, true);
  117. if (empty($u8Data)) continue;
  118. // 组织接口数据
  119. $batchData[] = [
  120. 'operationType' => SyncTempRecordProduct::$opMapping[$record->op_type],
  121. 'materialCode' => $u8Data['product_code'] ?? '',
  122. 'materialName' => $u8Data['product_name'] ?? '',
  123. 'materialSpec' => $u8Data['product_size'] ?? '',
  124. 'materialTypeCode' => $u8Data['product_category_code'] ?? '',
  125. 'materialTypeName' => $u8Data['product_category_name'] ?? '',
  126. 'unitCode' => $u8Data['product_unit_title'] ?? '',
  127. 'netWeight' => 0,
  128. 'grossWeight' => $u8Data['grossWeight'] ?? 0,
  129. ];
  130. $record_ids[] = $record->id;
  131. // 缓存这一行的数据,用于后续成功后批量写回快照
  132. $processedItems[] = [
  133. 'code' => $record->code,
  134. 'ufts' => $record->ufts,
  135. 'op_type' => $record->op_type,
  136. 'payload' => $record->payload
  137. ];
  138. }
  139. if (empty($batchData)) return;
  140. // 5. 发送数据
  141. list($status, $msg) = $this->sendToTargetSystem($batchData);
  142. if (!$status) {
  143. // 批量失败记录错误
  144. SyncTempRecordProduct::whereIn('id', $record_ids)
  145. ->update(['status' => SyncTempRecordProduct::status_two, 'error_msg' => $msg]);
  146. } else {
  147. // 批量成功更新状态
  148. SyncTempRecordProduct::whereIn('id', $record_ids)
  149. ->update(['status' => SyncTempRecordProduct::status_one]);
  150. // --- 批量维护快照表 ---
  151. foreach ($processedItems as $item) {
  152. if ($item['op_type'] == SyncTempRecordProduct::opt_two) {
  153. // 删除操作:从快照移除
  154. DB::table('sync_snapshot_product')
  155. ->where('code', $item['code'])
  156. ->delete();
  157. } else {
  158. // 新增或修改:更新/插入快照
  159. DB::table('sync_snapshot_product')->updateOrInsert(
  160. ['code' => $item['code']],
  161. [
  162. 'ufts' => $item['ufts'],
  163. 'payload' => $item['payload'],
  164. 'code' => $item['code']
  165. ]
  166. );
  167. }
  168. }
  169. }
  170. });
  171. }
  172. public function sendToTargetSystem($jsonBody){
  173. // 4. 接口路由
  174. $path = '/erp/material';
  175. $apiUrl = config('wms.api_url') . $path;
  176. // 5. 调用
  177. list($status, $result) = $this->post_helper($apiUrl, $jsonBody, ['Content-Type: application/json']);
  178. return [$status, $result];
  179. }
  180. private function createSyncTask($no, $payload, $opType, $ufts = "", $time) {
  181. SyncTempRecordProduct::create([
  182. 'code' => $no,
  183. 'payload' => json_encode($payload),
  184. 'ufts' => $ufts,
  185. 'op_type' => $opType,
  186. 'crt_time'=> $time,
  187. ]);
  188. }
  189. public function post_helper($url, $data, $header = [], $timeout = 30)
  190. {
  191. Log::channel('apiLog')->info('存货同步', ["api" => $url, "param" => $data]);
  192. $ch = curl_init();
  193. curl_setopt($ch, CURLOPT_URL, $url);
  194. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  195. curl_setopt($ch, CURLOPT_POST, 1);
  196. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  197. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  198. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  199. if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  200. $r = curl_exec($ch);
  201. if ($r === false) {
  202. $errorMessage = curl_error($ch);
  203. curl_close($ch);
  204. Log::channel('apiLog')->error('存货同步异常:WMS_CURL_ERROR', ["msg" => $errorMessage]);
  205. return [false, "网络错误: " . $errorMessage];
  206. }
  207. curl_close($ch);
  208. $return = json_decode($r, true);
  209. Log::channel('apiLog')->info('存货同步返回结果', ["res" => $return]);
  210. // 判断逻辑:code 存在且为 200 才算 true
  211. if (isset($return['code']) && $return['code'] == 200) {
  212. return [true, $return];
  213. }
  214. $msg = $return['message'] ?? '未知接口错误';
  215. return [false, $msg];
  216. }
  217. }