U8SettleInventory.php 9.7 KB

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