Jelajahi Sumber

IOS商品上架更新到手价和售价转换逻辑;短信服务添加阿里云短信发送支持。

wangjingyu 1 bulan lalu
induk
melakukan
399cfde5a3

+ 92 - 0
JiaZhiQuan.Common/AliMessage/AliMessageHelper.cs

@@ -0,0 +1,92 @@
+using System;
+using System.Collections.Generic;
+using AlibabaCloud.SDK.Dysmsapi20170525;
+using AlibabaCloud.SDK.Dysmsapi20170525.Models;
+using Newtonsoft.Json;
+using Tea;
+using Wicture.DbRESTFul;
+
+namespace JiaZhiQuan.Common.AliMessage
+{
+    public class AliMessageHelper
+    {
+        /// <summary>
+        /// key
+        /// </summary>
+        public readonly static string AccessKey = "LTAI5tGReikR9NjZT17dNQb4";
+        /// <summary>
+        /// secret
+        /// </summary>
+        public readonly static string AccessSecret = "xBIM4MAoFLghCy7D7AIipiLiq7BXn8";
+        /// <summary>
+        /// 短信签名
+        /// </summary>
+        public readonly static string SignName = "欧拉鼠";
+
+        /// <summary>
+        /// 初始化aliyun客户端
+        /// </summary>
+        /// <param name="accessKey">key</param>
+        /// <param name="accessKeySecret">secret</param>
+        /// <returns></returns>
+        public static Client CreateClient(string accessKey, string accessKeySecret)
+        {
+            // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
+            // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378671.html。
+            AlibabaCloud.OpenApiClient.Models.Config config = new()
+            {
+                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
+                AccessKeyId = accessKey, //;Environment.GetEnvironmentVariable(accessKey),
+                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
+                AccessKeySecret = accessKeySecret //Environment.GetEnvironmentVariable(accessKeySecret),
+            };
+            // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
+            config.Endpoint = "dysmsapi.aliyuncs.com";
+            return new Client(config);
+        }
+
+        /// <summary>
+        /// 发送短信
+        /// </summary>
+        /// <param name="phoneNumber">手机号</param>
+        /// <param name="template">模板</param>
+        /// <param name="data">数据</param>
+        /// <returns></returns>
+        public static string SendMessage(string phoneNumber, AliMessageTemplateEnum template, string data)
+        {
+            Client client = CreateClient(AccessKey, AccessSecret);//填入授权码
+            SendSmsRequest sendSmsRequest = new()
+            {
+                SignName = SignName,//短信签名
+                TemplateCode = template.GetDescription(),//短信模板
+                PhoneNumbers = phoneNumber,//手机号
+                TemplateParam = data, //模板参数
+            }; 
+            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new();
+            var resMessage = string.Empty;
+            try
+            {
+                // 复制代码运行请自行打印 API 的返回值
+                var res = client.SendSmsWithOptions(sendSmsRequest, runtime);
+                resMessage = res.Body.Message;
+            }
+            catch (TeaException error)
+            {
+                // 如有需要,请打印 error
+                resMessage = AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
+                LoggerManager.Logger.Error($"调用阿里云发送验证码短信API失败:" + resMessage);
+            }
+            catch (Exception _error)
+            {
+                TeaException error = new TeaException(new Dictionary<string, object>
+                {
+                    { "message", _error.Message }
+                });
+                // 如有需要,请打印 error
+                resMessage = AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
+                LoggerManager.Logger.Error($"调用阿里云发送验证码短信API失败:" + resMessage);
+            }
+            return resMessage;
+        }
+    }
+}

+ 13 - 0
JiaZhiQuan.Common/AliMessage/AliMessageTemplateEnum.cs

@@ -0,0 +1,13 @@
+namespace JiaZhiQuan.Common.AliMessage
+{
+    public enum AliMessageTemplateEnum
+    {
+        /// <summary>
+        /// 验证码
+        /// 
+        /// 您的验证码是${code}。如非本人操作,请忽略本短信
+        /// </summary>
+        [Description("SMS_480085126")]
+        SMS_480085126
+    }
+}

+ 22 - 0
JiaZhiQuan.Common/Enum/EnumExtention.cs

