using System.Text; using DS.Module.Core; using DS.Module.Core.Extensions; using DS.WMS.Core.Application.Dtos; using DS.WMS.Core.Application.Entity; using DS.WMS.Core.Application.Interface; using DS.WMS.Core.Fee.Entity; using DS.WMS.Core.Fee.Method; using DS.WMS.Core.Info.Entity; using DS.WMS.Core.Op.Entity; using Microsoft.Extensions.Hosting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DS.WMS.Core.Application.Method { /// /// 发票模板服务 /// public class InvoiceTemplateService : FeeServiceBase, IInvoiceTemplateService { const int MAX_NUM = 3;//每个用户的最大模板数量 /// /// 初始化 /// /// public InvoiceTemplateService(IServiceProvider serviceProvider) : base(serviceProvider) { } /// /// 获取模板字段 /// /// public DataResult> GetFields(IHostEnvironment environment) { string path = Path.Combine(environment.ContentRootPath, "inv_template.json"); if (!File.Exists(path)) return DataResult>.FailedWithDesc(nameof(MultiLanguageConst.TemplateFileNotFound)); string json = File.ReadAllText(path); var list = JsonConvert.DeserializeObject>(json); return DataResult>.Success(list); } /// /// 获取列表 /// /// 模板所有人 /// 如果为空则创建 /// public DataResult> GetList(long userId, bool createIfEmpty) { var list = TenantDb.Queryable().Where(x => x.CreateBy == userId) .OrderByDescending(x => x.CreateTime).Take(MAX_NUM).ToList(); if (list.Count == 0 && createIfEmpty) { var arr = new InvoiceTemplate[MAX_NUM]; for (int i = 0; i < MAX_NUM; i++) { arr[i] = new InvoiceTemplate { Content = string.Empty, Name = $"{MultiLanguageConst.DefaultTemplateName}{i + 1}" }; } return Save(arr); } return DataResult>.Success(list); } /// /// 保存模板 /// /// public DataResult> Save(params InvoiceTemplate[] templates) { int rows = TenantDb.Storageable(templates).DefaultAddElseUpdate().ExecuteCommand(); return rows > 0 ? DataResult>.Success(new List(templates)) : DataResult>.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed)); } /// /// 渲染模板 /// /// 发票申请ID /// 模板文本 /// /// public async Task> RenderTemplateAsync(long id, string templateText, IHostEnvironment environment) { var dto = await GetTemplateFormAsync(id); if (dto == null) return DataResult.FailedWithDesc(nameof(MultiLanguageConst.EmptyData)); string json = JsonConvert.SerializeObject(dto); var jObj = JObject.Parse(json); var jArray = jObj[nameof(InvoiceTemplateForm.Details)] as JArray; StringBuilder sb = new(templateText); StringBuilder sb2 = new(); var fields = GetFields(environment).Data; foreach (var field in fields) { //循环输出 if (templateText.Contains($"<{field.FieldName}>")) { foreach (var item in jArray) { sb2.Append(item[field.FieldName]?.Value()); sb2.Append(' '); } if (sb2.Length > 0) { sb2.Remove(sb2.Length - 1, 1); //移除最后一个空格 sb = sb.Replace($"<{field.FieldName}>", sb2.ToString()); sb2.Clear(); } } //单次输出 else if (templateText.Contains($"[{field.FieldName}]")) { string val = string.Empty; if (field.IsSumValue) { val = jObj[field.FieldName]?.Value(); } else if (jArray.Count > 0) { var item1 = jArray[0]; val = item1[field.FieldName]?.Value(); } if (!val.IsNullOrEmpty()) sb = sb.Replace($"[{field.FieldName}]", val); } } return DataResult.Success(sb.ToString()); } /// /// 获取发票模板所需数据 /// /// 发票申请ID /// internal async Task GetTemplateFormAsync(long id) { var dto = await TenantDb.Queryable() .LeftJoin((a, b) => a.CustomerBankId == b.Id) .Where((a, b) => a.Id == id).Select((a, b) => new InvoiceTemplateForm { CustomerId = a.CustomerId, CustomerName = a.CustomerName, CustomerBankId = a.CustomerBankId, ClientAccount = b.Account, ClientBankName = b.BankName }).FirstAsync(); if (dto != null) { dto.Details = await TenantDb.Queryable() .LeftJoin((d, f) => d.RecordId == f.Id) .Where(d => d.ApplicationId == id) .Select((d, f) => new InvoiceTemplateDetail { Amount = d.ApplyAmount, OriginalAmount = d.OriginalAmount, OriginalCurrency = d.OriginalCurrency, OriginalRate = f.ExchangeRate, ExchangeRate = d.ExchangeRate }).ToListAsync(); var gList = dto.Details.GroupBy(x => x.BusinessType).ToList(); foreach (var g in gList) { var ids = g.Select(x => x.BusinessId).ToList(); switch (g.Key) { case BusinessType.OceanShippingExport: var list1 = await TenantDb.Queryable().Where(x => ids.Contains(x.Id)).Select(x => new { x.Id, x.MBLNO, x.CustomerNo, ClientName = x.CustomerName, x.ETD, x.CntrTotal, x.AccountDate, x.OperatorCode, x.Vessel, x.Voyno, x.LoadPort, x.DischargePort, x.Destination }).ToListAsync(); foreach (var item in g) { var biz = list1.Find(x => x.Id == item.BusinessId); if (biz != null) { item.MBLNO = biz.MBLNO; item.ClientName = biz.ClientName; item.CustomerNo = biz.CustomerNo; item.ETD = biz.ETD; item.CntrTotal = biz.CntrTotal; item.Vessel = biz.Vessel; item.Voyage = biz.Voyno; item.LoadPort = biz.LoadPort; item.DischargePort = biz.DischargePort; item.Destination = biz.Destination; item.ForeignAmount = item.OriginalCurrency != RMB_CODE ? item.OriginalAmount : 0; item.RMBAmount = item.OriginalCurrency == RMB_CODE ? item.OriginalAmount : 0; } } break; case BusinessType.OceanShippingImport: break; } } dto.ForeignTotal = dto.Details.Sum(x => x.ForeignAmount); dto.RMBTotal = dto.Details.Sum(x => x.RMBAmount); dto.ExchangeRateTotal = dto.Details.Sum(x => x.ExchangeRate); } return dto; } } }