799 lines
30 KiB
C#
799 lines
30 KiB
C#
using KJD_Web.BLL.WXXD.Dtos;
|
||
using KJD_Web.BLL.WXXD.Requests;
|
||
using KJD_Web.Model;
|
||
using KJD_Web.Model.WxModel;
|
||
using KJD_Web.Utils;
|
||
using NaiBa.Util.Extension;
|
||
using NaiBa.Util.Helper;
|
||
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Serialization;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Data;
|
||
using System.Linq;
|
||
using System.Web;
|
||
|
||
namespace KJD_Web.BLL.WXXD
|
||
{
|
||
public class WXOemManage
|
||
{
|
||
/// <summary>
|
||
/// 手续费
|
||
/// </summary>
|
||
const long fee = 0;
|
||
public string AddMdyOem(string inputData)
|
||
{
|
||
if (!string.IsNullOrEmpty(inputData))
|
||
{
|
||
if (!WXUserManage.GetSign(inputData))
|
||
return "{\"code\":999,\"msg\":\"校验失败\"}";
|
||
|
||
var oem_id = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_id")?.Replace("'", "\\'"));
|
||
var oem_name = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_name")?.Replace("'", "\\'"));
|
||
var oem_owner = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_owner")?.Replace("'", "\\'"));
|
||
if (oem_id.IsNullOrEmpty() || oem_name.IsNullOrEmpty())
|
||
return "{\"code\":500,\"msg\":\"oem信息不能为空\"}";
|
||
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn);
|
||
string sql = "INSERT INTO wxxd.oem (oem_id,oem_name,oem_owner) VALUES('" + oem_id + "','" + oem_name + "','" + oem_owner + "')" +
|
||
"ON DUPLICATE KEY UPDATE oem_name=VALUES(oem_name),oem_owner=VALUES(oem_owner);";
|
||
|
||
var rst = mySql.ExecuteAffectedRows(sql);
|
||
mySql.Close();
|
||
|
||
if (!string.IsNullOrEmpty(mySql.Message))
|
||
{
|
||
return "{\"code\":500,\"msg\":\"" + mySql.Message + "\"}";
|
||
}
|
||
return "{\"code\":200,\"msg\":\"success\",\"affected_rows\":" + rst + "}";
|
||
}
|
||
return "{\"code\":19999,\"msg\":\"输入为空\"}";
|
||
}
|
||
|
||
public string DelOem(string inputData)
|
||
{
|
||
if (!string.IsNullOrEmpty(inputData))
|
||
{
|
||
if (!WXUserManage.GetSign(inputData))
|
||
return "{\"code\":999,\"msg\":\"校验失败\"}";
|
||
|
||
var id = (RegexUtils.GetStringQuery(ref inputData, "db_id")?.Replace("'", "\\'"));
|
||
var oem_id = (RegexUtils.GetStringQuery(ref inputData, "oem_id")?.Replace("'", "\\'"));
|
||
if (oem_id.IsNullOrEmpty() && id.IsNullOrEmpty())
|
||
return "{\"code\":500,\"msg\":\"oem信息不能为空\"}";
|
||
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn);
|
||
string sql = "UPDATE wxxd.oem SET is_del=1 WHERE id=" + id + " or oem_id='" + oem_id + "'";
|
||
|
||
var rst = mySql.ExecuteAffectedRows(sql);
|
||
mySql.Close();
|
||
|
||
if (!string.IsNullOrEmpty(mySql.Message))
|
||
{
|
||
return "{\"code\":500,\"msg\":\"" + mySql.Message + "\"}";
|
||
}
|
||
return "{\"code\":200,\"msg\":\"success\"}";
|
||
}
|
||
return "{\"code\":19999,\"msg\":\"输入为空\"}";
|
||
}
|
||
|
||
public string GetOem(string inputData)
|
||
{
|
||
if (!string.IsNullOrEmpty(inputData))
|
||
{
|
||
if (!WXUserManage.GetSign(inputData))
|
||
return "{\"code\":999,\"msg\":\"校验失败\"}";
|
||
|
||
var timeCalc = DateTime.Now;
|
||
var oem_id = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_id")?.Replace("'", "\\'"));
|
||
var oem_name = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_name")?.Replace("'", "\\'"));
|
||
var oem_owner = HtmlUtils.UrlDecodeUtf8(RegexUtils.GetStringQuery(ref inputData, "oem_owner")?.Replace("'", "\\'"));
|
||
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn);
|
||
string sql = "SELECT * FROM wxxd.oem WHERE is_del=0";
|
||
|
||
string where = "";
|
||
if (!string.IsNullOrEmpty(oem_id))
|
||
where += " and oem_id in ('" + oem_id.Replace(",", "','") + "')";
|
||
if (!string.IsNullOrEmpty(oem_name))
|
||
where += " and oem_name in ('" + oem_name.Replace(",", "','") + "')";
|
||
if (!string.IsNullOrEmpty(oem_owner))
|
||
where += " and oem_owner in ('" + oem_owner.Replace(",", "','") + "')";
|
||
|
||
sql += where;
|
||
sql += " ORDER BY add_time DESC;";
|
||
|
||
var dt = mySql.ExecuteDataTable(sql);
|
||
mySql.Close();
|
||
|
||
if (!string.IsNullOrEmpty(mySql.Message) || dt == null)
|
||
{
|
||
return "{\"code\":500,\"msg\":\"" + mySql.Message + "\"}";
|
||
}
|
||
|
||
try
|
||
{
|
||
List<oem> productLst = new List<oem>();
|
||
foreach (DataRow row in dt.Rows)
|
||
{
|
||
oem prod = new oem
|
||
{
|
||
id = row["id"].ParseToInt(),
|
||
oem_icon = null,
|
||
oem_id = row["oem_id"].ParseToString(),
|
||
add_time = row["add_time"].ParseToString().ParseToDateTime(),
|
||
mdy_time = row["mdy_time"].ParseToString().ParseToDateTime(),
|
||
oem_img = null,
|
||
oem_name = row["oem_name"].ParseToString(),
|
||
oem_owner = row["oem_owner"].ParseToString(),
|
||
available_balance = row.Table.Columns.Contains("available_balance") ? row["available_balance"].ParseToLong() : 0,
|
||
frozen_balance = row.Table.Columns.Contains("frozen_balance") ? row["frozen_balance"].ParseToLong() : 0,
|
||
total_rebate_amount = row.Table.Columns.Contains("total_rebate_amount") ? row["total_rebate_amount"].ParseToLong() : 0,
|
||
total_withdraw_amount = row.Table.Columns.Contains("total_withdraw_amount") ? row["total_withdraw_amount"].ParseToLong() : 0,
|
||
};
|
||
productLst.Add(prod);
|
||
}
|
||
JsonSerializerSettings jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
|
||
var data = JsonUtils.SerializeObjectToString(productLst, jsonSetting);
|
||
var seconds = (DateTime.Now - timeCalc).TotalSeconds.ToString("0.000");
|
||
return "{\"code\":200,\"msg\":\"success\",\"data\":" + data + ",\"count\":" + -1 + ",\"seconds\":" + seconds + "}";
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return "{\"code\":500,\"msg\":\"" + ex.Message + "\",\"data\":[],\"count\":" + 0 + "}";
|
||
}
|
||
}
|
||
return "{\"code\":19999,\"msg\":\"输入为空\"}";
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// OEM 提现记录查询(分页)
|
||
/// </summary>
|
||
/// <param name="request">查询请求</param>
|
||
/// <returns></returns>
|
||
public string OemWithdrawals(OemWithdrawalQueryRequest request)
|
||
{
|
||
Result ret = Result.ArgumentNull();
|
||
|
||
try
|
||
{
|
||
if (request == null || request.user_name.IsNullOrEmpty())
|
||
throw new Exception("参数错误:缺少用户名");
|
||
|
||
List<string> oemIdLst = new List<string>();
|
||
var user = new WXUserManage().GetUserByUserName(request.user_name);
|
||
if (user.sa_level != 1)//非管理员 判断 是否Oem 管理员
|
||
{
|
||
var oems = GetOems(new List<string> { request.user_name });
|
||
if (oems == null || oems.Any() == false)
|
||
{
|
||
throw new Exception("错误的账号");
|
||
}
|
||
oemIdLst.AddRange(oems.Select(a => a.oem_id).ToArray());
|
||
}
|
||
else
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(request.oem_ids))
|
||
{
|
||
oemIdLst.AddRange(request.oem_ids.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
|
||
|
||
}
|
||
}
|
||
|
||
|
||
|
||
int page = request.page <= 0 ? 1 : request.page;
|
||
int page_size = request.page_size <= 0 ? 20 : request.page_size;
|
||
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn);
|
||
|
||
string where = " WHERE w.is_deleted=0";
|
||
if (oemIdLst.Any())
|
||
where += " AND w.oem_id IN ('" + string.Join("','", oemIdLst) + "')";
|
||
if (!request.withdrawal_no.IsNullOrEmpty())
|
||
where += " AND w.withdrawal_no='" + MysqlUtils.ReplaceSqlSpecial(request.withdrawal_no) + "'";
|
||
if (request.status.HasValue)
|
||
where += " AND w.status=" + request.status.Value;
|
||
if (!request.start_time.IsNullOrEmpty())
|
||
where += " AND w.created_at >= '" + MysqlUtils.ReplaceSqlSpecial(request.start_time) + "'";
|
||
if (!request.end_time.IsNullOrEmpty())
|
||
where += " AND w.created_at <= '" + MysqlUtils.ReplaceSqlSpecial(request.end_time) + "'";
|
||
|
||
string countSql = "SELECT COUNT(*) FROM wxxd.oem_withdrawal w" + where;
|
||
int count = mySql.ExecuteFirstInt(countSql);
|
||
if (!string.IsNullOrEmpty(mySql.Message))
|
||
throw new Exception(mySql.Message);
|
||
|
||
string sql = "SELECT w.*, o.oem_name FROM wxxd.oem_withdrawal w " +
|
||
"LEFT JOIN wxxd.oem o ON w.oem_id = o.oem_id" + where +
|
||
" ORDER BY w.id DESC LIMIT " + Math.Max(page - 1, 0) * page_size + "," + page_size + ";";
|
||
|
||
var dt = mySql.ExecuteDataTable(sql);
|
||
mySql.Close();
|
||
if (!string.IsNullOrEmpty(mySql.Message) || dt == null)
|
||
throw new Exception(mySql.Message);
|
||
|
||
List<OemWithdrawalDto> list = new List<OemWithdrawalDto>();
|
||
foreach (DataRow row in dt.Rows)
|
||
{
|
||
list.Add(BuildOemWithdrawalDto(row));
|
||
}
|
||
|
||
//// 贴牌账户余额信息
|
||
//List<OemWithdrawalBalanceDto> balanceLst = oems.Where(x => oemIdLst.Contains(x.id)).Select(x => new OemWithdrawalBalanceDto
|
||
//{
|
||
// oem_id = x.id,
|
||
// oem_code = x.oem_id,
|
||
// oem_name = x.oem_name,
|
||
// available_balance = x.available_balance,
|
||
// frozen_balance = x.frozen_balance,
|
||
// total_rebate_amount = x.total_rebate_amount,
|
||
// total_withdraw_amount = x.total_withdraw_amount,
|
||
//}).ToList();
|
||
ret = new PageResult();
|
||
ret.Code = 200;
|
||
ret.Msg = "success";
|
||
ret.Data = list;
|
||
(ret as PageResult).Total = count;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ret = Result.Failure(ex.Message);
|
||
}
|
||
return JsonUtils.SerializeObjectToString(ret, new JsonSerializerSettings
|
||
{
|
||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||
});
|
||
}
|
||
/// <summary>
|
||
/// 计算Oem 流水
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public string SettleOemFlows(SignRequestBase request)
|
||
{
|
||
Result ret = Result.ArgumentNull();
|
||
|
||
try
|
||
{
|
||
if (request == null || request.user_name.IsNullOrEmpty())
|
||
throw new Exception("参数错误:缺少用户名");
|
||
|
||
|
||
var oems = GetOems(new List<string> { request.user_name });
|
||
if (oems == null || oems.Any() == false)
|
||
{
|
||
throw new Exception("错误的账号");
|
||
}
|
||
oem oemInfo = oems.First();
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn, true);
|
||
|
||
try
|
||
{
|
||
this.SettleOemFlows(mySql, oemInfo.oem_id);
|
||
mySql.Commit();
|
||
}
|
||
catch (Exception)
|
||
{
|
||
mySql.RollBack();
|
||
throw;
|
||
}
|
||
finally
|
||
{
|
||
mySql.Close();
|
||
}
|
||
oems = GetOems(new List<string> { request.user_name });
|
||
if (oems == null || oems.Any() == false)
|
||
{
|
||
throw new Exception("错误的账号");
|
||
}
|
||
oemInfo = oems.First();
|
||
ret.Code = 200;
|
||
ret.Msg = "success";
|
||
ret.Data = new
|
||
{
|
||
oemInfo.available_balance,
|
||
oemInfo.total_rebate_amount,
|
||
oemInfo.total_withdraw_amount,
|
||
};
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ret = Result.Failure(ex.Message);
|
||
}
|
||
return JsonUtils.SerializeObjectToString(ret, new JsonSerializerSettings
|
||
{
|
||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||
});
|
||
}
|
||
/// <summary>
|
||
/// OEM 申请提现
|
||
/// 申请时先把该用户未结算(settlement=0)的流水 oem_amount 汇总结算到 oem 账户
|
||
/// (available_balance 可提现、total_rebate_amount 累计返利),并把流水标记 settlement=1。
|
||
/// 每次只允许一笔进行中的提现(状态0待审核/1审核通过/3打款中)。
|
||
/// </summary>
|
||
/// <param name="request">申请提现请求</param>
|
||
/// <returns></returns>
|
||
public string ApplyOemWithdrawal(OemWithdrawalRequest request)
|
||
{
|
||
Result ret = Result.ArgumentNull();
|
||
string client_ip = "";
|
||
try
|
||
{
|
||
if (request == null || request.user_name.IsNullOrEmpty())
|
||
throw new Exception("参数错误:缺少用户名");
|
||
if (request.amount <= 0)
|
||
throw new Exception("提现金额必须大于0");
|
||
if (fee < 0)
|
||
throw new Exception("手续费不能为负数");
|
||
if (request.amount <= fee)
|
||
throw new Exception("提现金额必须大于手续费");
|
||
if (request.withdrawal_type != WithdrawalType.Bank &&
|
||
request.withdrawal_type != WithdrawalType.Alipay &&
|
||
request.withdrawal_type != WithdrawalType.WeChat &&
|
||
request.withdrawal_type != WithdrawalType.Other)
|
||
throw new Exception("提现方式不合法");
|
||
if (request.account_no.IsNullOrEmpty())
|
||
throw new Exception("收款账号不能为空");
|
||
|
||
var oems = GetOems(new List<string> { request.user_name });
|
||
if (oems == null || oems.Any() == false)
|
||
{
|
||
throw new Exception("错误的账号");
|
||
}
|
||
|
||
oem oemInfo = null;
|
||
if (!request.oem_id.IsNullOrEmpty())
|
||
{
|
||
oemInfo = oems.FirstOrDefault(x => x.oem_id == request.oem_id);
|
||
if (oemInfo == null)
|
||
throw new Exception("未找到该贴牌信息");
|
||
}
|
||
else
|
||
{
|
||
oemInfo = oems.First();
|
||
}
|
||
|
||
//// 收款人姓名默认取贴牌名称
|
||
//if (request.account_name.IsNullOrEmpty())
|
||
request.account_name = oemInfo.oem_name;
|
||
|
||
|
||
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn, true);
|
||
try
|
||
{
|
||
// 每次只能处理一笔提现申请
|
||
string sql = "SELECT COUNT(*) FROM wxxd.oem_withdrawal WHERE oem_id='" + oemInfo.oem_id +
|
||
"' AND status IN (" + (int)OemWithdrawalStatus.Pending + "," + (int)OemWithdrawalStatus.Approved + "," + (int)OemWithdrawalStatus.Paying + ")" +
|
||
" AND is_deleted=0";
|
||
int processingCount = mySql.ExecuteFirstInt(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message))
|
||
throw new Exception(mySql.Message);
|
||
if (processingCount > 0)
|
||
throw new Exception("存在进行中的提现申请,请等待审核完成后再次申请");
|
||
|
||
///申请编号
|
||
string withdrawal_no = "TX" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + RandomUtils.GetNumber(4);
|
||
//保存图片
|
||
if (ImageService.IsValidImage(request.account_no))
|
||
{
|
||
string savePath = ImageService.SaveBase64Image(request.account_no, fileName: withdrawal_no);
|
||
request.account_no = savePath;
|
||
}
|
||
|
||
|
||
// 结算未结算流水到oem账户(独立方法,写oem金额与改流水状态在同一事务内)
|
||
long settled_fen = SettleOemFlows(mySql, oemInfo.oem_id);
|
||
|
||
// 重新读取结算后的账户余额(分)
|
||
sql = "SELECT available_balance FROM wxxd.oem WHERE id=" + oemInfo.id;
|
||
var oemRow = mySql.ExecuteDataTableRow(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || oemRow == null)
|
||
throw new Exception("获取账户余额失败");
|
||
|
||
long available_fen = oemRow["available_balance"].ParseToLong();
|
||
if (available_fen < request.amount)
|
||
throw new Exception("可提现余额不足");
|
||
|
||
long amount_fen = request.amount;
|
||
long fee_fen = fee;
|
||
long actual_fen = amount_fen - fee_fen;
|
||
long balance_after_fen = available_fen - amount_fen;
|
||
|
||
// 冻结:扣减可提现,增加冻结金额(乐观锁)
|
||
sql = "UPDATE wxxd.oem SET available_balance=available_balance-" + amount_fen +
|
||
", frozen_balance=frozen_balance+" + amount_fen +
|
||
" WHERE id=" + oemInfo.id + " AND available_balance>=" + amount_fen;
|
||
var freezeRst = mySql.ExecuteAffectedRows(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || freezeRst <= 0)
|
||
throw new Exception("冻结余额失败,账户余额已发生变化,请刷新后重试");
|
||
|
||
string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||
|
||
sql = "INSERT INTO wxxd.oem_withdrawal " +
|
||
"(withdrawal_no,oem_id,apply_user_name,amount,fee,actual_amount,balance_before,balance_after," +
|
||
"withdrawal_type,account_name,account_no,bank_name,bank_branch," +
|
||
"status,audit_by,audit_time,audit_remark,remark,client_ip,version,is_deleted,created_at,updated_at) VALUES (" +
|
||
"'" + withdrawal_no + "','" + oemInfo.oem_id + "','" + MysqlUtils.ReplaceSqlSpecial(request.user_name) + "'," +
|
||
amount_fen + "," + fee_fen + "," + actual_fen + "," + available_fen + "," + balance_after_fen + "," +
|
||
(int)request.withdrawal_type + ",'" + MysqlUtils.ReplaceSqlSpecial(request.account_name) + "','" + MysqlUtils.ReplaceSqlSpecial(request.account_no) + "'," +
|
||
"'" + MysqlUtils.ReplaceSqlSpecial(request.bank_name) + "','" + MysqlUtils.ReplaceSqlSpecial(request.bank_branch) + "'," +
|
||
(int)OemWithdrawalStatus.Pending + ",'',NULL,NULL," +
|
||
"'" + MysqlUtils.ReplaceSqlSpecial(request.remark) + "','" + MysqlUtils.ReplaceSqlSpecial(client_ip) + "',0,0,'" + now + "','" + now + "');";
|
||
|
||
long insertId = mySql.ExecuteInsertId(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || insertId <= 0)
|
||
throw new Exception("创建提现记录失败");
|
||
|
||
mySql.Commit();
|
||
|
||
ret.Code = 200;
|
||
ret.Msg = "success";
|
||
ret.Data = new { withdrawal_no = withdrawal_no, id = insertId, balance_after = balance_after_fen, actual_amount = actual_fen };
|
||
}
|
||
catch (Exception)
|
||
{
|
||
mySql.RollBack();
|
||
throw;
|
||
}
|
||
finally
|
||
{
|
||
mySql.Close();
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ret = Result.Failure(ex.Message);
|
||
}
|
||
return JsonUtils.SerializeObjectToString(ret, new JsonSerializerSettings
|
||
{
|
||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// OEM 提现审核
|
||
/// 审核通过:冻结金额转历史累计提现;审核拒绝:冻结金额退回可提现余额。
|
||
/// </summary>
|
||
/// <param name="request">审核请求</param>
|
||
/// <returns></returns>
|
||
public string AuditOemWithdrawal(OemWithdrawalAuditRequest request)
|
||
{
|
||
Result ret = Result.ArgumentNull();
|
||
|
||
try
|
||
{
|
||
if (string.IsNullOrEmpty(request.withdrawal_no))
|
||
throw new Exception("参数错误:缺少提现单号");
|
||
if (request.audit_result != (int)OemWithdrawalStatus.Approved && request.audit_result != (int)OemWithdrawalStatus.Rejected)
|
||
throw new Exception("审核结果不合法:1审核通过 2审核拒绝");
|
||
if (request.user_name.IsNullOrEmpty())
|
||
throw new Exception("审核人不能为空");
|
||
var user = new WXUserManage().GetUserByUserName(request.user_name);
|
||
if (user.sa_level != 1)
|
||
{
|
||
throw new Exception("无权限审核");
|
||
}
|
||
string audit_remark = HtmlUtils.UrlDecodeUtf8(request.audit_remark);
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn, true);
|
||
try
|
||
{
|
||
string sql = "SELECT * FROM wxxd.oem_withdrawal WHERE withdrawal_no='" + request.withdrawal_no + "' AND is_deleted=0";
|
||
var row = mySql.ExecuteDataTableRow(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || row == null)
|
||
throw new Exception("提现记录不存在");
|
||
|
||
int status = row["status"].ParseToInt();
|
||
if (status != (int)OemWithdrawalStatus.Pending)
|
||
{
|
||
throw new Exception("当前状态不可审核");
|
||
}
|
||
|
||
//保存图片
|
||
if (ImageService.IsValidImage(request.pay_trade_no))
|
||
{
|
||
string savePath = ImageService.SaveBase64Image(request.pay_trade_no, fileName: "C" + request.withdrawal_no);
|
||
request.pay_trade_no = savePath;
|
||
}
|
||
|
||
|
||
string oem_id = row["oem_id"].ParseToString();
|
||
long amount_fen = row["amount"].ParseToLong();
|
||
string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||
|
||
// 更新oem账户余额
|
||
if (request.audit_result == (int)OemWithdrawalStatus.Approved)
|
||
{
|
||
// 审核通过:冻结金额减少,历史累计提现增加
|
||
sql = "UPDATE wxxd.oem SET frozen_balance=frozen_balance-" + amount_fen +
|
||
", total_withdraw_amount=total_withdraw_amount+" + amount_fen +
|
||
" WHERE oem_id='" + oem_id + "' AND frozen_balance>=" + amount_fen;
|
||
}
|
||
else
|
||
{
|
||
// 审核拒绝:冻结金额减少,退回可提现余额
|
||
sql = "UPDATE wxxd.oem SET frozen_balance=frozen_balance-" + amount_fen +
|
||
", available_balance=available_balance+" + amount_fen +
|
||
" WHERE oem_id='" + oem_id + "' AND frozen_balance>=" + amount_fen;
|
||
}
|
||
var oemRst = mySql.ExecuteAffectedRows(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || oemRst <= 0)
|
||
throw new Exception("更新账户余额失败");
|
||
if (request.audit_result == 1) request.audit_result = (int)OemWithdrawalStatus.Paid; //已付款
|
||
sql = "UPDATE wxxd.oem_withdrawal SET status=" + request.audit_result +
|
||
",audit_by='" + MysqlUtils.ReplaceSqlSpecial(request.user_name) +
|
||
"',audit_time='" + now +
|
||
"',audit_remark='" + MysqlUtils.ReplaceSqlSpecial(audit_remark) +
|
||
"',updated_at='" + now +
|
||
"',pay_time='" + now +
|
||
"',pay_trade_no='" + request.pay_trade_no +
|
||
"' WHERE withdrawal_no='" + request.withdrawal_no + "' AND status=" + (int)OemWithdrawalStatus.Pending + ";";
|
||
|
||
var updateRst = mySql.ExecuteAffectedRows(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || updateRst <= 0)
|
||
throw new Exception("审核失败,请刷新后重试");
|
||
|
||
mySql.Commit();
|
||
|
||
ret.Code = 200;
|
||
ret.Msg = request.audit_result == (int)OemWithdrawalStatus.Approved ? "审核通过" : "审核拒绝";
|
||
ret.Data = new { withdrawal_no = request.withdrawal_no, status = request.audit_result };
|
||
}
|
||
catch (Exception)
|
||
{
|
||
mySql.RollBack();
|
||
throw;
|
||
}
|
||
finally
|
||
{
|
||
mySql.Close();
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
ret = Result.Failure(ex.Message);
|
||
}
|
||
return JsonUtils.SerializeObjectToString(ret, new JsonSerializerSettings
|
||
{
|
||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 结算流水到oem账户(独立方法)。
|
||
/// 根据 oem_id(贴牌编号) 找到该oem下所有账户(wxxd.user.oem_id 匹配),
|
||
/// 然后按流水id升序遍历 wxxd.user_payment_record 中未结算(settlement=0)流水,按公式计算:
|
||
/// type=20:amount - 2.2
|
||
/// type=26:amount - 2.5
|
||
/// type=16:oem_amount
|
||
/// type=31:oem_amount
|
||
/// type=23:- amount(同一个订单(order_id)只能减少一次)
|
||
/// 各项金额之和为总金额(元),写入 oem.available_balance(当前可提现);
|
||
/// 其中正数部分累计到 oem.total_rebate_amount(历史累计返利)。
|
||
/// 写oem金额与更新流水settlement=1在同一个事务内执行(由调用方开启的事务)。
|
||
/// </summary>
|
||
/// <param name="mySql">事务连接(调用方已开启事务)</param>
|
||
/// <param name="oemIdCode">贴牌编号(wxxd.oem.oem_id / wxxd.user.oem_id)</param>
|
||
/// <param name="oemDbId">wxxd.oem.id 数字主键</param>
|
||
/// <returns>本次结算总金额(分)</returns>
|
||
private long SettleOemFlows(MysqlUtils mySql, string oem_id)
|
||
{
|
||
if (oem_id.IsNullOrEmpty())
|
||
return 0;
|
||
// 1. 找到该oem下所有账户
|
||
string sql = "SELECT b.user_name FROM `wxxd`.`user` AS A LEFT JOIN `wxxd`.`user` AS B ON A.user_name = B.parent_user_name WHERE A.oem_id='" + MysqlUtils.ReplaceSqlSpecial(oem_id) + "'";
|
||
var userDt = mySql.ExecuteDataTable(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || userDt == null || userDt.Rows.Count == 0)
|
||
return 0;
|
||
|
||
List<string> userLst = userDt.Rows.Cast<DataRow>()
|
||
.Select(r => r["user_name"].ParseToString())
|
||
.Where(x => !string.IsNullOrEmpty(x))
|
||
.Distinct()
|
||
.ToList();
|
||
if (userLst.Count == 0)
|
||
return 0;
|
||
// 2. 该oem所有账户的未结算流水,按id升序
|
||
sql = "SELECT * FROM `wxxd`.`user_payment_record` WHERE user_name IN ('" + string.Join("','", userLst) + "') AND type IN (20,23,26,16,31) AND settlement=0 AND is_deleted=0 ORDER BY id ASC";
|
||
var flowDt = mySql.ExecuteDataTable(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || flowDt == null || flowDt.Rows.Count == 0)
|
||
return 0;
|
||
decimal total_amount = 0m; // 总金额(元)
|
||
decimal rebate_amount = 0m; // 正数部分(累计返利)
|
||
HashSet<string> deductedOrderSet = new HashSet<string>(); // type=23 已扣减的订单
|
||
List<long> settleIdLst = new List<long>(); // 参与结算的流水id
|
||
|
||
foreach (DataRow row in flowDt.Rows)
|
||
{
|
||
int type = row["type"].ParseToInt();
|
||
decimal amount = row["amount"].ParseToDecimal();
|
||
decimal oem_amount = row["oem_amount"].ParseToDecimal();
|
||
long flowId = row["id"].ParseToLong();
|
||
|
||
decimal itemAmount = 0m;
|
||
if (type == 20)
|
||
itemAmount = amount - 2.2m;
|
||
else if (type == 26)
|
||
itemAmount = amount - 2.5m;
|
||
else if (type == 16)
|
||
itemAmount = oem_amount;
|
||
else if (type == 31)
|
||
itemAmount = oem_amount;
|
||
else if (type == 23)
|
||
{
|
||
// 同一个订单只能减少一次
|
||
string orderId = row["order_id"].ParseToString();
|
||
if (orderId.IsNullOrEmpty() || deductedOrderSet.Contains(orderId))
|
||
continue;
|
||
deductedOrderSet.Add(orderId);
|
||
itemAmount = -(amount - 2.2m);
|
||
}
|
||
else
|
||
{
|
||
continue; // 其他类型不计入
|
||
}
|
||
|
||
total_amount += itemAmount;
|
||
rebate_amount += itemAmount;
|
||
|
||
settleIdLst.Add(flowId);
|
||
}
|
||
|
||
if (settleIdLst.Count == 0)
|
||
return 0;
|
||
long total_fen = (long)Math.Round(total_amount * 100m);
|
||
long rebate_fen = (long)Math.Round(rebate_amount * 100m);
|
||
string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||
// 3. 写oem金额 + 更新流水状态(同一事务)
|
||
sql = "UPDATE wxxd.oem SET available_balance=available_balance+" + total_fen +
|
||
", total_rebate_amount=total_rebate_amount+" + rebate_fen +
|
||
" WHERE oem_id='" + oem_id + "'";
|
||
var oemRst = mySql.ExecuteAffectedRows(sql);
|
||
if (!string.IsNullOrEmpty(mySql.Message) || oemRst <= 0)
|
||
throw new Exception("结算流水到账户失败");
|
||
sql = "UPDATE wxxd.user_payment_record SET settlement=1,settlement_time='" + now + "' WHERE id IN (" + string.Join(",", settleIdLst) + ")";
|
||
var flowRst = mySql.ExecuteAffectedRows(sql);
|
||
|
||
if (!string.IsNullOrEmpty(mySql.Message) || flowRst <= 0)
|
||
throw new Exception("标记流水结算失败");
|
||
return total_fen;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将数据行转换为提现记录DTO
|
||
/// </summary>
|
||
private OemWithdrawalDto BuildOemWithdrawalDto(DataRow row)
|
||
{
|
||
int withdrawal_type = row["withdrawal_type"].ParseToInt();
|
||
int status = row["status"].ParseToInt();
|
||
return new OemWithdrawalDto
|
||
{
|
||
withdrawal_no = row["withdrawal_no"].ParseToString(),
|
||
oem_id = row["oem_id"].ParseToString(),
|
||
oem_name = row.Table.Columns.Contains("oem_name") ? row["oem_name"].ParseToString() : "",
|
||
apply_user_name = row["apply_user_name"].ParseToString(),
|
||
amount = row["amount"].ParseToLong(),
|
||
fee = row["fee"].ParseToLong(),
|
||
actual_amount = row["actual_amount"].ParseToLong(),
|
||
balance_before = row["balance_before"].ParseToLong(),
|
||
balance_after = row["balance_after"].ParseToLong(),
|
||
withdrawal_type = withdrawal_type,
|
||
withdrawal_type_string = GetWithdrawalTypeString(withdrawal_type),
|
||
account_name = row["account_name"].ParseToString(),
|
||
account_no = row["account_no"].ParseToString(),
|
||
bank_name = row["bank_name"].ParseToString(),
|
||
bank_branch = row["bank_branch"].ParseToString(),
|
||
status = status,
|
||
status_string = GetWithdrawalStatusString(status),
|
||
audit_by = row["audit_by"].ParseToString(),
|
||
audit_time = row["audit_time"] == DBNull.Value ? (DateTime?)null : row["audit_time"].ParseToString().ParseToDateTime(),
|
||
audit_remark = row["audit_remark"].ParseToString(),
|
||
pay_time = row["pay_time"] == DBNull.Value ? (DateTime?)null : row["pay_time"].ParseToString().ParseToDateTime(),
|
||
pay_channel = row["pay_channel"].ParseToString(),
|
||
pay_trade_no = row["pay_trade_no"].ParseToString(),
|
||
fail_reason = row["fail_reason"].ParseToString(),
|
||
remark = row["remark"].ParseToString(),
|
||
client_ip = row["client_ip"].ParseToString(),
|
||
created_at = row["created_at"].ParseToString().ParseToDateTime(),
|
||
updated_at = row["updated_at"].ParseToString().ParseToDateTime(),
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 提现方式名称
|
||
/// </summary>
|
||
private string GetWithdrawalTypeString(int withdrawal_type)
|
||
{
|
||
switch (withdrawal_type)
|
||
{
|
||
case (int)WithdrawalType.Bank: return "银行卡";
|
||
case (int)WithdrawalType.Alipay: return "支付宝";
|
||
case (int)WithdrawalType.WeChat: return "微信";
|
||
case (int)WithdrawalType.Other: return "其他";
|
||
default: return "";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 提现状态名称
|
||
/// </summary>
|
||
private string GetWithdrawalStatusString(int status)
|
||
{
|
||
switch (status)
|
||
{
|
||
case (int)OemWithdrawalStatus.Pending: return "待审核";
|
||
case (int)OemWithdrawalStatus.Approved: return "审核通过";
|
||
case (int)OemWithdrawalStatus.Rejected: return "审核拒绝";
|
||
case (int)OemWithdrawalStatus.Paying: return "打款中";
|
||
case (int)OemWithdrawalStatus.Paid: return "已打款";
|
||
case (int)OemWithdrawalStatus.PayFailed: return "打款失败";
|
||
case (int)OemWithdrawalStatus.Cancelled: return "已取消";
|
||
default: return "";
|
||
}
|
||
}
|
||
|
||
private List<oem> GetOems(IEnumerable<string> oem_owners)
|
||
{
|
||
List<oem> productLst = new List<oem>();
|
||
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnKJD"].ConnectionString;
|
||
MysqlUtils mySql = new MysqlUtils(conn);
|
||
string sql = "SELECT * FROM wxxd.oem WHERE is_del=0";
|
||
|
||
string where = "";
|
||
if (oem_owners?.Any() ?? false)
|
||
where += $" and oem_owner in ('{string.Join("','", oem_owners)}')";
|
||
|
||
sql += where;
|
||
sql += " ORDER BY add_time DESC;";
|
||
|
||
var dt = mySql.ExecuteDataTable(sql);
|
||
mySql.Close();
|
||
|
||
if (!string.IsNullOrEmpty(mySql.Message) || dt == null)
|
||
{
|
||
return productLst;
|
||
}
|
||
|
||
try
|
||
{
|
||
|
||
foreach (DataRow row in dt.Rows)
|
||
{
|
||
oem prod = new oem
|
||
{
|
||
id = row["id"].ParseToInt(),
|
||
oem_icon = null,
|
||
oem_id = row["oem_id"].ParseToString(),
|
||
add_time = row["add_time"].ParseToString().ParseToDateTime(),
|
||
mdy_time = row["mdy_time"].ParseToString().ParseToDateTime(),
|
||
oem_img = null,
|
||
oem_name = row["oem_name"].ParseToString(),
|
||
oem_owner = row["oem_owner"].ParseToString(),
|
||
available_balance = row.Table.Columns.Contains("available_balance") ? row["available_balance"].ParseToLong() : 0,
|
||
frozen_balance = row.Table.Columns.Contains("frozen_balance") ? row["frozen_balance"].ParseToLong() : 0,
|
||
total_rebate_amount = row.Table.Columns.Contains("total_rebate_amount") ? row["total_rebate_amount"].ParseToLong() : 0,
|
||
total_withdraw_amount = row.Table.Columns.Contains("total_withdraw_amount") ? row["total_withdraw_amount"].ParseToLong() : 0,
|
||
};
|
||
productLst.Add(prod);
|
||
}
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return null;
|
||
}
|
||
return productLst;
|
||
|
||
}
|
||
}
|
||
}
|