using System.Dynamic;
using Aop.Api.Domain;
using JNPF.Common.Core.Manager;
using JNPF.Common.Extension;
using JNPF.Common.Filter;
using JNPF.Common.Security;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.FriendlyException;
using JNPF.Logging;
using JNPF.Systems.Entitys.System;
using JNPF.Systems.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.OpenXmlFormats.Shared;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;
using SqlSugar;
using Tnb.ProductionMgr.Entitys.Dto.PrdManage;
using Tnb.ProductionMgr.Entitys.Dto.WorkOrder;
using Tnb.ProductionMgr.Entitys.Entity;
using Tnb.ProductionMgr.Entitys.新文件夹;
using Tnb.ProductionPlanMgr.Entitys.Dto.WorkOrder;
using Tnb.ProductionPlanMgr.Interfaces;
namespace Tnb.ProductionPlanMgr
{
///
/// 生产计划管理
///
[ApiDescriptionSettings(Tag = "ProductionMgr", Area = "production", Order = 700)]
[Route("api/[area]/[controller]/[action]")]
public class PrdMoService : IPrdMoService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository _repository;
private readonly IDataBaseManager _dataBaseManager;
private readonly IUserManager _userManager;
private readonly IDictionaryDataService _dictionaryDataService;
public PrdMoService(
ISqlSugarRepository repository,
IDataBaseManager dataBaseManager,
IUserManager userManager,
IDictionaryDataService dictionaryDataService
)
{
_repository = repository;
_dataBaseManager = dataBaseManager;
_userManager = userManager;
_dictionaryDataService = dictionaryDataService;
}
#region Get
///
/// 根据产品ID获取模具列表
///
/// 产品ID
///
///
///
return results:
///
[
///
{
///
mold_code:模具编号
///
mold_name:模具名称
///
item_name:产品名称
///
item_code:产品编号
///
cavity_qty:模穴数
///
}
///
]
///
[HttpGet("moldlist/{itemId}")]
public async Task GetMoldListByItemId(string itemId)
{
var db = _repository.AsSugarClient();
var list = await db.Queryable().InnerJoin((a, b) => a.item_id == b.id)
.Where((a, b) => a.item_id == itemId)
.Select((a, b) => new MoldListOutput
{
id = a.id,
mold_code = a.mold_code,
mold_name = a.mold_name,
item_name = b.item_name,
cavity_qty = a.cavity_qty,
item_code = b.item_code,
})
.ToListAsync();
return list;
}
///
/// 根据模具Id获取设备列表
///
///
///
[HttpGet("equipments/{moldId}")]
public async Task GetEquipmentListByMoldId(string moldId)
{
var items = await _repository.AsSugarClient().Queryable()
.InnerJoin((a, b) => a.id == b.eqp_id)
.Where((a, b) => a.mold_id == moldId)
.Select((a, b) => new
{
eqp_code = a.eqp_code,
eqp_type_code = a.eqp_type_code,
tonnage = b.tonnage,
task_list_qty = SqlFunc.Subqueryable().Where(it => it.eqp_id == a.id).Count(),
first_date = SqlFunc.Subqueryable().Where(it => it.eqp_id == a.id).OrderByDesc(o => o.estimated_end_date).Select(it => it.estimated_end_date)
}).ToListAsync();
return items;
}
///
/// 工单调整-生产任务重新排序
///
/// 设备ID
/// 排序后生产任务列表
///
/// returns:
///
[
///
{
///
no:生产序号
///
mo_id:工单编号
///
group_flag:同组标识
///
plan_qty:计划生产数量
///
comple_qty:完成数量
///
item_name:产品名称
///
mold_code:模具编号
///
}
///
]
///
[HttpGet("sort/{eqpId}")]
public async Task PrdTaskSort(string eqpId)
{
var taskStatusDic = await _dictionaryDataService.GetDicByTypeId(DictionaryConstants.PrdTaskStatusTypeId);
var list = await _repository.AsSugarClient().Queryable()
.Where(it => it.eqp_id == eqpId)
.OrderBy(o => o.estimated_start_date)
.ToListAsync();
var data = list.Select((x, idx) => new PrdTaskSortOutput
{
no = idx + 1,
mo_id = x.mo_id,
status = taskStatusDic.ContainsKey(x.status) ? taskStatusDic[x.status].ToString() : "",
group_flag = x.group_flag,
plan_qty = x.plan_qty,
comple_qty = x.comple_qty,
item_name = x.item_name,
mold_code = x.mold_code,
}).ToList();
return data;
}
///
/// 查看工单操作记录
///
/// 任务ID
///
[HttpGet("record/{taskId}")]
public async Task GetMoOperRecord(string taskId)
{
var list = await _repository.AsSugarClient().Queryable().Where(it => it.id == taskId).ToListAsync();
var data = list.Adapt>();
var dic = await _dictionaryDataService.GetDicByTypeId(DictionaryConstants.PrdTaskStatusTypeId);
_repository.AsSugarClient().ThenMapper(data, x => x.statusName = dic.ContainsKey(x.status) ? dic[x.status].ToString() : "");
return data;
}
#endregion
#region Post
///
/// 生产工单创建-生产工单下发
///
/// 生产工单下发输入参数
///
[HttpPut("workorder-issue")]
public async Task WorkOrderIssue(MoCrInput input)
{
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
var db = _repository.AsSugarClient();
//获取同组工单的Id,一起下发
var combineMoCodes = await db.Queryable().Where(it => input.WorkOrderIds.Contains(it.id)).Select(it => it.combine_mo_code).ToListAsync();
if (combineMoCodes?.Count > 0)
{
var moIds = await db.Queryable().Where(it => combineMoCodes.Contains(it.combine_mo_code) && !input.WorkOrderIds.Contains(it.id)).Select(it => it.id).ToListAsync();
input.WorkOrderIds = input.WorkOrderIds.Concat(moIds).ToList();
}
var row = await db.Updateable()
.SetColumns(it => new PrdMo { mo_status = DictionaryConstants.IssueId })
.Where(it => input.WorkOrderIds.Contains(it.id))
.ExecuteCommandAsync();
return (row > 0);
}
///
/// 关联同组工单
///
/// 关联同组工单输入参数
///
[HttpPost("relevancy")]
public async Task RelevancySameGroupMo(MoCrInput input)
{
(bool executeRes, string errMsg) multi = (true, "");
var list = await _repository.AsSugarClient().Queryable()
.InnerJoin((a, b) => a.item_code == b.item_id)
.Where((a, b) => input.WorkOrderIds.Contains(a.id))
.Select((a, b) => new
{
planDate = a.plan_start_date,
mold_code = b.mold_code,
}).ToListAsync();
var planDateAll = true;
var moldIdAll = true;
if (list?.Count > 0)
{
var planDate = list.FirstOrDefault()?.planDate;
var moldCode = list.FirstOrDefault()?.mold_code;
planDateAll = list.Skip(1).All(x => x.planDate == planDate);
moldIdAll = list.Skip(1).All(x => x.mold_code == moldCode);
if (planDateAll && moldIdAll)
{
var groupId = SnowflakeIdHelper.NextId();
multi.executeRes = await _repository.AsSugarClient().Updateable()
.SetColumns(c => new PrdMo { combine_mo_code = groupId })
.Where(it => input.WorkOrderIds.Contains(it.id))
.ExecuteCommandHasChangeAsync();
}
else
{
multi.executeRes = false;
if (!planDateAll)
{
throw new AppFriendlyException("计划开始日期不一致", null);
}
if (!moldIdAll)
{
throw new AppFriendlyException("未关联到同一模具下", null);
}
}
}
return multi;
}
///
/// 取消关联
///
/// 取消关联输入参数
///
[HttpPost("CanelRelevancy")]
public async Task CanelRelevancy(MoCrInput input)
{
return await _repository.AsSugarClient().Updateable()
.SetColumns(c => new PrdMo { combine_mo_code = "" })
.Where(it => input.WorkOrderIds.Contains(it.id))
.ExecuteCommandHasChangeAsync();
}
///
/// 生产工单-生产排产
///
///
///
{
///
Id:生产任务主键Id
///
MoType:工单类型 1、注塑/挤出 2、组装/包装
///
MoId:工单Id
///
ItemId:产品编号
///
ItemName:产品名称
///
MoldId:模具Id
///
MoldName:模具名称
///
EqpId:设备Id
///
EqpName:设备名称
///
LineId:产线编号
///
LineName:产线名称
///
}
///
///
[HttpPost("scheduling")]
public async Task ProductionScheduling(ProductionSchedulingCrInput input)
{
var row = -1;
if (input.mo_type.HasValue && input.mo_type.Value == 1)
{
input.id ??= SnowflakeIdHelper.NextId();
var entity = input.Adapt();
entity.status = "ToBeScheduled"; //任务单状态默认,待排产
entity.create_id = _userManager.UserId;
entity.create_time = DateTime.Now;
entity.prd_task_id = input.id;
var db = _repository.AsSugarClient();
try
{
await db.Ado.BeginTranAsync();
row = await db.Storageable(entity).ExecuteCommandAsync();
var taskLogEntity = input.Adapt();
taskLogEntity.id ??= SnowflakeIdHelper.NextId();
taskLogEntity.task_id = input.id;
taskLogEntity.status ??= "ToBeStarted";
taskLogEntity.create_id = _userManager.UserId;
taskLogEntity.create_time = DateTime.Now;
taskLogEntity.operator_name = _userManager.RealName;
//任务状态变更时插入操作记录
if (!db.Queryable().Where(it => it.task_id == input.id && it.status == taskLogEntity.status).Any())
{
row = await db.Insertable(taskLogEntity).ExecuteCommandAsync();
}
if (row > 0)
{
var obj = (await db.Queryable().FirstAsync(it => it.id == input.mo_id));
obj.input_qty += entity.scheduled_qty;
var moStatus = "";
//判断,已排产数量>=计划数量时将状态改为 已排产
if (obj.input_qty >= obj.plan_qty)
{
moStatus = MoStatus.AlreadyId;
}
else
{
//修改工单状态为待排产,同事修改已排产数量
moStatus = MoStatus.WaitProductId;
}
row = await db.Updateable().SetColumns(it => new PrdMo
{
mo_status = moStatus,
input_qty = obj.input_qty
})
.Where(it => it.id == entity.mo_id).ExecuteCommandAsync();
}
await db.Ado.CommitTranAsync();
}
catch (Exception ex)
{
Log.Error("生产任务发布时发生错误", ex);
await db.Ado.RollbackTranAsync();
}
}
return row > 0;
}
///
/// 生产任务下发
///
///
[HttpPost("task-release")]
public async Task PrdTaskRelease(PrdTaskReleaseUpInput input)
{
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
var db = _repository.AsSugarClient();
var row = await db.Updateable()
.SetColumns(it => new PrdTask { status = DictionaryConstants.ToBeStartedEnCode })
.Where(it => input.TaskIds.Contains(it.id))
.ExecuteCommandAsync();
return (row > 0);
}
///
/// 工单调整-转移机台
///
///
[HttpPost]
public async Task TransferPlatform(TransferPlatformUpInput input)
{
return await _repository.AsSugarClient().Updateable()
.SetColumns(it => new PrdTask { eqp_id = input.eqp_id })
.Where(it => it.id == input.icmo_id)
.ExecuteCommandHasChangeAsync();
}
#endregion
}
}