合并两个工位的 ERP 页面、存储过程及测试工具,分离 8010 与 9528 工位配置

This commit is contained in:
Developer
2026-12-05 11:30:18 +08:00
parent fffc3e9faf
commit ffb7417c24
554 changed files with 105022 additions and 156 deletions

View File

@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Web.Script.Serialization;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string ContractDraftSave = "ai_合同管理_报价转合同_保存草稿";
const string ContractDraftProof = "ai_合同管理_报价转合同_保存回执";
static decimal ContractAmount(decimal value,int places)
{
decimal result = decimal.Round(value,places,MidpointRounding.AwayFromZero);
decimal limit = places==2 ? 9999999999999999.99m : 99999999999999.9999m;
if(result<0 || result>limit) throw BadInput();
return result;
}
static void BindContractLines(SqlCommand cmd,object[] rows,decimal taxRate,JavaScriptSerializer json)
{
if(rows==null || rows.Length<1 || rows.Length>100) throw BadInput();
var table=new DataTable();
table.Columns.Add("行号",typeof(int));
table.Columns.Add("来源报价明细流水号",typeof(long));
table.Columns.Add("产品",typeof(string));
table.Columns.Add("数量",typeof(decimal));
table.Columns.Add("单位",typeof(string));
foreach(string field in new[]{"单价","未税金额","税额","含税金额"}) table.Columns.Add(field,typeof(decimal));
decimal grandTotal=0;
for(int i=0;i<rows.Length;i++) {
var row=rows[i] as Dictionary<string,object>;
if(row==null) throw BadInput();
long sourceLine=Positive(row,"sourceQuotationLineId",9007199254740991L,0);
string product=QuoteString(row,"product",500,true), unit=QuoteString(row,"unit",20,true);
decimal qty=QuoteDecimal(row,"quantity",4,99999999999999.9999m,false);
decimal price=QuoteDecimal(row,"unitPrice",4,99999999999999.9999m,true);
object amount;
decimal gross;
try {
gross=row.TryGetValue("totalAmount",out amount) && amount!=null
? QuoteDecimal(row,"totalAmount",2,9999999999999999.99m,true) : ContractAmount(qty*price*(1m+taxRate),2);
} catch(OverflowException) {throw BadInput();}
decimal net=ContractAmount(gross/(1m+taxRate),2);
decimal calculatedPrice=ContractAmount(net/qty,4);
decimal tax=gross-net;
table.Rows.Add(i+1,sourceLine,product,qty,unit,calculatedPrice,net,tax,gross);
row["lineNo"]=i+1; row["product"]=product; row["unit"]=unit; row["quantity"]=qty;
row["unitPrice"]=calculatedPrice; row["totalAmount"]=gross; row["untaxedAmount"]=net; row["taxAmount"]=tax;
row["taxRate"]=taxRate;
grandTotal+=gross;
}
ContractAmount(grandTotal,2);
AddQuoteTable(cmd,"@产品行","ai_合同管理_报价来源行",table);
cmd.Parameters.Add("@明细快照",SqlDbType.NVarChar,-1).Value=json.Serialize(rows);
}
static void BindContractDraft(SqlCommand cmd,string name,Dictionary<string,object> inputs)
{
if(name==ContractDraftProof) Only(inputs,"报价流水号","需求流水号","客户流水号","客户端请求号");
else Only(inputs,"报价流水号","需求流水号","客户流水号","原修订","客户端请求号","合同模板","提成模式","付款方式流水号","税率","交付日期","负责人","质保条款","备注","乙方资料","合同协议","产品行");
cmd.Parameters.Add("@报价流水号",SqlDbType.BigInt).Value=Positive(inputs,"报价流水号",9007199254740991L,0);
cmd.Parameters.Add("@需求流水号",SqlDbType.BigInt).Value=Positive(inputs,"需求流水号",9007199254740991L,0);
cmd.Parameters.Add("@客户流水号",SqlDbType.Int).Value=(int)Positive(inputs,"客户流水号",Int32.MaxValue,0);
Guid request;
if(!Guid.TryParseExact(Text(inputs,"客户端请求号",36,null),"D",out request) || request==Guid.Empty) throw BadInput();
cmd.Parameters.Add("@客户端请求号",SqlDbType.UniqueIdentifier).Value=request;
if(name==ContractDraftProof) return;
BindReviewVersion(cmd,inputs,"原修订");
cmd.Parameters.Add("@合同模板",SqlDbType.VarChar,30).Value=QuoteString(inputs,"合同模板",30,true);
cmd.Parameters.Add("@提成模式",SqlDbType.VarChar,40).Value=QuoteString(inputs,"提成模式",40,true);
cmd.Parameters.Add("@付款方式流水号",SqlDbType.Int).Value=(int)Positive(inputs,"付款方式流水号",Int32.MaxValue,0);
decimal tax=QuoteDecimal(inputs,"税率",6,1,true);
var taxParam=cmd.Parameters.Add("@税率",SqlDbType.Decimal);
taxParam.Scale=6; taxParam.Precision=9; taxParam.Value=tax;
DateTime delivery;
if(!DateTime.TryParseExact(Text(inputs,"交付日期",10,null),"yyyy-MM-dd",Invariant,DateTimeStyles.None,out delivery)) throw BadInput();
cmd.Parameters.Add("@交付日期",SqlDbType.Date).Value=delivery;
foreach(string field in new[]{"负责人","质保条款","备注","合同协议"}) {
int max=field=="负责人"?100:field=="合同协议"?6000:500;
cmd.Parameters.Add("@"+field,SqlDbType.NVarChar,max>4000?-1:max).Value=QuoteString(inputs,field,max,field!="备注");
}
string seller=QuoteString(inputs,"乙方资料",20000,true);
if(!(Parse(seller,false) is Dictionary<string,object>)) throw BadInput();
cmd.Parameters.Add("@乙方资料",SqlDbType.NVarChar,-1).Value=seller;
var json=new JavaScriptSerializer {MaxJsonLength=QuoteBodyLimit};
object lines;
if(!inputs.TryGetValue("产品行",out lines)) throw BadInput();
BindContractLines(cmd,lines as object[],tax,json);
string digest=QuoteFingerprint(cmd);
cmd.Parameters.Add("@请求指纹",SqlDbType.Char,64).Value=digest;
}
}
}

View File

