U8Settle.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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}')",
  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. ],
  96. 'limit' => 30,
  97. ],
  98. SyncTempRecord::type_two => [// 领料申请单 材料出库----
  99. 'main' => 'MaterialAppVouch',
  100. 'detail' => 'MaterialAppVouchs',
  101. 'main_key' => 'ID',
  102. 'key' => 'ID',
  103. 'whereRaw' => "(dDate >= '{$st}')",
  104. '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'],
  105. 'son_field' => [
  106. 'detail.ID as id',
  107. // 'detail.ivouchrowno as lineNum',
  108. // 'detail.cWhCode as warehouseCode',
  109. 'detail.cInvCode as materialCode',
  110. 'detail.iQuantity as planQty',
  111. ],
  112. 'limit' => 30,
  113. ],
  114. SyncTempRecord::type_three => [// 产品报检单 产成品入库流程----- 没有仓库
  115. 'main' => 'QMINSPECTVOUCHER',
  116. 'detail' => 'QMINSPECTVOUCHERS',
  117. 'main_key' => 'ID',
  118. 'key' => 'ID',
  119. 'whereRaw' => "(DDATE >= '{$st}' and CVOUCHTYPE = 'QM02')",
  120. 'main_field' => ['ID as id','CINSPECTCODE as no','DDATE as order_date','DMAKETIME as crt_time', 'DMODIFYTIME as upd_time','CVERIFIER as reviewer'],
  121. 'son_field' => [
  122. 'detail.ID as id',
  123. 'detail.AUTOID as auto_id',
  124. 'detail.CINVCODE as materialCode',
  125. 'detail.FQUANTITY as planQty',
  126. 'detail.cDefine23',
  127. ],
  128. 'limit' => 30,
  129. ],
  130. SyncTempRecord::type_four => [// 销售订单 销售出库流程 ------- 没有仓库
  131. 'main' => 'SO_SOMain',
  132. 'detail' => 'SO_SODetails',
  133. 'main_key' => 'ID',
  134. 'key' => 'ID',
  135. 'whereRaw' => "(dDate >= '{$sa}')",
  136. 'main_field' => ['ID as id','cSOCode as no','dDate as order_date','dcreatesystime as crt_time', 'dmodifysystime as upd_time','cVerifier as reviewer'],
  137. 'son_field' => [
  138. 'detail.ID as id',
  139. 'detail.cInvCode as materialCode',
  140. 'detail.iQuantity as planQty',
  141. ],
  142. 'limit' => 30,
  143. ],
  144. SyncTempRecord::type_five => [// 其他入 其他入库流程
  145. 'main' => 'RdRecord08',
  146. 'detail' => 'RdRecords08',
  147. 'main_key' => 'ID',
  148. 'key' => 'ID',
  149. 'whereRaw' => "(dDate >= '{$st}' and COALESCE(cMemo, '') <> '接口生成')",
  150. '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'],
  151. 'son_field' => [
  152. 'detail.ID as id',
  153. 'detail.cInvCode as materialCode',
  154. 'detail.iQuantity as planQty',
  155. ],
  156. 'limit' => 30,
  157. ],
  158. SyncTempRecord::type_six => [// 销售退货单 其他入库流程
  159. 'main' => 'DispatchList',
  160. 'detail' => 'DispatchLists',
  161. 'main_key' => 'DLID',
  162. 'key' => 'DLID',
  163. 'whereRaw' => "(dDate >= '{$st}' and bReturnFlag = 1)",
  164. 'main_field' => ['DLID as id','cDLCode as no', 'dDate as order_date','dcreatesystime as crt_time', 'dmodifysystime as upd_time','cVerifier as reviewer'],
  165. 'son_field' => [
  166. 'detail.DLID as id',
  167. 'detail.cInvCode as materialCode',
  168. 'detail.cWhCode as warehouseCode',
  169. 'detail.iQuantity as planQty',
  170. 'detail.cDefine23',
  171. 'detail.cBatch',
  172. 'detail.dMDate',
  173. 'detail.iMassDate',
  174. ],
  175. 'limit' => 30,
  176. ],
  177. SyncTempRecord::type_seven => [// 其他出 其他入库流程
  178. 'main' => 'RdRecord09',
  179. 'detail' => 'RdRecords09',
  180. 'main_key' => 'ID',
  181. 'key' => 'ID',
  182. 'whereRaw' => "(dDate >= '{$st}' and COALESCE(cMemo, '') <> '接口生成')",
  183. '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'],
  184. 'son_field' => [
  185. 'detail.ID as id',
  186. 'detail.cInvCode as materialCode',
  187. 'detail.iQuantity as planQty',
  188. ],
  189. 'limit' => 30,
  190. ],
  191. SyncTempRecord::type_eight => [
  192. //检验单
  193. //cvouchtype=QM03=>采购到货单 1 来料报检单
  194. //cvouchtype=QM04=>产品检验单 2
  195. //cvouchtype=QM14=>退货检验单 3
  196. 'main' => 'QMCHECKVOUCHER',
  197. 'detail' => '',
  198. 'main_key' => 'ID',
  199. 'key' => '',
  200. 'whereRaw' => "(DDATE >= '{$st}' and (CVOUCHTYPE = 'QM03' OR CVOUCHTYPE = 'QM04'))",
  201. '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'],
  202. 'son_field' => [],
  203. 'limit' => 30,
  204. ],
  205. ];
  206. $time = time();
  207. foreach ($tasks as $name => $config) {
  208. // 用于记录本次在 U8 查到的所有单号,用来比对删除
  209. $currentU8Nos = [];
  210. $lastId = 0;
  211. $orderDateLimit = $dateMap[$name]; // 当前类型的起始日期限制
  212. $isFetchSuccess = true; // 新增:标记本次扫描是否完整
  213. while (true) {
  214. list($status, $items) = $service->getPendingBills($config, $lastId);
  215. if(! $status){
  216. $isFetchSuccess = false;
  217. Log::channel('apiLog')->error("类型 {$name} 扫描中断,跳过删除逻辑");
  218. break;
  219. }
  220. if (empty($items)) break;
  221. $nos = collect($items)->pluck('no')->toArray();
  222. $currentU8Nos = array_merge($currentU8Nos, $nos); // 记录当前存在的单号
  223. //获取这 30 条的快照
  224. $snapshots = DB::table('sync_snapshot')
  225. ->where('type', $name)
  226. ->whereIn('u8_no', $nos)
  227. ->get()
  228. ->keyBy('u8_no');
  229. foreach ($items as $item) {
  230. if ($name == SyncTempRecord::type_eight){
  231. $type_v = 0;
  232. if($item['type'] == 'QM03'){
  233. $type_v = 1;
  234. }elseif ($item['type'] == 'QM04'){
  235. $type_v = 2;
  236. }elseif ($item['type'] == 'QM14'){
  237. $type_v = 3;
  238. }
  239. $item['type'] = $type_v;
  240. }
  241. $no = $item['no'];
  242. $u8Id = $item['id']; // 抓取主表 ID
  243. $u8Upd = $item['upd_time'] ?: $item['crt_time'];
  244. $snapshot = $snapshots->get($no);
  245. $type_2 = isset($item['type']) ? $item['type'] : 0;
  246. $bool = $item['reviewer'] ? true : false;
  247. if(! $bool) continue;// 没审核跳过
  248. $opType = null;
  249. if (!$snapshot) {
  250. $opType = SyncTempRecord::opt_zero;
  251. } elseif ($u8Upd > $snapshot->last_upd_time) {
  252. $opType = SyncTempRecord::opt_one;
  253. }
  254. if ($opType !== null) {
  255. // 写入任务流水
  256. $this->createSyncTask($name, $no, $u8Id, $item, $opType, $u8Upd, $time, $type_2);
  257. }
  258. }
  259. //分页最大id
  260. $lastId = collect($items)->max('id');
  261. }
  262. $currentU8NosLookup = array_flip($currentU8Nos);
  263. //只有这次分页查询完整才启动删除
  264. if($isFetchSuccess){
  265. // 使用 chunk 配合日期过滤,只查快照中大于等于月结日期的单据
  266. DB::table('sync_snapshot')
  267. ->where('type', $name)
  268. ->where('order_date', '>=', $orderDateLimit) // 关键:缩小快照查询范围
  269. ->orderBy('u8_id')
  270. ->chunk(100, function ($snapshots) use ($currentU8NosLookup, $name, $time) {
  271. foreach ($snapshots as $oldSnapshot) {
  272. // 如果快照里的单号不在本次 U8 扫描结果里
  273. if (!isset($currentU8NosLookup[$oldSnapshot->u8_no])) {
  274. $this->createSyncTask($name, $oldSnapshot->u8_no, $oldSnapshot->u8_id, json_decode($oldSnapshot->payload, true), SyncTempRecord::opt_two, "", $time);
  275. }
  276. }
  277. });
  278. unset($currentU8Nos); // 释放内存
  279. }
  280. }
  281. }
  282. private function createSyncTask($type, $no, $u8Id, $payload, $opType, $u8Upd = "", $time, $type_2 = 0) {
  283. $record = SyncTempRecord::create([
  284. 'type' => $type,
  285. 'type_2' => $type_2,
  286. 'u8_no' => $no,
  287. 'u8_id' => $u8Id,
  288. 'payload' => json_encode($payload),
  289. 'u8_upd' => $u8Upd,
  290. 'op_type' => $opType,
  291. 'crt_time'=> $time,
  292. ]);
  293. // 只分发 ID 给队列,Job 内部再根据此 ID 取 u8_id 和 payload
  294. ProcessWMSDataJob::dispatch(['id' => $record->id])->onQueue("sync_wms_order");
  295. }
  296. private function getYjData(){
  297. //结账
  298. //采购到货单 | 退货单 bflag_PU 采购
  299. //领料申请单|产成品入库单| bflag_ST 出和入
  300. //销售发货单 销售退货 bflag_SA 销售
  301. $result = DB::connection('u8_third_sqlserver')
  302. ->table('gl_mend')
  303. ->lock('WITH(NOLOCK)')
  304. ->selectRaw("
  305. MIN(CASE WHEN bflag_PU = 0 AND iyear >= 2023 THEN iYPeriod END) as min_pu,
  306. MIN(CASE WHEN bflag_ST = 0 THEN iYPeriod END) as min_st,
  307. MIN(CASE WHEN bflag_SA = 0 THEN iYPeriod END) as min_sa
  308. ")
  309. ->whereRaw("RIGHT(CAST(iYPeriod AS VARCHAR), 2) <> '00'")
  310. ->first();
  311. // 转换成数组方便取值
  312. $minPeriods = (array)$result;
  313. $formatDate = function($period) {
  314. if (!$period) return null; // 如果没有未结账月份,返回null
  315. $period = (string)$period; // 确保是字符串
  316. $year = substr($period, 0, 4);
  317. $month = substr($period, 4, 2);
  318. return "{$year}-{$month}-01";
  319. };
  320. // 2. 执行转换
  321. $formattedPeriods = [
  322. 'pu_date' => $formatDate($minPeriods['min_pu'] ?? null),
  323. 'st_date' => $formatDate($minPeriods['min_st'] ?? null),
  324. 'sa_date' => $formatDate($minPeriods['min_sa'] ?? null),
  325. ];
  326. return $formattedPeriods;
  327. }
  328. }