You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

530 lines
35 KiB

2 years ago
  1. using Aspose.Cells;
  2. using EasyBL.WebApi.Message;
  3. using Entity.Sugar;
  4. using Entity.ViewModels;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Linq;
  7. using SqlSugar;
  8. using SqlSugar.Base;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Drawing;
  13. using System.Linq;
  14. namespace EasyBL.WEBAPP.OPM
  15. {
  16. public class BillStatus_QryService : ServiceBase
  17. {
  18. #region 賬單狀態(分頁查詢)
  19. /// <summary>
  20. /// 賬單狀態(分頁查詢)
  21. /// </summary>
  22. /// <param name="i_crm"></param>
  23. /// <returns></returns>
  24. public ResponseMessage QueryPage(RequestMessage i_crm)
  25. {
  26. ResponseMessage rm = null;
  27. string sMsg = null;
  28. var db = SugarBase.GetIntance();
  29. try
  30. {
  31. do
  32. {
  33. var pml = new PageModel
  34. {
  35. PageIndex = _fetchInt(i_crm, @"pageIndex"),
  36. PageSize = _fetchInt(i_crm, @"pageSize")
  37. };
  38. var iPageCount = 0;
  39. var sSortField = _fetchString(i_crm, @"sortField");
  40. var sSortOrder = _fetchString(i_crm, @"sortOrder");
  41. var sBillNO = _fetchString(i_crm, @"BillNO");
  42. var sExhibitionName = _fetchString(i_crm, @"ExhibitionName");
  43. var sExhibitionSN = _fetchString(i_crm, @"ExhibitionSN");
  44. var sPayer = _fetchString(i_crm, @"Payer");
  45. var sPayerGuid = _fetchString(i_crm, @"PayerGuid");
  46. var sResponsiblePerson = _fetchString(i_crm, @"ResponsiblePerson");
  47. var sBillStatus = _fetchString(i_crm, @"BillStatus");
  48. string sSearchBetween = _fetchString(i_crm, "SearchBetween"); //查詢區間
  49. string sBillDateStart = _fetchString(i_crm, "BillDateStart"); //區間起始
  50. string sBillDateEnd = _fetchString(i_crm, "BillDateEnd"); //區間結束
  51. DateTime dtBillDateStart = DateTime.Now;
  52. DateTime dtBillDateEnd = DateTime.Now;
  53. var Filter = new CVPFilter();
  54. var bExcel = _fetchBool(i_crm, @"Excel");
  55. var sExcelType = _fetchString(i_crm, @"ExcelType");
  56. var spOrgID = new SugarParameter("@OrgID", i_crm.ORIGID);
  57. var spUserID = new SugarParameter("@UserID", i_crm.USERID);
  58. var saRoles = db.Queryable<OTB_SYS_MembersToRule>().Where(x => x.OrgID == i_crm.ORIGID && x.MemberID == i_crm.USERID).Select(x => x.RuleID).ToList().ToArray();
  59. var saDeptIdsByUser = db.Ado.SqlQuery<string>("SELECT DepartmentId FROM [dbo].[OFN_SYS_GetChilDepartmentIdByUserID](@OrgID,@UserID)", spOrgID, spUserID).ToArray();
  60. var saChildUserIds = db.Ado.SqlQuery<string>("SELECT MemberID FROM [dbo].[OFN_SYS_GetMemberIDDownByChief](@OrgID,@UserID)", spOrgID, spUserID).ToArray();
  61. var sDeptId = db.Queryable<OTB_SYS_Members>().Single(x => x.OrgID == i_crm.ORIGID && x.MemberID == i_crm.USERID).DepartmentID;
  62. var saStatus = sBillStatus.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  63. pml.DataList = db.Queryable<OTB_OPM_BillInfo, OTB_SYS_Members, OTB_SYS_Members, OTB_OPM_Exhibition, OTB_CRM_Customers, OTB_OPM_ExportExhibition, OTB_OPM_ImportExhibition, OTB_OPM_OtherExhibition, OTB_OPM_OtherExhibitionTG>
  64. ((t1, t2, t3, t4, t5, t6, t7, t8, t9) =>
  65. new object[] {
  66. JoinType.Inner, t1.OrgID == t2.OrgID && t1.CreateUser == t2.MemberID,
  67. JoinType.Left, t1.OrgID == t3.OrgID && t1.ResponsiblePerson == t3.MemberID,
  68. JoinType.Left, t1.OrgID == t4.OrgID && t1.ExhibitionNO == t4.SN.ToString(),
  69. JoinType.Left, t1.OrgID == t5.OrgID && t1.Payer == t5.guid,
  70. JoinType.Left, t1.OrgID == t6.OrgID && t1.ParentId == t6.ExportBillNO,
  71. JoinType.Left, t1.OrgID == t7.OrgID && t1.ParentId == t7.ImportBillNO,
  72. JoinType.Left, t1.OrgID == t8.OrgID && t1.ParentId == t8.Guid,
  73. JoinType.Left, t1.OrgID == t8.OrgID && t1.ParentId == t9.Guid}
  74. )
  75. .Where((t1) => t1.OrgID == i_crm.ORIGID)
  76. .WhereIF(!string.IsNullOrEmpty(sBillNO), (t1) => t1.BillNO.Contains(sBillNO))
  77. .WhereIF(!string.IsNullOrEmpty(sExhibitionName), (t1, t2, t3, t4) => (t4.Exhibitioname_TW + t4.Exhibitioname_EN + t4.ExhibitioShotName_TW).Contains(sExhibitionName))
  78. .WhereIF(!string.IsNullOrEmpty(sExhibitionSN), (t1, t2, t3, t4) => SqlFunc.ToString(t4.SN) == sExhibitionSN)
  79. .WhereIF(!string.IsNullOrEmpty(sPayer), (t1, t2, t3, t4, t5) => (t5.CustomerCName + t5.CustomerEName).Contains(sPayer))
  80. .WhereIF(!string.IsNullOrEmpty(sPayerGuid), (t1, t2, t3, t4, t5) => t5.guid == sPayerGuid)
  81. .WhereIF(!string.IsNullOrEmpty(sResponsiblePerson), (t1) => t1.ResponsiblePerson == sResponsiblePerson)
  82. .WhereIF(saStatus.Length > 0, (t1) => SqlFunc.ContainsArray(saStatus, t1.AuditVal))
  83. //帳單區間
  84. .WhereIF(sSearchBetween == "1" && DateTime.TryParse(sBillDateStart, out dtBillDateStart), (t1) => SqlFunc.ToDate(t1.BillFirstCheckDate) >= dtBillDateStart)
  85. .WhereIF(sSearchBetween == "1" && DateTime.TryParse(sBillDateEnd, out dtBillDateEnd), (t1) => SqlFunc.ToDate(t1.BillFirstCheckDate) < dtBillDateEnd)
  86. //銷帳區間
  87. .WhereIF(sSearchBetween == "2" && DateTime.TryParse(sBillDateStart, out dtBillDateStart), (t1) => SqlFunc.ToDate(t1.BillWriteOffDate) >= dtBillDateStart)
  88. .WhereIF(sSearchBetween == "2" && DateTime.TryParse(sBillDateEnd, out dtBillDateEnd), (t1) => SqlFunc.ToDate(t1.BillWriteOffDate) < dtBillDateEnd)
  89. //帳單創建區間
  90. .WhereIF(sSearchBetween == "3" && DateTime.TryParse(sBillDateStart, out dtBillDateStart), (t1) => SqlFunc.ToDate(t1.BillCreateDate) >= dtBillDateStart)
  91. .WhereIF(sSearchBetween == "3" && DateTime.TryParse(sBillDateEnd, out dtBillDateEnd), (t1) => SqlFunc.ToDate(t1.BillCreateDate) < dtBillDateEnd)
  92. //Excel下載,帳單成本金額
  93. .WhereIF(bExcel && sExcelType == "BillAndPrice", (t1) => t1.AuditVal != "6")
  94. .Where((t1) => t1.CreateUser == i_crm.USERID || t1.ResponsiblePerson == i_crm.USERID
  95. ||
  96. //SqlFunc.Subqueryable<OTB_SYS_Members>().Where(c => c.MemberID == t1.ResponsiblePerson && c.OrgID == t1.OrgID).Select(c => c.DepartmentID) == sDeptId || //挑選出相同部門的資料
  97. //SqlFunc.Subqueryable<OTB_SYS_Members>().Where(p => p.MemberID == t1.CreateUser && p.OrgID == t1.OrgID).Select(c => c.DepartmentID) == sDeptId ////挑選出相同部門的資料
  98. //||
  99. SqlFunc.Subqueryable<OTB_SYS_Members>().Where(p => p.MemberID == t1.ResponsiblePerson && p.OrgID == t1.OrgID).Select(c => c.ImmediateSupervisor) == i_crm.USERID
  100. ||
  101. SqlFunc.MappingColumn(t1.BillNO, "[dbo].[OFN_OPM_CheckBillCreateUser](t1.BillType,t1.ParentId)") == i_crm.USERID
  102. || SqlFunc.ContainsArray(saChildUserIds, t1.ResponsiblePerson) || SqlFunc.ContainsArray(saRoles, "Account") || SqlFunc.ContainsArray(saRoles, "CDD") || SqlFunc.ContainsArray(saRoles, "Admin") || SqlFunc.ContainsArray(saRoles, "Manager"))
  103. .Select((t1, t2, t3, t4, t5, t6, t7, t8, t9) => new View_OPM_BillInfo
  104. {
  105. OrgID = t1.OrgID,
  106. BillNO = t1.BillNO,
  107. ExhibitioName = t4.Exhibitioname_TW,
  108. BillType = t1.BillType,
  109. ParentId = t1.ParentId,
  110. IsRetn = t1.IsRetn,
  111. ReFlow = t1.ReFlow,
  112. PayerName = SqlFunc.IIF(SqlFunc.HasValue(t5.CustomerCName), t5.CustomerCName, t5.CustomerEName),
  113. ResponsiblePersonName = t3.MemberName,
  114. Currency = t1.Currency,
  115. Payer = t1.Payer,
  116. Number = t1.Number + t1.Unit,
  117. Weight = t1.Weight,
  118. Volume = t1.Volume,
  119. CreateUserName = t2.MemberName,
  120. BillCreateDate = t1.BillCreateDate,
  121. AuditVal = t1.AuditVal,
  122. ExchangeRate = t1.ExchangeRate,
  123. Advance = t1.Advance,
  124. AmountSum = t1.AmountSum,
  125. TaxSum = t1.TaxSum,
  126. AmountTaxSum = t1.AmountTaxSum,
  127. TotalReceivable = t1.TotalReceivable,
  128. FeeItems = t1.FeeItems,
  129. CreateDate = SqlFunc.MappingColumn(t1.CreateDate, "CASE BillType WHEN 'ExhibitionExport_Upd' THEN t6.CreateDate WHEN 'ExhibitionImport_Upd' THEN t7.CreateDate WHEN 'OtherBusiness_Upd' THEN t8.CreateDate WHEN 'OtherExhibitionTG_Upd' THEN t9.CreateDate END"),
  130. _ExchangeRate = SqlFunc.MappingColumn(t1.SN, "CONVERT(decimal,CASE ISNULL(t1.ExchangeRate,'') WHEN '' THEN '0' ELSE t1.ExchangeRate END)"),
  131. _Advance = SqlFunc.MappingColumn(t1.SN, "CONVERT(decimal,REPLACE(t1.Advance,',',''))"),
  132. _AmountSum = SqlFunc.MappingColumn(t1.SN, "CONVERT(decimal,REPLACE(t1.AmountSum,',',''))"),
  133. _TaxSum = SqlFunc.MappingColumn(t1.SN, "CONVERT(decimal,REPLACE(t1.TaxSum,',',''))"),
  134. _AmountTaxSum = SqlFunc.MappingColumn(t1.SN, "CONVERT(decimal,REPLACE(t1.AmountTaxSum,',',''))"),
  135. _TotalReceivable = SqlFunc.MappingColumn(t1.SN, "CONVERT(decimal,REPLACE(t1.TotalReceivable,',',''))"),
  136. //BillCheckDate = SqlFunc.MappingColumn(t1.BillCheckDate, "CONVERT(datetime,CASE ISNULL(BillCheckDate,'') WHEN '' THEN '0' ELSE BillCheckDate END)"),
  137. //BillWriteOffDate = SqlFunc.MappingColumn(t1.BillCheckDate, "CONVERT(datetime,CASE ISNULL(BillWriteOffDate,'') WHEN '' THEN '0' ELSE BillWriteOffDate END)")
  138. // 20180308 可能要額外判斷欄位是否為NULL或空值,不然會有轉換資料時會出錯
  139. //_Advance = SqlFunc.MappingColumn(t1.SN, "Convert(decimal,case isnull(Advance,'') when '' then '0' else REPLACE(Advance,',','') end)"),
  140. //_AmountSum = SqlFunc.MappingColumn(t1.SN, "Convert(decimal,case isnull(AmountSum,'') when '' then '0' else REPLACE(AmountSum,',','') end)"),
  141. //_TaxSum = SqlFunc.MappingColumn(t1.SN, "Convert(decimal,case isnull(TaxSum,'') when '' then '0' else REPLACE(TaxSum,',','') end)"),
  142. //_AmountTaxSum = SqlFunc.MappingColumn(t1.SN, "Convert(decimal,case isnull(AmountTaxSum,'') when '' then '0' else REPLACE(AmountTaxSum,',','') end)"),
  143. //_TotalReceivable = SqlFunc.MappingColumn(t1.SN, "Convert(decimal,case isnull(TotalReceivable,'') when '' then '0' else REPLACE(TotalReceivable,',','') end)")
  144. })
  145. .MergeTable()
  146. .OrderBy(("_ExchangeRate,_Advance,_AmountSum,_TaxSum,_AmountTaxSum,_TotalReceivable".Contains(sSortField) ? "_" : "") + sSortField, sSortOrder)
  147. .ToPageList(pml.PageIndex, bExcel ? 100000 : pml.PageSize, ref iPageCount);
  148. pml.Total = iPageCount;
  149. Dictionary<string, decimal> dicCurrencyInfo = new Dictionary<string, decimal>();
  150. foreach (View_OPM_BillInfo billinfo in pml.DataList as List<View_OPM_BillInfo>)
  151. {
  152. billinfo._ExchangeRate = 0M;
  153. /* 匯率抓取 */
  154. if (billinfo.CreateDate != default(DateTime))
  155. {
  156. if (!string.IsNullOrEmpty(billinfo.Currency))
  157. {
  158. int iYear = SqlFunc.ToDate(billinfo.CreateDate).Year;
  159. int iMonth = SqlFunc.ToDate(billinfo.CreateDate).Month;
  160. string sKey = $"{ iYear }|{iMonth}|{billinfo.Currency}";
  161. if (!dicCurrencyInfo.Keys.Contains(sKey))
  162. {
  163. var data = db.Queryable<OTB_SYS_Currency>()
  164. .Single(p => p.OrgID == billinfo.OrgID &&
  165. p.year == iYear &&
  166. p.month == iMonth &&
  167. p.currency == billinfo.Currency);
  168. if (data != null)
  169. {
  170. dicCurrencyInfo.Add(sKey, data.exchange_rate);
  171. }
  172. else
  173. {
  174. continue;
  175. }
  176. }
  177. billinfo.ExchangeRate = dicCurrencyInfo[sKey].ToString("#0.##");
  178. billinfo._ExchangeRate = dicCurrencyInfo[sKey];
  179. }
  180. }
  181. }
  182. rm = new SuccessResponseMessage(null, i_crm);
  183. if (bExcel)
  184. {
  185. var AllCBMUsage = CommonRPT.GetAllCBMUsages(db, i_crm.ORIGID);
  186. #region 設定幣別名稱
  187. var CurrencyName = CommonRPT.GetCurrencyUnit(i_crm.ORIGID);
  188. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  189. var DollorFormated = "N" + RoundingPoint.ToString();
  190. #endregion
  191. var sFileName = "";
  192. var oHeader = new Dictionary<string, string>();
  193. var listMerge = new List<Dictionary<string, int>>();
  194. var dicAlain = new Dictionary<string, string>();
  195. var saBillInfo = pml.DataList as List<View_OPM_BillInfo>;
  196. var dt_new = saBillInfo.ListToDataTable<View_OPM_BillInfo>();
  197. var saBillPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "PrepayForCustomerCode");
  198. var BillPrepayFeeList = saBillPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  199. var saActualPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "ActualPrepayForCustomerCode");
  200. var ActualPrepayFeeList = saActualPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  201. switch (sExcelType)
  202. {
  203. case "BillList":
  204. sFileName = "帳單狀態查詢資料";
  205. oHeader = new Dictionary<string, string>
  206. {
  207. { "RowIndex", "項次" },
  208. { "BillNO", "帳單號碼" },
  209. { "ExhibitioName", "展覽/活動名稱" },
  210. { "PayerName", "付款人" },
  211. { "ResponsiblePersonName", "負責業務" },
  212. { "Currency", "幣別代號" },
  213. //{ "ExchangeRate", "匯率" },
  214. { "Advance", "預收金額(A)" },
  215. { "AmountSum", "未稅金額(B)" },
  216. { "TaxSum", "稅金(C)" },
  217. { "AmountTaxSum", "含稅金額(D)=B+C" },
  218. { "TotalReceivable", "總應收D-A" },
  219. { "ExchangeRate", "匯率(會計用)(E)" },
  220. { "UntaxAmountMutiRate", $"未稅金額({CurrencyName})(B*E)" }, //new
  221. { "BillReimburseAmount", $"帳單代墊款({CurrencyName})" },
  222. { "CreateUserName", "創建人員" },
  223. { "BillCreateDate", "帳單創建時間" },
  224. { "AuditVal", "帳單狀態" }
  225. };
  226. dt_new.Columns.Add("UntaxAmountMutiRate");
  227. dt_new.Columns.Add("BillReimburseAmount");
  228. double UntaxAmountMutiRateTotalByLocalCurrency = 0;
  229. decimal BillReimburseAmountTotalByLocalCurrency = 0;
  230. foreach (DataRow row in dt_new.Rows)
  231. {
  232. double.TryParse(row["ExchangeRate"].ToString(), out var dExchangeRate);
  233. double.TryParse(row["AmountSum"].ToString(), out var dAmountSum);
  234. row["Advance"] = row["Advance"].ToString() == "" ? "0" : $"{Convert.ToDouble(row["Advance"].ToString()):N2}";
  235. row["AmountSum"] = row["AmountSum"].ToString() == "" ? "0" : $"{dAmountSum:N2}";
  236. row["TaxSum"] = row["TaxSum"].ToString() == "" ? "0" : $"{Convert.ToDouble(row["TaxSum"].ToString()):N2}";
  237. row["AmountTaxSum"] = row["AmountTaxSum"].ToString() == "" ? "0" : $"{Convert.ToDouble(row["AmountTaxSum"].ToString()):N2}";
  238. row["TotalReceivable"] = row["TotalReceivable"].ToString() == "" ? "0" : $"{Convert.ToDouble(row["TotalReceivable"].ToString()):N2}";
  239. row["BillCreateDate"] = Convert.ToDateTime(row["BillCreateDate"].ToString()).ToString("yyyy/MM/dd HH:mm");
  240. //換算匯率
  241. //帳單代墊款(NTD)
  242. var BillFeeItemList = CommonRPT.ToFeeItems(row["FeeItems"].ObjToString());
  243. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  244. var BillReimburseAmountLocalCurrency = Rounding(BillReimburseAmount * dExchangeRate.ObjToDecimal(), RoundingPoint);
  245. row["BillReimburseAmount"] = $"{BillReimburseAmountLocalCurrency:N2}";
  246. BillReimburseAmountTotalByLocalCurrency += BillReimburseAmountLocalCurrency;
  247. //未稅金額(NTD)
  248. var UntaxAmountSubtotalLocalCurrency = Rounding(dAmountSum * dExchangeRate, RoundingPoint);
  249. row["UntaxAmountMutiRate"] = $"{UntaxAmountSubtotalLocalCurrency:N2}";
  250. UntaxAmountMutiRateTotalByLocalCurrency += UntaxAmountSubtotalLocalCurrency;
  251. var sBill_Status = "";
  252. switch (row["AuditVal"].ToString())
  253. {
  254. case "0"://未提交審核
  255. sBill_Status = "未提交審核";
  256. break;
  257. case "1"://提交審核中
  258. sBill_Status = "提交審核中";
  259. break;
  260. case "2"://已審核
  261. sBill_Status = "已審核";
  262. break;
  263. case "3"://不通過
  264. sBill_Status = "不通過";
  265. break;
  266. case "4"://已銷帳
  267. sBill_Status = "已銷帳";
  268. break;
  269. case "5"://已過帳
  270. sBill_Status = "已過帳";
  271. break;
  272. case "6"://已作廢
  273. sBill_Status = "已作廢";
  274. break;
  275. case "7"://抽單中
  276. sBill_Status = "抽單中";
  277. break;
  278. default:
  279. break;
  280. }
  281. row["AuditVal"] = sBill_Status;
  282. }
  283. var rowLast1 = dt_new.NewRow();
  284. rowLast1["ExchangeRate"] = "總計" + CurrencyName;
  285. rowLast1["UntaxAmountMutiRate"] = $"{UntaxAmountMutiRateTotalByLocalCurrency:N2}";
  286. rowLast1["BillReimburseAmount"] = $"{BillReimburseAmountTotalByLocalCurrency:N2}";
  287. dt_new.Rows.Add(rowLast1);
  288. dicAlain = ExcelService.GetExportAlain(oHeader, "RowIndex", "ExchangeRate,Advance,AmountSum,TaxSum,TotalReceivable,AmountTaxSum,UntaxAmountMutiRate,BillReimburseAmount");
  289. break;
  290. case "BillAndPrice":
  291. sFileName = "帳單成本金額";
  292. #region 檢查幣別設定
  293. var EmptyECurrency = saBillInfo.Where(c => string.IsNullOrWhiteSpace(c.Currency)).Select(c => c.BillNO).Distinct().ToList();
  294. var EmptyExchangeRates = saBillInfo.Where(c => string.IsNullOrWhiteSpace(c.ExchangeRate)).Select(c => c.BillNO).Distinct().ToList();
  295. if (EmptyECurrency.Any() || EmptyExchangeRates.Any())
  296. {
  297. string ErrorMsg = string.Empty;
  298. if (EmptyECurrency.Any())
  299. ErrorMsg += $"帳單:{ string.Join(",", EmptyECurrency)}幣別為空。";
  300. if (EmptyExchangeRates.Any())
  301. ErrorMsg += $"帳單:{ string.Join(",", EmptyExchangeRates)}匯率為空。";
  302. if (i_crm.LANG == @"zh")
  303. ErrorMsg = ErrorMsg = ChineseStringUtility.ToSimplified(ErrorMsg);
  304. return new ErrorResponseMessage(ErrorMsg, i_crm);
  305. }
  306. #endregion
  307. oHeader = new Dictionary<string, string>
  308. {
  309. { "RowIndex", "項次" },
  310. { "ExhibitioName", "展覽/活動名稱" },
  311. { "PayerName", "付款人" },
  312. { "BillNO", "帳單號碼" },
  313. { "AmountSum", $"未稅金額({CurrencyName})" },
  314. { "BillReimburseAmount", $"帳單代墊款({CurrencyName})" },
  315. { "ActualCost", $"實際成本({CurrencyName})" },
  316. { "ActualBillReimburseAmount", $"實際代墊款({CurrencyName})" },
  317. { "Number", "件數" },
  318. { "Weight", "重量" },
  319. { "Volume", "材積(CBM)" },
  320. { "TransportationMode", "運送方式" },
  321. { "IsRetn", "是否退運" }
  322. };
  323. dt_new.Columns.Add("BillReimburseAmount");
  324. dt_new.Columns.Add("ActualBillReimburseAmount");
  325. dt_new.Columns.Add("ActualCost");
  326. dt_new.Columns.Add("TransportationMode");
  327. Double iTotalAmountSum = 0;
  328. Double iTotalActualCost = 0;
  329. Double iTotalBillReimburseAmount = 0;
  330. Double iTotalActualBillReimburseAmount = 0;
  331. foreach (DataRow row in dt_new.Rows)
  332. {
  333. var ActualCostFeeItemJson = "";
  334. var sActualCost = "";
  335. var sTransportationMode = "";
  336. var _sBillNO = row["BillNO"].ToString();
  337. var sId = row["ParentId"].ToString();
  338. var sOrgId = row["OrgID"].ToString();
  339. var BillParentId = row[View_OPM_BillInfo.CN_PARENTID].ObjToString();
  340. var sIsRetn = row["IsRetn"].ToString();
  341. var sReFlow = row["ReFlow"].ToString();
  342. var sBillType = row["BillType"].ToString();
  343. var ThisBillCBMUsage = AllCBMUsage.Where(t1 => t1.ParentID == BillParentId && t1.IsReturn == sIsRetn).ToList();
  344. CommonRPT.CalcuCostAndProfit(db, ref ActualCostFeeItemJson, ref sActualCost, ref sTransportationMode, _sBillNO, sId, sIsRetn, sReFlow, sBillType);
  345. if (!string.IsNullOrEmpty(sTransportationMode))
  346. {
  347. var oArgument = db.Queryable<OTB_SYS_Arguments>().Single(it => it.OrgID == sOrgId && it.ArgumentClassID == "Transport" && it.ArgumentID == sTransportationMode);
  348. if (oArgument == null)
  349. {
  350. oArgument = new OTB_SYS_Arguments();
  351. }
  352. row["TransportationMode"] = oArgument.ArgumentValue ?? "";
  353. }
  354. row["IsRetn"] = sIsRetn == "Y" ? "是" : "否";
  355. var ActualCostFeeItemList = CommonRPT.ToFeeItems(ActualCostFeeItemJson);
  356. //實際成本(成本 + 代墊款 ): (整票貨總成本/整票貨CBM)*單家廠商CBM
  357. var SharedActualCost = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, _sBillNO);
  358. SharedActualCost = Rounding(SharedActualCost, RoundingPoint);
  359. row["ActualCost"] = $"{SharedActualCost:N2}";
  360. iTotalActualCost += SharedActualCost.ObjToMoney();
  361. //帳單代墊款 BillReimburseAmount ==> bill裡面的
  362. var BillFeeItemList = CommonRPT.ToFeeItems(row["FeeItems"].ObjToString());
  363. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  364. BillReimburseAmount = Rounding(BillReimburseAmount, RoundingPoint);
  365. row["BillReimburseAmount"] = BillReimburseAmount;
  366. iTotalBillReimburseAmount += BillReimburseAmount.ObjToMoney();
  367. //實際代墊款(NT$) ==> 成本裡面的
  368. var ActualBillReimburseAmount = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, _sBillNO, ActualPrepayFeeList);//抓實際成本的資料
  369. ActualBillReimburseAmount = Rounding(ActualBillReimburseAmount, RoundingPoint);
  370. row["ActualBillReimburseAmount"] = ActualBillReimburseAmount;
  371. iTotalActualBillReimburseAmount += ActualBillReimburseAmount.ObjToMoney();
  372. #region ConvertToTWD 僅只有Receivable
  373. double RowExchangeRate = 0;
  374. double AmountSum = 0;
  375. double.TryParse(row["ExchangeRate"].ToString(), out RowExchangeRate);
  376. double.TryParse(row["AmountSum"].ToString(), out AmountSum);
  377. double MultipliedAmountSum = Math.Round(AmountSum * RowExchangeRate, MidpointRounding.AwayFromZero);
  378. row["AmountSum"] = MultipliedAmountSum.ToString();
  379. iTotalAmountSum += MultipliedAmountSum;
  380. #endregion
  381. }
  382. var rowLast = dt_new.NewRow();
  383. rowLast["RowIndex"] = dt_new.Rows.Count + 1;
  384. rowLast["ExhibitioName"] = "";
  385. rowLast["PayerName"] = "";
  386. rowLast["BillNO"] = "總計" + CurrencyName;
  387. rowLast["AmountSum"] = $"{iTotalAmountSum:N2}";
  388. rowLast["ActualCost"] = $"{iTotalActualCost:N2}";
  389. rowLast["BillReimburseAmount"] = $"{iTotalBillReimburseAmount:N2}";
  390. rowLast["ActualBillReimburseAmount"] = $"{iTotalActualBillReimburseAmount:N2}";
  391. rowLast["Number"] = "";
  392. rowLast["Weight"] = "";
  393. rowLast["Volume"] = "";
  394. rowLast["TransportationMode"] = "";
  395. rowLast["IsRetn"] = "";
  396. dt_new.Rows.Add(rowLast);
  397. dicAlain = ExcelService.GetExportAlain(oHeader, "RowIndex,IsRetn", "ActualCost,AmountSum,ActualBillReimburseAmount,BillReimburseAmount,Weight,Volume");
  398. break;
  399. default:
  400. {
  401. break;
  402. }
  403. }
  404. var bOk = new ExcelService().CreateExcelByTb(dt_new, out string sPath, oHeader, dicAlain, listMerge, sFileName);
  405. if (bOk)
  406. {
  407. var hightLight = Color.FromArgb(226, 240, 217);
  408. HightLightColumn(sExcelType, sPath, hightLight);
  409. }
  410. rm.DATA.Add(BLWording.REL, sPath);
  411. }
  412. else
  413. {
  414. rm.DATA.Add(BLWording.REL, pml);
  415. }
  416. } while (false);
  417. }
  418. catch (Exception ex)
  419. {
  420. sMsg = Util.GetLastExceptionMsg(ex);
  421. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(BillStatus_QryService), "", "QueryPage(賬單狀態(分頁查詢))", "", "", "");
  422. }
  423. finally
  424. {
  425. if (null != sMsg)
  426. {
  427. rm = new ErrorResponseMessage(sMsg, i_crm);
  428. }
  429. }
  430. return rm;
  431. }
  432. #endregion 賬單狀態(分頁查詢)
  433. public OVW_OPM_BillInfo GetBillInfoByRow(DataRow row, string isRetun)
  434. {
  435. var sAuditVal = row["AuditVal"] == null ? "" : row["AuditVal"].ToString();
  436. var sVolume = row["Volume"] == null ? "0" : row["Volume"].ToString();
  437. OVW_OPM_BillInfo _BillInfo = new OVW_OPM_BillInfo()
  438. {
  439. OrgID = row["OrgID"].ToString(),
  440. ParentId = row["ParentId"].ToString(),
  441. IsRetn = isRetun,
  442. AuditVal = sAuditVal,
  443. Volume = sVolume
  444. };
  445. return _BillInfo;
  446. }
  447. public decimal Rounding(decimal value, int digit = 0)
  448. {
  449. if (digit <= 0)
  450. return Math.Round(value, MidpointRounding.AwayFromZero);
  451. else
  452. return Math.Round(value, digit, MidpointRounding.AwayFromZero);
  453. }
  454. public double Rounding(double value, int digit = 0)
  455. {
  456. if (digit <= 0)
  457. return Math.Round(value, MidpointRounding.AwayFromZero);
  458. else
  459. return Math.Round(value, digit, MidpointRounding.AwayFromZero);
  460. }
  461. public void HightLightColumn(string Type, string ExcelPath, Color color)
  462. {
  463. if (Type == "BillList")
  464. {
  465. var cellsApp = new ExcelService(ExcelPath);
  466. var cells = cellsApp.sheet.Cells;//单元格
  467. var StartColumnIndex = 11;
  468. var EndColumnIndex = StartColumnIndex + 3;
  469. var StartRowIndex = 3;
  470. var EndRowIndex = cells.Rows.Count;
  471. for (int row = StartRowIndex; row < EndRowIndex; row++)
  472. {
  473. for (int col = StartColumnIndex; col < EndColumnIndex; col++)
  474. {
  475. var Style = cells[row, col].GetStyle();
  476. Style.ForegroundColor = color;
  477. //Style.BackgroundColor = color;
  478. cells[row, col].SetStyle(Style);
  479. }
  480. }
  481. cellsApp.workbook.Save(ExcelPath);
  482. }
  483. }
  484. }
  485. }