From 8ea869644aaff39c018cb65a1e4e56e1527275d5 Mon Sep 17 00:00:00 2001 From: Hygge Date: Sun, 30 Jul 2023 13:44:10 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=95=86=E9=93=BA?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E4=B8=BA=E7=A9=BA=E4=BC=9A=E6=8A=A5=E9=94=99?= =?UTF-8?q?=E7=9A=84=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Repository/ShopRepository.cs | 9 +++++++-- .../UserControls/StoreManageUserControl.xaml.cs | 8 +++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Repository/ShopRepository.cs b/Repository/ShopRepository.cs index 24cc5cd..eac6a0a 100644 --- a/Repository/ShopRepository.cs +++ b/Repository/ShopRepository.cs @@ -245,10 +245,12 @@ private static string GetMaxInventoryShopId(List shopIdList, List private static List GetAllShopList() { - List list = new List(); + var list = new List(); if (File.Exists(App.StoreListFile)) { list = JsonConvert.DeserializeObject>(File.ReadAllText(App.StoreListFile)); + if (list.Count == 0) + throw new Exception("未获取到可用商店列表,请先尝试刷新商店列表"); return list; } using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); @@ -273,7 +275,10 @@ private static List GetAllShopList() }; list.Add(storeEntity); } - File.WriteAllText(App.StoreListFile, JsonConvert.SerializeObject(list)); + if(list.Count != 0) + File.WriteAllText(App.StoreListFile, JsonConvert.SerializeObject(list)); + if (list.Count == 0) + throw new Exception("未获取到可用商店列表,请先尝试刷新商店列表"); return list; } diff --git a/UserInterface/UserControls/StoreManageUserControl.xaml.cs b/UserInterface/UserControls/StoreManageUserControl.xaml.cs index 21e60a5..ab32f76 100644 --- a/UserInterface/UserControls/StoreManageUserControl.xaml.cs +++ b/UserInterface/UserControls/StoreManageUserControl.xaml.cs @@ -1,4 +1,5 @@ -using System.Threading; +using System.IO; +using System.Threading; using System.Windows; using Flurl.Http; using hygge_imaotai.Domain; @@ -39,6 +40,11 @@ private void RefreshData() /// private async void RefreshShopButton_OnClick(object sender, RoutedEventArgs e) { + // 判断App.StoreListFile是否存在,存在则删除 + if (File.Exists(App.StoreListFile)) + { + File.Delete(App.StoreListFile); + } await IMTService.RefreshShop(); RefreshData(); } From ea212b534afa113ed2afc40044da435eac403f6b Mon Sep 17 00:00:00 2001 From: Hygge Date: Sat, 5 Aug 2023 12:33:35 +0800 Subject: [PATCH 2/3] =?UTF-8?q?feat:=20=E6=8C=81=E4=B9=85=E5=B1=82?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E6=9B=B4=E6=96=B0=E4=B8=BAFreeSQL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App.xaml.cs | 2 +- Domain/LogListViewModel.cs | 20 +- Domain/MainWindowViewModel.cs | 2 +- ...eListViewModel.cs => ShopListViewModel.cs} | 32 ++- Domain/UserManageViewModel.cs | 18 +- Entity/{StoreEntity.cs => ShopEntity.cs} | 26 +-- Entity/UserEntity.cs | 6 +- IMTService.cs | 134 +++++++----- Repository/CommonRepository.cs | 104 +-------- Repository/DB.cs | 15 ++ Repository/LogRepository.cs | 112 ---------- Repository/ShopRepository.cs | 167 +------------- Repository/UserRepository.cs | 207 ------------------ .../DirectAddAccountDialogUserControl.xaml.cs | 34 +-- .../UserControls/LogUserControl.xaml.cs | 18 +- ...ontrol.xaml => ShopManageUserControl.xaml} | 6 +- ....xaml.cs => ShopManageUserControl.xaml.cs} | 29 ++- .../UserControls/UserManageControl.xaml.cs | 17 +- hygge-imaotai.csproj | 3 +- 19 files changed, 254 insertions(+), 698 deletions(-) rename Domain/{StoreListViewModel.cs => ShopListViewModel.cs} (64%) rename Entity/{StoreEntity.cs => ShopEntity.cs} (82%) create mode 100644 Repository/DB.cs delete mode 100644 Repository/LogRepository.cs delete mode 100644 Repository/UserRepository.cs rename UserInterface/UserControls/{StoreManageUserControl.xaml => ShopManageUserControl.xaml} (98%) rename UserInterface/UserControls/{StoreManageUserControl.xaml.cs => ShopManageUserControl.xaml.cs} (57%) diff --git a/App.xaml.cs b/App.xaml.cs index e3c9b2c..1500156 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -28,7 +28,7 @@ public partial class App : Application /// /// 订单数据库表名 /// - public const string OrderDatabasePath = "imaotai.db"; + public const string OrderDatabasePath = "cache/imaotai.db"; /// /// 订单数据库连接字符串 /// diff --git a/Domain/LogListViewModel.cs b/Domain/LogListViewModel.cs index 57586ae..b656d39 100644 --- a/Domain/LogListViewModel.cs +++ b/Domain/LogListViewModel.cs @@ -1,5 +1,4 @@ -using System; -using hygge_imaotai.Entity; +using hygge_imaotai.Entity; using System.Collections.ObjectModel; using hygge_imaotai.Repository; using System.Windows.Input; @@ -19,10 +18,10 @@ public class LogListViewModel:ViewModelBase private string _searchContent; // 分页数据 - private int _total = 0; + private long _total = 0; private int _current = 1; private int _pageSize = 10; - private int _pageCount = 0; + private long _pageCount = 0; #endregion @@ -46,7 +45,7 @@ public string SearchContent set => SetProperty(ref _searchContent, value); } - public int Total + public long Total { get => _total; set => SetProperty(ref _total, value); @@ -64,7 +63,7 @@ public int PageSize set => SetProperty(ref _pageSize, value); } - public int PageCount + public long PageCount { get => _pageCount; set => SetProperty(ref _pageCount, value); @@ -88,7 +87,14 @@ public LogListViewModel() private void UpdateData(object parameter) { LogList.Clear(); - LogRepository.GetPageData((int)parameter, 10,this).ForEach(LogList.Add); + DB.Sqlite.Select() + .WhereIf(!string.IsNullOrEmpty(this.Mobile), + i => i.MobilePhone.Contains(this.Mobile)) + .WhereIf(!string.IsNullOrEmpty(this.SearchContent), + i => i.Content.Contains(this.SearchContent)) + .WhereIf(!string.IsNullOrEmpty(this.Status), + i => i.Status.Contains(this.Status)) + .Page((int)parameter, 10).ToList().ForEach(LogListViewModel.LogList.Add); } #endregion diff --git a/Domain/MainWindowViewModel.cs b/Domain/MainWindowViewModel.cs index 5f4dbc3..b98e0d1 100644 --- a/Domain/MainWindowViewModel.cs +++ b/Domain/MainWindowViewModel.cs @@ -127,7 +127,7 @@ private static IEnumerable GenerateDemoItems(ISnackbarMessageQueue sna yield return new DemoItem( "店铺管理", - typeof(StoreManageUserControl), + typeof(ShopManageUserControl), selectedIcon: PackIconKind.Store, unselectedIcon:PackIconKind.Store ); diff --git a/Domain/StoreListViewModel.cs b/Domain/ShopListViewModel.cs similarity index 64% rename from Domain/StoreListViewModel.cs rename to Domain/ShopListViewModel.cs index 3f9ceeb..381053f 100644 --- a/Domain/StoreListViewModel.cs +++ b/Domain/ShopListViewModel.cs @@ -2,14 +2,13 @@ using System.Windows.Input; using hygge_imaotai.Entity; using hygge_imaotai.Repository; -using hygge_imaotai.UserInterface.UserControls; namespace hygge_imaotai.Domain { /// /// 门店列表Page的ViewModel /// - public class StoreListViewModel:ViewModelBase + public class ShopListViewModel : ViewModelBase { #region Field private string _shopId; @@ -19,10 +18,10 @@ public class StoreListViewModel:ViewModelBase private string _companyName; // 分页数据 - private int _total = 0; + private long _total = 0; private int _current = 1; - private int _pageSize = 10; - private int _pageCount = 0; + private long _pageSize = 10; + private long _pageCount = 0; #endregion #region Properties @@ -57,9 +56,9 @@ public string CompanyName set => SetProperty(ref _companyName, value); } - public static ObservableCollection StoreList { get; } = new ObservableCollection(); + public static ObservableCollection StoreList { get; } = new ObservableCollection(); - public int Total + public long Total { get => _total; set => SetProperty(ref _total, value); @@ -71,13 +70,13 @@ public int Current set => SetProperty(ref _current, value); } - public int PageSize + public long PageSize { get => _pageSize; set => SetProperty(ref _pageSize, value); } - public int PageCount + public long PageCount { get => _pageCount; set => SetProperty(ref _pageCount, value); @@ -87,18 +86,27 @@ public int PageCount #region Constructor - public StoreListViewModel() + public ShopListViewModel() { CurrentPageChangeCommand = new AnotherCommandImplementation(UpdateData); } -#endregion + #endregion #region DelegateCommand public ICommand CurrentPageChangeCommand { get; private set; } private void UpdateData(object parameter) { StoreList.Clear(); - ShopRepository.GetPageData((int)parameter, 10,this).ForEach(StoreList.Add); + DB.Sqlite.Select() + .WhereIf(!string.IsNullOrEmpty(this.ShopId), + i => i.ShopId.Contains(this.ShopId)) + .WhereIf(!string.IsNullOrEmpty(this.Province), + i => i.Province.Contains(this.Province)) + .WhereIf(!string.IsNullOrEmpty(this.City), + i => i.City.Contains(this.City)) + .WhereIf(!string.IsNullOrEmpty(this.Area), i => i.Area.Contains(this.Area)) + .WhereIf(!string.IsNullOrEmpty(this.CompanyName), i => i.CompanyName.Contains(this.CompanyName)) + .Page((int)parameter, 10).ToList().ForEach(StoreList.Add); } #endregion diff --git a/Domain/UserManageViewModel.cs b/Domain/UserManageViewModel.cs index c057d87..7bffac9 100644 --- a/Domain/UserManageViewModel.cs +++ b/Domain/UserManageViewModel.cs @@ -23,10 +23,10 @@ public class UserManageViewModel : ViewModelBase private string? _city; // 分页数据 - private int _total = 0; + private long _total = 0; private int _current = 1; private int _pageSize = 10; - private int _pageCount = 0; + private long _pageCount = 0; #endregion @@ -76,7 +76,7 @@ public bool? IsAllItems1Selected } } - public int Total + public long Total { get => _total; set => SetProperty(ref _total, value); @@ -94,7 +94,7 @@ public int PageSize set => SetProperty(ref _pageSize, value); } - public int PageCount + public long PageCount { get => _pageCount; set => SetProperty(ref _pageCount, value); @@ -133,7 +133,15 @@ private static void SelectAll(bool select, IEnumerable models) private void UpdateData(object parameter) { UserList.Clear(); - UserRepository.GetPageData((int)parameter, 10, this).ForEach(UserList.Add); + DB.Sqlite.Select() + .WhereIf(!string.IsNullOrEmpty(this.Phone), + i => i.Mobile.Contains(this.Phone)) + .WhereIf(!string.IsNullOrEmpty(this.UserId), + i => (i.UserId + "").Contains(this.UserId)) + .WhereIf(!string.IsNullOrEmpty(this.Province), + i => i.ProvinceName.Contains(this.Province)) + .WhereIf(!string.IsNullOrEmpty(this.City),i => i.CityName.Contains(this.City)) + .Page((int)parameter, 10).ToList().ForEach(UserList.Add); } #endregion diff --git a/Entity/StoreEntity.cs b/Entity/ShopEntity.cs similarity index 82% rename from Entity/StoreEntity.cs rename to Entity/ShopEntity.cs index 01876e9..304e813 100644 --- a/Entity/StoreEntity.cs +++ b/Entity/ShopEntity.cs @@ -1,6 +1,5 @@ - - -using System; +using System; +using FreeSql.DataAnnotations; using hygge_imaotai.Domain; using Newtonsoft.Json.Linq; @@ -9,11 +8,11 @@ namespace hygge_imaotai.Entity /// /// 店铺的实体类 /// - public class StoreEntity:ViewModelBase + public class ShopEntity:ViewModelBase { #region Field - private string _productId; + private string _shopId; private string _province; private string _city; private string _area; @@ -29,14 +28,14 @@ public class StoreEntity:ViewModelBase #region Construct - public StoreEntity() + public ShopEntity() { } - public StoreEntity(string shopId, JObject jObject) + public ShopEntity(string shopId, JObject jObject) { - ProductId = shopId; + ShopId = shopId; Province = jObject.GetValue("provinceName").Value(); City = jObject.GetValue("cityName").Value(); Area = jObject.GetValue("districtName").Value(); @@ -48,9 +47,9 @@ public StoreEntity(string shopId, JObject jObject) CreatedAt = DateTime.Now; } - public StoreEntity(string productId, string province, string city, string area, string unbrokenAddress, string lat, string lng, string name, string companyName) + public ShopEntity(string shopId, string province, string city, string area, string unbrokenAddress, string lat, string lng, string name, string companyName) { - _productId = productId; + _shopId = shopId; _province = province; _city = city; _area = area; @@ -66,10 +65,10 @@ public StoreEntity(string productId, string province, string city, string area, #region Properties - public string ProductId + public string ShopId { - get => _productId; - set => SetProperty(ref _productId, value); + get => _shopId; + set => SetProperty(ref _shopId, value); } public string Province @@ -126,6 +125,7 @@ public DateTime CreatedAt set => SetProperty(ref _createdAt, value); } + [Column(IsIgnore = true)] public double Distance { get; set; } #endregion diff --git a/Entity/UserEntity.cs b/Entity/UserEntity.cs index 10da96e..f6d67fc 100644 --- a/Entity/UserEntity.cs +++ b/Entity/UserEntity.cs @@ -1,5 +1,6 @@ using System; using System.Windows.Input; +using FreeSql.DataAnnotations; using hygge_imaotai.Domain; using hygge_imaotai.Repository; using hygge_imaotai.UserInterface.Component; @@ -76,7 +77,7 @@ public class UserEntity : ViewModelBase #region Properties - + [Column(IsIgnore = true)] public bool IsSelected { get => _isSelected; @@ -176,7 +177,8 @@ public DateTime ExpireTime private static void DeleteItemFunc(object? parameter) { - UserRepository.Delete((parameter as UserEntity)!); + var userEntity = (parameter as UserEntity)!; + DB.Sqlite.Delete().Where(i => i.Mobile == userEntity.Mobile).ExecuteAffrows(); UserManageViewModel.UserList.Remove((parameter as UserEntity)!); } diff --git a/IMTService.cs b/IMTService.cs index 9450f8e..1babde2 100644 --- a/IMTService.cs +++ b/IMTService.cs @@ -163,11 +163,24 @@ public async Task Login(string phone, string code) var foundUserEntity = UserManageViewModel.UserList.FirstOrDefault(user => user.Mobile == phone); if (foundUserEntity != null) { - UserRepository.UpdateUser(new UserEntity(phone,responseJson)); + await DB.Sqlite.Update().Set(i => i.UserId, foundUserEntity.UserId) + .Set(i => i.Token, foundUserEntity.Token) + .Set(i => i.ItemCode, foundUserEntity.ItemCode) + .Set(i => i.ProvinceName, foundUserEntity.ProvinceName) + .Set(i => i.CityName, foundUserEntity.CityName) + .Set(i => i.Address, foundUserEntity.Address) + .Set(i => i.Lat, foundUserEntity.Lat) + .Set(i => i.Lng, foundUserEntity.Lng) + .Set(i => i.ShopType, foundUserEntity.ShopType) + .Set(i => i.PushPlusToken, foundUserEntity.PushPlusToken) + .Set(i => i.JsonResult, foundUserEntity.JsonResult) + .Set(i => i.CreateTime, foundUserEntity.CreateTime) + .Set(i => i.ExpireTime, foundUserEntity.ExpireTime) + .Where(i => i.Mobile == foundUserEntity.Mobile).ExecuteAffrowsAsync(); } else { - UserRepository.InsertUser(new UserEntity(phone, responseJson)); + await DB.Sqlite.Insert(new UserEntity(phone, responseJson)).ExecuteAffrowsAsync(); } return true; } @@ -194,14 +207,15 @@ public static async void Reservation(UserEntity userEntity) } catch (Exception ex) { - LogRepository.InsertLog(new LogEntity() + await DB.Sqlite.Insert(new LogEntity() { CreateTime = DateTime.Now, MobilePhone = userEntity.Mobile, Content = $"[userId]:{userEntity.UserId}", Response = ex.Message, Status = "异常" - }); + }).ExecuteAffrowsAsync(); + new MessageBoxCustom("预约请求失败,响应结果详细请查看日志", MessageType.Error, MessageButtons.Ok).ShowDialog(); return; } @@ -211,8 +225,6 @@ public static async void Reservation(UserEntity userEntity) public static async Task Reservation(UserEntity user, string itemId, string shopId) { - var client = new HttpClient(); - var info = new Dictionary { { "itemId", itemId }, @@ -227,45 +239,62 @@ public static async Task Reservation(UserEntity user, string itemId, string shop {"userId",user.UserId + ""} }; values.Add("actParam", EncryptAES_CBC(JsonConvert.SerializeObject(values).Replace("\\\"", "\""))); - - client.DefaultRequestHeaders.Add("MT-Lat", user.Lat); - client.DefaultRequestHeaders.Add("MT-K", "1675213490331"); - client.DefaultRequestHeaders.Add("MT-Lng", user.Lng); - client.DefaultRequestHeaders.Add("Host", "app.moutai519.com.cn"); - client.DefaultRequestHeaders.Add("MT-User-Tag", "0"); - client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*"); - client.DefaultRequestHeaders.Add("MT-Network-Type", "WIFI"); - client.DefaultRequestHeaders.TryAddWithoutValidation("MT-Token", user.Token); - client.DefaultRequestHeaders.TryAddWithoutValidation("MT-Team-ID", ""); - client.DefaultRequestHeaders.Add("MT-Info", "028e7f96f6369cafe1d105579c5b9377"); - client.DefaultRequestHeaders.Add("MT-Device-ID", "2F2075D0-B66C-4287-A903-DBFF6358342A"); - client.DefaultRequestHeaders.Add("MT-Bundle-ID", "com.moutai.mall"); - client.DefaultRequestHeaders.Add("Accept-Language", "en-CN;q=1, zh-Hans-CN;q=0.9"); - client.DefaultRequestHeaders.Add("MT-Request-ID", "167560018873318465"); - client.DefaultRequestHeaders.Add("MT-APP-Version", await GetMtVersion()); - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "iOS;16.3;Apple;?unrecognized?"); - client.DefaultRequestHeaders.Add("MT-R", "clips_OlU6TmFRag5rCXwbNAQ/Tz1SKlN8THcecBp/HGhHdw=="); - client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", "93"); - client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br"); - client.DefaultRequestHeaders.Add("Connection", "keep-alive"); - client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); - client.DefaultRequestHeaders.TryAddWithoutValidation("userId", user.UserId + ""); - - var content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json"); - - var response = await client - .PostAsync("https://app.moutai519.com.cn/xhr/front/mall/reservation/add", content); - var responseString = await response.Content.ReadAsStringAsync(); - var responseJson = JObject.Parse(responseString); - - LogRepository.InsertLog(new LogEntity() + var requestBody = JsonConvert.SerializeObject(values); + + var response = await "https://app.moutai519.com.cn/xhr/front/mall/reservation/add" + .WithHeader("userId", user.UserId + "") + .WithHeader("Content-Type", "application/json") + .WithHeader("Connection", "keep-alive") + .WithHeader("MT-Bundle-ID", "com.moutai.mall") + .WithHeader("MT-R", "clips_OlU6TmFRag5rCXwbNAQ/Tz1SKlN8THcecBp/HGhHdw==") + .WithHeader("Accept-Encoding", "gzip, deflate, br") + .WithHeader("Accept-Language", "en-CN;q=1, zh-Hans-CN;q=0.9") + .WithHeader("MT-Lat", user.Lat) + .WithHeader("MT-K", "1675213490331") + .WithHeader("MT-Lng", user.Lng) + .WithHeader("Host", "app.moutai519.com.cn") + .WithHeader("MT-User-Tag", "0") + .WithHeader("Accept", "*/*") + .WithHeader("MT-Network-Type", "WIFI") + .WithHeader("MT-Token", user.Token) + .WithHeader("MT-Team-ID", "") + .WithHeader("MT-Info", "028e7f96f6369cafe1d105579c5b9377") + .WithHeader("MT-Device-ID", "2F2075D0-B66C-4287-A903-DBFF6358342A") + .WithHeader("MT-Request-ID", "167560018873318465") + .WithHeader("MT-APP-Version", await GetMtVersion()) + .WithHeader("User-Agent", "iOS;16.3;Apple;?unrecognized?") + .AllowAnyHttpStatus() + .PostStringAsync(requestBody); + if (response.StatusCode is 200 or 480) { - CreateTime = DateTime.Now, - MobilePhone = user.Mobile, - Content = $"[userId]:{user.UserId} [shopId]:{itemId}", - Response = responseString, - Status = responseJson["code"].Value() == 2000 ? "预约成功" : "预约失败" - }); + var responseString = await response.GetStringAsync(); + var responseJson = JObject.Parse(responseString); + await DB.Sqlite.Insert(new LogEntity() + { + CreateTime = DateTime.Now, + MobilePhone = user.Mobile, + Content = $"[userId]:{user.UserId} [shopId]:{itemId}", + Response = responseString, + Status = responseJson["code"].Value() == 2000 ? "预约成功" : "预约失败" + }).ExecuteAffrowsAsync(); + } + else + { + var logEntity = new LogEntity() + { + CreateTime = DateTime.Now, + MobilePhone = user.Mobile, + Content = $"[userId]:{user.UserId} [shopId]:{itemId}", + Response = $"本次抢购会话已过期,请手动刷新一下商品列表和店铺列表后重试", + Status = "预约失败" + }; + if (response.StatusCode != 404) + { + logEntity.Response = await response.GetStringAsync(); + } + await DB.Sqlite.Insert(logEntity).ExecuteAffrowsAsync(); + } + } /// @@ -335,7 +364,10 @@ public static async Task GetCurrentSessionId() /// public static void ReservationBatch() { - var users = UserRepository.GetReservationUser(); + var users = DB.Sqlite.Select().Where(i => + i.ExpireTime > DateTime.Now && !string.IsNullOrEmpty(i.Lat) && !string.IsNullOrEmpty(i.Lng) && + !string.IsNullOrEmpty(i.ShopType + "") && !string.IsNullOrEmpty(i.ItemCode)) + .ToList(); foreach (var userEntity in users) { try @@ -346,14 +378,14 @@ public static void ReservationBatch() catch (Exception e) { Logger.Error($"用户{userEntity.Mobile}预约产生异常,错误原因:{e.Message}"); - LogRepository.InsertLog(new LogEntity() + DB.Sqlite.Insert(new LogEntity() { CreateTime = DateTime.Now, MobilePhone = userEntity.Mobile, Content = $"[userId]:{userEntity.UserId}", Response = e.Message, Status = "异常" - }); + }).ExecuteAffrows(); } } } @@ -369,8 +401,8 @@ public static async void RefreshAll() public static async Task RefreshShop() { - StoreListViewModel.StoreList.Clear(); - ShopRepository.TruncateTable(); + ShopListViewModel.StoreList.Clear(); + await DB.Sqlite.Delete().ExecuteAffrowsAsync(); var responseStr = await "https://static.moutai519.com.cn/mt-backend/xhr/front/mall/resource/get" .GetStringAsync(); @@ -379,13 +411,13 @@ public static async Task RefreshShop() var shopInnerJson = await shopsUrl.GetStringAsync(); var shopInnerJObject = JObject.Parse(shopInnerJson); - Task task = Task.Run(() => + var task = Task.Run(() => { foreach (var property in shopInnerJObject.Properties()) { var shopId = property.Name; var nestedObject = (JObject)property.Value; - ShopRepository.InsertShop(new StoreEntity(shopId, nestedObject)); + DB.Sqlite.Insert(new ShopEntity(shopId, nestedObject)).ExecuteAffrows(); } }); await task; diff --git a/Repository/CommonRepository.cs b/Repository/CommonRepository.cs index d726a4f..ffbc2c4 100644 --- a/Repository/CommonRepository.cs +++ b/Repository/CommonRepository.cs @@ -1,5 +1,6 @@ -using Microsoft.Data.Sqlite; +using System.Data.SQLite; using System.IO; +using hygge_imaotai.Entity; namespace hygge_imaotai.Repository { @@ -16,101 +17,12 @@ public static void CreateDatabase() // 判断数据库文件是否存在 if (File.Exists(App.OrderDatabasePath)) return; // 创建数据库连接 - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - // 判断表是否存在 - CreateShopTable(connection); - CreateLogTable(connection); - CreateUserTable(connection); - } - - private static void CreateUserTable(SqliteConnection connection) - { - const string checkTableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='i_user';"; - using var checkTableCommand = new SqliteCommand(checkTableSql, connection); - using var reader = checkTableCommand.ExecuteReader(); - if (reader.HasRows)// 表存在,不需要创建 - return; - - // 创建新的表 - const string createTableSql = @"CREATE TABLE i_user ( - mobile_phone TEXT PRIMARY KEY NOT NULL, - user_id TEXT, - token TEXT, - item_code TEXT, - province_name TEXT, - city_name TEXT, -address TEXT, -lat TEXT, -lng TEXT, -shop_type TEXT, -push_plus_token TEXT, -json_result TEXT, -create_time TEXT, -expire_time TEXT -); -"; - using var command = new SqliteCommand(createTableSql, connection); - - command.ExecuteNonQuery(); - } - - /// - /// 创建店铺表 - /// - /// - private static void CreateShopTable(SqliteConnection connection) - { - const string checkTableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='i_shop';"; - using var checkTableCommand = new SqliteCommand(checkTableSql, connection); - using var reader = checkTableCommand.ExecuteReader(); - if (reader.HasRows)// 表存在,不需要创建 - return; - - // 创建新的表 - const string createTableSql = @"CREATE TABLE i_shop ( - shop_id INTEGER PRIMARY KEY NOT NULL, - i_shop_id TEXT, - province_name TEXT, - city_name TEXT, - district_name TEXT, - full_address TEXT, - lat TEXT, - lng TEXT, - name TEXT, - tenant_name TEXT, - create_time TEXT -); -"; - using var command = new SqliteCommand(createTableSql, connection); - - command.ExecuteNonQuery(); - } - - /// - /// 创建日志表 - /// - private static void CreateLogTable(SqliteConnection connection) - { - const string checkTableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='i_logs';"; - using var checkTableCommand = new SqliteCommand(checkTableSql, connection); - using var reader = checkTableCommand.ExecuteReader(); - if (reader.HasRows)// 表存在,不需要创建 - return; - - // 创建新的表 - const string createTableSql = @"CREATE TABLE i_logs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - status TEXT NOT NULL, - mobilePhone TEXT NOT NULL, - content TEXT NOT NULL, - response TEXT, - createTime DATETIME NOT NULL -); -"; - using var command = new SqliteCommand(createTableSql, connection); - - command.ExecuteNonQuery(); + SQLiteConnection.CreateFile(App.OrderDatabasePath); + var sqLiteConnection = new SQLiteConnection(App.OrderDatabaseConnectStr); + sqLiteConnection.Open(); + // 创建表结构 + var types = new[] { typeof(UserEntity),typeof(ShopEntity),typeof(LogEntity) }; + DB.Sqlite.CodeFirst.SyncStructure(types); } } } diff --git a/Repository/DB.cs b/Repository/DB.cs new file mode 100644 index 0000000..676fa86 --- /dev/null +++ b/Repository/DB.cs @@ -0,0 +1,15 @@ +using System; +using System.Diagnostics; + +namespace hygge_imaotai.Repository +{ + public class DB + { + static readonly Lazy SqliteLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseMonitorCommand(cmd => Trace.WriteLine($"Sql:{cmd.CommandText}"))//监听SQL语句,Trace在输出选项卡中查看 + .UseConnectionString(FreeSql.DataType.Sqlite, App.OrderDatabaseConnectStr) + .UseAutoSyncStructure(true) //自动同步实体结构到数据库,FreeSql不会扫描程序集,只有CRUD时才会生成表。 + .Build()); + public static IFreeSql Sqlite => SqliteLazy.Value; + } +} diff --git a/Repository/LogRepository.cs b/Repository/LogRepository.cs deleted file mode 100644 index 42ac4e2..0000000 --- a/Repository/LogRepository.cs +++ /dev/null @@ -1,112 +0,0 @@ -using hygge_imaotai.Entity; -using Microsoft.Data.Sqlite; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using hygge_imaotai.Domain; - -namespace hygge_imaotai.Repository -{ - /// - /// 日志表的相关操作 - /// - public class LogRepository - { - #region Functions - - /// - /// 向表中添加一行数据 - /// - /// - public static void InsertLog(LogEntity logEntity) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - const string insertSql = @"INSERT INTO i_logs (status, mobilePhone, content, response, createTime) VALUES (@status, @mobilePhone, @content, @response, @createTime);"; - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@status", logEntity.Status); - command.Parameters.AddWithValue("@mobilePhone", logEntity.MobilePhone); - command.Parameters.AddWithValue("@content", logEntity.Content); - command.Parameters.AddWithValue("response", logEntity.Response); - command.Parameters.AddWithValue("@createTime", logEntity.CreateTime); - command.ExecuteNonQuery(); - } - - /// - /// 获取数据总数 - /// - /// - public static int GetTotalCount(LogListViewModel viewModel) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - var insertSql = @"select count(*) from i_logs where 1 = 1 "; - if (!string.IsNullOrEmpty(viewModel.Mobile)) insertSql += " and mobilePhone like @mobilePhone"; - if (!string.IsNullOrEmpty(viewModel.Status)) insertSql += " and status like @status"; - if (!string.IsNullOrEmpty(viewModel.SearchContent)) insertSql += " and content like @content"; - - - using var command = new SqliteCommand(insertSql, connection); - - if (!string.IsNullOrEmpty(viewModel.Mobile)) command.Parameters.AddWithValue("@mobilePhone", $"%{viewModel.Mobile}%"); - if (!string.IsNullOrEmpty(viewModel.Status)) command.Parameters.AddWithValue("@status", $"%{viewModel.Status}%"); - if (!string.IsNullOrEmpty(viewModel.SearchContent)) command.Parameters.AddWithValue("@content", $"%{viewModel.SearchContent}%"); - - using var reader = command.ExecuteReader(); - var count = 0; - while (reader.Read()) - { - count = reader.GetInt32(0); - } - return count; - } - - /// - /// 分页获取数据 - /// - /// - /// - /// - /// - public static List GetPageData(int page, int pageSize,LogListViewModel viewModel) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - var insertSql = @"select * from i_logs where 1 = 1 "; - - if (!string.IsNullOrEmpty(viewModel.Mobile)) insertSql += " and mobilePhone like @mobilePhone"; - if (!string.IsNullOrEmpty(viewModel.Status)) insertSql += " and status like @status"; - if (!string.IsNullOrEmpty(viewModel.SearchContent)) insertSql += " and content like @content"; - - insertSql += " limit @pageSize OFFSET @offset"; - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@offset", (page - 1) * pageSize); - command.Parameters.AddWithValue("@pageSize", pageSize); - if (!string.IsNullOrEmpty(viewModel.Mobile)) command.Parameters.AddWithValue("@mobilePhone", $"%{viewModel.Mobile}%"); - if (!string.IsNullOrEmpty(viewModel.Status)) command.Parameters.AddWithValue("@status", $"%{viewModel.Status}%"); - if (!string.IsNullOrEmpty(viewModel.SearchContent)) command.Parameters.AddWithValue("@content", $"%{viewModel.SearchContent}%"); - - using var reader = command.ExecuteReader(); - var list = new List(); - while (reader.Read()) - { - var logEntity = new LogEntity() - { - Id = reader.GetInt32(0), - Status = reader.GetString(1), - MobilePhone = reader.GetString(2), - Content = reader.GetString(3), - Response = reader.GetString(4), - CreateTime = reader.GetDateTime(5) - }; - list.Add(logEntity); - } - return list; - } - #endregion - - - } -} diff --git a/Repository/ShopRepository.cs b/Repository/ShopRepository.cs index eac6a0a..f1fe615 100644 --- a/Repository/ShopRepository.cs +++ b/Repository/ShopRepository.cs @@ -3,11 +3,9 @@ using System.IO; using System.Linq; using System.Threading.Tasks; -using System.Windows.Documents; using Flurl.Http; using hygge_imaotai.Domain; using hygge_imaotai.Entity; -using Microsoft.Data.Sqlite; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -18,130 +16,7 @@ namespace hygge_imaotai.Repository /// public class ShopRepository { - /// - /// 清空数据表数据 - /// - public static void TruncateTable() - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - const string truncateTableSql = "DELETE FROM i_shop;"; - using var command = new SqliteCommand(truncateTableSql, connection); - command.ExecuteNonQuery(); - } - - /// - /// 向表中添加一行数据 - /// - /// - public static void InsertShop(StoreEntity storeEntity) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - const string insertSql = @"INSERT INTO i_shop (i_shop_id,province_name,city_name,district_name,full_address,lat,lng,name,tenant_name,create_time)" + - "VALUES (@i_shop_id,@province_name,@city_name,@district_name,@full_address,@lat,@lng,@name,@tenant_name,@create_time);"; - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@i_shop_id", storeEntity.ProductId); - command.Parameters.AddWithValue("@province_name", storeEntity.Province); - command.Parameters.AddWithValue("@city_name", storeEntity.City); - command.Parameters.AddWithValue("@district_name", storeEntity.Area); - command.Parameters.AddWithValue("@full_address", storeEntity.UnbrokenAddress); - command.Parameters.AddWithValue("@lat", storeEntity.Lat); - command.Parameters.AddWithValue("@lng", storeEntity.Lng); - command.Parameters.AddWithValue("@name", storeEntity.Name); - command.Parameters.AddWithValue("@tenant_name", storeEntity.CompanyName); - command.Parameters.AddWithValue("@create_time", storeEntity.CreatedAt); - command.ExecuteNonQuery(); - } - - /// - /// 分页获取数据 - /// - /// - /// - /// - /// - public static List GetPageData(int page, int pageSize, StoreListViewModel? storeListViewModel = null) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - var insertSql = @"select * from i_shop where 1 = 1 "; - if (storeListViewModel != null) - { - if (!string.IsNullOrEmpty(storeListViewModel.ShopId)) insertSql += "And i_shop_id = @shopId "; - if (!string.IsNullOrEmpty(storeListViewModel.Province)) insertSql += "And province_name = @provinceName "; - if (!string.IsNullOrEmpty(storeListViewModel.City)) insertSql += "And city_name = @cityName "; - if (!string.IsNullOrEmpty(storeListViewModel.Area)) insertSql += "And district_name = @districtName "; - if (!string.IsNullOrEmpty(storeListViewModel.CompanyName)) insertSql += "And name = @name "; - } - - insertSql += "limit @pageSize OFFSET @offset"; - - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@offset", (page - 1) * pageSize); - command.Parameters.AddWithValue("@pageSize", pageSize); - if (storeListViewModel != null) - { - if (!string.IsNullOrEmpty(storeListViewModel.ShopId)) command.Parameters.AddWithValue("@shopId", storeListViewModel.ShopId); - if (!string.IsNullOrEmpty(storeListViewModel.Province)) command.Parameters.AddWithValue("@provinceName", storeListViewModel.Province); - if (!string.IsNullOrEmpty(storeListViewModel.City)) command.Parameters.AddWithValue("@cityName", storeListViewModel.City); - if (!string.IsNullOrEmpty(storeListViewModel.Area)) command.Parameters.AddWithValue("@districtName", storeListViewModel.Area); - if (!string.IsNullOrEmpty(storeListViewModel.CompanyName)) command.Parameters.AddWithValue("@name", storeListViewModel.CompanyName); - } - using var reader = command.ExecuteReader(); - var list = new List(); - while (reader.Read()) - { - var storeEntity = new StoreEntity - { - ProductId = reader.GetString(1), - Province = reader.GetString(2), - City = reader.GetString(3), - Area = reader.GetString(4), - UnbrokenAddress = reader.GetString(5), - Lat = reader.GetString(6), - Lng = reader.GetString(7), - Name = reader.GetString(8), - CompanyName = reader.GetString(9), - CreatedAt = DateTime.Parse(reader.GetString(10)) - }; - list.Add(storeEntity); - } - return list; - } - - /// - /// 获取数据总数 - /// - /// - /// - public static int GetTotalCount(StoreListViewModel storeListViewModel) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - var insertSql = @"select count(*) from i_shop where 1 = 1 "; - if (!string.IsNullOrEmpty(storeListViewModel.ShopId)) insertSql += "And i_shop_id = @shopId "; - if (!string.IsNullOrEmpty(storeListViewModel.Province)) insertSql += "And province_name = @provinceName "; - if (!string.IsNullOrEmpty(storeListViewModel.City)) insertSql += "And city_name = @cityName "; - if (!string.IsNullOrEmpty(storeListViewModel.Area)) insertSql += "And district_name = @districtName "; - if (!string.IsNullOrEmpty(storeListViewModel.CompanyName)) insertSql += "And name = @name "; - - - using var command = new SqliteCommand(insertSql, connection); - if (!string.IsNullOrEmpty(storeListViewModel.ShopId)) command.Parameters.AddWithValue("@shopId", storeListViewModel.ShopId); - if (!string.IsNullOrEmpty(storeListViewModel.Province)) command.Parameters.AddWithValue("@provinceName", storeListViewModel.Province); - if (!string.IsNullOrEmpty(storeListViewModel.City)) command.Parameters.AddWithValue("@cityName", storeListViewModel.City); - if (!string.IsNullOrEmpty(storeListViewModel.Area)) command.Parameters.AddWithValue("@districtName", storeListViewModel.Area); - if (!string.IsNullOrEmpty(storeListViewModel.CompanyName)) command.Parameters.AddWithValue("@name", storeListViewModel.CompanyName); - - using var reader = command.ExecuteReader(); - var count = 0; - while (reader.Read()) - { - count = reader.GetInt32(0); - } - return count; - } + /// /// 获取预约的店铺id @@ -159,7 +34,7 @@ public static async Task GetShopId(int userEntityShopType, string item, var shopIdList = shopList.Select(i => i.ShopId).ToList(); var iShops = GetAllShopList(); // 获取今日的门店信息列表 - var filteredShop = iShops.Where(i => shopIdList.Contains(i.ProductId)).ToList(); + var filteredShop = iShops.Where(i => shopIdList.Contains(i.ShopId)).ToList(); var shopId = ""; if (userEntityShopType == 1) @@ -189,7 +64,7 @@ public static async Task GetShopId(int userEntityShopType, string item, /// /// /// - private static string GetMinDistanceShopId(List filteredShop, string userEntityProvinceName, string userEntityLat, string userEntityLng) + private static string GetMinDistanceShopId(List filteredShop, string userEntityProvinceName, string userEntityLat, string userEntityLng) { var iShopList = filteredShop.Where(i => i.Province.Contains(userEntityProvinceName)).ToList(); var mapPoint = new MapPoint(double.Parse(userEntityLat), double.Parse(userEntityLng)); @@ -199,7 +74,7 @@ private static string GetMinDistanceShopId(List filteredShop, strin storeEntity.Distance = GetDistance(mapPoint, point); } var minDistance = iShopList.Min(i => i.Distance); - var shopId = iShopList.FirstOrDefault(i => i.Distance == minDistance)?.ProductId; + var shopId = iShopList.FirstOrDefault(i => i.Distance == minDistance)?.ShopId; return shopId; } @@ -227,10 +102,10 @@ public static double GetDistance(MapPoint point1, MapPoint point2) /// /// /// - private static string GetMaxInventoryShopId(List shopIdList, List filteredShop, string userEntityCityName) + private static string GetMaxInventoryShopId(List shopIdList, List filteredShop, string userEntityCityName) { // 本城市的shopId集合 - var cityShopIdList = filteredShop.Where(i => i.City.Contains(userEntityCityName)).Select(i => i.ProductId) + var cityShopIdList = filteredShop.Where(i => i.City.Contains(userEntityCityName)).Select(i => i.ShopId) .ToList(); var collect = shopIdList.Where(i => cityShopIdList.Contains(i.ShopId)).ToList(); @@ -243,38 +118,18 @@ private static string GetMaxInventoryShopId(List shopIdList, List /// - private static List GetAllShopList() + private static List GetAllShopList() { - var list = new List(); + var list = new List(); if (File.Exists(App.StoreListFile)) { - list = JsonConvert.DeserializeObject>(File.ReadAllText(App.StoreListFile)); + list = JsonConvert.DeserializeObject>(File.ReadAllText(App.StoreListFile)); if (list.Count == 0) throw new Exception("未获取到可用商店列表,请先尝试刷新商店列表"); return list; } - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - const string queryAllSql = @"select * from i_shop"; - using var command = new SqliteCommand(queryAllSql, connection); - using var reader = command.ExecuteReader(); - while (reader.Read()) - { - var storeEntity = new StoreEntity - { - ProductId = reader.GetString(1), - Province = reader.GetString(2), - City = reader.GetString(3), - Area = reader.GetString(4), - UnbrokenAddress = reader.GetString(5), - Lat = reader.GetString(6), - Lng = reader.GetString(7), - Name = reader.GetString(8), - CompanyName = reader.GetString(9), - CreatedAt = DateTime.Parse(reader.GetString(10)) - }; - list.Add(storeEntity); - } + + list = DB.Sqlite.Select().ToList(); if(list.Count != 0) File.WriteAllText(App.StoreListFile, JsonConvert.SerializeObject(list)); if (list.Count == 0) diff --git a/Repository/UserRepository.cs b/Repository/UserRepository.cs deleted file mode 100644 index 877196d..0000000 --- a/Repository/UserRepository.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using hygge_imaotai.Entity; -using Microsoft.Data.Sqlite; -using System.Collections.Generic; -using hygge_imaotai.Domain; - -namespace hygge_imaotai.Repository -{ - /// - /// 用户表的操作类 - /// - public class UserRepository - { - #region Functions - - /// - /// 向表中添加一行数据 - /// - /// - public static void InsertUser(UserEntity user) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - // 先根据手机号查询是否存在 - const string querySql = @"SELECT * FROM i_user WHERE mobile_phone=@mobile;"; - using var command = new SqliteCommand(querySql, connection); - command.Parameters.AddWithValue("@mobile", user.Mobile); - using var reader = command.ExecuteReader(); - if (reader.HasRows) - { - throw new Exception("数据已经存在"); - } - - const string insertSql = @"INSERT INTO i_user(mobile_phone,user_id,token,item_code,province_name,city_name,address,lat,lng,shop_type,push_plus_token,json_result,create_time,expire_time) - Values(@mobile,@user_id,@token,@item_code,@province_name,@city_name,@address,@lat,@lng,@shop_type,@push_plus_token,@json_result,@create_time,@expire_time);"; - using var insertCommand = new SqliteCommand(insertSql, connection); - insertCommand.Parameters.AddWithValue("@mobile", user.Mobile); - insertCommand.Parameters.AddWithValue("@user_id", user.UserId); - insertCommand.Parameters.AddWithValue("@token", user.Token); - insertCommand.Parameters.AddWithValue("@item_code", user.ItemCode); - insertCommand.Parameters.AddWithValue("@province_name", user.ProvinceName); - insertCommand.Parameters.AddWithValue("@city_name", user.CityName); - insertCommand.Parameters.AddWithValue("@address", user.Address); - insertCommand.Parameters.AddWithValue("@lat", user.Lat); - insertCommand.Parameters.AddWithValue("@lng", user.Lng); - insertCommand.Parameters.AddWithValue("@shop_type", user.ShopType); - insertCommand.Parameters.AddWithValue("@push_plus_token", user.PushPlusToken); - insertCommand.Parameters.AddWithValue("@json_result", user.JsonResult); - insertCommand.Parameters.AddWithValue("@create_time", user.CreateTime); - insertCommand.Parameters.AddWithValue("@expire_time", user.ExpireTime); - insertCommand.ExecuteNonQuery(); - } - - /// - /// 获取数据总数 - /// - /// - public static int GetTotalCount(UserManageViewModel viewModel) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - var insertSql = @"select count(*) from i_user where 1 = 1 "; - if (!string.IsNullOrEmpty(viewModel.Phone)) insertSql += "and mobile_phone like @phone "; - if (!string.IsNullOrEmpty(viewModel.UserId)) insertSql += "and user_id like @userId "; - if (!string.IsNullOrEmpty(viewModel.Province)) insertSql += "and province_name like @province "; - if (!string.IsNullOrEmpty(viewModel.City)) insertSql += "and city_name like @city "; - using var command = new SqliteCommand(insertSql, connection); - if (!string.IsNullOrEmpty(viewModel.Phone)) command.Parameters.AddWithValue("@phone", $"%{viewModel.Phone}%"); - if (!string.IsNullOrEmpty(viewModel.UserId)) command.Parameters.AddWithValue("@userId", $"%{viewModel.UserId}%"); - if (!string.IsNullOrEmpty(viewModel.Province)) command.Parameters.AddWithValue("@province", $"%{viewModel.Province}%"); - if (!string.IsNullOrEmpty(viewModel.City)) command.Parameters.AddWithValue("@city", $"%{viewModel.City}%"); - using var reader = command.ExecuteReader(); - var count = 0; - while (reader.Read()) - { - count = reader.GetInt32(0); - } - return count; - } - - /// - /// 获取符合条件的可预约用户 - /// - /// - public static List GetReservationUser() - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - // 过期时间大于当前时间的 且 Lat 不为空字符串 且 Lng 不为空空字符串 且 ShopType 不为空字符串 且 ItemCode 不为空字符串 - const string insertSql = @"select * from i_user where expire_time>@expire_time and lat!='' and lng!='' and shop_type!='' and item_code!=''"; - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@expire_time", DateTime.Now); - using var reader = command.ExecuteReader(); - var list = new List(); - while (reader.Read()) - { - var userEntity = new UserEntity() - { - Mobile = reader.GetString(0), - UserId = long.Parse(reader.GetString(1)), - Token = reader.GetString(2), - ItemCode = reader.GetString(3), - ProvinceName = reader.GetString(4), - CityName = reader.GetString(5), - Address = reader.GetString(6), - Lat = reader.GetString(7), - Lng = reader.GetString(8), - ShopType = reader.GetInt32(9), - PushPlusToken = reader.GetString(10), - JsonResult = reader.GetString(11), - CreateTime = reader.GetDateTime(12), - ExpireTime = reader.GetDateTime(13) - }; - list.Add(userEntity); - } - return list; - } - - /// - /// 分页获取数据 - /// - /// - /// - /// - /// - public static List GetPageData(int page, int pageSize, UserManageViewModel viewModel) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - string insertSql = @"select * from i_user where 1 = 1 "; - if(!string.IsNullOrEmpty(viewModel.Phone)) insertSql += "and mobile_phone like @phone "; - if(!string.IsNullOrEmpty(viewModel.UserId)) insertSql += "and user_id like @userId "; - if(!string.IsNullOrEmpty(viewModel.Province)) insertSql += "and province_name like @province "; - if(!string.IsNullOrEmpty(viewModel.City)) insertSql += "and city_name like @city "; - insertSql += "limit @pageSize OFFSET @offset"; - - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@offset", (page - 1) * pageSize); - command.Parameters.AddWithValue("@pageSize", pageSize); - - if(!string.IsNullOrEmpty(viewModel.Phone)) command.Parameters.AddWithValue("@phone", $"%{viewModel.Phone}%"); - if(!string.IsNullOrEmpty(viewModel.UserId)) command.Parameters.AddWithValue("@userId", $"%{viewModel.UserId}%"); - if(!string.IsNullOrEmpty(viewModel.Province)) command.Parameters.AddWithValue("@province", $"%{viewModel.Province}%"); - if(!string.IsNullOrEmpty(viewModel.City)) command.Parameters.AddWithValue("@city", $"%{viewModel.City}%"); - - using var reader = command.ExecuteReader(); - var list = new List(); - while (reader.Read()) - { - var userEntity = new UserEntity() - { - Mobile = reader.GetString(0), - UserId = long.Parse(reader.GetString(1)), - Token = reader.GetString(2), - ItemCode = reader.GetString(3), - ProvinceName = reader.GetString(4), - CityName = reader.GetString(5), - Address = reader.GetString(6), - Lat = reader.GetString(7), - Lng = reader.GetString(8), - ShopType = reader.GetInt32(9), - PushPlusToken = reader.GetString(10), - JsonResult = reader.GetString(11), - CreateTime = reader.GetDateTime(12), - ExpireTime = reader.GetDateTime(13) - }; - list.Add(userEntity); - } - return list; - } - - public static void UpdateUser(UserEntity user) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - const string insertSql = @"UPDATE i_user SET user_id=@user_id,token=@token,item_code=@item_code,province_name=@province_name,city_name=@city_name,address=@address,lat=@lat,lng=@lng, -shop_type=@shop_type,push_plus_token=@push_plus_token,json_result=@json_result,create_time=@create_time,expire_time=@expire_time WHERE mobile_phone=@mobile;"; - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@mobile", user.Mobile); - command.Parameters.AddWithValue("@user_id", user.UserId); - command.Parameters.AddWithValue("@token", user.Token); - command.Parameters.AddWithValue("@item_code", user.ItemCode); - command.Parameters.AddWithValue("@province_name", user.ProvinceName); - command.Parameters.AddWithValue("@city_name", user.CityName); - command.Parameters.AddWithValue("@address", user.Address); - command.Parameters.AddWithValue("@lat", user.Lat); - command.Parameters.AddWithValue("@lng", user.Lng); - command.Parameters.AddWithValue("@shop_type", user.ShopType); - command.Parameters.AddWithValue("@push_plus_token", user.PushPlusToken); - command.Parameters.AddWithValue("@json_result", user.JsonResult); - command.Parameters.AddWithValue("@create_time", user.CreateTime); - command.Parameters.AddWithValue("@expire_time", user.ExpireTime); - command.ExecuteNonQuery(); - } - public static void Delete(UserEntity parameter) - { - using var connection = new SqliteConnection(App.OrderDatabaseConnectStr); - connection.Open(); - const string insertSql = @"delete from i_user where mobile_phone=@mobile;"; - using var command = new SqliteCommand(insertSql, connection); - command.Parameters.AddWithValue("@mobile", parameter.Mobile); - command.ExecuteNonQuery(); - } - #endregion - - } -} diff --git a/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml.cs b/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml.cs index 67a89c1..759bfc7 100644 --- a/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml.cs +++ b/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml.cs @@ -12,16 +12,16 @@ namespace hygge_imaotai.UserInterface.Dialogs.DirectAddAccountDialog public partial class DirectAddAccountDialogUserControl { private IMTService service = new(); - private UserEntity _dataContext; + private readonly UserEntity _dataContext; - private string willFindPhone; + public DirectAddAccountDialogUserControl(UserEntity dataContext, bool isUpadte = false) { InitializeComponent(); DataContext = dataContext; _dataContext = (dataContext as UserEntity)!; - willFindPhone = isUpadte ? dataContext.Mobile : _dataContext.Mobile; + TitleBlock.Text = isUpadte ? "更新i茅台用户:" : "添加i茅台用户:"; LoginButton.Content = isUpadte ? "更新" : "添加"; } @@ -29,25 +29,27 @@ public DirectAddAccountDialogUserControl(UserEntity dataContext, bool isUpadte = private void LoginButton_OnClick(object sender, RoutedEventArgs e) { var foundUserEntity = - UserManageViewModel.UserList.FirstOrDefault(user => user.Mobile == willFindPhone); + UserManageViewModel.UserList.FirstOrDefault(user => user.Mobile == _dataContext.Mobile); if (foundUserEntity != null) { // 此处执行更新操作o // 更新寻找到的用户信息 - foundUserEntity.Mobile = _dataContext.Mobile; - foundUserEntity.UserId = _dataContext.UserId; - foundUserEntity.Token = _dataContext.Token; - foundUserEntity.ItemCode = _dataContext.ItemCode; - foundUserEntity.ProvinceName = _dataContext.ProvinceName; - foundUserEntity.CityName = _dataContext.CityName; - foundUserEntity.Lat = _dataContext.Lat; - foundUserEntity.Lng = _dataContext.Lng; - foundUserEntity.ShopType = _dataContext.ShopType; - foundUserEntity.ExpireTime = _dataContext.ExpireTime; - UserRepository.UpdateUser(foundUserEntity); + DB.Sqlite.Update() + .Set(i => i.UserId,_dataContext.UserId) + .Set(i => i.Token, _dataContext.Token) + .Set(i => i.ItemCode, _dataContext.ItemCode) + .Set(i => i.ProvinceName, _dataContext.ProvinceName) + .Set(i => i.CityName, _dataContext.CityName) + .Set(i => i.Lat, _dataContext.Lat) + .Set(i => i.Lng, _dataContext.Lng) + .Set(i => i.ShopType, _dataContext.ShopType) + .Set(i => i.ExpireTime, _dataContext.ExpireTime) + .Where(i => i.Mobile == _dataContext.Mobile).ExecuteAffrows(); + return; } - UserRepository.InsertUser(_dataContext); + + DB.Sqlite.Insert(_dataContext).ExecuteAffrows(); } } } diff --git a/UserInterface/UserControls/LogUserControl.xaml.cs b/UserInterface/UserControls/LogUserControl.xaml.cs index 4f8b7a0..8199ed1 100644 --- a/UserInterface/UserControls/LogUserControl.xaml.cs +++ b/UserInterface/UserControls/LogUserControl.xaml.cs @@ -1,5 +1,6 @@ using System.Windows; using hygge_imaotai.Domain; +using hygge_imaotai.Entity; using hygge_imaotai.Repository; namespace hygge_imaotai.UserInterface.UserControls @@ -20,11 +21,20 @@ private void RefreshData() { var logListViewModel = (LogListViewModel)DataContext; LogListViewModel.LogList.Clear(); - LogRepository.GetPageData(1, 10,logListViewModel).ForEach(LogListViewModel.LogList.Add); + + DB.Sqlite.Select() + .WhereIf(!string.IsNullOrEmpty(logListViewModel.Mobile), + i => i.MobilePhone.Contains(logListViewModel.Mobile)) + .WhereIf(!string.IsNullOrEmpty(logListViewModel.SearchContent), + i => i.Content.Contains(logListViewModel.SearchContent)) + .WhereIf(!string.IsNullOrEmpty(logListViewModel.Status), + i => i.Status.Contains(logListViewModel.Status)) + .Count(out var count) + .Page(1, 10).ToList().ForEach(LogListViewModel.LogList.Add); + // 分页数据 - var total = LogRepository.GetTotalCount(logListViewModel); - var pageCount = total / 10 + 1; - logListViewModel.Total = total; + var pageCount = count / 10 + 1; + logListViewModel.Total = count; logListViewModel.PageCount = pageCount; } diff --git a/UserInterface/UserControls/StoreManageUserControl.xaml b/UserInterface/UserControls/ShopManageUserControl.xaml similarity index 98% rename from UserInterface/UserControls/StoreManageUserControl.xaml rename to UserInterface/UserControls/ShopManageUserControl.xaml index b44ed8f..9ab5a82 100644 --- a/UserInterface/UserControls/StoreManageUserControl.xaml +++ b/UserInterface/UserControls/ShopManageUserControl.xaml @@ -1,4 +1,4 @@ - @@ -187,7 +187,7 @@ HeadersVisibility="All" ItemsSource="{Binding StoreList}"> - /// StoreManageUserControl.xaml 的交互逻辑 /// - public partial class StoreManageUserControl + public partial class ShopManageUserControl { - public StoreManageUserControl() + public ShopManageUserControl() { InitializeComponent(); - DataContext = new StoreListViewModel(); + DataContext = new ShopListViewModel(); RefreshData(); } private void RefreshData() { - var storeListViewModel = (StoreListViewModel)DataContext; - StoreListViewModel.StoreList.Clear(); - ShopRepository.GetPageData(1, 10,storeListViewModel).ForEach(StoreListViewModel.StoreList.Add); + var storeListViewModel = (ShopListViewModel)DataContext; + ShopListViewModel.StoreList.Clear(); + DB.Sqlite.Select() + .WhereIf(!string.IsNullOrEmpty(storeListViewModel.ShopId), + i => i.ShopId.Contains(storeListViewModel.ShopId)) + .WhereIf(!string.IsNullOrEmpty(storeListViewModel.Province), + i => i.Province.Contains(storeListViewModel.Province)) + .WhereIf(!string.IsNullOrEmpty(storeListViewModel.City), + i => i.City.Contains(storeListViewModel.City)) + .WhereIf(!string.IsNullOrEmpty(storeListViewModel.Area), i => i.Area.Contains(storeListViewModel.Area)) + .WhereIf(!string.IsNullOrEmpty(storeListViewModel.CompanyName), i => i.CompanyName.Contains(storeListViewModel.CompanyName)) + .Count(out var total) + .Page(1, 10).ToList().ForEach(ShopListViewModel.StoreList.Add); + + // 分页数据 - var total = ShopRepository.GetTotalCount((StoreListViewModel)DataContext); + var pageCount = total / 10 + 1; storeListViewModel.Total = total; storeListViewModel.PageCount = pageCount; @@ -51,7 +64,7 @@ private async void RefreshShopButton_OnClick(object sender, RoutedEventArgs e) private void ResetButton_OnClick(object sender, RoutedEventArgs e) { - var storeListViewModel = (StoreListViewModel)DataContext; + var storeListViewModel = (ShopListViewModel)DataContext; storeListViewModel.ShopId = ""; storeListViewModel.Province = ""; storeListViewModel.City = ""; diff --git a/UserInterface/UserControls/UserManageControl.xaml.cs b/UserInterface/UserControls/UserManageControl.xaml.cs index 98511a8..33fd798 100644 --- a/UserInterface/UserControls/UserManageControl.xaml.cs +++ b/UserInterface/UserControls/UserManageControl.xaml.cs @@ -1,5 +1,7 @@ -using System.Windows; +using System.Reflection.Metadata; +using System.Windows; using hygge_imaotai.Domain; +using hygge_imaotai.Entity; using hygge_imaotai.Repository; namespace hygge_imaotai.UserInterface.UserControls @@ -20,9 +22,18 @@ private void RefreshData() { var userListViewModel = (UserManageViewModel)DataContext; UserManageViewModel.UserList.Clear(); - UserRepository.GetPageData(1,10,userListViewModel).ForEach(UserManageViewModel.UserList.Add); + + DB.Sqlite.Select() + .WhereIf(!string.IsNullOrEmpty(userListViewModel.Phone), + i => i.Mobile.Contains(userListViewModel.Phone)) + .WhereIf(!string.IsNullOrEmpty(userListViewModel.UserId), + i => (i.UserId + "").Contains(userListViewModel.UserId)) + .WhereIf(!string.IsNullOrEmpty(userListViewModel.Province), + i => i.ProvinceName.Contains(userListViewModel.Province)) + .WhereIf(!string.IsNullOrEmpty(userListViewModel.City), i => i.CityName.Contains(userListViewModel.City)).Count(out var total) + .Page(1, 10).ToList().ForEach(UserManageViewModel.UserList.Add); + // 分页数据 - var total = UserRepository.GetTotalCount(userListViewModel); var pageCount = total / 10 + 1; userListViewModel.Total = total; userListViewModel.PageCount = pageCount; diff --git a/hygge-imaotai.csproj b/hygge-imaotai.csproj index 2142484..f35ebf8 100644 --- a/hygge-imaotai.csproj +++ b/hygge-imaotai.csproj @@ -34,8 +34,9 @@ + + - From d81bdcec94d1d540fc2ec575f7310c2c3720801f Mon Sep 17 00:00:00 2001 From: Hygge Date: Sat, 5 Aug 2023 14:32:28 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E9=A2=84=E7=BA=A6=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App.xaml.cs | 18 ++++++++++----- Entity/LogEntity.cs | 4 +++- Entity/ProductEntity.cs | 4 ---- Entity/UserEntity.cs | 12 ++++++++-- IMTService.cs | 7 ++---- .../DirectAddAccountDialogUserControl.xaml | 7 +++--- .../DirectAddAccountDialogUserControl.xaml.cs | 23 ++++++++++++++++++- 7 files changed, 52 insertions(+), 23 deletions(-) diff --git a/App.xaml.cs b/App.xaml.cs index 1500156..8ddd29c 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -19,7 +19,7 @@ namespace hygge_imaotai /// public partial class App : Application { - const string CacheDir = "cache"; + const string CacheDir = "cache"; // 内部使用缓存文件 private readonly string _productListFile = Path.Combine(CacheDir, "productList.json"); private readonly string _sessionIdFile = Path.Combine(CacheDir, "mtSessionId.txt"); @@ -43,9 +43,9 @@ public partial class App : Application protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); - + // 判断cache文件夹是否存在 - if(!Directory.Exists(CacheDir)) + if (!Directory.Exists(CacheDir)) Directory.CreateDirectory(CacheDir); // 判断productListFile是否存在,存在则读入缓存 @@ -57,7 +57,7 @@ protected override async void OnStartup(StartupEventArgs e) // 开始初始化数据库 CommonRepository.CreateDatabase(); // 读取会话ID - if(File.Exists(_sessionIdFile)) + if (File.Exists(_sessionIdFile)) MtSessionId = File.ReadAllText(_sessionIdFile); // 创建任务调度器 @@ -65,16 +65,22 @@ protected override async void OnStartup(StartupEventArgs e) var scheduler = await stdSchedulerFactory.GetScheduler(); await scheduler.Start(); Console.WriteLine("任务调度器已启动"); + + // 创建抢购预约的任务 var jobDetail = JobBuilder.Create().Build(); var trigger = TriggerBuilder.Create().WithCronSchedule("0 5 9 ? * * ").Build(); + // 创建刷新数据的任务 + var refreshJobDetail = JobBuilder.Create().Build(); + var refreshTrigger = TriggerBuilder.Create().WithCronSchedule("0 25,55 6,7,8 ? * * ").Build(); // 添加调度 await scheduler.ScheduleJob(jobDetail, trigger); + await scheduler.ScheduleJob(refreshJobDetail, refreshTrigger); } - public static void WriteCache(string filename,string content) + public static void WriteCache(string filename, string content) { var path = Path.Combine(CacheDir, filename); - File.WriteAllText(path,content); + File.WriteAllText(path, content); } } } diff --git a/Entity/LogEntity.cs b/Entity/LogEntity.cs index c14ac82..0f3175c 100644 --- a/Entity/LogEntity.cs +++ b/Entity/LogEntity.cs @@ -1,4 +1,6 @@ using System; +using System.Security.Principal; +using FreeSql.DataAnnotations; using hygge_imaotai.Domain; namespace hygge_imaotai.Entity @@ -19,7 +21,7 @@ public class LogEntity : ViewModelBase #endregion #region Properties - + [Column(IsIdentity = true, IsPrimary = true)] public int Id { get => _id; diff --git a/Entity/ProductEntity.cs b/Entity/ProductEntity.cs index a06213a..571e64f 100644 --- a/Entity/ProductEntity.cs +++ b/Entity/ProductEntity.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using hygge_imaotai.Domain; namespace hygge_imaotai.Entity diff --git a/Entity/UserEntity.cs b/Entity/UserEntity.cs index f6d67fc..f921e23 100644 --- a/Entity/UserEntity.cs +++ b/Entity/UserEntity.cs @@ -190,7 +190,7 @@ private static void ModifyItemFunc(object? parameter) DialogHost.Show(view, "RootDialog"); } - private static void ReserveCommandItemFunc(object? parameter) + private static async void ReserveCommandItemFunc(object? parameter) { var userEntity = parameter as UserEntity; if (string.IsNullOrEmpty(userEntity?.ItemCode)) @@ -199,7 +199,15 @@ private static void ReserveCommandItemFunc(object? parameter) } else { - IMTService.Reservation(userEntity); + try + { + await IMTService.Reservation(userEntity); + new MessageBoxCustom("手动发起预约成功,响应结果请查看日志", MessageType.Success, MessageButtons.Ok).ShowDialog(); + } + catch (Exception e) + { + new MessageBoxCustom("预约请求失败,响应结果详细请查看日志", MessageType.Error, MessageButtons.Ok).ShowDialog(); + } } } #endregion diff --git a/IMTService.cs b/IMTService.cs index 1babde2..d5305c9 100644 --- a/IMTService.cs +++ b/IMTService.cs @@ -189,7 +189,7 @@ await DB.Sqlite.Update().Set(i => i.UserId, foundUserEntity.UserId) /// 预约方法 /// /// - public static async void Reservation(UserEntity userEntity) + public static async Task Reservation(UserEntity userEntity) { var items = userEntity.ItemCode.Split("@"); @@ -215,11 +215,7 @@ await DB.Sqlite.Insert(new LogEntity() Response = ex.Message, Status = "异常" }).ExecuteAffrowsAsync(); - - new MessageBoxCustom("预约请求失败,响应结果详细请查看日志", MessageType.Error, MessageButtons.Ok).ShowDialog(); - return; } - new MessageBoxCustom("手动发起预约成功,响应结果请查看日志", MessageType.Success, MessageButtons.Ok).ShowDialog(); } @@ -345,6 +341,7 @@ public static async Task GetCurrentSessionId() var dataJObject = jObject["data"]; App.MtSessionId = dataJObject["sessionId"].Value(); var itemList = (JArray)dataJObject["itemList"]; + AppointProjectViewModel.ProductList.Clear(); foreach (var itemElement in itemList) { AppointProjectViewModel.ProductList.Add(new ProductEntity(itemElement["itemCode"].Value(), diff --git a/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml b/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml index 04f5d38..9d4fbc5 100644 --- a/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml +++ b/UserInterface/Dialogs/DirectAddAccountDialog/DirectAddAccountDialogUserControl.xaml @@ -81,12 +81,12 @@ Text="{Binding ShopType}" Style="{StaticResource MaterialDesignFloatingHintTextBox}"/> @@ -100,8 +100,7 @@ -