Files
tnb.server/WarehouseMgr/Tnb.WarehouseMgr/WmsPDACarryBindService.cs
2024-09-21 09:30:19 +08:00

520 lines
26 KiB
C#

using Aop.Api.Domain;
using JNPF.Common.Core.Manager;
using JNPF.Common.Dtos.VisualDev;
using JNPF.Common.Enums;
using JNPF.Common.Extension;
using JNPF.Common.Security;
using JNPF.FriendlyException;
using JNPF.Systems.Interfaces.System;
using JNPF.VisualDev;
using JNPF.VisualDev.Entitys;
using JNPF.VisualDev.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using Tnb.BasicData.Entities;
using Tnb.WarehouseMgr.Entities;
using Tnb.WarehouseMgr.Entities.Consts;
using Tnb.WarehouseMgr.Entities.Dto;
using Tnb.WarehouseMgr.Entities.Dto.Inputs;
using Tnb.WarehouseMgr.Entities.Entity;
using Tnb.WarehouseMgr.Entities.Enums;
using Tnb.WarehouseMgr.Interfaces;
namespace Tnb.WarehouseMgr
{
/// <summary>
/// 载具绑定
/// </summary>
[OverideVisualDev(ModuleConsts.MODULE_WMSCARRYBINDPDA_ID)]
public class WmsPDACarryBindService : BaseWareHouseService
{
private readonly ISqlSugarClient _db;
private readonly IRunService _runService;
private readonly IVisualDevService _visualDevService;
private readonly IUserManager _userManager;
private readonly IBillRullService _billRullService;
private readonly IWareHouseService _wareHouseService;
private readonly IWmsCarryBindService _wmsCarryBindService;
private readonly IWmsCarryUnbindService _wmsCarryUnbindService;
private readonly IWmsCarryService _wmsCarryService;
public WmsPDACarryBindService(
ISqlSugarRepository<WmsCarryH> repository,
IRunService runService,
IVisualDevService visualDevService,
IUserManager userManager,
IWareHouseService wareHouseService,
IBillRullService billRullService,
IWmsCarryBindService wmsCarryBindService,
IWmsCarryUnbindService wmsCarryUnbindService,
IWmsCarryService wmsCarryService)
{
_db = repository.AsSugarClient();
_runService = runService;
_visualDevService = visualDevService;
_userManager = userManager;
_billRullService = billRullService;
_wareHouseService = wareHouseService;
_wmsCarryBindService = wmsCarryBindService;
_wmsCarryUnbindService = wmsCarryUnbindService;
_wmsCarryService = wmsCarryService;
OverideFuncs.CreateAsync = PDACarryBind;
}
private async Task<dynamic> PDACarryBind(VisualDevModelDataCrInput input)
{
bool isOk = false;
try
{
await _db.Ado.BeginTranAsync();
VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(ModuleConsts.MODULE_WMSCARRYBINDPDA_ID, true);
await _runService.Create(templateEntity, input);
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
string? carryId = input.data.ContainsKey("carry_id") ? input.data["carry_id"]?.ToString() : "";
string? subCarryId = input.data.ContainsKey("membercarry_id") ? input.data["membercarry_id"]?.ToString() : "";
WmsCarryH? carry = await _db.Queryable<WmsCarryH>().SingleAsync(it => it.id == carryId);
WmsCarryH? subCarry = await _db.Queryable<WmsCarryH>().SingleAsync(it => it.id == subCarryId);
if (carry != null && subCarry != null)
{
//更新载具明细
WmsCarryD wmsCarryD = new()
{
id = SnowflakeIdHelper.NextId(),
carry_id = carry.id,
org_id = carry?.org_id!,
membercarry_id = subCarry.id,
membercarry_code = subCarry.carry_code,
loc = input.data[nameof(WmsCarrybindH.loc)].ParseToInt(1),
create_id = _userManager.UserId,
create_time = DateTime.Now
};
int row = await _db.Insertable(wmsCarryD).ExecuteCommandAsync();
carry!.carry_status = ((int)EnumCarryStatus.).ToString();
row = await _db.Updateable(carry).ExecuteCommandAsync();
subCarry.carry_status = ((int)EnumCarryStatus.).ToString();
row = await _db.Updateable(subCarry).ExecuteCommandAsync();
List<WmsCarryCode> items = await _db.Queryable<WmsCarryCode>().Where(it => it.carry_id == subCarryId).ToListAsync();
//更新载具绑定条码表
for (int i = 0; i < items.Count; i++)
{
WmsCarrybindCode wmsCarrybindCode = new()
{
id = SnowflakeIdHelper.NextId(),
org_id = subCarry?.org_id!,
carrybind_id = input.data["ReturnIdentity"]?.ToString()!,
material_id = items[i].material_id,
material_code = items[i].material_code,
barcode = items[i].barcode,
code_batch = items[i].code_batch,
codeqty = items[i].codeqty,
membercarry_id = subCarry?.id,
membercarry_code = subCarry?.carry_code,
unit_id = items[i].unit_id,
unit_code = items[i].unit_code,
create_id = _userManager.UserId,
create_time = DateTime.Now
};
row = await _db.Insertable(wmsCarrybindCode).ExecuteCommandAsync();
}
isOk = row > 0;
if (!isOk)
{
throw Oops.Oh(ErrorCode.COM1001);
}
}
else
{
if (carry == null || subCarry == null)
{
throw new AppFriendlyException("没有可用的主载具", 500);
}
}
await _db.Ado.CommitTranAsync();
}
catch (Exception)
{
await _db.Ado.RollbackTranAsync();
throw;
}
return Task.FromResult(true);
}
/* public override async Task ModifyAsync(WareHouseUpInput input)
{
if (input == null) throw new ArgumentNullException(nameof(input));
var isOk = await _db.Updateable<WmsCarryReplaceH>().SetColumns(it => new WmsCarryReplaceH { status = input.bizTypeId }).Where(it => it.id == input.requireId).ExecuteCommandHasChangeAsync();
if (!isOk) throw Oops.Oh(ErrorCode.COM1001);
}*/
/// <summary>
/// 1楼到3楼 外协入库
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="AppFriendlyException"></exception>
[HttpPost, NonUnify, AllowAnonymous]
public async Task<Tnb.WarehouseMgr.Entities.Dto.Outputs.Result> OutsourcedPartsInstock(OutsourcedPartsInstockInput input)
{
SemaphoreSlim semaphoreSlim = null;
try
{
semaphoreSlim = _wareHouseService.GetSemaphore("instock", WmsWareHouseConst.WAREHOUSE_CP_ID);
await semaphoreSlim.WaitAsync();
if (string.IsNullOrEmpty(input.carry_code))
{
throw new AppFriendlyException("载具编号不可为空", 500);
}
if (string.IsNullOrEmpty(input.material_id))
{
throw new AppFriendlyException("物料id不可为空", 500);
}
if (input.qty <= 0)
{
throw new AppFriendlyException("数量必须大于0", 500);
}
if (string.IsNullOrEmpty(input.source_id))
{
throw new AppFriendlyException("成品调拨明细id不可为空", 500);
}
if (string.IsNullOrEmpty(input.startlocation_id))
{
throw new AppFriendlyException("起点不可为空", 500);
}
WmsTransferInstockD wmsTransferInstockD = await _db.Queryable<WmsTransferInstockD>().Where(r => r.id == input.source_id).FirstAsync();
if (wmsTransferInstockD.status == WmsWareHouseConst.TASK_BILL_STATUS_COMPLE_ID)
{
throw new AppFriendlyException("此成品调拨任务已完成,不允许重复提交", 500);
}
await _db.Ado.BeginTranAsync();
//入库取终点 //出库起点
InStockStrategyQuery inStockStrategyInput = new() { warehouse_id = WmsWareHouseConst.WAREHOUSE_CP_ID,Region_id = WmsWareHouseConst.REGION_CPOutstock_ID, Size = 1 };
List<BasLocation> endLocations = await _wareHouseService.InStockStrategy(inStockStrategyInput);
if (endLocations.Count == 0)
{
throw new AppFriendlyException("没有可用的入库库位", 500);
}
WmsPointH sPoint = null!;
WmsPointH ePoint = null!;
sPoint = await _db.Queryable<WmsPointH>().FirstAsync(it => it.location_id == input.startlocation_id);
if (endLocations?.Count > 0)
{
WmsCarryH carry = await _db.Queryable<WmsCarryH>().SingleAsync(it => it.carry_code == input.carry_code);
if (carry.carry_status == "1")
{
throw new AppFriendlyException("载具已占用!", 500);
}
if (carry.is_lock == 1)
{
throw new AppFriendlyException("载具已锁定!", 500);
}
BasLocation loc = await _db.Queryable<BasLocation>().SingleAsync(it => it.id == endLocations[0].id);
bool isMatch = await IsCarryAndLocationMatchByCarryStd(carry, loc);
if (!isMatch)
{
throw new AppFriendlyException("库位与载具规格不匹配", 500);
}
ePoint = await _db.Queryable<WmsPointH>().FirstAsync(it => it.location_id == endLocations[0].id);
}
else
{
throw new AppFriendlyException($"库位{endLocations[0].location_code}未在点位表中维护对应点位", 500);
}
string endLocationId = endLocations[0].id;
// 在线开发
//VisualDevEntity? templateEntity = await _visualDevService?.GetInfoById(ModuleConsts.MODULE_WMSDELIVERYPDA_ID, true)!;
//await _runService.Create(templateEntity, input);
// 计算路径,插入预任务申请
if (sPoint != null && ePoint != null)
{
List<WmsPointH> points = new List<WmsPointH>();
if (sPoint.area_code != ePoint.area_code)
{
points = await _wareHouseService.PathAlgorithms(sPoint.id, ePoint.id);
if (points.Count <= 2)
{
throw new AppFriendlyException($"sPoint {sPoint.point_code} ePoint{ePoint.point_code}该路径不存在", 500);
}
}
else
{
points.Add(sPoint);
points.Add(ePoint);
}
WmsCarryH wmsCarryH = await _db.Queryable<WmsCarryH>().FirstAsync(it => it.carry_code == input.carry_code);
//根据获取的路径点生成预任务,生成顺序必须预路径算法返回的起终点的顺序一致(预任务顺序)
if (points?.Count > 0)
{
List<WmsPretaskH> preTasks = points.Where(it => !it.location_id.IsNullOrEmpty()).GroupBy(g => g.area_code).Select(it =>
{
WmsPointH? sPoint = it.FirstOrDefault();
WmsPointH? ePoint = it.LastOrDefault();
WmsPretaskH preTask = new()
{
org_id = _userManager!.User.OrganizeId,
startlocation_id = sPoint?.location_id!,
startlocation_code = sPoint?.location_code!,
endlocation_id = ePoint?.location_id!,
endlocation_code = ePoint?.location_code!,
start_floor = sPoint?.floor.ToString(),
end_floor = ePoint?.floor.ToString(),
startpoint_id = sPoint?.id!,
startpoint_code = sPoint?.point_code!,
endpoint_id = ePoint?.id!,
endpoint_code = ePoint?.point_code!,
bill_code = _billRullService!.GetBillNumber(WmsWareHouseConst.WMS_PRETASK_H_ENCODE).GetAwaiter().GetResult(),
status = WmsWareHouseConst.PRETASK_BILL_STATUS_DXF_ID,
biz_type = WmsWareHouseConst.BIZTYPE_WMSTRANSFERINSTOCK_ID,
task_type = WmsWareHouseConst.WMS_PRETASK_TRANSFER_TYPE_ID
};
preTask.carry_id = wmsCarryH.id;
preTask.carry_code = wmsCarryH.carry_code;
preTask.area_id = sPoint?.area_id!;
preTask.area_code = it.Key;
preTask.require_id = input.source_id;
preTask.require_code = "";
preTask.create_id = _userManager.UserId;
preTask.create_time = DateTime.Now;
return preTask;
}).ToList();
bool isOk = await _wareHouseService.GenPreTask(preTasks, null!, _db);
if (isOk)
{
if (endLocationId != null)
{
//查询库位表
BasLocation location = await _db.Queryable<BasLocation>().SingleAsync(it => it.id == input.startlocation_id);
{
//载具加锁,增加库位信息
_ = await _db.Updateable<WmsCarryH>().SetColumns(it => new WmsCarryH
{
carry_status = ((int)EnumCarryStatus.).ToString(),
is_lock = 1,
location_id = input.startlocation_id,
location_code = location.location_code
}).Where(it => it.id == wmsCarryH.id).ExecuteCommandAsync();
}
//所有库位加锁
string?[] ids = new[] { input.startlocation_id, endLocationId };
_ = await _db.Updateable<BasLocation>().SetColumns(it => new BasLocation { is_lock = 1 }).Where(it => ids.Contains(it.id)).ExecuteCommandAsync();
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().FirstAsync(it => it.id == input.material_id);
if (basMaterial == null)
{
throw new Exception($"找不到物料id为{input.material_id}的物料");
}
BindCarryCodeInput bindCarryCodeInput = new BindCarryCodeInput();
bindCarryCodeInput.carry_id = wmsCarryH.id;
bindCarryCodeInput.barcode = wmsCarryH.carry_code;
bindCarryCodeInput.codeqty = input.qty;
bindCarryCodeInput.material_id = input.material_id;
bindCarryCodeInput.material_code = basMaterial.code;
bindCarryCodeInput.material_name = basMaterial.name;
bindCarryCodeInput.location_id = endLocations[0].id;
bindCarryCodeInput.location_code = endLocations[0].location_code;
bindCarryCodeInput.code_batch = wmsTransferInstockD.pi_code;
bindCarryCodeInput.unit_id = basMaterial.unit_id;
await _wmsCarryService.BindCarryMaterial(bindCarryCodeInput);
}
}
}
}
else
{
throw new AppFriendlyException($"【OutsourcedPartsInstock】点位不存在", 500);
}
// 更新成品调拨入库单子表已下发数量
await _db.Updateable<WmsTransferInstockD>().SetColumns(r => r.xf_qty == r.xf_qty + input.qty).Where(r => r.id == input.source_id).ExecuteCommandAsync();
// 已下发数量达到需求数量回写已完成
wmsTransferInstockD = await _db.Queryable<WmsTransferInstockD>().Where(r => r.id == input.source_id).FirstAsync();
if (wmsTransferInstockD.xf_qty == wmsTransferInstockD.pr_qty)
{
await _db.Updateable<WmsTransferInstockD>().SetColumns(r => r.status == WmsWareHouseConst.TASK_BILL_STATUS_COMPLE_ID).Where(r => r.id == input.source_id).ExecuteCommandAsync();
}
// 入库明细都完成 回写主表完成状态
List<WmsTransferInstockD> wmsTransferInstockDs = _db.Queryable<WmsTransferInstockD>().InnerJoin<WmsTransferInstockD>((a, b) => a.bill_id == b.bill_id).Where((a, b) => a.id == input.source_id)
.Where((a, b) => b.status != WmsWareHouseConst.TASK_BILL_STATUS_COMPLE_ID).ToList();
if (wmsTransferInstockDs.Count == 0)
{
await _db.Updateable<WmsTransferInstockH>().SetColumns(r => r.status == WmsWareHouseConst.TASK_BILL_STATUS_COMPLE_ID).Where(r => r.id == wmsTransferInstockD.bill_id).ExecuteCommandAsync();
}
await _db.Ado.CommitTranAsync();
}
catch (Exception ex)
{
Logger.LogWarning($"外协入库出现异常 {ex.Message}");
Logger.LogWarning($"外协入库出现异常 {ex.StackTrace}");
await _db.Ado.RollbackTranAsync();
return await ToApiResult(HttpStatusCode.InternalServerError, ex.Message);
}
finally
{
semaphoreSlim.Release();
await InvokeGenPretaskExcute();
}
return await ToApiResult(HttpStatusCode.OK, "成功");
}
/// <summary>
/// 盘点签收
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost, NonUnify, AllowAnonymous]
public async Task<Tnb.WarehouseMgr.Entities.Dto.Outputs.Result> FinishproductOutstockSign(FinishproductOutstockSignInput input)
{
Logger.LogInformation($"【FinishproductOutstockSign】载具签收 {input.carry_code}");
if (string.IsNullOrEmpty(input.carry_code))
{
throw new AppFriendlyException("请扫描载具", 500);
}
//if (!_wareHouseService.GetFloor1OutstockLocation().Contains(input.location_id))
//{
// throw new AppFriendlyException("非一楼出库库位不允许通过此功能解锁", 500);
//}
await _db.Ado.BeginTranAsync();
try
{
WmsCarryH wmsCarryH = _db.Queryable<WmsCarryH>().Where(r => r.carry_code == input.carry_code).First();
if (wmsCarryH == null)
{
Logger.Error($"【FinishproductOutstockSign】请扫描正确的载具条码");
throw new AppFriendlyException($"请扫描正确的载具条码", 500);
}
if (string.IsNullOrEmpty(wmsCarryH.location_id))
{
Logger.Error($"【FinishproductOutstockSign】载具 {input.carry_code}没有当前库位 不能签收!可能是重复签收");
throw new AppFriendlyException($"载具 {input.carry_code}没有当前库位 不能签收!可能是重复签收", 500);
}
BasLocation location = _db.Queryable<BasLocation>().Where(r => r.id == wmsCarryH.location_id).First();
if (string.IsNullOrEmpty(location.location_code))
{
Logger.Error($"【FinishproductOutstockSign】库位id {wmsCarryH.location_id}没有对应的库位基础资料!");
throw new AppFriendlyException($"库位id {wmsCarryH.location_id}没有对应的库位基础资料!", 500);
}
WmsDistaskH wmsDistaskH = _db.Queryable<WmsDistaskH>().Where(r => r.carry_code == input.carry_code && r.endlocation_id == location.id
&& r.status != WmsWareHouseConst.TASK_BILL_STATUS_COMPLE_ID && r.status != WmsWareHouseConst.TASK_BILL_STATUS_CANCEL_ID).First();
if (wmsDistaskH != null)
{
Logger.Error($"【FinishproductOutstockSign】载具 {input.carry_code} 库位 {location.location_code}有正在执行的任务,不允许签收!");
throw new AppFriendlyException($"载具 {input.carry_code} 库位 {location.location_code}有正在执行的任务,不允许签收!", 500);
}
await _db.Updateable<BasLocation>().SetColumns(r => new BasLocation
{
is_lock = 0,
is_use = "0"
}).Where(r => r.id == wmsCarryH.location_id).ExecuteCommandAsync();
await _db.Updateable<WmsCarryH>().SetColumns(r => new WmsCarryH
{
location_id = "",
location_code = "",
is_lock = 0,
carry_status = "0"
}).Where(r => r.id == wmsCarryH.id).ExecuteCommandAsync();
await _db.Updateable<WmsPointH>().SetColumns(r => new WmsPointH
{
is_lock = 0
}).Where(r => r.location_id == location.id).ExecuteCommandAsync();
CarryCodeUnbindInput carryCodeUnbindInput = new CarryCodeUnbindInput();
carryCodeUnbindInput.carry_id = wmsCarryH.id;
Tnb.WarehouseMgr.Entities.Dto.Outputs.Result result = await _wmsCarryUnbindService.CarryCodeUnbind(carryCodeUnbindInput, _db);
if (result.code != JNPF.Common.Enums.HttpStatusCode.OK)
{
Logger.Error($"【FinishproductOutstockSign】载具 {input.carry_code}解绑失败!");
throw new AppFriendlyException($"载具 {input.carry_code}解绑失败!", 500);
}
await _db.Ado.CommitTranAsync();
Logger.LogInformation($"【FinishproductOutstockSign】载具签收成功 载具:{input.carry_code} 库位:{location.location_code}");
}
catch (Exception ex)
{
Logger.LogWarning($"【FinishproductOutstockSign】 {ex.Message}");
Logger.LogWarning($"【FinishproductOutstockSign】 {ex.StackTrace}");
await _db.Ado.RollbackTranAsync();
return await ToApiResult(HttpStatusCode.InternalServerError, ex.Message);
}
return await ToApiResult(HttpStatusCode.OK, "成功");
}
/// <summary>
/// 盘点签收(全部签收)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost, NonUnify, AllowAnonymous]
public async Task<Tnb.WarehouseMgr.Entities.Dto.Outputs.Result> FinishproductOutstockSignAll(FinishproductOutstockSignAllInput input)
{
Logger.LogInformation($"【FinishproductOutstockSign】载具签收 {input.region_id}");
if (string.IsNullOrEmpty(input.region_id))
{
throw new AppFriendlyException("请选择区域", 500);
}
try
{
OutStockStrategyQuery outStockStrategyInput = new() { warehouse_id = WmsWareHouseConst.WAREHOUSE_CP_ID, qty = 200, Region_id = WmsWareHouseConst.REGION_CPManualOutstock_ID, filter_carry_status = false };
List<WmsCarryH> items = await _wareHouseService.OutStockStrategy(outStockStrategyInput);
foreach (WmsCarryH wmsCarryH in items)
{
FinishproductOutstockSignInput signInput = new FinishproductOutstockSignInput();
signInput.carry_code = wmsCarryH.carry_code;
Entities.Dto.Outputs.Result result = await FinishproductOutstockSign(signInput);
if (result.code != HttpStatusCode.OK)
{
throw new Exception($@"库位{wmsCarryH.location_code}中的载具{wmsCarryH.carry_code}签收失败! 错误信息:{result.msg}");
}
}
}
catch (Exception ex)
{
Logger.LogWarning($"【FinishproductOutstockSignAll】 {ex.Message}");
Logger.LogWarning($"【FinishproductOutstockSignAll】 {ex.StackTrace}");
return await ToApiResult(HttpStatusCode.InternalServerError, ex.Message);
}
return await ToApiResult(HttpStatusCode.OK, "成功");
}
}
}