@@ -0,0 +1,339 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Script.Serialization;
namespace Jingyao.AIEmployee
{
// 仅保留登录成功时供应商返回的员工数据,供同一应用的服务端处理程序使用。
public sealed class Employee
{
public string PersonId { get; private set; }
public string Name { get; private set; }
public string AttendanceNumber { get; private set; }
public string RoleId { get; private set; }
internal Employee(string person, string name, string attendance, string role)
{
PersonId = person;
Name = name;
AttendanceNumber = attendance;
RoleId = role;
}
internal Dictionary<string, object> ToRow()
{
return new Dictionary<string, object> {
{ "人员编号", PersonId }, { "姓名", Name }, { "考勤编号", AttendanceNumber }, { "角色编号", RoleId }
};
}
}
public static class AiEmployeeSessions
{
const string CookieName = "JY_AI_EMPLOYEE";
const string Prefix = "JY.AI.Employee.v1:";
// 凭据是 32 字节随机数,服务器缓存其摘要。重启、过期、退出后必须重新登录。
static string CacheKey(string ticket)
{
if (String.IsNullOrEmpty(ticket) || ticket.Length != 43) return null;
foreach (char c in ticket)
{
if (!(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_')) return null;
}
using (SHA256 hash = SHA256.Create())
{
return Prefix + Convert.ToBase64String(hash.ComputeHash(Encoding.ASCII.GetBytes(ticket)));
}
}
static string RequestKey(HttpContext context)
{
HttpCookie cookie = context.Request.Cookies[CookieName];
return cookie == null ? null : CacheKey(cookie.Value);
}
public static Employee RequireCurrent(HttpContext context)
{
string key = RequestKey(context);
Employee person = key == null ? null : HttpRuntime.Cache.Get(key) as Employee;
if (person == null) throw new HttpException(401, "当前员工会话已结束,请重新登录");
return person;
}
static HttpCookie Cookie(string ticket, bool secure)
{
return new HttpCookie(CookieName, ticket) {
HttpOnly = true, Secure = secure, SameSite = SameSiteMode.Strict, Path = "/submit/"
};
}
internal static void End(HttpContext context, bool secure)
{
string key = RequestKey(context);
if (key != null) HttpRuntime.Cache.Remove(key);
HttpCookie expired = Cookie("", secure);
expired.Expires = DateTime.UtcNow.AddDays(-1);
context.Response.Cookies.Set(expired);
}
internal static void Begin(HttpContext context, Employee employee, bool secure)
{
byte[] bytes = new byte[32];
using (RandomNumberGenerator generator = RandomNumberGenerator.Create()) generator.GetBytes(bytes);
string ticket = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
HttpRuntime.Cache.Insert(CacheKey(ticket), employee, null, DateTime.UtcNow.AddHours(8), Cache.NoSlidingExpiration);
context.Response.Cookies.Set(Cookie(ticket, secure));
}
}
internal sealed class ApiFailure : Exception
{
internal readonly int Status;
internal ApiFailure(int status, string message) : base(message) { Status = status; }
}
public abstract class EmployeeHandler : IHttpHandler
{
public bool IsReusable { get { return false; } }
protected abstract object Execute(HttpContext context, Dictionary<string, object> body, bool secure);
protected virtual int ResponseLimit(Dictionary<string, object> body) { return 2097152; }
protected virtual int RequestLimit(HttpContext context) { return 4096; }
internal static Uri Setting(string name)
{
Uri uri;
if (!Uri.TryCreate(ConfigurationManager.AppSettings[name], UriKind.Absolute, out uri) ||
!String.IsNullOrEmpty(uri.UserInfo) || !String.IsNullOrEmpty(uri.Query) || !String.IsNullOrEmpty(uri.Fragment) ||
(uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
throw new ApiFailure(503, "员工身份服务配置尚未就绪");
return uri;
}
internal static bool ValidateOrigin(HttpRequest request)
{
Uri origin = Setting("AiEmployee.PublicOrigin");
if (origin.AbsolutePath != "/" || (origin.Scheme != "https" && !origin.IsLoopback))
throw new ApiFailure(503, "员工身份服务访问地址配置未就绪");
// HTTPS 公网由本机反向代理终止 TLS 时,应用端只接受回环连接。
IPAddress peer;
bool loopback = IPAddress.TryParse(request.UserHostAddress, out peer) && IPAddress.IsLoopback(peer);
if (!request.IsSecureConnection && !loopback)
throw new ApiFailure(403, "请通过本站安全入口访问");
string sentOrigin = request.Headers["Origin"];
Uri source;
bool matches;
if (!String.IsNullOrEmpty(sentOrigin))
{
matches = String.Equals(sentOrigin, origin.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase);
}
else
{
matches = Uri.TryCreate(request.Headers["Referer"], UriKind.Absolute, out source) &&
String.Equals(source.GetLeftPart(UriPartial.Authority), origin.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase);
}
if (!matches || request.Headers["X-Requested-With"] != "XMLHttpRequest")
throw new ApiFailure(403, "请从当前站点访问员工身份服务");
return origin.Scheme == "https";
}
internal static string ReadText(Stream stream, int maximum, bool upstream)
{
using (MemoryStream body = new MemoryStream())
{
byte[] chunk = new byte[4096];
int count;
while ((count = stream.Read(chunk, 0, chunk.Length)) > 0)
{
if (body.Length + count > maximum)
throw new ApiFailure(upstream ? 502 : 413, upstream ? "登录服务响应超出范围" : "请求内容过大");
body.Write(chunk, 0, count);
}
return Encoding.UTF8.GetString(body.ToArray()).TrimStart('\uFEFF');
}
}
internal static object Parse(string text, bool upstream, int maximum = 2097152)
{
try { return new JavaScriptSerializer { RecursionLimit = 12, MaxJsonLength = maximum }.DeserializeObject(text); }
catch (ArgumentException) { throw InvalidJson(upstream); }
catch (InvalidOperationException) { throw InvalidJson(upstream); }
}
static ApiFailure InvalidJson(bool upstream)
{
return new ApiFailure(upstream ? 502 : 400, upstream ? "登录服务响应格式不符" : "请求数据格式不符");
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
response.ContentType = "application/json";
response.ContentEncoding = Encoding.UTF8;
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
response.Headers["X-Content-Type-Options"] = "nosniff";
response.SuppressFormsAuthenticationRedirect = true;
response.TrySkipIisCustomErrors = true;
object result;
int responseLimit = 2097152;
try
{
HttpRequest request = context.Request;
if (request.HttpMethod != "POST") throw new ApiFailure(405, "请使用 POST 请求");
if (request.QueryString.Count != 0) throw InvalidJson(false);
if (!String.Equals((request.ContentType ?? "").Split(';')[0].Trim(), "application/json", StringComparison.OrdinalIgnoreCase))
throw new ApiFailure(415, "请发送 JSON 数据");
bool secure = ValidateOrigin(request);
int requestLimit = RequestLimit(context);
var body = Parse(ReadText(request.InputStream, requestLimit, false), false, requestLimit) as Dictionary<string, object>;
if (body == null) throw InvalidJson(false);
result = Execute(context, body, secure);
responseLimit = ResponseLimit(body);
}
catch (ApiFailure error) { response.StatusCode = error.Status; result = new { message = error.Message }; }
catch (HttpException error)
{
if (error.GetHttpCode() == 401)
{
response.StatusCode = 401;
result = new { message = "当前员工会话已结束,请重新登录" };
}
else { response.StatusCode = 503; result = new { message = "员工身份服务暂时不可用" }; }
}
catch (Exception) { response.StatusCode = 503; result = new { message = "员工身份服务暂时不可用" }; }
response.Write(new JavaScriptSerializer { MaxJsonLength = responseLimit }.Serialize(result));
}
protected static void NoParameters(Dictionary<string, object> body)
{
if (body.Count != 0) throw new ApiFailure(400, "此项操作无需输入参数");
}
}
public sealed class CurrentHandler : EmployeeHandler
{
protected override object Execute(HttpContext context, Dictionary<string, object> body, bool secure)
{
NoParameters(body);
return new { data = AiEmployeeSessions.RequireCurrent(context).ToRow() };
}
}
public sealed class LogoutHandler : EmployeeHandler
{
protected override object Execute(HttpContext context, Dictionary<string, object> body, bool secure)
{
NoParameters(body);
AiEmployeeSessions.End(context, secure);
return new { data = true };
}
}
public sealed class LoginHandler : EmployeeHandler
{
static string Credential(Dictionary<string, object> body, string field, int max)
{
object value;
string s = body.TryGetValue(field, out value) ? value as string : null;
// 供应商的 type=1 接口用 & 分隔字段。
if (String.IsNullOrWhiteSpace(s) || s.Length > max || s.IndexOf('&') >= 0 ||
s.IndexOf('=') >= 0 || s.IndexOfAny(new [] { '\r', '\n', '\0' }) >= 0)
throw new ApiFailure(400, "账号或密码格式不符合登录接口要求");
return s;
}
static object Authenticate(string username, string password)
{
Uri endpoint = Setting("AiEmployee.LoginEndpoint");
if (!endpoint.AbsolutePath.EndsWith("/submit/MESCommonBase.ashx", StringComparison.OrdinalIgnoreCase))
throw new ApiFailure(503, "供应商登录地址配置未就绪");
if (endpoint.Scheme == Uri.UriSchemeHttp && !endpoint.IsLoopback &&
!(endpoint.Host == "192.168.1.27" && endpoint.Port == 8030))
throw new ApiFailure(503, "登录服务需使用 HTTPS 或已配置的本机通讯服务");
var payload = new { type = "1", name = "菜单系统模块_用户名密码_查询数据_new2", param = "用户名=" + username + "&密码=" + password };
byte[] bytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(payload));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Proxy = null;
request.UseDefaultCredentials = false;
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = bytes.Length;
request.Timeout = 15000;
request.ReadWriteTimeout = 15000;
try
{
using (Stream stream = request.GetRequestStream()) stream.Write(bytes, 0, bytes.Length);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK) throw new ApiFailure(502, "登录服务暂时不可用");
using (Stream input = response.GetResponseStream()) return Parse(ReadText(input, 65536, true), true);
}
}
catch (WebException error)
{
if (error.Response != null) error.Response.Close();
throw new ApiFailure(502, "暂时无法连接登录服务");
}
}
static string Field(Dictionary<string, object> row, string key, int max)
{
object value;
if (!row.TryGetValue(key, out value) || value == null || !(value is string || value is int || value is long || value is decimal))
throw new ApiFailure(502, "登录服务返回的人员资料不完整");
string text = Convert.ToString(value, CultureInfo.InvariantCulture).Trim();
if (text.Length == 0 || text.Length > max) throw new ApiFailure(502, "登录服务返回的人员资料不完整");
return text;
}
static string NumericId(Dictionary<string, object> row, string key)
{
int value;
if (!Int32.TryParse(Field(row, key, 12), NumberStyles.None, CultureInfo.InvariantCulture, out value) || value <= 0)
throw new ApiFailure(502, "登录服务返回的人员或角色编号无效");
return value.ToString(CultureInfo.InvariantCulture);
}
protected override object Execute(HttpContext context, Dictionary<string, object> body, bool secure)
{
AiEmployeeSessions.End(context, secure);
if (body.Count != 2) throw new ApiFailure(400, "请提交登录账号和密码");
object upstream = Authenticate(Credential(body, "username", 128), Credential(body, "password", 256));
var denial = upstream as Dictionary<string, object>;
object flag;
if (denial != null && denial.TryGetValue("result", out flag) && Convert.ToString(flag) == "0")
throw new ApiFailure(401, "账号或密码错误");
var records = upstream as object[];
if (records == null || records.Length > 128) throw new ApiFailure(502, "登录服务返回的数据格式不符");
if (records.Length == 0) throw new ApiFailure(401, "账号或密码错误");
var allowed = new List<Dictionary<string, object>>();
Employee first = null;
foreach (object record in records)
{
var row = record as Dictionary<string, object>;
if (row == null) throw new ApiFailure(502, "登录服务返回的数据格式不符");
if (row.TryGetValue("result", out flag) && Convert.ToString(flag) == "0") throw new ApiFailure(401, "账号或密码错误");
var employee = new Employee(NumericId(row, "人员编号"), Field(row, "姓名", 150),
Field(row, "考勤编号", 128), NumericId(row, "角色编号"));
if (first == null) first = employee;
else if (first.PersonId != employee.PersonId || first.AttendanceNumber != employee.AttendanceNumber || first.Name != employee.Name)
throw new ApiFailure(502, "登录结果没有唯一对应到一名员工");
var safe = employee.ToRow();
safe["session_id"] = Field(row, "session_id", 4000);
allowed.Add(safe);
}
AiEmployeeSessions.Begin(context, first, secure);
return allowed;
}
}
}

View File

@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string LegacyList = "ai_旧订单商务与回款核验";
const string LegacySource = LegacyList + "_商务来源", LegacyCash = LegacyList + "_回款记录", LegacyFinance = LegacyList + "_财务决定";
const string LegacyRegister = LegacySource + "_登记", LegacyVerify = LegacyCash + "_登记核验", LegacyDecide = LegacyFinance + "_登记";
static bool LegacyWrite(string name) { return name == LegacyRegister || name == LegacyVerify || name == LegacyDecide; }
static bool IsLegacy(string name)
{
return name == LegacyList || name == LegacySource || name == LegacyCash || name == LegacyFinance || LegacyWrite(name);
}
static void LegacyVersion(SqlCommand command, Dictionary<string,object> fields, string key)
{
string value = Text(fields,key,64,null);
if (!Revision.IsMatch(value)) throw BadInput();
command.Parameters.Add("@" + key,SqlDbType.VarChar,64).Value = value;
}
static void LegacyAmount(SqlCommand command, Dictionary<string,object> fields, string key)
{
string value = Text(fields,key,19,null);
if (!Regex.IsMatch(value,@"\A(?:0|[1-9][0-9]{0,15})(?:\.[0-9]{1,2})?\z")) throw BadInput();
command.Parameters.Add("@" + key,SqlDbType.VarChar,19).Value = value;
}
static void BindLegacy(SqlCommand command, string name, Dictionary<string,object> inputs, Dictionary<string,object> body)
{
if (name == LegacyList) {
Only(inputs,"关键字");
AddText(command,inputs,"关键字",100,"");
command.Parameters.Add("@页码",SqlDbType.Int).Value = (int)Positive(body,"pageList",100000,1);
command.Parameters.Add("@每页条数",SqlDbType.Int).Value = (int)Positive(body,"pageSize",100,20);
return;
}
command.Parameters.Add("@旧项目流水号", SqlDbType.Int).Value = (int)Positive(inputs,"旧项目流水号",Int32.MaxValue,0);
if (name == LegacySource || name == LegacyRegister) {
ReworkKey(command,inputs,"装配计划流水号"); ReworkKey(command,inputs,"旧订单装配基线流水号");
} else ReworkKey(command,inputs,"商务承接流水号");
if (name == LegacyRegister || name == LegacyFinance || name == LegacyDecide)
command.Parameters.Add("@旧订单流水号",SqlDbType.Int).Value = (int)Positive(inputs,"旧订单流水号",Int32.MaxValue,0);
if (!LegacyWrite(name)) {
if (name == LegacySource) Only(inputs,"装配计划流水号","旧订单装配基线流水号","旧项目流水号");
else if (name == LegacyFinance) Only(inputs,"商务承接流水号","旧项目流水号","旧订单流水号");
else Only(inputs,"商务承接流水号","旧项目流水号");
return;
}
if (body.ContainsKey("pageList") || body.ContainsKey("pageSize")) throw BadInput();
if (inputs.ContainsKey("预期前版流水号")) ReworkKey(command,inputs,"预期前版流水号");
else command.Parameters.Add("@预期前版流水号",SqlDbType.BigInt).Value = DBNull.Value;
string statement;
if (name == LegacyRegister) {
Only(inputs,"装配计划流水号","旧订单装配基线流水号","旧订单流水号","旧项目流水号","组件流水号","预期制造来源版本",
"预期商务来源版本","预期前版流水号","金额口径","合同金额文本","合同依据来源","收货地址","收货联系人","收货联系电话","商务确认依据","幂等键");
command.Parameters.Add("@组件流水号",SqlDbType.Int).Value = (int)Positive(inputs,"组件流水号",Int32.MaxValue,0);
LegacyVersion(command,inputs,"预期制造来源版本"); LegacyVersion(command,inputs,"预期商务来源版本");
AddText(command,inputs,"金额口径",20,null,"TAX_INCLUDED","TAX_EXCLUDED");
LegacyAmount(command,inputs,"合同金额文本");
AddText(command,inputs,"合同依据来源",30,null,"LEGACY_REVISION","LEGACY_HEADER");
AddText(command,inputs,"收货地址",300,null); AddText(command,inputs,"收货联系人",100,null);
AddText(command,inputs,"收货联系电话",100,null); AddText(command,inputs,"商务确认依据",1000,null);
statement = "REGISTER_LEGACY_COMMERCIAL_SNAPSHOT_NOT_RELEASE";
} else if (name == LegacyVerify) {
Only(inputs,"商务承接流水号","旧项目流水号","旧收款记录流水号","预期旧记录版本","预期前版流水号","核验结论","核验金额文本","核验依据","幂等键");
command.Parameters.Add("@旧收款记录流水号",SqlDbType.Int).Value = (int)Positive(inputs,"旧收款记录流水号",Int32.MaxValue,0);
LegacyVersion(command,inputs,"预期旧记录版本");
AddText(command,inputs,"核验结论",20,null,"CONFIRMED","REJECTED");
if (Text(inputs,"核验结论",20,null) == "CONFIRMED") LegacyAmount(command,inputs,"核验金额文本");
else if (inputs.ContainsKey("核验金额文本")) throw BadInput();
else command.Parameters.Add("@核验金额文本",SqlDbType.VarChar,19).Value = DBNull.Value;
AddText(command,inputs,"核验依据",1000,null); statement = "VERIFY_LEGACY_CASH_EVIDENCE_NOT_SHIPMENT_RELEASE";
} else {
Only(inputs,"商务承接流水号","旧订单流水号","旧项目流水号","预期商务来源版本","预期回款证据版本","预期前版流水号","结论","复核意见","幂等键");
LegacyVersion(command,inputs,"预期商务来源版本"); LegacyVersion(command,inputs,"预期回款证据版本");
AddText(command,inputs,"结论",20,null,"APPROVED","REJECTED"); AddText(command,inputs,"复核意见",1000,null);
statement = Text(inputs,"结论",20,null) == "APPROVED" ? "APPROVE_LEGACY_SHIPMENT_FINANCE_ONLY" : "REJECT_LEGACY_SHIPMENT_FINANCE_ONLY";
}
command.Parameters.Add("@确认声明",SqlDbType.NVarChar,100).Value = statement;
BindIdempotency(command,inputs);
}
static void LegacyMoney(Dictionary<string,object> row)
{
foreach (string key in new[] {"原记录数量","待核验数量","来源丢失数量"}) {
object count;
if (!row.TryGetValue(key,out count)) continue;
int value;
if (!Int32.TryParse(Convert.ToString(count,Invariant),out value) || value < 0) throw Unavailable();
row[key] = value;
}
foreach (string key in new[] {"合同金额","核验金额","已核验回款合计"}) {
object value;
if (!row.TryGetValue(key,out value)) continue;
if (value != null && (!(value is decimal) || (decimal)value < 0 || Decimal.Round((decimal)value,2) != (decimal)value)) throw Unavailable();
row[key + "文本"] = value == null ? null : ((decimal)value).ToString("0.00",Invariant);
}
object approximate;
if (row.TryGetValue("原金额",out approximate))
row["原金额近似文本"] = approximate == null ? null : Convert.ToDouble(approximate,Invariant).ToString("R",Invariant);
}
static object ReadLegacy(SqlCommand command, string name, SqlDataReader reader)
{
if (name == LegacyList) return ReadPageWithSummary(command, reader, false);
var first = ReadRows(reader,1);
if (first.Count != 1) throw Unavailable();
LegacyMoney(first[0]);
if (LegacyWrite(name)) {
if (reader.NextResult()) throw Unavailable();
return new { rows = first };
}
var second = NextRows(reader,name == LegacyCash ? Int32.MaxValue : 1);
foreach (var row in second) LegacyMoney(row);
if (name == LegacyCash) {
var summary = NextRows(reader,1);
if (summary.Count != 1 || reader.NextResult()) throw Unavailable();
LegacyMoney(summary[0]);
return new { source = first[0], records = second, summary = summary[0] };
}
if (reader.NextResult()) throw Unavailable();
if (name == LegacySource) return new { source = first[0], registration = second.Count == 0 ? null : second[0] };
return new { source = first[0], decision = second.Count == 0 ? null : second[0] };
}
}
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string DraftList = "ai_外协单位与加工草稿";
const string DraftDetail = DraftList + "_草稿详情";
const string DraftSave = DraftDetail + "_保存";
const string DraftRehearsal = DraftList + "_软件演练";
static bool IsDraft(string name)
{
return name == DraftList || name == DraftDetail || name == DraftSave || name == DraftRehearsal;
}
static void BindIdempotency(SqlCommand command, Dictionary<string,object> inputs)
{
string key = Text(inputs, "幂等键", 100, null);
if (!Regex.IsMatch(key, @"\A[A-Za-z0-9_.:-]+\z")) throw BadInput();
command.Parameters.Add("@幂等键", SqlDbType.VarChar, 100).Value = key;
string fingerprint = RequestFingerprint(command);
command.Parameters.Add("@请求指纹", SqlDbType.Char, 64).Value = fingerprint;
}
static int DraftNumber(Dictionary<string,object> inputs, string field, bool allowZero)
{
object value;
if (allowZero && inputs.TryGetValue(field, out value) &&
(Object.Equals(value, 0) || Object.Equals(value,"0"))) return 0;
return (int)Positive(inputs, field, Int32.MaxValue, 0);
}
static void BindDraft(SqlCommand command, string name, Dictionary<string,object> inputs, Dictionary<string,object> body)
{
if (name == DraftRehearsal) { Only(inputs); return; }
AddText(command, inputs, "类型", 10, null, "vendor", "process");
if (name == DraftList) {
Only(inputs, "类型");
command.Parameters.Add("@页码", SqlDbType.Int).Value = (int)Positive(body, "pageList", 100000, 1);
command.Parameters.Add("@每页条数", SqlDbType.Int).Value = (int)Positive(body, "pageSize", 200, 25);
return;
}
bool save = name == DraftSave;
command.Parameters.Add("@编号", SqlDbType.Int).Value = DraftNumber(inputs,"编号",save);
command.Parameters.Add("@版本", SqlDbType.Int).Value = DraftNumber(inputs,"版本",save);
if (!save) { Only(inputs,"类型","编号","版本"); return; }
Only(inputs, "类型","编号","版本","资料XML","幂等键");
if (body.ContainsKey("pageList") || body.ContainsKey("pageSize")) throw BadInput();
string xml = Text(inputs, "资料XML", 12000, null);
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 12000 };
try {
using (var reader = XmlReader.Create(new StringReader(xml), settings)) {
if (reader.MoveToContent() != XmlNodeType.Element || reader.Name != "draft") throw BadInput();
while (reader.Read()) { }
}
} catch (XmlException) { throw BadInput(); }
command.Parameters.Add("@资料XML", SqlDbType.NVarChar, -1).Value = xml;
BindIdempotency(command, inputs);
}
static object ReadDraft(SqlCommand command, string name, SqlDataReader reader)
{
if (name == DraftList) return ReadPageWithSummary(command, reader, false);
if (name == DraftDetail) {
var records = ReadRows(reader, 1);
var checks = NextRows(reader, 64);
if (records.Count != 1 || checks.Count == 0 || reader.NextResult()) throw Unavailable();
return new { record = records[0], checks = checks };
}
int expected = name == DraftSave ? 1 : 7;
var rows = ReadRows(reader, expected);
if (rows.Count != expected || reader.NextResult()) throw Unavailable();
return new { rows = rows };
}
}
}

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string PayableList = "ai_采购与应付来源核对";
const string PayableDetail = "ai_采购与应付来源核对_来源单详情";
const string PayableSuppliers = "ai_采购与应付来源核对_来源单详情_供应商查询";
const string PayableConfirm = "ai_采购与应付来源核对_来源单详情_确认接管";
static bool IsPayableSource(string name)
{
return name == PayableList || name == PayableDetail || name == PayableSuppliers || name == PayableConfirm;
}
static void PayableVersion(SqlCommand command, Dictionary<string, object> inputs, string field)
{
string version = Text(inputs, field, 16, null);
if (!Regex.IsMatch(version, @"\A[0-9A-Fa-f]{16}\z")) throw BadInput();
command.Parameters.Add("@" + field, SqlDbType.VarChar, 16).Value = version.ToUpperInvariant();
}
static void BindPayableSource(SqlCommand command, string name, Dictionary<string,object> inputs, Dictionary<string,object> body)
{
if (name == PayableList || name == PayableSuppliers) {
if (name == PayableList) {
Only(inputs, "来源类型", "状态", "关键字");
AddText(command, inputs, "来源类型", 20, null, "PURCHASE_ORDER", "PAYABLE");
AddText(command, inputs, "状态", 12, null, "PENDING", "CONFIRMED", "ALL");
} else Only(inputs, "关键字");
AddText(command, inputs, "关键字", 100, "");
command.Parameters.Add("@页码", SqlDbType.Int).Value = (int)Positive(body, "pageList", 100000, 1);
command.Parameters.Add("@每页条数", SqlDbType.Int).Value = (int)Positive(body, "pageSize", 200, 20);
return;
}
AddText(command, inputs, "来源类型", 20, null, "PURCHASE_ORDER", "PAYABLE");
command.Parameters.Add("@来源流水号", SqlDbType.Int).Value = (int)Positive(inputs, "来源流水号", Int32.MaxValue, 0);
if (name == PayableDetail) {
Only(inputs, "来源类型", "来源流水号");
return;
}
if (name != PayableConfirm || body.ContainsKey("pageList") || body.ContainsKey("pageSize")) throw BadInput();
Only(inputs, "来源类型", "来源流水号", "供应商流水号", "预期版本", "关联订单预期版本", "接管依据", "幂等键");
command.Parameters.Add("@供应商流水号", SqlDbType.Int).Value = (int)Positive(inputs, "供应商流水号", Int32.MaxValue, 0);
PayableVersion(command, inputs, "预期版本");
if ((string)command.Parameters["@来源类型"].Value == "PAYABLE") PayableVersion(command, inputs, "关联订单预期版本");
else if (inputs.ContainsKey("关联订单预期版本")) throw BadInput();
AddText(command, inputs, "接管依据", 1000, null);
string key = Text(inputs, "幂等键", 100, null);
if (!Regex.IsMatch(key, @"\A[A-Za-z0-9_.:-]+\z")) throw BadInput();
command.Parameters.Add("@幂等键", SqlDbType.VarChar, 100).Value = key;
string fingerprint = RequestFingerprint(command);
command.Parameters.Add("@请求指纹", SqlDbType.Char, 64).Value = fingerprint;
}
static object ReadPayableSource(SqlCommand command, string name, SqlDataReader reader)
{
if (name == PayableList || name == PayableSuppliers) return ReadPageWithSummary(command, reader, false);
var header = ReadRows(reader, 1);
if (name == PayableConfirm) {
if (header.Count != 1 || reader.NextResult()) throw Unavailable();
return new { rows = header };
}
var audit = NextRows(reader, Int32.MaxValue);
if (reader.NextResult() || (header.Count == 0 && audit.Count != 0)) throw Unavailable();
return new { record = header.Count == 0 ? null : header[0], audit = audit };
}
}
}

