Browse Source

1

updatebug
shanji 2 years ago
parent
commit
ab98caf594
  1. 7
      BBWYB.Client/APIServices/BaseApiService.cs
  2. 6
      BBWYB.Client/APIServices/MdsApiService.cs
  3. 51
      BBWYB.Client/APIServices/OneBoundAPIService.cs
  4. 6
      BBWYB.Client/APIServices/ProductService.cs
  5. 166
      BBWYB.Client/APIServices/PurchaseOrderService.cs
  6. 76
      BBWYB.Client/APIServices/PurchaseProductAPIService.cs
  7. 6
      BBWYB.Client/APIServices/PurchaseService.cs
  8. 91
      BBWYB.Client/APIServices/ShopService.cs
  9. 22
      BBWYB.Client/App.xaml
  10. 105
      BBWYB.Client/App.xaml.cs
  11. 19
      BBWYB.Client/BBWYB.Client.csproj
  12. 21
      BBWYB.Client/Converters/EnumToBooleanConverter.cs
  13. 26
      BBWYB.Client/Converters/InputNumberConverter.cs
  14. 23
      BBWYB.Client/Converters/ItemHeightConverter.cs
  15. 81
      BBWYB.Client/Converters/MultiObjectConverter.cs
  16. 22
      BBWYB.Client/Converters/MultiParameterTransferConverter.cs
  17. 55
      BBWYB.Client/Converters/ObjectConverter.cs
  18. 21
      BBWYB.Client/Converters/ProfitRatioConverter.cs
  19. 25
      BBWYB.Client/Converters/SaleGrossProfitConverter.cs
  20. 27
      BBWYB.Client/Converters/WidthConveter.cs
  21. 12
      BBWYB.Client/Extensions/CopyExtensions.cs
  22. 85
      BBWYB.Client/Extensions/EncryptionExtension.cs
  23. 5
      BBWYB.Client/GlobalContext.cs
  24. 49
      BBWYB.Client/Helpers/MemoryHelper.cs
  25. 36
      BBWYB.Client/Helpers/ShellExecuteHelper.cs
  26. 6
      BBWYB.Client/Models/KVModel.cs
  27. 14
      BBWYB.Client/Models/MappingProfile.cs
  28. 7
      BBWYB.Client/Models/MenuModel.cs
  29. 23
      BBWYB.Client/Models/NotifyObject.cs
  30. 7
      BBWYB.Client/Models/Product/Product.cs
  31. 9
      BBWYB.Client/Models/Product/ProductSku.cs
  32. 9
      BBWYB.Client/Models/Product/PurchaseScheme.cs
  33. 11
      BBWYB.Client/Models/Product/PurchaseSchemeProduct.cs
  34. 11
      BBWYB.Client/Models/Product/PurchaseSchemeProductSku.cs
  35. 8
      BBWYB.Client/Models/Product/Purchaser.cs
  36. 177
      BBWYB.Client/Models/PurchaseOrder/PurchaseOrder.cs
  37. 11
      BBWYB.Client/Models/PurchaseOrder/StorageModel.cs
  38. 7
      BBWYB.Client/Models/Shop/Department.cs
  39. 15
      BBWYB.Client/Models/Shop/PurchaseAccount.cs
  40. 9
      BBWYB.Client/Models/Shop/Shop.cs
  41. 8
      BBWYB.Client/Models/User/User.cs
  42. 37
      BBWYB.Client/ViewModels/BaseVM.cs
  43. 245
      BBWYB.Client/ViewModels/MainViewModel.cs
  44. 68
      BBWYB.Client/ViewModels/ViewModelLocator.cs
  45. 115
      BBWYB.Client/Views/MainWindow.xaml
  46. 32
      BBWYB.Client/Views/MainWindow.xaml.cs
  47. 56
      BBWYB.Client/Views/SelectShop/SelectShopW.xaml
  48. 45
      BBWYB.Client/Views/SelectShop/SelectShopW.xaml.cs
  49. 5
      BBWYB.Client/appsettings.json
  50. 2
      BBWYB.Common/BBWYB.Common.csproj
  51. 4
      BBWYB.Common/Http/RestAPIService.cs
  52. 2
      BBWYB.Common/Log/NLogManager.cs
  53. 2
      BBWYB.Server.API/BBWYB.Server.API.csproj
  54. 30
      BBWYB.Server.API/Filters/ResultFilter.cs
  55. 85
      BBWYB.Server.API/Middlewares/CustomExceptionMiddleWare.cs
  56. 39
      BBWYB.Server.API/Program.cs
  57. 1
      BBWYB.Server.Business/BBWYB.Server.Business.csproj
  58. 1
      BBWYB.Server.Model/BBWYB.Server.Model.csproj
  59. 63
      BBWYB.Server.Model/MappingProfiles.cs

