diff --git a/BBWYB.Client/APIServices/BaseApiService.cs b/BBWYB.Client/APIServices/BaseApiService.cs index 2234c1f..747db0f 100644 --- a/BBWYB.Client/APIServices/BaseApiService.cs +++ b/BBWYB.Client/APIServices/BaseApiService.cs @@ -1,11 +1,10 @@ -using BBWY.Common.Http; -using BBWY.Common.Models; +using BBWYB.Common.Http; +using BBWYB.Common.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; -using Microsoft.Extensions.Configuration; -namespace BBWY.Client.APIServices +namespace BBWYB.Client.APIServices { public class BaseApiService { diff --git a/BBWYB.Client/APIServices/MdsApiService.cs b/BBWYB.Client/APIServices/MdsApiService.cs index cbbe17b..11940be 100644 --- a/BBWYB.Client/APIServices/MdsApiService.cs +++ b/BBWYB.Client/APIServices/MdsApiService.cs @@ -1,13 +1,13 @@ using BBWYB.Client.Models; -using BBWY.Common.Http; -using BBWY.Common.Models; +using BBWYB.Common.Http; +using BBWYB.Common.Models; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; -namespace BBWY.Client.APIServices +namespace BBWYB.Client.APIServices { public class MdsApiService : BaseApiService, IDenpendency { diff --git a/BBWYB.Client/APIServices/OneBoundAPIService.cs b/BBWYB.Client/APIServices/OneBoundAPIService.cs deleted file mode 100644 index d88d80f..0000000 --- a/BBWYB.Client/APIServices/OneBoundAPIService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using BBWY.Common.Http; -using BBWY.Common.Models; -using Newtonsoft.Json.Linq; -using System; -using System.Net.Http; - -namespace BBWY.Client.APIServices -{ - public class OneBoundAPIService : IDenpendency - { - private RestApiService restApiService; - private string key = "t5060712539"; - private string secret = "20211103"; - - public OneBoundAPIService(RestApiService restApiService) - { - this.restApiService = restApiService; - } - - /// - /// 产品详细信息接口 - /// - /// 1699/jd/taobao 更多值参阅https://open.onebound.cn/help/api/ - /// - /// - /// - /// - public ApiResponse GetProductInfo(string platform, string productId) - { - try - { - //https://api-gw.onebound.cn/1688/item_get/key=t5060712539&secret=20211103&num_iid=649560646832&lang=zh-CN&cache=no - var result = restApiService.SendRequest("https://api-gw.onebound.cn/", $"{platform}/item_get", $"key={key}&secret={secret}&num_iid={productId}&lang=zh-CN&cache=no", null, HttpMethod.Get, paramPosition: ParamPosition.Query, enableRandomTimeStamp: true); - if (result.StatusCode != System.Net.HttpStatusCode.OK) - throw new Exception($"{result.StatusCode} {result.Content}"); - - var j = JObject.Parse(result.Content); - return new ApiResponse() - { - Data = j, - Code = j.Value("error_code") == "0000" ? 200 : 0, - Msg = j.Value("error") - }; - } - catch (Exception ex) - { - return ApiResponse.Error(0, ex.Message); - } - } - } -} diff --git a/BBWYB.Client/APIServices/ProductService.cs b/BBWYB.Client/APIServices/ProductService.cs index 9bcb591..0de5eb7 100644 --- a/BBWYB.Client/APIServices/ProductService.cs +++ b/BBWYB.Client/APIServices/ProductService.cs @@ -1,10 +1,10 @@ using BBWYB.Client.Models; -using BBWY.Common.Http; -using BBWY.Common.Models; +using BBWYB.Common.Http; +using BBWYB.Common.Models; using System.Collections.Generic; using System.Net.Http; -namespace BBWY.Client.APIServices +namespace BBWYB.Client.APIServices { public class ProductService : BaseApiService, IDenpendency { diff --git a/BBWYB.Client/APIServices/PurchaseOrderService.cs b/BBWYB.Client/APIServices/PurchaseOrderService.cs deleted file mode 100644 index 7ba0ffa..0000000 --- a/BBWYB.Client/APIServices/PurchaseOrderService.cs +++ /dev/null @@ -1,166 +0,0 @@ -using BBWYB.Client.Models; -using BBWY.Common.Http; -using BBWY.Common.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; - -namespace BBWY.Client.APIServices -{ - public class PurchaseOrderService : BaseApiService, IDenpendency - { - public PurchaseOrderService(RestApiService restApiService, GlobalContext globalContext) : base(restApiService, globalContext) - { - - } - - public ApiResponse AddPurchaseOrder(PurchaseOrder purchaseOrder) - { - return SendRequest(globalContext.BBYWApiHost, - "api/PurchaseOrder/AddPurchaseOrder", - purchaseOrder, - null, - HttpMethod.Post); - } - - public ApiResponse EditPurchaseOrder(PurchaseOrder purchaseOrder) - { - return SendRequest(globalContext.BBYWApiHost, - "api/PurchaseOrder/EditPurchaseOrder", - purchaseOrder, - null, - HttpMethod.Put); - } - - public ApiResponse> GetList(IList skuIdList, StorageType storageType, long shopId) - { - return SendRequest>(globalContext.BBYWApiHost, - "api/PurchaseOrder/GetList", - new { SkuIdList = skuIdList, StorageType = storageType, ShopId = shopId }, - null, - HttpMethod.Post); - } - - public ApiResponse DeletePurchaseOrder(long id) - { - return SendRequest(globalContext.BBYWApiHost, - $"api/purchaseOrder/deletePurchaseOrder/{id}", - null, - null, - HttpMethod.Delete); - } - - /// - /// 预览订单 - /// - /// - /// - /// - public ApiResponse PreviewPurchaseOrder(Consignee consignee, IList purchaseSchemeProductSkuList, Platform purchasePlatform, PurchaseAccount purchaseAccount, PurchaseOrderMode purchaseOrderMode) - { - return SendRequest(globalContext.BBYWApiHost, "api/purchaseOrder/PreviewPurchaseOrder", new - { - purchaseOrderMode, - consignee, - CargoParamList = purchaseSchemeProductSkuList.Select(sku => new - { - ProductId = sku.PurchaseProductId, - SkuId = sku.PurchaseSkuId, - SpecId = sku.PurchaseSkuSpecId, - Quantity = sku.ItemTotal, - BelongSkuId = sku.SkuId - }), - Platform = purchasePlatform, - AppKey = purchaseAccount.AppKey, - AppSecret = purchaseAccount.AppSecret, - AppToken = purchaseAccount.AppToken, - SaveResponseLog = true - }, null, HttpMethod.Post); - } - - /// - /// 创建采购单 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public ApiResponse FastCreateOrder(Consignee consignee, - IList purchaseSchemeProductSkuList, - Platform purchasePlatform, - PurchaseAccount purchaseAccount, - PurchaseOrderMode purchaseOrderMode, - string tradeMode, - string remark, - string orderId, - long shopId, - long purchaseAccountId, - string buyerAccount, - string sellerAccount, - string purchaserId, - decimal platformCommissionRatio, - string extensions) - { - return SendRequest(globalContext.BBYWApiHost, "api/purchaseOrder/NewFastCreateOrder", new - { - purchaseOrderMode, - consignee, - CargoParamList = purchaseSchemeProductSkuList.Select(sku => new - { - ProductId = sku.PurchaseProductId, - SkuId = sku.PurchaseSkuId, - SpecId = sku.PurchaseSkuSpecId, - Quantity = sku.ItemTotal, - BelongSkuId = sku.SkuId - }), - Platform = purchasePlatform, - AppKey = purchaseAccount.AppKey, - AppSecret = purchaseAccount.AppSecret, - AppToken = purchaseAccount.AppToken, - SaveResponseLog = true, - tradeMode, - remark, - orderId, - shopId, - purchaseAccountId, - buyerAccount, - sellerAccount, - purchaserId, - platformCommissionRatio, - extensions - }, null, HttpMethod.Post); - } - - - - /// - /// 查询审核采购单 - /// - /// - /// - /// - /// - public ApiResponse> GetAuditPurchaseOrderList(IList shopIdList, DateTime startDate, DateTime endDate) - { - return SendRequest>(globalContext.BBYWApiHost, "Api/PurchaseOrder/GetAuditPurchaseOrderList", new - { - startDate, - endDate, - shopIdList - }, null, HttpMethod.Post); - } - } -} diff --git a/BBWYB.Client/APIServices/PurchaseProductAPIService.cs b/BBWYB.Client/APIServices/PurchaseProductAPIService.cs index bbc55ea..f3ddb57 100644 --- a/BBWYB.Client/APIServices/PurchaseProductAPIService.cs +++ b/BBWYB.Client/APIServices/PurchaseProductAPIService.cs @@ -1,13 +1,17 @@ -using BBWY.Common.Http; -using BBWY.Common.Models; +using BBWY.Client.Extensions; +using BBWYB.Client.Extensions; +using BBWYB.Client.Models; +using BBWYB.Common.Http; +using BBWYB.Common.Models; using Microsoft.Extensions.Caching.Memory; +using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; -namespace BBWY.Client.APIServices +namespace BBWYB.Client.APIServices { public class PurchaseProductAPIService : IDenpendency { @@ -16,8 +20,8 @@ namespace BBWY.Client.APIServices private string oneBoundKey = "t5060712539"; private string oneBoundSecret = "20211103"; - private string qtAppId = "BBWY2023022001"; - private string qtAppSecret = "908e131365d5448ca651ba20ed7ddefe"; + //private string qtAppId = "BBWY2023022001"; + //private string qtAppSecret = "908e131365d5448ca651ba20ed7ddefe"; private TimeSpan purchaseProductCacheTimeSpan; //private TimeSpan _1688SessionIdTimeSpan; @@ -151,8 +155,8 @@ namespace BBWY.Client.APIServices { case Platform.阿里巴巴: return LoadFrom1688Spider(platform, productId, skuId, purchaseProductId, priceMode); - case Platform.拳探: - return LoadFromQTSpider(platform, productId, skuId, purchaseProductId, priceMode); + //case Platform.拳探: + // return LoadFromQTSpider(platform, productId, skuId, purchaseProductId, priceMode); } return null; } @@ -245,34 +249,34 @@ namespace BBWY.Client.APIServices } } - private (Purchaser purchaser, IList purchaseSchemeProductSkus)? LoadFromQTSpider(Platform platform, string productId, string skuId, string purchaseProductId, PurchaseOrderMode priceMode) - { - try - { - var response = quanTanProductClient.GetProductInfo(purchaseProductId, qtAppId, qtAppSecret); - if (response.Status != 200) - return null; - return (new Purchaser() - { - Id = response.Data.Supplier.VenderId, - Name = response.Data.Supplier.VerdenName, - Location = response.Data.Supplier.Location - }, response.Data.ProductSku.Select(qtsku => new PurchaseSchemeProductSku() - { - ProductId = productId, - SkuId = skuId, - PurchaseProductId = purchaseProductId, - Price = qtsku.Price, - Title = qtsku.Title, - PurchaseSkuId = qtsku.SkuId, - PurchaseSkuSpecId = string.Empty, - Logo = qtsku.Logo - }).ToList()); - } - catch - { - return null; - } - } + //private (Purchaser purchaser, IList purchaseSchemeProductSkus)? LoadFromQTSpider(Platform platform, string productId, string skuId, string purchaseProductId, PurchaseOrderMode priceMode) + //{ + // try + // { + // var response = quanTanProductClient.GetProductInfo(purchaseProductId, qtAppId, qtAppSecret); + // if (response.Status != 200) + // return null; + // return (new Purchaser() + // { + // Id = response.Data.Supplier.VenderId, + // Name = response.Data.Supplier.VerdenName, + // Location = response.Data.Supplier.Location + // }, response.Data.ProductSku.Select(qtsku => new PurchaseSchemeProductSku() + // { + // ProductId = productId, + // SkuId = skuId, + // PurchaseProductId = purchaseProductId, + // Price = qtsku.Price, + // Title = qtsku.Title, + // PurchaseSkuId = qtsku.SkuId, + // PurchaseSkuSpecId = string.Empty, + // Logo = qtsku.Logo + // }).ToList()); + // } + // catch + // { + // return null; + // } + //} } } diff --git a/BBWYB.Client/APIServices/PurchaseService.cs b/BBWYB.Client/APIServices/PurchaseService.cs index 80d980d..a215106 100644 --- a/BBWYB.Client/APIServices/PurchaseService.cs +++ b/BBWYB.Client/APIServices/PurchaseService.cs @@ -1,10 +1,10 @@ using BBWYB.Client.Models; -using BBWY.Common.Http; -using BBWY.Common.Models; +using BBWYB.Common.Http; +using BBWYB.Common.Models; using System.Collections.Generic; using System.Net.Http; -namespace BBWY.Client.APIServices +namespace BBWYB.Client.APIServices { public class PurchaseService : BaseApiService, IDenpendency { diff --git a/BBWYB.Client/APIServices/ShopService.cs b/BBWYB.Client/APIServices/ShopService.cs deleted file mode 100644 index e50a002..0000000 --- a/BBWYB.Client/APIServices/ShopService.cs +++ /dev/null @@ -1,91 +0,0 @@ -using BBWYB.Client.Models; -using BBWY.Common.Http; -using BBWY.Common.Models; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; - -namespace BBWY.Client.APIServices -{ - public class ShopService : BaseApiService, IDenpendency - { - public ShopService(RestApiService restApiService, GlobalContext globalContext) : base(restApiService, globalContext) { } - - public ApiResponse SaveShopSetting(long shopId, - string managerPwd, - decimal platformCommissionRatio, - PurchaseAccount purchaseAccount, - string dingDingWebHook, - string dingDingKey, - int skuSafeTurnoverDays, - string siNanDingDingWebHook, - string siNanDingDingKey, - int siNanPolicyLevel) - { - return SendRequest(globalContext.BBYWApiHost, "api/vender/SaveShopSetting", new - { - shopId, - managerPwd, - platformCommissionRatio, - PurchaseAccountId = purchaseAccount.Id, - purchaseAccount.AccountName, - purchaseAccount.AppKey, - purchaseAccount.AppSecret, - purchaseAccount.AppToken, - purchaseAccount.PurchasePlatformId, - dingDingWebHook, - dingDingKey, - skuSafeTurnoverDays, - siNanDingDingWebHook, - siNanDingDingKey, - siNanPolicyLevel - }, null, HttpMethod.Post); - } - - /// - /// 根据订单Id查询归属店铺 - /// - /// - /// - public ApiResponse> GetOrderBelongShop(IList orderIdList) - { - return SendRequest>(globalContext.BBYWApiHost, "api/order/GetOrderBelongShop", orderIdList, null, HttpMethod.Post); - } - - /// - /// 获取部门及下属店铺 - /// - /// - public ApiResponse> GetDepartmentList() - { - return SendRequest>(globalContext.BBYWApiHost, "api/vender/GetDeparmentList", null, - new Dictionary() - { - { "bbwyTempKey", "21jfhayu27q" } - }, HttpMethod.Get); - } - - public ApiResponse> GetShopListByIds(IList shopIds) - { - return SendRequest>(globalContext.BBYWApiHost, "api/vender/GetShopListByShopIds", new - { - shopIds - }, new Dictionary() - { - { "bbwyTempKey", "21jfhayu27q" } - }, HttpMethod.Post); - } - - public ApiResponse> GetServiceGroupList() - { - return SendRequest>(globalContext.BBYWApiHost, "api/vender/GetServiceGroupList", new - { - globalContext.User.Shop.Platform, - globalContext.User.Shop.AppKey, - globalContext.User.Shop.AppSecret, - globalContext.User.Shop.AppToken, - }, null, HttpMethod.Post); - } - } -} diff --git a/BBWYB.Client/App.xaml b/BBWYB.Client/App.xaml index 692fc99..7e71157 100644 --- a/BBWYB.Client/App.xaml +++ b/BBWYB.Client/App.xaml @@ -2,8 +2,26 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BBWYB.Client" - StartupUri="MainWindow.xaml"> + xmlns:vm="clr-namespace:BBWYB.Client.ViewModels" + xmlns:ctr="clr-namespace:BBWYB.Client.Converters" + StartupUri="/Views/MainWindow.xaml" + ShutdownMode="OnExplicitShutdown"> - + + + + + + + + + + + + + + + + diff --git a/BBWYB.Client/App.xaml.cs b/BBWYB.Client/App.xaml.cs index a689af0..2fe17b6 100644 --- a/BBWYB.Client/App.xaml.cs +++ b/BBWYB.Client/App.xaml.cs @@ -1,10 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Linq; +using BBWYB.Client.Helpers; +using BBWYB.Client.Models; +using BBWYB.Common.Extensions; +using BBWYB.Common.Http; +using BBWYB.Common.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.IO; +using System.Net.Http; +using System.Reflection; using System.Threading.Tasks; using System.Windows; +using System.Windows.Threading; namespace BBWYB.Client { @@ -13,5 +20,93 @@ namespace BBWYB.Client /// public partial class App : Application { + public IServiceProvider ServiceProvider { get; private set; } + public IConfiguration Configuration { get; private set; } + + + protected override void OnStartup(StartupEventArgs e) + { + var gl = new GlobalContext(); + string userToken = string.Empty; + +#if DEBUG + //齐越山鸡 + //userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNTM1MzMwMzI4ODkyMTQ5NzYwIiwidGVhbUlkIjoiMTUxNjk3NDI1MDU0MjUwMTg4OCIsInNvblRlYW1JZHMiOiIxNDM2Mjg4NTAwMjM1MjQzNTIwIiwiZXhwIjoxNjk0NjY5NjkxfQ.cSwro-7bGwOu92YejH9JhMenTai7Mvf99i2paQCmxIw"; + + //拳探店铺 测试002 + userToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMzk1NzA4MjA4NjU1MzcyMjg4IiwidGVhbUlkIjoiMTYyMDM0NDE0MDg1MDAwODA2NCIsInNvblRlYW1JZHMiOiIiLCJleHAiOjE3MDk5ODUwOTB9.v9iMB4kSpiYvHoPK3WSaOn5GE7bIUhO7266yowvxjfU"; +#else + + var tokenResult = ReadMMF(); + if (tokenResult.isOk) + userToken = tokenResult.content; + else + { + MessageBox.Show($"读取内存数据失败\r\n{tokenResult.content}", "提示"); + Environment.Exit(0); + } +#endif + gl.UserToken = userToken; + + #region 注册全局异常 + this.DispatcherUnhandledException += App_DispatcherUnhandledException; ; + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; ; + TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; ; + #endregion + + + var applicationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + var builder = new ConfigurationBuilder().SetBasePath(applicationPath).AddJsonFile("appsettings.json", false, true); + Configuration = builder.Build(); + gl.BBYWApiHost = Configuration.GetSection("BBWYApiHost").Value; + gl.MDSApiHost = Configuration.GetSection("MDSApiHost").Value; + + IServiceCollection serviceCollection = new ServiceCollection(); + serviceCollection.AddHttpClient(); + serviceCollection.AddHttpClient("gzip").ConfigurePrimaryHttpMessageHandler(handler => new HttpClientHandler() + { + AutomaticDecompression = System.Net.DecompressionMethods.GZip + }); + + serviceCollection.AddMemoryCache(); + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(gl); + serviceCollection.BatchRegisterServices(new Assembly[] { Assembly.Load("BBWYB.Client") }, typeof(IDenpendency)); + serviceCollection.AddMapper(new MappingProfile()); + ServiceProvider = serviceCollection.BuildServiceProvider(); + base.OnStartup(e); + } + + private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) + { + throw new NotImplementedException(); + } + + private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + throw new NotImplementedException(); + } + + private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + throw new NotImplementedException(); + } + + public (bool isOk, string content) ReadMMF() + { + + try + { + var token = MemoryHelper.GetMemoryToken(); + if (string.IsNullOrEmpty(token)) + return (false, "token为空"); + else + return (true, token); + } + catch (Exception ex) + { + return (false, ex.Message); + } + } } } diff --git a/BBWYB.Client/BBWYB.Client.csproj b/BBWYB.Client/BBWYB.Client.csproj index d4fc390..a1d3c3e 100644 --- a/BBWYB.Client/BBWYB.Client.csproj +++ b/BBWYB.Client/BBWYB.Client.csproj @@ -8,12 +8,27 @@ + + + PreserveNewest + + + + + + + + + + + + @@ -25,8 +40,4 @@ - - - - diff --git a/BBWYB.Client/Converters/EnumToBooleanConverter.cs b/BBWYB.Client/Converters/EnumToBooleanConverter.cs new file mode 100644 index 0000000..f70fb2e --- /dev/null +++ b/BBWYB.Client/Converters/EnumToBooleanConverter.cs @@ -0,0 +1,21 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + public class EnumToBooleanConverter : IValueConverter + { + /// + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value == null ? false : value.Equals(parameter); + } + + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return value != null && value.Equals(true) ? parameter : Binding.DoNothing; + } + } +} diff --git a/BBWYB.Client/Converters/InputNumberConverter.cs b/BBWYB.Client/Converters/InputNumberConverter.cs new file mode 100644 index 0000000..d982618 --- /dev/null +++ b/BBWYB.Client/Converters/InputNumberConverter.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + public class InputNumberConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + string strValue = value as string; + if (string.IsNullOrEmpty(strValue)) + return null; + decimal result; + if (strValue.IndexOf('.') == strValue.Length - 1 || !decimal.TryParse(strValue, out result)) + return DependencyProperty.UnsetValue; + return result; + } + } +} diff --git a/BBWYB.Client/Converters/ItemHeightConverter.cs b/BBWYB.Client/Converters/ItemHeightConverter.cs new file mode 100644 index 0000000..f758acf --- /dev/null +++ b/BBWYB.Client/Converters/ItemHeightConverter.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + public class ItemHeightConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + int.TryParse(value.ToString(), out int itemCount); + int.TryParse(parameter.ToString(), out int itemHeight); + return itemCount * itemHeight; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/BBWYB.Client/Converters/MultiObjectConverter.cs b/BBWYB.Client/Converters/MultiObjectConverter.cs new file mode 100644 index 0000000..1f613d8 --- /dev/null +++ b/BBWYB.Client/Converters/MultiObjectConverter.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Data; +using System.Windows.Media; + +namespace BBWYB.Client.Converters +{ + public class MultiObjectConverter : IMultiValueConverter + { + /// + /// 多值转换器 + /// + /// 参数值数组 + /// + /// 参数 + /// 各组比较值:比较条件(&或|):true返回值:false返回值:返回值类型枚举 + /// v1;v2-1|v2-2;v3:&:Visible:Collapsed:1 + /// + /// + public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) + { + string[] param = parameter.ToString().ToLower().Split(':'); //将参数字符串分段 + string[] compareValues = param[0].Split(';'); //将比较值段分割为数组 + if (values.Length != compareValues.Length) //比较源数据和比较参数个数是否一致 + return ConvertValue(param[3], param[4]); + var trueCount = 0; //满足条件的结果数量 + var currentValue = string.Empty; + IList currentParamArray = null; + for (var i = 0; i < values.Length; i++) + { + currentValue = values[i] != null ? values[i].ToString().ToLower() : string.Empty; + if (compareValues[i].Contains("|")) + { + //当前比较值段包含多个比较值 + currentParamArray = compareValues[i].Split('|'); + trueCount += currentParamArray.Contains(currentValue) ? 1 : 0; //满足条件,结果+1 + } + else + { + trueCount += compareValues[i].Equals(currentValue) ? 1 : 0; //满足条件,结果+1 + } + } + currentParamArray = null; + currentValue = string.Empty; + var compareResult = param[1].Equals("&") ? + trueCount == values.Length : + trueCount > 0; //判断比较结果 + return ConvertValue(compareResult ? param[2] : param[3], param[4]); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) + { + throw new NotImplementedException(); + } + + private object ConvertValue(string result, string enumStr) + { + var convertResult = (ConvertResult)int.Parse(enumStr); + if (convertResult == ConvertResult.显示类型) + return result.Equals("collapsed") ? Visibility.Collapsed : Visibility.Visible; + if (convertResult == ConvertResult.布尔类型) + return System.Convert.ToBoolean(result); + if (convertResult == ConvertResult.画刷类型) + return new SolidColorBrush((Color)ColorConverter.ConvertFromString(result)); + return null; //后续自行扩展 + } + + private enum ConvertResult + { + 显示类型 = 1, + 布尔类型 = 2, + 字符串类型 = 3, + 整型 = 4, + 小数型 = 5, + 画刷类型 = 6, + 样式类型 = 7, + 模板类型 = 8 + } + } +} diff --git a/BBWYB.Client/Converters/MultiParameterTransferConverter.cs b/BBWYB.Client/Converters/MultiParameterTransferConverter.cs new file mode 100644 index 0000000..8694f7d --- /dev/null +++ b/BBWYB.Client/Converters/MultiParameterTransferConverter.cs @@ -0,0 +1,22 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + /// + /// Command多参数传递类 + /// + public class MultiParameterTransferConverter : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + return values.Clone(); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/BBWYB.Client/Converters/ObjectConverter.cs b/BBWYB.Client/Converters/ObjectConverter.cs new file mode 100644 index 0000000..3f1df4f --- /dev/null +++ b/BBWYB.Client/Converters/ObjectConverter.cs @@ -0,0 +1,55 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + public class ObjectConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + string[] parray = parameter.ToString().ToLower().Split(':'); + string valueStr = value == null ? string.Empty : value.ToString().ToLower(); + string returnValue = string.Empty; + try + { + if (string.IsNullOrEmpty(valueStr)) + { + returnValue = parray[0].Contains("#null") ? parray[1] : parray[2]; + } + else if (parray[0].Contains("|")) + { + returnValue = parray[0].Split('|').Contains(valueStr) ? parray[1] : parray[2]; + } + else + { + returnValue = parray[0].Equals(valueStr) ? parray[1] : parray[2]; + } + if (returnValue.Equals("#source", StringComparison.CurrentCultureIgnoreCase)) + return value; + return returnValue; + } + catch (Exception ex) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"ObjectConverter {ex.Message} {parameter}"); + Console.ResetColor(); + } + return parray[2]; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + var returnValue = "otherValue"; + string[] parray = parameter.ToString().ToLower().Split(':'); + if (value == null) + return returnValue; + var valueStr = value.ToString().ToLower(); + if (valueStr != parray[1]) + return returnValue; + else + return parray[0].Contains('|') ? parray[0].Split('|')[0] : parray[0]; + } + } +} diff --git a/BBWYB.Client/Converters/ProfitRatioConverter.cs b/BBWYB.Client/Converters/ProfitRatioConverter.cs new file mode 100644 index 0000000..b15932d --- /dev/null +++ b/BBWYB.Client/Converters/ProfitRatioConverter.cs @@ -0,0 +1,21 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + public class ProfitRatioConverter : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + decimal.TryParse(values[0]?.ToString(), out decimal profit); + decimal.TryParse(values[1]?.ToString(), out decimal totalCost); + return totalCost == 0 ? "0" : Math.Round(profit / totalCost * 100, 2).ToString(); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/BBWYB.Client/Converters/SaleGrossProfitConverter.cs b/BBWYB.Client/Converters/SaleGrossProfitConverter.cs new file mode 100644 index 0000000..da5a805 --- /dev/null +++ b/BBWYB.Client/Converters/SaleGrossProfitConverter.cs @@ -0,0 +1,25 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + /// + /// 销售毛利率转换器 + /// + public class SaleGrossProfitConverter : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + decimal.TryParse(values[0]?.ToString(), out decimal profit); + decimal.TryParse(values[1]?.ToString(), out decimal actualAmount); + + return $"{(actualAmount == 0 ? 0M : Math.Round(profit / actualAmount * 100, 2))}%"; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/BBWYB.Client/Converters/WidthConveter.cs b/BBWYB.Client/Converters/WidthConveter.cs new file mode 100644 index 0000000..81c94a8 --- /dev/null +++ b/BBWYB.Client/Converters/WidthConveter.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace BBWYB.Client.Converters +{ + public class WidthConveter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is double) + { + double.TryParse(parameter?.ToString(), out double p); + var width = (double)value; + if (width == 0) + return 0; + return width - p; + } + return 0; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/BBWYB.Client/Extensions/CopyExtensions.cs b/BBWYB.Client/Extensions/CopyExtensions.cs new file mode 100644 index 0000000..7633981 --- /dev/null +++ b/BBWYB.Client/Extensions/CopyExtensions.cs @@ -0,0 +1,12 @@ +using Newtonsoft.Json; + +namespace BBWYB.Client.Extensions +{ + public static class CopyExtensions + { + public static T Copy(this T p) + { + return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(p)); + } + } +} diff --git a/BBWYB.Client/Extensions/EncryptionExtension.cs b/BBWYB.Client/Extensions/EncryptionExtension.cs new file mode 100644 index 0000000..8154d6a --- /dev/null +++ b/BBWYB.Client/Extensions/EncryptionExtension.cs @@ -0,0 +1,85 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace BBWY.Client.Extensions +{ + public static class EncryptionExtension + { + + public static string Md5Encrypt(this string originStr) + { + using (var md5 = MD5.Create()) + { + return string.Join(string.Empty, md5.ComputeHash(Encoding.UTF8.GetBytes(originStr)).Select(x => x.ToString("x2"))); + } + } + + //AES加密 传入,要加密的串和, 解密key + public static string AESEncrypt(this string input) + { + var key = "dataplatform2019"; + var ivStr = "1012132405963708"; + + var encryptKey = Encoding.UTF8.GetBytes(key); + var iv = Encoding.UTF8.GetBytes(ivStr); //偏移量,最小为16 + using (var aesAlg = Aes.Create()) + { + using (var encryptor = aesAlg.CreateEncryptor(encryptKey, iv)) + { + using (var msEncrypt = new MemoryStream()) + { + using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, + CryptoStreamMode.Write)) + + using (var swEncrypt = new StreamWriter(csEncrypt)) + { + swEncrypt.Write(input); + } + var decryptedContent = msEncrypt.ToArray(); + + return Convert.ToBase64String(decryptedContent); + } + } + } + } + + public static string AESDecrypt(this string cipherText) + { + var fullCipher = Convert.FromBase64String(cipherText); + + var ivStr = "1012132405963708"; + var key = "dataplatform2019"; + + var iv = Encoding.UTF8.GetBytes(ivStr); + var decryptKey = Encoding.UTF8.GetBytes(key); + + using (var aesAlg = Aes.Create()) + { + using (var decryptor = aesAlg.CreateDecryptor(decryptKey, iv)) + { + string result; + using (var msDecrypt = new MemoryStream(fullCipher)) + { + using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + { + using (var srDecrypt = new StreamReader(csDecrypt)) + { + result = srDecrypt.ReadToEnd(); + } + } + } + + return result; + } + } + } + + public static string Base64Encrypt(this string originStr) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(originStr)); + } + } +} diff --git a/BBWYB.Client/GlobalContext.cs b/BBWYB.Client/GlobalContext.cs index cdd8079..613328e 100644 --- a/BBWYB.Client/GlobalContext.cs +++ b/BBWYB.Client/GlobalContext.cs @@ -1,9 +1,10 @@ using BBWYB.Client.Models; +using CommunityToolkit.Mvvm.ComponentModel; using System.Collections.Generic; namespace BBWYB.Client { - public class GlobalContext : NotifyObject + public class GlobalContext : ObservableObject { public GlobalContext() { @@ -11,7 +12,7 @@ namespace BBWYB.Client private User user; - public User User { get => user; set { Set(ref user, value); } } + public User User { get => user; set { SetProperty(ref user, value); } } public string UserToken { get; set; } diff --git a/BBWYB.Client/Helpers/MemoryHelper.cs b/BBWYB.Client/Helpers/MemoryHelper.cs new file mode 100644 index 0000000..d2cce08 --- /dev/null +++ b/BBWYB.Client/Helpers/MemoryHelper.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using System.IO.Pipes; + +namespace BBWYB.Client.Helpers +{ + public class MemoryHelper + { + /// + /// 获取token + /// + /// + public static string GetMemoryToken() + { + try + { + string pipeId = Environment.GetCommandLineArgs()[1]; + //创建输入类型匿名管道 + using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, pipeId)) + { + using (StreamReader sr = new StreamReader(pipeClient)) + { + string temp; + + do + { + temp = sr.ReadLine(); + } + while (!temp.StartsWith("SYNC")); + + + while ((temp = sr.ReadLine()) != null) + { + return temp; + } + } + } + + return string.Empty; + } + catch (Exception ex) + { + return string.Empty; + } + + } + + } +} diff --git a/BBWYB.Client/Helpers/ShellExecuteHelper.cs b/BBWYB.Client/Helpers/ShellExecuteHelper.cs new file mode 100644 index 0000000..642914e --- /dev/null +++ b/BBWYB.Client/Helpers/ShellExecuteHelper.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.InteropServices; + +namespace BBWYB.Client.Helpers +{ + public class ShellExecuteHelper + { + public enum ShowCommands : int + { + SW_HIDE = 0, + SW_SHOWNORMAL = 1, + SW_NORMAL = 1, + SW_SHOWMINIMIZED = 2, + SW_SHOWMAXIMIZED = 3, + SW_MAXIMIZE = 3, + SW_SHOWNOACTIVATE = 4, + SW_SHOW = 5, + SW_MINIMIZE = 6, + SW_SHOWMINNOACTIVE = 7, + SW_SHOWNA = 8, + SW_RESTORE = 9, + SW_SHOWDEFAULT = 10, + SW_FORCEMINIMIZE = 11, + SW_MAX = 11 + } + + [DllImport("shell32.dll")] + public static extern IntPtr ShellExecute( + IntPtr hwnd, + string lpOperation, + string lpFile, + string lpParameters, + string lpDirectory, + ShowCommands nShowCmd); + } +} diff --git a/BBWYB.Client/Models/KVModel.cs b/BBWYB.Client/Models/KVModel.cs index 6fec62d..18a88de 100644 --- a/BBWYB.Client/Models/KVModel.cs +++ b/BBWYB.Client/Models/KVModel.cs @@ -1,6 +1,8 @@ -namespace BBWYB.Client.Models +using CommunityToolkit.Mvvm.ComponentModel; + +namespace BBWYB.Client.Models { - public class KVModel : NotifyObject + public class KVModel : ObservableObject { public string Key { get; set; } diff --git a/BBWYB.Client/Models/MappingProfile.cs b/BBWYB.Client/Models/MappingProfile.cs index 4cffcec..47349b3 100644 --- a/BBWYB.Client/Models/MappingProfile.cs +++ b/BBWYB.Client/Models/MappingProfile.cs @@ -6,15 +6,7 @@ namespace BBWYB.Client.Models { public MappingProfile() { - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap().ForMember(t => t.ProductItemNum, opt => opt.MapFrom(f => f.ProductNo)); - CreateMap(); + CreateMap().ForMember(t => t.TeamId, opt => opt.MapFrom(f => f.DepartmentId)) .ForMember(t => t.TeamName, opt => opt.MapFrom(f => f.DepartmentName)) .ForMember(t => t.Name, opt => opt.MapFrom(f => f.UserName)); @@ -26,10 +18,6 @@ namespace BBWYB.Client.Models CreateMap(); CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); } } } diff --git a/BBWYB.Client/Models/MenuModel.cs b/BBWYB.Client/Models/MenuModel.cs index 183bd35..dd22312 100644 --- a/BBWYB.Client/Models/MenuModel.cs +++ b/BBWYB.Client/Models/MenuModel.cs @@ -1,12 +1,13 @@ -using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; +using System.Collections.Generic; namespace BBWYB.Client.Models { - public class MenuModel : NotifyObject + public class MenuModel : ObservableObject { private bool isSelected; - public bool IsSelected { get => isSelected; set { Set(ref isSelected, value); } } + public bool IsSelected { get => isSelected; set { SetProperty(ref isSelected, value); } } public string Name { get; set; } diff --git a/BBWYB.Client/Models/NotifyObject.cs b/BBWYB.Client/Models/NotifyObject.cs deleted file mode 100644 index d5f6861..0000000 --- a/BBWYB.Client/Models/NotifyObject.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.ComponentModel; -using System.Runtime.CompilerServices; - -namespace BBWYB.Client.Models -{ - public class NotifyObject : INotifyPropertyChanged - { - public event PropertyChangedEventHandler PropertyChanged; - protected void OnPropertyChanged([CallerMemberName]string propertyName = "") - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - protected bool Set(ref T oldValue, T newValue, [CallerMemberName]string propertyName = "") - { - if (Equals(oldValue, newValue)) - return false; - oldValue = newValue; - OnPropertyChanged(propertyName); - return true; - } - } -} diff --git a/BBWYB.Client/Models/Product/Product.cs b/BBWYB.Client/Models/Product/Product.cs index 96f32ad..d2d0542 100644 --- a/BBWYB.Client/Models/Product/Product.cs +++ b/BBWYB.Client/Models/Product/Product.cs @@ -1,9 +1,10 @@ -using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; +using System.Collections.Generic; using System.Collections.ObjectModel; namespace BBWYB.Client.Models { - public class Product : NotifyObject + public class Product : ObservableObject { public Product() { @@ -49,7 +50,7 @@ namespace BBWYB.Client.Models public Platform SelectedPurchasePlatformModel { get => selectedPurchasePlatformModel; - set { Set(ref selectedPurchasePlatformModel, value); } + set { SetProperty(ref selectedPurchasePlatformModel, value); } } public void CreatePlatformList() diff --git a/BBWYB.Client/Models/Product/ProductSku.cs b/BBWYB.Client/Models/Product/ProductSku.cs index b3e3871..3cd1590 100644 --- a/BBWYB.Client/Models/Product/ProductSku.cs +++ b/BBWYB.Client/Models/Product/ProductSku.cs @@ -1,11 +1,10 @@ -using System; +using CommunityToolkit.Mvvm.ComponentModel; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Text; namespace BBWYB.Client.Models { - public class ProductSku : NotifyObject + public class ProductSku : ObservableObject { private PurchaseScheme selectedPurchaseScheme; private StorageModel selectedStorageModel; @@ -43,13 +42,13 @@ namespace BBWYB.Client.Models public PurchaseScheme SelectedPurchaseScheme { get => selectedPurchaseScheme; - set { Set(ref selectedPurchaseScheme, value); } + set { SetProperty(ref selectedPurchaseScheme, value); } } /// /// 选中的仓储平台 /// - public StorageModel SelectedStorageModel { get => selectedStorageModel; set { Set(ref selectedStorageModel, value); } } + public StorageModel SelectedStorageModel { get => selectedStorageModel; set { SetProperty(ref selectedStorageModel, value); } } public ProductSku() { diff --git a/BBWYB.Client/Models/Product/PurchaseScheme.cs b/BBWYB.Client/Models/Product/PurchaseScheme.cs index ad77309..37307b4 100644 --- a/BBWYB.Client/Models/Product/PurchaseScheme.cs +++ b/BBWYB.Client/Models/Product/PurchaseScheme.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; +using System.Collections.Generic; using System.Collections.ObjectModel; namespace BBWYB.Client.Models @@ -6,7 +7,7 @@ namespace BBWYB.Client.Models /// /// 采购方案 /// - public class PurchaseScheme : NotifyObject + public class PurchaseScheme : ObservableObject { private decimal defaultCost; private decimal realCost; @@ -16,8 +17,8 @@ namespace BBWYB.Client.Models public string ProductId { get; set; } public string SkuId { get; set; } - public decimal DefaultCost { get => defaultCost; set { Set(ref defaultCost, value); } } - public decimal RealCost { get => realCost; set { Set(ref realCost, value); } } + public decimal DefaultCost { get => defaultCost; set { SetProperty(ref defaultCost, value); } } + public decimal RealCost { get => realCost; set { SetProperty(ref realCost, value); } } public string PurchaserId { get; set; } public string PurchaserName { get; set; } diff --git a/BBWYB.Client/Models/Product/PurchaseSchemeProduct.cs b/BBWYB.Client/Models/Product/PurchaseSchemeProduct.cs index c0838b9..16bc54e 100644 --- a/BBWYB.Client/Models/Product/PurchaseSchemeProduct.cs +++ b/BBWYB.Client/Models/Product/PurchaseSchemeProduct.cs @@ -1,7 +1,6 @@ -using System; +using CommunityToolkit.Mvvm.ComponentModel; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Text; using System.Linq; namespace BBWYB.Client.Models @@ -9,7 +8,7 @@ namespace BBWYB.Client.Models /// /// 采购商品 /// - public class PurchaseSchemeProduct : NotifyObject + public class PurchaseSchemeProduct : ObservableObject { private string purchaseUrl; @@ -26,7 +25,7 @@ namespace BBWYB.Client.Models public string SkuId { get; set; } - public string PurchaseUrl { get => purchaseUrl; set { Set(ref purchaseUrl, value); } } + public string PurchaseUrl { get => purchaseUrl; set { SetProperty(ref purchaseUrl, value); } } public string PurchaseProductId { get => purchaseProductId; set => purchaseProductId = value; } public bool IsEditing @@ -35,7 +34,7 @@ namespace BBWYB.Client.Models set { SearchPurchaseSkuName = string.Empty; - Set(ref isEditing, value); + SetProperty(ref isEditing, value); } } @@ -55,7 +54,7 @@ namespace BBWYB.Client.Models public string SearchPurchaseSkuName { get => searchPurchaseSkuName; - set { Set(ref searchPurchaseSkuName, value); } + set { SetProperty(ref searchPurchaseSkuName, value); } } public PurchaseSchemeProduct() diff --git a/BBWYB.Client/Models/Product/PurchaseSchemeProductSku.cs b/BBWYB.Client/Models/Product/PurchaseSchemeProductSku.cs index 14c94cc..a17e8b7 100644 --- a/BBWYB.Client/Models/Product/PurchaseSchemeProductSku.cs +++ b/BBWYB.Client/Models/Product/PurchaseSchemeProductSku.cs @@ -1,11 +1,12 @@ -using System; +using CommunityToolkit.Mvvm.ComponentModel; +using System; namespace BBWYB.Client.Models { /// /// 采购商品的Sku /// - public class PurchaseSchemeProductSku : NotifyObject + public class PurchaseSchemeProductSku : ObservableObject { /// /// 采购商品的SKU和采购方案的关系Id @@ -13,7 +14,7 @@ namespace BBWYB.Client.Models public long Id { get; set; } private bool isSelected; - public bool IsSelected { get => isSelected; set { Set(ref isSelected, value); } } + public bool IsSelected { get => isSelected; set { SetProperty(ref isSelected, value); } } public decimal Price { get; set; } @@ -39,7 +40,7 @@ namespace BBWYB.Client.Models { get => itemTotal; set { - if (Set(ref itemTotal, value)) + if (SetProperty(ref itemTotal, value)) { SkuAmount = value * Price; OnItemTotalChanged?.Invoke(value); @@ -47,7 +48,7 @@ namespace BBWYB.Client.Models } } - public decimal SkuAmount { get => skuAmount; set { Set(ref skuAmount, value); } } + public decimal SkuAmount { get => skuAmount; set { SetProperty(ref skuAmount, value); } } private int itemTotal; private decimal skuAmount; diff --git a/BBWYB.Client/Models/Product/Purchaser.cs b/BBWYB.Client/Models/Product/Purchaser.cs index 48be4b3..9d0040d 100644 --- a/BBWYB.Client/Models/Product/Purchaser.cs +++ b/BBWYB.Client/Models/Product/Purchaser.cs @@ -1,9 +1,11 @@ -namespace BBWYB.Client.Models +using CommunityToolkit.Mvvm.ComponentModel; + +namespace BBWYB.Client.Models { /// /// 采购商 /// - public class Purchaser : NotifyObject + public class Purchaser : ObservableObject { private int skuUseCount; @@ -14,7 +16,7 @@ /// /// 使用该采购商的SKU数量 /// - public int SkuUseCount { get => skuUseCount; set { Set(ref skuUseCount, value); } } + public int SkuUseCount { get => skuUseCount; set { SetProperty(ref skuUseCount, value); } } public string ProductId { get; set; } diff --git a/BBWYB.Client/Models/PurchaseOrder/PurchaseOrder.cs b/BBWYB.Client/Models/PurchaseOrder/PurchaseOrder.cs new file mode 100644 index 0000000..08622ff --- /dev/null +++ b/BBWYB.Client/Models/PurchaseOrder/PurchaseOrder.cs @@ -0,0 +1,177 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using System; + +namespace BBWYB.Client.Models +{ + public class PurchaseOrder : ObservableObject + { + public long Id { get; set; } + public DateTime? CreateTime { get; set; } + + public string ProductId { get; set; } + + public PurchaseMethod? PurchaseMethod { get; set; } + + public string PurchaseOrderId { get; set; } + + + public Platform? PurchasePlatform { get; set; } + + + public string SkuId { get; set; } + + public StorageType? StorageType { get; set; } + + public long? UserId { get; set; } + + public bool IsEdit { get => isEdit; set { SetProperty(ref isEdit, value); } } + + /// + /// 单件均摊成本 + /// + public decimal UnitCost { get => unitCost; private set { SetProperty(ref unitCost, value); } } + + public int PurchaseQuantity + { + get => purchaseQuantity; set + { + SetProperty(ref purchaseQuantity, value); + RefreshUnitCost(); + if (IsEdit) + RemainingQuantity = value; + } + } + + public int RemainingQuantity { get => remainingQuantity; set { SetProperty(ref remainingQuantity, value); } } + + + public long ShopId { get; set; } + + /// + /// 单件发货预估运费(不参与单件均摊成本计算) + /// + public decimal SingleDeliveryFreight + { + get => singleDeliveryFreight; set { SetProperty(ref singleDeliveryFreight, value); } + } + + ///// + ///// 单间操作成本 + ///// + //public decimal SingleOperationAmount + //{ + // get => singleOperationAmount; + // set + // { + // if (SetProperty(ref singleOperationAmount, value)) + // RefreshUnitCost(); + // } + //} + + /// + /// 单件耗材成本 + /// + public decimal SingleConsumableAmount + { + get => singleConsumableAmount; + set + { + if (SetProperty(ref singleConsumableAmount, value)) + RefreshUnitCost(); + } + } + + /// + /// 单件SKU成本 + /// + public decimal SingleSkuAmount + { + get => singleSkuAmount; + set + { + if (SetProperty(ref singleSkuAmount, value)) + RefreshUnitCost(); + } + } + + /// + /// 单件采购运费 + /// + public decimal SingleFreight + { + get => singleFreight; + set + { + if (SetProperty(ref singleFreight, value)) + RefreshUnitCost(); + } + } + + /// + /// 单件头程费 + /// + public decimal SingleFirstFreight + { + get => singleFirstFreight; + set + { + if (SetProperty(ref singleFirstFreight, value)) + RefreshUnitCost(); + } + } + + /// + /// 单件仓储费 + /// + public decimal SingleStorageAmount + { + get => singleStorageAmount; + set + { + if (SetProperty(ref singleStorageAmount, value)) + RefreshUnitCost(); + } + } + + public decimal SingleInStorageAmount + { + get => singleInStorageAmount; + set + { + if (SetProperty(ref singleInStorageAmount, value)) + RefreshUnitCost(); + } + } + public decimal SingleOutStorageAmount + { + get => singleOutStorageAmount; + set + { + if (SetProperty(ref singleOutStorageAmount, value)) + RefreshUnitCost(); + } + } + + public decimal SingleRefundInStorageAmount { get => singleRefundInStorageAmount; set { SetProperty(ref singleRefundInStorageAmount, value); } } + + public void RefreshUnitCost() + { + UnitCost = SingleSkuAmount + SingleFreight + SingleFirstFreight + SingleInStorageAmount + SingleOutStorageAmount + SingleConsumableAmount + SingleStorageAmount; + } + + private bool isEdit; + private decimal unitCost; + private int purchaseQuantity; + private int remainingQuantity; + private decimal singleSkuAmount; + private decimal singleFreight; + private decimal singleFirstFreight; + private decimal singleDeliveryFreight; + //private decimal singleOperationAmount; + private decimal singleConsumableAmount; + private decimal singleStorageAmount; + private decimal singleInStorageAmount; + private decimal singleOutStorageAmount; + private decimal singleRefundInStorageAmount; + } +} diff --git a/BBWYB.Client/Models/PurchaseOrder/StorageModel.cs b/BBWYB.Client/Models/PurchaseOrder/StorageModel.cs new file mode 100644 index 0000000..2cee522 --- /dev/null +++ b/BBWYB.Client/Models/PurchaseOrder/StorageModel.cs @@ -0,0 +1,11 @@ +namespace BBWYB.Client.Models +{ + public class StorageModel + { + public string ProductId { get; set; } + + public string SkuId { get; set; } + + public StorageType StorageType { get; set; } + } +} diff --git a/BBWYB.Client/Models/Shop/Department.cs b/BBWYB.Client/Models/Shop/Department.cs index 26745c5..8959f4c 100644 --- a/BBWYB.Client/Models/Shop/Department.cs +++ b/BBWYB.Client/Models/Shop/Department.cs @@ -1,9 +1,10 @@ -using System; +using CommunityToolkit.Mvvm.ComponentModel; +using System; using System.Collections.Generic; namespace BBWYB.Client.Models { - public class Department : NotifyObject + public class Department : ObservableObject { private bool isSelected; @@ -17,7 +18,7 @@ namespace BBWYB.Client.Models get => isSelected; set { - if (Set(ref isSelected, value)) + if (SetProperty(ref isSelected, value)) OnIsSelectedChanged?.Invoke(); } } diff --git a/BBWYB.Client/Models/Shop/PurchaseAccount.cs b/BBWYB.Client/Models/Shop/PurchaseAccount.cs index 0c01ce9..d39d804 100644 --- a/BBWYB.Client/Models/Shop/PurchaseAccount.cs +++ b/BBWYB.Client/Models/Shop/PurchaseAccount.cs @@ -1,8 +1,9 @@ -using System; +using CommunityToolkit.Mvvm.ComponentModel; +using System; namespace BBWYB.Client.Models { - public class PurchaseAccount : NotifyObject,ICloneable + public class PurchaseAccount : ObservableObject,ICloneable { private string accountName; private Platform purchasePlatformId; @@ -13,11 +14,11 @@ namespace BBWYB.Client.Models public long Id { get; set; } public long ShopId { get; set; } - public string AccountName { get => accountName; set { Set(ref accountName, value); } } - public Platform PurchasePlatformId { get => purchasePlatformId; set { Set(ref purchasePlatformId, value); } } - public string AppKey { get => appKey; set { Set(ref appKey, value); } } - public string AppSecret { get => appSecret; set { Set(ref appSecret, value); } } - public string AppToken { get => appToken; set { Set(ref appToken, value); } } + public string AccountName { get => accountName; set { SetProperty(ref accountName, value); } } + public Platform PurchasePlatformId { get => purchasePlatformId; set { SetProperty(ref purchasePlatformId, value); } } + public string AppKey { get => appKey; set { SetProperty(ref appKey, value); } } + public string AppSecret { get => appSecret; set { SetProperty(ref appSecret, value); } } + public string AppToken { get => appToken; set { SetProperty(ref appToken, value); } } public object Clone() { diff --git a/BBWYB.Client/Models/Shop/Shop.cs b/BBWYB.Client/Models/Shop/Shop.cs index 03f43e9..5ca9ad8 100644 --- a/BBWYB.Client/Models/Shop/Shop.cs +++ b/BBWYB.Client/Models/Shop/Shop.cs @@ -1,13 +1,14 @@ -using System.Collections.Generic; +using CommunityToolkit.Mvvm.ComponentModel; +using System.Collections.Generic; namespace BBWYB.Client.Models { - public class Shop : NotifyObject + public class Shop : ObservableObject { private bool isSelected; private string shopName; - public bool IsSelected { get => isSelected; set { Set(ref isSelected, value); } } + public bool IsSelected { get => isSelected; set { SetProperty(ref isSelected, value); } } /// /// 店铺Id /// @@ -35,7 +36,7 @@ namespace BBWYB.Client.Models public string AppToken2 { get; set; } - public string ShopName { get => shopName; set { Set(ref shopName, value); } } + public string ShopName { get => shopName; set { SetProperty(ref shopName, value); } } public IList PurchaseAccountList { get; set; } diff --git a/BBWYB.Client/Models/User/User.cs b/BBWYB.Client/Models/User/User.cs index 149ad53..edbe32d 100644 --- a/BBWYB.Client/Models/User/User.cs +++ b/BBWYB.Client/Models/User/User.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; +using CommunityToolkit.Mvvm.ComponentModel; +using System.Collections.Generic; namespace BBWYB.Client.Models { - public class User : NotifyObject + public class User : ObservableObject { //private string name; @@ -19,7 +19,7 @@ namespace BBWYB.Client.Models public string SonDepartmentNames { get; set; } - public Shop Shop { get => shop; set { Set(ref shop, value); } } + public Shop Shop { get => shop; set { SetProperty(ref shop, value); } } public IList DepartmentList { get; set; } diff --git a/BBWYB.Client/ViewModels/BaseVM.cs b/BBWYB.Client/ViewModels/BaseVM.cs new file mode 100644 index 0000000..36dfb03 --- /dev/null +++ b/BBWYB.Client/ViewModels/BaseVM.cs @@ -0,0 +1,37 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using System; +using System.Windows.Input; +namespace BBWYB.Client.ViewModels +{ + public class BaseVM : ObservableRecipient + { + public Guid VMId { get; set; } + + public ICommand LoadCommand { get; set; } + + public ICommand UnloadCommand { get; set; } + + public BaseVM() + { + VMId = Guid.NewGuid(); + LoadCommand = new RelayCommand(Load); + UnloadCommand = new RelayCommand(Unload); + } + + public virtual void Refresh() + { + + } + + protected virtual void Load() + { + + } + + protected virtual void Unload() + { + + } + } +} diff --git a/BBWYB.Client/ViewModels/MainViewModel.cs b/BBWYB.Client/ViewModels/MainViewModel.cs new file mode 100644 index 0000000..22ba2d7 --- /dev/null +++ b/BBWYB.Client/ViewModels/MainViewModel.cs @@ -0,0 +1,245 @@ +using BBWYB.Client.APIServices; +using BBWYB.Client.Models; +using BBWYB.Client.Views.SelectShop; +using BBWYB.Common.Extensions; +using BBWYB.Common.Models; +using CommunityToolkit.Mvvm.Input; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; + +namespace BBWYB.Client.ViewModels +{ + public class MainViewModel : BaseVM, IDenpendency + { + #region Properties + private MdsApiService mdsApiService; + private MenuModel selectedMenuModel; + private bool showShopChoosePanel; + + + public GlobalContext GlobalContext { get; set; } + public IList MenuList { get; set; } + + public IList ShopList { get; set; } + + public MenuModel SelectedMenuModel + { + get => selectedMenuModel; + set + { + if (value == null) + return; + SetProperty(ref selectedMenuModel, value); + foreach (var menu in MenuList) + { + foreach (var cmenu in menu.ChildList) + { + if (!ReferenceEquals(value, cmenu)) + cmenu.IsSelected = false; + } + } + } + } + + /// + /// 是否显示店铺选择列表 + /// + public bool ShowShopChoosePanel { get => showShopChoosePanel; set { SetProperty(ref showShopChoosePanel, value); } } + #endregion + + #region Commands + public ICommand ClosingCommand { get; set; } + + //public ICommand ChooseShopCommand { get; set; } + + public ICommand OpenSelectShopCommand { get; set; } + #endregion + + #region Methods + public MainViewModel(GlobalContext globalContext, + MdsApiService mdsApiService) + { + + this.mdsApiService = mdsApiService; + ClosingCommand = new RelayCommand(Exit); + //ChooseShopCommand = new RelayCommand((s) => ChooseShop(s)); + OpenSelectShopCommand = new RelayCommand(OpenSelectShop); + this.GlobalContext = globalContext; + ShopList = new ObservableCollection(); + MenuList = new ObservableCollection() + { + + }; + Task.Factory.StartNew(Login); + + } + + + private void CreateMenu() + { + App.Current.Dispatcher.Invoke(() => + { + //MenuList.Add(new MenuModel() + //{ + // Name = "订单管理", + // ChildList = new List() + // { + // new MenuModel(){ Name="最近订单",Url="/Views/Order/OrderList.xaml" } + // } + //}); + MenuList.Add(new MenuModel() + { + Name = "商品管理", + ChildList = new List() + { + new MenuModel(){ Name="货源管理",Url="/Views/Ware/WareManager.xaml" }, + new MenuModel(){ Name="产品库存",Url="/Views/Ware/WareStock.xaml" } + } + }); + //MenuList.Add(new MenuModel() + //{ + // Name = "设置", + // ChildList = new List() + // { + // new MenuModel(){ Name="店铺设置",Url="/Views/Setting/ShopSetting.xaml" }, + // new MenuModel(){ Name="团队配置",Url="/Views/Setting/TeamSetting.xaml" } + // } + //}); + }); + } + + private void Exit(System.ComponentModel.CancelEventArgs e) + { + App.Current.Shutdown(); + //Environment.Exit(Environment.ExitCode); + } + + private void Login() + { + try + { + Thread.Sleep(1000); + + var mdsUserResponse = mdsApiService.GetUserInfo(GlobalContext.UserToken); + if (!mdsUserResponse.Success) + throw new Exception($"获取磨刀石用户信息失败 {mdsUserResponse.Msg}"); + + GlobalContext.User = mdsUserResponse.Data.Map(); + GlobalContext.User.SonDepartmentNames = string.Empty; + if (mdsUserResponse.Data.SonDepartmentList != null && mdsUserResponse.Data.SonDepartmentList.Count > 0) + GlobalContext.User.SonDepartmentNames = string.Join(',', mdsUserResponse.Data.SonDepartmentList.Select(sd => sd.DepartmentName)); + + CreateMenu(); + + //if (GlobalContext.User.TeamName == "刷单组") + // return; + + IList departmentList = null; + + var response = mdsApiService.GetShopDetailList(); + if (!response.Success) + throw new Exception(response.Msg); + departmentList = response.Data; + if (departmentList.Count == 0) + throw new Exception("缺少有效的部门数据"); + + var shopIds = new List(); + foreach (var d in departmentList) + { + if (d.ShopList != null && d.ShopList.Count > 0) + { + foreach (var s in d.ShopList) + shopIds.Add(s.ShopId.ToString()); + } + } + + if (departmentList.Count == 1 && departmentList[0].ShopList.Count == 1) + { + ShowShopChoosePanel = false; + ChooseShop(departmentList[0].ShopList[0], true); + return; + } + else + ShowShopChoosePanel = true; + GlobalContext.User.DepartmentList = departmentList; + + if (GlobalContext.User.TeamName == "刷单组") + return; + + App.Current.Dispatcher.Invoke(() => + { + var selectShop = new SelectShopW(departmentList); + if (selectShop.ShowDialog() == true) + { + ChooseShop(selectShop.Shop, true); + } + else + { + Environment.Exit(Environment.ExitCode); + } + }); + } + catch (Exception ex) + { + App.Current.Dispatcher.Invoke(() => + { + MessageBox.Show(ex.Message, "登录失败"); + }); + Environment.Exit(Environment.ExitCode); + } + } + + private void OpenSelectShop() + { + try + { + var selectShop = new SelectShopW(GlobalContext.User.DepartmentList); + if (selectShop.ShowDialog() == true) + { + ChooseShop(selectShop.Shop, true); + var vm = App.Current.Resources["Locator"] as ViewModelLocator; + //if (vm.IsCreateOrderList) + // vm.OrderList.Refresh(); + //if (vm.IsCreateWareManager) + // vm.WareManager.Refresh(); + //if (vm.IsCreateWareStock) + // vm.WareStock.Refresh(); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "切换失败"); + } + } + + private void ChooseShop(Shop shop, bool _throw = false) + { + if (shop.ShopId == 0 || + string.IsNullOrEmpty(shop.AppKey) || + string.IsNullOrEmpty(shop.AppSecret) || + string.IsNullOrEmpty(shop.AppToken)) + { + var error = $"{shop.ShopName} 店铺数据不完整"; + if (_throw) + throw new Exception(error); + else + { + MessageBox.Show(error, "选择店铺"); + return; + } + } + + GlobalContext.User.Shop = shop; + //ShowShopChoosePanel = false; + } + + + #endregion + } +} diff --git a/BBWYB.Client/ViewModels/ViewModelLocator.cs b/BBWYB.Client/ViewModels/ViewModelLocator.cs new file mode 100644 index 0000000..40eb08a --- /dev/null +++ b/BBWYB.Client/ViewModels/ViewModelLocator.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.DependencyInjection; +using System; + +namespace BBWYB.Client.ViewModels +{ + public class ViewModelLocator + { + private IServiceProvider sp; + + public ViewModelLocator() + { + sp = (App.Current as App).ServiceProvider; + } + + public bool IsCreateWareManager { get; private set; } + + public bool IsCreateWareStock { get; private set; } + + public bool IsCreateOrderList { get; private set; } + + + public MainViewModel Main + { + get + { + using (var s = sp.CreateScope()) + { + return s.ServiceProvider.GetRequiredService(); + } + } + } + + //public WareManagerViewModel WareManager + //{ + // get + // { + // IsCreateWareManager = true; + // using (var s = sp.CreateScope()) + // { + // return s.ServiceProvider.GetRequiredService(); + // } + // } + //} + + //public WareStockViewModel WareStock + //{ + // get + // { + // IsCreateWareStock = true; + // using (var s = sp.CreateScope()) + // { + // return s.ServiceProvider.GetRequiredService(); + // } + // } + //} + + //public BindingPurchaseProductViewModel BindingPurchaseProduct + //{ + // get + // { + // using (var s = sp.CreateScope()) + // { + // return s.ServiceProvider.GetRequiredService(); + // } + // } + //} + } +} diff --git a/BBWYB.Client/Views/MainWindow.xaml b/BBWYB.Client/Views/MainWindow.xaml new file mode 100644 index 0000000..ff9494f --- /dev/null +++ b/BBWYB.Client/Views/MainWindow.xaml @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/BBWYB.Client/Views/MainWindow.xaml.cs b/BBWYB.Client/Views/MainWindow.xaml.cs new file mode 100644 index 0000000..19591ee --- /dev/null +++ b/BBWYB.Client/Views/MainWindow.xaml.cs @@ -0,0 +1,32 @@ +using CommunityToolkit.Mvvm.Messaging; +using SJ.Controls; +using System; +using System.Windows; + +namespace BBWYB.Client.Views +{ + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : BWindow + { + public MainWindow() + { + InitializeComponent(); + this.Width = SystemParameters.WorkArea.Size.Width * 0.8; + this.Height = SystemParameters.WorkArea.Size.Height * 0.7; + this.Loaded += MainWindow_Loaded; + } + + private void MainWindow_Loaded(object sender, RoutedEventArgs e) + { + + } + + private void frame_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) + { + if (frame.CanGoBack) + frame.RemoveBackEntry(); + } + } +} diff --git a/BBWYB.Client/Views/SelectShop/SelectShopW.xaml b/BBWYB.Client/Views/SelectShop/SelectShopW.xaml new file mode 100644 index 0000000..9eda974 --- /dev/null +++ b/BBWYB.Client/Views/SelectShop/SelectShopW.xaml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/BBWYB.Client/Views/SelectShop/SelectShopW.xaml.cs b/BBWYB.Client/Views/SelectShop/SelectShopW.xaml.cs new file mode 100644 index 0000000..bced032 --- /dev/null +++ b/BBWYB.Client/Views/SelectShop/SelectShopW.xaml.cs @@ -0,0 +1,45 @@ +using BBWYB.Client.Models; +using SJ.Controls; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Controls; + +namespace BBWYB.Client.Views.SelectShop +{ + /// + /// SelectShop.xaml 的交互逻辑 + /// + public partial class SelectShopW : BWindow + { + public IList DepartmentList { get; set; } + public Shop Shop { get; set; } + + public SelectShopW(IList departmentList) + { + InitializeComponent(); + this.DepartmentList = departmentList; + this.Loaded += SelectShop_Loaded; + } + + private void SelectShop_Loaded(object sender, RoutedEventArgs e) + { + var d = cbx_department.SelectedItem as Department; + cbx_shop.ItemsSource = d.ShopList; + + } + + private void btn_ok_Click(object sender, RoutedEventArgs e) + { + Shop = cbx_shop.SelectedItem as Shop; + this.DialogResult = true; + this.Close(); + } + + private void cbx_department_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + var d = cbx_department.SelectedItem as Department; + cbx_shop.ItemsSource = d.ShopList; + cbx_shop.SelectedIndex = 0; + } + } +} diff --git a/BBWYB.Client/appsettings.json b/BBWYB.Client/appsettings.json new file mode 100644 index 0000000..0d8a671 --- /dev/null +++ b/BBWYB.Client/appsettings.json @@ -0,0 +1,5 @@ +{ + //"BBWYApiHost": "http://localhost:5000", + "BBWYApiHost": "http://bbwyb.qiyue666.com", + "MDSApiHost": "http://mdsapi.qiyue666.com" +} \ No newline at end of file diff --git a/BBWYB.Common/BBWYB.Common.csproj b/BBWYB.Common/BBWYB.Common.csproj index c165dfe..f811516 100644 --- a/BBWYB.Common/BBWYB.Common.csproj +++ b/BBWYB.Common/BBWYB.Common.csproj @@ -10,8 +10,8 @@ + - diff --git a/BBWYB.Common/Http/RestAPIService.cs b/BBWYB.Common/Http/RestAPIService.cs index f0b89ca..dac5a77 100644 --- a/BBWYB.Common/Http/RestAPIService.cs +++ b/BBWYB.Common/Http/RestAPIService.cs @@ -1,5 +1,5 @@ using BBWYB.Common.Extensions; -using Swifter.Json; +using Newtonsoft.Json; using System.Net; using System.Net.Http.Headers; using System.Text; @@ -80,7 +80,7 @@ namespace BBWYB.Common.Http request.Headers.Add(key, requestHeaders[key]); if (paramPosition == ParamPosition.Body && param != null) - request.Content = new StringContent(contentType == ContentType_Json ? JsonFormatter.SerializeObject(param) : param.ToString(), Encoding.UTF8, contentType); + request.Content = new StringContent(contentType == ContentType_Json ? JsonConvert.SerializeObject(param) : param.ToString(), Encoding.UTF8, contentType); using (var response = httpClient.SendAsync(request, httpCompletionOption).Result) { diff --git a/BBWYB.Common/Log/NLogManager.cs b/BBWYB.Common/Log/NLogManager.cs index 698aede..54c00a6 100644 --- a/BBWYB.Common/Log/NLogManager.cs +++ b/BBWYB.Common/Log/NLogManager.cs @@ -29,6 +29,8 @@ namespace BBWYB.Common.Log loggerDictionary.TryAdd(loggerName, logger); } return logger; + + } } } diff --git a/BBWYB.Server.API/BBWYB.Server.API.csproj b/BBWYB.Server.API/BBWYB.Server.API.csproj index ef243e8..e8e4fa5 100644 --- a/BBWYB.Server.API/BBWYB.Server.API.csproj +++ b/BBWYB.Server.API/BBWYB.Server.API.csproj @@ -11,6 +11,8 @@ + + diff --git a/BBWYB.Server.API/Filters/ResultFilter.cs b/BBWYB.Server.API/Filters/ResultFilter.cs new file mode 100644 index 0000000..46ac6ea --- /dev/null +++ b/BBWYB.Server.API/Filters/ResultFilter.cs @@ -0,0 +1,30 @@ +using BBWYB.Common.Models; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace BBWYB.Server.API.Filters +{ + public class ResultFilter : IResultFilter + { + public void OnResultExecuted(ResultExecutedContext context) + { + + } + + public void OnResultExecuting(ResultExecutingContext context) + { + if (context.Result is ObjectResult) + { + var objectResult = context.Result as ObjectResult; + if (!(objectResult.Value is ApiResponse)) + { + objectResult.Value = new ApiResponse() { Data = objectResult.Value }; + } + } + else if (context.Result is EmptyResult) + { + context.Result = new ObjectResult(new ApiResponse()); + } + } + } +} diff --git a/BBWYB.Server.API/Middlewares/CustomExceptionMiddleWare.cs b/BBWYB.Server.API/Middlewares/CustomExceptionMiddleWare.cs new file mode 100644 index 0000000..9aacf9d --- /dev/null +++ b/BBWYB.Server.API/Middlewares/CustomExceptionMiddleWare.cs @@ -0,0 +1,85 @@ +using BBWYB.Common.Log; +using BBWYB.Common.Models; +using Newtonsoft.Json; +using System.Text; + +namespace BBWYB.Server.API.Middlewares +{ + public class CustomExceptionMiddleWare + { + /// + /// 管道请求委托 + /// + private RequestDelegate _next; + + /// + /// 需要处理的状态码字典 + /// + private IDictionary _exceptionStatusCodeDic; + + //private NLogManager nLogManager; + + private NLogManager nLogManager; + + public CustomExceptionMiddleWare(RequestDelegate next, NLogManager nLogManager) + { + _next = next; + //this.logger = logger; + _exceptionStatusCodeDic = new Dictionary + { + { 401, "未授权的请求" }, + { 404, "找不到该资源" }, + { 403, "访问被拒绝" }, + { 500, "服务器发生意外的错误" }, + { 503, "服务不可用" } + //其余状态自行扩展 + }; + } + + public async Task Invoke(HttpContext context) + { + try + { + await _next(context); //调用管道执行下一个中间件 + } + catch (Exception ex) + { + if (ex is BusinessException) + { + var busEx = ex as BusinessException; + context.Response.StatusCode = 200; //业务异常时将Http状态码改为200 + await ErrorHandle(context, busEx.Code, busEx.Message); + } + else + { + context.Response.Clear(); + context.Response.StatusCode = 500; //发生未捕获的异常,手动设置状态码 + //logger.Error(ex); //记录错误 + nLogManager.Default().Error(ex); + } + } + finally + { + if (_exceptionStatusCodeDic.TryGetValue(context.Response.StatusCode, out string exMsg)) + { + await ErrorHandle(context, context.Response.StatusCode, exMsg); + } + } + } + + /// + /// 处理方式:返回Json格式 + /// + /// + /// + /// + /// + private async Task ErrorHandle(HttpContext context, int code, string exMsg) + { + var apiResponse = ApiResponse.Error(code, exMsg); + var serialzeStr = JsonConvert.SerializeObject(apiResponse); + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(serialzeStr, Encoding.UTF8); + } + } +} diff --git a/BBWYB.Server.API/Program.cs b/BBWYB.Server.API/Program.cs index 40a6a2f..3471c8b 100644 --- a/BBWYB.Server.API/Program.cs +++ b/BBWYB.Server.API/Program.cs @@ -1,7 +1,15 @@ +using BBWYB.Common.Extensions; +using BBWYB.Common.Http; +using BBWYB.Common.Log; +using BBWYB.Common.Models; +using BBWYB.Server.API.Filters; +using BBWYB.Server.API.Middlewares; using BBWYB.Server.Business; +using BBWYB.Server.Model; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; +using Newtonsoft.Json.Serialization; using System.Reflection; using System.Text; using Yitter.IdGenerator; @@ -16,8 +24,8 @@ var idOption = new IdGeneratorOptions(1); var idGenerator = new DefaultIdGenerator(idOption); services.AddSingleton(typeof(IIdGenerator), idGenerator); -//var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, configuration.GetConnectionString("DB")).Build(); -//services.AddSingleton(typeof(IFreeSql), fsql); +var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, configuration.GetConnectionString("DB")).Build(); +services.AddSingleton(typeof(IFreeSql), fsql); services.AddSingleton(); services.AddSingleton(); @@ -34,7 +42,30 @@ services.AddCors(options => }); }); -services.AddControllers(); + +services.BatchRegisterServices(new Assembly[] { Assembly.Load("BBWYB.Server.Business") }, typeof(IDenpendency)); +services.AddMapper(new MappingProfiles()); + +services.AddControllers(c => +{ + c.Filters.Add(); +}).AddNewtonsoftJson(setupAction => +{ + setupAction.SerializerSettings.ContractResolver = new DefaultContractResolver(); + setupAction.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; + //setupAction.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include; + //setupAction.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include; +}); + +//.AddJsonOptions(c => c.JsonSerializerOptions.PropertyNamingPolicy = null); + +//services.ConfigureJsonFormatter(configuration: (f) => +//{ +// f.SetDateTimeFormat("yyyy-MM-dd HH:mm:ss"); +// //f.JsonFormatter.Options = Swifter.Json.JsonFormatterOptions.IgnoreNull | +// // Swifter.Json.JsonFormatterOptions.IgnoreZero | +// // Swifter.Json.JsonFormatterOptions.IgnoreEmptyString; +//}); services.AddEndpointsApiExplorer(); services.AddSwaggerGen(c => { @@ -112,8 +143,8 @@ if (isAllowedSwagger) c.RoutePrefix = string.Empty; }); } - //app.UseHttpsRedirection(); +app.UseMiddleware(); app.UseRouting(); app.UseCors("cors"); app.UseAuthorization(); diff --git a/BBWYB.Server.Business/BBWYB.Server.Business.csproj b/BBWYB.Server.Business/BBWYB.Server.Business.csproj index dd73615..fc48f97 100644 --- a/BBWYB.Server.Business/BBWYB.Server.Business.csproj +++ b/BBWYB.Server.Business/BBWYB.Server.Business.csproj @@ -10,6 +10,7 @@ + diff --git a/BBWYB.Server.Model/BBWYB.Server.Model.csproj b/BBWYB.Server.Model/BBWYB.Server.Model.csproj index fea6112..66a14df 100644 --- a/BBWYB.Server.Model/BBWYB.Server.Model.csproj +++ b/BBWYB.Server.Model/BBWYB.Server.Model.csproj @@ -8,6 +8,7 @@ + diff --git a/BBWYB.Server.Model/MappingProfiles.cs b/BBWYB.Server.Model/MappingProfiles.cs new file mode 100644 index 0000000..9f29c5f --- /dev/null +++ b/BBWYB.Server.Model/MappingProfiles.cs @@ -0,0 +1,63 @@ +using AutoMapper; +using BBWYB.Server.Model.Db; +using BBWYB.Server.Model.Dto; + +namespace BBWYB.Server.Model +{ + public class MappingProfiles : Profile + { + // private IDictionary storeDictionary; + + public MappingProfiles() + { + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); + + CreateMap(); + CreateMap(); + CreateMap(); + + //CreateMap(); + //CreateMap(); + + //CreateMap(); + //CreateMap(); + //CreateMap(); + //CreateMap(); + //CreateMap(); + //CreateMap(); + //CreateMap(); + //CreateMap().ForMember(t => t.Id, opt => opt.MapFrom(f => f.SkuId)); + //CreateMap().ForMember(t => t.OrderStartTime, opt => opt.MapFrom(f => f.StartTime)) + // .ForMember(t => t.OrderEndTime, opt => opt.MapFrom(f => f.EndTime)) + // .ForMember(t => t.OrderModifyTime, opt => opt.MapFrom(f => f.ModifyTime)) + // .ForPath(t => t.Consignee.IsDecode, opt => opt.MapFrom(f => f.IsDecode)) + // .ForPath(t => t.Consignee.Province, opt => opt.MapFrom(f => f.Province)) + // .ForPath(t => t.Consignee.City, opt => opt.MapFrom(f => f.City)) + // .ForPath(t => t.Consignee.County, opt => opt.MapFrom(f => f.County)) + // .ForPath(t => t.Consignee.Town, opt => opt.MapFrom(f => f.Town)) + // .ForPath(t => t.Consignee.Address, opt => opt.MapFrom(f => f.Address)) + // .ForPath(t => t.Consignee.Mobile, opt => opt.MapFrom(f => f.Mobile)) + // .ForPath(t => t.Consignee.TelePhone, opt => opt.MapFrom(f => f.TelePhone)) + // .ForPath(t => t.Consignee.ContactName, opt => opt.MapFrom(f => f.ContactName)) + // .ForPath(t => t.OrderCost.OrderId, opt => opt.MapFrom(f => f.Id)) + // .ForPath(t => t.OrderCost.PurchaseAmount, opt => opt.MapFrom(f => f.PurchaseAmount ?? 0)) + // .ForPath(t => t.OrderCost.Profit, opt => opt.MapFrom(f => f.Profit ?? 0)) + // .ForPath(t => t.OrderCost.DeliveryExpressFreight, opt => opt.MapFrom(f => f.DeliveryExpressFreight ?? 0)) + // .ForPath(t => t.OrderCost.PlatformCommissionAmount, opt => opt.MapFrom(f => f.PlatformCommissionAmount ?? 0)) + // .ForPath(t => t.OrderCost.PlatformCommissionRatio, opt => opt.MapFrom(f => f.PlatformCommissionRatio ?? 0)) + // .ForPath(t => t.OrderCost.PreferentialAmount, opt => opt.MapFrom(f => f.PreferentialAmount)) + // .ForPath(t => t.OrderCost.IsManualEdited, opt => opt.MapFrom(f => f.IsManualEdited)) + // .ForPath(t => t.OrderCost.SDCommissionAmount, opt => opt.MapFrom(f => f.SDCommissionAmount)) + // .ForPath(t => t.OrderCost.SDOrderAmount, opt => opt.MapFrom(f => f.SDOrderAmount)) + // .ForPath(t => t.OrderCost.RefundAmount, opt => opt.MapFrom(f => f.RefundAmount)) + // .ForPath(t => t.OrderCost.RefundPurchaseAmount, opt => opt.MapFrom(f => f.RefundPurchaseAmount)) + // .ForPath(t => t.OrderCost.AfterTotalCost, opt => opt.MapFrom(f => f.AfterTotalCost)); + + //CreateMap(); + + } + } +}