View File

@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string PaymentHome = "ai_供应商付款与核销";
static readonly Dictionary<string,string> PaymentModes = new Dictionary<string,string>(StringComparer.Ordinal) {
{PaymentHome, "LIST"}, {PaymentHome+"_付款详情", "DETAIL"}, {PaymentHome+"_办理历史", "HISTORY"},
{PaymentHome+"_办理历史_原始回执", "RECEIPT"}, {PaymentHome+"_付款登记_供应商查询", "SUPPLIERS"},
{PaymentHome+"_分次核销_应付单查询", "PAYABLES"}, {PaymentHome+"_本人原请求", "LOOKUP"}, {PaymentHome+"_付款登记_凭证查询","VOUCHERS"},
{PaymentHome+"_付款登记_提交", "REGISTER"}, {PaymentHome+"_付款审批_复核", "REVIEW"},
{PaymentHome+"_分次核销_提交", "ALLOCATE"}, {PaymentHome+"_本人原请求_核对", "INSPECT"},
{PaymentHome+"_本人原请求_关闭", "CLOSE_UNCOMMITTED"}, {PaymentHome+"_本人原请求_收讫", "ACK"}
};
static bool IsPaymentJournal(string name) { return PaymentModes.ContainsKey(name); }
static bool IsPaymentJournalWrite(string name)
{
string mode;
return PaymentModes.TryGetValue(name,out mode) && (mode=="REGISTER" || mode=="REVIEW" || mode=="ALLOCATE" || mode=="CLOSE_UNCOMMITTED" || mode=="ACK");
}
static bool PaymentPaged(string mode) { return mode=="LIST" || mode=="HISTORY" || mode=="SUPPLIERS" || mode=="PAYABLES" || mode=="VOUCHERS"; }
static bool PaymentLedger(string mode) { return PaymentPaged(mode) || mode=="DETAIL" || mode=="RECEIPT"; }
static void BindPaymentJournal(SqlCommand command,string name,Dictionary<string,object> inputs,Dictionary<string,object> body)
{
string mode=PaymentModes[name];
if (!PaymentPaged(mode) && (body.ContainsKey("pageList") || body.ContainsKey("pageSize"))) throw BadInput();
if (mode=="LOOKUP") { Only(inputs); return; }
if (PaymentLedger(mode)) {
if (mode=="LIST" || mode=="VOUCHERS") {
if (mode=="LIST") {
Only(inputs,"状态","供应商流水号","关键字");
AddText(command,inputs,"状态",9,"ALL","ALL","PENDING","CONFIRMED","REJECTED");
} else Only(inputs,"供应商流水号","关键字");
object supplier;
if(inputs.TryGetValue("供应商流水号",out supplier) && supplier!=null && !Object.Equals(supplier,""))
command.Parameters.Add("@供应商流水号",SqlDbType.Int).Value=(int)Positive(inputs,"供应商流水号",Int32.MaxValue,0);
} else if (mode=="SUPPLIERS") Only(inputs,"关键字");
else {
if(mode=="PAYABLES") Only(inputs,"付款流水号","关键字");
else if(mode=="RECEIPT") Only(inputs,"付款流水号","审计流水号");
else Only(inputs,"付款流水号");
command.Parameters.Add("@付款流水号",SqlDbType.BigInt).Value=Positive(inputs,"付款流水号",Int64.MaxValue,0);
if(mode=="RECEIPT") command.Parameters.Add("@审计流水号",SqlDbType.BigInt).Value=Positive(inputs,"审计流水号",Int64.MaxValue,0);
}
if (mode=="LIST" || mode=="SUPPLIERS" || mode=="PAYABLES" || mode=="VOUCHERS") AddText(command,inputs,"关键字",100,"");
if (PaymentPaged(mode)) {
command.Parameters.Add("@页码",SqlDbType.Int).Value=(int)Positive(body,"pageList",10000,1);
command.Parameters.Add("@每页条数",SqlDbType.Int).Value=(int)Positive(body,"pageSize",100,20);
}
return;
}
Only(inputs,"原请求");
object raw;
if(!inputs.TryGetValue("原请求",out raw) || !(raw is Dictionary<string,object>)) throw BadInput();
var original=(Dictionary<string,object>)raw;
string actor=Convert.ToString(command.Parameters["@人员编号"].Value,Invariant);
try {
using (var bound=new SqlCommand()) {
if(mode=="ACK") FinancePaymentInboxRequest.BindRecovery(bound,original,actor,true);
else if(mode=="INSPECT" || mode=="CLOSE_UNCOMMITTED") {
if(Text(original,"mode",17,null)!=mode) throw BadInput();
FinancePaymentInboxRequest.BindResolution(bound,original,actor);
} else FinancePaymentInboxRequest.BindWrite(bound,mode,original,actor);
foreach(SqlParameter p in bound.Parameters) {
if(p.ParameterName=="@操作人" || p.ParameterName=="@模式") continue;
command.Parameters.Add((SqlParameter)((ICloneable)p).Clone());
}
}
} catch(ArgumentException) { throw BadInput(); }
}
static DataSet PaymentSets(SqlDataReader reader)
{
var result=new DataSet();
do {
if(result.Tables.Count>=3) throw Unavailable();
var table=new DataTable();
for(int i=0;i<reader.FieldCount;i++) table.Columns.Add(reader.GetName(i),reader.GetFieldType(i));
while(reader.Read()) {
if(table.Rows.Count>=200) throw Unavailable();
var values=new object[reader.FieldCount]; reader.GetValues(values); table.Rows.Add(values);
}
result.Tables.Add(table);
} while(reader.NextResult());
return result;
}
static Dictionary<string,object> PaymentRow(DataRow row)
{
var result=new Dictionary<string,object>();
foreach(DataColumn c in row.Table.Columns) {
object v=row[c];
if(v==DBNull.Value) v=null;
else if(v is DateTime) v=((DateTime)v).ToString("yyyy-MM-dd HH:mm:ss",Invariant);
result.Add(c.ColumnName,v);
}
return result;
}
static List<Dictionary<string,object>> PaymentRows(DataTable table)
{
var rows=new List<Dictionary<string,object>>();
foreach(DataRow r in table.Rows) rows.Add(PaymentRow(r)); return rows;
}
static Dictionary<string,object> PaymentProof(SqlCommand command,DataTable header,DataTable allocations,bool replay)
{
if(header.Rows.Count!=1) throw Unavailable();
DataRow r=header.Rows[0];
string actor=Convert.ToString(command.Parameters["@人员编号"].Value,Invariant);
string action=(string)command.Parameters["@动作"].Value;
if((string)r["动作"]!=action || (string)r["操作人"]!=actor || (string)r["幂等键"]!=(string)command.Parameters["@幂等键"].Value ||
(string)r["策略版本"]!=FinancePaymentJournalPolicy.Version || (action=="ALLOCATE")!=(allocations.Rows.Count>0) ||
(replay && !(bool)r["是否幂等返回"])) throw Unavailable();
return new Dictionary<string,object> {{"record",PaymentRow(r)},{"idempotent",(bool)r["是否幂等返回"]},{"allocations",PaymentRows(allocations)}};
}
static object ReadPaymentJournal(SqlCommand command,string name,SqlDataReader reader)
{
string mode=PaymentModes[name], actor=Convert.ToString(command.Parameters["@人员编号"].Value,Invariant);
using(var data=PaymentSets(reader)) {
if(data.Tables.Count<2 || data.Tables[0].Rows.Count!=1) throw Unavailable();
DataRow h=data.Tables[0].Rows[0];
if(PaymentLedger(mode)) {
if(data.Tables.Count!=3 || (string)h["查询模式"]!=mode || (string)h["策略版本"]!=FinancePaymentJournalPolicy.Version) throw Unavailable();
foreach(string key in new[]{"付款流水号","审计流水号"}) {
string expected=command.Parameters.Contains("@"+key)?Convert.ToString(command.Parameters["@"+key].Value,Invariant):"";
if(Convert.ToString(h[key],Invariant)!=expected) throw Unavailable();
}
long total=Convert.ToInt64(h["总数"],Invariant), page=PaymentPaged(mode)?(int)command.Parameters["@页码"].Value:1,
size=PaymentPaged(mode)?(int)command.Parameters["@每页条数"].Value:20;
if(total<0 || total>9007199254740991L || data.Tables[1].Rows.Count!=Math.Min(size,Math.Max(0,total-(page-1)*size)) ||
(!PaymentPaged(mode) && total!=1) || (mode!="RECEIPT" && data.Tables[2].Rows.Count!=0)) throw Unavailable();
return new {rows=PaymentRows(data.Tables[1]),summary=PaymentRow(h),total=total,entries=PaymentRows(data.Tables[2])};
}
if(mode=="LOOKUP" || mode=="ACK" || (command.Parameters.Contains("@请求处理") && (string)command.Parameters["@请求处理"].Value=="PREPARE")) {
var permissions=new List<string>();
if(mode=="LOOKUP") {
if(data.Tables.Count!=3 || data.Tables[2].Rows.Count>6) throw Unavailable();
foreach(DataRow r in data.Tables[2].Rows) permissions.Add((string)r["权限代码"]);
data.Tables.RemoveAt(2);
}
if(mode=="LOOKUP" || mode=="ACK") command.Parameters.Add("@模式",SqlDbType.VarChar,6).Value=mode;
var inbox=FinancePaymentInboxRequest.Read(data,actor,command);
if(mode=="LOOKUP") inbox.Add("permissions",permissions);
return inbox;
}
if(mode=="INSPECT" || mode=="CLOSE_UNCOMMITTED") {
if(data.Tables.Count!=3 || (string)h["请求处理"]!=mode || (string)h["操作人"]!=actor ||
(string)h["动作"]!=(string)command.Parameters["@动作"].Value || (string)h["幂等键"]!=(string)command.Parameters["@幂等键"].Value ||
(string)h["策略版本"]!=FinancePaymentJournalPolicy.Version) throw Unavailable();
string state=(string)h["请求状态"];
if(state!="CLOSED" && state!="COMMITTED" && !(state=="ABSENT" && mode=="INSPECT")) throw Unavailable();
var receipt=state=="COMMITTED"?PaymentProof(command,data.Tables[1],data.Tables[2],true):null;
if(receipt==null && (data.Tables[1].Rows.Count!=0 || data.Tables[2].Rows.Count!=0)) throw Unavailable();
if(receipt!=null && !Object.Equals(data.Tables[1].Rows[0]["请求摘要"],h["请求摘要"])) throw Unavailable();
if(state=="CLOSED" && (h["关闭流水号"]==DBNull.Value || h["关闭版本"]==DBNull.Value || h["关闭说明"]==DBNull.Value ||
(mode=="CLOSE_UNCOMMITTED" && !Object.Equals(h["关闭说明"],command.Parameters["@关闭说明"].Value)))) throw Unavailable();
return new {resolution=PaymentRow(h),receipt=receipt};
}
if(data.Tables.Count!=2) throw Unavailable();
return PaymentProof(command,data.Tables[0],data.Tables[1],false);
}
}
}
}

View File

