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.

2260 lines
134 KiB

2 years ago
  1. using Aspose.Cells;
  2. using EasyBL.WebApi.Message;
  3. using EasyNet.Common;
  4. using Entity.Sugar;
  5. using Entity.ViewModels;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using SqlSugar;
  9. using SqlSugar.Base;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Drawing;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Diagnostics;
  16. namespace EasyBL.WEBAPP.RPT
  17. {
  18. public class CostAndProfitReportService : ServiceBase
  19. {
  20. private bool ShowSource = false;
  21. private static int TimeOut = 120;
  22. #region 利潤明細表(依業務)
  23. public ResponseMessage CVPAnalysisBySaler(RequestMessage i_crm)
  24. {
  25. //帳單(拋轉)區間、銷帳區間、部門、業務
  26. ShowSource = CommonRPT.RPTShow();
  27. ResponseMessage rm = null;
  28. string sMsg = null;
  29. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  30. var FunctionName = nameof(CVPAnalysisBySaler);
  31. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "利潤明細表(依業務)");
  32. var sOutPut = ExcutePath.Item1;
  33. var sTempFile = ExcutePath.Item2;
  34. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  35. var CurrencyUnit = CommonRPT.GetCurrencyUnit(i_crm.ORIGID);
  36. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  37. try
  38. {
  39. do
  40. {
  41. var saBillPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "PrepayForCustomerCode");
  42. var BillPrepayFeeList = saBillPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  43. var saActualPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "ActualPrepayForCustomerCode");
  44. var ActualPrepayFeeList = saActualPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  45. var sBillAuditDateStart = _fetchString(i_crm, @"BillAuditDateStart");
  46. var sBillAuditDateEnd = _fetchString(i_crm, @"BillAuditDateEnd");
  47. var sBillWriteOffDateStart = _fetchString(i_crm, @"BillWriteOffDateStart");
  48. var sBillWriteOffDateEnd = _fetchString(i_crm, @"BillWriteOffDateEnd");
  49. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  50. var sResponsiblePerson = _fetchString(i_crm, @"ResponsiblePerson");
  51. var SearchMatchedExps = !string.IsNullOrWhiteSpace(sResponsibleDeptID) || !string.IsNullOrWhiteSpace(sResponsiblePerson);
  52. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  53. var MatchedExpList = CommonRPT.GetMatchedExps(db, i_crm.ORIGID, ChildDeptIDs, sResponsiblePerson);
  54. var MatchedExpGuids = MatchedExpList.Select(t1 => t1.Guid).Distinct().ToArray();
  55. var sFlag = _fetchString(i_crm, @"Flag");
  56. var Filter = new CVPFilter();
  57. Filter.SetBill(sBillAuditDateStart, sBillAuditDateEnd, sBillWriteOffDateStart, sBillWriteOffDateEnd);
  58. //撈取符合的billguid
  59. var view = db.Queryable<OVW_OPM_Bills, OTB_OPM_BillInfo>
  60. ((t1, t2) =>
  61. new object[] {
  62. JoinType.Inner, t1.OrgID == t2.OrgID && t1.BillNO == t2.BillNO
  63. }
  64. )
  65. .Where((t1, t2) => t1.OrgID == i_crm.ORIGID && Filter.PassStatus.Contains(t2.AuditVal))
  66. .WhereIF(SearchMatchedExps, (t1, t2) => SqlFunc.ContainsArray(MatchedExpGuids, t2.ParentId))
  67. .WhereIF(!string.IsNullOrEmpty(Filter.sBillAuditDateStart), (t1, t2) => SqlFunc.ToDate(t2.BillFirstCheckDate) >= Filter.rBillAuditDateStart.Date)
  68. .WhereIF(!string.IsNullOrEmpty(Filter.sBillAuditDateEnd), (t1, t2) => SqlFunc.ToDate(t2.BillFirstCheckDate) < Filter.rBillAuditDateEnd.Date)
  69. .WhereIF(!string.IsNullOrEmpty(Filter.sBillWriteOffDateStart), (t1, t2) => SqlFunc.ToDate(t2.BillWriteOffDate) >= Filter.rBillWriteOffDateStart.Date)
  70. .WhereIF(!string.IsNullOrEmpty(Filter.sBillWriteOffDateEnd), (t1, t2) => SqlFunc.ToDate(t2.BillWriteOffDate) < Filter.rBillWriteOffDateEnd.Date);
  71. var saBills = view.Select((t1, t2) =>
  72. new View_OPM_BillIReport
  73. {
  74. BillNO = t2.BillNO,
  75. BillType = t2.BillType,
  76. ParentId = t2.ParentId,
  77. ProjectNumber = t1.ProjectNumber,
  78. CustomerCode = t1.CustomerCode,
  79. ResponsiblePerson = t2.ResponsiblePerson,
  80. Currency = t2.Currency,
  81. ExchangeRate = t2.ExchangeRate,
  82. InCome = t1.TWNOTaxAmount, //未稅總計
  83. OrgID = t2.OrgID,
  84. IsReturn = t2.IsRetn,
  85. Volume = t2.Volume,
  86. AuditVal = t2.AuditVal,
  87. ReFlow = t2.ReFlow,
  88. FeeItems = t2.FeeItems
  89. })
  90. .MergeTable()
  91. .OrderBy("ResponsiblePerson", "asc")
  92. .ToList();
  93. var cellsApp = new ExcelService(sTempFile);
  94. var cells = cellsApp.sheet.Cells;//单元格
  95. var iCurrRow = 4;
  96. cells[1, 1].PutValue(sBillAuditDateStart + "~" + sBillAuditDateEnd);//帳單區間
  97. cells[1, 11].PutValue(i_crm.USERID);//列表人
  98. cells[2, 1].PutValue(string.Join(",", ChildDeptIDs));//部門
  99. cells[2, 11].PutValue(DateTime.Now.ToString(@"yyyy/MM/dd"));//列印時間
  100. var AllofPorfits = new List<ProfitInfo>();
  101. var group = saBills.GroupBy(c => c.ResponsiblePerson).OrderBy(c => c.Key);
  102. var CellType = GetCellType(RPTEnum.CVPAnalysisBySaler, RoundingPoint, ShowSource);
  103. var AllCBMUsage = CommonRPT.GetAllCBMUsages(db, i_crm.ORIGID);
  104. foreach (IGrouping<string, View_OPM_BillIReport> bills in group)
  105. {
  106. var _bills = bills.OrderBy(x => x.BillType).ThenBy(x => x.ProjectNumber).ThenBy(x => x.ParentId);
  107. var SubProfits = new List<ProfitInfo>();
  108. foreach (View_OPM_BillIReport bill in _bills)
  109. {
  110. var ThisBillCBMUsage = AllCBMUsage.Where(t1 => t1.ParentID == bill.ParentId && t1.IsReturn == bill.IsReturn).ToList();
  111. var BillUntaxAmt = bill.InCome * decimal.Parse(bill.ExchangeRate == "" ? "0" : bill.ExchangeRate);
  112. var ActualCostFeeItemJson = "";
  113. var sActualCost = "";
  114. var sTransportationMode = "";
  115. CommonRPT.CalcuCostAndProfit(db, ref ActualCostFeeItemJson, ref sActualCost, ref sTransportationMode, bill.BillNO, bill.ParentId, bill.IsReturn, bill.ReFlow, bill.BillType);
  116. var ActualCostFeeItemList = CommonRPT.ToFeeItems(ActualCostFeeItemJson);
  117. var BillFeeItemList = CommonRPT.ToFeeItems(bill.FeeItems);
  118. var SharedActualCost = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO);
  119. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  120. var ActualBillReimburseAmount = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO, ActualPrepayFeeList);//抓實際成本的資料
  121. ProfitInfo profitInfo = new ProfitInfo()
  122. {
  123. ExField = bill.IsReturn,
  124. MemberID = bill.ResponsiblePerson,
  125. BillUntaxAmt = BillUntaxAmt.Value,
  126. SharedActualCost = SharedActualCost,
  127. BillReimburseAmount = BillReimburseAmount,
  128. ActualBillReimburseAmount = ActualBillReimburseAmount
  129. };
  130. if (ShowSource)
  131. {
  132. profitInfo.BillNO = $"類型:{bill.BillType}-單號:{bill.BillNO}-狀態:{bill.AuditVal}";
  133. }
  134. SubProfits.Add(profitInfo);
  135. }
  136. var GroupByLogistic = SubProfits.GroupBy(c => c.ExField);
  137. ProfitInfo SubtotalProfitInfo = new ProfitInfo() { MemberID = _bills.FirstOrDefault()?.ResponsiblePerson };
  138. foreach (var items in GroupByLogistic)
  139. {
  140. SubtotalProfitInfo.BillUntaxAmt += CommonRPT.Rounding(items.Sum(c => c.BillUntaxAmt), RoundingPoint);
  141. SubtotalProfitInfo.SharedActualCost += CommonRPT.Rounding(items.Sum(c => c.SharedActualCost), RoundingPoint);
  142. SubtotalProfitInfo.BillReimburseAmount += CommonRPT.Rounding(items.Sum(c => c.BillReimburseAmount), RoundingPoint);
  143. SubtotalProfitInfo.ActualBillReimburseAmount += CommonRPT.Rounding(items.Sum(c => c.ActualBillReimburseAmount), RoundingPoint);
  144. }
  145. var CellColumns = CalcuCellValue(RPTEnum.CVPAnalysisBySaler, SubtotalProfitInfo).ToList();
  146. if (ShowSource)
  147. {
  148. SubtotalProfitInfo.BillNO = string.Join("■", SubProfits.Select(test => test.BillNO));
  149. CellColumns.Add(SubtotalProfitInfo.BillNO);
  150. }
  151. CellsSetValue(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  152. AllofPorfits.Add(SubtotalProfitInfo);
  153. iCurrRow++;
  154. }
  155. //總計
  156. if (AllofPorfits.Any())
  157. {
  158. ProfitInfo TotalProfitInfo = new ProfitInfo()
  159. {
  160. MemberID = $"合計({CurrencyUnit})",
  161. BillUntaxAmt = CommonRPT.Rounding(AllofPorfits.Sum(c => c.BillUntaxAmt), RoundingPoint),
  162. SharedActualCost = CommonRPT.Rounding(AllofPorfits.Sum(c => c.SharedActualCost), RoundingPoint),
  163. BillReimburseAmount = CommonRPT.Rounding(AllofPorfits.Sum(c => c.BillReimburseAmount), RoundingPoint),
  164. ActualBillReimburseAmount = CommonRPT.Rounding(AllofPorfits.Sum(c => c.ActualBillReimburseAmount), RoundingPoint),
  165. };
  166. var CellColumns = CalcuCellValue(RPTEnum.CVPAnalysisBySaler, TotalProfitInfo);
  167. CellsSetValue(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  168. }
  169. cellsApp.sheet.AutoFitColumns();
  170. if (File.Exists(sOutPut))
  171. {
  172. File.Delete(sOutPut);
  173. }
  174. //保存
  175. cellsApp.workbook.Save(sOutPut);
  176. if (sFlag == @"pdf")
  177. {
  178. var excelApp = new ExcelEdit();
  179. try
  180. {
  181. excelApp.Open(sOutPut);
  182. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  183. excelApp.SaveAsPdf(sOutPut);
  184. excelApp.Close();
  185. }
  186. catch (Exception ex)
  187. {
  188. sMsg = ex.Message;
  189. excelApp.Close();
  190. }
  191. }
  192. File.Delete(sTempFile); //刪除臨時文件
  193. sOutPut = sOutPut.Replace(sBase, @"");
  194. rm = new SuccessResponseMessage(null, i_crm);
  195. rm.DATA.Add(BLWording.REL, sOutPut);
  196. } while (false);
  197. }
  198. catch (Exception ex)
  199. {
  200. sMsg = Util.GetLastExceptionMsg(ex);
  201. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName, "", "", "");
  202. }
  203. finally
  204. {
  205. if (null != sMsg)
  206. {
  207. rm = new ErrorResponseMessage(sMsg, i_crm);
  208. }
  209. }
  210. return rm;
  211. }
  212. #endregion
  213. #region 利潤明細表(依展覽)
  214. public ResponseMessage CVPAnalysisByExhibition(RequestMessage i_crm)
  215. {
  216. //展覽區間(第一天)、展覽名稱
  217. ShowSource = CommonRPT.RPTShow();
  218. ResponseMessage rm = null;
  219. string sMsg = null;
  220. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  221. var FunctionName = nameof(CVPAnalysisByExhibition);
  222. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "利潤明細表(依展覽)");
  223. var sOutPut = ExcutePath.Item1;
  224. var sTempFile = ExcutePath.Item2;
  225. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  226. var CurrencyUnit = CommonRPT.GetCurrencyUnit(i_crm.ORIGID);
  227. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  228. try
  229. {
  230. do
  231. {
  232. var saBillPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "PrepayForCustomerCode");
  233. var BillPrepayFeeList = saBillPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  234. var saActualPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "ActualPrepayForCustomerCode");
  235. var ActualPrepayFeeList = saActualPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  236. var sExhibitionDateStart = _fetchString(i_crm, @"ExhibitionDateStart");
  237. var sExhibitionDateEnd = _fetchString(i_crm, @"ExhibitionDateEnd");
  238. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  239. var sResponsiblePerson = _fetchString(i_crm, @"ResponsiblePerson");
  240. var SearchMatchedExps = !string.IsNullOrWhiteSpace(sResponsibleDeptID) || !string.IsNullOrWhiteSpace(sResponsiblePerson);
  241. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  242. var MatchedExpList = CommonRPT.GetMatchedExps(db, i_crm.ORIGID, ChildDeptIDs, sResponsiblePerson);
  243. var MatchedExpGuids = MatchedExpList.Select(t1 => t1.Guid).Distinct().ToArray();
  244. var Filter = new CVPFilter();
  245. Filter.SetExhibition(sExhibitionDateStart, sExhibitionDateEnd);
  246. //根據前端選擇
  247. var sProjectNO = _fetchString(i_crm, @"ProjectNO"); //ProjectNO == OTB_OPM_Exhibition.ExhibitionCode
  248. var sProjectName = _fetchString(i_crm, @"ProjectName");
  249. var sFlag = _fetchString(i_crm, @"Flag");
  250. //展覽區間依「展覽日期第一天」來定義區間
  251. var MatchedExhibitions = db.Queryable<OTB_OPM_Exhibition>()
  252. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.Effective == "Y")
  253. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateStart), (t1) => t1.ExhibitionDateStart >= Filter.rExhibitionDateStart.Date)
  254. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateEnd), (t1) => t1.ExhibitionDateStart < Filter.rExhibitionDateEnd.Date)
  255. .WhereIF(!string.IsNullOrWhiteSpace(sProjectName), (t1) =>
  256. t1.Exhibitioname_EN.Contains(sProjectName) || t1.Exhibitioname_TW.Contains(sProjectName) ||
  257. t1.Exhibitioname_CN.Contains(sProjectName) || t1.ExhibitioShotName_TW.Contains(sProjectName) ||
  258. t1.ExhibitioShotName_CN.Contains(sProjectName) || t1.ExhibitioShotName_EN.Contains(sProjectName))
  259. .WhereIF(!string.IsNullOrWhiteSpace(sProjectNO), (t1) => t1.ExhibitionCode == sProjectNO)
  260. .Select(ex => new { ex.ExhibitionCode, ex.ExhibitioShotName_TW, ex.ExhibitionDateStart, SN = ex.SN.ToString(), ProjectNumber = ex.SN.ToString() }).ToList();
  261. var FindProjectNum = MatchedExhibitions.Select(c => c.ExhibitionCode).ToArray();
  262. //挑調
  263. var saBills = new List<View_OPM_BillIReport>();
  264. //資料guid
  265. if (FindProjectNum.Length != 0)
  266. {
  267. var view = db.Queryable<OVW_OPM_Bills, OTB_OPM_BillInfo>
  268. ((t1, t2) => new object[] {
  269. JoinType.Inner, t1.OrgID == t2.OrgID && t1.BillNO == t2.BillNO })
  270. .Where((t1, t2) => t1.OrgID == i_crm.ORIGID && CommonRPT.PassStatus.Contains(t2.AuditVal))
  271. .WhereIF(FindProjectNum.Any(), (t1, t2) => !SqlFunc.IsNullOrEmpty(t1.ProjectNumber) && SqlFunc.ContainsArray(FindProjectNum, t1.ProjectNumber))
  272. .WhereIF(SearchMatchedExps, (t1, t2) => SqlFunc.ContainsArray(MatchedExpGuids, t2.ParentId));
  273. saBills = view.Select((t1, t2) =>
  274. new View_OPM_BillIReport
  275. {
  276. BillNO = t2.BillNO,
  277. BillType = t2.BillType,
  278. ParentId = t2.ParentId,
  279. ProjectNumber = t1.ProjectNumber,
  280. CustomerCode = t1.CustomerCode,
  281. ResponsiblePerson = t2.ResponsiblePerson,
  282. Currency = t2.Currency,
  283. ExchangeRate = t2.ExchangeRate,
  284. InCome = t1.TWNOTaxAmount, //未稅總計
  285. OrgID = t2.OrgID,
  286. IsReturn = t2.IsRetn,
  287. Volume = t2.Volume,
  288. AuditVal = t2.AuditVal,
  289. ReFlow = t2.ReFlow,
  290. FeeItems = t2.FeeItems
  291. })
  292. .MergeTable()
  293. .OrderBy("ResponsiblePerson", "asc")
  294. .ToList();
  295. }
  296. var cellsApp = new ExcelService(sTempFile);
  297. var cells = cellsApp.sheet.Cells;//单元格
  298. var iCurrRow = 4;
  299. var iCurrRowOri = iCurrRow;
  300. cells[1, 1].PutValue(sExhibitionDateStart + "~" + sExhibitionDateEnd);//展覽區間
  301. cells[1, 11].PutValue(i_crm.USERID);//列表人
  302. cells[2, 1].PutValue(string.Join(",", ChildDeptIDs));//部門
  303. cells[2, 11].PutValue(DateTime.Now.ToString(@"yyyy/MM/dd"));//列印時間
  304. var AllofPorfits = new List<ProfitInfo>();
  305. var group = saBills.GroupBy(c => c.ProjectNumber).OrderBy(c => c.Key);
  306. var AllCBMUsage = CommonRPT.GetAllCBMUsages(db, i_crm.ORIGID);
  307. foreach (IGrouping<string, View_OPM_BillIReport> bills in group)
  308. {
  309. var _bills = bills.OrderBy(x => x.BillNO).ThenBy(x => x.BillType).ThenBy(x => x.ProjectNumber).ThenBy(x => x.ParentId);
  310. var SubProfits = new List<ProfitInfo>();
  311. foreach (View_OPM_BillIReport bill in _bills)
  312. {
  313. var ThisBillCBMUsage = AllCBMUsage.Where(t1 => t1.ParentID == bill.ParentId && t1.IsReturn == bill.IsReturn).ToList();
  314. var BillUntaxAmt = bill.InCome * decimal.Parse(bill.ExchangeRate == "" ? "0" : bill.ExchangeRate);
  315. var ActualCostFeeItemJson = "";
  316. var sActualCost = "";
  317. var sTransportationMode = "";
  318. CommonRPT.CalcuCostAndProfit(db, ref ActualCostFeeItemJson, ref sActualCost, ref sTransportationMode, bill.BillNO, bill.ParentId, bill.IsReturn, bill.ReFlow, bill.BillType);
  319. var ActualCostFeeItemList = CommonRPT.ToFeeItems(ActualCostFeeItemJson);
  320. var BillFeeItemList = CommonRPT.ToFeeItems(bill.FeeItems);
  321. var SharedActualCost = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO);
  322. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  323. var ActualBillReimburseAmount = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO, ActualPrepayFeeList);//抓實際成本的資料
  324. ProfitInfo profitInfo = new ProfitInfo()
  325. {
  326. ExField = bill.IsReturn,
  327. BillUntaxAmt = BillUntaxAmt.Value,
  328. SharedActualCost = SharedActualCost,
  329. BillReimburseAmount = BillReimburseAmount,
  330. ActualBillReimburseAmount = ActualBillReimburseAmount
  331. };
  332. if (ShowSource)
  333. {
  334. profitInfo.BillNO = $"類型:{bill.BillType}-單號:{bill.BillNO}-狀態:{bill.AuditVal}";
  335. }
  336. SubProfits.Add(profitInfo);
  337. }
  338. var Exhibition = MatchedExhibitions.Find(c => c.ExhibitionCode == _bills.FirstOrDefault()?.ProjectNumber);
  339. //分成正物流、逆物流計算
  340. var GroupByLogistic = SubProfits.GroupBy(c => c.ExField);
  341. ProfitInfo SubtotalProfitInfo = new ProfitInfo() { MemberID = Exhibition.ExhibitioShotName_TW };
  342. foreach (var items in GroupByLogistic)
  343. {
  344. SubtotalProfitInfo.BillUntaxAmt += CommonRPT.Rounding(items.Sum(c => c.BillUntaxAmt), RoundingPoint);
  345. SubtotalProfitInfo.SharedActualCost += CommonRPT.Rounding(items.Sum(c => c.SharedActualCost), RoundingPoint);
  346. SubtotalProfitInfo.BillReimburseAmount += CommonRPT.Rounding(items.Sum(c => c.BillReimburseAmount), RoundingPoint);
  347. SubtotalProfitInfo.ActualBillReimburseAmount += CommonRPT.Rounding(items.Sum(c => c.ActualBillReimburseAmount), RoundingPoint);
  348. }
  349. SubtotalProfitInfo.OrderValue = Exhibition.ExhibitionDateStart == null ? 0 : Exhibition.ExhibitionDateStart.Value.Ticks;
  350. if (ShowSource)
  351. {
  352. SubtotalProfitInfo.BillNO = string.Join("■", SubProfits.Select(test => test.BillNO));
  353. }
  354. AllofPorfits.Add(SubtotalProfitInfo);
  355. iCurrRow++;
  356. }
  357. //總計
  358. if (AllofPorfits.Any())
  359. {
  360. List<object> CellColumns = null;
  361. var CellType = GetCellType(RPTEnum.CVPAnalysisByExhibition, RoundingPoint, ShowSource);
  362. //依展期先後順序排序
  363. foreach (var SubtotalProfitInfo in AllofPorfits.OrderBy(c => c.OrderValue))
  364. {
  365. CellColumns = CalcuCellValue(RPTEnum.CVPAnalysisBySaler, SubtotalProfitInfo);
  366. if (ShowSource)
  367. {
  368. CellColumns.Add(SubtotalProfitInfo.BillNO);
  369. }
  370. CellsSetValue(cellsApp.workbook, cells, iCurrRowOri, CellColumns, CellType);
  371. ++iCurrRowOri;
  372. }
  373. //總計
  374. ProfitInfo TotalProfitInfo = new ProfitInfo()
  375. {
  376. MemberID = $"合計({CurrencyUnit})",
  377. BillUntaxAmt = CommonRPT.Rounding(AllofPorfits.Sum(c => c.BillUntaxAmt), RoundingPoint),
  378. SharedActualCost = CommonRPT.Rounding(AllofPorfits.Sum(c => c.SharedActualCost), RoundingPoint),
  379. BillReimburseAmount = CommonRPT.Rounding(AllofPorfits.Sum(c => c.BillReimburseAmount), RoundingPoint),
  380. ActualBillReimburseAmount = CommonRPT.Rounding(AllofPorfits.Sum(c => c.ActualBillReimburseAmount), RoundingPoint),
  381. };
  382. CellColumns = CalcuCellValue(RPTEnum.CVPAnalysisBySaler, TotalProfitInfo);
  383. CellsSetValue(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  384. }
  385. if (File.Exists(sOutPut))
  386. {
  387. File.Delete(sOutPut);
  388. }
  389. //保存
  390. cellsApp.workbook.Save(sOutPut);
  391. if (sFlag == @"pdf")
  392. {
  393. var excelApp = new ExcelEdit();
  394. try
  395. {
  396. excelApp.Open(sOutPut);
  397. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  398. excelApp.SaveAsPdf(sOutPut);
  399. excelApp.Close();
  400. }
  401. catch (Exception ex)
  402. {
  403. sMsg = ex.Message;
  404. excelApp.Close();
  405. }
  406. }
  407. File.Delete(sTempFile);
  408. sOutPut = sOutPut.Replace(sBase, @"");
  409. rm = new SuccessResponseMessage(null, i_crm);
  410. rm.DATA.Add(BLWording.REL, sOutPut);
  411. } while (false);
  412. }
  413. catch (Exception ex)
  414. {
  415. sMsg = Util.GetLastExceptionMsg(ex);
  416. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  417. }
  418. finally
  419. {
  420. if (null != sMsg)
  421. {
  422. rm = new ErrorResponseMessage(sMsg, i_crm);
  423. }
  424. }
  425. return rm;
  426. }
  427. #endregion
  428. #region 金流帳單
  429. public ResponseMessage CashFlow(RequestMessage i_crm)
  430. {
  431. ResponseMessage rm = null;
  432. string sMsg = null;
  433. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  434. var FunctionName = nameof(CashFlow);
  435. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "金流帳單");
  436. var sOutPut = ExcutePath.Item1;
  437. var sTempFile = ExcutePath.Item2;
  438. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  439. var saBillPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "PrepayForCustomerCode");
  440. var BillPrepayFeeList = saBillPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  441. var saActualPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "ActualPrepayForCustomerCode");
  442. var ActualPrepayFeeList = saActualPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  443. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  444. try
  445. {
  446. do
  447. {
  448. #region BillType 帳單資料:「帳單號碼」、 「帳單狀態」 、 「帳單拋轉日期」、 「銷帳日期」(OTB_OPM_BillInfo )
  449. var sBillNO = _fetchString(i_crm, @"BillNO");
  450. var sBillStatus = _fetchString(i_crm, @"BillStatus");
  451. var sBillAuditDateStart = _fetchString(i_crm, @"BillAuditDateStart");
  452. var sBillAuditDateEnd = _fetchString(i_crm, @"BillAuditDateEnd");
  453. var sBillWriteOffDateStart = _fetchString(i_crm, @"BillWriteOffDateStart");
  454. var sBillWriteOffDateEnd = _fetchString(i_crm, @"BillWriteOffDateEnd");
  455. var Filter = new CVPFilter();
  456. Filter.SetBill(sBillAuditDateStart, sBillAuditDateEnd, sBillWriteOffDateStart, sBillWriteOffDateEnd, sBillStatus);
  457. #endregion
  458. #region ExhibitionType 展覽資料:「專案代號」、「展覽名稱」、「展覽區間(第1天)」、「組團單位」(OTB_OPM_BillInfo : ExhibitionNO => OTB_OPM_Exhibition.SN)
  459. var sExhibitionCode = _fetchString(i_crm, @"ExhibitionCode");
  460. var sExhibitionName = _fetchString(i_crm, @"ExhibitionName");
  461. var sExhibitionSN = _fetchString(i_crm, @"ExhibitionSN");
  462. var sExhibitionDateStart = _fetchString(i_crm, @"ExhibitionDateStart");
  463. var sExhibitionDateEnd = _fetchString(i_crm, @"ExhibitionDateEnd");
  464. var sOrganizerGuid = _fetchString(i_crm, @"OrganizerGuid");
  465. Filter.SetExhibition(sExhibitionDateStart, sExhibitionDateEnd);
  466. #endregion
  467. #region CustomerType 顧客資料:「客戶名稱」、「客戶編號」、「客戶類別(國內 / 外)」(OTB_OPM_BillInfo : Payer => OTB_CRM_Customers.guid)
  468. var sCustomerName = _fetchString(i_crm, @"CustomerName");
  469. var sCustomerGuid = _fetchString(i_crm, @"CustomerGuid");
  470. var sCustomerNO = _fetchString(i_crm, @"CustomerNO");
  471. var sTranType = _fetchString(i_crm, @"TransType");
  472. #endregion
  473. #region SalerType 業務資料:「負責部門、組別」、「負責業務」(OTB_OPM_BillInfo :ResponsiblePerson => OTB_SYS_Members.MemberID)
  474. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  475. var sResponsiblePerson = _fetchString(i_crm, @"ResponsiblePerson");
  476. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  477. var MatchedExps = CommonRPT.GetMatchedExps(db, i_crm.ORIGID, ChildDeptIDs, sResponsiblePerson);
  478. var MatchedExpGuids = MatchedExps.Select(x => x.Guid).Distinct().ToArray();
  479. #endregion
  480. #region Exhibition(四展覽)
  481. var viewExpIm = db.Queryable<OTB_OPM_ImportExhibition>().Where(t1 => t1.OrgID == i_crm.ORIGID)
  482. .Select((t1) => new ExpInfo
  483. {
  484. Id = t1.ImportBillNO,
  485. ExhibitionType = "ExhibitionImport_Upd",
  486. DeptOfResponsibleMember = t1.DepartmentID,
  487. });
  488. var viewExpEx = db.Queryable<OTB_OPM_ExportExhibition>().Where(t1 => t1.OrgID == i_crm.ORIGID)
  489. .Select((t1) => new ExpInfo
  490. {
  491. Id = t1.ExportBillNO,
  492. ExhibitionType = "ExhibitionExport_Upd",
  493. DeptOfResponsibleMember = t1.DepartmentID,
  494. });
  495. var viewExpOth = db.Queryable<OTB_OPM_OtherExhibition>().Where(t1 => t1.OrgID == i_crm.ORIGID)
  496. .Select((t1) => new ExpInfo
  497. {
  498. Id = t1.Guid,
  499. ExhibitionType = "OtherBusiness_Upd",
  500. DeptOfResponsibleMember = t1.DepartmentID,
  501. });
  502. var viewExpOthtG = db.Queryable<OTB_OPM_OtherExhibitionTG>().Where(t1 => t1.OrgID == i_crm.ORIGID)
  503. .Select((t1) => new ExpInfo
  504. {
  505. Id = t1.Guid,
  506. ExhibitionType = "OtherExhibitionTG_Upd",
  507. DeptOfResponsibleMember = t1.DepartmentID,
  508. });
  509. var saExps = db.UnionAll(viewExpIm, viewExpEx, viewExpOth, viewExpOthtG).ToList();
  510. #endregion
  511. var saBills = db.Queryable<OTB_OPM_BillInfo, OTB_OPM_Exhibition, OTB_SYS_Arguments, OTB_CRM_Customers, OTB_CRM_CustomersMST, OTB_SYS_Members>((bill, exp, args, cus, cus_m, mber) => new object[] {
  512. JoinType.Left, bill.OrgID == exp.OrgID && bill.ExhibitionNO == exp.SN.ToString(),
  513. JoinType.Left, args.OrgID == "TE" && exp.Industry == args.ArgumentID && args.ArgumentClassID == "ExhibClass",
  514. JoinType.Left, bill.OrgID == cus.OrgID && bill.Payer == cus.guid,
  515. JoinType.Left, cus.OrgID == cus_m.OrgID && cus.guid == cus_m.customer_guid,
  516. JoinType.Left, bill.OrgID == mber.OrgID && bill.ResponsiblePerson == mber.MemberID })
  517. .Where(bill => bill.OrgID == i_crm.ORIGID)
  518. //帳單資料:「帳單號碼」、 「帳單狀態」 、 「帳單拋轉日期」、 「銷帳日期」
  519. .WhereIF(!string.IsNullOrWhiteSpace(sBillNO), bill => bill.BillNO.Contains(sBillNO))
  520. .WhereIF(!string.IsNullOrWhiteSpace(Filter.PassStatus), bill => Filter.PassStatus.Contains(bill.AuditVal))
  521. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sBillAuditDateStart), bill => SqlFunc.ToDate(bill.BillFirstCheckDate) >= Filter.rBillAuditDateStart)
  522. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sBillAuditDateEnd), bill => SqlFunc.ToDate(bill.BillFirstCheckDate) < Filter.rBillAuditDateEnd)
  523. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sBillWriteOffDateStart), bill => SqlFunc.ToDate(bill.BillWriteOffDate) >= Filter.rBillWriteOffDateStart)
  524. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sBillWriteOffDateEnd), bill => SqlFunc.ToDate(bill.BillWriteOffDate) < Filter.rBillWriteOffDateEnd)
  525. //展覽資料:「專案代號」、「展覽名稱」、「展覽區間(第1天)」、 「組團單位」?????
  526. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionCode), (bill, exp) => exp.ExhibitionCode == sExhibitionCode)
  527. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionName), (bill, exp) => exp.Exhibitioname_EN.Contains(sExhibitionName) || exp.Exhibitioname_TW.Contains(sExhibitionName) ||
  528. exp.Exhibitioname_CN.Contains(sExhibitionName) || exp.ExhibitioShotName_TW.Contains(sExhibitionName) ||
  529. exp.ExhibitioShotName_CN.Contains(sExhibitionName) || exp.ExhibitioShotName_EN.Contains(sExhibitionName))
  530. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionSN), (bill, exp) => exp.SN.ToString() == sExhibitionSN)
  531. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateStart), (bill, exp) => SqlFunc.ToDate(exp.ExhibitionDateStart) >= Filter.rExhibitionDateStart)
  532. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateEnd), (bill, exp) => SqlFunc.ToDate(exp.ExhibitionDateStart) < Filter.rExhibitionDateEnd)
  533. .WhereIF(!string.IsNullOrWhiteSpace(sOrganizerGuid), (bill) => bill.Organizer.Contains(sOrganizerGuid))
  534. //顧客資料:「客戶名稱」、「客戶編號」、「客戶類別(國內 / 外)」
  535. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerName), (bill, exp, args, cus) => cus.CustomerCName.Contains(sCustomerName) || cus.CustomerEName.Contains(sCustomerName) ||
  536. cus.CustomerShotCName.Contains(sCustomerName) || cus.CustomerShotEName.Contains(sCustomerName))
  537. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerNO), (bill, exp, args, cus, cus_m) => cus_m.CustomerNO.Contains(sCustomerNO))
  538. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerGuid), (bill, exp, args, cus, cus_m) => cus.guid == sCustomerGuid)
  539. .WhereIF(!string.IsNullOrWhiteSpace(sTranType), (bill, exp, args, cus, cus_m) => sTranType.Contains(cus.TransactionType))
  540. .Where((bill, exp, args, cus, cus_m) => cus_m.Effective == "Y")
  541. //業務資料:「負責部門、組別」、「負責業務」
  542. .WhereIF(!string.IsNullOrEmpty(sResponsibleDeptID) || !string.IsNullOrEmpty(sResponsiblePerson),
  543. (bill, exp, args, cus, cus_m) => SqlFunc.ContainsArray(MatchedExpGuids, bill.ParentId))
  544. .Select((bill, exp, args, cus, cus_m, mber) => new
  545. {
  546. bill.BillNO,
  547. bill.AuditVal,
  548. bill.BillWriteOffDate,
  549. bill.BillFirstCheckDate,
  550. bill.CreateDate,
  551. exp.ExhibitionCode,
  552. exp.Exhibitioname_TW,
  553. exp.ExhibitioShotName_TW,
  554. exp.Industry,
  555. exp.ExhibitionDateStart,
  556. sOrganizer = bill.Organizer,
  557. cus_m.CustomerNO,
  558. cus.CustomerCName,
  559. cus.CustomerEName,
  560. cus.CustomerShotCName,
  561. cus.TransactionType,
  562. bill.ResponsiblePerson,
  563. bill.Volume,
  564. bill.Currency,
  565. bill.ExchangeRate,
  566. bill.AmountSum, //(原幣別)
  567. bill.TaxSum,
  568. //拼湊資料用
  569. bill.OrgID,
  570. bill.FeeItems,
  571. bill.ParentId,
  572. bill.IsRetn,
  573. bill.ReFlow,
  574. bill.BillType
  575. }).ToList();
  576. var TransDic = new Dictionary<string, string>() { {"A","國內" },{"B","國外" },{"C","國外" },
  577. { "D","國內" },{"E","其他" },{"F","其他" } };
  578. var CustomerDic = db.Queryable<OTB_CRM_Customers>().Where(t1 => t1.OrgID == i_crm.ORIGID)
  579. .Select((t1) => new OTB_CRM_Customers
  580. {
  581. guid = t1.guid,
  582. CustomerCName = t1.CustomerCName
  583. }).ToList().Distinct().ToList();
  584. CustomerDic.Add(new OTB_CRM_Customers { guid = "SelfCome", CustomerCName = "自來" });
  585. var DeptDic = CommonRPT.GetDeptInfos(db, i_crm.ORIGID);
  586. var cellsApp = new ExcelService(sTempFile);
  587. var cells = cellsApp.sheet.Cells;//单元格
  588. var iCurrRow = 1;
  589. saBills = saBills.OrderBy(c => c.OrgID).ThenBy(c => c.BillNO).ThenBy(c => c.AuditVal).ToList();
  590. var CellType = GetCellType(RPTEnum.CashFlow, RoundingPoint, ShowSource);
  591. var AllCBMUsage = CommonRPT.GetAllCBMUsages(db, i_crm.ORIGID);
  592. var SearchList = GetExpList(db);
  593. foreach (var bill in saBills)
  594. {
  595. var OrganierCName = "";
  596. if (!string.IsNullOrWhiteSpace(bill.sOrganizer))
  597. OrganierCName = CustomerDic.FirstOrDefault(t1 => t1.guid == bill.sOrganizer.Trim())?.CustomerCName;
  598. var UpperDeptID = "";// 負責部門
  599. var ResDeptID = "";//負責組別
  600. var expInfo = saExps.Where(c => c.Id == bill.ParentId).FirstOrDefault(c => c.Id == bill.ParentId);
  601. if (expInfo != null && DeptDic.TryGetValue(expInfo.DeptOfResponsibleMember, out var DeptInfo))
  602. {
  603. //DepartmentID, DepartmentName, ParentDepartmentID, ParentDepartmentName, Level
  604. if (DeptInfo.Item5 == "2")
  605. {
  606. UpperDeptID = DeptInfo.Item4;
  607. ResDeptID = DeptInfo.Item2;
  608. }
  609. else
  610. {
  611. UpperDeptID = DeptInfo.Item2;
  612. }
  613. }
  614. var ExchangeRate = decimal.Parse(bill.ExchangeRate == "" ? "0" : bill.ExchangeRate);
  615. TransDic.TryGetValue(bill.TransactionType, out var TransCategory);
  616. var BillUntaxAmt = decimal.Parse(bill.AmountSum == "" ? "0" : bill.AmountSum) * ExchangeRate;
  617. var BilltaxAmt = decimal.Parse(bill.TaxSum == "" ? "0" : bill.TaxSum) * ExchangeRate;
  618. var ActualCostFeeItemJson = "";
  619. var sActualCost = "";
  620. var sTransportationMode = "";
  621. var BillInfo = new OVW_OPM_BillInfo()
  622. {
  623. OrgID = bill.OrgID,
  624. ParentId = bill.ParentId,
  625. IsRetn = bill.IsRetn,
  626. AuditVal = bill.AuditVal,
  627. Volume = bill.Volume,
  628. };
  629. var ThisBillCBMUsage = AllCBMUsage.Where(t1 => t1.ParentID == bill.ParentId && t1.IsReturn == bill.IsRetn).ToList();
  630. CommonRPT.CalcuCostAndProfitFast(SearchList, ref ActualCostFeeItemJson, ref sActualCost, ref sTransportationMode, bill.BillNO, bill.ParentId, bill.IsRetn, bill.ReFlow, bill.BillType);
  631. var ActualCostFeeItemList = CommonRPT.ToFeeItems(ActualCostFeeItemJson);
  632. var BillFeeItemList = CommonRPT.ToFeeItems(bill.FeeItems);
  633. var SharedActualCost = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO);
  634. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  635. var ActualBillReimburseAmount = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO, ActualPrepayFeeList);//抓實際成本的資料
  636. ProfitInfo profitInfo = new ProfitInfo()
  637. {
  638. BillUntaxAmt = CommonRPT.Rounding(BillUntaxAmt, RoundingPoint),
  639. SharedActualCost = CommonRPT.Rounding(SharedActualCost, RoundingPoint),
  640. BillReimburseAmount = CommonRPT.Rounding(BillReimburseAmount, RoundingPoint),
  641. ActualBillReimburseAmount = CommonRPT.Rounding(ActualBillReimburseAmount, RoundingPoint)
  642. };
  643. var SummaryInfo = new List<object>
  644. {
  645. bill.BillNO,
  646. bill.AuditVal,
  647. bill.BillWriteOffDate,
  648. bill.BillFirstCheckDate,
  649. bill.CreateDate.ToString(),
  650. bill.ExhibitionCode,
  651. bill.Exhibitioname_TW,
  652. bill.ExhibitioShotName_TW,
  653. bill.Industry,
  654. bill.ExhibitionDateStart.ObjToString(),
  655. OrganierCName,
  656. bill.CustomerNO,
  657. bill.CustomerCName,
  658. bill.CustomerEName,
  659. bill.CustomerShotCName,
  660. TransCategory,
  661. bill.TransactionType,
  662. UpperDeptID,
  663. ResDeptID,
  664. bill.ResponsiblePerson,
  665. bill.Volume.ObjToDecimal(),
  666. bill.Currency,
  667. bill.ExchangeRate.ObjToDecimal(),
  668. bill.AmountSum.ObjToDecimal(),
  669. profitInfo.BillUntaxAmt,
  670. BilltaxAmt,
  671. profitInfo.SharedActualCost,
  672. profitInfo.BillReimburseAmount,
  673. profitInfo.ActualBillReimburseAmount,
  674. profitInfo.GrossProfit,
  675. profitInfo.NetProfit
  676. };
  677. CellsSetValue(cellsApp.workbook, cells, iCurrRow, SummaryInfo, CellType);
  678. iCurrRow++;
  679. }
  680. //DATAS
  681. cells.StandardWidth = 15;
  682. cellsApp.sheet.AutoFitColumns();
  683. cellsApp.sheet.AutoFitRows();
  684. if (File.Exists(sOutPut))
  685. {
  686. File.Delete(sOutPut);
  687. }
  688. cellsApp.sheet.AutoFitColumns();
  689. cellsApp.sheet.AutoFitRows();
  690. //保存
  691. cellsApp.workbook.Save(sOutPut);
  692. File.Delete(sTempFile); //刪除臨時文件
  693. sOutPut = sOutPut.Replace(sBase, @"");
  694. rm = new SuccessResponseMessage(null, i_crm);
  695. rm.DATA.Add(BLWording.REL, sOutPut);
  696. } while (false);
  697. }
  698. catch (Exception ex)
  699. {
  700. sMsg = Util.GetLastExceptionMsg(ex);
  701. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  702. }
  703. finally
  704. {
  705. if (null != sMsg)
  706. {
  707. rm = new ErrorResponseMessage(sMsg, i_crm);
  708. }
  709. }
  710. return rm;
  711. }
  712. private List<dynamic> GetExpList(SqlSugarClient db)
  713. {
  714. var SearchDatas = new List<dynamic>();
  715. var Others = db.Queryable<OTB_OPM_OtherExhibition>().Select(t1 => new OTB_OPM_OtherExhibition() { ActualCost = t1.ActualCost, ExFeild1 = "OtherBusiness_Upd", Guid = t1.Guid }).ToList();
  716. SearchDatas.AddRange(Others);
  717. var Imports = db.Queryable<OTB_OPM_ImportExhibition>().Select(t1 => new OTB_OPM_ImportExhibition() { ExFeild1 = "ExhibitionImport_Upd", ReturnBills = t1.ReturnBills, ReImports = t1.ReImports, ActualCost = t1.ActualCost, TransportationMode = t1.TransportationMode, ImportBillNO = t1.ImportBillNO }).ToList();
  718. SearchDatas.AddRange(Imports);
  719. var Exports = db.Queryable<OTB_OPM_ExportExhibition>().Select(t1 => new OTB_OPM_ExportExhibition() { ExFeild1 = "ExhibitionExport_Upd", ReturnBills = t1.ReturnBills, Exhibitors = t1.Exhibitors, ActualCost = t1.ActualCost, TransportationMode = t1.TransportationMode, ExportBillNO = t1.ExportBillNO }).ToList();
  720. SearchDatas.AddRange(Exports);
  721. return SearchDatas;
  722. }
  723. #endregion
  724. #region 貢獻度報表(代理)
  725. public ResponseMessage DegreeOfContributionByAgent(RequestMessage i_crm)
  726. {
  727. //帳單(拋轉)區間、銷帳區間、部門、業務 代理 ==> C
  728. ShowSource = CommonRPT.RPTShow();
  729. ResponseMessage rm = null;
  730. string sMsg = null;
  731. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  732. var FunctionName = nameof(DegreeOfContributionByAgent);
  733. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "貢獻度報表(代理)");
  734. var sOutPut = ExcutePath.Item1;
  735. var sTempFile = ExcutePath.Item2;
  736. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  737. var stransactiontype = "C";
  738. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  739. try
  740. {
  741. do
  742. {
  743. var sBillAuditDateStart = _fetchString(i_crm, @"BillAuditDateStart");
  744. var sBillAuditDateEnd = _fetchString(i_crm, @"BillAuditDateEnd");
  745. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  746. var sResponsiblePerson = _fetchString(i_crm, @"ResponsiblePerson");
  747. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  748. var sAgentName = _fetchString(i_crm, @"AgentName");
  749. var sAgentGuid = _fetchString(i_crm, @"AgentGuid");
  750. var sFlag = _fetchString(i_crm, @"Flag");
  751. var Filter = new CVPFilter();
  752. Filter.SetBill(sBillAuditDateStart, sBillAuditDateEnd, "", "");
  753. //依序1.Customers => 2.Exhibition(四展覽) => 3.Billinfo => 4.統計
  754. var CustomerKey = "";
  755. var Customers = db.Queryable<OTB_CRM_Customers>()
  756. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.Effective == "Y" && t1.TransactionType == stransactiontype)
  757. .WhereIF(!string.IsNullOrWhiteSpace(sAgentName), (t1) =>
  758. t1.CustomerCName.Contains(sAgentName) || t1.CustomerEName.Contains(sAgentName) ||
  759. t1.CustomerShotCName.Contains(sAgentName) || t1.CustomerShotEName.Contains(sAgentName))
  760. .WhereIF(!string.IsNullOrWhiteSpace(sAgentGuid), t1 => t1.guid == sAgentGuid);
  761. CustomerKey = Customers.Select(t1 => t1.guid).ToJson();
  762. #region Exhibition(四展覽)
  763. var viewExpIm = db.Queryable<OTB_OPM_ImportExhibition, OTB_CRM_Customers>
  764. ((t1, t2) => new object[] { JoinType.Left, t1.OrgID == t2.OrgID && t1.Agent == t2.guid })
  765. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N" && !SqlFunc.IsNullOrEmpty(t1.Agent))
  766. .WhereIF(!string.IsNullOrWhiteSpace(CustomerKey), (t1) => CustomerKey.Contains(t1.Agent))
  767. .WhereIF(ChildDeptIDs.Any(), t1 => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  768. .WhereIF(!string.IsNullOrWhiteSpace(sResponsiblePerson), t1 => t1.ResponsiblePerson == sResponsiblePerson)
  769. .Select((t1, t2) => new ExpInfo
  770. {
  771. Id = t1.ImportBillNO,
  772. ExhibitionType = "ExhibitionImport_Upd",
  773. ActualCost = t1.ActualCost,
  774. Bills = t1.Bills,
  775. ReturnBills = t1.ReturnBills,
  776. RefNumber = t1.RefNumber,
  777. ExpNO = t1.ExhibitionNO,
  778. Agent = t2.CustomerShotCName
  779. });
  780. var viewExpEx = db.Queryable<OTB_OPM_ExportExhibition, OTB_CRM_Customers>
  781. ((t1, t2) => new object[] { JoinType.Left, t1.OrgID == t2.OrgID && t1.Agent == t2.guid })
  782. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N" && !SqlFunc.IsNullOrEmpty(t1.Agent))
  783. .WhereIF(!string.IsNullOrWhiteSpace(CustomerKey), (t1) => CustomerKey.Contains(t1.Agent))
  784. .WhereIF(ChildDeptIDs.Any(), t1 => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  785. .WhereIF(!string.IsNullOrWhiteSpace(sResponsiblePerson), t1 => t1.ResponsiblePerson == sResponsiblePerson)
  786. .Select((t1, t2) => new ExpInfo
  787. {
  788. Id = t1.ExportBillNO,
  789. ExhibitionType = "ExhibitionExport_Upd",
  790. ActualCost = t1.ActualCost,
  791. Bills = t1.Bills,
  792. ReturnBills = t1.ReturnBills,
  793. RefNumber = t1.RefNumber,
  794. ExpNO = t1.ExhibitionNO,
  795. Agent = t2.CustomerShotCName
  796. });
  797. var viewExpOth = db.Queryable<OTB_OPM_OtherExhibition, OTB_CRM_Customers>
  798. ((t1, t2) => new object[] { JoinType.Left, t1.OrgID == t2.OrgID && t1.Agent == t2.guid })
  799. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N" && !SqlFunc.IsNullOrEmpty(t1.Agent))
  800. .WhereIF(!string.IsNullOrWhiteSpace(CustomerKey), (t1) => CustomerKey.Contains(t1.Agent))
  801. .WhereIF(ChildDeptIDs.Any(), t1 => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  802. .WhereIF(!string.IsNullOrWhiteSpace(sResponsiblePerson), t1 => t1.ResponsiblePerson == sResponsiblePerson)
  803. .Select((t1, t2) => new ExpInfo
  804. {
  805. Id = t1.Guid,
  806. ExhibitionType = "OtherBusiness_Upd",
  807. ActualCost = t1.ActualCost,
  808. Bills = t1.Bills,
  809. ReturnBills = "",
  810. RefNumber = "",
  811. ExpNO = t1.ExhibitionNO,
  812. Agent = t2.CustomerShotCName
  813. });
  814. var viewExpOthtG = db.Queryable<OTB_OPM_OtherExhibitionTG, OTB_CRM_Customers>
  815. ((t1, t2) => new object[] { JoinType.Left, t1.OrgID == t2.OrgID && t1.Agent == t2.guid })
  816. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N" && !SqlFunc.IsNullOrEmpty(t1.Agent))
  817. .WhereIF(!string.IsNullOrWhiteSpace(CustomerKey), (t1) => CustomerKey.Contains(t1.Agent))
  818. .WhereIF(ChildDeptIDs.Any(), t1 => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  819. .WhereIF(!string.IsNullOrWhiteSpace(sResponsiblePerson), t1 => t1.ResponsiblePerson == sResponsiblePerson)
  820. .Select((t1, t2) => new ExpInfo
  821. {
  822. Id = t1.Guid,
  823. ExhibitionType = "OtherExhibitionTG_Upd",
  824. ActualCost = t1.ActualCost,
  825. Bills = t1.Bills,
  826. ReturnBills = "",
  827. RefNumber = "",
  828. ExpNO = t1.ExhibitionNO,
  829. Agent = t2.CustomerShotCName
  830. });
  831. var saExps = db.UnionAll(viewExpIm, viewExpEx, viewExpOth, viewExpOthtG).ToList();
  832. var SearchedExp =!string.IsNullOrWhiteSpace(CustomerKey) || !string.IsNullOrWhiteSpace(sResponsibleDeptID) || !string.IsNullOrWhiteSpace(sResponsibleDeptID);
  833. #endregion
  834. #region 符合展覽的的帳單
  835. var ExhibitionKeys = string.Join(",", saExps.Select(c => c.Id).ToList());
  836. var view = db.Queryable<OVW_OPM_Bills, OTB_OPM_BillInfo>
  837. ((t1, t2) =>
  838. new object[] {
  839. JoinType.Inner, t1.OrgID == t2.OrgID && t1.BillNO == t2.BillNO
  840. }
  841. )
  842. .Where((t1, t2) => t1.OrgID == i_crm.ORIGID && CommonRPT.PassStatus.Contains(t2.AuditVal))
  843. .WhereIF(SearchedExp, (t1, t2) => ExhibitionKeys.Contains(t2.ParentId))
  844. .WhereIF(!string.IsNullOrEmpty(Filter.sBillAuditDateStart), (t1, t2) => SqlFunc.ToDate(t2.BillFirstCheckDate) >= Filter.rBillAuditDateStart.Date)
  845. .WhereIF(!string.IsNullOrEmpty(Filter.sBillAuditDateEnd), (t1, t2) => SqlFunc.ToDate(t2.BillFirstCheckDate) < Filter.rBillAuditDateEnd.Date);
  846. var saBills = view.Select((t1, t2) =>
  847. new View_OPM_BillIReport
  848. {
  849. BillNO = t2.BillNO,
  850. BillType = t2.BillType,
  851. ParentId = t2.ParentId,
  852. ProjectNumber = t1.ProjectNumber,
  853. CustomerCode = t1.CustomerCode,
  854. ResponsiblePerson = t1.ResponsiblePersonFullCode,
  855. Currency = t2.Currency,
  856. ExchangeRate = t2.ExchangeRate,
  857. InCome = t1.TWNOTaxAmount, //未稅總計
  858. OrgID = t2.OrgID,
  859. IsReturn = t2.IsRetn,
  860. Weight = t2.Weight,
  861. Volume = t2.Volume,
  862. AuditVal = t2.AuditVal,
  863. ReFlow = t2.ReFlow,
  864. FeeItems = t2.FeeItems
  865. })
  866. .MergeTable()
  867. .ToList();
  868. #endregion
  869. var cellsApp = new ExcelService(sTempFile);
  870. var cells = cellsApp.sheet.Cells;//单元格
  871. var iCurrRow = 6;
  872. cells[1, 1].PutValue(sBillAuditDateStart + "~" + sBillAuditDateEnd);//帳單區間
  873. cells[1, 7].PutValue(i_crm.USERID);//列表人
  874. cells[2, 1].PutValue(string.Join(",", ChildDeptIDs));//部門
  875. cells[2, 7].PutValue(DateTime.Now.ToString(@"yyyy/MM/dd"));//列印時間
  876. cells[3, 1].PutValue(sResponsiblePerson);//業務
  877. var saBillPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "PrepayForCustomerCode");
  878. var BillPrepayFeeList = saBillPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  879. var saActualPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "ActualPrepayForCustomerCode");
  880. var ActualPrepayFeeList = saActualPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  881. var AllofPorfits = new List<ProfitInfo>();
  882. var BillGroup = saBills.GroupBy(c => c.ParentId);
  883. var AllCBMUsage = CommonRPT.GetAllCBMUsages(db, i_crm.ORIGID);
  884. foreach (var bills in BillGroup)
  885. {
  886. var SubProfits = new List<ProfitInfo>();
  887. foreach (View_OPM_BillIReport bill in bills)
  888. {
  889. var ThisBillCBMUsage = AllCBMUsage.Where(t1 => t1.ParentID == bill.ParentId && t1.IsReturn == bill.IsReturn).ToList();
  890. var iInCome = bill.InCome * decimal.Parse(bill.ExchangeRate == "" ? "0" : bill.ExchangeRate);
  891. var ActualCostFeeItemJson = "";
  892. var sActualCost = "";
  893. var sTransportationMode = "";
  894. CommonRPT.CalcuCostAndProfit(db, ref ActualCostFeeItemJson, ref sActualCost, ref sTransportationMode, bill.BillNO, bill.ParentId, bill.IsReturn, bill.ReFlow, bill.BillType);
  895. var ActualCostFeeItemList = CommonRPT.ToFeeItems(ActualCostFeeItemJson);
  896. var BillFeeItemList = CommonRPT.ToFeeItems(bill.FeeItems);
  897. var SharedActualCost = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO);
  898. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  899. var ActualBillReimburseAmount = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO, ActualPrepayFeeList);//抓實際成本的資料
  900. decimal.TryParse(bill.Volume, out var Volume);
  901. decimal.TryParse(bill.Weight, out var Weight);
  902. var CustomerName = saExps.FirstOrDefault(c => c.Id == bill.ParentId)?.Agent;
  903. ProfitInfo profitInfo = new ProfitInfo()
  904. {
  905. ExhibitionName = bill.ProjectNumber,
  906. CustomerName = CustomerName,
  907. BillUntaxAmt = CommonRPT.Rounding(iInCome.Value, RoundingPoint),
  908. SharedActualCost = SharedActualCost,
  909. BillReimburseAmount = BillReimburseAmount,
  910. ActualBillReimburseAmount = ActualBillReimburseAmount,
  911. Weight = Weight,
  912. Volume = Volume
  913. };
  914. if (ShowSource)
  915. {
  916. profitInfo.BillNO = $"類型:{bill.BillType}-單號:{bill.BillNO}-狀態:{bill.AuditVal}";
  917. }
  918. SubProfits.Add(profitInfo);
  919. }
  920. ProfitInfo SubtotalProfitInfo = new ProfitInfo()
  921. {
  922. ExhibitionName = SubProfits.First().ExhibitionName,
  923. CustomerName = SubProfits.First().CustomerName,
  924. BillUntaxAmt = SubProfits.Sum(c => c.BillUntaxAmt),
  925. SharedActualCost = CommonRPT.Rounding(SubProfits.Sum(c => c.SharedActualCost), RoundingPoint),
  926. BillReimburseAmount = CommonRPT.Rounding(SubProfits.Sum(c => c.BillReimburseAmount), RoundingPoint),
  927. ActualBillReimburseAmount = CommonRPT.Rounding(SubProfits.Sum(c => c.ActualBillReimburseAmount), RoundingPoint),
  928. Weight = SubProfits.Sum(c => c.Weight),
  929. Volume = SubProfits.Sum(c => c.Volume)
  930. };
  931. if (ShowSource)
  932. {
  933. SubtotalProfitInfo.BillNO = string.Join("■", SubProfits.Select(test => test.BillNO));
  934. }
  935. AllofPorfits.Add(SubtotalProfitInfo);
  936. }
  937. //分類印出來
  938. var AgentGroup = AllofPorfits.GroupBy(c => c.CustomerName).OrderBy(c => c.Key);
  939. var CellType = GetCellType(RPTEnum.DegreeOfContributionByAgent, RoundingPoint, ShowSource);
  940. foreach (var profitInfos in AgentGroup)
  941. {
  942. ProfitInfo profitInfo = new ProfitInfo()
  943. {
  944. ExField = profitInfos.Select(c => c.ExhibitionName).Distinct().Count(),
  945. CustomerName = profitInfos.First().CustomerName,
  946. BillUntaxAmt = CommonRPT.Rounding(profitInfos.Sum(c => c.BillUntaxAmt), RoundingPoint),
  947. SharedActualCost = CommonRPT.Rounding(profitInfos.Sum(c => c.SharedActualCost), RoundingPoint),
  948. BillReimburseAmount = CommonRPT.Rounding(profitInfos.Sum(c => c.BillReimburseAmount), RoundingPoint),
  949. ActualBillReimburseAmount = CommonRPT.Rounding(profitInfos.Sum(c => c.ActualBillReimburseAmount), RoundingPoint),
  950. Weight = profitInfos.Sum(c => c.Weight),
  951. Volume = profitInfos.Sum(c => c.Volume)
  952. };
  953. var CellColumns = CalcuCellValue(RPTEnum.DegreeOfContributionByAgent, profitInfo).ToList();
  954. if (ShowSource)
  955. {
  956. var Source = string.Join("", profitInfos.Select(test => test.BillNO));
  957. CellColumns.Add(Source);
  958. }
  959. CellsSetValue(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  960. iCurrRow++;
  961. }
  962. cellsApp.sheet.AutoFitColumns();
  963. if (File.Exists(sOutPut))
  964. {
  965. File.Delete(sOutPut);
  966. }
  967. //保存
  968. cellsApp.workbook.Save(sOutPut);
  969. if (sFlag == @"pdf")
  970. {
  971. var excelApp = new ExcelEdit();
  972. try
  973. {
  974. excelApp.Open(sOutPut);
  975. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  976. excelApp.SaveAsPdf(sOutPut);
  977. excelApp.Close();
  978. }
  979. catch (Exception ex)
  980. {
  981. rm = new SuccessResponseMessage(null, i_crm);
  982. sMsg = ex.Message;
  983. excelApp.Close();
  984. }
  985. }
  986. File.Delete(sTempFile); //刪除臨時文件
  987. sOutPut = sOutPut.Replace(sBase, @"");
  988. rm = new SuccessResponseMessage(null, i_crm);
  989. rm.DATA.Add(BLWording.REL, sOutPut);
  990. } while (false);
  991. }
  992. catch (Exception ex)
  993. {
  994. sMsg = Util.GetLastExceptionMsg(ex);
  995. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  996. }
  997. finally
  998. {
  999. if (null != sMsg)
  1000. {
  1001. rm = new ErrorResponseMessage(sMsg, i_crm);
  1002. }
  1003. }
  1004. return rm;
  1005. }
  1006. #endregion
  1007. #region 貢獻度報表(客戶)
  1008. public ResponseMessage DegreeOfContributionByCustomer(RequestMessage i_crm)
  1009. {
  1010. //帳單(拋轉)區間、銷帳區間、部門、業務 客戶 ==> A B
  1011. ShowSource = CommonRPT.RPTShow();
  1012. ResponseMessage rm = null;
  1013. string sMsg = null;
  1014. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  1015. var FunctionName = nameof(DegreeOfContributionByCustomer);
  1016. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "貢獻度報表(客戶)");
  1017. var sOutPut = ExcutePath.Item1;
  1018. var sTempFile = ExcutePath.Item2;
  1019. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  1020. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  1021. var sTransactiontype = "A,B";
  1022. try
  1023. {
  1024. do
  1025. {
  1026. var sBillAuditDateStart = _fetchString(i_crm, @"BillAuditDateStart");
  1027. var sBillAuditDateEnd = _fetchString(i_crm, @"BillAuditDateEnd");
  1028. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  1029. var sResponsiblePerson = _fetchString(i_crm, @"ResponsiblePerson");
  1030. var SearchMatchedExps = !string.IsNullOrWhiteSpace(sResponsibleDeptID) || !string.IsNullOrWhiteSpace(sResponsiblePerson);
  1031. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  1032. var MatchedExpList = CommonRPT.GetMatchedExps(db, i_crm.ORIGID, ChildDeptIDs, sResponsiblePerson);
  1033. var MatchedExpGuids = MatchedExpList.Select(t1 => t1.Guid).Distinct().ToArray();
  1034. var sCustomerName = _fetchString(i_crm, @"CustomerName");
  1035. var sCustomerGuid = _fetchString(i_crm, @"CustomerGuid");
  1036. var sFlag = _fetchString(i_crm, @"Flag");
  1037. var Filter = new CVPFilter();
  1038. Filter.SetBill(sBillAuditDateStart, sBillAuditDateEnd, "", "");
  1039. //依序1.Customers => 2.Exhibition(四展覽) => 3.Billinfo => 4.統計
  1040. var CustomerKey = "";
  1041. var Customers = db.Queryable<OTB_CRM_Customers>()
  1042. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.Effective == "Y" && sTransactiontype.Contains(t1.TransactionType))
  1043. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerName), (t1) =>
  1044. t1.CustomerCName.Contains(sCustomerName) || t1.CustomerEName.Contains(sCustomerName) ||
  1045. t1.CustomerShotCName.Contains(sCustomerName) || t1.CustomerShotEName.Contains(sCustomerName))
  1046. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerGuid), t1 => t1.guid == sCustomerGuid);
  1047. //找不到也要篩選
  1048. CustomerKey = Customers.Select(t1 => t1.guid).ToJson();
  1049. #region 符合展覽的的帳單
  1050. var view = db.Queryable<OVW_OPM_Bills, OTB_OPM_BillInfo, OTB_CRM_Customers>
  1051. ((t1, t2, t3) =>
  1052. new object[] {
  1053. JoinType.Inner, t1.OrgID == t2.OrgID && t1.BillNO == t2.BillNO,
  1054. JoinType.Inner, t1.OrgID == t3.OrgID && t2.Payer == t3.guid && sTransactiontype.Contains(t3.TransactionType)
  1055. }
  1056. )
  1057. .Where((t1, t2) => t1.OrgID == i_crm.ORIGID && CommonRPT.PassStatus.Contains(t2.AuditVal))
  1058. .WhereIF(!string.IsNullOrWhiteSpace(CustomerKey), (t1, t2) => !SqlFunc.IsNullOrEmpty(t2.Payer) && CustomerKey.Contains(t2.Payer))
  1059. .WhereIF(SearchMatchedExps, (t1, t2) => SqlFunc.ContainsArray(MatchedExpGuids, t2.ParentId))
  1060. .WhereIF(!string.IsNullOrEmpty(Filter.sBillAuditDateStart), (t1, t2) => SqlFunc.ToDate(t2.BillFirstCheckDate) >= Filter.rBillAuditDateStart.Date)
  1061. .WhereIF(!string.IsNullOrEmpty(Filter.sBillAuditDateEnd), (t1, t2) => SqlFunc.ToDate(t2.BillFirstCheckDate) < Filter.rBillAuditDateEnd.Date);
  1062. var saBills = view.Select((t1, t2, t3) =>
  1063. new View_OPM_BillIReport
  1064. {
  1065. BillNO = t2.BillNO,
  1066. BillType = t2.BillType,
  1067. ParentId = t2.ParentId,
  1068. ProjectNumber = t1.ProjectNumber,
  1069. CustomerName = t3.CustomerShotCName,
  1070. ResponsiblePerson = t1.ResponsiblePersonFullCode,
  1071. Currency = t2.Currency,
  1072. ExchangeRate = t2.ExchangeRate,
  1073. InCome = t1.TWNOTaxAmount, //未稅總計
  1074. OrgID = t2.OrgID,
  1075. IsReturn = t2.IsRetn,
  1076. Weight = t2.Weight,
  1077. Volume = t2.Volume,
  1078. AuditVal = t2.AuditVal,
  1079. ReFlow = t2.ReFlow,
  1080. FeeItems = t2.FeeItems
  1081. })
  1082. .MergeTable()
  1083. .ToList();
  1084. #endregion
  1085. var cellsApp = new ExcelService(sTempFile);
  1086. var cells = cellsApp.sheet.Cells;//单元格
  1087. var iCurrRow = 6;
  1088. cells[1, 1].PutValue(sBillAuditDateStart + "~" + sBillAuditDateEnd);//帳單區間
  1089. cells[1, 7].PutValue(i_crm.USERID);//列表人
  1090. cells[2, 1].PutValue(string.Join(",", ChildDeptIDs));//部門
  1091. cells[2, 7].PutValue(DateTime.Now.ToString(@"yyyy/MM/dd"));//列印時間
  1092. cells[3, 1].PutValue(sResponsiblePerson);//業務
  1093. var saBillPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "PrepayForCustomerCode");
  1094. var BillPrepayFeeList = saBillPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  1095. var saActualPrepayFee = Common.GetSystemSetting(db, i_crm.ORIGID, "ActualPrepayForCustomerCode");
  1096. var ActualPrepayFeeList = saActualPrepayFee.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  1097. var AllofPorfits = new List<ProfitInfo>();
  1098. //統計帳單資料
  1099. var BillGroup = saBills.GroupBy(c => c.CustomerName).OrderBy(c => c.Key);
  1100. var CellType = GetCellType(RPTEnum.DegreeOfContributionByCustomer, RoundingPoint, ShowSource);
  1101. var AllCBMUsage = CommonRPT.GetAllCBMUsages(db, i_crm.ORIGID);
  1102. foreach (var bills in BillGroup)
  1103. {
  1104. var SubProfits = new List<ProfitInfo>();
  1105. foreach (View_OPM_BillIReport bill in bills)
  1106. {
  1107. var ThisBillCBMUsage = AllCBMUsage.Where(t1 => t1.ParentID == bill.ParentId && t1.IsReturn == bill.IsReturn).ToList();
  1108. var iInCome = bill.InCome * decimal.Parse(bill.ExchangeRate == "" ? "0" : bill.ExchangeRate);
  1109. var ActualCostFeeItemJson = "";
  1110. var sActualCost = "";
  1111. var sTransportationMode = "";
  1112. CommonRPT.CalcuCostAndProfit(db, ref ActualCostFeeItemJson, ref sActualCost, ref sTransportationMode, bill.BillNO, bill.ParentId, bill.IsReturn, bill.ReFlow, bill.BillType);
  1113. var ActualCostFeeItemList = CommonRPT.ToFeeItems(ActualCostFeeItemJson);
  1114. var BillFeeItemList = CommonRPT.ToFeeItems(bill.FeeItems);
  1115. var SharedActualCost = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO);
  1116. var BillReimburseAmount = BillFeeItemList.Where(c => BillPrepayFeeList.Contains(c.FinancialCode)).Sum(c => c.TWAmount); //帳單內特定費用代碼資料
  1117. var ActualBillReimburseAmount = CommonRPT.GetShareCost(ActualCostFeeItemList, ThisBillCBMUsage, bill.BillNO, ActualPrepayFeeList);//抓實際成本的資料
  1118. decimal.TryParse(bill.Volume, out var Volume);
  1119. decimal.TryParse(bill.Weight, out var Weight);
  1120. ProfitInfo profitInfo = new ProfitInfo()
  1121. {
  1122. ExhibitionName = bill.ProjectNumber,
  1123. CustomerName = bill.CustomerName,
  1124. BillUntaxAmt = CommonRPT.Rounding(iInCome.Value, RoundingPoint),
  1125. SharedActualCost = SharedActualCost,
  1126. BillReimburseAmount = BillReimburseAmount,
  1127. ActualBillReimburseAmount = ActualBillReimburseAmount,
  1128. Weight = Weight,
  1129. Volume = Volume
  1130. };
  1131. if (ShowSource)
  1132. {
  1133. profitInfo.BillNO = $"類型:{bill.BillType}-單號:{bill.BillNO}-狀態:{bill.AuditVal}";
  1134. }
  1135. SubProfits.Add(profitInfo);
  1136. }
  1137. ProfitInfo SubtotalProfitInfo = new ProfitInfo()
  1138. {
  1139. //放展覽次數
  1140. ExField = SubProfits.Select(c => c.ExhibitionName).Distinct().Count(),
  1141. CustomerName = SubProfits.First().CustomerName,
  1142. BillUntaxAmt = CommonRPT.Rounding(SubProfits.Sum(c => c.BillUntaxAmt), RoundingPoint),
  1143. SharedActualCost = CommonRPT.Rounding(SubProfits.Sum(c => c.SharedActualCost), RoundingPoint),
  1144. BillReimburseAmount = CommonRPT.Rounding(SubProfits.Sum(c => c.BillReimburseAmount), RoundingPoint),
  1145. ActualBillReimburseAmount = CommonRPT.Rounding(SubProfits.Sum(c => c.ActualBillReimburseAmount), RoundingPoint),
  1146. Weight = SubProfits.Sum(c => c.Weight),
  1147. Volume = SubProfits.Sum(c => c.Volume)
  1148. };
  1149. var CellColumns = CalcuCellValue(RPTEnum.DegreeOfContributionByCustomer, SubtotalProfitInfo).ToList();
  1150. if (ShowSource)
  1151. {
  1152. var Source = string.Join("■", SubProfits.Select(test => test.BillNO));
  1153. CellColumns.Add(Source);
  1154. }
  1155. CellsSetValue(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  1156. AllofPorfits.AddRange(SubProfits);
  1157. iCurrRow++;
  1158. }
  1159. cells.StandardWidth = 15;
  1160. cellsApp.sheet.AutoFitColumn(7);
  1161. if (File.Exists(sOutPut))
  1162. {
  1163. File.Delete(sOutPut);
  1164. }
  1165. cellsApp.sheet.AutoFitColumns();
  1166. //保存
  1167. cellsApp.workbook.Save(sOutPut);
  1168. if (sFlag == @"pdf")
  1169. {
  1170. var excelApp = new ExcelEdit();
  1171. try
  1172. {
  1173. excelApp.Open(sOutPut);
  1174. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  1175. excelApp.SaveAsPdf(sOutPut);
  1176. excelApp.Close();
  1177. }
  1178. catch (Exception ex)
  1179. {
  1180. rm = new SuccessResponseMessage(null, i_crm);
  1181. sMsg = ex.Message;
  1182. excelApp.Close();
  1183. }
  1184. }
  1185. File.Delete(sTempFile); //刪除臨時文件
  1186. sOutPut = sOutPut.Replace(sBase, @"");
  1187. rm = new SuccessResponseMessage(null, i_crm);
  1188. rm.DATA.Add(BLWording.REL, sOutPut);
  1189. } while (false);
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. sMsg = Util.GetLastExceptionMsg(ex);
  1194. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  1195. }
  1196. finally
  1197. {
  1198. if (null != sMsg)
  1199. {
  1200. rm = new ErrorResponseMessage(sMsg, i_crm);
  1201. }
  1202. }
  1203. return rm;
  1204. }
  1205. #endregion
  1206. #region 現有客戶資訊
  1207. public ResponseMessage ExistingCustomer(RequestMessage i_crm)
  1208. {
  1209. ShowSource = CommonRPT.RPTShow();
  1210. ResponseMessage rm = null;
  1211. string sMsg = null;
  1212. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  1213. var FunctionName = nameof(ExistingCustomer);
  1214. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "現有客戶資訊");
  1215. var sOutPut = ExcutePath.Item1;
  1216. var sTempFile = ExcutePath.Item2;
  1217. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  1218. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  1219. try
  1220. {
  1221. do
  1222. {
  1223. var sCustomerName = _fetchString(i_crm, @"CustomerName");
  1224. var sCustomerGuid = _fetchString(i_crm, @"CustomerGuid");
  1225. var sState = _fetchString(i_crm, @"State");
  1226. var sStartAttendeeTime = _fetchString(i_crm, @"StartAttendeeTime");
  1227. var sEndAttendeeTime = _fetchString(i_crm, @"EndAttendeeTime");
  1228. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  1229. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  1230. var iStartAttendeeTime = 0;
  1231. var iEndAttendeeTime = 0;
  1232. int.TryParse(sStartAttendeeTime, out iStartAttendeeTime);
  1233. int.TryParse(sEndAttendeeTime, out iEndAttendeeTime);
  1234. var stransactiontype = _fetchString(i_crm, @"TransactionType");
  1235. var sFlag = _fetchString(i_crm, @"Flag");
  1236. //「客戶」、「交易型態」、「國家」、「參展次數」
  1237. var Customers = db.Queryable<OTB_CRM_Customers>()
  1238. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.Effective == "Y")
  1239. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerName), (t1) =>
  1240. t1.CustomerCName.Contains(sCustomerName) || t1.CustomerEName.Contains(sCustomerName) ||
  1241. t1.CustomerShotCName.Contains(sCustomerName) || t1.CustomerShotEName.Contains(sCustomerName))
  1242. .WhereIF(!string.IsNullOrWhiteSpace(sCustomerGuid), (t1) => t1.guid == sCustomerGuid)
  1243. .WhereIF(!string.IsNullOrWhiteSpace(stransactiontype), (t1) => stransactiontype.Contains(t1.TransactionType))
  1244. .WhereIF(!string.IsNullOrWhiteSpace(sState), (t1) => t1.State == sState)
  1245. .ToList();
  1246. var ExistingCustomerInfo = new List<ExistingCustomerInfo>();
  1247. foreach (var customer in Customers)
  1248. {
  1249. var info = new ExistingCustomerInfo()
  1250. {
  1251. GUID = customer.guid,
  1252. ChName = customer.CustomerCName,
  1253. EnName = customer.CustomerEName,
  1254. TaxNumber = customer.UniCode,
  1255. TransType = customer.TransactionType,
  1256. State = customer.State,
  1257. AttendeeTimes = 0,
  1258. Address = customer.Address,
  1259. Website = customer.WebsiteAdress,
  1260. AttendeeExhibitions = new List<string>(),
  1261. };
  1262. #region 計算次數
  1263. var sId = customer.guid;
  1264. var saExhibitions = new List<Map>();
  1265. //出口
  1266. var saExport = db.Queryable<OTB_OPM_Exhibition, OTB_OPM_ExportExhibition>((t1, t2) => t1.SN.ToString() == t2.ExhibitionNO && t1.OrgID == t2.OrgID && t1.Effective == "Y" && t2.IsVoid == "N")
  1267. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1, t2) => SqlFunc.ContainsArray(ChildDeptIDs, t2.DepartmentID))
  1268. .Select((t1, t2) => new { t1.OrgID, t1.SN, t1.ExhibitionCode, t1.Exhibitioname_TW, t1.Exhibitioname_CN, t2.ExhibitionNO, t2.Exhibitors, t2.Agent }).MergeTable()
  1269. .Where(it => it.ExhibitionNO != @"" && it.OrgID == i_crm.ORIGID && (it.Exhibitors.Contains(sId) || it.Agent == sId)).ToList();
  1270. if (saExport.Count > 0)
  1271. {
  1272. foreach (var opm in saExport)
  1273. {
  1274. if (!saExhibitions.Any(x => (x[@"SN"].ToString() == opm.SN.ToString())))
  1275. {
  1276. var m = new Map
  1277. {
  1278. { @"RowIndex", saExhibitions.Count + 1 },
  1279. { @"SN", opm.SN },
  1280. { @"ExhibitionCode", opm.ExhibitionCode },
  1281. { @"Exhibitioname_TW", opm.Exhibitioname_TW },
  1282. { @"Exhibitioname_CN", opm.Exhibitioname_CN },
  1283. { @"Source", "OTB_OPM_ExportExhibition" }
  1284. };
  1285. saExhibitions.Add(m);
  1286. }
  1287. }
  1288. }
  1289. //進口
  1290. var saImport = db.Queryable<OTB_OPM_Exhibition, OTB_OPM_ImportExhibition>((t1, t2) => t1.SN.ToString() == t2.ExhibitionNO && t1.OrgID == t2.OrgID && t1.Effective == "Y" && t2.IsVoid == "N")
  1291. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1, t2) => SqlFunc.ContainsArray(ChildDeptIDs, t2.DepartmentID))
  1292. .Select((t1, t2) => new { t1.OrgID, t1.SN, t1.ExhibitionCode, t1.Exhibitioname_TW, t1.Exhibitioname_CN, t2.ExhibitionNO, t2.Suppliers, t2.Supplier, t2.Agent }).MergeTable()
  1293. .Where(it => it.ExhibitionNO != @"" && it.OrgID == i_crm.ORIGID && (it.Suppliers.Contains(sId) || it.Supplier == sId || it.Agent == sId)).ToList();
  1294. if (saImport.Count > 0)
  1295. {
  1296. foreach (var opm in saImport)
  1297. {
  1298. if (!saExhibitions.Any(x => (x[@"SN"].ToString() == opm.SN.ToString())))
  1299. {
  1300. var m = new Map
  1301. {
  1302. { @"RowIndex", saExhibitions.Count + 1 },
  1303. { @"SN", opm.SN },
  1304. { @"ExhibitionCode", opm.ExhibitionCode },
  1305. { @"Exhibitioname_TW", opm.Exhibitioname_TW },
  1306. { @"Exhibitioname_CN", opm.Exhibitioname_CN },
  1307. { @"Source", "OTB_OPM_ImportExhibition" }
  1308. };
  1309. saExhibitions.Add(m);
  1310. }
  1311. }
  1312. }
  1313. //其他
  1314. var saOther = db.Queryable<OTB_OPM_Exhibition, OTB_OPM_OtherExhibition>((t1, t2) => t1.SN.ToString() == t2.ExhibitionNO && t1.OrgID == t2.OrgID && t1.Effective == "Y" && t2.IsVoid == "N")
  1315. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1, t2) => SqlFunc.ContainsArray(ChildDeptIDs, t2.DepartmentID))
  1316. .Select((t1, t2) => new { t1.OrgID, t1.SN, t1.ExhibitionCode, t1.Exhibitioname_TW, t1.Exhibitioname_CN, t2.ExhibitionNO, t2.Supplier, t2.Agent }).MergeTable()
  1317. .Where(it => it.ExhibitionNO != @"" && it.OrgID == i_crm.ORIGID && (it.Supplier == sId || it.Agent == sId)).ToList();
  1318. if (saOther.Count > 0)
  1319. {
  1320. foreach (var opm in saOther)
  1321. {
  1322. if (!saExhibitions.Any(x => (x[@"SN"].ToString() == opm.SN.ToString())))
  1323. {
  1324. var m = new Map
  1325. {
  1326. { @"RowIndex", saExhibitions.Count + 1 },
  1327. { @"SN", opm.SN },
  1328. { @"ExhibitionCode", opm.ExhibitionCode },
  1329. { @"Exhibitioname_TW", opm.Exhibitioname_TW },
  1330. { @"Exhibitioname_CN", opm.Exhibitioname_CN },
  1331. { @"Source", "OTB_OPM_OtherExhibition" }
  1332. };
  1333. saExhibitions.Add(m);
  1334. }
  1335. }
  1336. }
  1337. //其他
  1338. var saOtherTG = db.Queryable<OTB_OPM_Exhibition, OTB_OPM_OtherExhibitionTG>((t1, t2) => t1.SN.ToString() == t2.ExhibitionNO && t1.OrgID == t2.OrgID && t1.Effective == "Y" && t2.IsVoid == "N")
  1339. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1, t2) => SqlFunc.ContainsArray(ChildDeptIDs, t2.DepartmentID))
  1340. .Select((t1, t2) => new { t1.OrgID, t1.SN, t1.ExhibitionCode, t1.Exhibitioname_TW, t1.Exhibitioname_CN, t2.ExhibitionNO, t2.Exhibitors, t2.Agent }).MergeTable()
  1341. .Where(it => it.ExhibitionNO != @"" && it.OrgID == i_crm.ORIGID && (it.Exhibitors.Contains(sId) || it.Agent == sId)).ToList();
  1342. if (saOtherTG.Count > 0)
  1343. {
  1344. foreach (var opm in saOtherTG)
  1345. {
  1346. if (!saExhibitions.Any(x => (x[@"SN"].ToString() == opm.SN.ToString())))
  1347. {
  1348. var m = new Map
  1349. {
  1350. { @"RowIndex", saExhibitions.Count + 1 },
  1351. { @"SN", opm.SN },
  1352. { @"ExhibitionCode", opm.ExhibitionCode },
  1353. { @"Exhibitioname_TW", opm.Exhibitioname_TW },
  1354. { @"Exhibitioname_CN", opm.Exhibitioname_CN },
  1355. { @"Source", "OTB_OPM_OtherExhibitionTG" }
  1356. };
  1357. saExhibitions.Add(m);
  1358. }
  1359. }
  1360. }
  1361. info.AttendeeTimes = saExhibitions.Count;
  1362. info.AttendeeExhibitions = saExhibitions.Select(t1 => t1["ExhibitionCode"].ObjToString()).ToList();
  1363. #endregion
  1364. if (!string.IsNullOrEmpty(customer.Contactors))
  1365. {
  1366. var jaContactors = (JArray)JsonConvert.DeserializeObject(customer.Contactors);
  1367. var ShowOneContactor = jaContactors.First;
  1368. if (ShowOneContactor != null)
  1369. {
  1370. info.FullName = ShowOneContactor["FullName"]?.ObjToString();
  1371. info.Email = ShowOneContactor["Email"]?.ObjToString();
  1372. info.JobtitleName = ShowOneContactor["JobtitleName"]?.ObjToString();
  1373. info.TEL = ShowOneContactor["TEL1"]?.ObjToString();
  1374. }
  1375. }
  1376. ExistingCustomerInfo.Add(info);
  1377. }
  1378. //篩選次數
  1379. if (!string.IsNullOrWhiteSpace(sStartAttendeeTime))
  1380. ExistingCustomerInfo = ExistingCustomerInfo.Where(e => e.AttendeeTimes >= iStartAttendeeTime).ToList();
  1381. if (!string.IsNullOrWhiteSpace(sEndAttendeeTime))
  1382. ExistingCustomerInfo = ExistingCustomerInfo.Where(e => e.AttendeeTimes <= iEndAttendeeTime).ToList();
  1383. var cellsApp = new ExcelService(sTempFile);
  1384. var cells = cellsApp.sheet.Cells;//单元格
  1385. var iCurrRow = 4;
  1386. ExistingCustomerInfo = ExistingCustomerInfo.OrderByDescending(e => e.AttendeeTimes).ToList();
  1387. var CellType = GetCellType(RPTEnum.ExistingCustomer, RoundingPoint, false);
  1388. foreach (var ECI in ExistingCustomerInfo)
  1389. {
  1390. var CellColumns = CalcuCellValue(RPTEnum.ExistingCustomer, ECI);
  1391. CellsSetValueWithAutoHeight(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  1392. ++iCurrRow;
  1393. }
  1394. if (File.Exists(sOutPut))
  1395. {
  1396. File.Delete(sOutPut);
  1397. }
  1398. //保存
  1399. cellsApp.workbook.Save(sOutPut);
  1400. if (sFlag == @"pdf")
  1401. {
  1402. var excelApp = new ExcelEdit();
  1403. try
  1404. {
  1405. excelApp.Open(sOutPut);
  1406. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  1407. excelApp.SaveAsPdf(sOutPut);
  1408. excelApp.Close();
  1409. }
  1410. catch (Exception ex)
  1411. {
  1412. sMsg = ex.Message;
  1413. excelApp.Close();
  1414. }
  1415. }
  1416. File.Delete(sTempFile); //刪除臨時文件
  1417. sOutPut = sOutPut.Replace(sBase, @"");
  1418. rm = new SuccessResponseMessage(null, i_crm);
  1419. rm.DATA.Add(BLWording.REL, sOutPut);
  1420. } while (false);
  1421. }
  1422. catch (Exception ex)
  1423. {
  1424. sMsg = Util.GetLastExceptionMsg(ex);
  1425. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  1426. }
  1427. finally
  1428. {
  1429. if (null != sMsg)
  1430. {
  1431. rm = new ErrorResponseMessage(sMsg, i_crm);
  1432. }
  1433. }
  1434. return rm;
  1435. }
  1436. #endregion
  1437. #region 展覽資訊
  1438. public ResponseMessage ExhibitionInfo(RequestMessage i_crm)
  1439. {
  1440. ShowSource = CommonRPT.RPTShow();
  1441. ResponseMessage rm = null;
  1442. string sMsg = null;
  1443. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  1444. var FunctionName = nameof(ExhibitionInfo);
  1445. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "展覽資訊");
  1446. var sOutPut = ExcutePath.Item1;
  1447. var sTempFile = ExcutePath.Item2;
  1448. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  1449. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  1450. try
  1451. {
  1452. do
  1453. {
  1454. //「展覽名稱」、「展期」、「國家」、「展覽產業別」
  1455. var sExhibitionName = _fetchString(i_crm, @"ExhibitionName");
  1456. var sExhibitionCode = _fetchString(i_crm, @"ExhibitionCode");
  1457. var sExhibitionDateStart = _fetchString(i_crm, @"ExhibitionDateStart");
  1458. var sExhibitionDateEnd = _fetchString(i_crm, @"ExhibitionDateEnd");
  1459. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  1460. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  1461. var sState = _fetchString(i_crm, @"State");
  1462. var sIndustry = _fetchString(i_crm, @"Industry");
  1463. var sFlag = _fetchString(i_crm, @"Flag");
  1464. var Filter = new CVPFilter();
  1465. Filter.SetExhibition(sExhibitionDateStart, sExhibitionDateEnd);
  1466. // => 篩選出展覽code
  1467. //
  1468. var ActiveCustomers = db.Queryable<OTB_CRM_Customers>().Where(t1 => t1.Effective == "Y" && t1.OrgID == i_crm.ORIGID).Select(c => c.guid).ToList();
  1469. var MatchedExhibitions = db.Queryable<OTB_OPM_Exhibition, OTB_SYS_Arguments, OTB_SYS_Arguments>(((t1, t2, t3) => new object[] {
  1470. JoinType.Left, t1.OrgID == t2.OrgID && t1.State == t2.ArgumentID && t2.ArgumentClassID == "Area" && t2.DelStatus == "N" ,
  1471. JoinType.Left, t3.OrgID == "TE" && t1.Industry == t3.ArgumentID && t3.ArgumentClassID == "ExhibClass"&& t2.DelStatus == "N" ,
  1472. }
  1473. ))
  1474. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.Effective == "Y")
  1475. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionName), t1 =>
  1476. t1.Exhibitioname_EN.Contains(sExhibitionName) || t1.Exhibitioname_TW.Contains(sExhibitionName) ||
  1477. t1.Exhibitioname_CN.Contains(sExhibitionName) || t1.ExhibitioShotName_TW.Contains(sExhibitionName) ||
  1478. t1.ExhibitioShotName_CN.Contains(sExhibitionName) || t1.ExhibitioShotName_EN.Contains(sExhibitionName))
  1479. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionCode), t1 => t1.ExhibitionCode == sExhibitionCode)
  1480. .WhereIF(!string.IsNullOrWhiteSpace(sIndustry), t1 => t1.Industry == sIndustry)
  1481. .WhereIF(!string.IsNullOrWhiteSpace(sState), t1 => t1.State == sState)
  1482. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateStart), t1 => SqlFunc.ToDate(t1.ExhibitionDateStart) >= Filter.rExhibitionDateStart.Date)
  1483. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateEnd), t1 => SqlFunc.ToDate(t1.ExhibitionDateStart) < Filter.rExhibitionDateEnd.Date);
  1484. var ExhibitionList = MatchedExhibitions.Select((t1, t2, t3) =>
  1485. new OTB_OPM_Exhibition()
  1486. {
  1487. Exhibitioname_TW = t1.Exhibitioname_TW,
  1488. SN = t1.SN,
  1489. ExhibitionDateStart = t1.ExhibitionDateStart,
  1490. ExhibitionDateEnd = t1.ExhibitionDateEnd,
  1491. State = t2.ArgumentValue,
  1492. Industry = t3.ArgumentValue,
  1493. ExFeild1 = t1.State,
  1494. ExFeild2 = t1.Industry,
  1495. }).ToList();
  1496. var ExhibitionKeys = string.Join("", ExhibitionList.Select(t1 => "|" + t1.SN + "|").ToList());
  1497. var ExhibitionDic = ExhibitionList.ToDictionary(t1 => t1.SN.ToString());
  1498. #region Exhibition(四展覽)
  1499. var viewExpIm = db.Queryable<OTB_OPM_ImportExhibition, OTB_CRM_Customers>((t1, t2) => new object[] {
  1500. JoinType.Left,t1.Agent==t2.guid && t1.OrgID==t2.OrgID && t2.Effective == "Y"})
  1501. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N")
  1502. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1) => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  1503. .Select((t1) => new ExpInfo
  1504. {
  1505. ExpNO = t1.ExhibitionNO,
  1506. ExhibitionType = "ImportExhibition",
  1507. Exhibitors = "",
  1508. Organizer = "",
  1509. Supplier = t1.Supplier,
  1510. Agent = t1.Agent,
  1511. ResponsibleMember = t1.ResponsiblePerson,
  1512. DeptOfResponsibleMember = t1.DepartmentID,
  1513. OrgID = t1.OrgID
  1514. });
  1515. var viewExpEx = db.Queryable<OTB_OPM_ExportExhibition, OTB_CRM_Customers>((t1, t2) => new object[] {
  1516. JoinType.Left,t1.Agent==t2.guid && t1.OrgID==t2.OrgID && t2.Effective == "Y"})
  1517. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N")
  1518. //Organizer、Exhibitors
  1519. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1) => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  1520. .Select((t1) => new ExpInfo
  1521. {
  1522. ExpNO = t1.ExhibitionNO,
  1523. ExhibitionType = "ExportExhibition",
  1524. Exhibitors = t1.Exhibitors,
  1525. Organizer = t1.Organizer,
  1526. Supplier = "",
  1527. Agent = t1.Agent,
  1528. ResponsibleMember = t1.ResponsiblePerson,
  1529. DeptOfResponsibleMember = t1.DepartmentID,
  1530. OrgID = t1.OrgID
  1531. });
  1532. var viewExpOth = db.Queryable<OTB_OPM_OtherExhibition, OTB_CRM_Customers>((t1, t2) => new object[] {
  1533. JoinType.Left,t1.Agent==t2.guid && t1.OrgID==t2.OrgID && t2.Effective == "Y"})
  1534. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N")
  1535. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1) => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  1536. .Select((t1) => new ExpInfo
  1537. {
  1538. ExpNO = t1.ExhibitionNO,
  1539. ExhibitionType = "OtherExhibition",
  1540. Exhibitors = "",
  1541. Organizer = "",
  1542. Supplier = t1.Supplier,
  1543. Agent = t1.Agent,
  1544. ResponsibleMember = t1.ResponsiblePerson,
  1545. DeptOfResponsibleMember = t1.DepartmentID,
  1546. OrgID = t1.OrgID
  1547. });
  1548. var viewExpOthtG = db.Queryable<OTB_OPM_OtherExhibitionTG, OTB_CRM_Customers>((t1, t2) => new object[] {
  1549. JoinType.Left,t1.Agent==t2.guid && t1.OrgID==t2.OrgID && t2.Effective == "Y"})
  1550. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.IsVoid == "N")
  1551. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), (t1) => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  1552. .Select((t1) => new ExpInfo
  1553. {
  1554. ExpNO = t1.ExhibitionNO,
  1555. ExhibitionType = "OtherExhibitionTG",
  1556. Exhibitors = t1.Exhibitors,
  1557. Organizer = "",
  1558. Supplier = "",
  1559. Agent = t1.Agent,
  1560. ResponsibleMember = t1.ResponsiblePerson,
  1561. DeptOfResponsibleMember = t1.DepartmentID,
  1562. OrgID = t1.OrgID
  1563. });
  1564. var saExps = db.UnionAll(viewExpIm, viewExpEx, viewExpOth, viewExpOthtG).ToList();
  1565. #endregion
  1566. var cellsApp = new ExcelService(sTempFile);
  1567. var cells = cellsApp.sheet.Cells;//单元格
  1568. var iCurrRow = 1;
  1569. var ExhibitionGroup = saExps.Where(c => ExhibitionKeys.Contains("|" + c.ExpNO.Trim() + "|"))
  1570. .GroupBy(c => c.ExpNO).OrderBy(c => c.Key);
  1571. var CellType = GetCellType(RPTEnum.ExhibitionInfo, RoundingPoint, ShowSource);
  1572. if (ExhibitionGroup.Any())
  1573. {
  1574. var DeptDic = CommonRPT.GetDeptInfos(db, i_crm.ORIGID);
  1575. foreach (var Exhibitions in ExhibitionGroup)
  1576. {
  1577. var ExhibitionCode = Exhibitions.First().ExpNO;
  1578. ExhibitionDic.TryGetValue(ExhibitionCode, out var ExhibitionInfo);
  1579. var AgentCount = Exhibitions.Where(c => !string.IsNullOrWhiteSpace(c.Agent) && ActiveCustomers.Any(ac => ac == c.Agent))
  1580. .Select(c => c.Agent).Distinct().Count();
  1581. var OrganizerList = new List<string>();
  1582. var SuppliersList = Exhibitions.Where(c => !string.IsNullOrWhiteSpace(c.Supplier))
  1583. .Select(c => c.Supplier.Trim()).ToList();
  1584. var Organizers = Exhibitions.Where(c => !string.IsNullOrWhiteSpace(c.Organizer)).Select(c => c.Organizer).ToList();
  1585. var Exhibitors = Exhibitions.Where(c => !string.IsNullOrWhiteSpace(c.Exhibitors)).Select(c => c.Exhibitors).ToList();
  1586. //組團單位數
  1587. if (Organizers.Any())
  1588. {
  1589. var SingleOrganizers = Organizers.Where(c => c.Length == 36).ToList();
  1590. OrganizerList.AddRange(SingleOrganizers);
  1591. //出口展覽的組團單位包含舊資料(guid)、新資料(json後的guids)
  1592. var MultipleOrganizer = Organizers.Where(c => c.Length > 36).ToList();
  1593. foreach (var sOrganizer in MultipleOrganizer)
  1594. {
  1595. var jaContactors = (JArray)JsonConvert.DeserializeObject(sOrganizer);
  1596. foreach (var jaContactor in jaContactors)
  1597. {
  1598. var sContactor = jaContactor.ObjToString();
  1599. if (!OrganizerList.Any(c => c == sContactor))
  1600. {
  1601. OrganizerList.Add(sContactor);
  1602. }
  1603. }
  1604. }
  1605. }
  1606. //參加廠商家數
  1607. if (Exhibitors.Any())
  1608. {
  1609. var ExhibitorsList = new List<string>() { };
  1610. foreach (var sExhibitor in Exhibitors)
  1611. {
  1612. var jaExhibitors = (JArray)JsonConvert.DeserializeObject(sExhibitor);
  1613. var SupplierIDs = jaExhibitors.Where(c => !string.IsNullOrWhiteSpace(c["SupplierID"].ObjToString())).Select(c => c["SupplierID"].ToString()).Distinct().ToList();
  1614. ExhibitorsList.AddRange(SupplierIDs);
  1615. }
  1616. SuppliersList.AddRange(ExhibitorsList);
  1617. }
  1618. //依序:展覽名稱 展期 國家 展覽產業別 組團公司 國外代理 部門 組別 負責業務 參展廠商家數
  1619. #region 取相關業務資料
  1620. var ResponsibleMembersList = Exhibitions.Select(c => c.ResponsibleMember).Distinct().ToList();
  1621. var DeptOfResponsibleMembers = Exhibitions.Select(c => c.DeptOfResponsibleMember).Distinct().ToList();
  1622. var TotalResponsibleMembers = string.Join(",", ResponsibleMembersList);
  1623. var ResDeptID = "";
  1624. var UpperDeptID = "";
  1625. if (ResponsibleMembersList.Count >= 2 && DeptOfResponsibleMembers.Count > 2)
  1626. {
  1627. UpperDeptID = DeptOfResponsibleMembers.Count.ToString();
  1628. }
  1629. else
  1630. {
  1631. //只有兩層代表是只顯示部門
  1632. if (DeptDic.TryGetValue(DeptOfResponsibleMembers.First(), out var DeptInfo))
  1633. {
  1634. if (DeptInfo.Item5 == "2")
  1635. {
  1636. ResDeptID = DeptInfo.Item2;
  1637. UpperDeptID = DeptInfo.Item4;
  1638. }
  1639. else
  1640. {
  1641. UpperDeptID = DeptInfo.Item2;
  1642. }
  1643. }
  1644. }
  1645. #endregion
  1646. var DateStart = ExhibitionInfo.ExhibitionDateStart.HasValue ? ExhibitionInfo.ExhibitionDateStart.Value.ToString("yyyy/MM/dd") : "";
  1647. var DateEnd = ExhibitionInfo.ExhibitionDateEnd.HasValue ? ExhibitionInfo.ExhibitionDateEnd.Value.ToString("yyyy/MM/dd") : "";
  1648. OrganizerList = OrganizerList.Distinct().ToList();
  1649. SuppliersList = SuppliersList.Distinct().ToList();
  1650. var SummaryInfo = new List<object>
  1651. {
  1652. ExhibitionInfo.Exhibitioname_TW.ObjToString() ?? "",
  1653. DateStart + "-" + DateEnd,
  1654. ExhibitionInfo.State.ObjToString() ?? "",
  1655. ExhibitionInfo.Industry.ObjToString() ?? "",
  1656. OrganizerList.Count,
  1657. AgentCount.ObjToInt(),
  1658. UpperDeptID.ObjToString(),
  1659. ResDeptID.ObjToString(),
  1660. TotalResponsibleMembers.ObjToString(),
  1661. SuppliersList.Count
  1662. };
  1663. CellsSetValueWithAutoHeight(cellsApp.workbook, cells, iCurrRow, SummaryInfo, CellType);
  1664. ++iCurrRow;
  1665. }
  1666. }
  1667. if (File.Exists(sOutPut))
  1668. {
  1669. File.Delete(sOutPut);
  1670. }
  1671. //保存
  1672. cellsApp.workbook.Save(sOutPut);
  1673. if (sFlag == @"pdf")
  1674. {
  1675. var excelApp = new ExcelEdit();
  1676. try
  1677. {
  1678. excelApp.Open(sOutPut);
  1679. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  1680. excelApp.SaveAsPdf(sOutPut);
  1681. excelApp.Close();
  1682. }
  1683. catch (Exception ex)
  1684. {
  1685. rm = new SuccessResponseMessage(null, i_crm);
  1686. sMsg = ex.Message;
  1687. excelApp.Close();
  1688. }
  1689. }
  1690. File.Delete(sTempFile); //刪除臨時文件
  1691. sOutPut = sOutPut.Replace(sBase, @"");
  1692. rm = new SuccessResponseMessage(null, i_crm);
  1693. rm.DATA.Add(BLWording.REL, sOutPut);
  1694. } while (false);
  1695. }
  1696. catch (Exception ex)
  1697. {
  1698. sMsg = Util.GetLastExceptionMsg(ex);
  1699. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  1700. }
  1701. finally
  1702. {
  1703. if (null != sMsg)
  1704. {
  1705. rm = new ErrorResponseMessage(sMsg, i_crm);
  1706. }
  1707. }
  1708. return rm;
  1709. }
  1710. #endregion
  1711. #region 展覽資訊
  1712. public ResponseMessage CostFeeItemReport(RequestMessage i_crm)
  1713. {
  1714. ShowSource = CommonRPT.RPTShow();
  1715. ResponseMessage rm = null;
  1716. string sMsg = null;
  1717. var db = SugarBase.GetIntance(commandTimeOut: TimeOut);
  1718. var FunctionName = nameof(CostFeeItemReport);
  1719. var ExcutePath = CommonRPT.GetExcutePath(FunctionName, "成本費用報表");
  1720. var sOutPut = ExcutePath.Item1;
  1721. var sTempFile = ExcutePath.Item2;
  1722. var sBase = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"");
  1723. var RoundingPoint = CommonRPT.GetRoundingPoint(i_crm.ORIGID);
  1724. try
  1725. {
  1726. do
  1727. {
  1728. //「展覽名稱」(下拉)、「展期」、「部門」、「費用項目」、
  1729. var sExhibitionCode = _fetchString(i_crm, @"ProjectNO");
  1730. var sExhibitionName = "";
  1731. var sExhibitionDateStart = _fetchString(i_crm, @"ExhibitionDateStart");
  1732. var sExhibitionDateEnd = _fetchString(i_crm, @"ExhibitionDateEnd");
  1733. var sResponsibleDeptID = _fetchString(i_crm, @"ResponsibleDeptID");
  1734. var sFeeClass = _fetchString(i_crm, @"FeeClass");
  1735. var ChildDeptIDs = CommonRPT.GetChildDepteList(db, i_crm.ORIGID, sResponsibleDeptID);
  1736. var sFlag = _fetchString(i_crm, @"Flag");
  1737. var Filter = new CVPFilter();
  1738. Filter.SetExhibition(sExhibitionDateStart, sExhibitionDateEnd);
  1739. // => 篩選出展覽code
  1740. var MatchedExhibitions = db.Queryable<OTB_OPM_Exhibition>()
  1741. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.Effective == "Y")
  1742. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionCode), t1 => t1.ExhibitionCode == sExhibitionCode)
  1743. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateStart), t1 => SqlFunc.ToDate(t1.ExhibitionDateStart) >= Filter.rExhibitionDateStart.Date)
  1744. .WhereIF(!string.IsNullOrWhiteSpace(Filter.sExhibitionDateEnd), t1 => SqlFunc.ToDate(t1.ExhibitionDateStart) < Filter.rExhibitionDateEnd.Date);
  1745. var ExpSNs = MatchedExhibitions
  1746. .Select(t1 => t1.SN.ToString()).ToList().ToArray();
  1747. var saActualCosts = db.Queryable<OVW_OPM_ALLExps>()
  1748. .Where((t1) => t1.OrgID == i_crm.ORIGID)
  1749. .WhereIF(!string.IsNullOrWhiteSpace(sExhibitionCode) || !string.IsNullOrWhiteSpace(Filter.sExhibitionDateStart)
  1750. || !string.IsNullOrWhiteSpace(Filter.sExhibitionDateEnd), t1 => SqlFunc.ContainsArray(ExpSNs, t1.ExhibitionSN))
  1751. .WhereIF(!string.IsNullOrWhiteSpace(sResponsibleDeptID), t1 => SqlFunc.ContainsArray(ChildDeptIDs, t1.DepartmentID))
  1752. .ToList();
  1753. if (!string.IsNullOrWhiteSpace(sExhibitionCode))
  1754. {
  1755. sExhibitionName = db.Queryable<OTB_OPM_Exhibition>()
  1756. .Where(t1 => t1.OrgID == "TE" && t1.Effective == "Y" && t1.ExhibitionCode == sExhibitionCode)
  1757. .Select(t1 => t1.Exhibitioname_TW).First();
  1758. }
  1759. var ActualCostSummary = db.Queryable<OTB_SYS_Arguments>()
  1760. .Where(t1 => t1.OrgID == i_crm.ORIGID && t1.ArgumentClassID == "FeeClass" && t1.DelStatus == "N")
  1761. .WhereIF(!string.IsNullOrWhiteSpace(sFeeClass), t1 => t1.ArgumentID == sFeeClass)
  1762. .Select(t1 => new CostFeeItem
  1763. {
  1764. ArgumentID = t1.ArgumentID,
  1765. ArgumentDescription = t1.ArgumentValue,
  1766. })
  1767. .ToList().Where(t1 => t1.ArgumentID.IndexOf("99") == 0).ToList();
  1768. var ToAnalysisList = saActualCosts.Select(t1 => t1.ActualCost).ToList();
  1769. foreach (var ReturnBill in saActualCosts.Select(t1 => t1.ReturnBills).ToList())
  1770. {
  1771. var JADatas = JArray.Parse(ReturnBill);
  1772. if (JADatas.Any())
  1773. {
  1774. foreach (var jToken in JADatas)
  1775. {
  1776. var sActualCost = jToken["ActualCost"];
  1777. if (sActualCost != null)
  1778. {
  1779. ToAnalysisList.Add(sActualCost.ToString());
  1780. }
  1781. }
  1782. }
  1783. }
  1784. foreach (string sJsons in ToAnalysisList)
  1785. {
  1786. var ActualCostBills = JToken.Parse(sJsons);
  1787. var ActualCosts = ActualCostBills["FeeItems"];
  1788. if (ActualCostBills.Any() && ActualCosts != null && ActualCosts.Any())
  1789. {
  1790. foreach (var ActualCost in ActualCosts)
  1791. {
  1792. var FinancialCode = ActualCost["FinancialCode"].ObjToString();
  1793. var AlreadyExist = ActualCostSummary.FirstOrDefault(c => c.ArgumentID == FinancialCode);
  1794. if (AlreadyExist != null)
  1795. {
  1796. AlreadyExist.Amount += ActualCost["FinancialTWAmount"].ObjToDecimal();
  1797. }
  1798. }
  1799. }
  1800. }
  1801. var CellType = GetCellType(RPTEnum.CostFeeItemReport, RoundingPoint);
  1802. var cellsApp = new ExcelService(sTempFile);
  1803. var cells = cellsApp.sheet.Cells;//单元格
  1804. var iCurrRow = 5;
  1805. cells[1, 0].PutValue("展覽區間:" + sExhibitionDateStart + "~" + sExhibitionDateEnd);
  1806. cells[1, 2].PutValue("部門:" + string.Join(",", ChildDeptIDs));
  1807. cells[2, 0].PutValue("展覽名稱:" + sExhibitionName);
  1808. cells[2, 2].PutValue("列表人:" + i_crm.USERID);
  1809. cells[3, 2].PutValue("列印時間:" + DateTime.Now.ToString(@"yyyy/MM/dd"));
  1810. foreach (var costFee in ActualCostSummary)
  1811. {
  1812. var CellColumns = CalcuCellValue(RPTEnum.CostFeeItemReport, costFee);
  1813. CellsSetValue(cellsApp.workbook, cells, iCurrRow, CellColumns, CellType);
  1814. ++iCurrRow;
  1815. }
  1816. if (File.Exists(sOutPut))
  1817. {
  1818. File.Delete(sOutPut);
  1819. }
  1820. //保存
  1821. cellsApp.workbook.Save(sOutPut);
  1822. if (sFlag == @"pdf")
  1823. {
  1824. var excelApp = new ExcelEdit();
  1825. try
  1826. {
  1827. excelApp.Open(sOutPut);
  1828. sOutPut = sOutPut.Replace(@".xlsx", @".pdf").Replace(@".xls", @".pdf");
  1829. excelApp.SaveAsPdf(sOutPut);
  1830. excelApp.Close();
  1831. }
  1832. catch (Exception ex)
  1833. {
  1834. sMsg = ex.Message;
  1835. excelApp.Close();
  1836. }
  1837. }
  1838. File.Delete(sTempFile); //刪除臨時文件
  1839. sOutPut = sOutPut.Replace(sBase, @"");
  1840. rm = new SuccessResponseMessage(null, i_crm);
  1841. rm.DATA.Add(BLWording.REL, sOutPut);
  1842. } while (false);
  1843. }
  1844. catch (Exception ex)
  1845. {
  1846. sMsg = Util.GetLastExceptionMsg(ex);
  1847. LogAndSendEmail(sMsg + "Params:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, nameof(CostAndProfitReportService), "", FunctionName + "(報表模組)", "", "", "");
  1848. }
  1849. finally
  1850. {
  1851. if (null != sMsg)
  1852. {
  1853. rm = new ErrorResponseMessage(sMsg, i_crm);
  1854. }
  1855. }
  1856. return rm;
  1857. }
  1858. #endregion
  1859. private void CellsSetValueWithAutoHeight(Aspose.Cells.Workbook workbook, Cells cells, int irow, List<object> values, List<int> NumberTypes = null)
  1860. {
  1861. var DefaultHeight = 20;
  1862. var LengthList = values.Select(t1 =>
  1863. {
  1864. var st1 = t1.ObjToString();
  1865. if (!string.IsNullOrWhiteSpace(st1))
  1866. {
  1867. byte[] Dbyte = System.Text.Encoding.Default.GetBytes(st1);
  1868. return Math.Ceiling((Dbyte.Length / 10.0)) * 10 + 10;
  1869. }
  1870. else
  1871. return DefaultHeight;
  1872. });
  1873. CellsSetValue(workbook, cells, irow, values, NumberTypes, LengthList.Max());
  1874. }
  1875. private void CellsSetValue(Aspose.Cells.Workbook workbook, Cells cells, int irow, List<object> values, List<int> NumberTypes = null, double SetRowHeight = 20)
  1876. {
  1877. var styleForNumber = GetStyle(workbook, 12, false, TextAlignmentType.Right, Color.White, true);
  1878. var styleForText = GetStyle(workbook, 12, false, TextAlignmentType.Left, Color.White, true);
  1879. styleForNumber.Number = 4;
  1880. cells.SetRowHeight(irow, SetRowHeight);
  1881. var SetRowValueNumber = NumberTypes != null && values.Count == NumberTypes.Count;
  1882. for (int i = 0; i < values.Count; i++)
  1883. {
  1884. if (values[i] is string)
  1885. {
  1886. cells[irow, i].PutValue(values[i]);
  1887. cells[irow, i].SetStyle(styleForText);
  1888. }
  1889. else
  1890. {
  1891. cells[irow, i].PutValue(values[i]);
  1892. if (SetRowValueNumber && NumberTypes[i] != -1)
  1893. {
  1894. styleForNumber.Number = NumberTypes[i];
  1895. }
  1896. cells[irow, i].SetStyle(styleForNumber);
  1897. }
  1898. }
  1899. }
  1900. public List<object> CalcuCellValue(RPTEnum type, object Data, int RoundingPoint = 0)
  1901. {
  1902. switch (type)
  1903. {
  1904. case RPTEnum.CVPAnalysisBySaler:
  1905. case RPTEnum.CVPAnalysisByExhibition:
  1906. {
  1907. ProfitInfo profitInfo = (ProfitInfo)Data;
  1908. return new List<object>
  1909. {
  1910. profitInfo.MemberID,//名稱
  1911. profitInfo.BillUntaxAmt,//收入(A)
  1912. profitInfo.SharedActualCost,//成本 (B)
  1913. profitInfo.GrossProfit,//毛利(C)=(A)-(B)
  1914. profitInfo.GrossProfitPercent, //毛利率(C)/(A)
  1915. profitInfo.BillReimburseAmount,//帳單代墊款(D)
  1916. profitInfo.ActualBillReimburseAmount, //實際代墊款(E)
  1917. profitInfo.NetIncome,//淨收入(F) =(A)-(D)
  1918. profitInfo.NetCost, //淨成本(G) =(B)-(E)
  1919. profitInfo.NetProfit, //淨毛利(H)=(F)-(G)
  1920. profitInfo.NetProfitPercent//淨毛利率(H)/(F)
  1921. };
  1922. }
  1923. case RPTEnum.CashFlow:
  1924. break;
  1925. case RPTEnum.DegreeOfContributionByCustomer:
  1926. case RPTEnum.DegreeOfContributionByAgent:
  1927. {
  1928. ProfitInfo profitInfo = (ProfitInfo)Data;
  1929. return new List<object>()
  1930. {
  1931. profitInfo.CustomerName,//(代理/客戶)簡稱
  1932. profitInfo.ExField,//次數
  1933. profitInfo.Weight,//重量
  1934. CommonRPT.Rounding(profitInfo.Volume, RoundingPoint),//材積
  1935. CommonRPT.Rounding(profitInfo.BillUntaxAmt, RoundingPoint),//收入(A)
  1936. CommonRPT.Rounding(profitInfo.GrossProfit, RoundingPoint),//毛利(C)=(A)-(B)
  1937. CommonRPT.Rounding(profitInfo.NetIncome, RoundingPoint),//淨收入(F) =(A)-(D)
  1938. CommonRPT.Rounding(profitInfo.NetProfit, RoundingPoint), //淨毛利(H)=(F)-(G)
  1939. };
  1940. }
  1941. case RPTEnum.ExistingCustomer:
  1942. {
  1943. ExistingCustomerInfo eci = (ExistingCustomerInfo)Data;
  1944. return new List<object>()
  1945. {
  1946. eci.ChName ,
  1947. eci.EnName ,
  1948. eci.TaxNumber ,
  1949. eci.TransType ,
  1950. eci.State ,
  1951. eci.AttendeeTimes,
  1952. eci.FullName ,
  1953. eci.JobtitleName ,
  1954. eci.TEL ,
  1955. eci.Email ,
  1956. eci.Address ,
  1957. eci.Website ,
  1958. };
  1959. }
  1960. case RPTEnum.ExhibitionInfo:
  1961. break;
  1962. case RPTEnum.CostFeeItemReport:
  1963. {
  1964. CostFeeItem CFI = (CostFeeItem)Data;
  1965. return new List<object>()
  1966. {
  1967. CFI.ArgumentID,
  1968. CFI.ArgumentDescription,
  1969. CFI.Amount
  1970. };
  1971. }
  1972. default:
  1973. break;
  1974. }
  1975. return new List<object> { };
  1976. }
  1977. public List<int> GetCellType(RPTEnum type, int RoundingPoint = 0, bool showSource = false)
  1978. {
  1979. //Ref:https://docs.aspose.com/display/cellsnet/List+of+Supported+Number+Formats
  1980. var CurrencyType = 5;
  1981. if (RoundingPoint != 0)
  1982. CurrencyType = 4;
  1983. var Types = new List<int>();
  1984. switch (type)
  1985. {
  1986. case RPTEnum.CVPAnalysisBySaler:
  1987. case RPTEnum.CVPAnalysisByExhibition:
  1988. {
  1989. Types = new List<int>
  1990. {
  1991. -1,//名稱
  1992. CurrencyType,//收入(A)
  1993. CurrencyType,//成本 (B)
  1994. CurrencyType,//毛利(C)=(A)-(B)
  1995. 10, //毛利率(C)/(A)
  1996. CurrencyType,//帳單代墊款(D)
  1997. CurrencyType, //實際代墊款(E)
  1998. CurrencyType,//淨收入(F) =(A)-(D)
  1999. CurrencyType, //淨成本(G) =(B)-(E)
  2000. CurrencyType, //淨毛利(H)=(F)-(G)
  2001. 10//淨毛利率(H)/(F)
  2002. };
  2003. }
  2004. break;
  2005. case RPTEnum.CashFlow:
  2006. {
  2007. Types = new List<int>
  2008. {
  2009. -1,//帳單號碼
  2010. -1,//帳單狀態
  2011. -1,//銷帳日期
  2012. -1,//帳單拋轉日期
  2013. -1,//帳單創建日期
  2014. -1,//專案代號
  2015. -1,//展覽名稱
  2016. -1,//展覽簡稱
  2017. -1,//展覽類別
  2018. -1,//展期第一天
  2019. -1,//組團單位
  2020. -1,//客戶編號
  2021. -1,//客戶中文名
  2022. -1,//客戶英文名
  2023. -1,//客戶簡稱
  2024. -1,//國內/國外
  2025. -1,//交易型態
  2026. -1,//負責部門
  2027. -1,//負責組別
  2028. -1,//負責業務
  2029. 4,//材積(CBM)
  2030. -1,//帳單幣別
  2031. 4,//匯率
  2032. 4,//未稅金額(原幣別)
  2033. CurrencyType,//未稅金額(收入)
  2034. CurrencyType,//稅額
  2035. CurrencyType,//成本
  2036. CurrencyType,//帳單代墊款
  2037. CurrencyType,//實際代墊款
  2038. CurrencyType,//毛利
  2039. CurrencyType,//淨毛利
  2040. };
  2041. }
  2042. break;
  2043. case RPTEnum.DegreeOfContributionByCustomer:
  2044. case RPTEnum.DegreeOfContributionByAgent:
  2045. {
  2046. Types = new List<int>
  2047. {
  2048. -1,//(代理/客戶)簡稱
  2049. 1,//次數
  2050. 4,//重量
  2051. 4,//材積
  2052. CurrencyType,//收入(A)
  2053. CurrencyType,//毛利(C)=(A)-(B)
  2054. CurrencyType,//淨收入(F) =(A)-(D)
  2055. CurrencyType, //淨毛利(H)=(F)-(G)
  2056. };
  2057. }
  2058. break;
  2059. case RPTEnum.ExistingCustomer:
  2060. {
  2061. Types = new List<int>
  2062. {
  2063. -1,//客戶中文名稱
  2064. -1,//客戶英文名稱
  2065. -1,//統一編號
  2066. -1,//交易型態
  2067. -1,//國家
  2068. 1,//參展次數
  2069. -1, //聯絡人
  2070. -1, //職稱
  2071. -1, //電話
  2072. -1, //EMAIL
  2073. -1, //地址
  2074. -1, //網址
  2075. };
  2076. }
  2077. break;
  2078. case RPTEnum.ExhibitionInfo:
  2079. {
  2080. Types = new List<int>
  2081. {
  2082. -1,//展覽名稱
  2083. -1 ,//展期
  2084. -1 ,//國家
  2085. -1 ,//展覽產業別
  2086. 1 ,//組團公司(數字)
  2087. 1,//國外代理(數字)
  2088. -1,//部門
  2089. -1 ,//組別
  2090. -1 ,//負責業務
  2091. 1 ,//參展廠商家數
  2092. };
  2093. }
  2094. break;
  2095. case RPTEnum.CostFeeItemReport:
  2096. {
  2097. Types = new List<int>
  2098. {
  2099. -1,//參數值
  2100. -1 ,//費用項目
  2101. CurrencyType//金額(NT$)
  2102. };
  2103. }
  2104. break;
  2105. default:
  2106. break;
  2107. }
  2108. if (showSource)
  2109. {
  2110. Types.Add(-1);
  2111. }
  2112. return Types;
  2113. }
  2114. /// <summary>
  2115. /// 固定的樣式
  2116. /// </summary>
  2117. /// <param name="sFontSize"></param>
  2118. /// <param name="bIsBold"></param>
  2119. /// <param name="sAlign"></param>
  2120. /// <param name="sBgColor"></param>
  2121. /// <param name="bIsWrap"></param>
  2122. /// <param name="workbook"></param>
  2123. /// <returns></returns>
  2124. public static Aspose.Cells.Style GetStyle(Aspose.Cells.Workbook workbook, int sFontSize, bool bIsBold, TextAlignmentType sAlign, Color sBgColor, bool bIsWrap)
  2125. {
  2126. var style = workbook.CreateStyle();
  2127. style.HorizontalAlignment = sAlign;//文字居左/中/右 ---TextAlignmentType.Center
  2128. style.VerticalAlignment = TextAlignmentType.Top;
  2129. if (sFontSize != 0)
  2130. {
  2131. style.Font.Size = sFontSize;//文字大小 ----12
  2132. }
  2133. style.Font.IsBold = bIsBold;//粗体 ----false
  2134. style.ForegroundColor = sBgColor;//背景顏色
  2135. style.Pattern = BackgroundType.Solid;//设置背景類型
  2136. style.IsTextWrapped = bIsWrap;//单元格内容自动换行
  2137. // 邊線設置
  2138. style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
  2139. return style;
  2140. }
  2141. public OVW_OPM_BillInfo ToBillInfo(View_OPM_BillIReport billIReport)
  2142. {
  2143. return new OVW_OPM_BillInfo()
  2144. {
  2145. OrgID = billIReport.OrgID,
  2146. ParentId = billIReport.ParentId,
  2147. IsRetn = billIReport.IsReturn,
  2148. AuditVal = billIReport.AuditVal,
  2149. Volume = billIReport.Volume,
  2150. };
  2151. }
  2152. public void CalcAttendeeAsCustomerGuid(string ExhibitionNO, string CustomerGuid, List<ExistingCustomerInfo> existingCustomerInfos)
  2153. {
  2154. if (!string.IsNullOrWhiteSpace(CustomerGuid))
  2155. {
  2156. var ECI = existingCustomerInfos.FirstOrDefault(c => c.GUID == CustomerGuid);
  2157. if (ECI != null && !ECI.AttendeeExhibitions.Any(e => e == ExhibitionNO))
  2158. {
  2159. ECI.AttendeeExhibitions.Add(ExhibitionNO);
  2160. ++ECI.AttendeeTimes;
  2161. }
  2162. }
  2163. }
  2164. }
  2165. }