合并两个工位的 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,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);
}
}
}
}
}