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.

309 lines
15 KiB

  1. using CounsellorBL.BLStructure;
  2. using CounsellorBL.Helper;
  3. using MonumentDefine;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Linq;
  6. using OT.COM.ArsenalDB;
  7. using OT.COM.SignalerMessage;
  8. using SoldierData.EnterprizeV4;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Linq;
  13. using Util = OT.COM.LogisticsUtil.Util;
  14. namespace CounsellorBL.ORD
  15. {
  16. public class BranchBusinessReportService : SingleDataTableTemplate<tb_grp_branch>
  17. {
  18. public BranchBusinessReportService()
  19. {
  20. dgReadCommandGenerator = readCommandGenerator;
  21. dgReadCommandPostDataHandler = readCommandPostDataHandler;
  22. }
  23. public new CResponseMessage Read(CRequestMessage i_crmInput) => base.Read(i_crmInput);
  24. protected string readCommandGenerator(CRequestMessage i_crmInput, JArray i_jaData, tb_sys_session i_sSessionUser, out Command o_c,
  25. [System.Runtime.CompilerServices.CallerLineNumber] int i_nCodeLine = 0,
  26. [System.Runtime.CompilerServices.CallerMemberName] string i_sMemberName = "",
  27. [System.Runtime.CompilerServices.CallerFilePath] string i_sSourcePath = "")
  28. {
  29. string sMsg;
  30. Command cRes = null;
  31. try
  32. {
  33. do
  34. {
  35. var lsBranch = ProjectHelper.GetUserGroup(i_crmInput);
  36. var authBranch = ProjectHelper.GetUserBranch(i_crmInput);
  37. var session = ProjectHelper.GetLoginUser(i_crmInput);
  38. Logger.Info(session);
  39. if (session == null)
  40. {
  41. sMsg = "Session error!!";
  42. Logger.Error($"Session error!! i_crmInput={JsonConvert.SerializeObject(i_crmInput)}. ");
  43. }
  44. Dictionary<string, object> dicCondition = GetQueryMasterFirstWhereData(i_crmInput); // 取得condition
  45. QueryJsonElementCollection lBlocks = new QueryJsonElementCollection();
  46. QueryJsonElement qjeBranch = lBlocks.GetInst();
  47. qjeBranch.table = tb_grp_branch.TABLENAME;
  48. qjeBranch.aliascols = new Dictionary<string, List<string>>
  49. {
  50. { tb_grp_branch.CN_UID, new List<string>() { tb_ord_purchase_detail.CN_BRANCH_UID } }
  51. };
  52. qjeBranch.displaycols = new List<string>() { tb_grp_branch.CN_UID };
  53. QueryJsonElement qjePurchase = lBlocks.GetInst();
  54. qjePurchase.table = tb_ord_purchase.TABLENAME;
  55. qjePurchase.jointype = QueryJsonElement.JOIN;
  56. qjePurchase.jointable = qjeBranch;
  57. qjePurchase.joincols = new Dictionary<string, string>() {
  58. { tb_ord_purchase.CN_RECEIVE_BRANCH_UID,tb_grp_branch.CN_UID }};
  59. qjePurchase.displaycols = new List<string>()
  60. {
  61. tb_ord_purchase.CN_AMOUNT
  62. };
  63. List<WhereNode> lwWhereData = new List<WhereNode>();
  64. if (dicCondition.ContainsKey("create_date_start"))
  65. {
  66. if (DateTime.Today.Day > 5)
  67. {
  68. var thisMonth = DateTime.Today.AddDays(-(DateTime.Today.Day - 1));
  69. if (Convert.ToDateTime(dicCondition["create_date_start"]) >= thisMonth)
  70. {
  71. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), dicCondition["create_date_start"]));
  72. }
  73. else
  74. {
  75. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), thisMonth.ToString("yyyy-MM-dd")));
  76. }
  77. }
  78. else
  79. {
  80. var lastMonth = DateTime.Today.AddMonths(-1).AddDays(-(DateTime.Today.Day - 1));
  81. if (Convert.ToDateTime(dicCondition["create_date_start"]) >= lastMonth)
  82. {
  83. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), dicCondition["create_date_start"]));
  84. }
  85. else
  86. {
  87. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), lastMonth.ToString("yyyy-MM-dd")));
  88. }
  89. }
  90. }
  91. if (dicCondition.ContainsKey("create_date_end"))
  92. {
  93. if (!dicCondition.ContainsKey("create_date_start"))
  94. {
  95. if (DateTime.Today.Day > 5)
  96. {
  97. var thisMonth = DateTime.Today.AddDays(-(DateTime.Today.Day - 1));
  98. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), thisMonth.ToString("yyyy-MM-dd")));
  99. }
  100. else
  101. {
  102. var lastMonth = DateTime.Today.AddMonths(-1).AddDays(-(DateTime.Today.Day - 1));
  103. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), lastMonth.ToString("yyyy-MM-dd")));
  104. }
  105. }
  106. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_LT, typeof(tb_ord_purchase), Convert.ToDateTime(dicCondition["create_date_end"]).AddDays(1).ToString("yyyy-MM-dd")));
  107. }
  108. if (!dicCondition.Any())
  109. {
  110. var today = DateTime.Today;
  111. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_GTEQ, typeof(tb_ord_purchase), today));
  112. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_CREATE_DATE, WhereNode.EColumnOperation.EOT_LT, typeof(tb_ord_purchase), today.AddDays(1).ToString("yyyy-MM-dd")));
  113. }
  114. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_STATUS_FLAG, WhereNode.EColumnOperation.EOT_EQ, typeof(tb_ord_purchase), (int)Enums.Flag.Enable));
  115. lwWhereData.Add(new WhereNode(tb_ord_purchase.CN_RECEIVE_BRANCH_UID, WhereNode.EColumnOperation.EOT_IN, typeof(tb_ord_purchase), authBranch.ToArray()));
  116. if (lwWhereData.Any())
  117. {
  118. qjePurchase.wherecols = new WhereNode(WhereNode.ENodeOperation.ENO_AND, lwWhereData.ToArray());
  119. }
  120. QueryJsonElement qjeGroup = lBlocks.GetInst();
  121. qjeGroup.table = tb_grp_group.TABLENAME;
  122. qjeGroup.jointype = QueryJsonElement.JOIN;
  123. qjeGroup.jointable = qjeBranch;
  124. qjeGroup.joincols = new Dictionary<string, string>() {
  125. { tb_grp_group.CN_UID,tb_grp_branch.CN_GROUP_UID }};
  126. qjeGroup.wherecols = new WhereNode(tb_grp_group.CN_UID, WhereNode.EColumnOperation.EOT_IN, typeof(tb_grp_group), lsBranch.ToArray());
  127. qjeGroup.aliascols = new Dictionary<string, List<string>>
  128. {
  129. { tb_grp_group.CN_UID, new List<string>() { tb_grp_branch.CN_GROUP_UID } }
  130. };
  131. QueryJsonElement qjePurchaseDetail = lBlocks.GetInst();
  132. qjePurchaseDetail.table = tb_ord_purchase_detail.TABLENAME;
  133. qjePurchaseDetail.jointype = QueryJsonElement.JOIN;
  134. qjePurchaseDetail.jointable = qjePurchase;
  135. qjePurchaseDetail.joincols = new Dictionary<string, string>() {
  136. { tb_ord_purchase_detail.CN_PURCHASE_UID,tb_ord_purchase.CN_UID }};
  137. qjePurchaseDetail.aliascols = new Dictionary<string, List<string>>
  138. {
  139. { tb_ord_purchase_detail.CN_PURCHASE_UID, new List<string>() { "purchase_uid" } },
  140. { tb_ord_purchase_detail.CN_QTY, new List<string>() { tb_ord_purchase_detail.CN_QTY } },
  141. };
  142. QueryJsonElement qjeArticle2Product = lBlocks.GetInst();
  143. qjeArticle2Product.table = tb_prd_article2product.TABLENAME;
  144. qjeArticle2Product.jointype = QueryJsonElement.JOIN;
  145. qjeArticle2Product.jointable = qjePurchaseDetail;
  146. qjeArticle2Product.joincols = new Dictionary<string, string>() {
  147. { tb_prd_article2product.CN_UID,tb_ord_purchase_detail.CN_ARTICLE2PRODUCT_UID }};
  148. qjeArticle2Product.displaycols = new List<string>()
  149. {
  150. tb_prd_article2product.CN_COST_PRICE,
  151. tb_prd_article2product.CN_PRD_UID,
  152. };
  153. lBlocks.Add(qjeBranch);
  154. lBlocks.Add(qjePurchase);
  155. lBlocks.Add(qjeGroup);
  156. lBlocks.Add(qjePurchaseDetail);
  157. lBlocks.Add(qjeArticle2Product);
  158. sMsg = MakeSelectJoinByBlocks(lBlocks, out cRes);
  159. if (sMsg != null)
  160. {
  161. break;
  162. }
  163. }
  164. while (false);
  165. }
  166. catch (Exception ex)
  167. {
  168. LogHelper.DBLog(Util.GetLastExceptionMsg(ex), i_nCodeLine, i_sMemberName, i_sSourcePath);
  169. sMsg = $"{nameof(readCommandGenerator)} unknwon exception. i_crmInput={JsonConvert.SerializeObject(i_crmInput)}. Call from {i_sMemberName} {i_sSourcePath}({i_nCodeLine}).";
  170. #if DEBUG
  171. System.Diagnostics.Debug.WriteLine(sMsg);
  172. #endif
  173. }
  174. o_c = cRes;
  175. return sMsg;
  176. }
  177. protected string readCommandPostDataHandler(CRequestMessage i_crmInput, ArsenalInterface i_aiArsenal, Command i_cCmd, JArray i_jaData, tb_sys_session i_sSessionUser, out object o_oReault,
  178. [System.Runtime.CompilerServices.CallerLineNumber] int i_nCodeLine = 0,
  179. [System.Runtime.CompilerServices.CallerMemberName] string i_sMemberName = "",
  180. [System.Runtime.CompilerServices.CallerFilePath] string i_sSourcePath = "")
  181. {
  182. string sMsg = null;
  183. object oResultData = null;
  184. try
  185. {
  186. do
  187. {
  188. //QueryDataSet qds = i_aiArsenal.RunQueryDataSet(i_cCmd);
  189. ArsenalInterface ai = ArsenalDBMgr.GetInst(i_cCmd);
  190. List<ReportData> lRes = ai.RunQueryList<ReportData>(i_cCmd);
  191. if (!i_cCmd.IsSuccess)
  192. {
  193. sMsg = i_cCmd.LastErrorCode;
  194. break;
  195. }
  196. //找出detail中的成本
  197. var cost_result = lRes.GroupBy(x => new
  198. {
  199. x.prd_uid,
  200. x.payee,
  201. x.group_uid,
  202. x.branch_uid,
  203. x.purchase_uid,
  204. x.amount,
  205. x.cost_price,
  206. x.qty,
  207. })
  208. .Select(x => new ReportData
  209. {
  210. payee = x.Key.payee,
  211. group_uid = x.Key.group_uid,
  212. branch_uid = x.Key.branch_uid,
  213. prd_uid = x.Key.prd_uid,
  214. amount = x.Key.amount,
  215. purchase_uid = x.Key.purchase_uid,
  216. cost_price = x.Key.cost_price,
  217. qty = x.Key.qty,
  218. calCost = x.Sum(x => x.cost_price * x.qty),
  219. });
  220. // 透過group by 加總成本
  221. var report = cost_result.GroupBy(x => new
  222. {
  223. x.payee,
  224. x.group_uid,
  225. x.branch_uid,
  226. x.amount,
  227. x.purchase_uid
  228. }).Select(x => new ReportData
  229. {
  230. payee = x.Key.payee,
  231. group_uid = x.Key.group_uid,
  232. branch_uid = x.Key.branch_uid,
  233. amount = x.Key.amount,
  234. calCost = x.Sum(x => x.calCost),
  235. }).GroupBy(x => new //再group by一次依照收款人分出資料
  236. {
  237. x.payee,
  238. x.group_uid,
  239. x.branch_uid,
  240. }).Select(x => new ReportData
  241. {
  242. payee = x.Key.payee,
  243. group_uid = x.Key.group_uid,
  244. branch_uid = x.Key.branch_uid,
  245. amount = x.Sum(c => c.amount),
  246. calCost = x.Sum(x => x.calCost),
  247. });
  248. // 最後用SELECT 算出獲利傳回前端
  249. var data = report.Select(x => new ReportData
  250. {
  251. payee = x.payee,
  252. group_uid = x.group_uid,
  253. branch_uid = x.branch_uid,
  254. amount = x.amount,
  255. profit = x.amount - x.calCost,
  256. uid = Guid.NewGuid().ToString()
  257. }).OrderBy(x => x.group_uid).ThenBy(x => x.branch_uid);
  258. oResultData = data;
  259. }
  260. while (false);
  261. }
  262. catch (Exception ex)
  263. {
  264. LogHelper.DBLog(Util.GetLastExceptionMsg(ex), i_nCodeLine, i_sMemberName, i_sSourcePath);
  265. sMsg = $"{nameof(readCommandGenerator)} unknwon exception. i_crmInput={JsonConvert.SerializeObject(i_crmInput)}. Call from {i_sMemberName} {i_sSourcePath}({i_nCodeLine}).";
  266. #if DEBUG
  267. System.Diagnostics.Debug.WriteLine(sMsg);
  268. #endif
  269. }
  270. o_oReault = oResultData;
  271. return sMsg;
  272. }
  273. private class ReportData
  274. {
  275. public int amount { get; set; }
  276. public string uid { get; set; }
  277. public string branch_uid { get; set; }
  278. public string group_uid { get; set; }
  279. public string prd_uid { get; set; }
  280. public string payee { get; set; }
  281. public string purchase_uid { get; set; }
  282. public int qty { get; set; }
  283. public int calCost { get; set; }
  284. public int cost_price { get; set; }
  285. public int profit { get; set; }
  286. }
  287. }
  288. }