@@ -0,0 +1,22 @@
+using System;
+
+namespace JiaZhiQuan.Common
+{
+    /// <summary>
+    /// 枚举拓展
+    /// </summary>
+    public static class EnumExtention
+    {
+        /// <summary>
+        /// 获取枚举描述
+        /// </summary>
+        /// <param name="val"></param>
+        /// <returns></returns>
+        public static string GetDescription(this System.Enum val)
+        {
+            var field = val.GetType().GetField(val.ToString());
+            var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
+            return customAttribute == null ? val.ToString() : ((DescriptionAttribute) customAttribute).Description;
+        }
+    }
+}

+ 1 - 0
JiaZhiQuan.Common/JiaZhiQuan.Common.csproj

@@ -6,6 +6,7 @@
   </PropertyGroup>
 
   <ItemGroup>
+    <PackageReference Include="AlibabaCloud.SDK.Dysmsapi20170525" Version="3.1.1" />
     <PackageReference Include="aliyun-net-sdk-core" Version="1.6.2" />
     <PackageReference Include="aliyun-net-sdk-vod" Version="2.16.31" />
     <PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.14.1" />

+ 15 - 7
JiaZhiQuan.Common/JuheAPI/SendSms/JuheSendSmsUtils.cs

@@ -1,5 +1,6 @@
 using Aliyun.OSS.Model;
 using CSRedis;
+using JiaZhiQuan.Common.AliMessage;
 using Newtonsoft.Json;
 using System;
 using System.Net.Http;
@@ -41,7 +42,14 @@ namespace JiaZhiQuan.Common.JuheAPI.SendSms
             }
             // 发送短信
             string sendParams = HttpUtility.UrlEncode($"#code#={code}");
-            var res = await client.GetStringAsync($"http://v.juhe.cn/sms/send?mobile={mobile}&tpl_id={JUHE_SMS_TPL_ID}&tpl_value={sendParams}&key={JUHE_SMS_KEY}");
+            //使用阿里云短信服务
+            var res = AliMessageHelper.SendMessage(mobile, AliMessageTemplateEnum.SMS_480085126, JsonConvert.SerializeObject(new { code }));
+                            // await client.GetStringAsync($"http://v.juhe.cn/sms/send?mobile={mobile}&tpl_id={JUHE_SMS_TPL_ID}&tpl_value={sendParams}&key={JUHE_SMS_KEY}");
+            if (!res.Equals("OK"))
+            {
+                LoggerManager.Logger.Error($"调用阿里云发送验证码短信API失败:" + JsonConvert.SerializeObject(res));
+                throw new LogicalException("发送短信失败,请稍后再试[" + res + "]", ErrorCodes.Exception);
+            }
             // 设置今天的发送次数
             int newDayLimitCount = dayLimitCount + 1;
             await redis.Set(dayLimitKey, newDayLimitCount, DateTime.Now.Date.AddDays(1));
@@ -55,12 +63,12 @@ namespace JiaZhiQuan.Common.JuheAPI.SendSms
             };
             await redis.Set(continuousLimitKey, newContinuousLimit, expiration);
             // 查看发送结果
-            var obj = JsonConvert.DeserializeObject<JuheResponseModel1<JuheMobileAddressResultDetails>>(res);
-            if (obj.error_code != 0)
-            {
-                LoggerManager.Logger.Error($"调用聚合发送验证码短信API失败:" + JsonConvert.SerializeObject(obj));
-                throw new LogicalException("发送短信失败,请稍后再试[" + res + "]", ErrorCodes.Exception);
-            }
+            //var obj = JsonConvert.DeserializeObject<JuheResponseModel1<JuheMobileAddressResultDetails>>(res);
+            //if (obj.error_code != 0)
+            //{
+            //    LoggerManager.Logger.Error($"调用聚合发送验证码短信API失败:" + JsonConvert.SerializeObject(obj));
+            //    throw new LogicalException("发送短信失败,请稍后再试[" + res + "]", ErrorCodes.Exception);
+            //}
         }
     }
 

+ 1 - 1
JiaZhiQuan.Common/Models/VO/UE/InPubInfo.cs