@@ -0,0 +1,464 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace Jingyao.AIEmployee
{
// 沿用原站付款请求原文、审核版本及核销 XML 校验。
internal static class FinancePaymentJournalRequest
{
private static string Text(Dictionary<string, object> values, string key, int maximum)
{
object raw;
if (!values.TryGetValue(key, out raw) || !(raw is string)) throw new ArgumentException(key + "必须为明确文本。");
string value = (string)raw;
if (String.IsNullOrWhiteSpace(value) || value.Length > maximum || value != value.Trim())
throw new ArgumentException(key + "缺失、超长或含首尾空格。");
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
if (Char.IsControl(c) || c == '\uFFFE' || c == '\uFFFF') throw new ArgumentException(key + "含非法字符。");
if (Char.IsHighSurrogate(c))
{ if (i + 1 >= value.Length || !Char.IsLowSurrogate(value[++i])) throw new ArgumentException(key + "含非法Unicode字符。"); }
else if (Char.IsLowSurrogate(c)) throw new ArgumentException(key + "含非法Unicode字符。");
}
return value;
}
private static long Id(string value, long maximum)
{
long id;
if (!Int64.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id) ||
id <= 0 || id > maximum || id.ToString(CultureInfo.InvariantCulture) != value)
throw new ArgumentException("必须提供实际主键范围内的正整数文本。");
return id;
}
private static void Fields(Dictionary<string, object> values, params string[] allowed)
{
var set = new HashSet<string>(allowed, StringComparer.Ordinal);
foreach (string key in values.Keys) if (!set.Contains(key)) throw new ArgumentException("存在非本动作字段。");
}
private static string Version(Dictionary<string, object> values)
{
string value = Text(values, "expectedVersion", 16);
FinancePaymentJournalPolicy.RequireVersion(value); return value;
}
private static byte[] VersionBytes(string value)
{
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++) bytes[i] = Byte.Parse(value.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
return bytes;
}
private static string AllocationXml(Dictionary<string, object> values)
{
object raw;
if (!values.TryGetValue("allocations", out raw) || !(raw is IList)) throw new ArgumentException("缺少核销明细数组。");
IList array = (IList)raw;
if (array.Count < 1 || array.Count > FinancePaymentJournalPolicy.MaxAllocationLines) throw new ArgumentException("核销明细条数须为1至200。");
var sorted = new SortedDictionary<int, string[]>();
foreach (object item in array)
{
var line = item as Dictionary<string, object>;
if (line == null) throw new ArgumentException("核销行必须是明确对象。");
Fields(line, "payableId", "amount", "expectedVersion");
int id = (int)Id(Text(line, "payableId", 10), Int32.MaxValue);
decimal amount = FinancePaymentRegistrationPolicy.ReadAmount(Text(line, "amount", 19), false);
string version = Version(line);
if (sorted.ContainsKey(id)) throw new ArgumentException("同一次核销不得重复应付主键。");
sorted.Add(id, new string[] { amount.ToString("F2", CultureInfo.InvariantCulture), version });
}
var result = new StringBuilder();
using (XmlWriter xml = XmlWriter.Create(result, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false, NewLineHandling = NewLineHandling.None }))
{
xml.WriteStartElement("allocations");
foreach (var row in sorted)
{
xml.WriteStartElement("line");
xml.WriteAttributeString("payableId", row.Key.ToString(CultureInfo.InvariantCulture));
xml.WriteAttributeString("amount", row.Value[0]); xml.WriteAttributeString("expectedVersion", row.Value[1]);
xml.WriteEndElement();
}
xml.WriteEndElement();
}
return result.ToString();
}
private static void Add(SqlCommand command, string name, SqlDbType type, object value)
{
SqlParameter parameter = command.Parameters.Add(name, type);
if (type == SqlDbType.VarChar || type == SqlDbType.NVarChar || type == SqlDbType.VarBinary) parameter.Size = -1;
if (type == SqlDbType.Decimal) { parameter.Precision = 18; parameter.Scale = 2; }
parameter.Value = value;
}
public static void BindResolution(SqlCommand command, Dictionary<string, object> values, string trustedPerson)
{
if (command == null || values == null || command.Parameters.Count != 0) throw new ArgumentException("须使用空命令与明确原请求。");
Fields(values, "action", "mode", "original", "closeReason", "checked");
string action = Text(values, "action", 8), mode = Text(values, "mode", 17);
if (mode != "INSPECT" && mode != "CLOSE_UNCOMMITTED") throw new ArgumentException("只能核对或关闭尚未办理的原请求,不能冲正。");
object raw, check;
if (!values.TryGetValue("original", out raw) || !(raw is Dictionary<string, object>) ||
!values.TryGetValue("checked", out check) || !(check is bool) || !(bool)check)
throw new ArgumentException("须提供完整原请求并明确核对本次请求处理。");
object reason = DBNull.Value;
if (mode == "CLOSE_UNCOMMITTED") reason = Text(values, "closeReason", 1000);
else if (values.ContainsKey("closeReason")) throw new ArgumentException("只读核对不能附带关闭说明。");
// Validate the original business request unchanged, using the current
// trusted actor. A failing nested request leaves the real command empty.
using (SqlCommand original = new SqlCommand())
{
Bind(original, action, (Dictionary<string, object>)raw, trustedPerson);
foreach (SqlParameter parameter in original.Parameters)
command.Parameters.Add((SqlParameter)((ICloneable)parameter).Clone());
}
Add(command, "@请求处理", SqlDbType.VarChar, mode);
Add(command, "@关闭说明", SqlDbType.NVarChar, reason);
}
public static void Bind(SqlCommand command, string action, Dictionary<string, object> values, string trustedPerson)
{
if (command == null || values == null || command.Parameters.Count != 0) throw new ArgumentException("须使用空参数命令与完整付款请求。");
Id(trustedPerson, Int32.MaxValue);
if (action == "REGISTER") Fields(values, "supplierId", "currency", "amount", "paymentDate", "voucherReference", "accountReference", "reason", "idempotencyKey", "checked");
else if (action == "REVIEW") Fields(values, "paymentId", "expectedVersion", "decision", "reason", "idempotencyKey", "checked");
else if (action == "ALLOCATE") Fields(values, "paymentId", "expectedVersion", "allocations", "reason", "idempotencyKey", "checked");
else throw new ArgumentException("付款动作未开放;冲正规则等待9007确认。");
object check;
if (!values.TryGetValue("checked", out check) || !(check is bool) || !(bool)check) throw new ArgumentException("须明确核对本次操作,不能自动勾选。");
string reason = Text(values, "reason", 1000), key = Text(values, "idempotencyKey", 100);
int supplier = 0; long payment = 0; decimal amount = 0; DateTime date = DateTime.MinValue;
string currency = null, voucher = null, account = null, version = null, decision = null, allocations = null;
if (action == "REGISTER")
{
supplier = (int)Id(Text(values, "supplierId", 10), Int32.MaxValue);
currency = Text(values, "currency", 3); FinancePaymentJournalPolicy.RequireCurrency(currency);
amount = FinancePaymentRegistrationPolicy.ReadAmount(Text(values, "amount", 19), false);
string dateText = Text(values, "paymentDate", 10);
if (!DateTime.TryParseExact(dateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date) ||
date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) != dateText)
throw new ArgumentException("付款日期须明确填写有效yyyy-MM-dd,不使用当前日期默认值。");
voucher = Text(values, "voucherReference", 200); account = Text(values, "accountReference", 200);
}
else
{
payment = Id(Text(values, "paymentId", 19), Int64.MaxValue); version = Version(values);
if (action == "REVIEW")
{
decision = Text(values, "decision", 7);
if (decision != "CONFIRM" && decision != "REJECT") throw new ArgumentException("付款审批结论无效。");
}
else allocations = AllocationXml(values);
}
// Only now bind: invalid requests leave the caller's command untouched.
Add(command, "@动作", SqlDbType.VarChar, action); Add(command, "@操作人", SqlDbType.NVarChar, trustedPerson);
Add(command, "@幂等键", SqlDbType.NVarChar, key); Add(command, "@办理说明", SqlDbType.NVarChar, reason);
Add(command, "@策略版本", SqlDbType.VarChar, FinancePaymentJournalPolicy.Version); Add(command, "@已核对", SqlDbType.Bit, true);
if (action == "REGISTER")
{
Add(command, "@供应商流水号", SqlDbType.Int, supplier); Add(command, "@币种", SqlDbType.VarChar, currency);
// Preserve explicit two-place text into SQL, so the procedure can
// reject excess precision before a DECIMAL parameter rounds it.
Add(command, "@付款金额", SqlDbType.NVarChar, amount.ToString("F2", CultureInfo.InvariantCulture)); Add(command, "@付款日期", SqlDbType.Date, date);
Add(command, "@付款凭证引用", SqlDbType.NVarChar, voucher); Add(command, "@付款账户引用", SqlDbType.NVarChar, account);
}
else
{
Add(command, "@付款流水号", SqlDbType.BigInt, payment); Add(command, "@预期版本", SqlDbType.VarBinary, VersionBytes(version));
if (action == "REVIEW") Add(command, "@审批结论", SqlDbType.VarChar, decision);
else Add(command, "@核销明细", SqlDbType.Xml, allocations);
}
}
}
internal static class FinancePaymentInboxRequest
{
public const string Version = "FINANCE_PAYMENT_INBOX_20261104_V1";
private static void Fields(Dictionary<string, object> values, params string[] names)
{
if (values == null) throw new ArgumentException("请求箱参数缺失。");
var set = new HashSet<string>(names, StringComparer.Ordinal);
foreach (string key in values.Keys) if (!set.Contains(key)) throw new ArgumentException("请求箱包含非本动作字段。");
}
private static string Text(Dictionary<string, object> values, string name, int maximum)
{
object raw;
if (!values.TryGetValue(name, out raw) || !(raw is string)) throw new ArgumentException("请求箱文本字段缺失。");
string value = (string)raw;
if (String.IsNullOrWhiteSpace(value) || value.Length > maximum || value != value.Trim()) throw new ArgumentException("请求箱文本格式无效。");
foreach (char c in value) if (Char.IsControl(c)) throw new ArgumentException("请求箱包含控制字符。");
return value;
}
private static long Id(string value)
{
long id;
if (!Int64.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id) || id <= 0 || id.ToString(CultureInfo.InvariantCulture) != value)
throw new ArgumentException("请求箱主键或代次必须为完整正整数文本。");
return id;
}
private static void Empty(SqlCommand command, string actor)
{
if (command == null || command.Parameters.Count != 0 || Id(actor) > Int32.MaxValue) throw new ArgumentException("请求箱命令或可信人员无效。");
}
private static void Add(SqlCommand command, string name, SqlDbType type, object value)
{
SqlParameter p = command.Parameters.Add(name, type);
if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar) p.Size = -1;
p.Value = value;
}
private static void Copy(SqlCommand from, SqlCommand to)
{
foreach (SqlParameter parameter in from.Parameters) to.Parameters.Add((SqlParameter)((ICloneable)parameter).Clone());
}
public static void BindWrite(SqlCommand command, string action, Dictionary<string, object> values, string actor)
{
Empty(command, actor);
if (values == null) throw new ArgumentException("付款原请求缺失。");
string mode = Text(values, "requestMode", 7);
if (mode != "PREPARE" && mode != "EXECUTE") throw new ArgumentException("付款请求处理模式无效。");
if (Text(values, "inboxVersion", 60) != Version) throw new ArgumentException("付款页面协议已变化,请恢复原请求。");
long generation = Id(Text(values, "generation", 19));
var business = new Dictionary<string, object>(values, StringComparer.Ordinal);
business.Remove("requestMode"); business.Remove("generation"); business.Remove("inboxVersion");
using (SqlCommand original = new SqlCommand())
{
FinancePaymentJournalRequest.Bind(original, action, business, actor);
Copy(original, command);
}
Add(command, "@请求处理", SqlDbType.VarChar, mode); Add(command, "@请求代次", SqlDbType.BigInt, generation);
}
public static void BindResolution(SqlCommand command, Dictionary<string, object> values, string actor)
{
Empty(command, actor);
if (values == null || Text(values, "inboxVersion", 60) != Version) throw new ArgumentException("付款请求处理协议不符。");
long generation = Id(Text(values, "generation", 19));
var original = new Dictionary<string, object>(values, StringComparer.Ordinal);
original.Remove("generation"); original.Remove("inboxVersion");
using (SqlCommand nested = new SqlCommand()) { FinancePaymentJournalRequest.BindResolution(nested, original, actor); Copy(nested, command); }
Add(command, "@请求代次", SqlDbType.BigInt, generation);
}
public static void BindRecovery(SqlCommand command, Dictionary<string, object> values, string actor, bool acknowledge)
{
Empty(command, actor);
object key = DBNull.Value, generation = DBNull.Value, terminal = DBNull.Value, terminalId = DBNull.Value;
if (!acknowledge)
{
Fields(values, "mode");
if (Text(values, "mode", 5) != "INBOX") throw new ArgumentException("只允许读取本人原请求。");
}
else
{
Fields(values, "mode", "inboxVersion", "idempotencyKey", "generation", "terminal", "terminalId", "checked");
object check;
if (Text(values, "mode", 3) != "ACK" || Text(values, "inboxVersion", 60) != Version ||
!values.TryGetValue("checked", out check) || !(check is bool) || !(bool)check)
throw new ArgumentException("须明确核对原请求终态后收讫。");
key = Text(values, "idempotencyKey", 100); generation = Id(Text(values, "generation", 19));
string state = Text(values, "terminal", 9);
if (state != "COMMITTED" && state != "CLOSED") throw new ArgumentException("未知请求不能收讫。");
terminal = state; terminalId = Id(Text(values, "terminalId", 19));
}
Add(command, "@模式", SqlDbType.VarChar, acknowledge ? "ACK" : "LOOKUP"); Add(command, "@操作人", SqlDbType.NVarChar, actor);
Add(command, "@幂等键", SqlDbType.NVarChar, key); Add(command, "@请求代次", SqlDbType.BigInt, generation);
Add(command, "@终态", SqlDbType.VarChar, terminal); Add(command, "@终态流水号", SqlDbType.BigInt, terminalId);
Add(command, "@已核对", SqlDbType.Bit, acknowledge);
}
private static string Cell(DataRow row, string name)
{
if (row[name] == DBNull.Value || !(row[name] is string)) throw new InvalidOperationException("请求箱文本回执不完整。");
return (string)row[name];
}
private static string OptionalId(DataRow row, string name)
{
if (row[name] == DBNull.Value) return null;
string value = Cell(row, name); Id(value); return value;
}
private static void Columns(DataTable table, params string[] expected)
{
if (table.Columns.Count != expected.Length) throw new InvalidOperationException("请求箱回执字段不符。");
foreach (string name in expected) if (!table.Columns.Contains(name)) throw new InvalidOperationException("请求箱回执字段缺失。");
}
private static XmlElement Xml(string source, string root)
{
if (source == null || source.Length > 262144) throw new InvalidOperationException("请求箱原文长度无效。");
var doc = new XmlDocument(); doc.XmlResolver = null; doc.PreserveWhitespace = true;
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 262144 };
using (var reader = XmlReader.Create(new StringReader(source), settings)) doc.Load(reader);
if (doc.ChildNodes.Count != 1 || doc.DocumentElement == null || doc.DocumentElement.Name != root || doc.DocumentElement.NamespaceURI != "" || doc.DocumentElement.Attributes.Count != 0)
throw new InvalidOperationException("请求箱原文根节点无效。");
return doc.DocumentElement;
}
private static Dictionary<string, XmlElement> Elements(XmlElement parent, params string[] names)
{
var allowed = new HashSet<string>(names, StringComparer.Ordinal); var result = new Dictionary<string, XmlElement>(StringComparer.Ordinal);
foreach (XmlNode node in parent.ChildNodes)
{
XmlElement element = node as XmlElement;
if (element == null || element.NamespaceURI != "" || element.Attributes.Count != 0 || !allowed.Contains(element.Name) || result.ContainsKey(element.Name))
throw new InvalidOperationException("请求箱原文含未知或重复节点。");
result.Add(element.Name, element);
}
if (result.Count != names.Length) throw new InvalidOperationException("请求箱原文节点缺失。");
return result;
}
private static string Value(Dictionary<string, XmlElement> elements, string key)
{
XmlElement e = elements[key];
if (e.ChildNodes.Count != 1 || e.FirstChild.NodeType != XmlNodeType.Text) throw new InvalidOperationException("请求箱标量不完整。");
return e.InnerText;
}
private static List<Dictionary<string, object>> Lines(XmlElement root, bool context)
{
var result = new List<Dictionary<string, object>>(); var ids = new HashSet<string>(StringComparer.Ordinal);
string[] names = context ? new[] { "payableId", "paidAmount", "remaining", "expectedVersion" } : new[] { "payableId", "amount", "expectedVersion" };
foreach (XmlNode node in root.ChildNodes)
{
XmlElement e = node as XmlElement;
if (e == null || e.Name != "line" || e.NamespaceURI != "" || e.HasChildNodes || e.Attributes.Count != names.Length) throw new InvalidOperationException("请求箱核销行无效。");
var line = new Dictionary<string, object>(StringComparer.Ordinal);
foreach (string name in names)
{
if (!e.HasAttribute(name)) throw new InvalidOperationException("请求箱核销行字段缺失。");
line.Add(name, e.GetAttribute(name));
}
string id = (string)line["payableId"];
if (Id(id) > Int32.MaxValue || !ids.Add(id)) throw new InvalidOperationException("请求箱核销行主键重复或越界。");
FinancePaymentJournalPolicy.RequireVersion((string)line["expectedVersion"]);
if (context) { FinancePaymentRegistrationPolicy.ReadAmount((string)line["paidAmount"], true); FinancePaymentRegistrationPolicy.ReadAmount((string)line["remaining"], true); }
else FinancePaymentRegistrationPolicy.ReadAmount((string)line["amount"], false);
result.Add(line);
}
if (result.Count > FinancePaymentJournalPolicy.MaxAllocationLines) throw new InvalidOperationException("请求箱核销行超限。");
return result;
}
private static void Hash(string source, string digest)
{
using (SHA256 sha = SHA256.Create())
{
string actual = BitConverter.ToString(sha.ComputeHash(Encoding.Unicode.GetBytes(source))).Replace("-", "");
if (actual != digest) throw new InvalidOperationException("请求箱原文摘要不符。");
}
}
private static bool Same(object left, object right)
{
byte[] a = left as byte[], b = right as byte[];
if (a != null && b != null) { if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) if (a[i] != b[i]) return false; return true; }
return Object.Equals(left, right);
}
public static Dictionary<string, object> Read(DataSet data, string actor, SqlCommand expected)
{
if (data == null || data.Tables.Count != 2 || data.Tables[0].Rows.Count != 1 || data.Tables[1].Rows.Count > 1)
throw new InvalidOperationException("请求箱回执不完整,不能另建付款。");
Columns(data.Tables[0], "协议版本", "操作人", "下一代次", "待核对流水号");
Columns(data.Tables[1], "请求流水号", "幂等键", "操作人", "代次", "动作", "原请求", "请求摘要", "核对快照", "快照摘要", "登记时间", "请求版本", "请求状态", "终态流水号", "已收讫");
DataRow h = data.Tables[0].Rows[0];
if (Cell(h, "协议版本") != Version || Cell(h, "操作人") != actor) throw new InvalidOperationException("请求箱人员或协议不符。");
string next = Cell(h, "下一代次"), active = OptionalId(h, "待核对流水号"); Id(next);
var summary = new Dictionary<string, object> { { "protocol", Version }, { "actor", actor }, { "nextGeneration", next }, { "activeRequestId", active } };
bool lookup = expected.Parameters.Contains("@模式") && (string)expected.Parameters["@模式"].Value == "LOOKUP";
if (data.Tables[1].Rows.Count == 0)
{
if (!lookup || active != null) throw new InvalidOperationException("请求箱原记录缺失。");
return new Dictionary<string, object> { { "summary", summary }, { "request", null } };
}
DataRow row = data.Tables[1].Rows[0];
string id = Cell(row, "请求流水号"), key = Cell(row, "幂等键"), generation = Cell(row, "代次"), action = Cell(row, "动作"), state = Cell(row, "请求状态");
Id(id); Id(generation); FinancePaymentJournalPolicy.RequireVersion(Cell(row, "请求版本"));
if (Cell(row, "操作人") != actor || !(row["已收讫"] is bool) || !(row["登记时间"] is DateTime) || (lookup && id != active)) throw new InvalidOperationException("请求箱原记录身份或范围不符。");
bool acknowledged = (bool)row["已收讫"]; string terminalId = OptionalId(row, "终态流水号");
if ((!acknowledged && active != id) || (acknowledged && active == id) || Id(next) <= Id(generation)) throw new InvalidOperationException("请求箱当前通道或后续代次不符。");
if ((state != "PENDING" && state != "COMMITTED" && state != "CLOSED") || (state == "PENDING" ? terminalId != null || acknowledged : terminalId == null)) throw new InvalidOperationException("请求箱终态凭据不完整。");
if (!lookup && (key != (string)expected.Parameters["@幂等键"].Value || generation != Convert.ToString(expected.Parameters["@请求代次"].Value, CultureInfo.InvariantCulture))) throw new InvalidOperationException("请求箱原键或代次不符。");
if (expected.Parameters.Contains("@模式") && (string)expected.Parameters["@模式"].Value == "ACK" && (!acknowledged || state != (string)expected.Parameters["@终态"].Value || terminalId != Convert.ToString(expected.Parameters["@终态流水号"].Value, CultureInfo.InvariantCulture))) throw new InvalidOperationException("请求收讫未核实。");
string original = Cell(row, "原请求"), snapshot = Cell(row, "核对快照"); Hash(original, Cell(row, "请求摘要")); Hash(snapshot, Cell(row, "快照摘要"));
XmlElement xml = Xml(original, "request"), ctx = Xml(snapshot, "context");
string[] names = action == "REGISTER" ? new[] { "action", "actor", "supplier", "currency", "amount", "paymentDate", "voucherReference", "accountReference", "reason", "policy" } :
action == "REVIEW" ? new[] { "action", "actor", "paymentId", "expectedVersion", "decision", "reason", "policy" } : new[] { "action", "actor", "paymentId", "expectedVersion", "allocations", "reason", "policy" };
var elements = Elements(xml, names);
if (Value(elements, "action") != action || Value(elements, "actor") != actor || Value(elements, "policy") != FinancePaymentJournalPolicy.Version) throw new InvalidOperationException("请求箱规范原文不匹配。");
var payload = new Dictionary<string, object> { { "idempotencyKey", key }, { "reason", Value(elements, "reason") }, { "checked", true } };
object context = null;
if (action == "REGISTER")
{
Elements(ctx); payload.Add("supplierId", Value(elements, "supplier"));
foreach (string name in new[] { "currency", "amount", "paymentDate", "voucherReference", "accountReference" }) payload.Add(name, Value(elements, name));
}
else
{
payload.Add("paymentId", Value(elements, "paymentId")); payload.Add("expectedVersion", Value(elements, "expectedVersion"));
var contextElements = Elements(ctx, "supplierId", "currency", "amount", "appliedAmount", "creatorId", "sources");
var contextData = new Dictionary<string, object>();
foreach (string name in new[] { "supplierId", "currency", "amount", "appliedAmount", "creatorId" }) contextData.Add(name, Value(contextElements, name));
if (Id((string)contextData["supplierId"]) > Int32.MaxValue || Id((string)contextData["creatorId"]) > Int32.MaxValue) throw new InvalidOperationException("快照主键无效。");
FinancePaymentJournalPolicy.RequireCurrency((string)contextData["currency"]);
decimal amount = FinancePaymentRegistrationPolicy.ReadAmount((string)contextData["amount"], false), applied = FinancePaymentRegistrationPolicy.ReadAmount((string)contextData["appliedAmount"], true);
if (applied > amount) throw new InvalidOperationException("快照金额不守恒。");
var sources = Lines(contextElements["sources"], true); contextData.Add("sources", sources); context = contextData;
if (action == "REVIEW") { if (sources.Count != 0) throw new InvalidOperationException("审批快照不能含核销来源。"); payload.Add("decision", Value(elements, "decision")); }
else
{
var nested = Elements(elements["allocations"], "allocations"); var lines = Lines(nested["allocations"], false);
if (lines.Count == 0 || lines.Count != sources.Count) throw new InvalidOperationException("核销原文与快照行数不符。");
for (int i = 0; i < lines.Count; i++) if ((string)lines[i]["payableId"] != (string)sources[i]["payableId"] || (string)lines[i]["expectedVersion"] != (string)sources[i]["expectedVersion"]) throw new InvalidOperationException("核销快照版本或主键不符。");
payload.Add("allocations", lines);
}
}
using (SqlCommand normalized = new SqlCommand())
{
FinancePaymentJournalRequest.Bind(normalized, action, payload, actor);
if (expected.Parameters.Contains("@动作")) foreach (SqlParameter p in normalized.Parameters)
{
if (p.ParameterName == "@操作人")
{
if (!Same(p.Value, actor) || !expected.Parameters.Contains("@人员编号") ||
Convert.ToString(expected.Parameters["@人员编号"].Value, CultureInfo.InvariantCulture) != actor)
throw new InvalidOperationException("留存原请求与受信员工不同。");
}
else if (!expected.Parameters.Contains(p.ParameterName) || !Same(p.Value, expected.Parameters[p.ParameterName].Value))
throw new InvalidOperationException("留存原请求与本次准备内容不同。");
}
}
var request = new Dictionary<string, object> { { "requestId", id }, { "actor", actor }, { "generation", generation }, { "action", action }, { "payload", payload }, { "context", context },
{ "requestHash", Cell(row, "请求摘要") }, { "contextHash", Cell(row, "快照摘要") }, { "requestVersion", Cell(row, "请求版本") }, { "state", state }, { "terminalId", terminalId }, { "acknowledged", acknowledged } };
return new Dictionary<string, object> { { "summary", summary }, { "request", request } };
}
}
internal static class FinancePaymentRegistrationPolicy {
public const decimal MaxAmount = 9999999999999999.99m;
// Matches the existing DECIMAL(18,2) storage envelope, not a new currency,
// exchange-rate, rounding, tolerance or accounting-period policy.
public static decimal ReadAmount(string value, bool allowZero)
{
decimal amount;
if (value == null || value.Length > 19 ||
!Regex.IsMatch(value, @"\A(?:0|[1-9][0-9]{0,15})(?:\.[0-9]{1,2})?\z") ||
!Decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out amount) ||
amount > MaxAmount || amount < 0 || (!allowZero && amount == 0))
throw new ArgumentException("付款/核销金额必须明确填写,使用最多两位小数的非负金额;本次付款及核销须大于零,不自动舍入。");
return amount;
}
}
internal static class FinancePaymentJournalPolicy {
public const string Version = "FINANCE_PAYMENT_JOURNAL_20261103_V1";
public const int MaxAllocationLines = 200;
public static void RequireCurrency(string currency)
{
if (currency != "USD" && currency != "CNY")
throw new ArgumentException("付款仅支持已明确两位金额精度的USD或CNY,不默认币种、不自动换汇。");
}
public static void RequireVersion(string version)
{
if (version == null || !Regex.IsMatch(version, @"\A[0-9A-F]{16}\z"))
throw new ArgumentException("付款及应付均须完整八字节大写十六进制版本。");
}
}
}