7
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
{

6
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
{

51
BBWYB.Client/APIServices/OneBoundAPIService.cs

@ -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;
}
/// <summary>
/// 产品详细信息接口
/// </summary>
/// <param name="platform">1699/jd/taobao 更多值参阅https://open.onebound.cn/help/api/</param>
/// <param name="key"></param>
/// <param name="secret"></param>
/// <param name="productId"></param>
/// <returns></returns>
public ApiResponse<JObject> 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<JObject>()
{
Data = j,
Code = j.Value<string>("error_code") == "0000" ? 200 : 0,
Msg = j.Value<string>("error")
};
}
catch (Exception ex)
{
return ApiResponse<JObject>.Error(0, ex.Message);
}
}
}
}

6
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
{

166
BBWYB.Client/APIServices/PurchaseOrderService.cs

@ -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<object> AddPurchaseOrder(PurchaseOrder purchaseOrder)
{
return SendRequest<object>(globalContext.BBYWApiHost,
"api/PurchaseOrder/AddPurchaseOrder",
purchaseOrder,
null,
HttpMethod.Post);
}
public ApiResponse<object> EditPurchaseOrder(PurchaseOrder purchaseOrder)
{
return SendRequest<object>(globalContext.BBYWApiHost,
"api/PurchaseOrder/EditPurchaseOrder",
purchaseOrder,
null,
HttpMethod.Put);
}
public ApiResponse<IList<PurchaseOrderResponse>> GetList(IList<string> skuIdList, StorageType storageType, long shopId)
{
return SendRequest<IList<PurchaseOrderResponse>>(globalContext.BBYWApiHost,
"api/PurchaseOrder/GetList",
new { SkuIdList = skuIdList, StorageType = storageType, ShopId = shopId },
null,
HttpMethod.Post);
}
public ApiResponse<object> DeletePurchaseOrder(long id)
{
return SendRequest<object>(globalContext.BBYWApiHost,
$"api/purchaseOrder/deletePurchaseOrder/{id}",
null,
null,
HttpMethod.Delete);
}
/// <summary>
/// 预览订单
/// </summary>
/// <param name="consignee"></param>
/// <param name="purchaseSchemeProductSkuList"></param>
/// <returns></returns>
public ApiResponse<PreviewOrderResponse> PreviewPurchaseOrder(Consignee consignee, IList<PurchaseSchemeProductSku> purchaseSchemeProductSkuList, Platform purchasePlatform, PurchaseAccount purchaseAccount, PurchaseOrderMode purchaseOrderMode)
{
return SendRequest<PreviewOrderResponse>(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);
}
/// <summary>
/// 创建采购单
/// </summary>
/// <param name="consignee"></param>
/// <param name="purchaseSchemeProductSkuList"></param>
/// <param name="purchasePlatform"></param>
/// <param name="purchaseAccount"></param>
/// <param name="purchaseOrderMode"></param>
/// <param name="tradeMode"></param>
/// <param name="remark"></param>
/// <param name="orderId"></param>
/// <param name="shopId"></param>
/// <param name="purchaseAccountId"></param>
/// <param name="buyerAccount"></param>
/// <param name="sellerAccount"></param>
/// <param name="purchaserId"></param>
/// <param name="platformCommissionRatio"></param>
/// <param name="extensions"></param>
/// <returns></returns>
public ApiResponse<object> FastCreateOrder(Consignee consignee,
IList<PurchaseSchemeProductSku> 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<object>(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);
}
/// <summary>
/// 查询审核采购单
/// </summary>
/// <param name="shopIdList"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public ApiResponse<IList<AuditPurchaseOrderResponse>> GetAuditPurchaseOrderList(IList<long> shopIdList, DateTime startDate, DateTime endDate)
{
return SendRequest<IList<AuditPurchaseOrderResponse>>(globalContext.BBYWApiHost, "Api/PurchaseOrder/GetAuditPurchaseOrderList", new
{
startDate,
endDate,
shopIdList
}, null, HttpMethod.Post);
}
}
}