@@ -21,7 +21,7 @@ namespace JiaZhiQuan.Common.Models.VO.UE {
         //售价
         public int salePrice { get; set; }
         //到手价
-        //public int netAmount {  get; set; }
+        public int netAmount {  get; set; }
         //1,接近全新,2,轻微痕迹,3,明显痕迹,4,严重痕迹
         public int usedState { get; set; }
         //成色(1,已验8成新,2,已验85新,3,已验9成新,4,已验95新,5已验99新,6已验全新)

+ 138 - 1
JiaZhiQuan.Common/Repository/RepositoryExtension.Temp.cs

@@ -71,6 +71,72 @@ namespace JiaZhiQuan.Common {
             });
             return result;
         }
+
+        /// <summary>
+        /// 获取服务费以及到手价
+        /// 
+        /// IOS更新,计算到手价和售价
+        /// </summary>
+        /// <param name="catId">类目id</param>
+        /// <param name="salePrices">多个销售价</param>
+        /// <param name="saleType">1,寄售,2挂售</param>
+        /// <returns></returns>
+        /// <exception cref="LogicalException"></exception>
+        public static async Task<Dictionary<int, FeeInfo>> GetSalePriceByCatIdV1(this DbRESTFulRepository repository,
+            int serviceFeeTempId, List<int> salePrices, bool careNetAmount = true)
+        {
+            if (serviceFeeTempId == 0)
+                throw new LogicalException("请输入正确的服务费模板id");
+
+            List<MallServiceFee> fees = new List<MallServiceFee>();
+            var feeRange = await repository.QueryAsync<MallServiceFeeRange>(@"SELECT 
+                                                        f.`name`,     
+                                                        fr.serviceFeeId,
+                                                        fr.chargeType,
+                                                        fr.startRange,
+                                                        fr.endRange,
+                                                        fr.chargeAmount,
+                                                        fr.chargeRate,
+                                                        fr.minFee,
+                                                        fr.maxFee,
+                                                        tl.displayOrder
+                                                       FROM mall_servicefee_temp t 
+                                                       INNER JOIN mall_servicefee_temp_list tl on t.id=tl.serviceFeeTempId
+                                                       INNER JOIN mall_service_fee f on f.id=tl.serviceFeeId
+                                                       INNER JOIN mall_service_fee_range fr on f.id=fr.serviceFeeId
+                                                       WHERE  t.id=@serviceFeeTempId AND t.state=1
+                                                       ORDER BY fr.startRange", new { serviceFeeTempId });
+            var result = new Dictionary<int, FeeInfo>();
+            salePrices.ForEach(p => {
+                var netFee = CalNetFeeV1(feeRange, p);
+                var rst = new FeeInfo
+                {
+                    totalServicePrice = (int)(netFee.totalServiceFee * UNIT),
+                    totalServiceFee = "-¥" + netFee.totalServiceFee.ToString("0.##"),
+                    netAmount = (int)(netFee.netAmount * UNIT),
+                    netAmountStr = "¥" + netFee.netAmount.ToString("0.##"), //到手金额
+                    fees = netFee.fees ?? new List<MallServiceFee>(), //服务费详情列表
+                    isBelowMiniPrice = netFee.isBelowMiniPrice,
+                    belowMiniPriceDesc = netFee.isBelowMiniPrice ? $"不足¥{UE_MIN_PRICE},请重新出价" : ""
+                };
+                result[p] = rst;
+                //服务费也不能大于salePrice
+                if (rst.totalServicePrice >= p || rst.netAmount <= 0)
+                {
+                    if (!careNetAmount)
+                    {
+                        //rst.totalServicePrice = p;
+                        rst.netAmount = 0;
+                        rst.netAmountStr = "¥" + rst.netAmount.ToString("0.##");
+                        rst.belowMiniPriceDesc = $"¥0,请重新出价";
+                        return;
+                    }
+                    throw new Exception("商品定价存在问题,服务价过高或到手价为0");
+                }
+            });
+            return result;
+        }
+
         /// <summary>
         /// 计算服务费
         /// </summary>
@@ -117,7 +183,7 @@ namespace JiaZhiQuan.Common {
                         fee = "-¥" + CommonUtils.DivideAndRound(money, UNIT).ToString("0.##"),
                         displayOrder = fee.displayOrder,
                     });