View File

@@ -0,0 +1,288 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string MonthlyReport = "ai_月度业绩结算";
const string MonthlyBatches = "ai_月度业绩结算_结算批次";
const string MonthlyDetail = "ai_月度业绩结算_结算批次_详情";
const string SettlementOutputAccess = "ai_月度业绩结算_合同清单_输出权限";
const string SettlementCopy = "ai_月度业绩结算_合同清单_复制";
const string SettlementDownload = "ai_月度业绩结算_合同清单_下载";
protected override int ResponseLimit(Dictionary<string,object> body)
{
object name;
if (body.TryGetValue("name", out name) && (Object.Equals(name, SettlementCopy) || Object.Equals(name, SettlementDownload)))
return 52 * 1024 * 1024;
if (Object.Equals(name,QuotePictureContent)) return 8 * 1024 * 1024;
if (Object.Equals(name,QuoteDetailPage)) return 52 * 1024 * 1024;
return base.ResponseLimit(body);
}
const string LegacyPropose = "ai_月度业绩结算_历史合同_提交补录";
const string LegacyReview = "ai_月度业绩结算_历史合同_复核补录";
const string FormalPropose = "ai_月度业绩结算_正式合同_提交补录";
const string FormalReview = "ai_月度业绩结算_正式合同_复核补录";
const string BatchDraft = "ai_月度业绩结算_结算批次_创建草稿";
const string BatchSubmit = "ai_月度业绩结算_结算批次_提交";
const string BatchReview = "ai_月度业绩结算_结算批次_复核";
const string BatchId = "月度结算批次流水号";
static bool IsSettlementWrite(string name)
{
return name == LegacyPropose || name == LegacyReview || name == FormalPropose ||
name == FormalReview || name == BatchDraft || name == BatchSubmit || name == BatchReview;
}
static bool IsSettlement(string name)
{
return name == MonthlyReport || name == MonthlyBatches || name == MonthlyDetail || IsSettlementWrite(name) ||
name == SettlementOutputAccess || name == SettlementCopy || name == SettlementDownload;
}
static void SettlementMonth(SqlCommand command, Dictionary<string,object> inputs, bool required)
{
string value = Text(inputs, "归集月份", 7, required ? null : "");
DateTime date;
if ((required || value.Length > 0) && !DateTime.TryParseExact(value + "-01", "yyyy-MM-dd", Invariant, DateTimeStyles.None, out date)) throw BadInput();
command.Parameters.Add("@归集月份", SqlDbType.Char, 7).Value = value;
}
static void SettlementId(SqlCommand command, Dictionary<string,object> inputs, string field)
{
bool small = field == "历史项目流水号";
long value = Positive(inputs, field, small ? Int32.MaxValue : Int64.MaxValue, 0);
command.Parameters.Add("@" + field, small ? SqlDbType.Int : SqlDbType.BigInt).Value = value;
}
static void AddVersion(SqlCommand command, Dictionary<string,object> inputs, string field)
{
string version = Text(inputs, field, 16, null);
if (!Regex.IsMatch(version, @"\A[0-9a-fA-F]{16}\z")) throw BadInput();
byte[] bytes = new byte[8];
for (int i = 0; i < bytes.Length; i++) bytes[i] = Byte.Parse(version.Substring(i * 2, 2), NumberStyles.HexNumber, Invariant);
command.Parameters.Add("@" + field, SqlDbType.Binary, 8).Value = bytes;
}
static void SettlementAdjustment(SqlCommand command, Dictionary<string,object> inputs)
{
object raw;
decimal amount = 0m;
if (inputs.TryGetValue("调整金额", out raw)) {
string number = Convert.ToString(raw, Invariant);
if (!Decimal.TryParse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, Invariant, out amount) ||
Decimal.Round(amount, 2) != amount || amount <= -10000000000000000m || amount >= 10000000000000000m) throw BadInput();
}
SqlParameter param = command.Parameters.Add("@调整金额", SqlDbType.Decimal);
param.Precision = 18; param.Scale = 2; param.Value = amount;
AddText(command, inputs, "调整原因", 500, "");
AddText(command, inputs, "依据引用", 500, "");
}
// 给已验证的、固定顺序的参数编码,长度前缀避免说明或引用中的分隔符导致碰撞。
static string RequestFingerprint(SqlCommand command)
{
using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer, Encoding.UTF8))
using (var sha = SHA256.Create()) {
writer.Write(command.CommandText);
foreach (SqlParameter parameter in command.Parameters) {
writer.Write(parameter.ParameterName);
object value = parameter.Value;
if (value is byte[]) writer.Write(Convert.ToBase64String((byte[])value));
else if (value is decimal) writer.Write(((decimal)value).ToString("F2", Invariant));
else writer.Write(Convert.ToString(value, Invariant));
}
writer.Flush();
return BitConverter.ToString(sha.ComputeHash(buffer.ToArray())).Replace("-", "");
}
}
static void BindSettlement(SqlCommand command, string name, Dictionary<string,object> inputs, Dictionary<string,object> body)
{
if (name == SettlementOutputAccess) { Only(inputs); return; }
bool output = name == SettlementCopy || name == SettlementDownload;
if (name == MonthlyReport || name == MonthlyBatches || output) {
if (name == MonthlyReport || output) {
if (output) Only(inputs, "归集月份", "负责人", "结算状态", "数据来源", "关键字", "筛选总数");
else Only(inputs, "归集月份", "负责人", "结算状态", "数据来源", "关键字");
AddText(command, inputs, "负责人", 100, "");
AddText(command, inputs, "结算状态", 30, "", "", "ALL", "EXPECTED", "PENDING_REVIEW", "PENDING_MODE", "NOT_EFFECTIVE");
AddText(command, inputs, "数据来源", 20, "", "", "ALL", "FORMAL", "LEGACY");
AddText(command, inputs, "关键字", 200, "");
} else {
Only(inputs, "归集月份", "负责人姓名", "状态");
AddText(command, inputs, "负责人姓名", 100, "");
AddText(command, inputs, "状态", 30, "", "", "ALL", "DRAFT", "PENDING_REVIEW", "APPROVED", "REJECTED");
}
SettlementMonth(command, inputs, false);
if (output) {
command.Parameters.Add("@页码", SqlDbType.Int).Value = 1;
// 预期条数只参与服务端完整性核对,不传给 SQL 控制查询范围。
command.Parameters.Add("@预期条数", SqlDbType.Int).Value = (int)Positive(inputs, "筛选总数", 10000, 0);
return;
}
command.Parameters.Add("@页码", SqlDbType.Int).Value = (int)Positive(body, "pageList", 100000, 1);
command.Parameters.Add("@每页条数", SqlDbType.Int).Value = (int)Positive(body, "pageSize", 200, name == MonthlyReport ? 50 : 20);
return;
}
if (name == MonthlyDetail) {
Only(inputs, BatchId);
SettlementId(command, inputs, BatchId);
return;
}
if (body.ContainsKey("pageList") || body.ContainsKey("pageSize")) throw BadInput();
if (name == LegacyPropose || name == FormalPropose) {
string id = name == LegacyPropose ? "历史项目流水号" : "合同流水号";
Only(inputs, id, "提成计算模式代码", "依据说明", "依据引用", "幂等键");
SettlementId(command, inputs, id);
AddText(command, inputs, "提成计算模式代码", 40, null, "REPURCHASE", "FIRST_SPECIAL_MACHINE", "FIRST_MODULE", "REFERRAL_SPECIAL_MACHINE", "REFERRAL_MODULE");
AddText(command, inputs, "依据说明", 500, null);
AddText(command, inputs, "依据引用", 500, "");
} else if (name == LegacyReview || name == FormalReview || name == BatchReview) {
string id = name == BatchReview ? BatchId : name == LegacyReview ? "历史合同提成补录流水号" : "正式合同提成补录流水号";
Only(inputs, id, "动作", "复核意见", "预期版本", "幂等键");
SettlementId(command, inputs, id);
AddText(command, inputs, "动作", 20, null, "APPROVE", "REJECT");
AddText(command, inputs, "复核意见", 500, null);
AddVersion(command, inputs, "预期版本");
} else if (name == BatchDraft) {
Only(inputs, "归集月份", "负责人姓名", "币种", "调整金额", "调整原因", "依据引用", "幂等键");
SettlementMonth(command, inputs, true);
AddText(command, inputs, "负责人姓名", 100, null);
string unit = Text(inputs, "币种", 3, null);
if (!Regex.IsMatch(unit, @"\A[A-Z]{3}\z")) throw BadInput();
command.Parameters.Add("@币种", SqlDbType.Char, 3).Value = unit;
SettlementAdjustment(command, inputs);
} else if (name == BatchSubmit) {
Only(inputs, BatchId, "调整金额", "调整原因", "依据引用", "预期版本", "幂等键");
SettlementId(command, inputs, BatchId);
AddVersion(command, inputs, "预期版本");
SettlementAdjustment(command, inputs);
} else throw BadInput();
string token = Text(inputs, "幂等键", 100, null);
if (String.IsNullOrWhiteSpace(token)) throw BadInput();
command.Parameters.Add("@幂等键", SqlDbType.NVarChar, 100).Value = token;
string fingerprint = RequestFingerprint(command);
command.Parameters.Add("@请求指纹", SqlDbType.Char, 64).Value = fingerprint;
}
static List<Dictionary<string,object>> NextRows(SqlDataReader reader, int limit)
{
if (!reader.NextResult()) throw Unavailable();
return ReadRows(reader, limit);
}
static object ReadSettlement(SqlCommand command, string name, SqlDataReader reader)
{
if (name == SettlementOutputAccess) {
var access = ReadRows(reader, 1);
if (access.Count != 1 || reader.NextResult()) throw Unavailable();
return access;
}
if (IsSettlementWrite(name)) {
var receipt = ReadRows(reader, 1);
if (receipt.Count != 1 || reader.NextResult()) throw Unavailable();
return new { rows = receipt };
}
if (name == MonthlyDetail) {
var record = ReadRows(reader, 1);
var lines = NextRows(reader, Int32.MaxValue);
var audit = NextRows(reader, Int32.MaxValue);
if (reader.NextResult() || (record.Count == 0 && (lines.Count > 0 || audit.Count > 0))) throw Unavailable();
return new { record = record.Count == 0 ? null : record[0], lines = lines, audit = audit };
}
return ReadPageWithSummary(command, reader, name == MonthlyReport);
}
static object ReadPageWithSummary(SqlCommand command, SqlDataReader reader, bool monthlyAggregates)
{
int page = (int)command.Parameters["@页码"].Value, size = (int)command.Parameters["@每页条数"].Value;
var rows = ReadRows(reader, size);
var summaries = NextRows(reader, 1);
object count;
if (summaries.Count != 1 || !summaries[0].TryGetValue("筛选总数", out count) || count == null) throw Unavailable();
long total = Convert.ToInt64(count, Invariant);
if (total < 0 || total > 9007199254740991L || rows.Count != Math.Min(size, Math.Max(0L, total - (page - 1L) * size))) throw Unavailable();
if (!monthlyAggregates) {
if (reader.NextResult()) throw Unavailable();
return new { rows = rows, total = total, summary = summaries[0] };
}
var currency = NextRows(reader, Int32.MaxValue);
var salespeople = NextRows(reader, Int32.MaxValue);
if (reader.NextResult()) throw Unavailable();
return new { rows = rows, summary = summaries[0], total = total, currencySummary = currency, salespeople = salespeople };
}
static readonly string[] OutputFields = {
"数据来源", "来源业务标识", "归集月份", "签订日期", "合同编号", "合同状态", "负责人姓名", "客户编码",
"客户名称", "产品快照", "含税金额", "提成类型", "提成比例", "预计结算金额", "结算状态", "结算说明"
};
static string OutputCell(object value, bool csv)
{
string cell = Convert.ToString(value, Invariant) ?? "";
if (value is string) {
// 两种输出都送入表格软件,换行或制表符不能生成新的单元格。
cell = Regex.Replace(cell, @"[\x00-\x1f\x7f]", " ");
string first = cell.TrimStart();
if (first.Length > 0 && "=+@-".IndexOf(first[0]) >= 0) cell = "'" + cell;
}
return csv ? "\"" + cell.Replace("\"", "\"\"") + "\"" : cell;
}
static object RunSettlementOutput(SqlCommand command, string name, SqlConnection connection)
{
int expected = (int)command.Parameters["@预期条数"].Value;
command.Parameters.RemoveAt("@预期条数");
bool csv = name == SettlementDownload;
string separator = csv ? "," : "\t";
var builder = new StringBuilder();
builder.AppendLine(String.Join(separator, OutputFields));
var seen = new HashSet<string>(StringComparer.Ordinal);
// 同一事务核验输出权限、过滤条件和各页,拒绝中途变化或只返回部分行。
using (SqlTransaction tx = connection.BeginTransaction(IsolationLevel.Serializable)) {
command.Transaction = tx;
for (int page = 1; seen.Count < expected; page++) {
command.Parameters["@页码"].Value = page;
using (SqlDataReader reader = command.ExecuteReader()) {
var rows = ReadRows(reader, 200);
if (rows.Count != Math.Min(200, expected - seen.Count)) throw new ApiFailure(409, "合同筛选结果已变化,请刷新后重新输出");
var totals = NextRows(reader, 1);
if (totals.Count != 1 || Convert.ToInt64(totals[0]["筛选总数"], Invariant) != expected) throw new ApiFailure(409, "合同筛选总数已变化");
NextRows(reader, Int32.MaxValue); NextRows(reader, Int32.MaxValue);
if (reader.NextResult()) throw Unavailable();
foreach (var row in rows) {
string key = Convert.ToString(row["数据来源代码"], Invariant) + ":" + Convert.ToString(row["来源业务标识"], Invariant);
if (!seen.Add(key)) throw new ApiFailure(409, "结算输出存在重复来源,请刷新核对");
var cells = new string[OutputFields.Length];
for (int i = 0; i < cells.Length; i++) {
string field = OutputFields[i];
object val = row[field];
if (field == "预计结算金额" && !Object.Equals(row["结算状态代码"], "EXPECTED")) val = null;
cells[i] = OutputCell(val, csv);
}
builder.AppendLine(String.Join(separator, cells));
if (builder.Length > 8 * 1024 * 1024) throw new ApiFailure(400, "输出超过大小上限,请缩小筛选范围");
}
}
}
tx.Commit();
}
string content = builder.ToString();
byte[] bytes = Encoding.UTF8.GetBytes(content);
if (bytes.Length > 20 * 1024 * 1024) throw new ApiFailure(400, "输出超过大小上限,请缩小筛选范围");
using (var sha = SHA256.Create()) {
return new { procedure = name, rowCount = seen.Count, text = content, contentSHA256 = BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "") };
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string InvoiceHome = "ai_采购发票", InvoiceFollow = InvoiceHome + "_入库发票跟进",
InvoiceSources = InvoiceFollow + "_来源明细", InvoiceList = InvoiceHome + "_已登记发票",
InvoiceWorkflow = "ai_采购发票办理", InvoiceReconciliations = InvoiceWorkflow + "_关联对账单",
InvoiceMetadata = InvoiceWorkflow + "_发票附件_下载", InvoiceReview = InvoiceWorkflow + "_审核",
InvoiceMatch = InvoiceWorkflow + "_自动匹配", InvoiceReconcile = InvoiceWorkflow + "_生成对账单";
static bool InvoiceWrite(string name) { return name == InvoiceReview || name == InvoiceMatch || name == InvoiceReconcile; }
static string InvoiceRoute(string name)
{
switch (name) {
case InvoiceHome: case InvoiceFollow: case InvoiceSources: case InvoiceList: return "/erp/purchase-invoices";
case InvoiceWorkflow: case InvoiceReconciliations: case InvoiceMetadata:
case InvoiceReview: case InvoiceMatch: case InvoiceReconcile: return "/erp/purchase-invoice-workflow";
default: return null;
}
}
static void BindInvoice(SqlCommand command, string name, Dictionary<string,object> inputs, Dictionary<string,object> body)
{
if (name == InvoiceHome) { Only(inputs); return; }
if (name == InvoiceFollow || name == InvoiceSources || name == InvoiceList) {
if (name == InvoiceSources) {
Only(inputs,"分组键","关键词","状态"); AddText(command,inputs,"分组键",100,null);
} else Only(inputs,"关键词","状态");
AddText(command,inputs,"关键词",150,""); AddText(command,inputs,"状态",30,"");
command.Parameters.Add("@页码",SqlDbType.Int).Value = (int)Positive(body,"pageList",100000,1);
command.Parameters.Add("@每页条数",SqlDbType.Int).Value = (int)Positive(body,"pageSize",200,20);
return;
}
command.Parameters.Add("@发票登记流水号",SqlDbType.Int).Value = (int)Positive(inputs,"发票登记流水号",Int32.MaxValue,0);
if (!InvoiceWrite(name)) {
Only(inputs,"发票登记流水号");
if (name == InvoiceMetadata) command.Parameters.Add("@包含内容",SqlDbType.Bit).Value = false;
return;
}
if (body.ContainsKey("pageList") || body.ContainsKey("pageSize")) throw BadInput();
if (name == InvoiceReview) {
Only(inputs,"发票登记流水号","动作","意见","幂等键");
AddText(command,inputs,"动作",30,null,"审核通过","审核驳回"); AddText(command,inputs,"意见",500,"");
} else Only(inputs,"发票登记流水号","幂等键");
BindIdempotency(command,inputs);
}
static List<string> ReadPermissionCodes(SqlDataReader reader, int maximum)
{
var permissions = new List<string>();
foreach (var row in NextRows(reader,maximum)) {
object code;
if (!row.TryGetValue("权限代码",out code) || !(code is string) || permissions.Contains((string)code)) throw Unavailable();
permissions.Add((string)code);
}
if (reader.NextResult()) throw Unavailable();
return permissions;
}
static object ReadInvoice(SqlCommand command,string name,SqlDataReader reader)
{
if (name == InvoiceFollow || name == InvoiceList || name == InvoiceSources) return ReadPageWithSummary(command,reader,false);
var rows = ReadRows(reader,name == InvoiceReconciliations ? Int32.MaxValue : 1);
if (name == InvoiceHome) {
if (rows.Count != 1) throw Unavailable();
return new { summary = rows[0], permissions = ReadPermissionCodes(reader,8) };
}
if (name == InvoiceWorkflow) {
var links = NextRows(reader,Int32.MaxValue);
if (rows.Count == 0 && links.Count > 0) throw Unavailable();
return new { record = rows.Count == 0 ? null : rows[0], links = links, permissions = ReadPermissionCodes(reader,8) };
}
if (name == InvoiceMetadata) {
foreach (var row in rows) {
foreach (var field in row.Values) if (field is byte[]) throw Unavailable();
row.Remove("附件内容");
}
}
if ((InvoiceWrite(name) && rows.Count != 1) || reader.NextResult()) throw Unavailable();
return new { rows = rows };
}
}
}

