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(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;nMaximum) 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(offset0) offset+=count; if(offset!=bytes.Length || input.ReadByte()!=-1) throw Bad("附件长度不符"); } string hash=Hash(bytes), mime=Type(filename,bytes); var ids=new SortedSet(); 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(""); foreach(int id in ids) xml.Append("").Append(id.ToString(Invariant)).Append(""); xml.Append(""); 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(); 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(); for(int n=0;nMaximum || 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); } } } } }