76
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<PurchaseSchemeProductSku> 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<PurchaseSchemeProductSku> 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;
// }
//}
}
}

6
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
{

91
BBWYB.Client/APIServices/ShopService.cs

@ -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<long> SaveShopSetting(long shopId,
string managerPwd,
decimal platformCommissionRatio,
PurchaseAccount purchaseAccount,
string dingDingWebHook,
string dingDingKey,
int skuSafeTurnoverDays,
string siNanDingDingWebHook,
string siNanDingDingKey,
int siNanPolicyLevel)
{
return SendRequest<long>(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);
}
/// <summary>
/// 根据订单Id查询归属店铺
/// </summary>
/// <param name="orderIdList"></param>
/// <returns></returns>
public ApiResponse<IList<OrderBelongShopResponse>> GetOrderBelongShop(IList<string> orderIdList)
{
return SendRequest<IList<OrderBelongShopResponse>>(globalContext.BBYWApiHost, "api/order/GetOrderBelongShop", orderIdList, null, HttpMethod.Post);
}
/// <summary>
/// 获取部门及下属店铺
/// </summary>
/// <returns></returns>
public ApiResponse<IList<DepartmentResponse>> GetDepartmentList()
{
return SendRequest<IList<DepartmentResponse>>(globalContext.BBYWApiHost, "api/vender/GetDeparmentList", null,
new Dictionary<string, string>()
{
{ "bbwyTempKey", "21jfhayu27q" }
}, HttpMethod.Get);
}
public ApiResponse<IList<ShopResponse>> GetShopListByIds(IList<string> shopIds)
{
return SendRequest<IList<ShopResponse>>(globalContext.BBYWApiHost, "api/vender/GetShopListByShopIds", new
{
shopIds
}, new Dictionary<string, string>()
{
{ "bbwyTempKey", "21jfhayu27q" }
}, HttpMethod.Post);
}
public ApiResponse<IList<WaiterResponse>> GetServiceGroupList()
{
return SendRequest<IList<WaiterResponse>>(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);
}
}
}

22
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">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/Themes/Color.xaml"/>
<ResourceDictionary Source="/Resources/Themes/Path.xaml"/>
<ResourceDictionary Source="/Resources/Themes/Generic.xaml"/>
<ResourceDictionary Source="/Resources/Themes/DataTemplate.xaml"/>
</ResourceDictionary.MergedDictionaries>
<vm:ViewModelLocator x:Key="Locator"/>
<ctr:ObjectConverter x:Key="objConverter"/>
<ctr:MultiObjectConverter x:Key="mobjConverter"/>
<ctr:WidthConveter x:Key="widthConverter"/>
<ctr:InputNumberConverter x:Key="inputNumberConverter"/>
<ctr:EnumToBooleanConverter x:Key="enumToBooleanConverter"/>
</ResourceDictionary>
</Application.Resources>
</Application>

105
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
/// </summary>
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<RestApiService>();
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);
}
}
}
}

19
BBWYB.Client/BBWYB.Client.csproj

@ -8,12 +8,27 @@
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
<None Remove="Resources\Images\bbwylogo.ico" />
<None Remove="Resources\Images\defaultItem.png" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.1.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
@ -25,8 +40,4 @@
<Resource Include="Resources\Images\defaultItem.png" />
</ItemGroup>
<ItemGroup>
<Folder Include="Views\" />
</ItemGroup>
</Project>

