ForecourtTrxManager.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. using Edge.Core.Database;
  2. using Edge.Core.Processor;using Edge.Core.IndustryStandardInterface.Pump;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Wayne.FDCPOSLibrary;
  11. using Edge.Core.Configuration;
  12. namespace SinochemInternetPlusApp
  13. {
  14. /// <summary>
  15. /// Manages pump transactions, inserting the transactions to POS database (table: Xiaofei2).
  16. /// </summary>
  17. public class ForecourtTrxManager
  18. {
  19. #region Logger
  20. static NLog.Logger logger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("SinochemEpsApp");
  21. #endregion
  22. #region Fields
  23. private IEnumerable<NozzleExtraInfo> nozzleProductConfig = Configurator.Default.NozzleExtraInfoConfiguration.Mapping;
  24. /// <summary>
  25. /// fdc pump handler is the entry for manage pumps.
  26. /// </summary>
  27. private IEnumerable<IFdcPumpController> fdcPumpControllers;
  28. /// <summary>
  29. /// PumpIdAsSideA:PumpIdAsSideB:JiHao
  30. /// </summary>
  31. private readonly IEnumerable<Tuple<int, int, int>> pumpSidePairs = null;
  32. /// <summary>
  33. /// pumpId:RealHoseLogicalId:HuiTianSiteLevelHoseId
  34. /// </summary>
  35. public static IEnumerable<Tuple<int, int, int>> nozzleRemappingPairs = null;
  36. /// <summary>
  37. /// rawName:FriendlyName
  38. /// </summary>
  39. private Dictionary<string, string> rawProductNameToPosProductNameMapping = new Dictionary<string, string>();
  40. private string sqlServerConnStr;
  41. /// <summary>
  42. /// mapping between PumpId, nozzleId, site level nozzle...
  43. /// </summary>
  44. private IOrderedEnumerable<DataRow> sortedSiteNozzlesDataRows;
  45. private bool initialized = false;
  46. #endregion
  47. #region Constructor
  48. /// <summary>
  49. ///
  50. /// </summary>
  51. /// <param name="pumpSideMappingStr">PumpIdAsSideA:PumpIdAsSideB:JiHao, like 1:2:1; 3:4:2; 5:6:3; </param>
  52. /// <param name="forceMappingFusionHoseToHuiTianHoseStr">pumpId:RealHoseLogicalId:HuiTianSiteLevelHoseId, like 14:2:16;14:1:17</param>
  53. /// <param name="gradeNameRemapping">rawGradeName:HuiTianPosGradeName, like 93gas:93#;98gas:98#;</param>
  54. public ForecourtTrxManager(IEnumerable<IFdcPumpController> pumpControllers, string pumpSideMappingStr,
  55. string forceMappingFusionHoseToHuiTianHoseStr, string sqlServerConnStr, string rawProductNameToPosProductNameStr)
  56. {
  57. fdcPumpControllers = pumpControllers;
  58. var pumpSideMappingRawString = pumpSideMappingStr.Trim().Replace(" ", "");
  59. if (pumpSideMappingRawString.Substring(pumpSideMappingRawString.Length - 1) == ";")
  60. pumpSideMappingRawString = pumpSideMappingRawString.Substring(0, pumpSideMappingRawString.Length - 1);
  61. pumpSidePairs = pumpSideMappingRawString.Split(';')
  62. .Select(p => new Tuple<int, int, int>(int.Parse(p.Split(':')[0]), int.Parse(p.Split(':')[1]), int.Parse(p.Split(':')[2])));
  63. if (!string.IsNullOrEmpty(forceMappingFusionHoseToHuiTianHoseStr))
  64. {
  65. var nozzleRemappingRawString = forceMappingFusionHoseToHuiTianHoseStr.Trim().Replace(" ", "");
  66. if (nozzleRemappingRawString.Substring(nozzleRemappingRawString.Length - 1) == ";")
  67. nozzleRemappingRawString = nozzleRemappingRawString.Substring(0, nozzleRemappingRawString.Length - 1);
  68. logger.Info("will parse forceMappingFusionHoseToHuiTianHose, raw string in config is: " + nozzleRemappingRawString);
  69. nozzleRemappingPairs = nozzleRemappingRawString.Split(';').Select(p =>
  70. new Tuple<int, int, int>(int.Parse(p.Split(':')[0]), int.Parse(p.Split(':')[1]),
  71. int.Parse(p.Split(':')[2])));
  72. }
  73. this.sqlServerConnStr = sqlServerConnStr;
  74. if (!string.IsNullOrEmpty(rawProductNameToPosProductNameStr))
  75. {
  76. rawProductNameToPosProductNameStr.Split(';')
  77. .Where(w => !string.IsNullOrEmpty(w))
  78. .Select(p => new KeyValuePair<string, string>(p.Split(':')[0], p.Split(':')[1])).ToList()
  79. .ForEach(v => rawProductNameToPosProductNameMapping.Add(v.Key, v.Value));
  80. }
  81. }
  82. #endregion
  83. public void Init()
  84. {
  85. if (initialized)
  86. return;
  87. foreach (var fdcPumpController in fdcPumpControllers)
  88. {
  89. fdcPumpController.OnStateChange += (s, a) =>
  90. {
  91. var pump = s as IFdcPumpController;
  92. try
  93. {
  94. if (a.NewPumpState == LogicalDeviceState.FDC_READY)
  95. {
  96. /* indicate for nozzle if replaced back */
  97. var sizeLevelNozzleIdsOnPump = SiteConfigUtility.Default.GetSiteLevelNozzleIdsByPumpId(pump.PumpId);
  98. if (!sizeLevelNozzleIdsOnPump.Any())
  99. {
  100. logger.Info("Could not found any site level nozzle ids for pump: " + pump.PumpId);
  101. return;
  102. }
  103. using (var posSqlConnection = new SqlConnection(this.sqlServerConnStr))
  104. {
  105. try
  106. {
  107. /* idle would not carry nozzle id, so here reset all nozzles on target pump.*/
  108. var setPumpOnIdleCommand
  109. = new SqlCommand(sizeLevelNozzleIdsOnPump.Select(siteLevelNozzleId =>
  110. {
  111. SqliteDbContext dbContext = new SqliteDbContext();
  112. //var lastTrx = dbContext.PumpTransactionModels.OrderByDescending(f => f.SaleEndTime)
  113. // .FirstOrDefault(f => f.PumpId == pump.PumpId && f.LogicalNozzleId == SiteConfigUtility.Default.GetNozzleLogicalIdBySiteLevelNozzleId(siteLevelNozzleId));
  114. //var totalizer =
  115. // new Tuple<float, float>((float)((lastTrx?.VolumeTotalizer ?? 0) * Math.Pow(10, 2)),
  116. // (float)((lastTrx?.AmountTotalizer ?? 0) * Math.Pow(10, 2)));
  117. //return
  118. // string.Format(
  119. // "Update jy_info set [status] = '{1}', qty=0, amount=0, fzqty='{2}', fzamount={3}" +
  120. // " where jihao = {0}", siteLevelNozzleId, 'F',
  121. // totalizer.Item1, totalizer.Item2);
  122. return
  123. string.Format(
  124. "Update jy_info set [status] = '{1}', qty=0, amount=0" +
  125. " where jihao = {0}", siteLevelNozzleId, 'F');
  126. }).Aggregate((acc, n) => acc + " " + n), posSqlConnection);
  127. logger.Debug("setPumpOnIdleCommand(via Fdc): " + setPumpOnIdleCommand.CommandText);
  128. posSqlConnection.Open();
  129. setPumpOnIdleCommand.ExecuteNonQuery();
  130. }
  131. catch (Exception ex)
  132. {
  133. logger.Error("executing setPumpOnIdleCommand(via Fdc) failed, exception detail: " + ex);
  134. }
  135. }
  136. }
  137. else if (a.NewPumpState == LogicalDeviceState.FDC_CALLING)
  138. {
  139. using (var posSqlConnection = new SqlConnection(this.sqlServerConnStr))
  140. {
  141. try
  142. {
  143. var operatingNozzleLogicalId = a?.StateChangedNozzles?.FirstOrDefault()?.LogicalId ?? (byte)0;
  144. var rawProductNo = nozzleProductConfig.First(f => f.PumpId == pump.PumpId
  145. && f.NozzleLogicalId == operatingNozzleLogicalId).ProductBarcode;
  146. var gradeFriendlyName = rawProductNameToPosProductNameMapping[rawProductNo.ToString()];
  147. //var updatePumpOnFuelingCommand =
  148. // new SqlCommand(string.Format("Update jy_info set [status] = '{1}', youpin = N'{2}', qty= {3}, amount= {4} where jihao = '{0}'"
  149. // , SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(pump.PumpId, a?.Transaction?.Nozzle?.LogicalId ?? 0),
  150. // 'B',
  151. // gradeFriendlyName,
  152. // a.Transaction.Volumn,
  153. // a.Transaction.Amount),
  154. // posSqlConnection);
  155. var updatePumpOnFuelingCommand =
  156. new SqlCommand(string.Format("Update jy_info set [status] = '{1}' where jihao = '{0}'"
  157. , SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(pump.PumpId, operatingNozzleLogicalId),
  158. 'B',
  159. gradeFriendlyName),
  160. posSqlConnection);
  161. logger.Debug("updatePumpOnFuelingCommand: " + updatePumpOnFuelingCommand.CommandText);
  162. posSqlConnection.Open();
  163. updatePumpOnFuelingCommand.ExecuteNonQuery();
  164. }
  165. catch (Exception ex)
  166. {
  167. logger.Error("executing updatePumpOnFuelingCommand failed, exception detail: " + ex);
  168. }
  169. }
  170. }
  171. }
  172. catch (Exception exx)
  173. { }
  174. };
  175. fdcPumpController.OnCurrentFuellingStatusChange += async (s, a) =>
  176. {
  177. try
  178. {
  179. var pump = s as IFdcPumpController;
  180. if (!a.Transaction.Finished)
  181. {
  182. logger.Info("Start to query accumulator");
  183. var acc = await pump.QueryTotalizerAsync(a.Transaction.Nozzle.LogicalId);
  184. logger.Info($"Amount accumulator: {acc.Item1}, Volume accumulator: {acc.Item2}");
  185. using (var posSqlConnection = new SqlConnection(this.sqlServerConnStr))
  186. {
  187. try
  188. {
  189. var rawProductNo = nozzleProductConfig.First(f => f.PumpId == pump.PumpId && f.NozzleLogicalId == a.Transaction.Nozzle.LogicalId).ProductBarcode;
  190. var gradeFriendlyName = rawProductNameToPosProductNameMapping[rawProductNo.ToString()];
  191. //var updatePumpOnFuelingCommand =
  192. // new SqlCommand(string.Format("Update jy_info set [status] = '{1}', youpin = N'{2}', qty= {3}, amount= {4} where jihao = '{0}'"
  193. // , SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(pump.PumpId, a?.Transaction?.Nozzle?.LogicalId ?? 0),
  194. // 'B',
  195. // gradeFriendlyName,
  196. // a.Transaction.Volumn,
  197. // a.Transaction.Amount),
  198. // posSqlConnection);
  199. var updatePumpOnFuelingCommand =
  200. new SqlCommand(string.Format("Update jy_info set youpin = N'{2}', qty= {3}, amount= {4}, fzqty= {5}, fzamount= {6} where jihao = '{0}'"
  201. , SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(pump.PumpId, a?.Transaction?.Nozzle?.LogicalId ?? 0),
  202. "",
  203. gradeFriendlyName,
  204. a.Transaction.Volumn / Math.Pow(10, pump.VolumeDecimalDigits),
  205. a.Transaction.Amount / Math.Pow(10, pump.AmountDecimalDigits),
  206. acc.Item2 / Math.Pow(10, pump.VolumeDecimalDigits),
  207. acc.Item1 / Math.Pow(10, pump.AmountDecimalDigits)),
  208. posSqlConnection);
  209. logger.Debug("updatePumpOnFuelingCommand: " + updatePumpOnFuelingCommand.CommandText);
  210. posSqlConnection.Open();
  211. updatePumpOnFuelingCommand.ExecuteNonQuery();
  212. }
  213. catch (Exception ex)
  214. {
  215. logger.Error("executing updatePumpOnFuelingCommand failed, exception detail: " + ex);
  216. }
  217. }
  218. }
  219. else
  220. {
  221. logger.Info("Fueling trx finished, start to query accumulator");
  222. var acc = await pump.QueryTotalizerAsync(a.Transaction.Nozzle.LogicalId);
  223. logger.Info($"Amount accumulator: {acc.Item1}, Volume accumulator: {acc.Item2}");
  224. var posSqlConnection = new SqlConnection(this.sqlServerConnStr);
  225. using (posSqlConnection)
  226. {
  227. try
  228. {
  229. var rawProductNo = nozzleProductConfig.First(f => f.PumpId == pump.PumpId && f.NozzleLogicalId == a.Transaction.Nozzle.LogicalId).ProductBarcode;
  230. var gradeFriendlyName = rawProductNameToPosProductNameMapping[rawProductNo.ToString()];
  231. //var totalizer = SiteConfigUtility.Default.GetTotalizer(e.Fuelling.Pump.Id, e.Fuelling.Nozzle.Id);
  232. var updateFuelingTrxDoneCommand =
  233. new SqlCommand(
  234. string.Format(
  235. "insert xiaofei2 (jihao, youpin, qty, danjia, amount, xf_date, xf_time, liushuino, fzqty, fzamount)" +
  236. " values({0}, N'{1}', {2}, {3}, {4}, '{5}', '{6}', {7}, {8}, {9})",
  237. SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(pump.PumpId, a.Transaction.Nozzle.LogicalId),
  238. gradeFriendlyName,
  239. a.Transaction.Volumn / Math.Pow(10, pump.VolumeDecimalDigits),
  240. a.Transaction.Price / Math.Pow(10, pump.PriceDecimalDigits),
  241. a.Transaction.Amount / Math.Pow(10, pump.AmountDecimalDigits),
  242. DateTime.Now.Date.ToString("yyyy-MM-dd"),
  243. DateTime.Now.ToString("HH:mm:ss"),
  244. a.Transaction.SequenceNumberGeneratedOnPhysicalPump,
  245. acc.Item2 / Math.Pow(10, pump.VolumeDecimalDigits),
  246. acc.Item1 / Math.Pow(10, pump.AmountDecimalDigits)),
  247. posSqlConnection);
  248. logger.Info("updateFuelingTrxDoneCommand: " + updateFuelingTrxDoneCommand.CommandText);
  249. logger.Info($"Inserted a finished fueling transaction into xiaofei2");
  250. posSqlConnection.Open();
  251. updateFuelingTrxDoneCommand.ExecuteNonQuery();
  252. }
  253. catch (Exception ex)
  254. {
  255. logger.Error("executing updateFuelingTrxDoneCommand failed, exception detail: " + ex);
  256. }
  257. }
  258. using (var sqlConnection = new SqlConnection(this.sqlServerConnStr))
  259. {
  260. try
  261. {
  262. //var rawProductNo = nozzleProductConfig.First(f => f.PumpId == pump.PumpId
  263. // && f.NozzleLogicalId == operatingNozzleLogicalId).ProductBarcode;
  264. //var gradeFriendlyName = rawProductNameToPosProductNameMapping[rawProductNo.ToString()];
  265. //var updatePumpOnFuelingCommand =
  266. // new SqlCommand(string.Format("Update jy_info set [status] = '{1}', youpin = N'{2}', qty= {3}, amount= {4} where jihao = '{0}'"
  267. // , SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(pump.PumpId, a?.Transaction?.Nozzle?.LogicalId ?? 0),
  268. // 'B',
  269. // gradeFriendlyName,
  270. // a.Transaction.Volumn,
  271. // a.Transaction.Amount),
  272. // posSqlConnection);
  273. var updatePumpOnFuelingCommand =
  274. new SqlCommand(string.Format("Update jy_info set fzqty = '{1}', fzamount={2} where jihao = '{0}'"
  275. ,
  276. SiteConfigUtility.Default.GetSiteLevelNozzleIdByLogicalNozzleId(
  277. pump.PumpId, a.Transaction.Nozzle.LogicalId),
  278. acc.Item2 / Math.Pow(10, pump.VolumeDecimalDigits),
  279. acc.Item1 / Math.Pow(10, pump.AmountDecimalDigits)),
  280. sqlConnection);
  281. logger.Debug("updatePumpOnFuelingCommand: " + updatePumpOnFuelingCommand.CommandText);
  282. sqlConnection.Open();
  283. updatePumpOnFuelingCommand.ExecuteNonQuery();
  284. }
  285. catch (Exception ex)
  286. {
  287. logger.Error("executing updatePumpOnFuelingCommand failed, exception detail: " + ex);
  288. }
  289. }
  290. }
  291. }
  292. catch (Exception exxx)
  293. { }
  294. };
  295. }
  296. #region table [jyjpz]
  297. try
  298. {
  299. var siteNozzlesDataTableInFcDb = new DataTable();
  300. siteNozzlesDataTableInFcDb.Columns.Add("pumpid");
  301. siteNozzlesDataTableInFcDb.Columns.Add("HoseLogicalId");
  302. siteNozzlesDataTableInFcDb.Columns.Add("productNo");
  303. foreach (var fdcPumpController in this.fdcPumpControllers)
  304. {
  305. foreach (var nozzle in fdcPumpController.Nozzles)
  306. {
  307. var bindProduct = nozzleProductConfig.FirstOrDefault(n =>
  308. n.PumpId == fdcPumpController.PumpId
  309. && n.NozzleLogicalId == nozzle.LogicalId);
  310. var fuelPrice = nozzle.RealPriceOnPhysicalPump == null ? 0 :
  311. (nozzle.RealPriceOnPhysicalPump.Value / Math.Pow(10, fdcPumpController.PriceDecimalDigits));
  312. var newRow = siteNozzlesDataTableInFcDb.NewRow();//.Rows.Add( new DataRow)
  313. newRow["pumpid"] = fdcPumpController.PumpId;
  314. newRow["HoseLogicalId"] = nozzle.LogicalId;
  315. newRow["productNo"] = bindProduct.ProductBarcode;
  316. siteNozzlesDataTableInFcDb.Rows.Add(newRow);
  317. }
  318. }
  319. // SinoChem defined a id of: 'jiHao' which stands for a physical pump(2 sides).
  320. siteNozzlesDataTableInFcDb.Columns.Add(new DataColumn("jiHao"));
  321. // SinoChem need another id of site overall id for a nozzle, start from 1.
  322. // we cacualte this based on jiHao and HostLogicalId
  323. siteNozzlesDataTableInFcDb.Columns.Add(new DataColumn("siteLevelNozzleId"));
  324. // as doc defined, side A is 0, side B is 1.
  325. siteNozzlesDataTableInFcDb.Columns.Add(new DataColumn("sideId"));
  326. var siteNozzlesDataRowsInFcDb = siteNozzlesDataTableInFcDb.Rows.Cast<DataRow>();
  327. foreach (var row in siteNozzlesDataRowsInFcDb)
  328. {
  329. var pumpId = int.Parse(row["pumpid"].ToString());
  330. var possibleSideA = this.pumpSidePairs.FirstOrDefault(p => p.Item1 == pumpId);
  331. Tuple<int, int, int> possibleSideB = null;
  332. if (possibleSideA != null)
  333. {
  334. row["sideId"] = "0";
  335. row["jiHao"] = possibleSideA.Item3;
  336. }
  337. else if ((possibleSideB = this.pumpSidePairs.FirstOrDefault(p => p.Item2 == pumpId)) != null)
  338. {
  339. row["sideId"] = "1";
  340. row["jiHao"] = possibleSideB.Item3;
  341. }
  342. else
  343. {
  344. throw new ArgumentException("Pump with pumpId: " + pumpId +
  345. " is neither side A nor side B, pls check Side definition config file.");
  346. }
  347. }
  348. this.sortedSiteNozzlesDataRows =
  349. siteNozzlesDataRowsInFcDb.OrderBy(r => int.Parse(r["jiHao"].ToString()))
  350. .ThenBy(r => r["sideId"])
  351. .ThenBy(r => r["HoseLogicalId"]);
  352. SiteConfigUtility.Default.UpdateLatestSiteConfig(this.sortedSiteNozzlesDataRows);
  353. logger.Debug("sortedSiteNozzlesDataRows: \r\n");
  354. // finally we get the ordered sequence, now give them sitelevel nozzle id.
  355. for (var i = 0; i < sortedSiteNozzlesDataRows.Count(); i++)
  356. {
  357. var oneRow = sortedSiteNozzlesDataRows.ElementAt(i);
  358. oneRow["siteLevelNozzleId"] = i + 1;
  359. logger.Debug(" JiHao: " + oneRow["jiHao"] + ", sideId: " + oneRow["sideId"] +
  360. ", nozzleLogicalId: " + oneRow["HoseLogicalId"] +
  361. ", siteLevelNozzleId: " + oneRow["siteLevelNozzleId"]
  362. + ", pumpId: " + oneRow["pumpid"]
  363. + ", productNo: " + oneRow["productNo"]
  364. //+ ", hoseName: " + oneRow["hosename"]
  365. );
  366. if (nozzleRemappingPairs != null)
  367. {
  368. var pumpId = int.Parse(oneRow["pumpid"].ToString());
  369. var fusionHoseLogicalId = int.Parse(oneRow["HoseLogicalId"].ToString());
  370. var matched = nozzleRemappingPairs.FirstOrDefault(m => m.Item1 == pumpId && m.Item2 == fusionHoseLogicalId);
  371. if (matched != null)
  372. {
  373. logger.Debug("Found nozzleRemappingPairs for pumpId: " + pumpId + " with HoseLogicalId: " + fusionHoseLogicalId + ", " +
  374. "will remapping the bound siteLevelNozzleId from: " + oneRow["siteLevelNozzleId"] + " to: " + matched.Item3);
  375. oneRow["siteLevelNozzleId"] = matched.Item3;
  376. }
  377. }
  378. }
  379. // for now, always overwrite the whole table in POS database without further check for rows or columns level.
  380. using (var posConn = new SqlConnection(this.sqlServerConnStr))
  381. {
  382. /* configInFcDb structure like below */
  383. //" JiHao: " + oneRow["jiHao"] + ", sideId: " + oneRow["sideId"] +
  384. //", nozzleLogicalId: " + oneRow["HoseLogicalId"] +
  385. //", siteLevelNozzleId: " + oneRow["siteLevelNozzleId"]
  386. string bulkInsertCmd = sortedSiteNozzlesDataRows.Select(
  387. r => string.Format("Select {0}, '{1}', {2}, {3}",
  388. r["jiHao"],
  389. r["sideId"],
  390. r["HoseLogicalId"],
  391. r["siteLevelNozzleId"])).Aggregate((acc, n) => acc + " Union all " + n);
  392. var truncateAndInsertCmd =
  393. new SqlCommand(
  394. "TRUNCATE table jyjpz; INSERT jyjpz (jihao, abtype, qianghao, luojiqh) " + bulkInsertCmd,
  395. posConn);
  396. logger.Info("truncateAndInsertSiteConfigCmd: " + truncateAndInsertCmd.CommandText);
  397. posConn.Open();
  398. truncateAndInsertCmd.ExecuteNonQuery();
  399. //return true;
  400. }
  401. }
  402. catch (Exception ex)
  403. {
  404. logger.Error("PerformCompareAndUpdate exceptioned, detail: " + ex);
  405. }
  406. #endregion
  407. #region table jy_info
  408. foreach (var nozzle in sortedSiteNozzlesDataRows)//.Select(n => n["siteLevelNozzleId"]))
  409. {
  410. var siteLevelNozzleId = nozzle["siteLevelNozzleId"];
  411. var pumpId = int.Parse(nozzle["pumpid"].ToString());
  412. var pump = this.fdcPumpControllers.First(f => f.PumpId == pumpId);
  413. var nozzleLogicalId = int.Parse(nozzle["HoseLogicalId"].ToString());
  414. var productNo = nozzle["productNo"].ToString();
  415. using (
  416. var posSqlConnection = new SqlConnection(this.sqlServerConnStr))
  417. {
  418. try
  419. {
  420. var gradeFriendlyName = rawProductNameToPosProductNameMapping[productNo];// Translator.GetFriendlyGradeName(SiteConfigUtility.Default.GetGradeName(siteLevelNozzleId));
  421. SqliteDbContext dbContext = new SqliteDbContext();
  422. var lastTrx = dbContext.PumpTransactionModels.OrderByDescending(f => f.SaleEndTime)
  423. .FirstOrDefault(f => f.PumpId == pumpId && f.LogicalNozzleId == nozzleLogicalId);
  424. var totalizer =
  425. new Tuple<float, float>((float)((lastTrx?.VolumeTotalizer / Math.Pow(10, pump.VolumeDecimalDigits) ?? 0)),
  426. (float)((lastTrx?.AmountTotalizer / Math.Pow(10, pump.AmountDecimalDigits) ?? 0) * Math.Pow(10, 2)));
  427. var setPumpOnStartingCommand =
  428. new SqlCommand(string.Format("if not exists(select * from jy_info where jihao={0})" +
  429. " BEGIN" +
  430. " insert jy_info (jihao, [status], youpin, qty, amount, fzqty, fzamount) values({0}, '{1}', N'{2}', 0, 0, '{3}', {4})" +
  431. " END", siteLevelNozzleId, 'F', gradeFriendlyName,
  432. totalizer.Item1, totalizer.Item2), posSqlConnection);
  433. logger.Debug("initTable_jy_info_Command: " + setPumpOnStartingCommand.CommandText);
  434. posSqlConnection.Open();
  435. setPumpOnStartingCommand.ExecuteNonQuery();
  436. }
  437. catch (Exception ex)
  438. {
  439. logger.Error("executing initTable_jy_info_Command failed for siteLevelNozzleId: " + siteLevelNozzleId + ", exception detail: " + ex);
  440. throw;
  441. }
  442. }
  443. }
  444. #endregion
  445. initialized = true;
  446. }
  447. private void PrepareInsertTransToXiaofei2()
  448. {
  449. }
  450. private Tuple<int, int> GetAccumulator(IFdcPumpController pumpController, byte logicalNozzleId)
  451. {
  452. return pumpController.QueryTotalizerAsync(logicalNozzleId).Result;
  453. }
  454. public Dictionary<int, string> GetNozzleFuelMapping()
  455. {
  456. var dict = new Dictionary<int, string>();
  457. foreach (var pump in fdcPumpControllers)
  458. {
  459. foreach (var nozzle in pump.Nozzles)
  460. {
  461. var currentNozzleProductBinding =
  462. nozzleProductConfig.FirstOrDefault(f => f.PumpId == pump.PumpId && f.NozzleLogicalId == nozzle.LogicalId);
  463. if (currentNozzleProductBinding != null)
  464. {
  465. var rawProductNo = currentNozzleProductBinding.ProductBarcode;
  466. var gradeFriendlyName = rawProductNameToPosProductNameMapping[rawProductNo.ToString()];
  467. if (!dict.ContainsKey(currentNozzleProductBinding.SiteLevelNozzleId ?? 0))
  468. {
  469. dict.Add(currentNozzleProductBinding.SiteLevelNozzleId ?? 0, gradeFriendlyName);
  470. }
  471. }
  472. }
  473. }
  474. return dict;
  475. }
  476. }
  477. }