using Aspose.Cells;
using Aspose.Cells.Charts;
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Tables;
using EyeSoft.Collections.Generic;
using EyeSoft.IO;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.SignalR;
using MySqlX.XDevAPI.Relational;
using NetUV.Core.Handles;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.POIFS.Properties;
using NPOI.SS.Format;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using OASystem.API.Middlewares;
using OASystem.API.OAMethodLib;
using OASystem.API.OAMethodLib.APNs;
using OASystem.API.OAMethodLib.File;
using OASystem.API.OAMethodLib.Hub.HubClients;
using OASystem.API.OAMethodLib.Hub.Hubs;
using OASystem.API.OAMethodLib.JuHeAPI;
using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
using OASystem.Domain.AesEncryption;
using OASystem.Domain.Dtos.CRM;
using OASystem.Domain.Dtos.FileDto;
using OASystem.Domain.Dtos.Financial;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Customer;
using OASystem.Domain.Entities.Financial;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels;
using OASystem.Domain.ViewModels.Financial;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Domain.ViewModels.Statistics;
using OASystem.Infrastructure.Repositories.CRM;
using OASystem.Infrastructure.Repositories.Financial;
using OASystem.Infrastructure.Repositories.Groups;
using OfficeOpenXml;
using Org.BouncyCastle.Asn1.Ocsp;
using Quartz.Util;
using SqlSugar;
using SqlSugar.Extensions;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using Ubiety.Dns.Core;
using static NPOI.POIFS.Crypt.CryptoFunctions;
using static OASystem.API.OAMethodLib.JWTHelper;
using static OASystem.Infrastructure.Repositories.Groups.AirTicketResRepository;
using static OpenAI.GPT3.ObjectModels.SharedModels.IOpenAiModels;
using Bookmark = Aspose.Words.Bookmark;
using Cell = Aspose.Words.Tables.Cell;
using Table = Aspose.Words.Tables.Table;
namespace OASystem.API.Controllers
{
///
/// 团组相关
///
//[Authorize]
[Route("api/[controller]/[action]")]
public class GroupsController : ControllerBase
{
private readonly ILogger _logger;
private readonly GrpScheduleRepository _grpScheduleRep;
private readonly IMapper _mapper;
private readonly DelegationInfoRepository _groupRepository;
private readonly TaskAssignmentRepository _taskAssignmentRep;
private readonly AirTicketResRepository _airTicketResRep;
private readonly DecreasePaymentsRepository _decreasePaymentsRep;
private readonly InvitationOfficialActivitiesRepository _InvitationOfficialActivitiesRep;
private readonly DelegationEnDataRepository _delegationEnDataRep;
private readonly DelegationVisaRepository _delegationVisaRep;
private readonly VisaPriceRepository _visaPriceRep;
private readonly CarTouristGuideGroundRepository _carTouristGuideGroundRep;
private readonly HotelPriceRepository _hotelPriceRep;
private readonly CustomersRepository _customersRep;
private readonly MessageRepository _message;
private readonly SqlSugarClient _sqlSugar;
private readonly TourClientListRepository _tourClientListRep;
private readonly TeamRateRepository _teamRateRep;
#region 成本相关
private readonly CheckBoxsRepository _checkBoxs;
private readonly GroupCostRepository _GroupCostRepository;
private readonly CostTypeHotelNumberRepository _CostTypeHotelNumberRepository;
private readonly GroupCostParameterRepository _GroupCostParameterRepository;
#endregion
private readonly SetDataRepository _setDataRep;
private string url;
private string path;
private readonly EnterExitCostRepository _enterExitCostRep;
private readonly IHubContext _hubContext;
private readonly UsersRepository _usersRep;
private readonly IJuHeApiService _juHeApi;
private readonly InvertedListRepository _invertedListRep;
private readonly VisaFeeInfoRepository _visaFeeInfoRep;
private readonly TicketBlackCodeRepository _ticketBlackCodeRep;
private readonly ThreeCodeRepository _threeCodeRepository;
private readonly HotelInquiryRepository _hotelInquiryRep;
private readonly FeeAuditRepository _feeAuditRep;
private readonly VisaCommissionRepository _visaCommissionRep;
private readonly ForeignReceivablesRepository _ffrRep; //对外收款账单仓库
private readonly OpinionaireRepository _opinionaireRep; //对外收款账单仓库
private readonly List _currencyInit;
private readonly List _portTypeData;
private readonly TableOperationRecordRepository _tableorRep;
public GroupsController(
ILogger logger,
IMapper mapper,
IHubContext hubContext,
SqlSugarClient sqlSugar,
GrpScheduleRepository grpScheduleRep,
DelegationInfoRepository groupRepository,
TaskAssignmentRepository taskAssignmentRep,
AirTicketResRepository airTicketResRep,
DecreasePaymentsRepository decreasePaymentsRep,
InvitationOfficialActivitiesRepository InvitationOfficialActivitiesRep,
DelegationEnDataRepository delegationEnDataRep,
EnterExitCostRepository enterExitCostRep,
DelegationVisaRepository delegationVisaRep,
MessageRepository message,
VisaPriceRepository visaPriceRep,
CarTouristGuideGroundRepository carTouristGuideGroundRep,
CheckBoxsRepository checkBoxs,
GroupCostRepository GroupCostRepository,
CostTypeHotelNumberRepository CostTypeHotelNumberRepository,
GroupCostParameterRepository GroupCostParameterRepository,
HotelPriceRepository hotelPriceRep,
CustomersRepository customersRep,
SetDataRepository setDataRep,
TourClientListRepository tourClientListRep,
TeamRateRepository teamRateRep,
UsersRepository usersRep, IJuHeApiService juHeApi,
InvertedListRepository invertedListRep,
VisaFeeInfoRepository visaFeeInfoRep,
TicketBlackCodeRepository ticketBlackCodeRep,
HotelInquiryRepository hotelInquiryRep,
ThreeCodeRepository threeCodeRepository,
FeeAuditRepository feeAuditRep,
VisaCommissionRepository visaCommissionRep,
ForeignReceivablesRepository ffrRep,
OpinionaireRepository opinionaireRep,
TableOperationRecordRepository tableorRep
)
{
_logger = logger;
_mapper = mapper;
_grpScheduleRep = grpScheduleRep;
_groupRepository = groupRepository;
_taskAssignmentRep = taskAssignmentRep;
_airTicketResRep = airTicketResRep;
_sqlSugar = sqlSugar;
url = AppSettingsHelper.Get("ExcelBaseUrl");
path = AppSettingsHelper.Get("ExcelBasePath");
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建文件夹
}
_decreasePaymentsRep = decreasePaymentsRep;
_InvitationOfficialActivitiesRep = InvitationOfficialActivitiesRep;
_delegationEnDataRep = delegationEnDataRep;
_enterExitCostRep = enterExitCostRep;
_delegationVisaRep = delegationVisaRep;
_message = message;
_visaPriceRep = visaPriceRep;
_carTouristGuideGroundRep = carTouristGuideGroundRep;
_checkBoxs = checkBoxs;
_GroupCostRepository = GroupCostRepository;
_CostTypeHotelNumberRepository = CostTypeHotelNumberRepository;
_GroupCostParameterRepository = GroupCostParameterRepository;
_hotelPriceRep = hotelPriceRep;
_customersRep = customersRep;
_setDataRep = setDataRep;
_tourClientListRep = tourClientListRep;
_teamRateRep = teamRateRep;
_hubContext = hubContext;
_usersRep = usersRep;
_juHeApi = juHeApi;
_invertedListRep = invertedListRep;
_visaFeeInfoRep = visaFeeInfoRep;
_ticketBlackCodeRep = ticketBlackCodeRep;
_hotelInquiryRep = hotelInquiryRep;
_threeCodeRepository = threeCodeRepository;
_feeAuditRep = feeAuditRep;
_visaCommissionRep = visaCommissionRep;
_ffrRep = ffrRep;
_opinionaireRep = opinionaireRep;
_currencyInit = new List()
{
new CurrencyInfo (){ CurrencyCode="USD",CurrencyName = "美元",Rate = 7.5000M },
new CurrencyInfo (){ CurrencyCode="EUR",CurrencyName = "欧元",Rate = 8.0000M },
new CurrencyInfo (){ CurrencyCode="GBP",CurrencyName = "英镑",Rate = 9.5000M },
new CurrencyInfo (){ CurrencyCode="JPY",CurrencyName = "日元",Rate = 0.0500M },
new CurrencyInfo (){ CurrencyCode="HKD",CurrencyName = "港币",Rate = 0.9500M },
};
_portTypeData = new List() { 2, 3 };
_tableorRep = tableorRep;
}
#region 流程管控
///
/// 获取团组流程管控信息
///
/// 参数Json字符串
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostSearchGrpSchedule(JsonDtoBase _jsonDto)
{
if (string.IsNullOrEmpty(_jsonDto.Paras))
{
return Ok(JsonView(false, "参数为空"));
}
Grp_ScheduleDto _ScheduleDto = JsonConvert.DeserializeObject(_jsonDto.Paras);
if (_ScheduleDto != null)
{
if (_ScheduleDto.SearchType == 2)//获取列表
{
List _grpScheduleViewList = await _grpScheduleRep.GetViewList_GrpSchedule(_ScheduleDto);
return Ok(JsonView(_grpScheduleViewList));
}
else//获取对象
{
Grp_ScheduleCombinView _grpScheduleView = await _grpScheduleRep.GetView_GrpSchedule(_ScheduleDto);
if (_grpScheduleView != null)
{
return Ok(JsonView(_grpScheduleView));
}
}
}
else
{
return Ok(JsonView(false, "参数反序列化失败"));
}
return Ok(JsonView(false, "暂无数据!"));
}
///
/// 修改团组流程管控详细表数据
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostUpdateGrpScheduleDetail(Grp_ScheduleDetailUpdDto dto)
{
Grp_ScheduleDetailInfo _detail = _mapper.Map(dto);
var result = await _grpScheduleRep._sqlSugar.Updateable()
.SetColumns(it => it.Duty == _detail.Duty)
.SetColumns(it => it.ExpectBeginDt == _detail.ExpectBeginDt)
.SetColumns(it => it.ExpectEndDt == _detail.ExpectEndDt)
.SetColumns(it => it.JobContent == _detail.JobContent)
.SetColumns(it => it.Remark == _detail.Remark)
.SetColumns(it => it.StepStatus == _detail.StepStatus)
.Where(s => s.Id == dto.Id)
//.UpdateColumns(s => new { s.Duty, s.ExpectBeginDt, s.ExpectEndDt, s.JobContent, s.Remark, s.StepStatus })
.ExecuteCommandAsync();
if (result > 0)
{
return Ok(JsonView(true, "保存成功!"));
}
return Ok(JsonView(false, "保存失败!"));
}
///
/// 删除团组流程管控详细表数据,删除人Id请放在Duty
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostDeleteGrpScheduleDetail(Grp_ScheduleDetailUpdDto dto)
{
Grp_ScheduleDetailInfo _detail = _mapper.Map(dto);
_detail.IsDel = 1;
_detail.DeleteUserId = dto.Duty;
_detail.DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var result = await _grpScheduleRep._sqlSugar.Updateable()
.SetColumns(it => it.IsDel == _detail.IsDel)
.SetColumns(it => it.DeleteUserId == _detail.DeleteUserId)
.SetColumns(it => it.DeleteTime == _detail.DeleteTime)
.Where(it => it.Id == dto.Id)
//.UpdateColumns(s => new { s.IsDel, s.DeleteUserId, s.DeleteTime })
//.WhereColumns(s => s.Id == dto.Id)
.ExecuteCommandAsync();
if (result > 0)
{
return Ok(JsonView(true, "删除成功!"));
}
return Ok(JsonView(false, "删除失败!"));
}
///
/// 增加团组流程管控详细表数据
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostInsertGrpScheduleDetail(Grp_ScheduleDetailInsertDto dto)
{
Grp_ScheduleDetailInfo _detail = _mapper.Map(dto);
if (DateTime.Now < _detail.ExpectBeginDt)
{
_detail.StepStatus = 0;
}
else
{//若大于设置时间,不考虑设置的预计结束日期,统一视为进行中
_detail.StepStatus = 1;
}
var result = await _grpScheduleRep._sqlSugar.Insertable(_detail).ExecuteReturnIdentityAsync();
if (result > 0)
{
Grp_ScheduleDetailView _result = await _grpScheduleRep.GetInsertBackData(result);
return Ok(JsonView(true, "添加成功!", _result));
}
return Ok(JsonView(false, "添加失败!"));
}
#endregion
#region 团组基本信息
///
/// 接团信息列表
///
/// 团组列表请求dto
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetGroupList(GroupListDto dto)
{
var groupData = await _groupRepository.GetGroupList(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(groupData.Data));
}
///
/// 分页查询团组列表
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryGroupListOffset(QueryGroupListOffsetDto dto)
{
var watch = new Stopwatch();
watch.Start();
RefAsync total = 0;
var countyDatas = await _sqlSugar.Queryable()
.Where((di) => di.IsDel == 0 && !string.IsNullOrWhiteSpace(di.TeamName))
.WhereIF(!string.IsNullOrEmpty(dto.Search), (di) => di.TeamName.Contains(dto.Search))
.OrderBy((di) => new { id = SqlFunc.Desc(di.Id) })
.Select((di) => new { id = di.Id, name = di.TeamName, di.ClientName, di.VisitPNumber, di.VisitCountry, di.VisitDays, di.VisitStartDate, di.VisitEndDate, di.TourCode })
.Distinct()
.ToPageListAsync(dto.PageIndex, dto.PageSize, total);
watch.Stop();
return Ok(JsonView(true, $"{MsgTips.Succeed},耗时 {watch.ElapsedMilliseconds} ms", countyDatas, total));
}
///
/// 接团信息列表 Page
///
/// 团组列表请求dto
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostGroupPageList(GroupPageListDto dto)
{
#region 参数验证
if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
if (dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
#region 页面操作权限验证
pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
#endregion
#endregion
if (dto.PortType == 1 || dto.PortType == 2) // web/Android
{
string sqlWhere = string.Empty;
if (dto.IsSure == 0) //未完成
{
sqlWhere += string.Format(@" And IsSure = 0");
}
else if (dto.IsSure == 1) //已完成
{
sqlWhere += string.Format(@" And IsSure = 1");
}
if (!string.IsNullOrEmpty(dto.SearchCriteria))
{
string tj = dto.SearchCriteria;
sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
tj, tj, tj, tj, tj);
}
string sql = string.Format(@"Select Row_Number,Id,SalesQuoteNo,TourCode,TeamTypeId, TeamType,
TeamLevId,TeamLev,TeamName,ClientName,ClientUnit,
VisitDate,VisitDays,VisitPNumber,JietuanOperatorId,
JietuanOperator,IsSure,CreateTime,IsBid
From (
Select row_number() over(order by gdi.CreateTime Desc) as Row_Number,
gdi.Id,SalesQuoteNo,TourCode,ssd.Id TeamTypeId, ssd.Name TeamType,
ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,ClientName,ClientUnit,
VisitDate,VisitDays,VisitPNumber,JietuanOperator JietuanOperatorId,
su.CnName JietuanOperator,IsSure,gdi.CreateTime,gdi.IsBid
From Grp_DelegationInfo gdi
Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
Left Join Sys_Users su On gdi.JietuanOperator = su.Id
Where gdi.IsDel = 0 {0}
) temp", sqlWhere);
RefAsync total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
var _DelegationList = await _sqlSugar.SqlQueryable(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total);//ToPageAsync
#region 处理所属部门
/*
* 1.sq 和 gyy 等显示 市场部
* 2.王鸽和主管及张总还有管理员号统一国交部
* 2-1. 4 管理员 ,21 张海麟
*/
List userIds = _DelegationList.Select(it => it.JietuanOperatorId).ToList();
List userIds1 = new List() { 4, 21 };
var UserDepDatas = _sqlSugar.Queryable()
.LeftJoin((u, d) => u.DepId == d.Id)
.Where(u => u.IsDel == 0 && userIds.Contains(u.Id))
.Select((u, d) => new { UserId = u.Id, DepName = userIds1.Contains(u.Id) ? "国交部" : d.DepName })
.ToList();
foreach (var item in _DelegationList)
{
item.Department = UserDepDatas.Find(it => item.JietuanOperatorId == it.UserId)?.DepName ?? "Unknown";
}
#endregion
var _view = new
{
PageFuncAuth = pageFunAuthView,
Data = _DelegationList
};
return Ok(JsonView(true, "查询成功!", _view, total));
}
else
{
return Ok(JsonView(false, "查询失败"));
}
}
///
/// 团组列表
///
///
[HttpPost]
public async Task GetGroupListByWhere(GroupListByWhere dto)
{
#region 参数验证
if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
if (dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
#region 页面操作权限验证
pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
#endregion
#endregion
if (dto.PortType != 1 && dto.PortType != 2)
{
return Ok(JsonView(false, "查询失败!"));
}
string orderbyStr = "order by gdi.CreateTime Desc";
string sqlWhere = string.Empty;
if (dto.IsSure == 0) //未完成
{
sqlWhere += string.Format(@" And IsSure = 0");
}
else if (dto.IsSure == 1) //已完成
{
sqlWhere += string.Format(@" And IsSure = 1");
}
//团组类型
if (dto.TeamDid > 0)
{
sqlWhere += string.Format(@"And TeamDid = {0} ", dto.TeamDid);
}
//团组名称
if (!string.IsNullOrEmpty(dto.TeamName))
{
sqlWhere += string.Format(@"And TeamName Like '%{0}%'", dto.TeamName);
}
//客户名称
if (!string.IsNullOrEmpty(dto.ClientName))
{
sqlWhere += string.Format(@"And ClientName Like '%{0}%'", dto.ClientName);
}
//客户单位
if (!string.IsNullOrEmpty(dto.ClientUnit))
{
sqlWhere += string.Format(@"And ClientUnit Like '%{0}%'", dto.ClientUnit);
}
//出访时间
if (!string.IsNullOrEmpty(dto.visitDataTime))
{
sqlWhere += string.Format(@"And VisitDate >= '{0}'", dto.visitDataTime);
orderbyStr = "order by gdi.VisitDate";
}
string sql = string.Format(@"Select Row_Number,Id,SalesQuoteNo,TourCode,TeamTypeId, TeamType,
TeamLevId,TeamLev,TeamName,ClientName,ClientUnit,
VisitDate,VisitDays,VisitPNumber,JietuanOperatorId,
JietuanOperator,IsSure,CreateTime
From (
Select row_number() over({0}) as Row_Number,
gdi.Id,SalesQuoteNo,TourCode,ssd.Id TeamTypeId, ssd.Name TeamType,
ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,ClientName,ClientUnit,
VisitDate,VisitDays,VisitPNumber,JietuanOperator JietuanOperatorId,
su.CnName JietuanOperator,IsSure,gdi.CreateTime
From Grp_DelegationInfo gdi
Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
Left Join Sys_Users su On gdi.JietuanOperator = su.Id
Where gdi.IsDel = 0 {1}
) temp ", orderbyStr, sqlWhere);
RefAsync total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
var _DelegationList = await _sqlSugar.SqlQueryable(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total);//ToPageAsync
#region 处理所属部门
/*
* 1.sq 和 gyy 等显示 市场部
* 2.王鸽和主管及张总还有管理员号统一国交部
* 2-1. 4 管理员 ,21 张海麟
*/
List userIds = _DelegationList.Select(it => it.JietuanOperatorId).ToList();
List userIds1 = new List() { 4, 21 };
var UserDepDatas = _sqlSugar.Queryable()
.LeftJoin((u, d) => u.DepId == d.Id)
.Where(u => u.IsDel == 0 && userIds.Contains(u.Id))
.Select((u, d) => new { UserId = u.Id, DepName = userIds1.Contains(u.Id) ? "国交部" : d.DepName })
.ToList();
foreach (var item in _DelegationList)
{
item.Department = UserDepDatas.Find(it => item.JietuanOperatorId == it.UserId)?.DepName ?? "Unknown";
}
#endregion
var _view = new
{
PageFuncAuth = pageFunAuthView,
Data = _DelegationList
};
return Ok(JsonView(true, "查询成功!", _view, total));
}
///
/// 接团信息详情
///
/// 团组info请求dto
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetGroupInfo(GroupInfoDto dto)
{
var groupData = await _groupRepository.GetGroupInfo(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(groupData.Data));
}
///
/// 接团信息 编辑添加
/// 基础信息数据源
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GroupEditBasicSource(GroupListDto dto)
{
var groupData = await _groupRepository.GroupEditBasicSource(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(groupData.Data));
}
///
/// 接团信息 操作(增改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GroupOperation(GroupOperationDto dto)
{
try
{
decimal ffrPrice = 0.00M;
DateTime? visitDt = null;
if (dto.Status == 2)
{
var groupInfo = await _sqlSugar.Queryable().FirstAsync(x => x.Id == dto.Id && x.IsDel == 0);
if (groupInfo != null)
{
ffrPrice = groupInfo.PaymentMoney;
visitDt = groupInfo.VisitDate.AddDays(-groupInfo.PayDay);
}
}
var groupData = await _groupRepository.GroupOperation(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
int diId = 0;
//添加时 默认加入团组汇率
if (dto.Status == 1) //添加
{
diId = groupData.Data;
//添加默认币种
await GeneralMethod.PostGroupRateAddInit(dto.UserId, diId);
//默认分配权限
await GeneralMethod.PostGroupAuthAddInit(dto.UserId, diId);
//消息提示 王鸽 主管号 2024-10-21 新增LZ UID
var _managerIds = new List() { 22, 32, 21 };
var userIds = _usersRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && _managerIds.Contains(it.JobPostId)).Select(it => it.Id).ToList();
if (userIds.Count > 0)
{
userIds.Add(208);
//创建团组管控
GroupStepForDelegation.CreateWorkStep(diId);
//发送消息
string groupName = dto.TeamName;
string createGroupUser = string.Empty;
var userInfo = _usersRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.Id == dto.UserId).First();
if (userInfo != null) createGroupUser = userInfo.CnName;
string title = $"系统通知";
string content = $"团组[{groupName}(创建人:{createGroupUser})]创建成功,请前往页面进行下一步操作!";
await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
}
//默认创建倒推表
await _invertedListRep._Create(dto.UserId, diId);
}
else if (dto.Status == 2)
{
diId = dto.Id;
}
#region 签证人员团组时间通知
#region 计算出访起止时间
var startTime = new DateTime();
var endTime = new DateTime();
if (DateTime.TryParse(dto.VisitDate, out startTime))
{
endTime = startTime.AddDays(dto.VisitDays - 1);//含当天
}
#endregion
if (diId > 0)
{
await AppNoticeLibrary.SendUserMsg_GroupTimeInfo_ToVisaUser(diId, startTime.ToString("yyyy-MM-dd"), endTime.ToString("yyyy-MM-dd"));
}
#endregion
#region 团组操作默认添加/修改收款账单
if (dto.PayDay > 0 && dto.PaymentMoney > 0)
{
var ffrInfo = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 &&
x.Diid == diId &&
x.Remark.Equals("预付款")
)
.WhereIF(ffrPrice > 0, x => x.ItemSumPrice == ffrPrice)
.WhereIF(visitDt != null, x => x.CreateTime == visitDt)
.FirstAsync();
ffrInfo = new Fin_ForeignReceivables()
{
Diid = diId,
PriceName = dto.ClientUnit,
Price = dto.PaymentMoney,
Count = 1,
Unit = $"元",
ItemSumPrice = dto.PaymentMoney,
Rate = 1.0000M,
Currency = 836,
AddingWay = 0,
CreateUserId = dto.UserId,
CreateTime = Convert.ToDateTime(dto.VisitDate).AddDays(-dto.PayDay),
Remark = $"预付款"
};
if (ffrInfo == null) //Add
{
await _sqlSugar.Insertable(ffrInfo).ExecuteCommandAsync();
}
else //修改
{
await _sqlSugar.Updateable(ffrInfo)
.UpdateColumns(x => new
{
x.PriceName,
x.Price,
x.ItemSumPrice,
x.CreateTime,
x.CreateUserId
})
.WhereColumns(x => x.Id)
.ExecuteCommandAsync();
}
}
#endregion
return Ok(JsonView(true, "操作成功!", diId));
}
catch (Exception ex)
{
Logs("[response]" + JsonConvert.SerializeObject(dto));
Logs(ex.Message);
return Ok(JsonView(false, ex.Message));
}
}
///
/// 接团流程操作(增改)
/// 安卓端使用 建团时添加客户名单
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GroupProcessOperation(GroupProcessOperationDto dto)
{
try
{
#region 参数验证
if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数"));
PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
#region 页面操作权限验证
//pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, 104);
//if (pageFunAuthView.AddAuth == 0) return Ok(JsonView(false, "客户名单您没有添加权限!"));
pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, 27);
if (pageFunAuthView.AddAuth == 0) return Ok(JsonView(false, "团组操作您没有添加权限!"));
#endregion
#endregion
_sqlSugar.BeginTran();
decimal ffrPrice = 0.00M;
DateTime? visitDt = null;
if (dto.Status == 2)
{
var groupInfo = await _sqlSugar.Queryable().FirstAsync(x => x.Id == dto.Id && x.IsDel == 0);
if (groupInfo != null)
{
ffrPrice = groupInfo.PaymentMoney;
visitDt = groupInfo.VisitDate.AddDays(-groupInfo.PayDay);
}
}
var _dto = new GroupOperationDto();
_dto = _mapper.Map(dto);
var groupData = await _groupRepository.GroupOperation(_dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, "团组操作添加失败!" + groupData.Msg));
}
int diId = 0;
//添加时 默认加入团组汇率
if (dto.Status == 1) //添加
{
diId = groupData.Data;
//添加默认币种
await GeneralMethod.PostGroupRateAddInit(dto.UserId, diId);
//默认分配权限
await GeneralMethod.PostGroupAuthAddInit(dto.UserId, diId);
//消息提示 王鸽 主管号 2024-10-21 新增LZ UID
List _managerIds = new List() { 21, 22, 32 };
var userIds = _usersRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && _managerIds.Contains(it.JobPostId)).Select(it => it.Id).ToList();
if (userIds.Count > 0)
{
userIds.Add(208);
//创建团组管控
GroupStepForDelegation.CreateWorkStep(diId);
//发送消息
string groupName = dto.TeamName;
string createGroupUser = string.Empty;
var userInfo = _usersRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.Id == dto.UserId).First();
if (userInfo != null) createGroupUser = userInfo.CnName;
string title = $"系统通知";
string content = $"团组[{groupName}(创建人:{createGroupUser})]创建成功,请前往页面进行下一步操作!";
await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
}
#region 应用推送
try
{
await AppNoticeLibrary.SendChatMsg_GroupStatus_Create(diId, QiyeWeChatEnum.CompanyCRMChat);
Sys_Users users = _airTicketResRep.Query(s => s.Id == dto.UserId).First();
Sys_Department department = _airTicketResRep.Query(s => s.Id == users.DepId).First();
if (department.Id == 6 && !string.IsNullOrEmpty(users.QiyeChatUserId))
{
List userList = new List() { users.QiyeChatUserId };
await AppNoticeLibrary.SendUserMsg_GroupStatus_Create(diId, userList);
}
}
catch (Exception ex)
{
}
#endregion
//默认创建倒推表
await _invertedListRep._Create(dto.UserId, diId);
}
if (dto.Status == 2)
{
diId = dto.Id;
if (diId == 0)
{
return Ok(JsonView(false, "修改失败! 未添加团组id" + groupData.Msg));
}
}
var viewData = await _tourClientListRep.OperMultiple(dto.TourClientListInfos, diId, dto.UserId);
if (viewData.Code != 0)
{
_sqlSugar.RollbackTran();
return Ok(JsonView(false, "客户名单添加失败!" + viewData.Msg));
}
#region 团组操作默认添加/修改收款账单
if (dto.PayDay > 0 && dto.PaymentMoney > 0)
{
var ffrInfo = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 &&
x.Diid == diId &&
x.Remark.Equals("预付款")
)
.WhereIF(ffrPrice > 0, x => x.ItemSumPrice == ffrPrice)
.WhereIF(visitDt != null, x => x.CreateTime == visitDt)
.FirstAsync();
ffrInfo = new Fin_ForeignReceivables()
{
Diid = diId,
PriceName = dto.ClientUnit,
Price = dto.PaymentMoney,
Count = 1,
Unit = $"元",
ItemSumPrice = dto.PaymentMoney,
Rate = 1.0000M,
Currency = 836,
AddingWay = 0,
CreateUserId = dto.UserId,
CreateTime = Convert.ToDateTime(dto.VisitDate).AddDays(-dto.PayDay),
Remark = $"预付款"
};
if (ffrInfo == null) //Add
{
await _sqlSugar.Insertable(ffrInfo).ExecuteCommandAsync();
}
else //修改
{
await _sqlSugar.Updateable(ffrInfo)
.UpdateColumns(x => new
{
x.PriceName,
x.Price,
x.ItemSumPrice,
x.CreateTime,
x.CreateUserId
})
.WhereColumns(x => x.Id)
.ExecuteCommandAsync();
}
}
#endregion
#region 签证人员团组时间通知
#region 计算出访起止时间
var startTime = new DateTime();
var endTime = new DateTime();
if (DateTime.TryParse(dto.VisitDate, out startTime))
{
endTime = startTime.AddDays(dto.VisitDays - 1);//含当天
}
#endregion
if (diId > 0)
{
await AppNoticeLibrary.SendUserMsg_GroupTimeInfo_ToVisaUser(diId, startTime.ToString("yyyy-MM-dd"), endTime.ToString("yyyy-MM-dd"));
}
#endregion
_sqlSugar.CommitTran();
return Ok(JsonView(true, "添加成功"));
}
catch (Exception ex)
{
_sqlSugar.RollbackTran();
return Ok(JsonView(false, ex.Message));
}
}
///
/// 接团信息 操作(删除)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GroupDel(GroupDelDto dto)
{
var diId = dto.Id;
if (diId < 1) return Ok(JsonView(false,MsgTips.Id));
#region 删除 验证 (费用录入、出入境费用、收款账单)
//var feeCount = _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.DIId == diId).Count();
//var eccCount = _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.DiId == diId).Count();
//var frCount = _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Diid == diId).Count();
//if (feeCount > 0 || feeCount > 0 || feeCount > 0) return Ok(JsonView(false, "该团组存在费用不可删除!"));
#endregion
var groupData = await _groupRepository.GroupDel(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true));
}
///
/// 获取团组销售报价号
/// 团组添加时 使用
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetGroupSalesQuoteNo()
{
var groupData = await _groupRepository.GetGroupSalesQuoteNo();
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
object salesQuoteNo = new
{
SalesQuoteNo = groupData.Data
};
return Ok(JsonView(salesQuoteNo));
}
///
/// 设置确认出团
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task SetConfirmationGroup(ConfirmationGroupDto dto)
{
var groupData = await _groupRepository.ConfirmationGroup(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
var groupInfo = _groupRepository.Query(s => s.Id == dto.GroupId).First();
#region OA消息推送
try
{
string groupName = groupInfo.TeamName;
var userIds = _airTicketResRep.Query(s => s.DepId == 7 && s.IsDel == 0).Select(x => x.Id).ToList();
string title = $"系统通知";
string content = $"团组[{groupName}]已确认出团!";
await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, dto.GroupId);
}
catch (Exception ex)
{
}
#endregion
#region 应用推送
try
{
await AppNoticeLibrary.SendChatMsg_GroupStatus_Create(dto.GroupId, QiyeWeChatEnum.CompanyCRMChat);
Sys_Users users = _airTicketResRep.Query(s => s.Id == groupInfo.JietuanOperator).First();
Sys_Department department = _airTicketResRep.Query(s => s.Id == users.DepId).First();
if (department.Id == 6 && !string.IsNullOrEmpty(users.QiyeChatUserId))
{
List userList = new List() { users.QiyeChatUserId };
await AppNoticeLibrary.SendUserMsg_GroupStatus_Create(dto.GroupId, userList);
}
}
catch (Exception ex)
{
}
#endregion
GroupStepForDelegation.CreateWorkStep(dto.GroupId); //创建管控流程
return Ok(JsonView(true, "操作成功!", groupData.Data));
}
///
/// 获取团组名称data And 签证国别Data
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetGroupNameAndVisaNationality(GroupNameDto dto)
{
var groupData = await _groupRepository.GetGroupNameAndVisaNationality(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(groupData.Data));
}
///
/// 根据CTable类型返回对应的团组名称及简单数据(APP端)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostGroupNameAndEasy(DecreasePaymentsDto dto)
{
try
{
Result groupData = await _decreasePaymentsRep.PostGroupNameAndEasy(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 团组清单 Excel
///
/// 开始时间 EG:“2024-01-01”
/// 结束时间 EG;“2024-12-31”
///
[HttpGet]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GroupListFile([FromQuery] string beginDt, [FromQuery] string endDt)
{
DateTime _beginDt, _endDt;
bool beginBool = DateTime.TryParse($"{beginDt} 00:00:00", out _beginDt),
endBool = DateTime.TryParse($"{endDt} 23:59:59", out _endDt);
if (!beginBool && !endBool)
{
return Ok(JsonView(false, "开始或结束时间不正确!"));
}
string sql = string.Format(@"
SELECT
ROW_NUMBER,
Id,
SalesQuoteNo,
TourCode,
TeamTypeId,
TeamType,
TeamLevId,
TeamLev,
TeamName,
ClientName,
ClientUnit,
VisitDate,
VisitDays,
VisitPNumber,
JietuanOperatorId,
JietuanOperator,
IsSure,
CreateTime,
IsBid
FROM
(
SELECT
ROW_NUMBER() OVER(
ORDER BY
gdi.CreateTime Desc
) AS ROW_NUMBER,
gdi.Id,
SalesQuoteNo,
TourCode,
ssd.Id TeamTypeId,
ssd.Name TeamType,
ssd1.Id TeamLevId,
ssd1.Name TeamLev,
TeamName,
ClientName,
ClientUnit,
VisitDate,
VisitDays,
VisitPNumber,
JietuanOperator JietuanOperatorId,
su.CnName JietuanOperator,
IsSure,
gdi.CreateTime,
gdi.IsBid
FROM
Grp_DelegationInfo gdi
LEFT JOIN Sys_SetData ssd ON gdi.TeamDid = ssd.Id
LEFT JOIN Sys_SetData ssd1 ON gdi.TeamLevSId = ssd1.Id
LEFT JOIN Sys_Users su ON gdi.JietuanOperator = su.Id
WHERE
gdi.IsDel = 0
AND gdi.IsBid = 0
AND gdi.CreateTime BETWEEN '{0}' AND '{1}'
) temp", _beginDt.ToString("yyyy-MM-dd HH:mm:ss"), _endDt.ToString("yyyy-MM-dd HH:mm:ss"));
var groupList = await _sqlSugar.SqlQueryable(sql).ToListAsync();
#region 处理所属部门
/*
* 1.sq 和 gyy 等显示 市场部
* 2.王鸽和主管及张总还有管理员号统一国交部
* 2-1. 4 管理员 ,21 张海麟
*/
List userIds = groupList.Select(it => it.JietuanOperatorId).ToList();
List userIds1 = new List() { 4, 21 };
var userDepDatas = await _sqlSugar.Queryable()
.LeftJoin((u, d) => u.DepId == d.Id)
.Where(u => u.IsDel == 0 && userIds.Contains(u.Id))
.Select((u, d) => new { UserId = u.Id, DepName = userIds1.Contains(u.Id) ? "国交部" : d.DepName })
.ToListAsync();
foreach (var item in groupList)
{
item.Department = userDepDatas.Find(it => item.JietuanOperatorId == it.UserId)?.DepName ?? "Unknown";
}
#endregion
#region Excel
var tempPath = AppSettingsHelper.Get("ExcelTempPath");
var servicePath = AppSettingsHelper.Get("GrpFileBaseUrl");
var savePath = AppSettingsHelper.Get("GrpListFileBasePath");
var ftpPath = AppSettingsHelper.Get("GrpListFileFtpPath");
var fileName = $"团组清单({beginDt}~{endDt}){DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
//载入模板
WorkbookDesigner designer = new WorkbookDesigner();
designer.Workbook = new Workbook($"{tempPath}团组清单模板.xlsx");
designer.SetDataSource("Titel", $"团组清单({beginDt}~{endDt})");
DataTable dt = CommonFun.GetDataTableFromIList(groupList); ;
dt.TableName = "GroupList";
designer.SetDataSource(dt);
designer.Process();
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
string serverPath = $"{savePath}{fileName}";
designer.Workbook.Save(serverPath);
string rst = $"{servicePath}{ftpPath}{fileName}";
#endregion
return Ok(JsonView(true, "操作成功!", rst));
}
#endregion
#region 团组&签证
///
/// 根据团组Id获取签证客户信息List
///
/// 请求dto
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetCrmByGroupId(ClientByGroupIdDto dto)
{
var groupData = await _groupRepository.GetCrmByGroupId(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(groupData.Data));
}
///
/// IOS获取团组签证拍照上传进度01(团组列表)
///
/// 请求dto
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostIOSVisaProgress(IOS_VisaDto dto)
{
if (dto == null)
{
return Ok(JsonView(false, "参数为空"));
}
DelegationVisaViewList visaList = _delegationVisaRep.GetDelegationList(dto);
return Ok(JsonView(visaList));
}
///
/// IOS获取团组签证拍照上传进度02(团组签证详情\人员列表\国家)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostIOSVisaProgressContent(IOS_VisaCustomerListDto dto)
{
if (dto == null)
{
return Ok(JsonView(false, "请求错误:"));
}
List list = _delegationVisaRep.GetDelegationProgressList(dto.diId);
return Ok(JsonView(list));
}
///
/// IOS获取团组签证拍照上传进度03(相册)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostIOSVisaProgressImageList(IOS_VisaImageListDto dto)
{
if (dto == null)
{
return Ok(JsonView(false, "请求错误:"));
}
List list = _delegationVisaRep.GetVisaProgressImageList(dto.visaProgressCustomerId, dto.picType);
string url = AppSettingsHelper.Get("VisaProgressImageBaseUrl") + AppSettingsHelper.Get("VisaProgressImageFtpPath");
list.ForEach(s => s.url = url);
return Ok(JsonView(list));
}
///
/// IOS获取团组签证拍照上传进度04(图片上传)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostIOSVisaProgressUploadImage(IOS_VisaUploadImageDto dto)
{
//string result = decodeBase64ToImage(dto.base64DataURL, dto.imageName);
//if (!string.IsNullOrEmpty(result))
//{
//}
//else {
// return Ok(JsonView(false, "上传失败"));
//}
DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
int sucNum = 0;
try
{
foreach (var item in dto.base64DataList)
{
string imageName = dto.imageName + ((DateTime.Now.Ticks - dt1970.Ticks) / 10000).ToString();
string result = decodeBase64ToImage(item, imageName);
if (!string.IsNullOrEmpty(result))
{
Grp_VisaProgressCustomerPicture pic = new Grp_VisaProgressCustomerPicture();
pic.CreateUserId = dto.CreateUserId;
pic.PicName = imageName;
pic.PicPath = result;
pic.VisaProgressCustomerId = dto.visaProgressCustomerId;
int insertResult = await _delegationVisaRep.AddAsync(pic);
if (insertResult > 0)
{
sucNum++;
}
}
}
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
}
string msg = string.Format(@"成功上传{0}张", sucNum);
return Ok(JsonView(true, msg));
}
private string decodeBase64ToImage(string base64DataURL, string imgName)
{
string filename = "";//声明一个string类型的相对路径
String base64 = base64DataURL.Substring(base64DataURL.IndexOf(",") + 1); //将‘,’以前的多余字符串删除
System.Drawing.Bitmap bitmap = null;//定义一个Bitmap对象,接收转换完成的图片
try//会有异常抛出,try,catch一下
{
byte[] arr = Convert.FromBase64String(base64);//将纯净资源Base64转换成等效的8位无符号整形数组
System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);//转换成无法调整大小的MemoryStream对象
bitmap = new System.Drawing.Bitmap(ms);//将MemoryStream对象转换成Bitmap对象
var fileDir = AppSettingsHelper.Get("VisaProgressImageBasePath");
//文件名称
filename = "VisaProgress_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + imgName + ".jpeg";//所要保存的相对路径及名字
//上传的文件的路径
string filePath = "";
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//上传的文件的路径
filePath = fileDir + filename;
//string url = HttpRuntime.AppDomainAppPath.ToString();
//string tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录
//string imagesurl2 = tmpRootDir + filename; //转换成绝对路径
bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到服务器路径
//bitmap.Save(filePath + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
//bitmap.Save(filePath + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
//bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
ms.Close();//关闭当前流,并释放所有与之关联的资源
bitmap.Dispose();
}
catch (Exception e)
{
string massage = e.Message;
Logs("IOS图片上传Error:" + massage);
//filename = e.Message;
}
return filename;//返回相对路径
}
///
/// IOS获取团组签证拍照上传进度05(修改签证状态/通知)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostIOSVisaProgressChangeStatus(IOS_VisaChangeStatusDto dto)
{
if (dto == null)
{
return Ok(JsonView(false, "请求错误:"));
}
string msg = "参数错误";
if (dto.diId > 0 && dto.visaStatus > 0 && dto.visaStatus < 4)
{
try
{
//_delegationVisaRep.BeginTran();
var updCount = await _delegationVisaRep._sqlSugar.Updateable()
.SetColumns(it => it.WorkStatus == dto.visaStatus)
.Where(s => s.Id == dto.visaProgressCustomerId)
.ExecuteCommandAsync();
if (updCount > 0 && dto.publishCode == 1)
{
_delegationVisaRep.ChangeDataBase(DBEnum.OA2014DB); //切换到新OA后删除
string sqlDelegation = string.Format(@" Select * From DelegationInfo With(Nolock) Where Id = {0} ", dto.diId);
OA2021_DelegationInfo groupData = _sqlSugar.SqlQueryable(sqlDelegation).First();
//GroupInfoDto grpDto = new GroupInfoDto() { Id = dto.diId };
//var groupData = await _groupRepository.GetGroupInfo(grpDto);
_delegationVisaRep.ChangeDataBase(DBEnum.OA2023DB); //切换到新OA后删除
if (groupData == null)
{
_delegationVisaRep.RollbackTran();
}
string title = string.Format(@"[签证进度更新]");
string content = string.Format(@"测试文本");
bool rst = await _message.AddMsg(new MessageDto()
{
Type = MessageTypeEnum.GroupVisaProgressUpdate,
IssuerId = dto.publisher,
Title = title,
Content = content,
ReleaseTime = DateTime.Now,
UIdList = new List {
234
}
});
if (rst)
{
return Ok(JsonView(true, "发送通知成功"));
}
}
//_delegationVisaRep.CommitTran();
}
catch (Exception)
{
//_delegationVisaRep.RollbackTran();
}
}
return Ok(JsonView(true, msg));
}
#endregion
#region 团组任务分配
///
/// 团组任务分配初始化
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetTaskAssignmen()
{
var groupData = await _taskAssignmentRep.GetTaskAssignmen();
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 团组任务分配查询
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task TaskAssignmenQuery(TaskAssignmenQueryDto dto)
{
var groupData = await _taskAssignmentRep.TaskAssignmenQuery(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 团组任务分配操作
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetTaskAssignmenOp(TaskAssignmenDto dto)
{
Result groupData = await _taskAssignmentRep.GetTaskAssignmenOp(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 团组任务分配
/// 批量分配
/// 查询团组
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task TaskAllocationGroupSelect(TaskAllocationGroupSelectDto dto)
{
//参数验证
if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
if (!DateTime.TryParse(dto.VisitBeginDt, out _) || !DateTime.TryParse(dto.VisitEndDt, out _))
return Ok(JsonView(false, "团组出访开始/结束日期格式不正确!"));
return Ok(await _taskAssignmentRep.TaskAllocationGroupSelect(dto));
}
///
/// 团组任务分配
/// 批量分配
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task TaskAllocationBulkAdd(TaskAllocationBulkAddDto dto)
{
//参数验证
if (dto.UserIds.Length < 1) return Ok(JsonView(false, $"请选择分配人员!"));
if (dto.PermissionTypeIds.Length < 1) return Ok(JsonView(false, $"请选择分配类型!"));
if (dto.GroupIds.Length < 1) return Ok(JsonView(false, "请选择分配团组Id"));
if (dto.CurrUserId < 1) return Ok(JsonView(false, "请传入有效的CurrUserId数组参数"));
return Ok(await _taskAssignmentRep.TaskAllocationBulkAdd(dto));
}
#endregion
#region 团组费用审核
///
/// 费用审核
/// 团组列表 Page
///
/// 团组列表请求dto
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostExpenseAuditGroupPageItems(ExpenseAuditGroupPageItemsDto _dto)
{
#region 参数验证
if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
#region 页面操作权限验证
pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
#endregion
#endregion
if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 2) // web/Android/IOS
{
string sqlWhere = string.Empty;
if (_dto.IsSure == 0) //未完成
{
sqlWhere += string.Format(@" And IsSure = 0");
}
else if (_dto.IsSure == 1) //已完成
{
sqlWhere += string.Format(@" And IsSure = 1");
}
if (!string.IsNullOrEmpty(_dto.SearchCriteria))
{
string tj = _dto.SearchCriteria;
sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
tj, tj, tj, tj, tj);
}
string sql = string.Format(@"Select Row_Number,Id,SalesQuoteNo,TourCode,TeamTypeId, TeamType,
TeamName,ClientName,ClientUnit, TeamLevId,TeamLev,VisitDate,
VisitDays,VisitPNumber,JietuanOperator,IsSure,CreateTime
From (
Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
gdi.Id,SalesQuoteNo,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
ClientName,ClientUnit,ssd.Id TeamTypeId, ssd.Name TeamType,VisitDate,
VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime
From Grp_DelegationInfo gdi
Inner Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
Inner Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
Left Join Sys_Users su On gdi.JietuanOperator = su.Id
Where gdi.IsDel = 0 {0}
) temp ", sqlWhere);
RefAsync total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
var _DelegationList = await _sqlSugar.SqlQueryable(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
var _view = new
{
PageFuncAuth = pageFunAuthView,
Data = _DelegationList
};
return Ok(JsonView(true, "查询成功!", _view, total));
}
else
{
return Ok(JsonView(false, "查询失败"));
}
}
///
/// 获取团组费用审核
///
/// 参数Json字符串
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostSearchGrpCreditCardPayment(Search_GrpCreditCardPaymentDto _dto)
{
try
{
#region 参数验证
if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
#region 页面操作权限验证
var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
#endregion
#endregion
var _view = new Grp_CreditCardPaymentView();
var clientNameList = getSimplClientList(_dto.DiId);
#region 费用清单
var exp = Expressionable.Create();
exp.AndIF(_dto.AuditStatus != -1, it => it.IsAuditGM == _dto.AuditStatus);
exp.AndIF(_dto.Label != -1, it => it.CTable == _dto.Label);
var entityList = _groupRepository .Query(s => s.DIId == _dto.DiId && s.IsDel == 0 && s.CreateUserId > 0).Where(exp.ToExpression()).ToList();
var detailList = new List();
var ccpCurrencyPrices = new List();
/*
* 76://酒店预订
*/
var _HotelReservations = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
var _HotelReservationsContents = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 79://车/导游地接
*/
var _CarTouristGuideGroundReservations = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
var _CarTouristGuideGroundReservationsContent = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 80: //签证
*/
var _VisaInfos = await _groupRepository.Query(s => s.DIId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
*81: //邀请/公务活动
*/
var _InvitationOfficialActivities = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 82: //团组客户保险
*/
var _Customers = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* Lable = 85 机票预订
*/
var p_AirTicketReservations = await _groupRepository.Query(s => s.DIId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 85 机票预定
*/
var _AirTicketReservations = await _groupRepository.Query(s => s.DIId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 98 其他款项
*/
var _DecreasePayments = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 285:收款退还
*/
var _PaymentRefundAndOtherMoneys = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 1015: //超支费用
*/
var _GroupExtraCosts = await _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).ToListAsync();
/*
* 币种信息
*/
var currencyItems = await _groupRepository.Query(s => s.STid == 66 && s.IsDel == 0).ToListAsync();
/*
* 车/导游地接 费用类型
*/
var carFeeTypeItems = await _groupRepository.Query(s => s.STid == 17 && s.IsDel == 0).ToListAsync();
/*
* 车/导游地接 费用类型
*/
var carFeeItems = await _groupRepository.Query(s => s.STid == 83 && s.IsDel == 0).ToListAsync();
var initDatas = await _groupRepository.Query(s => s.IsDel == 0).ToListAsync();
var cityData = await _groupRepository.Query(s => s.IsDel == 0).ToListAsync();
/*
* 用户信息
*/
var userItems = await _groupRepository.Query(s => s.IsDel == 0).ToListAsync();
/*
* 费用模块
*/
var sdPriceName = _groupRepository.Query(s => s.Id == _dto.Label).First();
string priceModule = string.Empty;
if (sdPriceName != null)
{
priceModule = sdPriceName.Name;
}
/*
* 成本信息
*/
var groupCost = _groupRepository.Query(s => s.DiId == _dto.DiId && s.IsDel == 0).First();
decimal _groupRate = 0.0000M;
string _groupCurrencyCode = "-";
if (groupCost != null)
{
_groupRate = groupCost.Rate;
if (int.TryParse(groupCost.Currency, out int _currency))
{
_groupCurrencyCode = currencyItems.Find(it => it.Id == _currency)?.Name ?? "-";
}
else _groupCurrencyCode = groupCost.Currency;
}
string costContentSql = $"Select * From Grp_GroupCost";
var groupCostDetails = _sqlSugar.SqlQueryable(costContentSql).Where(x => x.IsDel == 0 && x.Diid == _dto.DiId).ToList();
//处理日期为空的天数
for (int i = 0; i < groupCostDetails.Count; i++)
if (i != 0)
if (string.IsNullOrEmpty(groupCostDetails[i].Date))
groupCostDetails[i].Date = groupCostDetails[i - 1].Date;
/*
* 处理详情数据
*/
foreach (var entity in entityList)
{
var _detail = new Grp_CreditCardPaymentDetailView();
_detail.Id = entity.Id;
_detail.PriceName = priceModule;
_detail.PayType = initDatas.Find(it => it.Id == entity.PayDId)?.Name ?? "-";
if (_detail.PayType.Equals("现金")) _detail.CardType = "-";
else _detail.CardType = initDatas.Find(it => it.Id == entity.CTDId)?.Name ?? "-";
//处理金额
if (entity.CTable == 1015)
{
var czInfo = _GroupExtraCosts.Find(x => entity.CId == x.Id);
if (czInfo != null)
{
entity.PayMoney = czInfo.Price * czInfo.PriceCount;
entity.RMBPrice = czInfo.Price * czInfo.PriceCount * entity.DayRate;
}
}
/*
* 应付款金额
*/
var sdPaymentCurrency_WaitPay = currencyItems.Where(s => s.Id == entity.PaymentCurrency).FirstOrDefault();
string PaymentCurrency_WaitPay = "Unknown";
string hotelCurrncyCode = "Unknown";
string hotelCurrncyName = "Unknown";
if (sdPaymentCurrency_WaitPay != null)
{
PaymentCurrency_WaitPay = sdPaymentCurrency_WaitPay.Name;
hotelCurrncyCode = sdPaymentCurrency_WaitPay.Name;
hotelCurrncyName = sdPaymentCurrency_WaitPay.Remark;
if (hotelCurrncyCode.Equals("CNY"))
{
entity.DayRate = 1.0000M;
}
}
_detail.WaitPay = entity.PayMoney.ConvertToDecimal1().ToString("#0.00") + " " + PaymentCurrency_WaitPay;
/*
* 此次付款金额
*/
decimal CurrPayStr = 0.00M,
OriginalCurrPay = 0.00M;
if (entity.PayPercentage == 0)
{
if (entity.PayThenMoney != 0)
CurrPayStr = (entity.PayThenMoney * entity.DayRate).ConvertToDecimal1();
}
else
{
if (entity.PayMoney != 0)
{
CurrPayStr = (entity.PayMoney * entity.PayPercentage / 100 * entity.DayRate).ConvertToDecimal1();
}
}
//if (_dto.Label == 79)
//{
// string original = string.Empty;
// if (hotelCurrncyCode.Equals("CNY"))
// {
// OriginalCurrPay = CurrPayStr;
// _detail.CurrPay = CurrPayStr.ToString("#0.00") + " CNY";
// }
// else
// {
// OriginalCurrPay = ((entity.PayMoney / 100) * entity.PayPercentage).ConvertToDecimal1();
// //760 EUR(7600.00 CNY)
// _detail.CurrPay = $"{OriginalCurrPay.ToString("#0.00")} {hotelCurrncyCode}({CurrPayStr.ToString("#0.00")} CNY)";
// }
//}
//else _detail.CurrPay = CurrPayStr.ToString("#0.00") + " CNY";
string original = string.Empty;
if (hotelCurrncyCode.Equals("CNY"))
{
OriginalCurrPay = CurrPayStr;
_detail.CurrPay = CurrPayStr.ToString("#0.00") + " CNY";
}
else
{
OriginalCurrPay = ((entity.PayMoney / 100) * entity.PayPercentage).ConvertToDecimal1();
//760 EUR(7600.00 CNY)
_detail.CurrPay = $"{OriginalCurrPay.ToString("#0.00")} {hotelCurrncyCode}({CurrPayStr.ToString("#0.00")} CNY)";
}
/*
* 剩余尾款
*/
decimal BalanceStr = 0;
if (CurrPayStr != 0)
{
if (entity.PayMoney - (CurrPayStr / entity.DayRate) < 0.01M)
BalanceStr = 0;
else
BalanceStr = (entity.PayMoney - CurrPayStr / entity.DayRate).ConvertToDecimal1();
}
_detail.Balance = BalanceStr.ToString("#0.00") + " " + PaymentCurrency_WaitPay;
/*
* Bus名称
*/
_detail.BusName = "待增加";
/*
*费用所属
*/
switch (entity.CTable)
{
case 76://酒店预订
Grp_HotelReservations hotelReservations = _HotelReservations.Where(s => s.Id == entity.CId).FirstOrDefault();
if (hotelReservations != null)
{
DateTime checkIn = Convert.ToDateTime(hotelReservations.CheckInDate),
checkOut = Convert.ToDateTime(hotelReservations.CheckOutDate);
int hotel_days = (int)(checkOut - checkIn).TotalDays;
string roomFeeStr = "", roomFeestr1 = "";
//是否比较房型价格
bool __isSingle = false, __isDouble = false, __isSuite = false, __isOther = false;
//roomFeeStr += $"
";
roomFeeStr += $"
";
var roomTotal = 0.00M;
if (hotelReservations.SingleRoomPrice > 0)
{
var fee = hotelReservations.SingleRoomPrice * hotelReservations.SingleRoomCount * (int)hotel_days;
roomFeestr1 += $"单间:{hotelReservations.SingleRoomPrice.ToString("#0.00")} * {hotelReservations.SingleRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}
";
__isSingle = true;
roomTotal += fee;
}
if (hotelReservations.DoubleRoomPrice > 0)
{
var fee = hotelReservations.DoubleRoomPrice * hotelReservations.DoubleRoomCount * (int)hotel_days;
roomFeestr1 += $"双人间:{hotelReservations.DoubleRoomPrice.ToString("#0.00")} * {hotelReservations.DoubleRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}
";
__isDouble = true;
roomTotal += fee;
}
if (hotelReservations.SuiteRoomPrice > 0)
{
var fee = hotelReservations.SuiteRoomPrice * hotelReservations.SuiteRoomCount * (int)hotel_days;
roomFeestr1 += $"套房:{hotelReservations.SuiteRoomPrice.ToString("#0.00")} * {hotelReservations.SuiteRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}
";
__isSuite = true;
roomTotal += fee;
}
if (hotelReservations.OtherRoomPrice > 0)
{
var fee = hotelReservations.OtherRoomPrice * hotelReservations.OtherRoomCount * (int)hotel_days;
roomFeestr1 += $"其他:{hotelReservations.OtherRoomPrice.ToString("#0.00")} * {hotelReservations.OtherRoomCount}间 * {(int)hotel_days}晚 = {fee.ToString("#0.00")}
";
__isOther = true;
roomTotal += fee;
}
if (roomFeestr1.Length > 0) roomFeeStr += roomFeestr1 + $"房费总金额:{roomTotal.ToString("#0.00")}";
else roomFeeStr += " 0.00 * 0";
decimal governmentRentFee = 0.00M, cityTaxFee = 0.00M, breakfastFee = 0.00M, roomFee = 0.00M;
string governmentRentBool = "否", cityTaxBool = "否", breakfastBool = "否", roomBool = "否";
string governmentRentCode = "", governmentRentName = "", cityTaxCode = "", cityTaxName = "", breakfastCode = "", breakfastName = "", roomCode = "", roomName = "";
var _HotelReservationsContents1 = _HotelReservationsContents.Where(it => it.HrId == hotelReservations.Id).ToList();
/*
* 费用类型
* 1:房费
* 2:早餐
* 3:地税
* 4:城市税
*
*/
//地税
var governmentRentData = _HotelReservationsContents1.Find(it => it.PriceType == 3);
if (governmentRentData != null)
{
governmentRentBool = governmentRentData.IsOppay == 1 ? "是" : "否";
governmentRentFee = governmentRentData.Price;
var governmentRentCurrData = currencyItems.Find(s => s.Id == governmentRentData.Currency);
if (governmentRentCurrData != null)
{
governmentRentCode = governmentRentCurrData.Name;
governmentRentName = $"({governmentRentCurrData.Remark})";
}
}
//城市税
var cityTaxData = _HotelReservationsContents1.Find(it => it.PriceType == 4);
if (cityTaxData != null)
{
cityTaxBool = cityTaxData.IsOppay == 1 ? "是" : "否";
cityTaxFee = cityTaxData.Price;
var cityTaxCurrData = currencyItems.Find(s => s.Id == cityTaxData.Currency);
if (cityTaxCurrData != null)
{
cityTaxCode = cityTaxCurrData.Name;
cityTaxName = $"({cityTaxCurrData.Remark})";
}
}
//酒店早餐
var breakfastData = _HotelReservationsContents1.Find(it => it.PriceType == 2);
if (breakfastData != null)
{
breakfastBool = breakfastData.IsOppay == 1 ? "是" : "否";
breakfastFee = breakfastData.Price;
var breakfastCurrData = currencyItems.Find(s => s.Id == breakfastData.Currency);
if (breakfastCurrData != null)
{
breakfastCode = breakfastCurrData.Name;
breakfastName = $"({breakfastCurrData.Remark})";
}
}
//房间费用
var roomData = _HotelReservationsContents1.Find(it => it.PriceType == 1);
if (roomData != null)
{
_detail.PayType = initDatas.Find(it => it.Id == roomData.PayDId)?.Name ?? "-";
if (_detail.PayType.Equals("现金")) _detail.CardType = "-";
else _detail.CardType = initDatas.Find(it => it.Id == roomData.CTDId)?.Name ?? "-";
roomBool = roomData.IsOppay == 1 ? "是" : "否";
roomFee = roomData.Price;
var roomCurrData = currencyItems.Find(s => s.Id == roomData.Currency);
if (roomCurrData != null)
{
roomCode = roomCurrData.Name;
roomName = $"({roomCurrData.Remark})";
}
}
string hotelCostTitalStr = "成本信息
";
string hotelCostStr = "";
decimal hotelCsotTotal = 0.00M;
if (groupCost != null)
{
if (int.TryParse(groupCost.Currency, out int currencyId)) groupCost.Currency = currencyItems.Find(s => s.Id == currencyId)?.Name ?? "-";
hotelCostStr += $"{groupCost.Currency}(汇率:{groupCost.Rate.ToString("#0.0000")})
";
}
if (checkOut > checkIn) checkOut = checkOut.AddDays(-1);
var hotelCostDetails = groupCostDetails.Where(x => Convert.ToDateTime(x.Date) >= checkIn && Convert.ToDateTime(x.Date) <= checkOut).ToList();
string hotelCost_day = "";
var hotelCostDetails1 = hotelCostDetails.GroupBy(x => x.Date);
foreach (var item in hotelCostDetails1)
{
hotelCsotTotal += item.Sum(x => x.HotelSingleRoomFee) + item.Sum(x => x.HotelDoubleRoomFee) + item.Sum(x => x.HotelSuiteRoomFee) + item.Sum(x => x.HotelSuiteFee);
hotelCost_day += @$"{item.First()?.Date ?? "-"}";
if (item.Sum(x => x.HotelSingleRoomFee) != 0) hotelCost_day += @$" 单间:{item.Sum(x => x.HotelSingleRoomFee).ToString("#0.00")}";
//else { if (__isSingle) hotelCost_day += @$" 单间:0.00"; }
if (item.Sum(x => x.HotelDoubleRoomFee) != 0) hotelCost_day += @$" 双人间:{item.Sum(x => x.HotelDoubleRoomFee).ToString("#0.00")}";
//else { if (__isDouble) hotelCost_day += @$" 双人间:0.00"; }
if (item.Sum(x => x.HotelSuiteRoomFee) != 0) hotelCost_day += @$" 小套房/豪华套房:{item.Sum(x => x.HotelSuiteRoomFee).ToString("#0.00")}";
//else { if (__isSuite) hotelCost_day += @$" 小套房/豪华套房:0.00"; }
if (item.Sum(x => x.HotelSuiteFee) != 0) hotelCost_day += @$" 套房:{item.Sum(x => x.HotelSuiteFee).ToString("#0.00")}";
//else { if (__isOther) hotelCost_day += @$" 套房:0.00"; }
hotelCost_day += @$"
";
}
string hotelBreakfastStr = "", hotelGovernmentRentStr = "", hotelCityTaxStr = "";
if (breakfastFee > 0) hotelBreakfastStr = $"酒店早餐: {breakfastFee.ToString("#0.00")} {breakfastCode} {breakfastName} 当时汇率 {breakfastData?.Rate.ToString("#0.0000")}
是否由地接或其他人代付:{breakfastBool}
";
if (governmentRentFee > 0) hotelGovernmentRentStr = $"地税: {governmentRentFee.ToString("#0.00")} {governmentRentCode} {governmentRentName} 当时汇率 {governmentRentData?.Rate.ToString("#0.0000")}
是否由地接或其他人代付:{governmentRentBool}
";
if (cityTaxFee > 0) hotelCityTaxStr = $"城市税: {cityTaxFee.ToString("#0.00")} {cityTaxCode} {cityTaxName} 当时汇率 {cityTaxData?.Rate.ToString("#0.0000")}
是否由地接或其他人代付:{cityTaxBool}
";
string hotelCostTotalStr = "";// $" 成本合计:{hotelCsotTotal.ToString("#0.00")}
";
_detail.PriceMsgContent = $"{hotelCostTitalStr}{hotelCostStr}{hotelCostTotalStr}{hotelCost_day}
" +
$"{hotelReservations.HotelName} [{hotelReservations.CheckInDate} - {hotelReservations.CheckOutDate}]
" +
$"酒店费用总额:{_detail.WaitPay} ({hotelCurrncyName})
" +
$"房间说明: {hotelReservations.Remark}
" +
$"房间费用: {roomCode} {roomName} 当时汇率:{roomData?.Rate.ToString("#0.0000")}{roomFeeStr}
是否由地接或其他人代付:{roomBool}
" +
$"{hotelBreakfastStr}" +
$"{hotelGovernmentRentStr}" +
$"{hotelCityTaxStr}";
_detail.PriceNameContent = hotelReservations.HotelName;
}
break;
case 79://车/导游地接
Grp_CarTouristGuideGroundReservations touristGuideGroundReservations = _CarTouristGuideGroundReservations.Where(s => s.Id == entity.CId).FirstOrDefault();
if (touristGuideGroundReservations != null)
{
if (!string.IsNullOrEmpty(touristGuideGroundReservations.BusName))
{
_detail.BusName = touristGuideGroundReservations.BusName;
}
_detail.PriceNameContent = touristGuideGroundReservations.PriceName;
//bool isInt = int.TryParse(touristGuideGroundReservations.Area, out int cityId);
//if (isInt)
//{
// var cityInfo = cityData.Find(it => it.Id == cityId);
// if (cityInfo != null)
// {
// string nameContent = $@"{cityInfo.Country}-{cityInfo.City}";
// var carFeeItem = carFeeItems.Find(it => it.Id == touristGuideGroundReservations.PriceType);
// if (carFeeItem != null)
// {
// nameContent += $@"({carFeeItem.Name})";
// }
// _detail.PriceNameContent = nameContent;
// }
//}
//else
//{
// _detail.PriceNameContent = touristGuideGroundReservations.Area;
//}
var touristGuideGroundReservationsContents =
_CarTouristGuideGroundReservationsContent.Where(s => s.CTGGRId == touristGuideGroundReservations.Id && s.IsDel == 0 && s.Price != 0).ToList();
string priceMsg = $"{touristGuideGroundReservations.PriceName}({touristGuideGroundReservations.ServiceStartTime} - {touristGuideGroundReservations.ServiceEndTime})
";
foreach (var item in touristGuideGroundReservationsContents)
{
string typeName = "Unknown";
string carCurrencyCode = "Unknown";
string carCurrencyName = "Unknown";
var carTypeData = carFeeTypeItems.Where(s => s.Id == item.SId && s.IsDel == 0).FirstOrDefault();
if (carTypeData != null) typeName = carTypeData.Name;
var currencyData = currencyItems.Where(s => s.Id == item.Currency && s.IsDel == 0).FirstOrDefault();
if (currencyData != null)
{
carCurrencyCode = currencyData.Name;
carCurrencyName = currencyData.Remark;
}
//op、成本 币种是否一致
bool IsCurrencyAgreement = false;
if (carCurrencyCode.Equals(_groupCurrencyCode)) IsCurrencyAgreement = true;
string opCostStr = string.Empty;
decimal opCostTypePrice = 0.00M;
#region 处理成本各项费用
var opDate = item.DatePrice?.ToString("yyyy-MM-dd");
var opCost = groupCostDetails.Where(x => x.Date.Equals(opDate)).ToList();
if (opCost.Count > 0)
{
switch (item.SId)
{
case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //91车费
//case 982: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //982 车超时费 -- 暂无
case 92: opCostTypePrice = opCost.Sum(x => x.GuideFee); break; //92 导游费
case 94: opCostTypePrice = opCost.Sum(x => x.GuideScenicFee); break; //94 导游景点费
case 95: opCostTypePrice = opCost.Sum(x => x.GuideTipFee); break; //95 导游小费
case 983: opCostTypePrice = opCost.Sum(x => x.GuideMealFee); break; //983 导游餐补
case 984: opCostTypePrice = opCost.Sum(x => x.GuideMealFee); break; //984 导游房补
case 985: opCostTypePrice = opCost.Sum(x => x.GuideRoomFee); break; //985 导游交通
//case 96: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //96 接送机费 -- 暂无
//case 97: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //97 其他费用 -- 暂无
case 979: opCostTypePrice = opCost.Sum(x => x.DriverFee); break; //979 司机工资
case 980: opCostTypePrice = opCost.Sum(x => x.DriverTipFee); break; //980 司机小费
case 981: opCostTypePrice = opCost.Sum(x => x.DriverMealFee); break; //981 司机餐补
case 988: opCostTypePrice = opCost.Sum(x => x.ClientBreakfastFee); break; //988 客户早餐费用
case 93: opCostTypePrice = opCost.Sum(x => x.ClientDinnerFee); break; //93 客户午餐费用
case 989: opCostTypePrice = opCost.Sum(x => x.ClientLunchFee); break; //989 客户晚餐费用
case 990: opCostTypePrice = opCost.Sum(x => x.ScenicTicketFee); break; //990 景点门票费
case 991: opCostTypePrice = opCost.Sum(x => x.DrinkSnackFruitFee); break; //991 饮料/零食/水果
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //992 住补费用 -- 暂无
case 994: opCostTypePrice = opCost.Sum(x => x.TranslatorFee); break; //994 翻译费
case 1059: opCostTypePrice = opCost.Sum(x => x.GuideOverTimeFee); break; //1059 导游超时费用
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //1070 尾款金额
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //1071 其他额外费用
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //1073 翻译超时费
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //1074 早餐超支费用
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //1075 午餐超支费用
//case 91: opCostTypePrice = opCost.Sum(x => x.CarFee); break; //1076 晚餐超支费用
}
opCostStr = $" / 成本:{opCostTypePrice.ToString("#0.00")} {_groupCurrencyCode}(汇率:{_groupRate.ToString("#0.0000")})";
if (!IsCurrencyAgreement) opCostStr += $" ≈ {(opCostTypePrice * _groupRate).ToString("#0.00")} CNY";
}
#endregion
string opTypeStr = $"{typeName}:{item.Price.ToString("#0.00")} {carCurrencyCode}(汇率:{entity.DayRate.ToString("#0.0000")})";
if (!IsCurrencyAgreement) opTypeStr += $" ≈ {(item.Price * entity.DayRate).ToString("#0.00")} CNY";
priceMsg += $"日期:{item.DatePrice?.ToString("yyyy-MM-dd") ?? "-"}
" +
$"{opTypeStr} {opCostStr}
" +
$"明细:{item.PriceContent ?? "-"}
" +
$"备注:{item.Remark ?? "-"}
";
}
_detail.PriceMsgContent = priceMsg;
}
break;
case 80: //签证
Grp_VisaInfo visaInfo = _VisaInfos.Where(s => s.Id == entity.CId).FirstOrDefault();
if (visaInfo != null)
{
string visaName = getClientNameStr1(clientNameList, visaInfo.VisaClient);
_detail.PriceNameContent = visaInfo.VisaDescription;
_detail.PriceMsgContent = $"签证描述:{visaName}
备注:{visaInfo.Remark}";
}
break;
case 81: //邀请/公务活动
Grp_InvitationOfficialActivities _ioa = _InvitationOfficialActivities.Where(s => s.Id == entity.CId).FirstOrDefault();
if (_ioa != null)
{
string inviteCurrName = "Unknown", //邀请费用币种 Name
inviteCurrCode = "Unknown", //邀请费用币种 Code
sendCurrName = "Unknown", //快递费用币种 Name
sendCurrCode = "Unknown", //快递费用币种 Code
eventsCurrName = "Unknown", //公务活动费币种 Name
eventsCurrCode = "Unknown", //公务活动费币种 Code
translateCurrName = "Unknown", //公务翻译费 Name
translateCurrCode = "Unknown"; //公务翻译费 Code
#region 处理费用币种
var inviteCurrData = currencyItems.Where(s => s.Id == _ioa.InviteCurrency && s.IsDel == 0).FirstOrDefault();
if (inviteCurrData != null)
{
inviteCurrName = inviteCurrData.Remark;
inviteCurrCode = inviteCurrData.Name;
}
var sendCurrData = currencyItems.Where(s => s.Id == _ioa.SendCurrency && s.IsDel == 0).FirstOrDefault();
if (sendCurrData != null)
{
sendCurrName = sendCurrData.Remark;
sendCurrCode = sendCurrData.Name;
}
var eventsCurrData = currencyItems.Where(s => s.Id == _ioa.EventsCurrency && s.IsDel == 0).FirstOrDefault();
if (eventsCurrData != null)
{
eventsCurrName = eventsCurrData.Remark;
eventsCurrCode = eventsCurrData.Name;
}
var translateCurrData = currencyItems.Where(s => s.Id == _ioa.TranslateCurrency && s.IsDel == 0).FirstOrDefault();
if (translateCurrData != null)
{
translateCurrName = translateCurrData.Remark;
translateCurrCode = translateCurrData.Name;
}
#endregion
_detail.PriceNameContent = _ioa.InviterArea;
_detail.PriceMsgContent = $@"邀请费用:{_ioa.InviteCost.ToString("#0.00")} {inviteCurrCode}({inviteCurrName})
" +
$@"快递费用:{_ioa.SendCost.ToString("#0.00")} {sendCurrCode}({sendCurrName})
" +
$@"公务活动费:{_ioa.EventsCost.ToString("#0.00")} {eventsCurrCode}({eventsCurrName})
" +
$@"公务翻译费:{_ioa.TranslateCost.ToString("#0.00")} {translateCurrCode}({translateCurrName})
" +
$@"备注:" + _ioa.Remark + "
";
}
break;
case 82: //团组客户保险
Grp_Customers customers = _Customers.Where(s => s.Id == entity.CId && s.IsDel == 0).FirstOrDefault();
if (customers != null)
{
_detail.PriceNameContent = getClientNameStr(clientNameList, customers.ClientName);
_detail.PriceMsgContent = "备注:" + customers.Remark + "
";
}
break;
case 85: //机票预订
Grp_AirTicketReservations jpRes = _AirTicketReservations.Where(s => s.Id == entity.CId).FirstOrDefault();
if (jpRes != null)
{
string FlightsDescription = jpRes.FlightsDescription;
string PriceDescription = jpRes.PriceDescription;
_detail.PriceMsgContent = "航班号:" + jpRes.FlightsCode + "
城市A-B:" + jpRes.FlightsCity + "
航班描述:" + FlightsDescription.Replace("\r\n", "
") + "
" + "价格描述:" + PriceDescription;
_detail.PriceNameContent = "(" + jpRes.FlightsCode + ")";
}
break;
case 98://其他款项
Grp_DecreasePayments gdpRes = _DecreasePayments.Where(s => s.Id == entity.CId).FirstOrDefault();
if (gdpRes != null)
{
_detail.PriceMsgContent = "备注:" + gdpRes.Remark;
_detail.PriceNameContent = gdpRes.PriceName;
}
break;
case 285://收款退还
Fin_PaymentRefundAndOtherMoney refundAndOtherMoney = _PaymentRefundAndOtherMoneys.Where(s => s.Id == entity.CId).FirstOrDefault();
if (refundAndOtherMoney != null)
{
_detail.PriceMsgContent = "备注:" + refundAndOtherMoney.Remark;
_detail.PriceNameContent = refundAndOtherMoney.PriceName;
}
break;
case 751://酒店早餐
break;
case 1015://超支费用
Fin_GroupExtraCost groupExtraCost = _GroupExtraCosts.Where(s => s.Id == entity.CId).FirstOrDefault();
if (groupExtraCost != null)
{
_detail.PriceNameContent = groupExtraCost.PriceName;
_detail.PriceMsgContent = "备注:" + groupExtraCost.Remark;
}
break;
default:
break;
}
/*
* 申请人
*/
string operatorName = " - ";
var _opUser = userItems.Where(s => s.Id == entity.CreateUserId).FirstOrDefault();
if (_opUser != null)
{
operatorName = _opUser.CnName;
}
_detail.OperatorName = operatorName;
/*
* 审核人
*/
string auditOperatorName = "Unknown";
if (entity.AuditGMOperate == 0) auditOperatorName = " - ";
else if (entity.AuditGMOperate == 4) auditOperatorName = "自动审核";
else
{
var _adUser = userItems.Where(s => s.Id == entity.AuditGMOperate).FirstOrDefault();
if (_adUser != null)
{
auditOperatorName = _adUser.CnName;
}
}
_detail.AuditOperatorName = auditOperatorName;
/*
* 超预算比例
*/
string overBudgetStr = "";
if (entity.ExceedBudget == -1) overBudgetStr = sdPriceName.Name + "尚无预算";
else if (entity.ExceedBudget == 0)
{
if (entity.CTable == 76 || entity.CTable == 79)
{
if (entity.IsAuditGM == 3) overBudgetStr = "未超预算";
else overBudgetStr = _feeAuditRep.IsOverBudget(entity.CTable, entity.DIId, entity.CId);
}
else
{
overBudgetStr = "未超预算";
}
}
else overBudgetStr = entity.ExceedBudget.ToString("P");
_detail.OverBudget = overBudgetStr;
decimal auditFee = 0.00M; //已审核金额 人名币
decimal auditedFeeOriginal = 0.00M; ////已审核金额 原始
decimal unAuditFeeCNY = 0.00M; //未审核款项 原始
decimal unAuditFeeOriginal = 0.00M; //未审核款项 人名币
if (entity.IsAuditGM == 1 || entity.IsAuditGM == 3)
{
auditedFeeOriginal = entity.PayMoney;
auditFee = CurrPayStr;
}
else if (entity.IsAuditGM == 0)
{
unAuditFeeCNY = CurrPayStr;
unAuditFeeOriginal = OriginalCurrPay;
OriginalCurrPay = 0.00M;
}
/*
* 费用总计
*/
ccpCurrencyPrices.Add(new CreditCardPaymentCurrencyPriceItem()
{
CurrencyId = entity.PaymentCurrency,
CurrencyName = PaymentCurrency_WaitPay,
AmountPayable = entity.PayMoney,
ThisPayment = OriginalCurrPay,
BalancePayment = BalanceStr,
AuditedFunds = auditFee,
AuditedFundsOriginal = auditedFeeOriginal,
UnAuditFundsCNY = unAuditFeeCNY,
UnAuditFundsOriginal = unAuditFeeOriginal
});
_detail.IsAuditGM = entity.IsAuditGM;
detailList.Add(_detail);
}
#endregion
_view.DetailList = new List(detailList);
/*
* 下方描述处理
*/
var nonDuplicat = ccpCurrencyPrices.Where((x, i) => ccpCurrencyPrices.FindIndex(z => z.CurrencyId == x.CurrencyId) == i).ToList();//Lambda表达式去重
var ccpCurrencyPrice = nonDuplicat.Where(it => it.CurrencyId == 836).FirstOrDefault();
if (ccpCurrencyPrice != null)
{
int CNYIndex = nonDuplicat.IndexOf(ccpCurrencyPrice);
nonDuplicat.MoveItemAtIndexToFront(CNYIndex);
}
else
{
nonDuplicat.OrderBy(it => it.CurrencyId).ToList();
}
string amountPayableStr = string.Format(@"应付款总金额: ");
string thisPaymentStr = string.Format(@"此次付款总金额: ");
string balancePaymentStr = string.Format(@"目前剩余尾款总金额: ");
string auditedFundsStr = string.Format(@"已审费用总额: ");
string unAuditedFundsStr = string.Format(@"未审费用总额: ");
foreach (var item in nonDuplicat)
{
var currencyName = item.CurrencyName;
var strs = ccpCurrencyPrices.Where(it => it.CurrencyId == item.CurrencyId).ToList();
if (strs.Count > 0)
{
decimal amountPayable = strs.Sum(it => it.AmountPayable);
decimal thisPayment = ccpCurrencyPrices.Sum(it => it.ThisPayment);
decimal balancePayment = strs.Sum(it => it.BalancePayment);
amountPayableStr += string.Format(@"{0}{1} |", amountPayable.ToString("#0.00"), currencyName);
//单独处理此次付款金额
thisPaymentStr += string.Format(@"{0}{1} |", strs.Sum(x => x.ThisPayment).ToString("#0.00"), currencyName);
balancePaymentStr += string.Format(@"{0}{1} |", balancePayment.ToString("#0.00"), currencyName);
//单独处理已审核费用
//if (item.CurrencyId == 836) //人民币
//{
// decimal auditedFunds = ccpCurrencyPrices.Sum(it => it.AuditedFunds);
// auditedFundsStr += string.Format(@"{0}{1} |", auditedFunds.ToString("#0.00"), currencyName);
//}
//else
//{
// auditedFundsStr += string.Format(@"{0}{1} |", strs.Sum(x => x.AmountPayable), currencyName);
//}
if (currencyName.Equals("CNY"))
{
//已审核费用
auditedFundsStr += string.Format(@"{0}{1} |", strs.Sum(x => x.AuditedFundsOriginal).ToString("#0.00"), currencyName);
//未审核费用
unAuditedFundsStr += string.Format(@"{0}{1} |", strs.Sum(x => x.UnAuditFundsOriginal).ToString("#0.00"), currencyName);
}
else
{
//已审核费用
auditedFundsStr += string.Format(@"{0}{1}({2}CNY) |", strs.Sum(x => x.AuditedFundsOriginal).ToString("#0.00"), currencyName, strs.Sum(x => x.AuditedFunds).ToString("#0.00"));
//未审核费用
unAuditedFundsStr += string.Format(@"{0}{1}({2}CNY) |", strs.Sum(x => x.UnAuditFundsOriginal).ToString("#0.00"), currencyName, strs.Sum(x => x.UnAuditFundsCNY).ToString("#0.00"));
}
}
}
_view.TotalStr1 = amountPayableStr.Substring(0, amountPayableStr.Length - 1);
_view.TotalStr2 = thisPaymentStr.Substring(0, thisPaymentStr.Length - 1);
_view.TotalStr3 = balancePaymentStr.Substring(0, balancePaymentStr.Length - 1);
_view.TotalStr4 = $"{auditedFundsStr.Substring(0, auditedFundsStr.Length - 1)}
{unAuditedFundsStr.Substring(0, unAuditedFundsStr.Length - 1)}";
//_view.TotalStr5 = unAuditedFundsStr.Substring(0, unAuditedFundsStr.Length - 1);
var _view1 = new
{
PageFuncAuth = pageFunAuthView,
Data = _view
};
return Ok(JsonView(_view1));
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
}
}
///
/// 费用审核
/// 修改团组费用审核状态
///
/// 参数Json字符串
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostAuditGrpCreditCardPayment(Edit_GrpCreditCardPaymentDto _dto)
{
#region 参数验证
if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
#endregion
#region 页面操作权限验证
PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
if (pageFunAuthView.AuditAuth == 0) return Ok(JsonView(false, "您没有审核权限"));
#endregion
List idList = _dto.CreditIdStr.Split(',').ToList();
Grp_CreditCardPayment _detail = _mapper.Map(_dto);
DateTime dtNow = DateTime.Now;
_groupRepository.BeginTran();
int rst = 0;
var creditDatas = _grpScheduleRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && idList.Contains(it.Id.ToString())).ToList();
var creditTypeDatas = _grpScheduleRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.STid == 16).ToList();
var creditCurrencyDatas = _grpScheduleRep._sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.STid == 66).ToList();
var groupDatas = _grpScheduleRep._sqlSugar.Queryable().Where(it => it.IsDel == 0).ToList();
List msgDatas = new List();
Dictionary dic_ccp_user = new Dictionary() { };
foreach (var item in idList)
{
int CreditId = int.Parse(item);
var result = await _grpScheduleRep._sqlSugar.Updateable()
.SetColumns(it => it.IsAuditGM == _dto.AuditCode)
.SetColumns(it => it.AuditGMOperate == _dto.UserId)
.SetColumns(it => it.AuditGMDate == dtNow.ToString("yyyy-MM-dd HH:mm:ss"))
.Where(s => s.Id == CreditId)
.ExecuteCommandAsync();
if (result < 1)
{
rst = -1;
_groupRepository.RollbackTran();
return Ok(JsonView(false, "操作失败并回滚!"));
}
var creditData = creditDatas.Where(it => it.Id == CreditId).FirstOrDefault();
if (creditData != null)
{
#region 应用通知配置
try
{
dic_ccp_user.Add(creditData.Id, creditData.CreateUserId);
}
catch (Exception ex)
{
}
#endregion
string auditStr = _dto.AuditCode == 1 ? "已通过" : _dto.AuditCode == 2 ? "未通过" : "未审核";
string groupNameStr = string.Empty;
var groupData = groupDatas.Where(it => it.Id == creditData.DIId).FirstOrDefault();
if (groupData != null) groupNameStr = groupData.TeamName;
string creditTypeStr = string.Empty;
var creditTypeData = creditTypeDatas.Where(it => it.Id == creditData.CTable).FirstOrDefault();
if (creditTypeData != null) creditTypeStr = creditTypeData.Name;
string creditCurrency = string.Empty;
var creditCurrencyData = creditCurrencyDatas.Where(it => it.Id == creditData.PaymentCurrency).FirstOrDefault();
if (creditCurrencyData != null) creditCurrency = creditCurrencyData.Name;
if (creditCurrency.Equals("CNY"))
{
creditData.DayRate = 1.0000M;
}
if (creditData.PayPercentage == 0.00M)
{
creditData.PayPercentage = 100M;
}
decimal CNYPrice = (creditData.PayMoney * (creditData.PayPercentage / 100)) * creditData.DayRate;
string msgTitle = $"[{groupNameStr}({creditTypeStr})]的费用申请";
string msgContent = "";
if (creditCurrency.Equals("CNY"))
{
msgContent = $"[{groupNameStr}({creditTypeStr})]费用申请(金额:{CNYPrice.ToString("0.00")} CNY) {auditStr}!";
}
else
{
msgContent = $"[{groupNameStr}({creditTypeStr})]费用申请(金额:{CNYPrice.ToString("0.00")} CNY({creditData.PayMoney.ToString("0.00")} {creditCurrency})) {auditStr}!";
}
msgDatas.Add(new { DiId = creditData.DIId, UserId = creditData.CreateUserId, MsgTitle = msgTitle, MsgContent = msgContent });
}
}
if (rst == 0)
{
_groupRepository.CommitTran();
foreach (var item in msgDatas)
{
//发送消息
GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupExpenseAudit, item.MsgTitle, item.MsgContent, new List() { item.UserId }, item.DiId);
}
#region 应用推送
try
{
foreach (var ccpId in dic_ccp_user.Keys)
{
List templist = new List() { dic_ccp_user[ccpId].ToString() };
await AppNoticeLibrary.SendUserMsg_GroupStatus_AuditFee(ccpId, templist, QiyeWeChatEnum.CaiWuChat);
}
}
catch (Exception)
{
}
#endregion
return Ok(JsonView(true, "操作成功!"));
}
return Ok(JsonView(false, "操作失败!"));
}
#endregion
#region 机票费用录入
///
/// 机票录入当前登录人可操作团组
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task AirTicketResSelect(AirTicketResDto dto)
{
try
{
Result groupData = await _airTicketResRep.AirTicketResSelect(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 机票费用录入列表
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task AirTicketResList(AirTicketResDto dto)
{
try
{
Result groupData = await _airTicketResRep.AirTicketResList(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
throw;
}
}
///
/// 根据id查询费用录入信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task AirTicketResById(AirTicketResByIdDto dto)
{
Result groupData = await _airTicketResRep.AirTicketResById(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 机票费用录入操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpAirTicketRes(AirTicketResOpDto dto)
{
Result groupData = await _airTicketResRep.OpAirTicketRes(dto, _setDataRep.PostCurrencyByDiid);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
#region 应用推送
try
{
int ccpId = groupData.Data.GetType().GetProperty("ccpId").GetValue(groupData.Data, null);
int sign = groupData.Data.GetType().GetProperty("sign").GetValue(groupData.Data, null);
await AppNoticeLibrary.SendChatMsg_GroupStatus_ApplyFee(ccpId, sign, QiyeWeChatEnum.GuoJiaoLeaderChat);
//2024-10-21 新增LZ UID
var userIds = new List() { 21 };
string title = $"系统通知";
string content = "";
var diId = dto.AirTicketResOpData.DiId;
var groupInfo = await _groupRepository.Query(x => x.Id == diId).FirstAsync();
var ccpInfo = await _sqlSugar.Queryable().Where(x => x.Id == ccpId).FirstAsync();
if (dto.Status == 1) content = $"[新增-机票费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
else if (dto.Status == 2) content = $"[更新-机票费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
PageParam_PriceAuditH5 h5 = new PageParam_PriceAuditH5() { diid = diId.ToString(), uid = "21" };
await APNsTools.iOS_PushNotifications1("051", $"机票费用审核", "", content, true, "ExpenseAuditWebView", h5);
}
catch (Exception ex)
{
}
#endregion
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 根据舱位类型查询接团客户名单信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task tankType(AirTicketResByIdDto dto)
{
try
{
List crm_Groups = _sqlSugar.Queryable().Where(a => a.IsDel == 0 && a.AirType == dto.Id).ToList();
if (crm_Groups.Count != 0)
{
List Customer = new List();
foreach (var item in crm_Groups)
{
var data = new
{
Id = item.Id,
Pinyin = item.Pinyin,
Name = item.LastName + item.FirstName
};
Customer.Add(data);
}
return Ok(JsonView(true, "查询成功!", Customer));
}
return Ok(JsonView(true, "暂无数据", crm_Groups));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 根据团号获取客户信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public IActionResult QueryClientInfoByDIID(QueryClientInfoByDIIDDto dto)
{
var jw = JsonView(false);
if (dto.DIID < 1)
{
jw.Msg += "请输入正确的diid";
return Ok(jw);
}
var arr = getSimplClientList(dto.DIID);
jw = JsonView(true, "获取成功!", arr);
return Ok(jw);
}
private List getSimplClientList(int diId)
{
string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", diId);
List arr = _sqlSugar.SqlQueryable(sql).ToList();
foreach (var item in arr)
{
EncryptionProcessor.DecryptProperties(item);
}
return arr;
}
private string getClientNameStr(List list, string origin)
{
string result = origin;
if (Regex.Match(origin, @"\d+,?").Value.Length > 0)
{
string[] temparr = origin.Split(',');
string fistrStr = temparr[0];
int count = temparr.Count();
int tempId;
bool success = int.TryParse(fistrStr, out tempId);
if (success)
{
SimplClientInfo tempInfo = list.FirstOrDefault(s => s.Id == tempId);
if (tempInfo != null)
{
if (count > 1)
{
result = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
}
else
{
result = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
}
}
}
}
return result;
}
private string getClientNameStr1(List list, string origin)
{
string result = origin;
if (Regex.Match(origin, @"\d+,?").Value.Length > 0)
{
string[] temparr = origin.Split(',');
result = "";
foreach (var item in temparr)
{
int tempId;
bool success = int.TryParse(item, out tempId);
if (success)
{
SimplClientInfo tempInfo = list.FirstOrDefault(s => s.Id == tempId);
if (tempInfo != null)
{
result += string.Format(@"{0}{1}、", tempInfo.LastName, tempInfo.FirstName);
}
}
}
}
if (result.Length > 0) result = result.Substring(0, result.Length - 1);
return result;
}
///
/// 机票费用录入,删除
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelAirTicketRes(DelBaseDto dto)
{
try
{
var res = await _airTicketResRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (res)
{
var result = await _sqlSugar.Updateable().Where(a => a.CId == dto.Id && a.CTable == 85).SetColumns(a => new Grp_CreditCardPayment()
{
IsDel = 1,
DeleteUserId = dto.DeleteUserId,
DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
}).ExecuteCommandAsync();
return Ok(JsonView(true, "删除成功!"));
}
return Ok(JsonView(false, "删除失败!"));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 导出机票录入报表
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DeriveAirTicketRes(AirTicketResDto dto)
{
try
{
Result groupData = await _airTicketResRep.DeriveAirTicketRes(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(StatusCodes.Status400BadRequest, groupData.Msg, ""));
}
else
{
List AirTicketReservations = groupData.Data.GetType().GetProperty("AirTicketRes").GetValue(groupData.Data);
if (AirTicketReservations.Count != 0)
{
Grp_DelegationInfo DelegationInfo = groupData.Data.GetType().GetProperty("Delegation").GetValue(groupData.Data);
Sys_Users _Users = groupData.Data.GetType().GetProperty("Users").GetValue(groupData.Data);
string diCode = DelegationInfo != null ? DelegationInfo.TourCode : "XXX";
string diName = DelegationInfo != null ? DelegationInfo.TeamName : "XXX";
WorkbookDesigner designer = new WorkbookDesigner();
designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/机票预订费用报表模板.xlsx");
decimal countCost = 0;
foreach (var item in AirTicketReservations)
{
#region 处理客人姓名
string clientNames = _tourClientListRep._ResolveCustomerName(item.ClientName);
item.ClientName = clientNames;
#endregion
if (item.BankType == "其他")
{
item.BankNo = "--";
}
else
{
if (!string.IsNullOrEmpty(item.BankType))
{
item.BankNo = item.BankType + ":" + item.BankNo?.Substring(0, 3);
}
}
item.PrePrice = System.Decimal.Round(item.PrePrice, 2);
item.Price = System.Decimal.Round(item.Price, 2);
countCost += Convert.ToDecimal(item.Price);
}
designer.SetDataSource("Export", AirTicketReservations);
designer.SetDataSource("ExportDiCode", diCode);
designer.SetDataSource("ExportDiName", diName);
designer.SetDataSource("ExportOpUserName", _Users.CnName);
designer.SetDataSource("ExportCountCost", countCost + "(" + AirTicketReservations[0].CurrencyStr);
designer.Process();
string fileName = ("AirfareStatement/" + diName + "机票费用报表" + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx").Replace(":", "");
designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
return Ok(JsonView(true, "成功", url = rst));
}
else
{
return Ok(JsonView(StatusCodes.Status400BadRequest, "暂无数据!", ""));
}
}
}
catch (Exception ex)
{
return Ok(JsonView(StatusCodes.Status400BadRequest, ex.Message, ""));
throw;
}
}
Dictionary transDic = new Dictionary();
///
/// 行程单导出
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task ItineraryAirTicketRes(ItineraryAirTicketResDto dto)
{
try
{
Result groupData = await _airTicketResRep.ItineraryAirTicketRes(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(StatusCodes.Status400BadRequest, groupData.Msg, ""));
}
else
{
List _AirTicketReservations = groupData.Data;
if (dto.Language == "CN")
{
Document doc = new Document(AppSettingsHelper.Get("WordBasePath") + "Template/电子客票行程单模板_CN.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
int tableIndex = 0;//表格索引
//得到文档中的第一个表格
Table table = (Table)doc.GetChild(NodeType.Table, tableIndex, true);
foreach (var item in _AirTicketReservations)
{
#region 处理固定数据
string[] FlightsCode = item.FlightsCode.Split('/');
if (FlightsCode.Length != 0)
{
Res_AirCompany _AirCompany = _sqlSugar.Queryable().First(a => a.ShortCode == FlightsCode[0].Substring(0, 2));
if (_AirCompany != null)
{
table.Range.Bookmarks["AirlineCompany"].Text = _AirCompany.CnName;
}
else
{
table.Range.Bookmarks["AirlineCompany"].Text = "--";
}
}
table.Range.Bookmarks["AirlineRecordCode"].Text = "--";
table.Range.Bookmarks["ReservationRecordCode"].Text = "--";
string[] nameArray = Regex.Split(item.ClientName, "\\d+\\.", RegexOptions.IgnoreCase);
nameArray = nameArray.Where(str => str != "" && str != " " && !string.IsNullOrEmpty(str)).ToArray();
string name = "";
foreach (string clientName in nameArray)
{
if (!name.Contains(clientName))
{
name += clientName + ",";
}
}
if (!string.IsNullOrWhiteSpace(name))
{
table.Range.Bookmarks["ClientName"].Text = name.Substring(0, name.Length - 1);
}
else
{
table.Range.Bookmarks["ClientName"].Text = "--";
}
table.Range.Bookmarks["TicketNumber"].Text = "--";
table.Range.Bookmarks["IdentificationCode"].Text = "--";
table.Range.Bookmarks["JointTicket"].Text = "--";
table.Range.Bookmarks["TimeIssue"].Text = "--";
table.Range.Bookmarks["DrawingAgent"].Text = "--";
table.Range.Bookmarks["NavigationCode"].Text = "--";
table.Range.Bookmarks["AgentsAddress"].Text = "--";
table.Range.Bookmarks["AgentPhone"].Text = "--";
table.Range.Bookmarks["AgentFacsimile"].Text = "--";
#endregion
#region 循环数据处理
List airs = new List();
string[] DayArray = Regex.Split(item.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase);
DayArray = DayArray.Where(s => s != " " && s != "" && !string.IsNullOrEmpty(s)).ToArray();
for (int i = 0; i < FlightsCode.Length; i++)
{
AirInfo air = new AirInfo();
string[] tempstr = DayArray[i]
.Replace("\r\n", string.Empty)
.Replace("\\r\\n", string.Empty)
.TrimStart().TrimEnd()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Res_ThreeCode star_Three = _sqlSugar.Queryable().First(a => a.Three == tempstr[3].Substring(0, 3));
string starCity = "";
if (star_Three != null)
{
starCity = star_Three.AirPort;
}
Res_ThreeCode End_Three = _sqlSugar.Queryable().First(a => a.Three == tempstr[3].Substring(3, 3));
string EndCity = "";
if (End_Three != null)
{
EndCity = End_Three.AirPort;
}
air.Destination = starCity + "/" + EndCity;
air.Flight = FlightsCode[i];
air.SeatingClass = item.CTypeName;
string dateTime = tempstr[2];
string DateTemp = dateTime.Substring(2, 5).ToUpper();
air.FlightDate = DateTemp;
air.DepartureTime = tempstr[5];
air.LandingTime = tempstr[6];
air.ValidityPeriod = DateTemp + "/" + DateTemp;
air.TicketStatus = "--";
air.Luggage = "--";
air.DepartureTerminal = "--";
air.LandingTerminal = "--";
airs.Add(air);
}
int row = 13;
for (int i = 0; i < airs.Count; i++)
{
if (airs.Count > 2)
{
for (int j = 0; j < airs.Count - 2; j++)
{
var CopyRow = table.Rows[12].Clone(true);
table.Rows.Add(CopyRow);
}
}
PropertyInfo[] properties = airs[i].GetType().GetProperties();
int index = 0;
foreach (PropertyInfo property in properties)
{
string value = property.GetValue(airs[i]).ToString();
Cell ishcel0 = table.Rows[row].Cells[index];
Paragraph p = new Paragraph(doc);
string s = value;
p.AppendChild(new Run(doc, s));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
ishcel0.AppendChild(p);
ishcel0.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐
index++;
}
row++;
}
#endregion
Paragraph lastParagraph = new Paragraph(doc);
//第一个表格末尾加段落
table.ParentNode.InsertAfter(lastParagraph, table);
//复制第一个表格
Table cloneTable = (Table)table.Clone(true);
//在文档末尾段落后面加入复制的表格
table.ParentNode.InsertAfter(cloneTable, lastParagraph);
if (item != _AirTicketReservations[_AirTicketReservations.Count - 1])
{
int rownewsIndex = 13;
for (int i = 0; i < 2; i++)
{
var CopyRow = table.Rows[12].Clone(true);
table.Rows.RemoveAt(13);
table.Rows.Add(CopyRow);
rownewsIndex++;
}
}
else
{
table.Rows.RemoveAt(12);
}
cloneTable.Rows.RemoveAt(12);
}
if (_AirTicketReservations.Count != 0)
{
string[] FlightsCode = _AirTicketReservations[0].FlightsCode.Split('/');
if (FlightsCode.Length != 0)
{
Res_AirCompany _AirCompany = _sqlSugar.Queryable().First(a => a.ShortCode == FlightsCode[0].Substring(0, 2));
if (_AirCompany != null)
{
table.Range.Bookmarks["AirlineCompany"].Text = _AirCompany.CnName;
}
else
{
table.Range.Bookmarks["AirlineCompany"].Text = "--";
}
}
table.Range.Bookmarks["AirlineRecordCode"].Text = "--";
table.Range.Bookmarks["ReservationRecordCode"].Text = "--";
string[] nameArray = Regex.Split(_AirTicketReservations[0].ClientName, "\\d+\\.", RegexOptions.IgnoreCase);
nameArray = nameArray.Where(str => str != "" && str != " " && !string.IsNullOrEmpty(str)).ToArray();
string name = "";
foreach (string clientName in nameArray)
{
if (!name.Contains(clientName))
{
name += clientName + ",";
}
}
if (!string.IsNullOrWhiteSpace(name))
{
table.Range.Bookmarks["ClientName"].Text = name.Substring(0, name.Length - 1);
}
else
{
table.Range.Bookmarks["ClientName"].Text = "--";
}
table.Range.Bookmarks["TicketNumber"].Text = "--";
table.Range.Bookmarks["IdentificationCode"].Text = "--";
table.Range.Bookmarks["JointTicket"].Text = "--";
table.Range.Bookmarks["TimeIssue"].Text = "--";
table.Range.Bookmarks["DrawingAgent"].Text = "--";
table.Range.Bookmarks["NavigationCode"].Text = "--";
table.Range.Bookmarks["AgentsAddress"].Text = "--";
table.Range.Bookmarks["AgentPhone"].Text = "--";
table.Range.Bookmarks["AgentFacsimile"].Text = "--";
}
doc.MailMerge.Execute(new[] { "PageCount" }, new object[] { doc.PageCount });
//保存合并后的文档
string fileName = "AirItinerary/电子客票中文行程单_CN.docx";
string rst = AppSettingsHelper.Get("WordBaseUrl") + AppSettingsHelper.Get("WordFtpPath") + fileName;
doc.Save(AppSettingsHelper.Get("WordBasePath") + fileName);
return Ok(JsonView(true, "成功!", rst));
}
else
{
Document doc = new Document(AppSettingsHelper.Get("WordBasePath") + "Template/电子客票行程单模板_EN.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
int tableIndex = 0;//表格索引
//得到文档中的第一个表格
Table table = (Table)doc.GetChild(NodeType.Table, tableIndex, true);
List texts = new List();
foreach (var item in _AirTicketReservations)
{
string[] FlightsCode = item.FlightsCode.Split('/');
if (FlightsCode.Length != 0)
{
Res_AirCompany _AirCompany = _sqlSugar.Queryable().First(a => a.ShortCode == FlightsCode[0].Substring(0, 2));
if (_AirCompany != null)
{
if (!transDic.ContainsKey(_AirCompany.CnName))
{
transDic.Add(_AirCompany.CnName, _AirCompany.EnName);
}
}
else
{
if (!transDic.ContainsKey("--"))
{
transDic.Add("--", "--");
}
}
}
string[] nameArray = Regex.Split(item.ClientName, "\\d+\\.", RegexOptions.IgnoreCase);
nameArray = nameArray.Where(str => str != "" && str != " " && !string.IsNullOrEmpty(str)).ToArray();
string name = "";
foreach (string clientName in nameArray)
{
name += clientName + ",";
}
if (!texts.Contains(name))
{
texts.Add(name);
}
List airs = new List();
string[] DayArray = Regex.Split(item.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase);
DayArray = DayArray.Where(s => s != " " && s != "" && !string.IsNullOrEmpty(s)).ToArray();
for (int i = 0; i < FlightsCode.Length; i++)
{
AirInfo air = new AirInfo();
string[] tempstr = DayArray[i]
.Replace("\r\n", string.Empty)
.Replace("\\r\\n", string.Empty)
.TrimStart().TrimEnd()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Res_ThreeCode star_Three = _sqlSugar.Queryable().First(a => a.Three == tempstr[3].Substring(0, 3));
if (star_Three != null)
{
if (!transDic.ContainsKey(star_Three.AirPort))
{
transDic.Add(star_Three.AirPort, star_Three.AirPort_En);
}
}
Res_ThreeCode End_Three = _sqlSugar.Queryable().First(a => a.Three == tempstr[3].Substring(3, 3));
if (End_Three != null)
{
if (!transDic.ContainsKey(End_Three.AirPort))
{
transDic.Add(End_Three.AirPort, End_Three.AirPort_En);
}
}
if (!texts.Contains(item.CTypeName))
{
texts.Add(item.CTypeName);
}
}
}
List transData = _airTicketResRep.ReTransBatch(texts, "en");
if (transData.Count > 0)
{
foreach (TranslateResult item in transData)
{
if (!transDic.ContainsKey(item.Query))
{
transDic.Add(item.Query, item.Translation);
}
}
}
foreach (var item in _AirTicketReservations)
{
#region 处理固定数据
string[] FlightsCode = item.FlightsCode.Split('/');
if (FlightsCode.Length != 0)
{
Res_AirCompany _AirCompany = _sqlSugar.Queryable().First(a => a.ShortCode == FlightsCode[0].Substring(0, 2));
if (_AirCompany != null)
{
string str = "--";
string translateResult = transDic.Where(s => s.Key == _AirCompany.CnName).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult))
{
str = translateResult;
str = _airTicketResRep.Processing(str);
}
table.Range.Bookmarks["AirlineCompany"].Text = str;
}
else
{
table.Range.Bookmarks["AirlineCompany"].Text = "--";
}
}
table.Range.Bookmarks["AirlineRecordCode"].Text = "--";
table.Range.Bookmarks["ReservationRecordCode"].Text = "--";
string[] nameArray = Regex.Split(item.ClientName, "\\d+\\.", RegexOptions.IgnoreCase);
nameArray = nameArray.Where(str => str != "" && str != " " && !string.IsNullOrEmpty(str)).ToArray();
string names = "";
foreach (string clientName in nameArray)
{
names += clientName + ",";
}
if (!string.IsNullOrWhiteSpace(names))
{
string str = "--";
string translateResult = transDic.Where(s => s.Key == names).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult))
{
str = translateResult;
str = _airTicketResRep.Processing(str);
}
table.Range.Bookmarks["ClientName"].Text = str;
}
else
{
table.Range.Bookmarks["ClientName"].Text = "--";
}
table.Range.Bookmarks["TicketNumber"].Text = "--";
table.Range.Bookmarks["IdentificationCode"].Text = "--";
table.Range.Bookmarks["JointTicket"].Text = "--";
table.Range.Bookmarks["TimeIssue"].Text = "--";
table.Range.Bookmarks["DrawingAgent"].Text = "--";
table.Range.Bookmarks["NavigationCode"].Text = "--";
table.Range.Bookmarks["AgentsAddress"].Text = "--";
table.Range.Bookmarks["AgentPhone"].Text = "--";
table.Range.Bookmarks["AgentFacsimile"].Text = "--";
#endregion
#region 循环数据处理
List airs = new List();
string[] DayArray = Regex.Split(item.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase);
DayArray = DayArray.Where(s => s != " " && s != "" && !string.IsNullOrEmpty(s)).ToArray();
for (int i = 0; i < FlightsCode.Length; i++)
{
AirInfo air = new AirInfo();
string[] tempstr = DayArray[i]
.Replace("\r\n", string.Empty)
.Replace("\\r\\n", string.Empty)
.TrimStart().TrimEnd()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Res_ThreeCode star_Three = _sqlSugar.Queryable().First(a => a.Three == tempstr[3].Substring(0, 3));
string starCity = "";
if (star_Three != null)
{
string str2 = "--";
string translateResult2 = transDic.Where(s => s.Key == star_Three.AirPort).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult2))
{
str2 = translateResult2;
str2 = _airTicketResRep.Processing(str2);
}
starCity = str2;
}
Res_ThreeCode End_Three = _sqlSugar.Queryable().First(a => a.Three == tempstr[3].Substring(3, 3));
string EndCity = "";
if (End_Three != null)
{
string str1 = "--";
string translateResult1 = transDic.Where(s => s.Key == End_Three.AirPort).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult1))
{
str1 = translateResult1;
str1 = _airTicketResRep.Processing(str1);
}
EndCity = str1;
}
air.Destination = starCity + "/" + EndCity;
air.Flight = FlightsCode[i];
string str = "--";
string translateResult = transDic.Where(s => s.Key == item.CTypeName).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult))
{
str = translateResult;
str = _airTicketResRep.Processing(str);
}
air.SeatingClass = str;
string dateTime = tempstr[2];
string DateTemp = dateTime.Substring(2, 5).ToUpper();
air.FlightDate = DateTemp;
air.DepartureTime = tempstr[5];
air.LandingTime = tempstr[6];
air.ValidityPeriod = DateTemp + "/" + DateTemp;
air.TicketStatus = "--";
air.Luggage = "--";
air.DepartureTerminal = "--";
air.LandingTerminal = "--";
airs.Add(air);
}
int row = 13;
for (int i = 0; i < airs.Count; i++)
{
if (airs.Count > 2)
{
for (int j = 0; j < airs.Count - 2; j++)
{
var CopyRow = table.Rows[12].Clone(true);
table.Rows.Add(CopyRow);
}
}
PropertyInfo[] properties = airs[i].GetType().GetProperties();
int index = 0;
foreach (PropertyInfo property in properties)
{
string value = property.GetValue(airs[i]).ToString();
Cell ishcel0 = table.Rows[row].Cells[index];
Paragraph p = new Paragraph(doc);
string s = value;
p.AppendChild(new Run(doc, s));
p.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
ishcel0.AppendChild(p);
ishcel0.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐
//ishcel0.CellFormat.VerticalAlignment=
index++;
}
row++;
}
#endregion
Paragraph lastParagraph = new Paragraph(doc);
//第一个表格末尾加段落
table.ParentNode.InsertAfter(lastParagraph, table);
//复制第一个表格
Table cloneTable = (Table)table.Clone(true);
//在文档末尾段落后面加入复制的表格
table.ParentNode.InsertAfter(cloneTable, lastParagraph);
if (item != _AirTicketReservations[_AirTicketReservations.Count - 1])
{
int rownewsIndex = 13;
for (int i = 0; i < 2; i++)
{
var CopyRow = table.Rows[12].Clone(true);
table.Rows.RemoveAt(13);
table.Rows.Add(CopyRow);
rownewsIndex++;
}
}
else
{
table.Rows.RemoveAt(12);
}
cloneTable.Rows.RemoveAt(12);
}
if (_AirTicketReservations.Count != 0)
{
string[] FlightsCode = _AirTicketReservations[0].FlightsCode.Split('/');
if (FlightsCode.Length != 0)
{
Res_AirCompany _AirCompany = _sqlSugar.Queryable().First(a => a.ShortCode == FlightsCode[0].Substring(0, 2));
if (_AirCompany != null)
{
string str = "--";
string translateResult = transDic.Where(s => s.Key == _AirCompany.CnName).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult))
{
str = translateResult;
str = _airTicketResRep.Processing(str);
}
table.Range.Bookmarks["AirlineCompany"].Text = str;
}
else
{
table.Range.Bookmarks["AirlineCompany"].Text = "--";
}
}
table.Range.Bookmarks["AirlineRecordCode"].Text = "--";
table.Range.Bookmarks["ReservationRecordCode"].Text = "--";
string[] nameArray = Regex.Split(_AirTicketReservations[0].ClientName, "\\d+\\.", RegexOptions.IgnoreCase);
nameArray = nameArray.Where(str => str != "" && str != " " && !string.IsNullOrEmpty(str)).ToArray();
string names = "";
foreach (string clientName in nameArray)
{
names += clientName + ",";
}
if (!string.IsNullOrWhiteSpace(names))
{
string str = "--";
string translateResult = transDic.Where(s => s.Key == names).FirstOrDefault().Value;
if (!string.IsNullOrEmpty(translateResult))
{
str = translateResult;
str = _airTicketResRep.Processing(str);
}
table.Range.Bookmarks["ClientName"].Text = str;
}
else
{
table.Range.Bookmarks["ClientName"].Text = "--";
}
table.Range.Bookmarks["TicketNumber"].Text = "--";
table.Range.Bookmarks["IdentificationCode"].Text = "--";
table.Range.Bookmarks["JointTicket"].Text = "--";
table.Range.Bookmarks["TimeIssue"].Text = "--";
table.Range.Bookmarks["DrawingAgent"].Text = "--";
table.Range.Bookmarks["NavigationCode"].Text = "--";
table.Range.Bookmarks["AgentsAddress"].Text = "--";
table.Range.Bookmarks["AgentPhone"].Text = "--";
table.Range.Bookmarks["AgentFacsimile"].Text = "--";
}
doc.MailMerge.Execute(new[] { "PageCount" }, new object[] { doc.PageCount });
//保存合并后的文档
string fileName = "AirItinerary/电子客票英文行程单_EN.docx";
string rst = AppSettingsHelper.Get("WordBaseUrl") + AppSettingsHelper.Get("WordFtpPath") + fileName;
doc.Save(AppSettingsHelper.Get("WordBasePath") + fileName);
return Ok(JsonView(true, "成功!", rst));
}
}
}
catch (Exception ex)
{
return Ok(JsonView(StatusCodes.Status400BadRequest, "程序错误!", ""));
throw;
}
}
#endregion
#region 团组增减款项 --> 其他款项
///
/// 团组增减款项下拉框绑定
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DecreasePaymentsSelect(DecreasePaymentsDto dto)
{
#region 参数验证
if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
if (dto.CTId < 1) return Ok(JsonView(false, "请传入有效的CTId参数!"));
#endregion
return Ok(await _decreasePaymentsRep.DecreasePaymentsSelect(dto));
}
///
/// 根据团组Id查询团组增减款项
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DecreasePaymentsList(DecreasePaymentsListDto dto)
{
#region 参数验证
if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
if (dto.DiId < 1) return Ok(JsonView(false, "请传入有效的DiId参数!"));
#endregion
return Ok(await _decreasePaymentsRep.DecreasePaymentsList(dto));
}
///
/// 团组增减款项操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpDecreasePayments(DecreasePaymentsOpDto dto)
{
JsonView groupData = await _decreasePaymentsRep.OpDecreasePayments(dto);
if (groupData.Code != 200)
{
return Ok(JsonView(false, groupData.Msg));
}
#region 应用推送
int otherId = (int)groupData.Data.GetType().GetProperty("dataId").GetValue(groupData.Data, null);
int ccpId = (int)groupData.Data.GetType().GetProperty("ccpId").GetValue(groupData.Data, null);
int sign = (int)groupData.Data.GetType().GetProperty("sign").GetValue(groupData.Data, null);
//自动审核
var autoAdit = await _feeAuditRep.FeeAutomaticAudit(3, dto.DiId, otherId);
await AppNoticeLibrary.SendChatMsg_GroupStatus_ApplyFee(ccpId, sign, QiyeWeChatEnum.GuoJiaoLeaderChat);
//2024-10-21 新增LZ UID
var userIds = new List() { 21 };
string title = $"系统通知";
string content = "";
var diId = dto.DiId;
var groupInfo = await _groupRepository.Query(x => x.Id == diId).FirstAsync();
var ccpInfo = await _sqlSugar.Queryable().Where(x => x.Id == ccpId).FirstAsync();
if (dto.Status == 1) content = $"[新增-其他款项({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
else if (dto.Status == 2) content = $"[更新-其他款项({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
//await APNsTools.iOS_PushNotifications1("051", $"其他款项费用审核", "", content);
#endregion
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 团组增减款项操作 删除
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelDecreasePayments(DelBaseDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "请传入有效的Id参数!"));
if (dto.DeleteUserId < 1) return Ok(JsonView(false, "请传入有效的DeleteUserId参数!"));
var res = await _decreasePaymentsRep._Del(dto.Id, dto.DeleteUserId);
if (res.Code == 0)
{
return Ok(JsonView(true, "删除成功!"));
}
return Ok(JsonView(false, "删除失败!"));
}
///
/// 根据团组增减款项Id查询
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryDecreasePaymentsById(DecreasePaymentsByIdDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "请传入有效的数据Id!"));
return Ok(await _decreasePaymentsRep.QueryDecreasePaymentsById(dto));
}
///
/// 查询供应商名称
///
///
///
[HttpPost]
public IActionResult QueryAssociateSupplier(AssociateSupplierDto dto)
{
var dbResult = _sqlSugar.Queryable()
.Where(x => x.SupplierName.Contains(dto.param) && x.IsDel == 0).ToList()
?? new List();
dbResult = dbResult.Distinct(new
ProductComparer()).ToList();
var jw = JsonView(true, "success", dbResult.OrderByDescending(x => x.Id).Select(x => new
{
x.Id,
x.SupplierAddress,
x.SupplierArea,
x.SupplierContact,
x.SupplierContactNumber,
x.SupplierEmail,
x.SupplierName,
x.SupplierSocialAccount,
x.SupplierTypeId,
}).ToList());
return Ok(jw);
}
///
/// 团组增减款项 OTA匹配
///
///
///
[HttpPost]
public async Task DecreasePaymentsOTAMate(IFormFile file)
{
if (file.Length < 1) return Ok(JsonView(false, "请上传文件!"));
string fileName = file.FileName;
if (!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".xls"))
{
return Ok(JsonView(false, "请上传Excel文件!"));
}
//D:\FTP\File\OA2023\Office\GrpFile\团组增减款项相关文件\团组其他款项(OTA)
var path = @$"{AppSettingsHelper.Get("GrpFileBasePath")}团组增减款项相关文件/团组其他款项(OTA)";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var filePath = @$"{path}/{fileName}";
//保存文件
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
if (!System.IO.File.Exists(filePath)) return Ok(JsonView(false, "文件不存在!"));
//读取ExcelFile
DataTable dt = ConvertExcelToDataTable(filePath);
if (dt == null) return Ok(JsonView(false, $"您上传的Excel工作表没有内容,请检查!!!"));
dt.TableName = "TB";
//修改table列名
dt.Columns[0].ColumnName = "OrderNo"; // 订单号
dt.Columns[1].ColumnName = "OTAOrderNo"; // OTA订单号
dt.Columns[2].ColumnName = "PackageName"; // 套餐名
dt.Columns[3].ColumnName = "IsPay"; // 是否支付
dt.Columns[4].ColumnName = "IsShipments"; // 是否发货
dt.Columns[5].ColumnName = "IsSendBack"; // 是否寄回
dt.Columns[6].ColumnName = "OpUser"; // 使用人信息
dt.Columns[7].ColumnName = "OrderTime"; // 下单时间
dt.Columns[8].ColumnName = "UseTime"; // 使用时间
dt.Columns[9].ColumnName = "Quantity"; // 台数
dt.Columns[10].ColumnName = "Days"; // 租赁天数
dt.Columns[11].ColumnName = "QuantityShipped";// 发货数量
dt.Columns[12].ColumnName = "TotalPrice"; // 总金额
dt.Columns[13].ColumnName = "GroupName"; // 团组名称
dt.Columns[14].ColumnName = "OATotalPrice"; // OA金额
var otaOrderNos = new List();
foreach (DataRow item in dt.Rows)
{
otaOrderNos.Add(item["OTAOrderNo"].ToString());
}
var oaDatas = await _sqlSugar.Queryable()
.LeftJoin((dp, di) => dp.DiId == di.Id)
.Where((dp, di) => dp.IsDel == 0 && dp.PriceName.Contains("wifi") || otaOrderNos.Contains(dp.OTAOrderNo))
.Select((dp, di) => new
{
dp.PriceName,
dp.OTAOrderNo,
dp.FeeTotal,
di.TeamName,
})
.ToListAsync();
foreach (DataRow item in dt.Rows)
{
var otaOrderNo = item["OTAOrderNo"].ToString();
var oaData = oaDatas.Find(x => !string.IsNullOrEmpty(x.OTAOrderNo) && x.OTAOrderNo.Contains(otaOrderNo));
if (oaData == null) continue;
item["GroupName"] = oaData.TeamName;
item["OATotalPrice"] = oaData.FeeTotal.ToString("#0.00");
}
string fileName1 = $"OTA_WIFI费用{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
Dictionary pairs = new Dictionary();
List datas = new List();
datas.Add(dt);
url = AsposeHelper.ExpertExcelToModel("WIFI费用清单-模板.xlsx", $"GrpFile/团组增减款项相关文件/团组其他款项(OTA)", fileName1, pairs, datas);
return Ok(JsonView(true, "操作成功", new { url = url }));
}
#region
private DataTable ConvertExcelToDataTable(string excelFilePath)
{
// 创建Workbook对象
Workbook workbook = new Workbook(excelFilePath);
// 获取第一个工作表
Worksheet worksheet = workbook.Worksheets[0];
// 将工作表转换为DataTable
DataTable dataTable = worksheet.Cells.ExportDataTable(1, 0, worksheet.Cells.MaxDataRow + 1, worksheet.Cells.MaxDataColumn + 1);
return dataTable;
}
#endregion
#endregion
#region 文件上传、删除
///
/// region 文件上传 可以带参数
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task UploadProject(IFormFile file)
{
//var TypeName = Request.Headers["TypeName"].ToString();
//if (file == null) return Ok(JsonView(false, "文件不存在!"));
//var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
////文件名称
//string projectFileName = file.FileName;
////上传的文件的路径
//string filePath = $"{fileDir}/{projectFileName}";
//if (TypeName == "A")//A代表团组增减款项
//{
// filePath = fileDir + $@"\团组增减款项相关文件";
// if (!Directory.Exists(filePath))
// {
// Directory.CreateDirectory(filePath);
// }
// //上传的文件的路径
// filePath += $@"\{projectFileName}";
//}
//else if (TypeName == "B")//B代表商邀相关文件
//{
// //上传的文件的路径
// filePath = fileDir + $@"\商邀相关文件\{projectFileName}";
// if (!Directory.Exists(filePath))
// {
// Directory.CreateDirectory(filePath);
// }
// //上传的文件的路径
// filePath = $@"\{projectFileName}";
//}
//try
//{
// using (FileStream fs = System.IO.File.Create(filePath))
// {
// file.CopyTo(fs);
// fs.Flush();
// }
//}
//catch (Exception ex)
//{
// return Ok(JsonView(false, $"文件上传失败! Error:{ex.Message}"));
//}
//return Ok(JsonView(true, "上传成功!", projectFileName));
try
{
var TypeName = Request.Headers["TypeName"].ToString();
if (file != null)
{
var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
//文件名称
string projectFileName = file.FileName;
//上传的文件的路径
string filePath = $"{fileDir}/{projectFileName}";
if (TypeName == "A")//A代表团组增减款项
{
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//上传的文件的路径
filePath = fileDir + $@"\团组增减款项相关文件\{projectFileName}";
}
else if (TypeName == "B")//B代表商邀相关文件
{
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//上传的文件的路径
filePath = fileDir + $@"\商邀相关文件\{projectFileName}";
}
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
return Ok(JsonView(true, "上传成功!", projectFileName));
}
else
{
return Ok(JsonView(false, "上传失败!"));
}
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
}
}
///
/// 删除指定文件
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelFile(DelFileDto dto)
{
try
{
var TypeName = Request.Headers["TypeName"].ToString();
if (string.IsNullOrEmpty(TypeName)) return Ok(JsonView(false, "请选择选组对应模块!"));
string filePath = "";
var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
// 返回与指定虚拟路径相对应的物理路径即绝对路径
int id = 0;
if (TypeName == "A")
{
filePath = fileDir + "/团组增减款项相关文件/" + dto.fileName;
// 删除该文件
System.IO.File.Delete(filePath);
id = await _sqlSugar.Updateable()
.Where(a => a.Id == dto.Id)
.SetColumns(a => new Grp_DecreasePayments { FilePath = "" })
.ExecuteCommandAsync();
}
else if (TypeName == "B")
{
filePath = fileDir + "/商邀相关文件/" + dto.fileName;
// 删除该文件
System.IO.File.Delete(filePath);
var info = await _sqlSugar.Queryable().Where(x => x.Id == dto.Id && x.IsDel == 0).FirstAsync();
if (info != null)
{
string[] files = new string[] { };
if (!string.IsNullOrEmpty(info.Attachment))
{
try
{
files = JsonConvert.DeserializeObject(info.Attachment);
}
catch (Exception)
{
files = new List() { info.Attachment }.ToArray();
}
}
if (files.Length > 0)
{
var files1 = files.Where(x => !x.Equals(dto.fileName)).ToArray();
string filePath2 = string.Empty;
if (files1.Length > 0)
{
filePath2 = JsonConvert.SerializeObject(files1);
}
id = await _sqlSugar.Updateable()
.Where(a => a.Id == dto.Id)
.SetColumns(a => new Grp_InvitationOfficialActivities { Attachment = filePath2 })
.ExecuteCommandAsync();
}
}
}
if (id != 0)
{
return Ok(JsonView(true, "成功!"));
}
else
{
return Ok(JsonView(false, "失败!"));
}
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 文件上传多个文件 可以带参数
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task UploadProjects(IFormFile[] files)
{
try
{
var TypeName = Request.Headers["TypeName"].ToString();
if (string.IsNullOrEmpty(TypeName)) return Ok(JsonView(false, "请选择选组对应模块!"));
if (files.Length < 1) return Ok(JsonView(false, "请选择文件!"));
var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
var filePahts = new List();
foreach (var file in files)
{
//文件名称
string projectFileName = file.FileName;
//上传的文件的路径
string filePath = $"{fileDir}/{projectFileName}";
if (TypeName == "A")//A代表团组增减款项
{
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//上传的文件的路径
filePath = fileDir + $@"\团组增减款项相关文件\{projectFileName}";
}
else if (TypeName == "B")//B代表商邀相关文件
{
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//上传的文件的路径
filePath = fileDir + $@"\商邀相关文件\{projectFileName}";
}
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
filePahts.Add(projectFileName);
}
return Ok(JsonView(true, "上传成功!", filePahts));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
}
}
#endregion
#region 商邀费用录入
///
/// 根据团组Id查询商邀费用列表
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivitiesList(InvitationOfficialActivitiesListDto dto)
{
Result groupData = await _InvitationOfficialActivitiesRep.InvitationOfficialActivitiesList(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 商邀费用列表
/// 下载文件
///
///
///
[HttpGet("{id}")]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivitiesListDownFile(int id)
{
if (id < 1) return Ok(JsonView(false, "请传入有效的Id!"));
var info = await _InvitationOfficialActivitiesRep.Query(x => x.Id == id).FirstAsync();
if (info == null) return Ok(JsonView(false, "数据不存在!"));
if (string.IsNullOrEmpty(info.Attachment)) return Ok(JsonView(false, "文件不存在!"));
var filePaths = new List();
var filePathBase = @$"{AppSettingsHelper.Get("GrpFileBasePath")}/商邀相关文件/";
try
{
filePaths = JsonConvert.DeserializeObject>(info.Attachment);
}
catch (Exception ex)
{
filePaths.Add(info.Attachment);
}
if (filePaths != null && filePaths.Count < 1) return Ok(JsonView(false, "文件不存在!"));
for (int i = 0; i < filePaths.Count; i++)
{
filePaths[i] = $"{filePathBase}{filePaths[i]}";
}
var zipFilePathGuid = $"{Guid.NewGuid()}.zip";
var zipFilePath = $"{AppSettingsHelper.Get("GrpFileBasePath")}/商邀相关文件/{zipFilePathGuid}";
using (FileStream zipFileStream = new FileStream(zipFilePath, FileMode.Create))
{
using (ZipArchive zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Create))
{
foreach (string filePath in filePaths)
{
if (System.IO.File.Exists(filePath))
{
// 获取文件名
string fileName = Path.GetFileName(filePath);
// 将文件添加到ZIP归档中
zipArchive.CreateEntryFromFile(filePath, fileName);
}
}
}
}
return Ok(JsonView(new { url = @$"{AppSettingsHelper.Get("OfficeBaseUrl")}{AppSettingsHelper.Get("GrpFileFtpPath")}/商邀相关文件/{zipFilePathGuid}" }));
}
///
/// 商邀费用 Info Page 基础数据源
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivityInitBasicData()
{
try
{
Result groupData = await _InvitationOfficialActivitiesRep._InitBasicData();
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, "操作成功", groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
throw;
}
}
///
/// 根据商邀费用ID查询C表和商邀费用数据
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivitiesById(InvitationOfficialActivitiesByIdDto dto)
{
try
{
Result groupData = await _InvitationOfficialActivitiesRep.InvitationOfficialActivitiesById(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
throw;
}
}
///
/// 商邀费用录入操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpInvitationOfficialActivities(OpInvitationOfficialActivitiesDto dto)
{
Result groupData = await _InvitationOfficialActivitiesRep.OpInvitationOfficialActivities(dto, _setDataRep.PostCurrencyByDiid);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
#region 应用推送
try
{
int ccpId = groupData.Data.GetType().GetProperty("ccpId").GetValue(groupData.Data, null);
int sign = groupData.Data.GetType().GetProperty("sign").GetValue(groupData.Data, null);
await AppNoticeLibrary.SendChatMsg_GroupStatus_ApplyFee(ccpId, sign, QiyeWeChatEnum.GuoJiaoLeaderChat);
//2024-10-21 新增LZ UID
var userIds = new List() { 21 };
string title = $"系统通知";
string content = "";
var diId = dto.DiId;
var groupInfo = await _groupRepository.Query(x => x.Id == diId).FirstAsync();
var ccpInfo = await _sqlSugar.Queryable().Where(x => x.Id == ccpId).FirstAsync();
if (dto.Status == 1) content = $"[新增-商邀费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
else if (dto.Status == 2) content = $"[更新-商邀费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
PageParam_PriceAuditH5 h5 = new PageParam_PriceAuditH5() { diid = diId.ToString(), uid = "21" };
await APNsTools.iOS_PushNotifications1("051", $"商邀费用审核", "", content, true, "ExpenseAuditWebView", h5);
}
catch (Exception ex)
{
}
#endregion
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 商邀删除
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelInvitationOfficialActivities(DelBaseDto dto)
{
try
{
_sqlSugar.BeginTran();
var res1 = _sqlSugar.Updateable()
.SetColumns(it => new Grp_InvitationOfficialActivities()
{
IsDel = 1,
DeleteUserId = dto.DeleteUserId,
DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
})
.Where(it => it.Id == dto.Id)
.ExecuteCommand();
if (res1 > 0)
{
int _diId = 0;
var _ioaInfo = _sqlSugar.Queryable().Where(it => it.Id == dto.Id).First();
if (_ioaInfo != null)
{
_diId = _ioaInfo.DiId;
}
var res2 = _sqlSugar.Updateable()
.SetColumns(a => new Grp_CreditCardPayment()
{
IsDel = 1,
DeleteUserId = dto.DeleteUserId,
DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
})
.Where(a => a.CId == dto.Id && a.DIId == _diId && a.CTable == 81)
.ExecuteCommand();
if (res2 > 0)
{
_sqlSugar.CommitTran();
return Ok(JsonView(true, "删除成功!"));
}
}
_sqlSugar.RollbackTran();
return Ok(JsonView(false, "删除失败"));
}
catch (Exception ex)
{
_sqlSugar.RollbackTran();
return Ok(JsonView(false, ex.Message));
}
}
///
/// 团组模块文件上传
///
///
///
[HttpPost]
public IActionResult CommonSaveFile([FromForm] CommonSaveFileDto dto)
{
var jw = JsonView(false);
long M = 1024 * 1024;
if (dto.Files == null || dto.Files.Count == 0)
{
jw.Msg = "无文件信息!";
return Ok(jw);
}
if (dto.Files.Sum(x => x.Length) > 20 * M)
{
jw.Msg = "文件大小超过20M!";
return Ok(jw);
}
//var nameSp = dto.File.FileName.Split(".");
//if (nameSp.Length < 2)
//{
// jw.Msg = "拓展名称有误!";
// return Ok(jw);
//}
//var existsName = new string[]{ "RAR", "ZIP", "ARJ","GZ","Z","7Z","TAR" };
//if (!existsName.Contains(nameSp[1].ToUpper()))
//{
// jw.Msg = $"请使用指定拓展名!({string.Join("-",existsName)})";
// return Ok(jw);
//}
var Ctable = _sqlSugar.Queryable().First(x => x.STid == 16 && x.IsDel == 0 && x.Id == dto.Ctable);
if (Ctable == null)
{
jw.Msg = "Ctable指向有误!";
return Ok(jw);
}
var groupInfo = _sqlSugar.Queryable().First(x => x.Id == dto.Diid && x.IsDel == 0);
if (groupInfo == null)
{
jw.Msg = "团组信息不存在!";
return Ok(jw);
}
Ctable.Name = Regex.Replace(Ctable.Name, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
groupInfo.TeamName = Regex.Replace(groupInfo.TeamName, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
var path = "\\GroupModelFiles\\" + groupInfo.TeamName + "\\" + Ctable.Name;
var fileBase = AppSettingsHelper.Get("GrpFileBasePath") + path;
try
{
if (!Directory.Exists(fileBase))
{
Directory.CreateDirectory(fileBase);
}
List saveArr = new List();
foreach (var fileStream in dto.Files)
{
var saveFilePath = fileBase + "\\" + fileStream.FileName;
Grp_GroupModelFile file = new Grp_GroupModelFile()
{
Cid = dto.Cid,
CreateTime = DateTime.Now,
CreateUserId = dto.Userid,
Ctable = dto.Ctable,
Diid = dto.Diid,
IsDel = 0,
FilePath = saveFilePath,
FileName = fileStream.FileName
};
using (FileStream fs = System.IO.File.Create(saveFilePath))
{
fileStream.CopyTo(fs);
fs.Flush();
}
saveArr.Add(file);
}
var addResult = _sqlSugar.Insertable(saveArr).ExecuteCommand();
//url = AppSettingsHelper.Get("WordBaseUrl") + AppSettingsHelper.Get("GrpFileFtpPath") + path + "\\" + dto.File.FileName
jw = JsonView(true, "保存成功!", new
{
count = addResult,
filesName = saveArr.Select(x => x.FileName)
});
}
catch (Exception ex)
{
jw = JsonView(false, $"保存失败! ({ex.Message}) ", new
{
count = 0,
filesName = new string[0],
});
}
return Ok(jw);
}
///
/// 查询各模块已保存文件
///
///
///
[HttpPost]
public IActionResult QueryGroupModelFile(QueryGroupModelFileDto dto)
{
var expression = Expressionable.Create()
.AndIF(dto.UserId != -1, x => x.CreateUserId == dto.UserId);
var visaIds = _sqlSugar.Queryable().Where(x => x.JobPostId == 26).Select(x => x.Id).ToList();
if (visaIds.Contains(dto.UserId) && dto.Ctable == 80)
{
expression = Expressionable.Create()
.And(x => visaIds.Contains(x.CreateUserId));
}
var dbQuery = _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 && x.Cid == dto.Cid && x.Ctable == dto.Ctable && x.Diid == dto.Diid)
.Where(expression.ToExpression())
.ToList();
//.ToPageList(pagenumber, pageSize, ref totalCount, ref totalPage)
return Ok(JsonView(true, "success", dbQuery.Select(x => new
{
x.FileName,
x.Id,
Url = AppSettingsHelper.Get("GrpFileBaseUrl") + x.FilePath.Replace(AppSettingsHelper.Get("GrpFileBasePath"), AppSettingsHelper.Get("GrpFileFtpPath")),
CreateTime = x.CreateTime.ToString("yyyy-MM-dd HH-mm"),
})));
}
///
/// 下载该团组下的所有文件
///
///
///
[HttpPost]
public IActionResult ExportGroupZip(ExportGroupZipDto dto)
{
var jw = JsonView(false);
var groupInfo = _sqlSugar.Queryable().First(x => x.IsDel == 0 && x.Id == dto.Diid);
if (groupInfo == null)
{
jw.Msg = "团组信息不存在!";
return Ok(jw);
}
var dbQuery = _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Diid == dto.Diid).ToList();
var isModule = Convert.ToBoolean(dto.isModule);
Dictionary Zips = new Dictionary();
IOOperatorHelper io = new IOOperatorHelper();
if (isModule)
{
var moduleGroup = dbQuery.GroupBy(x => x.Ctable);
foreach (var moduleArr in moduleGroup)
{
var key = _sqlSugar.Queryable().First(x => x.Id == moduleArr.Key && x.IsDel == 0);
key.Name = Regex.Replace(key.Name, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
Dictionary chiZips = new Dictionary();
foreach (var item in moduleArr)
{
if (System.IO.File.Exists(item.FilePath))
{
using (FileStream fileStream = new FileStream(item.FilePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
Stream stream = new MemoryStream(bytes);
chiZips.Add(item.FileName, stream);
}
}
}
if (chiZips.Count > 0)
{
var byts = io.ConvertZipStream(chiZips);
Stream stream = new MemoryStream(byts);
Zips.Add(key.Name + "_.zip", stream);
}
}
}
else
{
foreach (var item in dbQuery)
{
using (FileStream fileStream = new FileStream(item.FilePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
Stream stream = new MemoryStream(bytes);
while (Zips.Keys.Contains(item.FileName))
{
item.FileName = new Random().Next(100) + "_" + item.FileName;
}
Zips.Add(item.FileName, stream);
}
}
}
groupInfo.TeamName = Regex.Replace(groupInfo.TeamName, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
if (Zips.Count > 0)
{
var byts = io.ConvertZipStream(Zips);
var path = "\\GroupModelFiles\\" + groupInfo.TeamName;
io.ByteToFile(byts, AppSettingsHelper.Get("GrpFileBasePath") + $"{path}\\{groupInfo.TeamName}_.Zip");
jw = JsonView(true, "success", new { url = AppSettingsHelper.Get("GrpFileBaseUrl") + $"{AppSettingsHelper.Get("GrpFileFtpPath")}{path}\\{groupInfo.TeamName}_.zip" });
}
else
{
jw.Msg = "暂无生成文件!";
}
return Ok(jw);
}
///
/// 下载该团组下此模块的所有文件
///
///
///
[HttpPost]
public IActionResult ExportGroupByModule(ExportGroupByModuleDto dto)
{
var jw = JsonView(false);
var groupInfo = _sqlSugar.Queryable().First(x => x.IsDel == 0 && x.Id == dto.Diid);
if (groupInfo == null)
{
jw.Msg = "团组信息不存在!";
return Ok(jw);
}
var dbQuery = _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Diid == dto.Diid && x.Ctable == dto.Ctable).ToList();
var key = _sqlSugar.Queryable().First(x => x.Id == dto.Ctable
&& x.IsDel == 0);
if (key == null)
{
jw.Msg = "Ctable指向错误!";
return Ok(jw);
}
key.Name = Regex.Replace(key.Name, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
groupInfo.TeamName = Regex.Replace(groupInfo.TeamName, @"[^\w\.@-]", "",
RegexOptions.None, TimeSpan.FromSeconds(1.5));
IOOperatorHelper io = new IOOperatorHelper();
Dictionary Zips = new Dictionary();
foreach (var item in dbQuery)
{
if (System.IO.File.Exists(item.FilePath))
{
using (FileStream fileStream = new FileStream(item.FilePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
Stream stream = new MemoryStream(bytes);
while (Zips.Keys.Contains(item.FileName))
{
item.FileName = new Random().Next(100) + "_" + item.FileName;
}
Zips.Add(item.FileName, stream);
}
}
}
if (Zips.Count > 0)
{
var byts = io.ConvertZipStream(Zips);
var path = "\\GroupModelFiles\\" + groupInfo.TeamName;
io.ByteToFile(byts, AppSettingsHelper.Get("GrpFileBasePath") + $"{path}\\{groupInfo.TeamName}_{key.Name}_.Zip");
jw = JsonView(true, "success", new { url = AppSettingsHelper.Get("GrpFileBaseUrl") + $"{AppSettingsHelper.Get("GrpFileFtpPath")}{path}\\{groupInfo.TeamName}_{key.Name}_.Zip" });
}
else
{
jw.Msg = "暂无生成文件!";
}
return Ok(jw);
}
///
/// 删除该团组下的指定文件
///
///
///
[HttpPost]
public IActionResult DeleteGroupFile(DeleteGroupFileDto dto)
{
var jw = JsonView(false);
var sing = _sqlSugar.Queryable().First(x => x.Id == dto.Id && x.IsDel == 0);
if (sing == null)
{
jw.Msg = "暂无";
return Ok(jw);
}
if (System.IO.File.Exists(sing.FilePath))
{
try
{
System.IO.File.Delete(sing.FilePath);
}
catch (Exception ex)
{
jw.Msg = "删除失败!" + ex.Message;
return Ok(jw);
}
}
sing.IsDel = 1;
sing.DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
sing.DeleteUserId = dto.UserId;
_sqlSugar.Updateable(sing).ExecuteCommand();
jw = JsonView(true, "删除成功!");
return Ok(jw);
}
#endregion
#region 团组英文资料
///
/// 查询团组英文所有资料
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryDelegationEnData(QueryDelegationEnDataDto dto)
{
try
{
Result groupData = await _delegationEnDataRep.QueryDelegationEnData(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 团组英文资料操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpDelegationEnData(OpDelegationEnDataDto dto)
{
try
{
Result groupData = await _delegationEnDataRep.OpDelegationEnData(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 团组英文资料Id查询数据
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryDelegationEnDataById(QueryDelegationEnDataByIdDto dto)
{
try
{
Grp_DelegationEnData _DelegationEnData = await _sqlSugar.Queryable().FirstAsync(it => it.Id == dto.Id && it.IsDel == 0);
if (_DelegationEnData != null)
{
return Ok(JsonView(true, "查询成功!", _DelegationEnData));
}
return Ok(JsonView(true, "暂无数据!", _DelegationEnData));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///