View File

@@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
namespace Jingyao.AIEmployee
{
public sealed class PurchaseInvoiceFileHandler : IHttpHandler
{
const int Maximum = 20 * 1024 * 1024;
static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
var res = context.Response;
res.Cache.SetCacheability(HttpCacheability.NoCache);
res.Cache.SetNoStore();
res.TrySkipIisCustomErrors = true;
res.SuppressFormsAuthenticationRedirect = true;
res.Headers["X-Content-Type-Options"] = "nosniff";
try {
var req = context.Request;
if (req.HttpMethod != "POST") throw new ApiFailure(405, "请从页面提交请求");
EmployeeHandler.ValidateOrigin(req);
var employee = AiEmployeeSessions.RequireCurrent(context);
if (req.QueryString.Count != 0) throw Bad("请求参数有误");
if (req.ContentLength <= 0 || req.ContentLength > Maximum + 65536) throw new ApiFailure(413, "文件为空或超过20MiB限制");
string media = (req.ContentType ?? "").Split(';')[0].Trim().ToLowerInvariant();
using (var db = OpenDatabase()) {
if (media == "multipart/form-data") Register(context, db, employee);
else if (media == "application/x-www-form-urlencoded") Download(context, db, employee);
else throw new ApiFailure(415, "请选择发票附件或使用业务下载按钮");
}
} catch (ApiFailure error) { Fail(res,error.Status,error.Message); }
catch (HttpException error) { Fail(res,error.GetHttpCode() == 401 ? 401 : 400,error.GetHttpCode() == 401 ? "登录会话已结束" : "请求格式无效"); }
catch (SqlException error) {
foreach (SqlError detail in error.Errors) {
if (detail.Number == 50000) {
Fail(res,detail.State == 11 ? 403 : 409,detail.State == 11 ? "当前员工尚未获得此项业务权限" : "单据或关联来源未通过校验,请重新查询");
return;
}
}
Fail(res,503,"采购发票服务暂时不可用");
} catch (Exception) { Fail(res,503,"采购发票服务暂时不可用"); }
}
static ApiFailure Bad(string message) { return new ApiFailure(400,message); }
static void Json(HttpResponse res, object value) {
res.ContentType = "application/json";
res.Write(new JavaScriptSerializer().Serialize(value));
}
static void Fail(HttpResponse res, int status, string message) {
res.Clear(); res.StatusCode = status; Json(res,new {message = message});
}
static SqlConnection OpenDatabase() {
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["AiWorkflowPersonal"];
if (settings == null) throw new ApiFailure(503,"发票服务未配置");
var db = new SqlConnection(settings.ConnectionString);
try {
db.Open();
using (var check = new SqlCommand("SELECT CASE WHEN IS_ROLEMEMBER(N'ai_workflow_personal_executor')=1 AND IS_SRVROLEMEMBER(N'sysadmin')=0 AND USER_NAME()<>N'dbo' AND IS_ROLEMEMBER(N'db_owner')=0 AND IS_ROLEMEMBER(N'db_securityadmin')=0 AND IS_ROLEMEMBER(N'db_datareader')=0 AND IS_ROLEMEMBER(N'db_datawriter')=0 THEN 1 ELSE 0 END",db)) {
if (Convert.ToInt32(check.ExecuteScalar(),Invariant) != 1) throw new ApiFailure(503,"发票服务数据库身份配置无效");
}
return db;
} catch { db.Dispose(); throw; }
}
static SqlCommand Procedure(SqlConnection db, string name, Employee actor) {
var cmd = new SqlCommand(name,db);
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandTimeout=45;
cmd.Parameters.Add("@人员编号",SqlDbType.Int).Value=Int32.Parse(actor.PersonId,Invariant);
cmd.Parameters.Add("@角色编号",SqlDbType.Int).Value=Int32.Parse(actor.RoleId,Invariant);
return cmd;
}
static void Only(HttpRequest req, params string[] fields) {
var allowed=new HashSet<string>(fields,StringComparer.Ordinal);
foreach (string field in req.Form.AllKeys) {
if (field==null || !allowed.Contains(field) || req.Form.GetValues(field).Length!=1) throw Bad("请求包含无效或重复的字段");
}
}
static string Field(HttpRequest req, string key, int length, bool required) {
string value=(req.Form[key] ?? "").Trim();
if (required && value.Length==0 || value.Length>length) throw Bad(key+"长度无效");
return value;
}
static string Hash(byte[] value) {
using (var sha=SHA256.Create()) return BitConverter.ToString(sha.ComputeHash(value)).Replace("-","").ToLowerInvariant();
}
static bool Starts(byte[] content, params byte[] signature) {
if(content.Length < signature.Length) return false;
for(int n=0;n<signature.Length;n++) if (signature[n]!=content[n]) return false;
return true;
}
static string Type(string filename, byte[] bytes) {
switch(Path.GetExtension(filename).ToLowerInvariant()) {
case ".pdf": if(Starts(bytes,0x25,0x50,0x44,0x46,0x2D)) return "application/pdf"; break;
case ".png": if(Starts(bytes,0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A)) return "image/png"; break;
case ".jpg": case ".jpeg": if(Starts(bytes,0xFF,0xD8,0xFF)) return "image/jpeg"; break;
case ".ofd": if(Starts(bytes,0x50,0x4B,3,4)) return "application/ofd"; break;
}
throw Bad("发票附件类型或文件内容不符");
}
static void Register(HttpContext ctx,SqlConnection db,Employee actor) {
var req=ctx.Request;
// 先核验会话内本人的登记许可,再读取 multipart 里的附件。
using (var auth=Procedure(db,"dbo.ai_采购发票",actor))
using (var rights=auth.ExecuteReader()) {
bool allowed=false;
if(rights.NextResult()) while(rights.Read()) if(Convert.ToString(rights["权限代码"],Invariant)=="ERP.PROCUREMENT.INVOICE_REGISTER_BATCH") allowed=true;
if(!allowed) throw new ApiFailure(403,"当前员工尚未获得此项业务权限");
}
Only(req,"type","name","ModularID","应付流水号","发票号码","发票代码","发票类型","开票日期","供应商","不含税金额","税额","含税金额","备注","幂等键");
if(req.Form["type"]!="12" || req.Form["name"]!="ai_采购发票_合并登记_保存" || req.Form["ModularID"]!="/erp/purchase-invoices" || req.Files.Count!=1 || req.Files.GetKey(0)!="附件")
throw Bad("请通过采购发票登记表单上传一份附件");
var file=req.Files[0];
if(file==null || file.ContentLength<=0 || file.ContentLength>Maximum) throw new ApiFailure(413,"发票附件大小须为1字节至20MiB");
string filename=Path.GetFileName(file.FileName ?? "");
if(filename.Length==0 || filename.Length>260 || filename.IndexOfAny(Path.GetInvalidFileNameChars())>=0) throw Bad("发票文件名无效");
var bytes=new byte[file.ContentLength];
using(var input=file.InputStream) {
int offset=0,count;
while(offset<bytes.Length && (count=input.Read(bytes,offset,bytes.Length-offset))>0) offset+=count;
if(offset!=bytes.Length || input.ReadByte()!=-1) throw Bad("附件长度不符");
}
string hash=Hash(bytes), mime=Type(filename,bytes);
var ids=new SortedSet<int>();
foreach(string text in Field(req,"应付流水号",1200,true).Split(',')) {
int id;
if(!Int32.TryParse(text,NumberStyles.None,Invariant,out id) || id<1 || !ids.Add(id) || ids.Count>100) throw Bad("所选应付流水必须唯一且不超过100笔");
}
var xml=new StringBuilder("<ids>");
foreach(int id in ids) xml.Append("<id>").Append(id.ToString(Invariant)).Append("</id>");
xml.Append("</ids>");
DateTime invoiceDate;
if(!DateTime.TryParseExact(Field(req,"开票日期",10,true),"yyyy-MM-dd",Invariant,DateTimeStyles.None,out invoiceDate)) throw Bad("开票日期无效");
using(var cmd=Procedure(db,"dbo.ai_采购发票_合并登记_保存",actor)) {
cmd.Parameters.Add("@应付流水号XML",SqlDbType.Xml).Value=xml.ToString();
cmd.Parameters.Add("@发票号码",SqlDbType.NVarChar,80).Value=Field(req,"发票号码",80,true);
cmd.Parameters.Add("@发票代码",SqlDbType.NVarChar,40).Value=Field(req,"发票代码",40,false);
cmd.Parameters.Add("@发票类型",SqlDbType.NVarChar,30).Value=Field(req,"发票类型",30,true);
cmd.Parameters.Add("@开票日期",SqlDbType.Date).Value=invoiceDate;
cmd.Parameters.Add("@供应商",SqlDbType.NVarChar,200).Value=Field(req,"供应商",200,true);
foreach(string key in new[]{"不含税金额","税额","含税金额"}) {
decimal amount;
if(!Decimal.TryParse(Field(req,key,24,true),NumberStyles.AllowDecimalPoint,Invariant,out amount) || Decimal.Round(amount,2)!=amount || amount>9999999999999999.99m)
throw Bad(key+"不是有效的两位小数金额");
var p=cmd.Parameters.Add("@"+key,SqlDbType.Decimal);p.Precision=18;p.Scale=2;p.Value=amount;
}
cmd.Parameters.Add("@备注",SqlDbType.NVarChar,500).Value=Field(req,"备注",500,false);
cmd.Parameters.Add("@附件名称",SqlDbType.NVarChar,260).Value=filename;
cmd.Parameters.Add("@内容类型",SqlDbType.VarChar,48).Value=mime;
cmd.Parameters.Add("@附件哈希",SqlDbType.Char,64).Value=hash;
string keyValue=Field(req,"幂等键",100,true);
if(!Regex.IsMatch(keyValue,@"\A[A-Za-z0-9_.:-]+\z")) throw Bad("提交标识无效");
cmd.Parameters.Add("@幂等键",SqlDbType.VarChar,100).Value=keyValue;
var canonical=new List<string>();
foreach(SqlParameter p in cmd.Parameters) {
string value=p.SqlDbType==SqlDbType.Date ? ((DateTime)p.Value).ToString("yyyy-MM-dd",Invariant)
: p.SqlDbType==SqlDbType.Decimal ? ((decimal)p.Value).ToString("0.00",Invariant) : Convert.ToString(p.Value,Invariant);
canonical.Add(value);
}
cmd.Parameters.Add("@请求指纹",SqlDbType.Char,64).Value=Hash(Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(canonical)));
cmd.Parameters.Add("@附件内容",SqlDbType.VarBinary,-1).Value=bytes;
using(var reader=cmd.ExecuteReader()) {
if(!reader.Read()) throw new ApiFailure(503,"缺少发票登记回执");
var row=new Dictionary<string,object>();
for(int n=0;n<reader.FieldCount;n++) row[reader.GetName(n)]=reader[n];
if(reader.Read() || reader.NextResult()) throw new ApiFailure(503,"发票登记回执不唯一");
Json(ctx.Response,new {actor=actor.PersonId,data=new {rows=new[]{row}}});
}
}
}
static void Download(HttpContext ctx,SqlConnection db,Employee actor) {
var req=ctx.Request;
Only(req,"name","type","ModularID","发票登记流水号");
int id;
if(req.Form["type"]!="11" || req.Form["name"]!="ai_采购发票办理_发票附件_下载" || req.Form["ModularID"]!="/erp/purchase-invoice-workflow"
|| !Int32.TryParse(req.Form["发票登记流水号"],NumberStyles.None,Invariant,out id) || id<1) throw Bad("请从所选发票办理页下载原件");
using(var cmd=Procedure(db,"dbo.ai_采购发票办理_发票附件_下载",actor)) {
cmd.Parameters.Add("@发票登记流水号",SqlDbType.Int).Value=id;
cmd.Parameters.Add("@包含内容",SqlDbType.Bit).Value=true;
using(var reader=cmd.ExecuteReader()) {
if(!reader.Read()) throw new ApiFailure(404,"所选发票没有已登记附件");
string filename=Convert.ToString(reader["附件名称"],Invariant);
string mime=Convert.ToString(reader["内容类型"],Invariant);
byte[] bytes=(byte[])reader["附件内容"];
if(bytes.Length<1 || bytes.Length>Maximum || bytes.Length!=Convert.ToInt64(reader["附件长度"],Invariant)
|| !String.Equals(Hash(bytes),Convert.ToString(reader["附件哈希"],Invariant),StringComparison.OrdinalIgnoreCase) || Type(filename,bytes)!=mime)
throw new ApiFailure(409,"存档附件的内容或哈希未通过核对");
ctx.Response.ContentType=mime;
ctx.Response.AddHeader("Content-Disposition","attachment; filename=\"invoice-"+id.ToString(Invariant)+Path.GetExtension(filename)+"\"; filename*=UTF-8''"+Uri.EscapeDataString(filename));
ctx.Response.BinaryWrite(bytes);
}
}
}
}
}