21
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
{
/// <inheritdoc/>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? false : value.Equals(parameter);
}
/// <inheritdoc/>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null && value.Equals(true) ? parameter : Binding.DoNothing;
}
}
}

26
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;
}
}
}

23
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();
}
}
}

81
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
{
/// <summary>
/// 多值转换器
/// </summary>
/// <param name="values">参数值数组</param>
/// <param name="parameter">
/// <para>参数</para>
/// <para>各组比较值:比较条件(&或|):true返回值:false返回值:返回值类型枚举</para>
/// <para>v1;v2-1|v2-2;v3:&:Visible:Collapsed:1</para>
/// </param>
/// <returns></returns>
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<string> 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
}
}
}

22
BBWYB.Client/Converters/MultiParameterTransferConverter.cs

@ -0,0 +1,22 @@
using System;
using System.Globalization;
using System.Windows.Data;
namespace BBWYB.Client.Converters
{
/// <summary>
/// Command多参数传递类
/// </summary>
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();
}
}
}

55
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];
}
}
}

21
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();
}
}
}

25
BBWYB.Client/Converters/SaleGrossProfitConverter.cs

@ -0,0 +1,25 @@
using System;
using System.Globalization;
using System.Windows.Data;
namespace BBWYB.Client.Converters
{
/// <summary>
/// 销售毛利率转换器
/// </summary>
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();
}
}
}

27
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();
}
}
}

12
BBWYB.Client/Extensions/CopyExtensions.cs

@ -0,0 +1,12 @@
using Newtonsoft.Json;
namespace BBWYB.Client.Extensions
{
public static class CopyExtensions
{
public static T Copy<T>(this T p)
{
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(p));
}
}
}

85
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));
}
}
}

5
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; }

49
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
{
/// <summary>
/// 获取token
/// </summary>
/// <returns></returns>
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;
}
}
}
}

36
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);
}
}

6
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; }

14
BBWYB.Client/Models/MappingProfile.cs

@ -6,15 +6,7 @@ namespace BBWYB.Client.Models
{
public MappingProfile()
{
CreateMap<OrderDropShippingResponse, OrderDropShipping>();
CreateMap<OrderCostDetailResponse, OrderCostDetail>();
CreateMap<OrderCouponResponse, OrderCoupon>();
CreateMap<OrderCostResponse, OrderCost>();
CreateMap<ConsigneeResponse, Consignee>();
CreateMap<AfterSaleOrderResponse, AfterSaleOrder>();
CreateMap<OrderResponse, Order>();
CreateMap<OrderSkuResponse, OrderSku>().ForMember(t => t.ProductItemNum, opt => opt.MapFrom(f => f.ProductNo));
CreateMap<AuditPayBillResponse, AuditPayBill>();
CreateMap<MDSUserResponse, User>().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<PurchaseAccountResponse, PurchaseAccount>();
CreateMap<DepartmentResponse, Department>();
CreateMap<PurchaseOrderResponse, PurchaseOrder>();
CreateMap<ToDayOrderAchievementResponse, ToDayOrderAchievement>();
CreateMap<SDGroupPersonStatisticsResponse, SDGroupPersonStatistics>();
CreateMap<BillCorrectionOrderResponse, BillCorrectionOrder>();
}
}
}

7
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; }

23
BBWYB.Client/Models/NotifyObject.cs

@ -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<T>(ref T oldValue, T newValue, [CallerMemberName]string propertyName = "")
{
if (Equals(oldValue, newValue))
return false;
oldValue = newValue;
OnPropertyChanged(propertyName);
return true;
}
}
}

7
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()

9
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); }
}
/// <summary>
/// 选中的仓储平台
/// </summary>
public StorageModel SelectedStorageModel { get => selectedStorageModel; set { Set(ref selectedStorageModel, value); } }
public StorageModel SelectedStorageModel { get => selectedStorageModel; set { SetProperty(ref selectedStorageModel, value); } }
public ProductSku()
{

9
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
/// <summary>
/// 采购方案
/// </summary>
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; }

