U8SettleInventory.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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' => 500,
  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 ($opType !== null) {
  81. $this->createSyncTask($no, $item, $opType, $u8Ufts, $time);
  82. }
  83. }
  84. // 分页标识:取本批次最后一个编码
  85. $lastCode = end($items)['product_code'];
  86. }
  87. // --- 第二步:处理删除 ---
  88. // DB::table('sync_snapshot_product')->orderBy('code')->chunk(1000, function ($snapshots) use ($currentU8Nos, $time) {
  89. // $localNos = $snapshots->pluck('code')->toArray();
  90. // $deletedNos = array_diff($localNos, $currentU8Nos);
  91. //
  92. // if (! empty($deletedNos)) {
  93. // foreach ($deletedNos as $no) {
  94. // $this->createSyncTask($no, ['product_code' => $no], SyncTempRecordProduct::opt_two, "", $time);
  95. // }
  96. // }
  97. // });
  98. }
  99. }
  100. public function productInsert($time)
  101. {
  102. DB::table('sync_temp_records_product')
  103. ->where('crt_time', $time)
  104. ->where('status', SyncTempRecordProduct::status_zero) // 只处理待处理的数据
  105. ->orderBy('id')
  106. ->chunkById(200, function ($records) {
  107. $batchData = [];
  108. $record_ids = [];
  109. $processedItems = []; // 用于批量维护快照
  110. foreach ($records as $record) {
  111. $u8Data = is_array($record->payload)
  112. ? $record->payload
  113. : json_decode($record->payload, true);
  114. if (empty($u8Data)) continue;
  115. // 组织接口数据
  116. $batchData[] = [
  117. 'operationType' => SyncTempRecordProduct::$opMapping[$record->op_type],
  118. 'materialCode' => $u8Data['product_code'] ?? '',
  119. 'materialName' => $u8Data['product_name'] ?? '',
  120. 'materialSpec' => $u8Data['product_size'] ?? '',
  121. 'materialTypeCode' => $u8Data['product_category_code'] ?? '',
  122. 'materialTypeName' => $u8Data['product_category_name'] ?? '',
  123. 'unitCode' => $u8Data['product_unit_title'] ?? '',
  124. 'netWeight' => 0,
  125. 'grossWeight' => $u8Data['grossWeight'] ?? 0,
  126. 'lottar1' => $u8Data['param_one'] ?? 0,
  127. 'lottar2' => $u8Data['param_two'] ?? 0,
  128. ];
  129. $record_ids[] = $record->id;
  130. // 缓存这一行的数据,用于后续成功后批量写回快照
  131. $processedItems[] = [
  132. 'code' => $record->code,
  133. 'ufts' => $record->ufts,
  134. 'op_type' => $record->op_type,
  135. 'payload' => $record->payload
  136. ];
  137. }
  138. if (empty($batchData)) return;
  139. // 5. 发送数据
  140. list($status, $msg) = $this->sendToTargetSystem($batchData);
  141. if (!$status) {
  142. // 批量失败记录错误
  143. SyncTempRecordProduct::whereIn('id', $record_ids)
  144. ->update(['status' => SyncTempRecordProduct::status_two, 'error_msg' => $msg]);
  145. } else {
  146. // 批量成功更新状态
  147. SyncTempRecordProduct::whereIn('id', $record_ids)
  148. ->update(['status' => SyncTempRecordProduct::status_one]);
  149. // --- 批量维护快照表 ---
  150. foreach ($processedItems as $item) {
  151. if ($item['op_type'] == SyncTempRecordProduct::opt_two) {
  152. // 删除操作:从快照移除
  153. DB::table('sync_snapshot_product')
  154. ->where('code', $item['code'])
  155. ->delete();
  156. } else {
  157. // 新增或修改:更新/插入快照
  158. DB::table('sync_snapshot_product')->updateOrInsert(
  159. ['code' => $item['code']],
  160. [
  161. 'ufts' => $item['ufts'],
  162. 'payload' => $item['payload'],
  163. 'code' => $item['code']
  164. ]
  165. );
  166. }
  167. }
  168. }
  169. });
  170. }
  171. public function sendToTargetSystem($jsonBody){
  172. // 4. 接口路由
  173. $path = '/erp/material';
  174. $apiUrl = config('wms.api_url') . $path;
  175. // 5. 调用
  176. list($status, $result) = $this->post_helper($apiUrl, $jsonBody, ['Content-Type: application/json']);
  177. return [$status, $result];
  178. }
  179. private function createSyncTask($no, $payload, $opType, $ufts = "", $time) {
  180. SyncTempRecordProduct::create([
  181. 'code' => $no,
  182. 'payload' => json_encode($payload),
  183. 'ufts' => $ufts,
  184. 'op_type' => $opType,
  185. 'crt_time'=> $time,
  186. ]);
  187. }
  188. public function post_helper($url, $data, $header = [], $timeout = 30)
  189. {
  190. Log::channel('apiLog')->info('物料同步', ["api" => $url, "param" => $data]);
  191. $ch = curl_init();
  192. curl_setopt($ch, CURLOPT_URL, $url);
  193. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  194. curl_setopt($ch, CURLOPT_ENCODING, '');
  195. curl_setopt($ch, CURLOPT_POST, 1);
  196. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  197. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  198. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  199. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  200. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  201. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $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['msg'] ?? '未知接口错误';
  218. return [false, $msg];
  219. }
  220. }