View File

@@ -0,0 +1,302 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string QuoteSave = "ai_报价管理_新建报价_保存草稿";
const string QuoteReceipt = "ai_报价管理_新建报价_草稿回执";
const string QuoteEdit = "ai_报价管理_修改报价_保存";
const string QuoteEditReceipt = "ai_报价管理_修改报价_保存回执";
const string QuoteDirect = "ai_报价管理_直接新建_保存";
const string QuoteDirectProof = "ai_报价管理_直接新建_保存回执";
const string QuoteDirectAccess = "ai_报价管理_直接新建_办理资格";
static bool QuoteFormWrite(string name) { return name==QuoteSave || name==QuoteEdit || name==QuoteDirect; }
const string QuoteSubmit = "ai_报价管理_报价审批_提交";
const string QuoteSubmitBasis = "ai_报价管理_报价审批_提交依据";
const string QuoteSubmitReceipt = "ai_报价管理_报价审批_提交回执";
const string QuoteApprove = "ai_报价管理_报价审批_批准";
const string QuoteReject = "ai_报价管理_报价审批_驳回";
const string QuoteReviewBasis = "ai_报价管理_报价审批_复核依据";
const string QuoteReviewReceipt = "ai_报价管理_报价审批_复核回执";
const string ContractSubmit = "ai_合同管理_合同审批_提交";
const string ContractSubmitBasis = ContractSubmit+"依据";
const string ContractSubmitProof = ContractSubmit+"回执";
const string ContractActivate = "ai_合同管理_合同生效_办理";
const string ContractActivationBasis = ContractActivate+"依据";
const string ContractActivationProof = ContractActivate+"回执";
const string ContractReviewBasis = "ai_合同管理_合同审批_复核依据";
const string ContractReviewProof = "ai_合同管理_合同审批_复核回执";
const string ContractApprove = "ai_合同管理_合同审批_批准";
const string ContractReject = "ai_合同管理_合同审批_驳回";
static bool ContractApproval(string name) {
return name==ContractReviewBasis || name==ContractReviewProof || name==ContractApprove || name==ContractReject;
}
static bool ContractSubmission(string name) {
return name==ContractSubmit || name==ContractSubmitBasis || name==ContractSubmitProof || name==ContractActivate || name==ContractActivationBasis || name==ContractActivationProof;
}
static bool QuoteSubmitQuery(string name) {
return name==ContractActivationBasis || name==ContractActivationProof || name==ContractReviewBasis || name==ContractReviewProof || name==ContractSubmitBasis || name==ContractSubmitProof || name==ContractDraftProof || name==QuoteDirectAccess || name==QuoteDirectProof || name==QuoteEditReceipt || name==QuoteSubmitBasis || name==QuoteSubmitReceipt || name==QuoteReviewBasis || name==QuoteReviewReceipt;
}
static bool QuoteWrite(string name) { return name==ContractActivate || name==ContractApprove || name==ContractReject || name==ContractSubmit || name==ContractDraftSave || QuoteFormWrite(name) || name==QuoteSubmit || name==QuoteApprove || name==QuoteReject; }
static void BindQuoteSubmit(SqlCommand cmd,string name,Dictionary<string,object> inputs)
{
string document=(ContractApproval(name) || ContractSubmission(name)) ? "合同流水号" : "报价流水号";
bool basis=name==ContractActivationBasis || name==ContractReviewBasis || name==ContractSubmitBasis || name==QuoteSubmitBasis || name==QuoteReviewBasis;
bool receipt=name==ContractActivationProof || name==ContractReviewProof || name==ContractSubmitProof || name==QuoteSubmitReceipt || name==QuoteReviewReceipt;
if (basis) Only(inputs,document,"需求流水号","客户流水号");
else if (receipt) Only(inputs,document,"需求流水号","客户流水号","客户端请求号");
else if (name==ContractReject || name==QuoteReject) Only(inputs,document,"需求流水号","客户流水号","原修订","客户端请求号","驳回原因");
else Only(inputs,document,"需求流水号","客户流水号","原修订","客户端请求号");
cmd.Parameters.Add("@"+document,SqlDbType.BigInt).Value=Positive(inputs,document,9007199254740991L,0);
cmd.Parameters.Add("@需求流水号",SqlDbType.BigInt).Value=Positive(inputs,"需求流水号",9007199254740991L,0);
cmd.Parameters.Add("@客户流水号",SqlDbType.Int).Value=(int)Positive(inputs,"客户流水号",Int32.MaxValue,0);
if (basis) return;
Guid key;
if (!Guid.TryParseExact(Text(inputs,"客户端请求号",36,null),"D",out key) || key==Guid.Empty) throw BadInput();
cmd.Parameters.Add("@客户端请求号",SqlDbType.UniqueIdentifier).Value=key;
if (receipt) return;
if (name==ContractReject || name==QuoteReject) {
string reason=Text(inputs,"驳回原因",500,null).Trim();
if (reason.Length==0) throw BadInput();
cmd.Parameters.Add("@驳回原因",SqlDbType.NVarChar,500).Value=reason;
}
BindReviewVersion(cmd,inputs,"原修订");
string digest=QuoteFingerprint(cmd);
cmd.Parameters.Add("@请求指纹",SqlDbType.Char,64).Value=digest;
}
const string QuoteDetailPage = "ai_报价管理_报价详情_行明细";
const string QuotePictures = "ai_报价管理_报价详情_行图片";
const string QuotePictureContent = "ai_报价管理_报价详情_图片内容";
const string ContractQuoteSource = "ai_合同管理_已批准报价_来源明细";
const string ContractNumberPreview = "ai_合同管理_新建合同_编号预览";
static bool PagedQuoteLines(string name) { return name==QuoteDetailPage || name==ContractQuoteSource; }
static bool QuoteDetails(string name) { return name==ContractNumberPreview || PagedQuoteLines(name) || name==QuotePictures || name==QuotePictureContent; }
static void BindQuoteDetails(SqlCommand cmd,string name,Dictionary<string,object> inputs,Dictionary<string,object> body) {
if (name==ContractNumberPreview) {
Only(inputs,"合同模板");
string template=Text(inputs,"合同模板",30,null);
if(template!="MODULE" && template!="SPECIAL_MACHINE" && template!="AFTER_SALES") throw BadInput();
cmd.Parameters.Add("@合同模板",SqlDbType.VarChar,30).Value=template;
return;
}
if (PagedQuoteLines(name)) Only(inputs,"报价流水号","需求流水号","客户流水号","页码","每页条数");
else if (name==QuotePictureContent) Only(inputs,"报价流水号","需求流水号","客户流水号","附件流水号");
else Only(inputs,"报价流水号","需求流水号","客户流水号");
cmd.Parameters.Add("@报价流水号",SqlDbType.BigInt).Value=Positive(inputs,"报价流水号",9007199254740991L,0);
cmd.Parameters.Add("@需求流水号",SqlDbType.BigInt).Value=Positive(inputs,"需求流水号",9007199254740991L,0);
cmd.Parameters.Add("@客户流水号",SqlDbType.Int).Value=(int)Positive(inputs,"客户流水号",Int32.MaxValue,0);
if (name==QuotePictureContent)
cmd.Parameters.Add("@附件流水号",SqlDbType.BigInt).Value=Positive(inputs,"附件流水号",9007199254740991L,0);
if (PagedQuoteLines(name)) {
if ((inputs.ContainsKey("页码") && body.ContainsKey("pageList")) || (inputs.ContainsKey("每页条数") && body.ContainsKey("pageSize"))) throw BadInput();
cmd.Parameters.Add("@页码",SqlDbType.Int).Value=(int)Positive(inputs,"页码",Int32.MaxValue,Positive(body,"pageList",Int32.MaxValue,1));
cmd.Parameters.Add("@每页条数",SqlDbType.Int).Value=(int)Positive(inputs,"每页条数",200,Positive(body,"pageSize",200,20));
}
}
const int QuoteBodyLimit = 64 * 1024 * 1024;
static decimal QuoteDecimal(Dictionary<string,object> row, string key, int scale, decimal max, bool allowZero)
{
object raw;
decimal value;
if (!row.TryGetValue(key,out raw) || !Decimal.TryParse(Convert.ToString(raw,Invariant),NumberStyles.AllowDecimalPoint,
Invariant,out value) || value<0 || (!allowZero && value==0) || value>max || Decimal.Round(value,scale)!=value)
throw BadInput();
return value;
}
static string QuoteString(Dictionary<string,object> row, string key, int max, bool required)
{
string value=Text(row,key,max,required?null:"").Trim();
if (required && value.Length==0) throw BadInput();
return value;
}
static string QuoteProductType(Dictionary<string,object> row,bool allowSpecial)
{
string kind=QuoteString(row,"productType",30,true);
if (kind!="MODULE" && kind!="BOM" && kind!="MATERIAL" && kind!="NON_STANDARD" &&
!(allowSpecial && kind=="SPECIAL_MACHINE")) throw BadInput();
return kind;
}
static string QuoteConfiguration(Dictionary<string,object> line,string kind)
{
if (kind!="SPECIAL_MACHINE") return "";
string raw=QuoteString(line,"configurationJson",200000,true);
object[] rows=Parse(raw,false) as object[];
if (rows==null || rows.Length<1 || rows.Length>100) throw BadInput();
foreach (object item in rows) {
var row=item as Dictionary<string,object>;
if (row==null) throw BadInput();
QuoteProductType(row,false);
QuoteString(row,"productName",500,true);
QuoteString(row,"productCode",100,false);
QuoteString(row,"specification",200,false);
QuoteString(row,"technicalRequirement",500,false);
QuoteString(row,"unit",20,true);
QuoteDecimal(row,"quantity",4,99999999999999.9999m,false);
QuoteDecimal(row,"unitPrice",4,99999999999999.9999m,true);
}
return raw;
}
static DataTable QuoteLines(object[] rows)
{
if (rows==null || rows.Length<1 || rows.Length>100) throw BadInput();
var table=new DataTable();
table.Columns.Add("行号",typeof(int));
foreach (string name in new[]{"产品类型","产品名称","产品编码","规格型号","技术要求","组成配置","配置明细Json"})
table.Columns.Add(name,typeof(string));
table.Columns.Add("数量",typeof(decimal));
table.Columns.Add("单位",typeof(string));
table.Columns.Add("单价",typeof(decimal));
table.Columns.Add("指定含税金额",typeof(decimal));
for (int i=0;i<rows.Length;i++) {
var line=rows[i] as Dictionary<string,object>;
if (line==null || Positive(line,"lineNo",100,0)!=i+1) throw BadInput();
string kind=QuoteProductType(line,true);
object total=DBNull.Value, raw;
if (line.TryGetValue("totalAmount",out raw) && raw!=null)
total=QuoteDecimal(line,"totalAmount",2,9999999999999999.99m,true);
table.Rows.Add(i+1,kind,QuoteString(line,"productName",500,true),QuoteString(line,"productCode",100,false),
QuoteString(line,"specification",200,false),QuoteString(line,"technicalRequirement",500,false),
kind=="SPECIAL_MACHINE"?QuoteString(line,"compositionConfiguration",1000,false):"",QuoteConfiguration(line,kind),
QuoteDecimal(line,"quantity",4,99999999999999.9999m,false),QuoteString(line,"unit",20,true),
QuoteDecimal(line,"unitPrice",4,99999999999999.9999m,true),total);
}
return table;
}
static DataTable QuoteImages(object[] items,int count)
{
if (items==null || items.Length>8) throw BadInput();
var table=new DataTable();
table.Columns.Add("图片序号",typeof(int)); table.Columns.Add("行号",typeof(int));
table.Columns.Add("文件名",typeof(string)); table.Columns.Add("内容类型",typeof(string));
table.Columns.Add("文件哈希",typeof(string)); table.Columns.Add("文件内容",typeof(byte[]));
table.Columns.Add("是否主图",typeof(bool));
int bytes=0,primaries=0;
for (int i=0;i<items.Length;i++) {
var image=items[i] as Dictionary<string,object>;
if (image==null) throw BadInput();
int line=(int)Positive(image,"lineNo",count,0);
if (line<1) throw BadInput();
string file=QuoteString(image,"name",255,true),type=QuoteString(image,"contentType",50,true);
if (type!="image/jpeg" && type!="image/png" && type!="image/webp") throw BadInput();
string data=Text(image,"dataUrl",7*1024*1024,null), prefix="data:"+type+";base64,";
if (!data.StartsWith(prefix,StringComparison.OrdinalIgnoreCase)) throw BadInput();
byte[] content;
try { content=Convert.FromBase64String(data.Substring(prefix.Length)); } catch (FormatException) { throw BadInput(); }
bytes+=content.Length;
if (content.Length<1 || content.Length>5*1024*1024 || bytes>20*1024*1024) throw BadInput();
object flag;
if (!image.TryGetValue("primary",out flag) || !(flag is bool)) throw BadInput();
if ((bool)flag && ++primaries>1) throw BadInput();
table.Rows.Add(i+1,line,file,type,LabelDigest(content),content,(bool)flag);
}
if (items.Length>0 && primaries==0) table.Rows[0]["是否主图"]=true;
return table;
}
static void AddQuoteTable(SqlCommand cmd,string param,string type,DataTable table)
{
var p=cmd.Parameters.Add(param,SqlDbType.Structured);
p.TypeName="dbo."+type;
p.Value=table;
}
static string QuoteFingerprint(SqlCommand cmd)
{
using (var stream=new MemoryStream())
using (var writer=new BinaryWriter(stream,Encoding.UTF8)) {
foreach (SqlParameter param in cmd.Parameters) {
if (param.ParameterName=="@角色编号") continue;
writer.Write(param.ParameterName);
var table=param.Value as DataTable;
if (table==null) {
var binary=param.Value as byte[];
if (binary!=null) { writer.Write(binary.Length); writer.Write(binary); continue; }
var date=param.Value as DateTime?;
writer.Write(date.HasValue?date.Value.ToString("yyyy-MM-dd",Invariant):Convert.ToString(param.Value,Invariant));
} else {
writer.Write(table.Rows.Count);
foreach (DataRow row in table.Rows) foreach (DataColumn col in table.Columns) {
// 图片内容已在同一绑定器计算 SHA-256,指纹写入该摘要即可。
if (col.DataType==typeof(byte[])) continue;
writer.Write(!row.IsNull(col));
if (!row.IsNull(col)) writer.Write(col.DataType==typeof(decimal)?
((decimal)row[col]).ToString("G29",Invariant):Convert.ToString(row[col],Invariant));
}
}
}
writer.Flush();
return LabelDigest(stream.ToArray());
}
}
static List<Dictionary<string,object>> ReadDirectQuoteProof(SqlDataReader reader, List<Dictionary<string,object>> draft) {
if (draft.Count!=1 || !reader.NextResult()) throw Unavailable();
var proof=ReadRows(reader,1);
if (proof.Count!=1) throw Unavailable();
foreach(string field in new[]{"报价流水号","需求流水号","客户流水号","客户端请求号","人员编号","报价单号","保存修订","含税金额"})
if (!Object.Equals(draft[0][field],proof[0][field])) throw Unavailable();
return proof;
}
static void BindQuotationDraft(SqlCommand cmd,string name,Dictionary<string,object> inputs)
{
if (name==QuoteDirectAccess) { Only(inputs); return; }
bool direct=name==QuoteDirect || name==QuoteDirectProof;
bool editing=name==QuoteEdit || name==QuoteEditReceipt;
if (direct) {
if (name==QuoteDirectProof) Only(inputs,"客户流水号","客户端请求号","需求请求号");
else Only(inputs,"客户流水号","客户端请求号","需求请求号","需求产品","税率","有效期","付款方式流水号","负责人","交货周期","交货方式","质保期限","备注","产品行","图片行");
Guid requirementKey;
if (!Guid.TryParseExact(Text(inputs,"需求请求号",36,null),"D",out requirementKey) || requirementKey==Guid.Empty) throw BadInput();
cmd.Parameters.Add("@需求请求号",SqlDbType.UniqueIdentifier).Value=requirementKey;
if (name==QuoteDirect) cmd.Parameters.Add("@需求产品",SqlDbType.NVarChar,500).Value=QuoteString(inputs,"需求产品",500,true);
}
else if (editing) {
if (name==QuoteEditReceipt) Only(inputs,"报价流水号","需求流水号","客户流水号","客户端请求号");
else Only(inputs,"报价流水号","原修订","需求流水号","客户流水号","客户端请求号","税率","有效期","付款方式流水号","负责人","交货周期","交货方式","质保期限","备注","产品行","图片行");
cmd.Parameters.Add("@报价流水号",SqlDbType.BigInt).Value=Positive(inputs,"报价流水号",9007199254740991L,0);
if (name==QuoteEdit) BindReviewVersion(cmd,inputs,"原修订");
}
else if (name==QuoteReceipt) Only(inputs,"需求流水号","客户流水号","客户端请求号");
else Only(inputs,"需求流水号","客户流水号","客户端请求号","税率","有效期","付款方式流水号","负责人","交货周期","交货方式","质保期限","备注","产品行","图片行");
if (!direct) cmd.Parameters.Add("@需求流水号",SqlDbType.BigInt).Value=Positive(inputs,"需求流水号",9007199254740991L,0);
cmd.Parameters.Add("@客户流水号",SqlDbType.Int).Value=(int)Positive(inputs,"客户流水号",Int32.MaxValue,0);
Guid key;
if (!Guid.TryParseExact(Text(inputs,"客户端请求号",36,null),"D",out key) || key==Guid.Empty) throw BadInput();
cmd.Parameters.Add("@客户端请求号",SqlDbType.UniqueIdentifier).Value=key;
if (direct && key.Equals(cmd.Parameters["@需求请求号"].Value)) throw BadInput();
if (name==QuoteReceipt || name==QuoteEditReceipt || name==QuoteDirectProof) return;
var tax=cmd.Parameters.Add("@税率",SqlDbType.Decimal);
tax.Precision=9; tax.Scale=6; tax.Value=QuoteDecimal(inputs,"税率",6,1,true);
DateTime date;
if (!DateTime.TryParseExact(Text(inputs,"有效期",10,null),"yyyy-MM-dd",Invariant,DateTimeStyles.None,out date)) throw BadInput();
cmd.Parameters.Add("@有效期",SqlDbType.Date).Value=date;
cmd.Parameters.Add("@付款方式流水号",SqlDbType.Int).Value=(int)Positive(inputs,"付款方式流水号",Int32.MaxValue,0);
foreach (string field in new[]{"负责人","交货周期","交货方式","质保期限","备注"}) {
int limit=field=="备注"?500:100;
cmd.Parameters.Add("@"+field,SqlDbType.NVarChar,limit).Value=QuoteString(inputs,field,limit,field=="负责人");
}
object products,images;
if (!inputs.TryGetValue("产品行",out products) || !inputs.TryGetValue("图片行",out images)) throw BadInput();
var lines=QuoteLines(products as object[]);
AddQuoteTable(cmd,"@产品行","ai_报价管理_草稿产品行",lines);
AddQuoteTable(cmd,"@图片行","ai_报价管理_草稿图片行",QuoteImages(images as object[],lines.Rows.Count));
string digest=QuoteFingerprint(cmd);
cmd.Parameters.Add("@请求指纹",SqlDbType.Char,64).Value=digest;
}
}
}