11
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
/// <summary>
/// 采购商品
/// </summary>
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()

11
BBWYB.Client/Models/Product/PurchaseSchemeProductSku.cs

@ -1,11 +1,12 @@
using System;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
namespace BBWYB.Client.Models
{
/// <summary>
/// 采购商品的Sku
/// </summary>
public class PurchaseSchemeProductSku : NotifyObject
public class PurchaseSchemeProductSku : ObservableObject
{
/// <summary>
/// 采购商品的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;

8
BBWYB.Client/Models/Product/Purchaser.cs

@ -1,9 +1,11 @@
namespace BBWYB.Client.Models
using CommunityToolkit.Mvvm.ComponentModel;
namespace BBWYB.Client.Models
{
/// <summary>
/// 采购商
/// </summary>
public class Purchaser : NotifyObject
public class Purchaser : ObservableObject
{
private int skuUseCount;
@ -14,7 +16,7 @@
/// <summary>
/// 使用该采购商的SKU数量
/// </summary>
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; }

177
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); } }
/// <summary>
/// 单件均摊成本
/// </summary>
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; }
/// <summary>
/// 单件发货预估运费(不参与单件均摊成本计算)
/// </summary>
public decimal SingleDeliveryFreight
{
get => singleDeliveryFreight; set { SetProperty(ref singleDeliveryFreight, value); }
}
///// <summary>
///// 单间操作成本
///// </summary>
//public decimal SingleOperationAmount
//{
// get => singleOperationAmount;
// set
// {
// if (SetProperty(ref singleOperationAmount, value))
// RefreshUnitCost();
// }
//}
/// <summary>
/// 单件耗材成本
/// </summary>
public decimal SingleConsumableAmount
{
get => singleConsumableAmount;
set
{
if (SetProperty(ref singleConsumableAmount, value))
RefreshUnitCost();
}
}
/// <summary>
/// 单件SKU成本
/// </summary>
public decimal SingleSkuAmount
{
get => singleSkuAmount;
set
{
if (SetProperty(ref singleSkuAmount, value))
RefreshUnitCost();
}
}
/// <summary>
/// 单件采购运费
/// </summary>
public decimal SingleFreight
{
get => singleFreight;
set
{
if (SetProperty(ref singleFreight, value))
RefreshUnitCost();
}
}
/// <summary>
/// 单件头程费
/// </summary>
public decimal SingleFirstFreight
{
get => singleFirstFreight;
set
{
if (SetProperty(ref singleFirstFreight, value))
RefreshUnitCost();
}
}
/// <summary>
/// 单件仓储费
/// </summary>
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;
}
}

11
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; }
}
}

7
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();
}
}

15
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()
{

9
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); } }
/// <summary>
/// 店铺Id
/// </summary>
@ -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<PurchaseAccount> PurchaseAccountList { get; set; }

8
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<Department> DepartmentList { get; set; }

37
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()
{
}
}
}

