SpsManager.cs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. using System;
  2. using System.Text;
  3. using System.Collections.Generic;
  4. using Dfs.WayneChina.SpsDbManager.Models;
  5. using Dfs.WayneChina.SpsDbManager.ResultSet;
  6. using System.Linq;
  7. using MySql.Data.MySqlClient;
  8. using Microsoft.EntityFrameworkCore;
  9. namespace Dfs.WayneChina.SpsDbManager
  10. {
  11. /// <summary>
  12. /// Manages the database interactions, mostly through stored procedures.
  13. /// </summary>
  14. public class SpsManager
  15. {
  16. #region Fields
  17. private System.Timers.Timer versionCheckTimer;
  18. private IList<DataVersion> currentVersion = null;
  19. private object syncObj = new object();
  20. private string connectionString =
  21. "server=localhost;database=sps_db;uid=root;password=HS1205;treattinyasboolean=false;convert zero datetime=true;";
  22. #endregion
  23. #region Constructor
  24. public SpsManager(string connectionString)
  25. {
  26. this.connectionString = connectionString;
  27. }
  28. #endregion
  29. #region Internal version info check
  30. public void Start()
  31. {
  32. //StartVersionCheckTimer();
  33. }
  34. private void StartVersionCheckTimer()
  35. {
  36. versionCheckTimer = new System.Timers.Timer();
  37. versionCheckTimer.Interval = 5000;
  38. versionCheckTimer.Elapsed += VersionCheckTimerElapsed;
  39. versionCheckTimer.Enabled = true;
  40. }
  41. private void VersionCheckTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
  42. {
  43. GetDataVersionInternal();
  44. }
  45. #endregion
  46. #region InitialData
  47. public InitialData GetInitialData(int posId)
  48. {
  49. IList<InitialData> results = new List<InitialData>();
  50. using (var context = new SpsDbContext(connectionString))
  51. {
  52. results = context.LoadStoredProc(SpsDbRoutines.InitialData)
  53. .WithSqlParam("Pos_Id", posId)
  54. .ExecuteStoredProc<InitialData>();
  55. }
  56. return results.FirstOrDefault();
  57. }
  58. #endregion
  59. #region Register
  60. public IList<RegisterTerminalResult> RegisterTerminal(string terminalId)
  61. {
  62. IList<RegisterReqResult> results = new List<RegisterReqResult>();
  63. using (var context = new SpsDbContext(connectionString))
  64. {
  65. results = context.LoadStoredProc(SpsDbRoutines.RegisterTerminal)
  66. .WithSqlParam("PayTermId", terminalId)
  67. .ExecuteStoredProc<RegisterReqResult>();
  68. }
  69. IList<RegisterTerminalResult> registerResult = new List<RegisterTerminalResult>();
  70. foreach (var r in results)
  71. {
  72. registerResult.Add(new RegisterTerminalResult
  73. {
  74. SystemKey = r.Keyword,
  75. StationNameLength = r.StationLength,
  76. StationName = r.SName,
  77. RegisterResultCode = r.RegistState
  78. });
  79. }
  80. return registerResult;
  81. }
  82. #endregion
  83. #region Version info
  84. private IList<DataVersion> GetDataVersionInternal()
  85. {
  86. IList<VersionInfo> versionInfos = new List<VersionInfo>();
  87. using (var context = new SpsDbContext(connectionString))
  88. {
  89. versionInfos = context.LoadStoredProc(SpsDbRoutines.VersionInfo)
  90. .WithSqlParam("", "")
  91. .ExecuteStoredProc<VersionInfo>();
  92. }
  93. if (versionInfos == null || versionInfos != null && versionInfos.Count == 0)
  94. {
  95. return null;
  96. }
  97. IList<DataVersion> dataVersions = new List<DataVersion>();
  98. foreach (var item in versionInfos)
  99. {
  100. dataVersions.Add(new DataVersion
  101. {
  102. VersionType = (VersionType)item.VersionId,
  103. VersionNo = item.VerNo,
  104. Effectivetime = item.GetEffectiveTime(),
  105. ExpiredTime = item.GetExpiredTime(),
  106. Remark = item.Remark
  107. });
  108. }
  109. //lock (syncObj)
  110. //{
  111. // currentVersion = dataVersions;
  112. //}
  113. //Console.WriteLine($"Retrieving version info from database at: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
  114. return dataVersions;
  115. }
  116. public IList<DataVersion> GetDataVersions()
  117. {
  118. lock (syncObj)
  119. {
  120. if (currentVersion != null)
  121. {
  122. return currentVersion;
  123. }
  124. }
  125. return GetDataVersionInternal();
  126. }
  127. private int UpdateVersionInfo(int versionId, int versionNo, string time)
  128. {
  129. using (var context = new SpsDbContext(connectionString))
  130. {
  131. var result = context.LoadStoredProc(SpsDbRoutines.UpdateVersionInfo)
  132. .WithSqlParam("Version_Id", versionId)
  133. .WithSqlParam("Version_No", versionNo)
  134. .WithSqlParam("Effect_Time", time)
  135. .ExecuteStoredProc<int>();
  136. return result.FirstOrDefault();
  137. }
  138. }
  139. public int UpdateGeneralInfoVersion()
  140. {
  141. return UpdateVersionInfo(1, 0, DateTime.Now.ToString("yyyyMMddHHmmss"));
  142. }
  143. #endregion
  144. #region Update Fuel Price
  145. public bool UpdateFuelPrice(string fuelProductNo, int price)
  146. {
  147. using (var context = new SpsDbContext(connectionString))
  148. {
  149. var fuel = context.TFuellist.FirstOrDefault(f => f.FuelNo == fuelProductNo);
  150. if (fuel != null)
  151. {
  152. var currentPrice = fuel.Price;
  153. fuel.OldPrice = currentPrice;
  154. fuel.Price = price;
  155. context.TFuellist.Update(fuel);
  156. int result = context.SaveChanges();
  157. if (result == 1)
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. #endregion
  164. #region Update fuel price version
  165. public int UpdateFuelPriceVersion()
  166. {
  167. return UpdateVersionInfo(2, 0, DateTime.Now.ToString("yyyyMMddHHmmss"));
  168. }
  169. #endregion
  170. #region Validate card
  171. public IList<CardResult> GetCheckCardResult(string logicalCardNo, long physicalCardNo, int pumpId)
  172. {
  173. IList<CheckCardResult> checkCardResults = new List<CheckCardResult>();
  174. using (var context = new SpsDbContext(connectionString))
  175. {
  176. checkCardResults = context.LoadStoredProc(SpsDbRoutines.CheckCard)
  177. .WithSqlParam("ASN", logicalCardNo)
  178. .WithSqlParam("PhysCardNo", physicalCardNo)
  179. .WithSqlParam("Pump_No", pumpId)
  180. .ExecuteStoredProc<CheckCardResult>();
  181. }
  182. IList<CardResult> cardResults = new List<CardResult>();
  183. if (checkCardResults != null)
  184. {
  185. foreach (var item in checkCardResults)
  186. {
  187. cardResults.Add(new CardResult
  188. {
  189. ReturnValue = item.ReturnVar,
  190. CardStatus = (CardState)item.CStatus,
  191. MaxAllowedAmount = item.Max_Mon,
  192. MaxAmountPerTrx = item.OnceMaxPay < 0 ? 0 : Convert.ToUInt32(item.OnceMaxPay),
  193. DiscountNo = Convert.ToUInt32(item.DiscountNo),
  194. TrxRestrictionIndicator = Convert.ToInt32(item.BalPay_Day),
  195. CardStateDescLen = item.CStateLen,
  196. CardStateDescription = item.CState
  197. });
  198. }
  199. }
  200. return cardResults;
  201. }
  202. public bool IsCardBlackListed(string cardNo)
  203. {
  204. IList<bool> results = new List<bool>();
  205. using (var context = new SpsDbContext(connectionString))
  206. {
  207. results = context.LoadStoredProc(SpsDbRoutines.CheckIfCardIsBlacklisted)
  208. .WithSqlParam("Card_No", cardNo.TrimStart('0'))
  209. .ExecuteStoredProc<bool>();
  210. }
  211. if (results.Count > 0)
  212. {
  213. return results[0];
  214. }
  215. return true;
  216. }
  217. #endregion
  218. #region Get amount after discount
  219. public DiscountedAmountResult GetDiscountedAmount(string cardNo, int amount, int volume, int unitPrice, int fuelProductCode)
  220. {
  221. IList<DiscountedAmountResult> results = new List<DiscountedAmountResult>();
  222. using (var context = new SpsDbContext(connectionString))
  223. {
  224. results = context.LoadStoredProc(SpsDbRoutines.CalculateDiscountedAmount)
  225. .WithSqlParam("ASN", cardNo.TrimStart('0')) //"10010873"
  226. .WithSqlParam("Mon", amount) //10139
  227. .WithSqlParam("TrdVol", volume) //1305
  228. .WithSqlParam("Price", unitPrice) //777
  229. .WithSqlParam("Fuel_No", fuelProductCode) //"1030"
  230. .ExecuteStoredProc<DiscountedAmountResult>();
  231. }
  232. return results.FirstOrDefault();
  233. }
  234. #endregion
  235. #region Account check and Insert auth info
  236. /// <summary>
  237. /// Gets the account info by card number.
  238. /// </summary>
  239. /// <param name="cardNo">The card number.</param>
  240. /// <returns></returns>
  241. public CardAccountInfoResult GetCardAccountInfo(string cardNo)
  242. {
  243. IList<CardAccountInfoResult> results = new List<CardAccountInfoResult>();
  244. using (var context = new SpsDbContext(connectionString))
  245. {
  246. results = context.LoadStoredProc(SpsDbRoutines.GetCardAccountInfo)
  247. .WithSqlParam("Card_No", cardNo)
  248. .ExecuteStoredProc<CardAccountInfoResult>();
  249. }
  250. return results?.FirstOrDefault();
  251. }
  252. /// <summary>
  253. /// Get the credits (or loyalty points) for the current card.
  254. /// </summary>
  255. /// <param name="fuelProductCode">The fuel product code, 1030, 1040 etc.</param>
  256. /// <param name="cardNo">The card number.</param>
  257. /// <param name="amount">The fueling amount.</param>
  258. /// <param name="volume">The fueling quantity.</param>
  259. /// <returns>The result which includes the credit amount.</returns>
  260. public CreditResult GetCredits(int fuelProductCode, string cardNo, int amount, int volume)
  261. {
  262. IList<CreditResult> results = new List<CreditResult>();
  263. using (var context = new SpsDbContext(connectionString))
  264. {
  265. results = context.LoadStoredProc(SpsDbRoutines.GetIcCardCredits)
  266. .WithSqlParam("Fuel_No", fuelProductCode) //"1030"
  267. .WithSqlParam("Card_No", cardNo) //"10010873"
  268. .WithSqlParam("Money", amount) //10139
  269. .WithSqlParam("Vol", volume) //1305
  270. .ExecuteStoredProc<CreditResult>();
  271. }
  272. return results.FirstOrDefault();
  273. }
  274. /// <summary>
  275. /// Check if the transaction record already exists in the database table (t_trdinfo).
  276. /// </summary>
  277. /// <param name="fillingStartTime">TTCTime or fueling start time.</param>
  278. /// <param name="ttc">TTC (Transaction counter).</param>
  279. /// <param name="pumpNo">The pump number.</param>
  280. /// <param name="trxType">The transaction type.</param>
  281. /// <returns>Non-existing->returns false; Existing->returns true.</returns>
  282. public bool CheckIfTransactionExists(string fillingStartTime, int ttc, byte pumpNo, byte trxType)
  283. {
  284. IList<CheckTrxResult> results = new List<CheckTrxResult>();
  285. using (var context = new SpsDbContext(connectionString))
  286. {
  287. results = context.LoadStoredProc(SpsDbRoutines.CheckIfCardTrxExists)
  288. .WithSqlParam("Ttc_Time", fillingStartTime)
  289. .WithSqlParam("Pos_Ttc", ttc)
  290. .WithSqlParam("Pump_No", pumpNo)
  291. .WithSqlParam("Trade_Type", trxType)
  292. .ExecuteStoredProc<CheckTrxResult>();
  293. }
  294. return results.First()?.FlagResult > 0;
  295. }
  296. public long AddTrade(int stationNo, string cardNo, string operCardNo, int payModeId, string payModeNo, byte trxType, string fuelProductCode,
  297. int unitPrice, int volume, int amount, int actualAmount, int cardBalance, byte cardType, int ctc, DateTime ttcTime,
  298. DateTime ttcEndTime, int ttc, ushort seqNo, int billNo, byte nozzleNo, byte pumpNo, long payTermId, long volumeTotal,
  299. int discountNo, int operatorId, byte posId, string psamAsn, uint psamTac, string psamTid, uint psamTtc, uint tac, uint gMac,
  300. uint tMac, int credit, int shiftNo, string carId, string lineNo, string carLicenseNo, byte pumpType)
  301. {
  302. using (MySqlConnection conn = new MySqlConnection(connectionString))
  303. {
  304. try
  305. {
  306. string query = "INSERT INTO `sps_db`.`t_trdinfo` " +
  307. "(`SNo`,`CardNo`, `OperCardNo`, `PaymodeID`,`PaymodeNo`, `TrdType`, `CommID`, `PRC`, `VOL`, `MON`, `RealMON`, `CardBal`,`CardType`, " +
  308. "`CTC`, `TTCTime`, `TTCTimeEnd`,`TTC`, `SeqNo`,`BillNo`, `NozNo`, `PumpNo`,`PayTemID`, `EndPumpID`, `DiscountNo`, " +
  309. "`Operator`, `POSID`,`PSAMASN`,`PSAMtac`,`PSAMTID`,`PSAMTTC`,`TAC`,`GMAC`,`TMAC`,`Integral`,`ShiftNo`,`CarID`,`LineNo`," +
  310. "`CarLicsNo`,`PumpType`) " +
  311. "VALUES(@stationno, @asn, @operAsn, @paytype, @paymode_no, @trade_type, @fuelcode, @prc, @vol, @amn, @realamn, @bal, @card_type, " +
  312. "@ctc, @time, @endtime, @posttc, @seqno, @billno, @nozzleno, @pump_no, @terminalid, @totalvol, @discountno, " +
  313. "@userno, @pos_id, @trd_psamasn, @trd_psamtac, @trd_psamtid, @trd_psamttc, @trd_tac, @trd_gmac, @trd_tmac, @trd_integral, " +
  314. "@shift_no, @carID, @lineNo, @carLicsNo, @pumpType); SELECT LAST_INSERT_ID();";
  315. if (conn.State != System.Data.ConnectionState.Open)
  316. {
  317. conn.Open();
  318. }
  319. using (MySqlCommand cmd = new MySqlCommand(query, conn))
  320. {
  321. cmd.Parameters.Add("@stationNo", MySqlDbType.UInt32).Value = stationNo;
  322. cmd.Parameters.Add("@asn", MySqlDbType.VarChar).Value = cardNo;
  323. cmd.Parameters.Add("@operAsn", MySqlDbType.VarChar).Value = operCardNo;
  324. cmd.Parameters.Add("@paytype", MySqlDbType.UInt32).Value = payModeId;
  325. cmd.Parameters.Add("@paymode_no", MySqlDbType.VarChar).Value = payModeNo;
  326. cmd.Parameters.Add("@trade_type", MySqlDbType.UInt32).Value = trxType;
  327. cmd.Parameters.Add("@fuelcode", MySqlDbType.VarChar).Value = fuelProductCode;
  328. cmd.Parameters.Add("@prc", MySqlDbType.UInt32).Value = unitPrice;
  329. cmd.Parameters.Add("@vol", MySqlDbType.UInt32).Value = volume;
  330. cmd.Parameters.Add("@amn", MySqlDbType.UInt32).Value = amount;
  331. cmd.Parameters.Add("@realamn", MySqlDbType.UInt32).Value = actualAmount;
  332. cmd.Parameters.Add("@bal", MySqlDbType.UInt32).Value = cardBalance;
  333. cmd.Parameters.Add("@card_type", MySqlDbType.UByte).Value = cardType;
  334. cmd.Parameters.Add("@ctc", MySqlDbType.UInt32).Value = ctc;
  335. cmd.Parameters.Add("@time", MySqlDbType.DateTime).Value = ttcTime;
  336. cmd.Parameters.Add("@endtime", MySqlDbType.DateTime).Value = ttcEndTime;
  337. cmd.Parameters.Add("@posttc", MySqlDbType.UInt32).Value = ttc;
  338. cmd.Parameters.Add("@seqno", MySqlDbType.UInt32).Value = seqNo;
  339. cmd.Parameters.Add("@billno", MySqlDbType.UInt32).Value = billNo;
  340. cmd.Parameters.Add("@nozzleno", MySqlDbType.UInt32).Value = nozzleNo;
  341. cmd.Parameters.Add("@pump_no", MySqlDbType.UInt32).Value = pumpNo;
  342. cmd.Parameters.Add("@terminalid", MySqlDbType.UInt64).Value = payTermId;
  343. cmd.Parameters.Add("@totalvol", MySqlDbType.UInt64).Value = volumeTotal;
  344. cmd.Parameters.Add("@discountno", MySqlDbType.UInt32).Value = discountNo;
  345. cmd.Parameters.Add("@userno", MySqlDbType.UInt32).Value = operatorId;
  346. cmd.Parameters.Add("@pos_id", MySqlDbType.UInt32).Value = posId;
  347. cmd.Parameters.Add("@trd_psamasn", MySqlDbType.VarChar).Value = psamAsn;
  348. cmd.Parameters.Add("@trd_psamtac", MySqlDbType.UInt32).Value = psamTac;
  349. cmd.Parameters.Add("@trd_psamtid", MySqlDbType.VarChar).Value = psamTid;
  350. cmd.Parameters.Add("@trd_psamttc", MySqlDbType.UInt32).Value = psamTtc;
  351. cmd.Parameters.Add("@trd_tac", MySqlDbType.UInt32).Value = tac;
  352. cmd.Parameters.Add("@trd_gmac", MySqlDbType.UInt32).Value = gMac;
  353. cmd.Parameters.Add("@trd_tmac", MySqlDbType.UInt32).Value = tMac;
  354. cmd.Parameters.Add("@trd_integral", MySqlDbType.UInt32).Value = credit;
  355. cmd.Parameters.Add("@shift_no", MySqlDbType.UInt32).Value = shiftNo;
  356. cmd.Parameters.Add("@carID", MySqlDbType.VarChar).Value = carId;
  357. cmd.Parameters.Add("@lineNo", MySqlDbType.VarChar).Value = lineNo;
  358. cmd.Parameters.Add("@carLicsNo", MySqlDbType.VarChar).Value = carLicenseNo;
  359. cmd.Parameters.Add("@pumpType", MySqlDbType.UInt32).Value = pumpType;
  360. object result = cmd.ExecuteScalar();
  361. return long.Parse(result.ToString()); //(long)result;
  362. }
  363. }
  364. catch (MySqlException ex)
  365. {
  366. Console.WriteLine("Error in adding mysql row. Error: " + ex.Message);
  367. }
  368. catch (Exception ex)
  369. {
  370. Console.WriteLine($"Exception: {ex.ToString()}");
  371. }
  372. finally
  373. {
  374. conn.Close();
  375. }
  376. }
  377. return -1;
  378. }
  379. public int AddTrxInfo(int stationNo, string cardNo, int payModeId, string payModeNo, byte trxType, string fuelProductCode,
  380. int unitPrice, int volume, int amount, int actualAmount, int cardBalance, byte cardType, int ctc, DateTime ttcTime,
  381. DateTime ttcEndTime, int ttc, ushort seqNo, int billNo, byte nozzleNo, byte pumpNo, long payTermId, long volumeTotal,
  382. int discountNo, int operatorId, byte posId, string psamAsn, int psamTac, string psamTid, int psamTtc, int tac, int gMac,
  383. int tMac, int credit, int shiftNo, string carId, string lineNo, string carLicenseNo, byte pumpType)
  384. {
  385. TTrdinfo trdinfo = new TTrdinfo
  386. {
  387. Sno = stationNo,
  388. CardNo = cardNo,
  389. PaymodeId = payModeId,
  390. PaymodeNo = payModeNo,
  391. TrdType = trxType,
  392. CommId = fuelProductCode,
  393. Prc = unitPrice,
  394. Vol = volume,
  395. Mon = amount,
  396. RealMon = actualAmount,
  397. CardBal = cardBalance,
  398. CardType = cardType,
  399. Ctc = ctc,
  400. Ttctime = ttcTime,
  401. TtctimeEnd = ttcEndTime,
  402. Ttc = ttc,
  403. SeqNo = seqNo,
  404. BillNo = billNo,
  405. NozNo = nozzleNo,
  406. PumpNo = pumpNo,
  407. PayTemId = payTermId,
  408. EndPumpId = volumeTotal,
  409. DiscountNo = discountNo,
  410. Operator = Convert.ToString(operatorId),
  411. Posid = posId,
  412. Psamasn = psamAsn,
  413. Psamtac = psamTac,
  414. Psamtid = psamTid,
  415. Psamttc = psamTtc,
  416. Tac = tac,
  417. Gmac = gMac,
  418. Tmac = tMac,
  419. Integral = credit,
  420. ShiftNo = shiftNo,
  421. CarId = carId,
  422. LineNo = lineNo,
  423. CarLicsNo = carLicenseNo,
  424. PumpType = pumpType
  425. };
  426. using (var context = new SpsDbContext(connectionString))
  427. {
  428. try
  429. {
  430. context.TTrdinfo.Add(trdinfo);
  431. int result = context.SaveChanges();
  432. return result;
  433. }
  434. catch (Exception ex)
  435. {
  436. }
  437. }
  438. return -1;
  439. }
  440. /// <summary>
  441. /// Update the card info after transaction is inserted.
  442. /// </summary>
  443. /// <param name="cardNo">The card number.</param>
  444. /// <param name="amount">The amount of the current fueling.</param>
  445. /// <param name="cardBalance">The balance of the current card.</param>
  446. /// <param name="cardType">The card type, customer card, operator card...</param>
  447. /// <param name="credit">The credits of the transaction earned.</param>
  448. /// <param name="cardAppType">Card application type, e.g. contactless card, CPU card...</param>
  449. /// <returns>The rows affected.</returns>
  450. public int UpdateCardInfo(string cardNo, int amount, int cardBalance, byte cardType, int credit, byte cardAppType)
  451. {
  452. using (var context = new SpsDbContext(connectionString))
  453. {
  454. int affectedRowCount = context.LoadStoredProc(SpsDbRoutines.UpdateCardInfo)
  455. .WithSqlParam("ASN", cardNo) //"10010873"
  456. .WithSqlParam("RealAmn", amount) //4444
  457. .WithSqlParam("Bal", cardBalance) //83694645
  458. .WithSqlParam("Card_Type", cardType) //3
  459. .WithSqlParam("Trd_Integral", credit) //0
  460. .WithSqlParam("Card_App", cardAppType) //1
  461. .ExecuteStoredProc();
  462. return affectedRowCount;
  463. }
  464. }
  465. public bool InsertAuthInfo(int posId, int terminalId, string cardNo, int amount, int volume, string fillingStartTime,
  466. string fillingEndTime, int posTtc, ushort seqNo, int accountType, int fuelProductCode, int unitPrice, int ctc,
  467. byte paymentType,byte pumpNo, byte nozzleNo, int cardBalance, int cardType, uint discountNo, byte cardState, int volumeTotal)
  468. {
  469. using (var context = new SpsDbContext(connectionString))
  470. {
  471. int affectedRowCount = context.LoadStoredProc(SpsDbRoutines.InsertAuthInfo)
  472. .WithSqlParam("Pos_Id", posId) //1
  473. .WithSqlParam("Term", terminalId) //0
  474. .WithSqlParam("ASN", cardNo) //"10010873"
  475. .WithSqlParam("MaxMoney", amount) //10139
  476. .WithSqlParam("MaxVol", volume) //1305
  477. .WithSqlParam("DisTime", fillingStartTime) //"20190408095056"
  478. .WithSqlParam("DisEndTime", fillingEndTime) //"20190408095119"
  479. .WithSqlParam("PosTtc", posTtc) //4696
  480. .WithSqlParam("SeqNo", seqNo) //0
  481. .WithSqlParam("AcountType", accountType) //80
  482. .WithSqlParam("FuelCode", fuelProductCode) //1030
  483. .WithSqlParam("FuelPrc", unitPrice) //777
  484. .WithSqlParam("Ctc", ctc) //511
  485. .WithSqlParam("PayType", paymentType) //100
  486. .WithSqlParam("Pump_No", pumpNo) //3
  487. .WithSqlParam("NozzleNo", nozzleNo) //3
  488. .WithSqlParam("Bal", cardBalance) //84043503
  489. .WithSqlParam("CardType", cardType) //3
  490. .WithSqlParam("DiscountNo", discountNo) //0
  491. .WithSqlParam("State", cardState) //1
  492. .WithSqlParam("TotalVol", volumeTotal) //61231111
  493. .ExecuteStoredProc();
  494. if (affectedRowCount == 1)
  495. {
  496. return true;
  497. }
  498. return false;
  499. }
  500. }
  501. #endregion
  502. #region Delete auth info
  503. public DeleteAuthInfoResult DeleteAuthInfo(byte pumpNo, int posTtc, string ttcTime)
  504. {
  505. IList<DeleteAuthInfoResult> results = new List<DeleteAuthInfoResult>();
  506. using (var context = new SpsDbContext(connectionString))
  507. {
  508. results = context.LoadStoredProc(SpsDbRoutines.DeleteAuthInfo)
  509. .WithSqlParam("Pump_No", pumpNo) //3
  510. .WithSqlParam("PosTtc", posTtc) //4696
  511. .WithSqlParam("TtcTimes", ttcTime) //"20190408095056"
  512. .ExecuteStoredProc<DeleteAuthInfoResult>();
  513. }
  514. return results?.FirstOrDefault();
  515. }
  516. #endregion
  517. #region Insert gray info
  518. public bool InsertGrayInfo(string cardNo, int payType, byte trdType, string productCode, ushort price, int volume, int amount,
  519. int payAmount, int cardBalance, ushort ctc, string time, string endTime, uint ttc, ushort seqNo, byte nozzleNo, byte pumpNo,
  520. string terminalId, ulong volumeTotal, ushort discountNo, string psamAsn, uint psamTac, string psamTid, uint psamTtc, uint tac,
  521. uint gmac, uint tmac, byte pumpType)
  522. {
  523. using (var context = new SpsDbContext(connectionString))
  524. {
  525. var affectedRowCount = context.LoadStoredProc(SpsDbRoutines.AddGrayInfo)
  526. .WithSqlParam("asn", cardNo)
  527. .WithSqlParam("payType", payType)
  528. .WithSqlParam("tradeType", trdType)
  529. .WithSqlParam("fuelCode", productCode)
  530. .WithSqlParam("prc", price)
  531. .WithSqlParam("vol", volume)
  532. .WithSqlParam("amn", amount)
  533. .WithSqlParam("realAmn", payAmount)
  534. .WithSqlParam("bal", cardBalance)
  535. .WithSqlParam("grayctc", ctc)
  536. .WithSqlParam("time", time)
  537. .WithSqlParam("endTime", endTime)
  538. .WithSqlParam("posttc", ttc)
  539. .WithSqlParam("SeqNo", seqNo)
  540. .WithSqlParam("NozzleNo", nozzleNo)
  541. .WithSqlParam("PumpNo", pumpNo)
  542. .WithSqlParam("TerminalId", terminalId)
  543. .WithSqlParam("TotalVol", volumeTotal)
  544. .WithSqlParam("DiscountNo", discountNo)
  545. .WithSqlParam("Trd_PSAMASN", psamAsn)
  546. .WithSqlParam(MySqlDbType.UInt32, "Trd_PSAMtac", psamTac)
  547. .WithSqlParam("Trd_PSAMTID", psamTid)
  548. .WithSqlParam(MySqlDbType.UInt32, "Trd_PSAMTTC", psamTtc)
  549. .WithSqlParam(MySqlDbType.UInt32, "Trd_TAC", tac)
  550. .WithSqlParam(MySqlDbType.UInt32, "Trd_GMAC", gmac)
  551. .WithSqlParam(MySqlDbType.UInt32, "Trd_TMAC", tmac)
  552. .WithSqlParam("Pump_Type", pumpType)
  553. .ExecuteStoredProc();
  554. if (affectedRowCount == 1)
  555. return true;
  556. return false;
  557. }
  558. }
  559. #endregion
  560. #region Free gray card
  561. public bool ReleaseGrayCard(string cardNo, uint grayCtc, string ttcTime)
  562. {
  563. using (var context = new SpsDbContext(connectionString))
  564. {
  565. var result = context.LoadStoredProc(SpsDbRoutines.ReleaseGrayCard)
  566. .WithSqlParam("asn", cardNo)
  567. .WithSqlParam("grayCtc", grayCtc)
  568. .WithSqlParam("ttcTimes", ttcTime)
  569. .ExecuteStoredProc();
  570. //0 = No such record or success
  571. return result == 0;
  572. }
  573. }
  574. #endregion
  575. #region Select gray info
  576. public GrayInfoResult SelectGrayInfo(string cardNo, int ctc, string ttcTime)
  577. {
  578. using (var context = new SpsDbContext(connectionString))
  579. {
  580. var result = context.LoadStoredProc(SpsDbRoutines.SelectGrayInfo)
  581. .WithSqlParam("asn", cardNo)
  582. .WithSqlParam("grayCtc", ctc)
  583. .WithSqlParam("ttcTimes", ttcTime)
  584. .ExecuteStoredProc<GrayInfoResult>();
  585. return result?.FirstOrDefault();
  586. }
  587. }
  588. #endregion
  589. #region Get Pump Info
  590. public IList<PumpInfoResult> GetPumpInfo(byte pumpId)
  591. {
  592. IList<PumpInfoResult> pumpInfos = new List<PumpInfoResult>();
  593. using (var context = new SpsDbContext(connectionString))
  594. {
  595. pumpInfos = context.LoadStoredProc(SpsDbRoutines.PumpInfo)
  596. .WithSqlParam("PumpNo", pumpId)
  597. .ExecuteStoredProc<PumpInfoResult>();
  598. return pumpInfos;
  599. }
  600. }
  601. #endregion
  602. #region Fuel price config
  603. public IList<FuelPriceConfigResult> GetFuelPriceConfig()
  604. {
  605. using (var context = new SpsDbContext(connectionString))
  606. {
  607. var result = context.LoadStoredProc(SpsDbRoutines.FuelPriceConfig)
  608. .ExecuteStoredProc<FuelPriceConfigResult>();
  609. return result;
  610. }
  611. }
  612. #endregion
  613. #region Fuel name setup
  614. public Dictionary<string, string> GetFuelNames()
  615. {
  616. Dictionary<string, string> dict = new Dictionary<string, string>();
  617. var fuels = GetFuelPriceConfig();
  618. foreach (var item in fuels)
  619. {
  620. dict.Add(item.FurlNo, item.FuelName);
  621. }
  622. return dict;
  623. }
  624. #endregion
  625. #region Get current fuel prices (cache)
  626. public Dictionary<string, uint> GetCurrentFuelPrices()
  627. {
  628. Dictionary<string, uint> dict = new Dictionary<string, uint>();
  629. var fuels = GetFuelPriceConfig();
  630. foreach (var item in fuels)
  631. {
  632. dict.Add(item.FurlNo, item.Price);
  633. }
  634. return dict;
  635. }
  636. #endregion
  637. #region Fuel price change for pump
  638. public IList<FuelPriceChangeConfigResult> GetFuelPriceChangeConfig(int pumpId)
  639. {
  640. using (var context = new SpsDbContext(connectionString))
  641. {
  642. var result = context.LoadStoredProc(SpsDbRoutines.GetFuelPriceChange)
  643. .WithSqlParam("PumpNodeId", pumpId)
  644. .ExecuteStoredProc<FuelPriceChangeConfigResult>();
  645. return result;
  646. }
  647. }
  648. #endregion
  649. #region Whitelist/(Newly-added, Newly-deleted, Base)Blacklist cards
  650. public IList<ListedCard> GetBaseBlacklistedCards(CardAppType cardAppType)
  651. {
  652. return GetListedCards(1, cardAppType);
  653. }
  654. public IList<ListedCard> GetNewlyAddedBlacklistedCards(CardAppType cardAppType)
  655. {
  656. return GetListedCards(2, cardAppType);
  657. }
  658. public IList<ListedCard> GetNewlyDeletedBlacklistedCards(CardAppType cardAppType)
  659. {
  660. return GetListedCards(3, cardAppType);
  661. }
  662. public IList<ListedCard> GetWhitelistedCards(CardAppType cardAppType)
  663. {
  664. return GetListedCards(4, cardAppType);
  665. }
  666. public IList<ListedCard> GetListedCards(int indexNo, CardAppType cardAppType)
  667. {
  668. using (var context = new SpsDbContext(connectionString))
  669. {
  670. var result = context.LoadStoredProc(SpsDbRoutines.GetListedCards)
  671. .WithSqlParam("IndexNo", indexNo)
  672. .WithSqlParam("Card_App", (int)cardAppType)
  673. .ExecuteStoredProc<ListedCard>();
  674. return result;
  675. }
  676. }
  677. #endregion
  678. #region Pump work mode
  679. public byte GetPumpWorkMode(byte pumpId)
  680. {
  681. using (var context = new SpsDbContext(connectionString))
  682. {
  683. var pump = context.TPumpinfo
  684. .AsNoTracking()
  685. .Where(p => p.LgNode == pumpId)
  686. .Select(f => new PumpMode
  687. {
  688. PumpId = f.LgNode,
  689. WorkMode = Convert.ToUInt16(f.Mode.Value)
  690. })
  691. .FirstOrDefault();
  692. if (pump != null)
  693. return Convert.ToByte(pump.WorkMode);
  694. return Convert.ToByte(-1);
  695. }
  696. }
  697. #endregion
  698. #region Station Info
  699. public TStationInfo GetStationInfo()
  700. {
  701. using var context = new SpsDbContext(connectionString);
  702. return context.TStationInfo.FirstOrDefault();
  703. }
  704. public void UpdateStationInfo(int stationNo, string name)
  705. {
  706. using (var context = new SpsDbContext(connectionString))
  707. {
  708. var currentStationInfo = context.TStationInfo.FirstOrDefault();
  709. try
  710. {
  711. if (currentStationInfo == null)
  712. {
  713. TStationInfo stationInfo = new TStationInfo();
  714. stationInfo.Sno = stationNo;
  715. stationInfo.Sname = name;
  716. context.TStationInfo.Add(stationInfo);
  717. context.SaveChanges();
  718. }
  719. else
  720. {
  721. currentStationInfo.Sno = stationNo;
  722. currentStationInfo.Sname = name;
  723. context.SaveChanges();
  724. }
  725. }
  726. catch (Exception ex)
  727. {
  728. }
  729. }
  730. }
  731. #endregion
  732. #region Database interactions - Forecourt config
  733. // TANK
  734. #region Tank
  735. public bool AddVirtualTank(byte tankId, string productCode)
  736. {
  737. using (var context = new SpsDbContext(connectionString))
  738. {
  739. TTanklist tanklist = new TTanklist();
  740. tanklist.TankId = tankId;
  741. tanklist.FuelNo = productCode;
  742. tanklist.ProbeId = "";
  743. tanklist.ProbeAddr = "";
  744. context.TTanklist.Add(tanklist);
  745. var result = context.SaveChanges();
  746. Console.WriteLine($"parameterized add: {result} rows affected!");
  747. return result == 1 ? true : false;
  748. }
  749. }
  750. public bool UpdateTankInfo(byte tankId, string productCode)
  751. {
  752. using (var context = new SpsDbContext(connectionString))
  753. {
  754. var tank = context.TTanklist.FirstOrDefault(t => t.TankId == tankId);
  755. if (tank != null)
  756. {
  757. tank.FuelNo = productCode;
  758. var result = context.SaveChanges();
  759. Console.WriteLine($"Update tank: {result} rows affected!");
  760. return result == 1 ? true : false;
  761. }
  762. }
  763. return false;
  764. }
  765. #endregion
  766. // FUEL
  767. #region Fuel
  768. public void InitializeFuelConfig(TFuellist[] fuellists)
  769. {
  770. using (var context = new SpsDbContext(connectionString))
  771. {
  772. context.TFuellist.RemoveRange(context.TFuellist);
  773. var result = context.SaveChanges();
  774. Console.WriteLine($"{result} rows removed!");
  775. if (context.TFuellist.Count() == 0)
  776. {
  777. Console.WriteLine("All fuels deleted");
  778. }
  779. AddFuel(context, fuellists);
  780. var results = context.LoadStoredProc(SpsDbRoutines.UpdateVersionInfo)
  781. .WithSqlParam("Version_Id", 2) // 2 means fuel price
  782. .WithSqlParam("Version_No", 0) // With Version No set to '0', it will bump the version number up by 1.
  783. .WithSqlParam("Effect_Time", DateTime.Now.ToString("yyyyMMddHHmmss"))
  784. .ExecuteStoredProc<int>()
  785. .FirstOrDefault();
  786. Console.WriteLine($"Update fuel price version, result code: {results}");
  787. }
  788. }
  789. static void AddFuel(SpsDbContext context, TFuellist[] fuellists)
  790. {
  791. foreach (var fuel in fuellists)
  792. {
  793. if (context.TFuellist.Count(f => f.FuelNo == fuel.FuelNo) == 0)
  794. {
  795. context.TFuellist.Add(fuel);
  796. }
  797. }
  798. var result = context.SaveChanges();
  799. Console.WriteLine($"Adding fuels to TFuellist table, {result} rows affected");
  800. }
  801. #endregion
  802. // PUMP
  803. #region Pumps
  804. public bool AddUpdatePump(int pumpId, int tankNo, int posId, string dispenserNo, int protocolNo, int protocolType,
  805. string ipAddress, int portId, int workMode, int maxUnpaidTrans, int checkOutMode, int nodeId, int subNodeId, int nozzleNo,
  806. int pumpType, uint maxAmount, uint maxVolume)
  807. {
  808. IList<PumpNozzleInfoOperateResult> results = new List<PumpNozzleInfoOperateResult>();
  809. using (var context = new SpsDbContext(connectionString))
  810. {
  811. var currentPump = context.TPumpinfo.FirstOrDefault(p => p.LgNode == pumpId);
  812. // An existing pump
  813. if (currentPump != null)
  814. {
  815. return UpdatePumpInfo(pumpId, tankNo, posId, dispenserNo, protocolNo, protocolType, ipAddress, portId, workMode,
  816. maxUnpaidTrans, checkOutMode, nodeId, subNodeId, nozzleNo, pumpType, maxAmount, maxVolume);
  817. }
  818. // A new pump
  819. results = context.LoadStoredProc(SpsDbRoutines.InsertPumpInfo)
  820. .WithSqlParam("pump_id", pumpId)
  821. .WithSqlParam("dsp_no", dispenserNo)
  822. .WithSqlParam("tank_no", tankNo)
  823. .WithSqlParam("pos_id", posId)
  824. .WithSqlParam("protocol_no", protocolNo)
  825. .WithSqlParam("prot_type", protocolType)
  826. .WithSqlParam("ip_address", ipAddress)
  827. .WithSqlParam("port_id", portId)
  828. .WithSqlParam("work_mode", workMode)
  829. .WithSqlParam("MaxUnpaidTrans", maxUnpaidTrans)
  830. .WithSqlParam("checkOutMode", checkOutMode)
  831. .WithSqlParam("node_id", nodeId)
  832. .WithSqlParam("subNode_id", subNodeId)
  833. .WithSqlParam("nozzle_num", nozzleNo)
  834. .WithSqlParam("pump_type", pumpType)
  835. .WithSqlParam("max_mon", maxAmount)
  836. .WithSqlParam("max_vol", maxVolume)
  837. .ExecuteStoredProc<PumpNozzleInfoOperateResult>();
  838. }
  839. if (results.Count == 1)
  840. {
  841. // 0 = Success, 2 = Pump exists
  842. return results.First().Result == 0 ? true : false;
  843. }
  844. return false;
  845. }
  846. public bool UpdatePumpInfo(int pumpId, int tankNo, int posId, string dispenserNo, int protocolNo, int protocolType,
  847. string ipAddress, int portId, int workMode, int maxUnpaidTrans, int checkOutMode, int nodeId, int subNodeId, int nozzleNo,
  848. int pumpType, uint maxAmount, uint maxVolume)
  849. {
  850. IList<PumpNozzleInfoOperateResult> results = new List<PumpNozzleInfoOperateResult>();
  851. using (var context = new SpsDbContext(connectionString))
  852. {
  853. results = context.LoadStoredProc(SpsDbRoutines.UpdatePumpInfo)
  854. .WithSqlParam("pump_id", pumpId)
  855. .WithSqlParam("tank_no", tankNo)
  856. .WithSqlParam("pos_id", posId)
  857. .WithSqlParam("dsp_no", dispenserNo)
  858. .WithSqlParam("protocol_no", protocolNo)
  859. .WithSqlParam("prot_type", protocolType)
  860. .WithSqlParam("ip_address", ipAddress)
  861. .WithSqlParam("port_id", portId)
  862. .WithSqlParam("work_mode", workMode)
  863. .WithSqlParam("MaxUnpaidTrans", maxUnpaidTrans)
  864. .WithSqlParam("checkOutMode", checkOutMode)
  865. .WithSqlParam("node_id", nodeId)
  866. .WithSqlParam("subNode_id", subNodeId)
  867. .WithSqlParam("nozzle_num", nozzleNo)
  868. .WithSqlParam("pump_type", pumpType)
  869. .WithSqlParam("max_mon", maxAmount)
  870. .WithSqlParam("max_vol", maxVolume)
  871. .ExecuteStoredProc<PumpNozzleInfoOperateResult>();
  872. }
  873. if (results.Count == 1)
  874. {
  875. // 0 = Success, 2 = Pump exists
  876. return results.First().Result == 0 ? true : false;
  877. }
  878. return false;
  879. }
  880. #endregion
  881. // NOZZLE
  882. #region Nozzle
  883. public bool AddUpdateNozzle(int logicalNozzleNo, int physicalId, int tankId, int pumpId, int? useState,
  884. string fuelType, string carIdenAddress)
  885. {
  886. IList<PumpNozzleInfoOperateResult> results = new List<PumpNozzleInfoOperateResult>();
  887. using (var context = new SpsDbContext(connectionString))
  888. {
  889. // An existing nozzle
  890. var currentNozzle = context.TNozzleinfo.FirstOrDefault(n => n.LogicId == logicalNozzleNo);
  891. if (currentNozzle != null)
  892. {
  893. return UpdateNozzleInfo(logicalNozzleNo, physicalId, tankId, pumpId, useState, fuelType, carIdenAddress);
  894. }
  895. // A new nozzle
  896. results = context.LoadStoredProc(SpsDbRoutines.InsertNozzleInfo)
  897. .WithSqlParam("logic_id", logicalNozzleNo)
  898. .WithSqlParam("physical_id", physicalId)
  899. .WithSqlParam("tank_id", tankId)
  900. .WithSqlParam("pump_id", pumpId)
  901. .WithSqlParam("usestate", useState)
  902. .WithSqlParam("oiltype_id", fuelType)
  903. .WithSqlParam("cariden_addr", carIdenAddress)
  904. .ExecuteStoredProc<PumpNozzleInfoOperateResult>();
  905. }
  906. foreach (var item in results)
  907. {
  908. Console.WriteLine($"Result: {item.Result}");
  909. }
  910. if (results.Count == 1)
  911. {
  912. return results.First().Result == 0 ? true : false;
  913. }
  914. return false;
  915. }
  916. public bool UpdateNozzleInfo(int logicalNozzleNo, int physicalId, int tankId, int pumpId, int? useState,
  917. string fuelType, string carIdenAddress)
  918. {
  919. IList<PumpNozzleInfoOperateResult> results = new List<PumpNozzleInfoOperateResult>();
  920. using (var context = new SpsDbContext(connectionString))
  921. {
  922. results = context.LoadStoredProc(SpsDbRoutines.UpdateNozzleInfo)
  923. .WithSqlParam("logic_id", logicalNozzleNo)
  924. .WithSqlParam("physical_id", physicalId)
  925. .WithSqlParam("tank_id", tankId)
  926. .WithSqlParam("pump_id", pumpId)
  927. .WithSqlParam("usestate", useState)
  928. .WithSqlParam("oiltype_id", fuelType)
  929. .WithSqlParam("cariden_addr", carIdenAddress)
  930. .ExecuteStoredProc<PumpNozzleInfoOperateResult>();
  931. }
  932. foreach (var item in results)
  933. {
  934. Console.WriteLine($"Result: {item.Result}");
  935. }
  936. if (results.Count == 1)
  937. {
  938. return results.First().Result == 0 ? true : false;
  939. }
  940. return false;
  941. }
  942. #endregion
  943. // TERMINAL
  944. #region Terminal
  945. public void UpdateTerminals(TPayterm[] payterms)
  946. {
  947. using (var context = new SpsDbContext(connectionString))
  948. {
  949. foreach (var term in payterms)
  950. {
  951. var terminal = context.TPayterm.FirstOrDefault(t => t.PayDevId == term.PayDevId);
  952. if (terminal.PayDevId == term.PayDevId && terminal.PayType == term.PayType && terminal.Protocl == term.Protocl
  953. && terminal.Address == term.Address)
  954. {
  955. continue;
  956. }
  957. if (terminal != null)
  958. {
  959. terminal.PayType = term.PayType;
  960. terminal.Protocl = term.Protocl;
  961. terminal.Address = term.Address;
  962. var result = context.SaveChanges();
  963. Console.WriteLine($"Update terminal, Id: {term.PayDevId}, pay type: {term.PayType}, protocol: {term.Protocl}, " +
  964. $"address: {term.Address}, {result} rows affected");
  965. }
  966. else
  967. {
  968. context.Add(term);
  969. var result = context.SaveChanges();
  970. Console.WriteLine($"Add terminal, Id: {term.PayDevId}, pay type: {term.PayType}, protocol: {term.Protocl}, " +
  971. $"address: {term.Address}, {result} rows affected");
  972. }
  973. }
  974. }
  975. }
  976. #endregion
  977. // Retrieve existing settings
  978. #region Get forecourt configuration (pumps, nozzles, terminals, etc.)
  979. public void GetAllNozzleInfo()
  980. {
  981. IList<NozzleInfoResult> nozzleInfoResults = new List<NozzleInfoResult>();
  982. using (var context = new SpsDbContext(connectionString))
  983. {
  984. nozzleInfoResults = context.LoadStoredProc(SpsDbRoutines.GetAllNozzleInfo)
  985. .WithSqlParam("", "")
  986. .ExecuteStoredProc<NozzleInfoResult>();
  987. }
  988. foreach (var item in nozzleInfoResults)
  989. {
  990. Console.Write($"Logic Id: {item.Logic_Id} ");
  991. Console.Write($"Physical Id: {item.Physical_Id} ");
  992. Console.Write($"Tank Id: {item.Tank_Id} ");
  993. Console.Write($"Pump Id: {item.Pump_Id} ");
  994. Console.Write($"UseState: {item.UseState} ");
  995. Console.Write($"OilType Id: {item.OilType_Id} ");
  996. Console.WriteLine($"Car Iden Addr: {item.CarIdenAddr} ");
  997. }
  998. }
  999. public void GetAllTankInformation()
  1000. {
  1001. IList<TankInfoResult> tankInfoResults = new List<TankInfoResult>();
  1002. using (var context = new SpsDbContext(connectionString))
  1003. {
  1004. tankInfoResults = context.LoadStoredProc(SpsDbRoutines.GetAllTankInfo)
  1005. .WithSqlParam("", "")
  1006. .ExecuteStoredProc<TankInfoResult>();
  1007. }
  1008. foreach (var item in tankInfoResults)
  1009. {
  1010. Console.Write($"Tank No: {item.Tank_No} ");
  1011. Console.Write($"Tank Height: {item.Tank_Height} ");
  1012. Console.Write($"Fuel No: {item.Fuel_No} ");
  1013. Console.Write($"Tank Max Height: {item.Tank_MaxHeight} ");
  1014. Console.Write($"Tank Min Height: {item.Tank_MinHeight} ");
  1015. Console.Write($"Tank Max Vol: {item.Tank_MaxVol} ");
  1016. Console.Write($"Tank Min Vol: {item.Tank_MinVol} ");
  1017. Console.Write($"Tank Max Water Height: {item.Tank_MaxwHeight} ");
  1018. Console.Write($"Tank Max Temp: {item.Tank_MaxTemp} ");
  1019. Console.Write($"Probe ID: {item.ProbeId} ");
  1020. Console.Write($"Offset: {item.Offset} ");
  1021. Console.Write($"Water Offset: {item.WaterOffset} ");
  1022. Console.Write($"Probe Address: {item.ProbeAddr} ");
  1023. Console.WriteLine($"Oil Offset: {item.OilOffset} ");
  1024. }
  1025. }
  1026. public void GetAllPumpNozzleInformation()
  1027. {
  1028. IList<PumpNozzleInfoResult> pumpNozzleInfoResults = new List<PumpNozzleInfoResult>();
  1029. using (var context = new SpsDbContext(connectionString))
  1030. {
  1031. pumpNozzleInfoResults = context.LoadStoredProc(SpsDbRoutines.GetAllPumpNozzleInfo)
  1032. .WithSqlParam("", "")
  1033. .ExecuteStoredProc<PumpNozzleInfoResult>();
  1034. }
  1035. foreach (var item in pumpNozzleInfoResults)
  1036. {
  1037. Console.Write($"Logical Node: {item.LgNode} ");
  1038. Console.Write($"Tank No: {item.TankNo} ");
  1039. Console.Write($"POS ID: {item.PosId} ");
  1040. Console.Write($"Protocol: {item.Protocol} ");
  1041. Console.Write($"ProtcType: {item.ProtcType} ");
  1042. Console.Write($"Port: {item.Port} ");
  1043. Console.Write($"LinkPort: {item.LinkPort} ");
  1044. Console.Write($"Mode: {item.Mode} ");
  1045. Console.Write($"BuffSize: {item.BuffSize} ");
  1046. Console.Write($"CheckMode: {item.CheckMode} ");
  1047. Console.Write($"Node: {item.Node} ");
  1048. Console.Write($"SubNode: {item.SubNode} ");
  1049. Console.Write($"NozzleNum: {item.NozzleNum} ");
  1050. Console.Write($"PumpType: {item.PumpType} ");
  1051. Console.Write($"DspNo: {item.DspNo} ");
  1052. Console.Write($"MaxMon: {item.MaxMon} ");
  1053. Console.Write($"MaxVol: {item.MaxVol} ");
  1054. Console.WriteLine();
  1055. }
  1056. }
  1057. public void GetPosConfigInfo()
  1058. {
  1059. IList<PosConfigInfoResult> posConfigInfoResults = new List<PosConfigInfoResult>();
  1060. using (var context = new SpsDbContext(connectionString))
  1061. {
  1062. posConfigInfoResults = context.LoadStoredProc(SpsDbRoutines.GetAllPosConfigInfo)
  1063. .WithSqlParam("", "")
  1064. .ExecuteStoredProc<PosConfigInfoResult>();
  1065. }
  1066. foreach (var item in posConfigInfoResults)
  1067. {
  1068. Console.Write($"POS ID: {item.Pos_Id} ");
  1069. Console.Write($"POS IP: {item.Pos_IP} ");
  1070. Console.WriteLine($"Shift_Num: {item.Shift_Num}");
  1071. }
  1072. }
  1073. public TTrdinfo SelectGrayTrade(string cardNo, int ctc, string time)
  1074. {
  1075. return null;
  1076. }
  1077. public TTrdinfo GetGrayTrdInfo(string cardNo, int ctc, int pumpId)
  1078. {
  1079. string selectStament = "SELECT * FROM sps_db.t_trdinfo WHERE CardNo=@cardNo AND CTC=@ctc AND PumpNo=@pumpId";
  1080. byte grayTrdType = 1;
  1081. try
  1082. {
  1083. using (MySqlConnection conn = new MySqlConnection(connectionString))
  1084. {
  1085. List<TTrdinfo> trdInfoList = new List<TTrdinfo>();
  1086. using (MySqlCommand cmd = new MySqlCommand(selectStament, conn))
  1087. {
  1088. cmd.Parameters.Add("@TrdType", MySqlDbType.Byte).Value = grayTrdType;
  1089. cmd.Parameters.Add("@cardNo", MySqlDbType.String).Value = cardNo;
  1090. cmd.Parameters.Add("@ctc", MySqlDbType.UInt32).Value = ctc;
  1091. cmd.Parameters.Add("@pumpId", MySqlDbType.Byte).Value = pumpId;
  1092. conn.Open();
  1093. using (MySqlDataReader dr = cmd.ExecuteReader())
  1094. {
  1095. if (dr.HasRows)
  1096. {
  1097. while (dr.Read())
  1098. {
  1099. var trdInfo = new TTrdinfo();
  1100. trdInfo.CommId = Convert.ToString(dr["CommID"]);
  1101. trdInfo.Mon = Convert.ToInt32(dr["Mon"]);
  1102. trdInfo.EndPumpId = Convert.ToInt64(dr["EndPumpID"]);
  1103. trdInfo.Ttctime = Convert.ToDateTime(dr["TTCTime"]);
  1104. trdInfoList.Add(trdInfo);
  1105. }
  1106. }
  1107. }
  1108. return trdInfoList.OrderByDescending(t => t.Ttctime).FirstOrDefault();
  1109. }
  1110. }
  1111. }
  1112. catch (Exception ex)
  1113. {
  1114. Console.WriteLine(ex.ToString());
  1115. }
  1116. return null;
  1117. }
  1118. #endregion
  1119. #endregion
  1120. #region Operations against legacy iFuel config in `sps_db` tables
  1121. public int AddOrUpdateFuelProduct(string productCode, string classNo, string productName, int price)
  1122. {
  1123. using (var context = new SpsDbContext(connectionString))
  1124. {
  1125. try
  1126. {
  1127. var entry = context.TFuellist.FirstOrDefault(f => f.FuelNo == productCode);
  1128. if (entry == null)
  1129. {
  1130. var fuelEntry = new TFuellist();
  1131. fuelEntry.FuelNo = productCode;
  1132. fuelEntry.ClassNo = classNo;
  1133. fuelEntry.Name = productName;
  1134. fuelEntry.Price = price;
  1135. fuelEntry.Unit = "升";
  1136. context.TFuellist.Add(fuelEntry);
  1137. }
  1138. else
  1139. {
  1140. entry.ClassNo = classNo;
  1141. entry.Name = productName;
  1142. entry.Unit = "升";
  1143. }
  1144. context.SaveChanges();
  1145. }
  1146. catch (Exception ex)
  1147. {
  1148. Console.WriteLine(ex.ToString());
  1149. }
  1150. }
  1151. return -1;
  1152. }
  1153. public int AddOrUpdateTankConfig(int tankNo, string product)
  1154. {
  1155. using (var context = new SpsDbContext(connectionString))
  1156. {
  1157. try
  1158. {
  1159. var currentTank = context.TTanklist.FirstOrDefault(t => t.TankId == tankNo);
  1160. if (currentTank == null)
  1161. {
  1162. var tank = new TTanklist();
  1163. tank.TankId = Convert.ToByte(tankNo);
  1164. tank.FuelNo = product;
  1165. tank.Height = 0;
  1166. tank.MaxHeight = 0;
  1167. tank.MinHeight = 0;
  1168. tank.MaxVolume = 0;
  1169. tank.MinVolume = 0;
  1170. tank.MaxWaterHeight = 0;
  1171. tank.MaxTemp = 0;
  1172. tank.OffSet = 0;
  1173. tank.OilOffSet = 0;
  1174. tank.WaterOffSet = 0;
  1175. tank.FixDate = new DateTime(1900, 01, 01);
  1176. tank.FactoryDate = new DateTime(1900, 01, 01);
  1177. tank.FactoryNo = "0";
  1178. tank.LimitDate = 0;
  1179. tank.ProbeId = "";
  1180. tank.ProbeAddr = "";
  1181. tank.FactName = "0";
  1182. context.TTanklist.Add(tank);
  1183. }
  1184. else
  1185. {
  1186. currentTank.FuelNo = product;
  1187. }
  1188. context.SaveChanges();
  1189. }
  1190. catch (Exception ex)
  1191. {
  1192. Console.WriteLine(ex.ToString());
  1193. }
  1194. }
  1195. return -1;
  1196. }
  1197. public int AddOrUpdatePump(int pumpMode, byte pumpId, int comPortNo, byte subAddress, int maxAmount, int maxVol = 999900)
  1198. {
  1199. using (var context = new SpsDbContext(connectionString))
  1200. {
  1201. try
  1202. {
  1203. var currentPumpInfo = context.TPumpinfo.FirstOrDefault(p => p.LgNode == pumpId);
  1204. if (currentPumpInfo == null)
  1205. {
  1206. var pumpInfo = new TPumpinfo();
  1207. pumpInfo.LgNode = pumpId;
  1208. pumpInfo.DspNo = "1";
  1209. pumpInfo.TankNo = 0;
  1210. pumpInfo.PosId = 1;
  1211. pumpInfo.PumpType = 0;
  1212. pumpInfo.Protocol = 2;
  1213. pumpInfo.ProtcType = 2;
  1214. pumpInfo.Port = "0";
  1215. pumpInfo.LinkPort = comPortNo;
  1216. pumpInfo.Node = 1;
  1217. pumpInfo.SubNode = subAddress;
  1218. pumpInfo.Mode = pumpMode; //1;
  1219. pumpInfo.NozzleNum = 1;
  1220. pumpInfo.DelayPara = 0;
  1221. pumpInfo.BuffSize = 4;
  1222. pumpInfo.CheckMode = 2;
  1223. pumpInfo.MaxMon = maxAmount;
  1224. pumpInfo.MaxVol = maxVol;
  1225. context.TPumpinfo.Add(pumpInfo);
  1226. }
  1227. else
  1228. {
  1229. currentPumpInfo.DspNo = "1";
  1230. currentPumpInfo.TankNo = 0;
  1231. currentPumpInfo.PosId = 1;
  1232. currentPumpInfo.PumpType = 0;
  1233. currentPumpInfo.Protocol = 2;
  1234. currentPumpInfo.ProtcType = 2;
  1235. currentPumpInfo.Port = "0";
  1236. currentPumpInfo.LinkPort = comPortNo;
  1237. currentPumpInfo.Node = 1;
  1238. currentPumpInfo.SubNode = subAddress;
  1239. currentPumpInfo.Mode = pumpMode;//1;
  1240. currentPumpInfo.NozzleNum = 1;
  1241. currentPumpInfo.DelayPara = 0;
  1242. currentPumpInfo.BuffSize = 4;
  1243. currentPumpInfo.CheckMode = 2;
  1244. currentPumpInfo.MaxMon = maxAmount;
  1245. currentPumpInfo.MaxVol = maxVol;
  1246. }
  1247. context.SaveChanges();
  1248. }
  1249. catch (Exception ex)
  1250. {
  1251. Console.WriteLine(ex.ToString());
  1252. }
  1253. }
  1254. return -1;
  1255. }
  1256. public int AddOrUpdateNozzle(byte nozzleId, byte pumpId, byte tankId, string fuelNo)
  1257. {
  1258. using (var context = new SpsDbContext(connectionString))
  1259. {
  1260. try
  1261. {
  1262. var currentNozzleInfo = context.TNozzleinfo.FirstOrDefault(n => n.LogicId == nozzleId);
  1263. if (currentNozzleInfo == null)
  1264. {
  1265. var nozzleInfo = new TNozzleinfo();
  1266. nozzleInfo.LogicId = nozzleId;
  1267. nozzleInfo.PhysId = 1;
  1268. nozzleInfo.DspNo = "0";
  1269. nozzleInfo.TankId = tankId;
  1270. nozzleInfo.PumpNode = pumpId;
  1271. nozzleInfo.State = "";
  1272. nozzleInfo.OilTypeId = fuelNo;
  1273. nozzleInfo.CarIdenAddr = "0";
  1274. context.TNozzleinfo.Add(nozzleInfo);
  1275. }
  1276. else
  1277. {
  1278. currentNozzleInfo.PhysId = 1;
  1279. currentNozzleInfo.DspNo = "0";
  1280. currentNozzleInfo.TankId = tankId;
  1281. currentNozzleInfo.PumpNode = pumpId;
  1282. currentNozzleInfo.State = "";
  1283. currentNozzleInfo.OilTypeId = fuelNo;
  1284. currentNozzleInfo.CarIdenAddr = "0";
  1285. }
  1286. context.SaveChanges();
  1287. }
  1288. catch (Exception ex)
  1289. {
  1290. Console.WriteLine(ex.ToString());
  1291. }
  1292. }
  1293. return -1;
  1294. }
  1295. #endregion
  1296. #region Get card holder and car number
  1297. public TCardinfo GetCardInfoByCardNo(string cardNo)
  1298. {
  1299. using (var context = new SpsDbContext(connectionString))
  1300. {
  1301. return context.TCardinfo.FirstOrDefault(c => c.CardNo == cardNo);
  1302. }
  1303. }
  1304. #endregion
  1305. }
  1306. }