View File

@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Jingyao.AIEmployee
{
public sealed partial class PersonalInboxHandler
{
const string ReworkAccept = "ai_供应商返工接收", ReworkStart = "ai_供应商返工启动准入",
ReworkAck = "ai_供应商返工接单回执", ReworkReturn = "ai_供应商返工完成回执";
static string ReworkRoute(string name)
{
switch (name) {
case ReworkAccept: case ReworkAccept + "_责任域_登记": return "/erp/supplier-rework-domain-acceptance";
case ReworkStart: case ReworkStart + "_策略版本_登记": case ReworkStart + "_启动申请_提交":
case ReworkStart + "_启动申请_复核": return "/erp/supplier-rework-start-request";
case ReworkAck: case ReworkAck + "_接单凭证_登记": return "/erp/supplier-rework-execution";
case ReworkReturn: case ReworkReturn + "_返厂发运_登记": return "/erp/supplier-rework-completion-return";
default: return null;
}
}
static bool ReworkQuery(string name)
{
return name == ReworkAccept || name == ReworkStart || name == ReworkAck || name == ReworkReturn;
}
static void ReworkDate(SqlCommand command, Dictionary<string,object> inputs, string field)
{
DateTime value;
if (!DateTime.TryParseExact(Text(inputs,field,10,null),"yyyy-MM-dd",Invariant,DateTimeStyles.None,out value)) throw BadInput();
command.Parameters.Add("@" + field,SqlDbType.Date).Value = value;
}
static void ReworkKey(SqlCommand command, Dictionary<string,object> inputs, string field)
{
object raw;
long maximum = inputs.TryGetValue(field,out raw) && raw is string ? Int64.MaxValue : 9007199254740991L;
command.Parameters.Add("@" + field, SqlDbType.BigInt).Value = Positive(inputs, field, maximum, 0);
}
static void BindRework(SqlCommand command, string name, Dictionary<string,object> inputs, Dictionary<string,object> body)
{
if (ReworkQuery(name)) {
Only(inputs,"执行契约流水号","状态");
object id;
if (inputs.TryGetValue("执行契约流水号", out id) && id != null && !Object.Equals(id,""))
ReworkKey(command,inputs,"执行契约流水号");
AddText(command,inputs,"状态",70,"ALL");
command.Parameters.Add("@页码",SqlDbType.Int).Value = (int)Positive(body,"pageList",100000,1);
command.Parameters.Add("@每页条数",SqlDbType.Int).Value = (int)Positive(body,"pageSize",200,25);
return;
}
if (body.ContainsKey("pageList") || body.ContainsKey("pageSize")) throw BadInput();
switch (name) {
case ReworkAccept + "_责任域_登记":
Only(inputs,"执行契约流水号","接受结论","接受意见","接受依据","幂等键");
ReworkKey(command,inputs,"执行契约流水号");
AddText(command,inputs,"接受结论",20,null,"ACCEPTED","REJECTED");
AddText(command,inputs,"接受意见",1000,null); AddText(command,inputs,"接受依据",1000,null);
break;
case ReworkStart + "_策略版本_登记":
Only(inputs,"执行契约流水号","策略类型","准入结论","策略内容哈希","有效开始日期","有效结束日期","准入意见","准入依据","幂等键");
ReworkKey(command,inputs,"执行契约流水号");
AddText(command,inputs,"策略类型",50,null,"ERP_SUPPLIER_REWORK_ROUTE","QMS_REINSPECTION_PLAN","WMS_QUARANTINE_POLICY","CROSS_SYSTEM_COMPENSATION_POLICY");
AddText(command,inputs,"准入结论",20,null,"APPROVED","REJECTED");
string hash = Text(inputs,"策略内容哈希",64,null);
if (!Regex.IsMatch(hash,@"\A[0-9a-fA-F]{64}\z")) throw BadInput();
command.Parameters.Add("@策略内容哈希",SqlDbType.Char,64).Value = hash.ToUpperInvariant();
ReworkDate(command,inputs,"有效开始日期"); ReworkDate(command,inputs,"有效结束日期");
AddText(command,inputs,"准入意见",1000,null); AddText(command,inputs,"准入依据",1000,null);
break;
case ReworkStart + "_启动申请_提交":
Only(inputs,"执行契约流水号","计划启动日期","计划完成日期","启动原因","启动依据","幂等键");
ReworkKey(command,inputs,"执行契约流水号");
ReworkDate(command,inputs,"计划启动日期"); ReworkDate(command,inputs,"计划完成日期");
AddText(command,inputs,"启动原因",1000,null); AddText(command,inputs,"启动依据",1000,null);
break;
case ReworkStart + "_启动申请_复核":
Only(inputs,"启动申请流水号","复核结论","复核意见","复核依据","幂等键");
ReworkKey(command,inputs,"启动申请流水号");
AddText(command,inputs,"复核结论",20,null,"APPROVED","REJECTED");
AddText(command,inputs,"复核意见",1000,null); AddText(command,inputs,"复核依据",1000,null);
break;
case ReworkAck + "_接单凭证_登记":
Only(inputs,"启动申请流水号","供应商接单回执号","供应商承诺完成日期","接单意见","接单依据","幂等键");
ReworkKey(command,inputs,"启动申请流水号");
AddText(command,inputs,"供应商接单回执号",100,null); ReworkDate(command,inputs,"供应商承诺完成日期");
AddText(command,inputs,"接单意见",1000,null); AddText(command,inputs,"接单依据",1000,null);
break;
case ReworkReturn + "_返厂发运_登记":
Only(inputs,"出库交接流水号","供应商完工凭证号","实际完成日期","返厂发运凭证号","返厂发运日期","完工摘要","完工依据","幂等键");
ReworkKey(command,inputs,"出库交接流水号");
AddText(command,inputs,"供应商完工凭证号",100,null); ReworkDate(command,inputs,"实际完成日期");
AddText(command,inputs,"返厂发运凭证号",100,null); ReworkDate(command,inputs,"返厂发运日期");
AddText(command,inputs,"完工摘要",1000,null); AddText(command,inputs,"完工依据",1000,null);
break;
default: throw BadInput();
}
BindIdempotency(command,inputs);
}
static object ReadRework(SqlCommand command, string name, SqlDataReader reader)
{
if (!ReworkQuery(name)) {
var receipt = ReadRows(reader,1);
if (receipt.Count != 1 || reader.NextResult()) throw Unavailable();
return new { rows = receipt };
}
int size = (int)command.Parameters["@每页条数"].Value, page = (int)command.Parameters["@页码"].Value;
var rows = ReadRows(reader,size);
var counts = NextRows(reader,1);
object count;
if (counts.Count != 1 || !counts[0].TryGetValue("筛选总数",out count) || count == null) throw Unavailable();
long total = Convert.ToInt64(count,Invariant);
if (total < 0 || total > 9007199254740991L || rows.Count != Math.Min(size,Math.Max(0,total-(page-1L)*size))) throw Unavailable();
return new { rows = rows, total = total, permissions = ReadPermissionCodes(reader,32) };
}
}
}