245
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<MenuModel> MenuList { get; set; }
public IList<Shop> 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;
}
}
}
}
/// <summary>
/// 是否显示店铺选择列表
/// </summary>
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<System.ComponentModel.CancelEventArgs>(Exit);
//ChooseShopCommand = new RelayCommand<Shop>((s) => ChooseShop(s));
OpenSelectShopCommand = new RelayCommand(OpenSelectShop);
this.GlobalContext = globalContext;
ShopList = new ObservableCollection<Shop>();
MenuList = new ObservableCollection<MenuModel>()
{
};
Task.Factory.StartNew(Login);
}
private void CreateMenu()
{
App.Current.Dispatcher.Invoke(() =>
{
//MenuList.Add(new MenuModel()
//{
// Name = "订单管理",
// ChildList = new List<MenuModel>()
// {
// new MenuModel(){ Name="最近订单",Url="/Views/Order/OrderList.xaml" }
// }
//});
MenuList.Add(new MenuModel()
{
Name = "商品管理",
ChildList = new List<MenuModel>()
{
new MenuModel(){ Name="货源管理",Url="/Views/Ware/WareManager.xaml" },
new MenuModel(){ Name="产品库存",Url="/Views/Ware/WareStock.xaml" }
}
});
//MenuList.Add(new MenuModel()
//{
// Name = "设置",
// ChildList = new List<MenuModel>()
// {
// 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<User>();
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<Department> 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<string>();
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
}
}

68
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<MainViewModel>();
}
}
}
//public WareManagerViewModel WareManager
//{
// get
// {
// IsCreateWareManager = true;
// using (var s = sp.CreateScope())
// {
// return s.ServiceProvider.GetRequiredService<WareManagerViewModel>();
// }
// }
//}
//public WareStockViewModel WareStock
//{
// get
// {
// IsCreateWareStock = true;
// using (var s = sp.CreateScope())
// {
// return s.ServiceProvider.GetRequiredService<WareStockViewModel>();
// }
// }
//}
//public BindingPurchaseProductViewModel BindingPurchaseProduct
//{
// get
// {
// using (var s = sp.CreateScope())
// {
// return s.ServiceProvider.GetRequiredService<BindingPurchaseProductViewModel>();
// }
// }
//}
}
}

115
BBWYB.Client/Views/MainWindow.xaml

@ -0,0 +1,115 @@
<c:BWindow x:Class="BBWYB.Client.Views.MainWindow"
xmlns:c="clr-namespace:SJ.Controls;assembly=SJ.Controls"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:local="clr-namespace:BBWYB.Client.Views"
DataContext="{Binding Main,Source={StaticResource Locator}}"
mc:Ignorable="d"
Style="{StaticResource bwstyle}"
Title="{Binding GlobalContext.User.Shop.ShopName,StringFormat=步步为盈 \{0\}}" Height="450" Width="800">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Closing">
<b:InvokeCommandAction Command="{Binding ClosingCommand}" PassEventArgsToCommand="True"/>
</b:EventTrigger>
</b:Interaction.Triggers>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border BorderThickness="0,0,0,1" BorderBrush="{StaticResource MainMenu.BorderBrush}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0">
<TextBlock Text="{Binding GlobalContext.User.Name}"/>
<!--<TextBlock Text="{Binding GlobalContext.User.TeamName}" Margin="5,0,0,0"/>
<TextBlock Text="{Binding GlobalContext.User.Shop.Platform}" Margin="5,0,0,0"/>-->
<TextBlock Text="{Binding GlobalContext.User.Shop.ShopName}" Margin="5,0,0,0"/>
<TextBlock Text="v10000" Margin="5,0,0,0"/>
</StackPanel>
</Border>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox x:Name="listbox_menu" ItemsSource="{Binding MenuList}"
ItemContainerStyle="{StaticResource NoBgListBoxItemStyle}"
Background="{StaticResource MainMenu.BackGround}"
Foreground="{StaticResource Text.Color}"
BorderThickness="0,0,1,0"
BorderBrush="{StaticResource MainMenu.BorderBrush}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding ActualWidth,ElementName=listbox_menu}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" Margin="10,5,0,5"/>
<ListBox ItemsSource="{Binding ChildList}"
SelectedItem="{Binding DataContext.SelectedMenuModel,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}"
Grid.Row="1"
Foreground="#4A4A4A">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource DefaultListBoxItemStyle}">
<Setter Property="IsSelected" Value="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Margin="20,5,0,5" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<c:BButton Content="切换店铺" VerticalAlignment="Bottom" HorizontalAlignment="Left" Style="{StaticResource LinkButton}" Panel.ZIndex="1" Margin="5,0,0,5"
Visibility="{Binding ShowShopChoosePanel,Converter={StaticResource objConverter},ConverterParameter=true:Visible:Collapsed}"
Command="{Binding OpenSelectShopCommand}"/>
<Frame x:Name="frame" Navigated="frame_Navigated" NavigationUIVisibility="Hidden"
Source="{Binding SelectedMenuModel.Url}"
Grid.Column="1"/>
<!--<Grid Grid.ColumnSpan="2" Background="{StaticResource Border.Background}"
Visibility="{Binding ShowShopChoosePanel,Converter={StaticResource objConverter},ConverterParameter=true:Visible:Collapsed}">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="请选择一个店铺" VerticalAlignment="Center" FontWeight="Bold" FontSize="20"/>
<ListBox ItemsSource="{Binding ShopList}" Grid.Row="1"
ItemContainerStyle="{StaticResource NoBgListBoxItemStyle}"
Style="{StaticResource NoScrollViewListBoxStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<c:BButton Content="{Binding Name}"
Background="Transparent"
Foreground="{StaticResource Text.Color}"
FontSize="14"
MouseOverBgColor="{StaticResource Button.Selected.Background}"
MouseOverFontColor="White"
Padding="5,0"
Command="{Binding DataContext.ChooseShopCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}"
CommandParameter="{Binding }"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>-->
<Grid Grid.ColumnSpan="2" Background="{StaticResource Border.Background}"
Visibility="{Binding ShowWB2RuntimeDownloadPanel,Converter={StaticResource objConverter},ConverterParameter=true:Visible:Collapsed}">
<c:RoundWaitProgress Play="{Binding ShowWB2RuntimeDownloadPanel}"
WaitText="{Binding Wb2DownloadProgress,Mode=OneWay,UpdateSourceTrigger=PropertyChanged,StringFormat=正在下载Webview2Runtime \{0\}%}"/>
</Grid>
</Grid>
</Grid>
</c:BWindow>

