TG.WXCRM.V4/WEB/Controllers/Base/EmployeeEmpowermentControll...

467 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Aop.Api.Domain;
using CRM.Core.DTO;
using CRM.Core.DTO.Ord;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using Ninject;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Providers.Entities;
using System.Web.Security;
using WebGrease.Css.Extensions;
using WX.CRM.BLL.Base;
using WX.CRM.BLL.Util;
using WX.CRM.Common;
using WX.CRM.Common.Employee;
using WX.CRM.Common.Layui;
using WX.CRM.Common.StockHelper;
using WX.CRM.Common.WxPay;
using WX.CRM.IBLL.Level2;
using WX.CRM.IBLL.MsgTool;
using WX.CRM.IBLL.Res;
using WX.CRM.IBLL.Util;
using WX.CRM.Model.DTO;
using WX.CRM.Model.Entity;
using WX.CRM.Model.Enum;
using WX.CRM.Model.MAP;
using WX.CRM.Model.QueryMap;
using WX.CRM.Model.SSO;
using WX.CRM.WEB.Controllers.Level2;
using WX.CRM.WEB.ViewModel.Sale;
using WX.CRM.WebHelper;
using WX.CRM.WebHelper.UtilityModel;
namespace WX.CRM.WEB.Controllers.Base
{
public class EmployeeEmpowermentController : BaseController
{
[Inject]
public ISecurityHelper sHelper { get; set; }
[Inject]
public IRES_RESOURCEMOBILE_Q _RES_RESOURCEMOBILE_Q { get; set; }
[Inject]
public ICACHE_Q cACHE_Q { get; set; }
[Inject]
public IL2_SOFT_ORDER_Q _order { get; set; }
private CACHE_BL cache_BL = new CACHE_BL();
// 初始化随机验证码
private string GenerateVerificationCode()
{
const string chars = "0123456789";
var random = new Random();
return new string(Enumerable.Repeat(chars, 6)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
// 发送验证码
public async Task<Common.Employee.ApiResult<string>> SendVerificationCode(string phoneNumber)
{
// Generate a random verification code
string code = GenerateVerificationCode();
// Send the verification code to the phone number (e.g., via SMS)
var url = "http://47.107.128.102:8096/SmsService.svc/PutSms";
var smsUrl = Utility.GetSettingOrNullByKey("SmsUrl");
if (!string.IsNullOrEmpty(smsUrl))
{
url = smsUrl;
}
var msg = "{\"typeCode\":\"ISVRSMS0001\",\"SubTypeCode\":\"verifyCode\",\"para\":\"" + code + "\"}";
//var msg = "{\"typeCode\":\"HgMsg\",\"SubTypeCode\":\"Sms_TencentRegisterDF\",\"para\":\"" + code + "\"}";
var para = JsonConvert.SerializeObject(new { message = msg, mobile = new string[] { phoneNumber } });
cache_BL.SetVerify(phoneNumber, code);
var res = Utility.PostAjaxData(url, para, Encoding.UTF8);
LogHelper.Info($"绑定账号发送短信的返回:{res}");
var resObj = JsonConvert.DeserializeObject<SmsResult>(res);
if (resObj.result)
return new Common.Employee.ApiResult<string> { code = 0, data = phoneNumber, message = "发送成功" };
else
return new Common.Employee.ApiResult<string> { code = -1, data = phoneNumber, message = "发送失败" };
}
private class SmsResult
{
public bool result { get; set; }
public int retcode { get; set; }
}
// 员工权限管理
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
public ActionResult Index()
{
//ToolBar
ToolBar tool = new ToolBar();
string[] toolbtn = new ToolButtonView().ToolButtonRight(InitRights., userRightId);
tool.AddOtherButton("Other1", "批量开通产品", "icon-lookup", "", true);
tool.AddOtherButton("Other2", "绑定账号", "icon-add", "", true);
tool.AddOtherButton("Other3", "解绑", "icon-delete", "", true);
tool.AllowButton(toolbtn);
var appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
ViewBag.appid = appid;
ViewBag.ToolBar = tool;
return View();
}
public class FreeApiResult<T>
{
public string code { get; set; }
public T data { get; set; }
public string message { get; set; }
}
// 查看软件用户具体权限,并调用更新最新赋权时间接口
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
public string GetEmpowerByAppuser(string username, string resid, string ajaxGuid)
{
var productString = "";
try
{
if (!string.IsNullOrWhiteSpace(username))
{
var url2 = cache_BL.GetValue_Parameter("ISVR_Saleclus_ProAuth");
var param = new { appid = "com.dongniu", appuserid = username };
var zxdCrmUrl = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/SSO/UpdateLastEmpowerTime";
//zxdCrmUrl = "https://localhost:44355/Api/SSO/UpdateLastEmpowerTime";
var json = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(param.ToJson(), "WK_EXT"));
Dictionary<string, string> header2 = new Dictionary<string, string>();
string retmss = Utility.PostAjaxData(url2, json, header2, Encoding.UTF8);
var result = Utility.JSONToObject<ReadModelResult>(retmss);
if (result.iRet == 0 && result.list.Any())
{
result.list.TryGetValue(username, out ReadModelValue values);
if (values != null)
{
//values.value.OrderBy(o => o.iEndTime);
foreach (var item in values.value.OrderByDescending(o => o.iEndTime))
{
productString += $"<p style='width:101%;font-size:18px'>{item.iModuleID}({item.sModuleName}) <span style='color:{(Utility.JavaLongToDateTime(item.iEndTime) > DateTime.Now ? "red" : "gray")}'> 权限到期时间:{Utility.JavaLongToDateTime(item.iEndTime)}</span></p>";
}
var newStartTime = values.value.OrderByDescending(o => o.iStartTime).FirstOrDefault().iStartTime;
var data = new UpdateLastEmpowerTime { residString = resid, timestamp = newStartTime };
var parms = JsonConvert.SerializeObject(data);
var response = Utility.PostAjaxData(zxdCrmUrl, parms, Encoding.UTF8);
}
}
}
}
catch (Exception ex)
{
LogHelper.Error("获取赋权情况数据失败" + ex.ToString());
return "获取赋权情况数据失败" + ex.ToString();
}
return productString;
}
public class UpdateLastEmpowerTime
{
public string residString { get; set; }
public long? timestamp { get; set; }
}
// 可赋权的员工列表
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
public JsonResult empowerList(Laypage pager, empowerDto dto)
{
try
{
var url = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/SSO/GetEmpowerment";
// url = "https://localhost:44355/" + "Api/SSO/GetEmpowerment";
var appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
//var userGroupList = cACHE_Q.GetList_InnerUserGroup();
var users = cACHE_Q.GetUserList();
var para = $"?appid={appid}&PageIndex={pager.page}&PageSize={pager.limit}&employeeStatus=1;3";
if (dto.eid != null) para += $"&eid={dto.eid}";
if (dto.txt_userId != null) para += $"&userId={users.FirstOrDefault(u => u.PKID == dto.txt_userId).EMPLOYEE_ID}";
if (dto.txt_departmentid != null) para += $"&deptId={dto.txt_departmentid}";
if (dto.name != null && dto.name != "") para += $"&name={dto.name}";
//if (dto.txt_groupIds != null) para += $"&groupIds={dto.txt_groupIds}";
//if (dto.txt_deptId != null) para += $"&deptId={dto.txt_deptId}";
Dictionary<string, string> header = new Dictionary<string, string>();
// 获取员工绑定账号
var res = Utility.GetData(url, para, header, Encoding.UTF8, 60000);
LogHelper.Info(res);
FreeApiResult<PageResult<GetEmpowermentDto>> reqInfo = JsonConvert.DeserializeObject<FreeApiResult<PageResult<GetEmpowermentDto>>>(res);
if (reqInfo.code != "0")
{
return Json(reqInfo.message, JsonRequestBehavior.AllowGet);
}
//var module = new List<OrderModelView>();
if (reqInfo.data != null && reqInfo.data.Data.Count == 0) return Json(reqInfo, JsonRequestBehavior.AllowGet);
var sort = 0;
reqInfo.data.Data.ForEach(employee =>
{
sort++;
employee.sort = sort;
var username = employee.appusername;
employee.productString = "";
});
return Json(reqInfo, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
LogHelper.Error("获取赋权情况数据失败" + ex.ToString());
return Json(ex, JsonRequestBehavior.DenyGet);
}
}
// 绑定
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
[HttpPost]
public string SoftEmployeeBindAdd(SoftEmployeeBindAddDto data)
{
if (!cache_BL.JudgeVerify(data.phone, data.verify_code))
{
return JsonConvert.SerializeObject(new Common.WxPay.ApiResult<bool> { code = "-1", message = "验证码不正确!", data = false });
}
var sendData = new SoftEmployeeBindChangeSendDto
{
to_by_eid = data.to_by_eid,
resid = ResUtil.CreateResId(data.phone),
from_by_eid = (int)Eid,
show_phone = Utility.ReturnPhoneNO(data.phone),
};
var zxdCrmUrl = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/SSO/AddSoftEmployeeBind";
// zxdCrmUrl = "https://localhost:7163/Api/SSO/AddSoftEmployeeBind";
var parms = JsonConvert.SerializeObject(sendData);
var response = Utility.PostAjaxData(zxdCrmUrl, parms, Encoding.UTF8);
var res = JsonConvert.DeserializeObject<ApiResult>(response);
return JsonConvert.SerializeObject(new Common.WxPay.ApiResult<bool> { code = res.Code.ToString(), message = res.Message, data = true });
}
public class SoftEmployeeBindChangeSendDto
{
public int to_by_eid { get; set; }
public string resid { get; set; }
public string show_phone { get; set; }
public int from_by_eid { get; set; }
}
// 获取软件用户名
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
[HttpPost]
public string UpdateAppusername(UpdateAppusernameString dto)
{
var zxdCrmUrl = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/SSO/UpdateAppusername";
// zxdCrmUrl = "https://localhost:44355/Api/SSO/UpdateAppusername";
var senddto = JsonConvert.DeserializeObject<List<Appuser>>(dto.UpdateAppusernameList);
var parms = JsonConvert.SerializeObject(senddto);
var response = Utility.PostAjaxData(zxdCrmUrl, parms, Encoding.UTF8);
var res = JsonConvert.DeserializeObject<ApiResult>(response);
return JsonConvert.SerializeObject(new Common.Employee.ApiResult<string> { code = res.Code, message = res.Message, data = "" });
}
// 解绑
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
[HttpPost]
public string SoftEmployeeBindDelete(SoftEmployeeBindDeleteDto data)
{
var zxdCrmUrl = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/SSO/DeleteSoftEmployeeBind";
// zxdCrmUrl = "https://localhost:7163/Api/SSO/DeleteSoftEmployeeBind";
data.from_by_eid = (int)Eid;
var parms = JsonConvert.SerializeObject(data);
var response = Utility.PostAjaxData(zxdCrmUrl, parms, Encoding.UTF8);
var res = JsonConvert.DeserializeObject<ApiResult>(response);
string retmss = "";
// 解绑后,关闭相应的免费订单
if (res.Code == 0)
{
var url2 = cache_BL.GetValue_Parameter("ISVR_Soft_Pre");
var param = new { username = data.username };
Dictionary<string, string> header2 = new Dictionary<string, string>();
retmss = Utility.PostAjaxData($"{url2}/order/doGetUserPerssion", JsonHelper.ObjDivertToJson(param), header2, Encoding.UTF8);
}
return JsonConvert.SerializeObject(new Common.WxPay.ApiResult<jsonString> { code = res.Code.ToString(), message = res.Message, data = new jsonString { json = retmss } });
}
public class jsonString
{
public string json { set; get; }
}
// 进行赋权
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
[HttpPost]
public string SetEmpowerment(SetEmpowermentDto data)
{
try
{
var tempEmployeeList = Utility.JSONToObject<List<Employee>>(data.EmployeeString);
data.EmployeeList = tempEmployeeList;
var tempProductList = Utility.JSONToObject<List<SubProduct>>(data.ProductString);
data.ProductList = tempProductList;
var zxdCrmUrl = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/SSO/SetEmpowerment";
//zxdCrmUrl = "https://localhost:7163/Api/SSO/SetEmpowerment";
// 调用开通服务
var EmployeeList = data.EmployeeList;
var errMessage = "";
for (var eIndex = 0; eIndex < EmployeeList.Count; eIndex++)
{
var curEmployee = EmployeeList[eIndex];
for (var pIndex = 0; pIndex < data.ProductList.Count; pIndex++)
{
var curPro = data.ProductList[pIndex];
var endtime = DateTime.Now.AddDays(data.duration);
data.fromByEid = (int)Eid;
decimal orderId = 0;
//var openMsg = (JsonResult)Leve2OrderController.OpenOrder(orderId.ToString(), $"{data.fromByEid}给{curEmployee.employee_id}开了{curPro.subproductid}的权限");
//var success = (JsonMessage)openMsg.Data;
//开通服务
var resFromEmpower = sendEmpower(data, curPro, curEmployee);
LogHelper.Error($"批量开通失败msg{resFromEmpower.retMsg}");
if (resFromEmpower.retCode == (int)NodeJsOrderEnum.)
{
data.orderid = resFromEmpower.orderId;
data.appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
// 开通后推送相关数据给SSO
string AppId = Utility.GetSettingByKey("appId");//坐席的appid
string Secret = Utility.GetSettingByKey("appSecret");//坐席的appid的密钥
ApiDockHelper dock = new ApiDockHelper(AppId, Secret);
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("employeeId", curEmployee.employee_id);
dic.Add("account", curEmployee.softusername);
dic.Add("operator", data.fromByEid);
dic.Add("reason", "批量开通");
var ssoUrl = cache_BL.GetValue_Parameter(Parameter.SSO_Pre_Url);
Common.Employee.ApiResult<string> model = dock.PostApi<string>(ssoUrl + "/v1/api/open/employee/ip/add", dic);
if (model.ret != 0)
{
LogHelper.Error("SSO推送开通数据错误:" + model.ToJson());
}
// 记录开通日志
var parms = JsonConvert.SerializeObject(data);
var response = Utility.PostAjaxData(zxdCrmUrl, parms, Encoding.UTF8);
}
else
{
errMessage += $"{curEmployee.softusername}开通{curPro.subproductname}产品失败;";
}
}
}
if (errMessage == "")
{
return JsonConvert.SerializeObject(new Common.WxPay.ApiResult<bool> { code = "0", message = "批量操作成功", data = true });
}
else
{
return JsonConvert.SerializeObject(new Common.WxPay.ApiResult<bool> { code = "-1", message = errMessage, data = false });
}
}
catch (Exception ex)
{
LogHelper.Error(ex);
var temp = new Common.WxPay.ApiResult<bool> { code = "-1", data = false, message = "添加失败" };
var ret = Utility.ObjectToJson(temp);
return ret;
}
}
// 赋权请求
public CreateOrderRsp sendEmpower(SetEmpowermentDto dto, SubProduct product, Employee employee)
{
freeordermodel theModel = new freeordermodel();
PhoneLogModel phoneLogModel = new PhoneLogModel
{
Method = System.Reflection.MethodBase.GetCurrentMethod().Name,
userid = 0
};
theModel.mobile = _RES_RESOURCEMOBILE_Q.GetNumberByResId(employee.resid, phoneLogModel);
theModel.needpay = product.price;
theModel.ordertype = 1;
theModel.productId = product.subproductid;
theModel.remark = $"{dto.fromByEid}给{employee.employee_id}开了{product.subproductid}的权限";
theModel.saledeptid = companyId;
theModel.source = "1";
theModel.softusername = employee.softusername;
theModel.productcode = product.productcode;//小类代码
theModel.needpay = 0;
theModel.teamserve = 1;
theModel.userid = dto.fromByEid;
theModel.productType = Convert.ToInt32(product.producttype);//产品分类
theModel.opuser = UserId;
theModel.ctime = DateTimeTool.ConvertDateTimeInt(DateTime.Now).ToString();
//theModel.companycode = companyCode;
theModel.companycode = Utility.GetSettingOrNullByKey("DataClientCode");
theModel.mainOrderId = null;
theModel.count = Convert.ToInt32(dto.duration); //产品数 --免费产品始终一天,这里天数作为数量传递,达到天数效果
var depment = cache_BL.GetList_SalesDepartMent();
// todo 通过eid拿渠道号接口
if (!string.IsNullOrEmpty(saleDeptCode))
{
var dep = depment.Find(p => p.SALEDEPTCODE == saleDeptCode);
if (dep != null)
{
if (dep.CHANNELDEF.HasValue)
theModel.ch = (int)dep.CHANNELDEF;
}
}
Console.WriteLine(System.Configuration.ConfigurationManager.AppSettings);
if (theModel.ch == null || theModel.ch == 0) theModel.ch = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Channel"]);
var url = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_FreeOrder);//内部接口··开通免费订单接口
var json = Utility.ConvertToJSON<freeordermodel>(theModel);
json = sHelper.createSignEncodingStr(json, SecurityHelper.OrderClientIdKey);
LogHelper.Info("批量开通:" + url + "?" + json);
string retmsg = Utility.PostData(url + "?" + json, Encoding.UTF8);
retmsg = sHelper.decyptData(SecurityHelper.OrderClientIdKey, retmsg);
CreateOrderRsp retmessage = JsonHelper.JsonDivertToObj<CreateOrderRsp>(retmsg);//返回信息
return retmessage;
}
// 可赋权的产品数据
[AuthorizeRedirect(Roles = InitRights.CONST_员工权限管理)]
public JsonResult productOfEmpower(Laypage pager)
{
var url = cache_BL.GetValue_Parameter(Parameter.Core_ZxdService_WebApi) + "Api/Product/GetProductByAppid";
//url = "https://localhost:7163/" + "Api/Product/GetProductByAppid";
var appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
var para = $"appid={appid}&PageIndex={pager.page}&PageSize={pager.limit}&Sort={pager.sort}&Order={pager.order}";
Dictionary<string, string> header = new Dictionary<string, string>();
var res = Utility.GetData(url, para, header, Encoding.UTF8, 60000);
//var reqInfo = JsonConvert.DeserializeObject<Common.WxPay.ApiResult<List<GetProductForEmpowerDto>>>(res);
FreeApiResult<PageResult<GetProductForEmpowerDto>> reqInfo = JsonConvert.DeserializeObject<FreeApiResult<PageResult<GetProductForEmpowerDto>>>(res);
return Json(reqInfo, JsonRequestBehavior.AllowGet);
}
}
}