-                    netAmount += money;
+                    netAmount -= money;
                     totalServiceFee += money;
                 }
             }
@@ -130,6 +196,77 @@ namespace JiaZhiQuan.Common {
                 totalServiceFee = CommonUtils.DivideAndRound(totalServiceFee, UNIT)
             };
         }
+
+        /// <summary>
+        /// 计算服务费
+        /// 
+        /// IOS更新,转换到手价和售价
+        /// </summary>
+        /// <param name="feeRange"></param>
+        /// <param name="salePrice">单位是分</param>
+        /// <returns></returns>
+        private static NetServiceFee CalNetFeeV1(IEnumerable<MallServiceFeeRange> feeRange, int salePrice)
+        {
+            List<MallServiceFee> fees = new List<MallServiceFee>();
+            //到手金额
+            int netAmount = salePrice;
+            int totalServiceFee = 0;
+            var feeDic = feeRange.GroupBy(f => f.serviceFeeId).ToDictionary(g => g.Key, g => g.ToList());
+
+            foreach (var item in feeDic)
+            {
+                int money = 0;
+                string name = string.Empty;
+                foreach (var fee in item.Value)
+                {
+                    //,1,比例,2,定额
+                    switch (fee.chargeType)
+                    {
+                        case 1:
+                            long lmoney = (long)salePrice * fee.chargeRate;
+                            int deduction = (int)(lmoney / 10000);
+                            name = fee.name + $"({CommonUtils.DivideAndRound(fee.chargeRate, UNIT):0.##}%";
+                            if (fee.minFee.HasValue && deduction < fee.minFee.Value)
+                            {
+                                deduction = fee.minFee.Value;
+                                name += $",最低¥{CommonUtils.DivideAndRound(deduction, UNIT):0.##}";
+                            }
+                            if (fee.maxFee.HasValue && deduction > fee.maxFee.Value)
+                            {
+                                deduction = fee.maxFee.Value;
+                                name += $",最高¥{CommonUtils.DivideAndRound(deduction, UNIT):0.##}";
+                            }
+
+                            money = deduction;
+                            name += ")";
+                            break;
+                        case 2:
+                            money = fee.chargeAmount;
+                            name = fee.name + $"(¥{CommonUtils.DivideAndRound(money, UNIT):0.##})";
+                            break;
+                    }
+
+                    fees.Add(new MallServiceFee
+                    {
+                        name = name,
+                        fee = "-¥" + CommonUtils.DivideAndRound(money, UNIT).ToString("0.##"),
+                        displayOrder = fee.displayOrder,
+                    });
+                    netAmount += money;
+                    totalServiceFee += money;
+                }
+            }
+            fees = fees.OrderByDescending(f => f.displayOrder).ToList();
+
+            return new NetServiceFee
+            {
+                fees = fees,
+                isBelowMiniPrice = netAmount < UE_MIN_PRICE * UNIT,
+                netAmount = CommonUtils.DivideAndRound(netAmount, UNIT),
+                totalServiceFee = CommonUtils.DivideAndRound(totalServiceFee, UNIT)
+            };
+        }
+
         #endregion
 
         #region 欧拉币抵扣计算

+ 3 - 3
JiaZhiQuan.Common/Utils/AttributeUtils.cs

@@ -16,10 +16,10 @@ namespace JiaZhiQuan.Common.Utils
         /// </summary>
         /// <param name="value"></param>
         /// <returns></returns>
-        public static T GetEnumDescription<T>(Enum value) where T : Attribute
+        public static T GetEnumDescription<T>(System.Enum value) where T : Attribute
         {
             var type = value.GetType();
-            var name = Enum.GetName(type, value);
+            var name = System.Enum.GetName(type, value);
             if (name == null) return null;
             var field = type.GetField(name);
             if (field == null) return null;
@@ -34,7 +34,7 @@ namespace JiaZhiQuan.Common.Utils
         /// <param name="func"></param>
         /// <returns></returns>
         public static List<TAttribute> FindEnumValues<TEnum, TAttribute>(Func<TAttribute, bool> func)
-            where TEnum : Enum
+            where TEnum : System.Enum
             where TAttribute : Attribute
         {
             List<TAttribute> attributes = new List<TAttribute>();