U8Settle.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Jobs\ProcessWMSDataJob;
  4. use App\Model\SyncTempRecord;
  5. use App\Service\U8ThirtyPartyDatabaseServerService;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Support\Facades\Redis;
  10. class U8Settle extends Command
  11. {
  12. /**
  13. * The name and signature of the console command.
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'command:u8_settle';
  18. /**
  19. * The console command description.
  20. *
  21. * @var string
  22. */
  23. protected $description = 'Command description';
  24. /**
  25. * Create a new command instance.
  26. *
  27. * @return void
  28. */
  29. public function __construct()
  30. {
  31. parent::__construct();
  32. }
  33. public function handle()
  34. {
  35. try {
  36. $this->settle();
  37. }catch (\Exception $exception){
  38. Log::channel('u8_daily')->info('单据同步异常', ['msg' => $exception->getMessage() . '|' . $exception->getLine()]);
  39. }
  40. }
  41. //array:3 [
  42. // "pu_date" => "2026-02-01"
  43. // "st_date" => "2026-02-01"
  44. // "sa_date" => "2026-02-01"
  45. //]
  46. public function settle(){
  47. $service = new U8ThirtyPartyDatabaseServerService();
  48. // $a =$service->insertUnAccountVouch('接口生成');dd($a);
  49. // $minPeriods = $this->getYjData();
  50. // if(empty($minPeriods['pu_date']) || empty($minPeriods['st_date']) || empty($minPeriods['sa_date'])) {
  51. // Log::channel('u8_daily')->info('月结数据为空', ['msg' => $minPeriods]);
  52. // return;
  53. // }
  54. $date = date("Y-m-d");
  55. if($date <= "2026-03-23") $date = date("Y-m-d", strtotime("+1 day"));
  56. $minPeriods = [
  57. 'pu_date' => $date,
  58. 'st_date' => $date,
  59. 'sa_date' => $date,
  60. ];
  61. //单据-----------------
  62. $this->orderInsert($service, $minPeriods);
  63. }
  64. public function orderInsert($service, $minPeriods){
  65. $pu = $minPeriods['pu_date'] . ' 00:00:00.000';
  66. $st = $minPeriods['st_date'] . ' 00:00:00.000';
  67. $sa = $minPeriods['sa_date'] . ' 00:00:00.000';
  68. $dateMap = [
  69. SyncTempRecord::type_one => $pu,
  70. SyncTempRecord::type_two => $st,
  71. SyncTempRecord::type_three => $st,
  72. SyncTempRecord::type_four => $sa,
  73. SyncTempRecord::type_five => $st,
  74. SyncTempRecord::type_six => $sa,
  75. SyncTempRecord::type_seven => $st,
  76. SyncTempRecord::type_eight => $st,
  77. ];
  78. // 配置不同单据的表名和字段
  79. $tasks = [
  80. SyncTempRecord::type_one => [// 采购到货 0 |退货 1
  81. 'main' => 'PU_ArrivalVouch',
  82. 'detail' => 'PU_ArrivalVouchs',
  83. 'main_key' => 'ID',
  84. 'key' => 'ID',
  85. 'whereRaw' => "(dDate >= '{$pu}' and cBusType = '普通采购')",
  86. 'main_field' => ['ID as id','cCode as no','dDate as order_date', 'cMakeTime as crt_time', 'cModifyTime as upd_time', 'iBillType as type', 'cverifier as reviewer'],
  87. 'son_field' => [
  88. 'detail.ID as id',
  89. // 'detail.ivouchrowno as lineNum',
  90. 'detail.cWhCode as warehouseCode',
  91. 'detail.cInvCode as materialCode',
  92. 'detail.iQuantity as planQty',
  93. 'detail.cDefine23',
  94. 'detail.cBatch',
  95. 'detail.bGsp', //是否检验
  96. ],
  97. 'limit' => 30,
  98. ],
  99. SyncTempRecord::type_two => [// 领料申请单 材料出库----
  100. 'main' => 'MaterialAppVouch',
  101. 'detail' => 'MaterialAppVouchs',
  102. 'main_key' => 'ID',
  103. 'key' => 'ID',
  104. 'whereRaw' => "(dDate >= '{$st}')",
  105. 'main_field' => ['ID as id','cCode as no', 'dDate as order_date', 'dnmaketime as crt_time', 'dnmodifytime as upd_time','iverifystate as state', 'cHandler as reviewer'],
  106. 'son_field' => [
  107. 'detail.ID as id',
  108. // 'detail.ivouchrowno as lineNum',
  109. // 'detail.cWhCode as warehouseCode',
  110. 'detail.cInvCode as materialCode',
  111. 'detail.iQuantity as planQty',
  112. ],
  113. 'limit' => 30,
  114. ],
  115. SyncTempRecord::type_three => [// 产品报检单 产成品入库流程----- 没有仓库
  116. 'main' => 'QMINSPECTVOUCHER',
  117. 'detail' => 'QMINSPECTVOUCHERS',
  118. 'main_key' => 'ID',
  119. 'key' => 'ID',
  120. 'whereRaw' => "(DDATE >= '{$st}' and CVOUCHTYPE = 'QM02')",
  121. 'main_field' => ['ID as id','CINSPECTCODE as no','DDATE as order_date','DMAKETIME as crt_time', 'DMODIFYTIME as upd_time','CVERIFIER as reviewer'],
  122. 'son_field' => [
  123. 'detail.ID as id',
  124. 'detail.AUTOID as auto_id',
  125. 'detail.CINVCODE as materialCode',
  126. 'detail.FQUANTITY as planQty',
  127. 'detail.cDefine23',
  128. ],
  129. 'limit' => 30,
  130. ],
  131. SyncTempRecord::type_four => [// 销售订单 销售出库流程 ------- 没有仓库
  132. 'main' => 'SO_SOMain',
  133. 'detail' => 'SO_SODetails',
  134. 'main_key' => 'ID',
  135. 'key' => 'ID',
  136. 'whereRaw' => "(dDate >= '{$sa}')",
  137. 'main_field' => ['ID as id','cSOCode as no','dDate as order_date','dcreatesystime as crt_time', 'dmodifysystime as upd_time','cVerifier as reviewer'],
  138. 'son_field' => [
  139. 'detail.ID as id',
  140. 'detail.cInvCode as materialCode',
  141. 'detail.iQuantity as planQty',
  142. ],
  143. 'limit' => 30,
  144. ],
  145. SyncTempRecord::type_five => [// 其他入 其他入库流程
  146. 'main' => 'RdRecord08',
  147. 'detail' => 'RdRecords08',
  148. 'main_key' => 'ID',
  149. 'key' => 'ID',
  150. 'whereRaw' => "(dDate >= '{$st}' and COALESCE(cMemo, '') <> '接口生成')",
  151. 'main_field' => ['ID as id','cCode as no','dDate as order_date','dnmaketime as crt_time', 'dnmodifytime as upd_time','cWhCode as warehouseCode','cHandler as reviewer'],
  152. 'son_field' => [
  153. 'detail.ID as id',
  154. 'detail.cInvCode as materialCode',
  155. 'detail.iQuantity as planQty',
  156. ],
  157. 'limit' => 30,
  158. ],
  159. SyncTempRecord::type_six => [// 销售退货单 其他入库流程
  160. 'main' => 'DispatchList',
  161. 'detail' => 'DispatchLists',
  162. 'main_key' => 'DLID',
  163. 'key' => 'DLID',
  164. 'whereRaw' => "(dDate >= '{$st}' and bReturnFlag = 1)",
  165. 'main_field' => ['DLID as id','cDLCode as no', 'dDate as order_date','dcreatesystime as crt_time', 'dmodifysystime as upd_time','cVerifier as reviewer'],
  166. 'son_field' => [
  167. 'detail.DLID as id',
  168. 'detail.cInvCode as materialCode',
  169. 'detail.cWhCode as warehouseCode',
  170. 'detail.iQuantity as planQty',
  171. 'detail.cDefine23',
  172. 'detail.cBatch',
  173. 'detail.dMDate',
  174. 'detail.iMassDate',
  175. ],
  176. 'limit' => 30,
  177. ],
  178. SyncTempRecord::type_seven => [// 其他出 其他入库流程
  179. 'main' => 'RdRecord09',
  180. 'detail' => 'RdRecords09',
  181. 'main_key' => 'ID',
  182. 'key' => 'ID',
  183. 'whereRaw' => "(dDate >= '{$st}' and COALESCE(cMemo, '') <> '接口生成')",
  184. 'main_field' => ['ID as id','cCode as no','dDate as order_date','dnmaketime as crt_time', 'dnmodifytime as upd_time','cWhCode as warehouseCode','cHandler as reviewer'],
  185. 'son_field' => [
  186. 'detail.ID as id',
  187. 'detail.cInvCode as materialCode',
  188. 'detail.iQuantity as planQty',
  189. ],
  190. 'limit' => 30,
  191. ],
  192. SyncTempRecord::type_eight => [
  193. //检验单
  194. //cvouchtype=QM03=>采购到货单 1 来料报检单
  195. //cvouchtype=QM04=>产品检验单 2
  196. //cvouchtype=QM14=>退货检验单 3
  197. 'main' => 'QMCHECKVOUCHER',
  198. 'detail' => '',
  199. 'main_key' => 'ID',
  200. 'key' => '',
  201. 'whereRaw' => "(DDATE >= '{$st}' and (CVOUCHTYPE = 'QM03' OR CVOUCHTYPE = 'QM04'))",
  202. 'main_field' => ['ID as id','CCHECKCODE as no','DDATE as order_date','DMAKETIME as crt_time', 'DMODIFYTIME as upd_time','CVERIFIER as reviewer', 'CVOUCHTYPE as type', 'CINVCODE as materialCode', 'CBATCH as lot', 'FREGQUANTITY as hg_quantity', 'FDISQUANTITY as hg_not_quantity', 'FCONQUANTIY as rb_quantity','SOURCECODE as from_order', 'CINSPECTCODE as bj_order'],
  203. 'son_field' => [],
  204. 'limit' => 30,
  205. ],
  206. ];
  207. $time = time();
  208. foreach ($tasks as $name => $config) {
  209. // 用于记录本次在 U8 查到的所有单号,用来比对删除
  210. $currentU8Nos = [];
  211. $lastId = 0;
  212. $orderDateLimit = $dateMap[$name]; // 当前类型的起始日期限制
  213. $isFetchSuccess = true; // 新增:标记本次扫描是否完整
  214. while (true) {
  215. list($status, $items) = $service->getPendingBills($config, $lastId);
  216. if(! $status){
  217. $isFetchSuccess = false;
  218. Log::channel('apiLog')->error("类型 {$name} 扫描中断,跳过删除逻辑");
  219. break;
  220. }
  221. if (empty($items)) break;
  222. $nos = collect($items)->pluck('no')->toArray();
  223. $currentU8Nos = array_merge($currentU8Nos, $nos); // 记录当前存在的单号
  224. //获取这 30 条的快照
  225. $snapshots = DB::table('sync_snapshot')
  226. ->where('type', $name)
  227. ->whereIn('u8_no', $nos)
  228. ->get()
  229. ->keyBy('u8_no');
  230. foreach ($items as $item) {
  231. if ($name == SyncTempRecord::type_eight){
  232. $type_v = 0;
  233. if($item['type'] == 'QM03'){
  234. $type_v = 1;
  235. }elseif ($item['type'] == 'QM04'){
  236. $type_v = 2;
  237. }elseif ($item['type'] == 'QM14'){
  238. $type_v = 3;
  239. }
  240. $item['type'] = $type_v;
  241. }
  242. $no = $item['no'];
  243. $u8Id = $item['id']; // 抓取主表 ID
  244. $u8Upd = $item['upd_time'] ?: $item['crt_time'];
  245. $snapshot = $snapshots->get($no);
  246. $type_2 = isset($item['type']) ? $item['type'] : 0;
  247. $bool = $item['reviewer'] ? true : false;
  248. if(! $bool) continue;// 没审核跳过
  249. $opType = null;
  250. if (!$snapshot) {
  251. $opType = SyncTempRecord::opt_zero;
  252. } elseif ($u8Upd > $snapshot->last_upd_time) {
  253. $opType = SyncTempRecord::opt_one;
  254. }
  255. if ($opType !== null) {
  256. // 写入任务流水
  257. $this->createSyncTask($name, $no, $u8Id, $item, $opType, $u8Upd, $time, $type_2);
  258. }
  259. }
  260. //分页最大id
  261. $lastId = collect($items)->max('id');
  262. }
  263. $currentU8NosLookup = array_flip($currentU8Nos);
  264. //只有这次分页查询完整才启动删除
  265. if($isFetchSuccess){
  266. // 使用 chunk 配合日期过滤,只查快照中大于等于月结日期的单据
  267. DB::table('sync_snapshot')
  268. ->where('type', $name)
  269. ->where('order_date', '>=', $orderDateLimit) // 关键:缩小快照查询范围
  270. ->orderBy('u8_id')
  271. ->chunk(100, function ($snapshots) use ($currentU8NosLookup, $name, $time) {
  272. foreach ($snapshots as $oldSnapshot) {
  273. // 如果快照里的单号不在本次 U8 扫描结果里
  274. if (!isset($currentU8NosLookup[$oldSnapshot->u8_no])) {
  275. $this->createSyncTask($name, $oldSnapshot->u8_no, $oldSnapshot->u8_id, json_decode($oldSnapshot->payload, true), SyncTempRecord::opt_two, "", $time);
  276. }
  277. }
  278. });
  279. unset($currentU8Nos); // 释放内存
  280. }
  281. }
  282. }
  283. private function createSyncTask($type, $no, $u8Id, $payload, $opType, $u8Upd = "", $time, $type_2 = 0) {
  284. $record = SyncTempRecord::create([
  285. 'type' => $type,
  286. 'type_2' => $type_2,
  287. 'u8_no' => $no,
  288. 'u8_id' => $u8Id,
  289. 'payload' => json_encode($payload),
  290. 'u8_upd' => $u8Upd,
  291. 'op_type' => $opType,
  292. 'crt_time'=> $time,
  293. ]);
  294. // 只分发 ID 给队列,Job 内部再根据此 ID 取 u8_id 和 payload
  295. ProcessWMSDataJob::dispatch(['id' => $record->id])->onQueue("sync_wms_order");
  296. }
  297. private function getYjData(){
  298. //结账
  299. //采购到货单 | 退货单 bflag_PU 采购
  300. //领料申请单|产成品入库单| bflag_ST 出和入
  301. //销售发货单 销售退货 bflag_SA 销售
  302. $result = DB::connection('u8_third_sqlserver')
  303. ->table('gl_mend')
  304. ->lock('WITH(NOLOCK)')
  305. ->selectRaw("
  306. MIN(CASE WHEN bflag_PU = 0 AND iyear >= 2023 THEN iYPeriod END) as min_pu,
  307. MIN(CASE WHEN bflag_ST = 0 THEN iYPeriod END) as min_st,
  308. MIN(CASE WHEN bflag_SA = 0 THEN iYPeriod END) as min_sa
  309. ")
  310. ->whereRaw("RIGHT(CAST(iYPeriod AS VARCHAR), 2) <> '00'")
  311. ->first();
  312. // 转换成数组方便取值
  313. $minPeriods = (array)$result;
  314. $formatDate = function($period) {
  315. if (!$period) return null; // 如果没有未结账月份,返回null
  316. $period = (string)$period; // 确保是字符串
  317. $year = substr($period, 0, 4);
  318. $month = substr($period, 4, 2);
  319. return "{$year}-{$month}-01";
  320. };
  321. // 2. 执行转换
  322. $formattedPeriods = [
  323. 'pu_date' => $formatDate($minPeriods['min_pu'] ?? null),
  324. 'st_date' => $formatDate($minPeriods['min_st'] ?? null),
  325. 'sa_date' => $formatDate($minPeriods['min_sa'] ?? null),
  326. ];
  327. return $formattedPeriods;
  328. }
  329. }