32
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
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
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();
}
}
}

56
BBWYB.Client/Views/SelectShop/SelectShopW.xaml

@ -0,0 +1,56 @@
<c:BWindow x:Class="BBWYB.Client.Views.SelectShop.SelectShopW"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BBWYB.Client.Views.SelectShop"
mc:Ignorable="d"
xmlns:c="clr-namespace:SJ.Controls;assembly=SJ.Controls"
Title="SelectShop" Height="200" Width="300"
CloseButtonVisibility="Visible"
CloseButtonColor="{StaticResource WindowButtonColor}"
MinButtonVisibility="Collapsed"
MaxButtonVisibility="Collapsed"
RightButtonGroupMargin="0,5,5,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Border BorderThickness="0,0,0,1" BorderBrush="{StaticResource MainMenu.BorderBrush}"
Background="{StaticResource Border.Background}">
<TextBlock Text="选择店铺" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Grid Grid.Row="1" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="团队" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox x:Name="cbx_department"
ItemsSource="{Binding DepartmentList,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type c:BWindow}}}"
SelectedIndex="0"
DisplayMemberPath="Name"
Width="150" Height="25"
HorizontalAlignment="Left" VerticalContentAlignment="Center"
Grid.Column="1" Margin="5,5,0,5"
SelectionChanged="cbx_department_SelectionChanged"/>
<TextBlock Text="店铺" HorizontalAlignment="Right" Grid.Row="1" VerticalAlignment="Center" />
<ComboBox x:Name="cbx_shop" Width="150" Height="25"
SelectedIndex="0"
HorizontalAlignment="Left" VerticalContentAlignment="Center"
DisplayMemberPath="ShopName"
Grid.Column="1" Grid.Row="1" Margin="5,5,0,5"/>
</Grid>
<c:BButton x:Name="btn_ok" Content="确定" Grid.Row="2" Width="60" HorizontalAlignment="Right" Margin="0,0,8,0"
Click="btn_ok_Click"/>
</Grid>
</c:BWindow>

45
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
{
/// <summary>
/// SelectShop.xaml 的交互逻辑
/// </summary>
public partial class SelectShopW : BWindow
{
public IList<Department> DepartmentList { get; set; }
public Shop Shop { get; set; }
public SelectShopW(IList<Department> 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;
}
}
}

5
BBWYB.Client/appsettings.json

