kyy
2025-07-14 fbbb2e3801dc7a1073d555278f92353d5c14ab86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
using MES.Service.Dto.webApi.RealTimeInventory;
 
namespace MESApplication.Controllers.RealTimeInventory;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
    [Route("api/[controller]")]
    [ApiController]
   
    public class RealTimeInventoryController : ControllerBase
    {
        private readonly string _connectionString;
        private readonly string _baseUrl = "http://122.227.249.70:5050/k3cloud";
 
        public RealTimeInventoryController(IConfiguration configuration)
        {
            _connectionString = configuration["AppSettings:DataBaseConn"];
        }
 
        [HttpPost("syncInventory")]
        public async Task<IActionResult> SyncInventory()
        {
            HttpClientEx httpClient = new HttpClientEx();
            httpClient.Url = $"{_baseUrl}/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
 
            var parameters = new List<object>
            {
                "6654201b47f099", // 帐套Id
                "Administrator", // 用户名
                "Lts88666*", // 密码
                2052 // 语言(中文)
            };
 
            httpClient.Content = JsonConvert.SerializeObject(parameters);
            var result = JObject.Parse(httpClient.AsyncRequest())["LoginResultType"].Value<int>();
 
            if (result != 1)
                return BadRequest("登录失败");
 
            List<string> depotCodes = FetchDepotCodes();
            if (depotCodes.Count == 0)
                return NotFound("未找到有效的DEPOTS_CODE");
 
            DeleteInventoryData();
 
            string depotCodesStr = string.Join(",", depotCodes);
            bool hasMoreData = true;
            int pageIndex = 1;
 
            while (hasMoreData)
            {
                InventoryParamModel model = new InventoryParamModel
                {
                    fstocknumbers = depotCodesStr,
                    isshowauxprop = true,
                    isshowstockloc = true,
                    pageindex = pageIndex,
                    pagerows = 10000
                };
 
                httpClient.Url = $"{_baseUrl}/Kingdee.K3.SCM.WebApi.ServicesStub.InventoryQueryService.GetInventoryData.common.kdsvc";
                httpClient.Content = JsonConvert.SerializeObject(new List<object> { model });
                string response = httpClient.AsyncRequest();
                var inventoryData = JsonConvert.DeserializeObject<InventoryResponse>(response);
 
                if (inventoryData?.Data == null || inventoryData.Data.Count == 0)
                    hasMoreData = false;
                else
                {
                    InsertInventoryData(inventoryData);
                    pageIndex++;
                }
            }
 
            return Ok("库存数据导入完成");
        }
 
        private List<string> FetchDepotCodes()
        {
            List<string> depotCodes = new List<string>();
            using (var connection = new OracleConnection(_connectionString))
            {
                try
                {
                    connection.Open();
                    string query = "SELECT DEPOTS_CODE FROM MES_INV_ITEM_STOCKS WHERE DEPOTS_CODE IS NOT NULL AND DEPOTS_CODE NOT IN ('MJ','CY-MJ') GROUP BY DEPOTS_CODE";
                    using (var cmd = new OracleCommand(query, connection))
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                            depotCodes.Add(reader.GetString(0));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取仓库代码时出错: " + ex.Message);
                }
            }
            return depotCodes;
        }
 
        private void DeleteInventoryData()
        {
            using (var connection = new OracleConnection(_connectionString))
            {
                try
                {
                    connection.Open();
                    using (var transaction = connection.BeginTransaction())
                    {
                        using (var deleteCmd = new OracleCommand("DELETE FROM ERPKCPC", connection))
                        {
                            deleteCmd.ExecuteNonQuery();
                        }
                        transaction.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("删除库存数据时出错: " + ex.Message);
                }
            }
        }
 
        private void InsertInventoryData(InventoryResponse inventoryData)
        {
            using (var connection = new OracleConnection(_connectionString))
            {
                try
                {
                    connection.Open();
                    using (var transaction = connection.BeginTransaction())
                    {
                        foreach (var item in inventoryData.Data)
                        {
                            string query = "INSERT INTO ERPKCPC (ITEM_ID, DEPOT_CODE, FQTY, ITEM_NO, ORGID) VALUES (:ITEM_ID, :DEPOT_CODE, :FQTY, :ITEM_NO, :ORGID)";
                            using (var cmd = new OracleCommand(query, connection))
                            {
                                cmd.Parameters.Add(new OracleParameter(":ITEM_ID", item.FmaterialId));
                                cmd.Parameters.Add(new OracleParameter(":DEPOT_CODE", item.FstockNumber));
                                cmd.Parameters.Add(new OracleParameter(":FQTY", item.Fqty));
                                cmd.Parameters.Add(new OracleParameter(":ITEM_NO", item.FmaterialNumber));
                                cmd.Parameters.Add(new OracleParameter(":ORGID", item.FstockorgId));
 
                                try
                                {
                                    cmd.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
                                    transaction.Rollback();
                                    Console.WriteLine("插入库存数据时出错: " + ex.Message);
                                    return;
                                }
                            }
                        }
                        transaction.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("数据库连接出错: " + ex.Message);
                }
            }
        }
    }