@ -0,0 +1,5 @@
{
//"BBWYApiHost": "http://localhost:5000",
"BBWYApiHost": "http://bbwyb.qiyue666.com",
"MDSApiHost": "http://mdsapi.qiyue666.com"
}

2
BBWYB.Common/BBWYB.Common.csproj

@ -10,8 +10,8 @@
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="5.1.2" />
<PackageReference Include="Swifter.Json" Version="1.6.0.6" />
</ItemGroup>
</Project>

4
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)
{

2
BBWYB.Common/Log/NLogManager.cs

@ -29,6 +29,8 @@ namespace BBWYB.Common.Log
loggerDictionary.TryAdd(loggerName, logger);
}
return logger;
}
}
}

2
BBWYB.Server.API/BBWYB.Server.API.csproj

@ -11,6 +11,8 @@
<PackageReference Include="FreeSql" Version="3.2.690" />
<PackageReference Include="FreeSql.Provider.MySql" Version="3.2.690" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.14" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.14" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
</ItemGroup>

30
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());
}
}
}
}

85
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
{
/// <summary>
/// 管道请求委托
/// </summary>
private RequestDelegate _next;
/// <summary>
/// 需要处理的状态码字典
/// </summary>
private IDictionary<int, string> _exceptionStatusCodeDic;
//private NLogManager nLogManager;
private NLogManager nLogManager;
public CustomExceptionMiddleWare(RequestDelegate next, NLogManager nLogManager)
{
_next = next;
//this.logger = logger;
_exceptionStatusCodeDic = new Dictionary<int, string>
{
{ 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);
}
}
}
/// <summary>
/// 处理方式:返回Json格式
/// </summary>
/// <param name="context"></param>
/// <param name="code"></param>
/// <param name="exMsg"></param>
/// <returns></returns>
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);
}
}
}

39
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<NLogManager>();
services.AddSingleton<RestApiService>();
@ -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<ResultFilter>();
}).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<CustomExceptionMiddleWare>();
app.UseRouting();
app.UseCors("cors");
app.UseAuthorization();

1
BBWYB.Server.Business/BBWYB.Server.Business.csproj

@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="FreeSql" Version="3.2.690" />
<PackageReference Include="FreeSql.Provider.MySql" Version="3.2.690" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
</ItemGroup>

1
BBWYB.Server.Model/BBWYB.Server.Model.csproj

@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="FreeSql" Version="3.2.690" />
</ItemGroup>

63
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<string, string> storeDictionary;
public MappingProfiles()
{
CreateMap<InputPurchaseSchemeRequest, PurchaseScheme>();
CreateMap<EditPurchaseSchemeRequest, PurchaseScheme>();
CreateMap<InputPurchaseSchemeProductRequest, PurchaseSchemeProduct>();
CreateMap<InputPurchaseSchemeProductSkuRequest, PurchaseSchemeProductSku>();
CreateMap<PurchaseScheme, PurchaseSchemeResponse>();
CreateMap<PurchaseSchemeProduct, PurchaseSchemeProductResponse>();
CreateMap<PurchaseSchemeProductSku, PurchaseSchemeProductSkuResponse>();
//CreateMap<AddPurchaseOrderRequest, PurchaseOrder>();
//CreateMap<PurchaseOrder, PurchaseOrderResponse>();
//CreateMap<OrderDropShippingRequest, OrderDropShipping>();
//CreateMap<OrderDropShipping, OrderDropShippingResponse>();
//CreateMap<OrderCostDetailRequest, OrderCostDetail>();
//CreateMap<OrderCostDetail, OrderCostDetailResponse>();
//CreateMap<OrderConsignee, ConsigneeResponse>();
//CreateMap<OrderCost, OrderCostResponse>();
//CreateMap<OrderCoupon, OrderCouponResponse>();
//CreateMap<OrderSku, OrderSkuResponse>().ForMember(t => t.Id, opt => opt.MapFrom(f => f.SkuId));
//CreateMap<Order, OrderResponse>().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<AddOrEditPromotionTaskRequest, PromotionTask>();
}
}
}
Loading…
Cancel
Save