Files
tnb.server/ProductionMgr/Tnb.ProductionMgr/TimeWorkService.cs

1664 lines
81 KiB
C#

using System.Diagnostics;
using System.Text.RegularExpressions;
using Aop.Api.Domain;
using JNPF;
using JNPF.Common.Const;
using JNPF.Common.Core.Manager;
using JNPF.Common.Enums;
using JNPF.Common.Extension;
using JNPF.Common.Security;
using JNPF.DataEncryption;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.Extras.CollectiveOAuth.Models;
using JNPF.Extras.CollectiveOAuth.Utils;
using JNPF.FriendlyException;
using JNPF.Logging;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Entitys.System;
using JNPF.Systems.Interfaces.Permission;
using JNPF.Systems.Interfaces.System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SQLitePCL;
using SqlSugar;
using SqlSugar.Extensions;
using Tnb.BasicData.Entities;
using Tnb.Common.Redis;
using Tnb.WarehouseMgr.Interfaces;
using Tnb.WarehouseMgr.Entities.Dto.Inputs;
using Tnb.WarehouseMgr.Entities.Consts;
using Tnb.WarehouseMgr.Entities.Dto.Outputs;
using Result = Tnb.WarehouseMgr.Entities.Dto.Outputs.Result;
using Tnb.BasicData;
using Tnb.EquipMgr.Entities;
using Tnb.WarehouseMgr;
using Tnb.WarehouseMgr.Entities;
using Tnb.ProductionMgr.Entities;
using Tnb.ProductionMgr.Interfaces;
using Tnb.ProductionMgr.Entities.Dto.PrdManage;
using Tnb.ProductionMgr.Entities.Entity;
using Tnb.ProductionMgr.Entities.Entity.ErpEntity;
using Tnb.BasicData.Entities.Dto;
using Tnb.BasicData;
using Tnb.BasicData.Interfaces;
using Tnb.PerMgr.Entities;
namespace Tnb.ProductionMgr
{
[ApiDescriptionSettings(Tag = ModuleConst.Tag, Area = ModuleConst.Area, Order = 700)]
[Route("api/[area]/[controller]/[action]")]
public class TimeWorkService : IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository<BasMaterial> _repository;
private readonly ISqlSugarClient _db;
private readonly IOrganizeService _organizeService;
private readonly IBillRullService _billRullService;
private readonly RedisData _redisData;
private readonly IWmsEmptyOutstockService _wmsEmptyOutstockService;
private readonly IWareHouseService _wareHouseService;
private readonly IPrdMoTaskService _prdMoTaskService;
private readonly IThirdApiRecordService _thirdApiRecordService;
public TimeWorkService(
RedisData redisData,
ISqlSugarRepository<BasMaterial> repository,
IBillRullService billRullService,
IOrganizeService organizeService,
IWmsEmptyOutstockService wmsEmptyOutstockService,
IPrdMoTaskService prdMoTaskService,
IThirdApiRecordService thirdApiRecordService,
IWareHouseService wareHouseService
)
{
_redisData = redisData;
_repository = repository;
_db = repository.AsSugarClient();
_organizeService = organizeService;
_billRullService = billRullService;
_wmsEmptyOutstockService = wmsEmptyOutstockService;
_wareHouseService = wareHouseService;
_thirdApiRecordService = thirdApiRecordService;
_prdMoTaskService = prdMoTaskService;
}
[HttpGet]
[AllowAnonymous]
public async Task<dynamic> test()
{
var db = _repository.AsSugarClient();
await db.Ado.BeginTranAsync();
BasUnit basUnit = new BasUnit();
basUnit.id = SnowflakeIdHelper.NextId();
basUnit.unit_name = "aaa";
basUnit.unit_code = "bbb";
await db.Insertable(basUnit).ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
await db.Ado.BeginTranAsync();
BasUnit basUnit2 = new BasUnit();
basUnit2.id = SnowflakeIdHelper.NextId();
basUnit2.unit_name = "ccc";
basUnit2.unit_code = "ddd";
await db.Insertable(basUnit2).ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
return Task.CompletedTask;
}
/// <summary>
/// 注塑空载具出库
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<string> EmptyCarryOutStk()
{
string state = await _redisData.TryGetValueByKeyField<string>("YTCS", "State");
if ("OK" != state) return "YTCS没开机";
string result = "";
bool? cs01 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "CallCtuEmptyIn_CS01");
bool? cs03 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "CallCtuEmptyIn_CS03");
bool? cs06 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "CallCtuEmptyIn_CS06");
bool? wbzxx1 = await _redisData.TryGetValueByKeyField<bool?>("外包装箱码垛线", "WBZX_x1_AGV_fan");
bool? wbzxx2 = await _redisData.TryGetValueByKeyField<bool?>("外包装箱码垛线", "WBZX_x2_AGV_fan");
// bool cs01Flag = _redisData.Get<bool>("YTCS_CallCtuEmptyIn_CS01_flag");
// bool cs03Flag = _redisData.Get<bool>("YTCS_CallCtuEmptyIn_CS03_flag");
// bool cs06Flag = _redisData.Get<bool>("YTCS_CallCtuEmptyIn_CS06_flag");
List<String> statusList = new List<string>(){WmsWareHouseConst.PRETASK_BILL_STATUS_DXF_ID,WmsWareHouseConst.PRETASK_BILL_STATUS_YXF_ID,WmsWareHouseConst.PRETASK_BILL_STATUS_START_ID};
bool cs01Flag = await _db.Queryable<WmsPretaskH>().AnyAsync(x => x.endlocation_code == "SSX-021-001" && statusList.Contains(x.status) );
bool cs03Flag = await _db.Queryable<WmsPretaskH>().AnyAsync(x => x.endlocation_code == "SSX-021-003" && statusList.Contains(x.status) );
bool cs06Flag = await _db.Queryable<WmsPretaskH>().AnyAsync(x => x.endlocation_code == "SSX-011-006" && statusList.Contains(x.status) );
bool wbzxx1Flag = await _db.Queryable<WmsPretaskH>().AnyAsync(x => x.endlocation_code == "ZZ-01-01" && statusList.Contains(x.status) );
bool wbzxx2Flag = await _db.Queryable<WmsPretaskH>().AnyAsync(x => x.endlocation_code == "ZZ-02-01" && statusList.Contains(x.status) );
Log.Information($"空箱入呼叫cs01值{(cs01==null ? "null" : cs01.ToString())},cs03值{(cs03==null ? "null" : cs03.ToString())},cs06值{(cs06==null ? "null" : cs06.ToString())}");
if (cs01Flag)
{
Log.Information($"【EmptyCarryOutStk】ctu1空箱入呼叫存在未完成的预任务,跳过此次自动呼叫");
}
if (cs03Flag)
{
Log.Information($"【EmptyCarryOutStk】ctu3空箱入呼叫存在未完成的预任务,跳过此次自动呼叫");
}
if (cs06Flag)
{
Log.Information($"【EmptyCarryOutStk】ctu6空箱入呼叫存在未完成的预任务,跳过此次自动呼叫");
}
if (wbzxx1Flag)
{
Log.Information($"【EmptyCarryOutStk】外包装x1空托盘呼叫存在未完成的预任务,跳过此次自动呼叫");
}
if (wbzxx2Flag)
{
Log.Information($"【EmptyCarryOutStk】外包装x2空托盘呼叫存在未完成的预任务,跳过此次自动呼叫");
}
if (cs01==true && !cs01Flag)
{
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
string response = HttpUtils.RequestGet($"{config.value}/api/production/time-work/empty-carry-out-stk-ctu1");
// string response = HttpUtils.RequestGet($"http://localhost:9232/api/production/time-work/empty-carry-out-stk-left");
AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(response);
result += authResponse.data.ToString();
}
if (cs03==true && !cs03Flag)
{
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
string response = HttpUtils.RequestGet($"{config.value}/api/production/time-work/empty-carry-out-stk-ctu3");
// string response = HttpUtils.RequestGet($"http://localhost:9232/api/production/time-work/empty-carry-out-stk-right");
AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(response);
result += authResponse.data.ToString();
}
if (cs06==true && !cs06Flag)
{
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
string response = HttpUtils.RequestGet($"{config.value}/api/production/time-work/empty-carry-out-stk-ctu6");
// string response = HttpUtils.RequestGet($"http://localhost:9232/api/production/time-work/empty-carry-out-stk-right");
AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(response);
result += authResponse.data.ToString();
}
if (wbzxx1==true && !wbzxx1Flag)
{
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
string response = HttpUtils.RequestGet($"{config.value}/api/production/time-work/empty-carry-out-stk-wbzx1");
// string response = HttpUtils.RequestGet($"http://localhost:9232/api/production/time-work/empty-carry-out-stk-right");
AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(response);
result += authResponse.data.ToString();
}
if (wbzxx2==true && !wbzxx2Flag)
{
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
string response = HttpUtils.RequestGet($"{config.value}/api/production/time-work/empty-carry-out-stk-wbzx2");
// string response = HttpUtils.RequestGet($"http://localhost:9232/api/production/time-work/empty-carry-out-stk-right");
AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(response);
result += authResponse.data.ToString();
}
return result;
}
[HttpGet]
[AllowAnonymous]
public async Task<string> EmptyCarryOutStkCtu1()
{
string msg = "";
BasFactoryConfig config = await _db.Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.EmptyCarryOutNum);
MESEmptyCarryOutStkInput input = new MESEmptyCarryOutStkInput();
input.org_id = WmsWareHouseConst.AdministratorOrgId;
input.location_code = "SSX-021-001";
input.warehouse_id = WmsWareHouseConst.WAREHOUSE_ZC_ID;
input.carrystd_id = WmsWareHouseConst.LIAOXIANGID;
input.qty = int.Parse(config?.value ?? "5");
input.create_id = WmsWareHouseConst.AdministratorUserId;
Log.Information($"【EmptyCarryOutStk】ctu1空箱入呼叫开始,参数:{JsonConvert.SerializeObject(input)}");
Result result = await _wmsEmptyOutstockService.MESEmptyCarryOutStk(input);
if (result.code == HttpStatusCode.OK)
{
msg = "ctu1空箱入呼叫成功";
Log.Information("【EmptyCarryOutStk】ctu1空箱入呼叫成功");
//_redisData.Set("YTCS_CallCtuEmptyIn_CS01_flag", true, TimeSpan.FromMinutes(20));
}
else
{
msg = $"ctu1空箱入呼叫失败:{result.msg}";
Log.Error($"【EmptyCarryOutStk】ctu1空箱入呼叫失败:{result.msg}");
}
return msg;
}
[HttpGet]
[AllowAnonymous]
public async Task<string> EmptyCarryOutStkCtu3()
{
string msg = "";
BasFactoryConfig config = await _db.Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.EmptyCarryOutNum);
MESEmptyCarryOutStkInput input = new MESEmptyCarryOutStkInput();
input.org_id = WmsWareHouseConst.AdministratorOrgId;
input.location_code = "SSX-021-003";
input.warehouse_id = WmsWareHouseConst.WAREHOUSE_ZC_ID;
input.carrystd_id = WmsWareHouseConst.LIAOXIANGID;
input.qty = int.Parse(config?.value ?? "5");
input.create_id = WmsWareHouseConst.AdministratorUserId;
Log.Information($"【EmptyCarryOutStk】ctu3空箱入呼叫开始,参数:{JsonConvert.SerializeObject(input)}");
Result result = await _wmsEmptyOutstockService.MESEmptyCarryOutStk(input);
if (result.code == HttpStatusCode.OK)
{
msg = "ctu3空箱入呼叫成功";
Log.Information("【EmptyCarryOutStk】ctu3空箱入呼叫成功");
//_redisData.Set("YTCS_CallCtuEmptyIn_CS03_flag", true, TimeSpan.FromMinutes(20));
}
else
{
msg = $"ctu3空箱入呼叫失败:{result.msg}";
Log.Error($"【EmptyCarryOutStk】ctu3空箱入呼叫失败:{result.msg}");
}
return msg;
}
[HttpGet]
[AllowAnonymous]
public async Task<string> EmptyCarryOutStkCtu6()
{
string msg = "";
BasFactoryConfig config = await _db.Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.EmptyCarryOutNum);
MESEmptyCarryOutStkInput input = new MESEmptyCarryOutStkInput();
input.org_id = WmsWareHouseConst.AdministratorOrgId;
input.location_code = "SSX-011-006";
input.warehouse_id = WmsWareHouseConst.WAREHOUSE_ZC_ID;
input.carrystd_id = WmsWareHouseConst.LIAOXIANGID;
input.qty = int.Parse(config?.value ?? "5");
input.create_id = WmsWareHouseConst.AdministratorUserId;
Log.Information($"【EmptyCarryOutStk】ctu6空箱入呼叫开始,参数:{JsonConvert.SerializeObject(input)}");
Result result = await _wmsEmptyOutstockService.MESEmptyCarryOutStk(input);
if (result.code == HttpStatusCode.OK)
{
msg = "ctu6空箱入呼叫成功";
Log.Information("【EmptyCarryOutStk】ctu6空箱入呼叫成功");
//_redisData.Set("YTCS_CallCtuEmptyIn_CS06_flag", true, TimeSpan.FromMinutes(20));
}
else
{
msg = $"ctu6空箱入呼叫失败:{result.msg}";
Log.Error($"【EmptyCarryOutStk】ctu6空箱入呼叫失败:{result.msg}");
}
return msg;
}
[HttpGet]
[AllowAnonymous]
public async Task<string> EmptyCarryOutStkWbzx1()
{
string msg = "";
MESEmptyCarryOutStkInput input = new MESEmptyCarryOutStkInput();
input.org_id = WmsWareHouseConst.AdministratorOrgId;
input.location_code = "ZZ-01-01";
input.warehouse_id = WmsWareHouseConst.WAREHOUSE_F2KTQ_ID;
input.carrystd_id = WmsWareHouseConst.CARRY_TP_ID;
input.qty = 1;
input.create_id = WmsWareHouseConst.AdministratorUserId;
Log.Information($"【EmptyCarryOutStk】外包装x1空托盘呼叫开始,参数:{JsonConvert.SerializeObject(input)}");
Result result = await _wmsEmptyOutstockService.MESEmptyCarryOutStk(input);
if (result.code == HttpStatusCode.OK)
{
msg = "外包装x1空托盘呼叫成功";
Log.Information("【EmptyCarryOutStk】外包装x1空托盘呼叫成功");
//_redisData.Set("YTCS_CallCtuEmptyIn_CS06_flag", true, TimeSpan.FromMinutes(20));
}
else
{
msg = $"外包装x1空托盘呼叫失败:{result.msg}";
Log.Error($"【EmptyCarryOutStk】外包装x1空托盘呼叫失败:{result.msg}");
}
return msg;
}
[HttpGet]
[AllowAnonymous]
public async Task<string> EmptyCarryOutStkWbzx2()
{
string msg = "";
MESEmptyCarryOutStkInput input = new MESEmptyCarryOutStkInput();
input.org_id = WmsWareHouseConst.AdministratorOrgId;
input.location_code = "ZZ-02-01";
input.warehouse_id = WmsWareHouseConst.WAREHOUSE_F2KTQ_ID;
input.carrystd_id = WmsWareHouseConst.CARRY_TP_ID;
input.qty = 1;
input.create_id = WmsWareHouseConst.AdministratorUserId;
Log.Information($"【EmptyCarryOutStk】外包装x2空托盘呼叫开始,参数:{JsonConvert.SerializeObject(input)}");
Result result = await _wmsEmptyOutstockService.MESEmptyCarryOutStk(input);
if (result.code == HttpStatusCode.OK)
{
msg = "外包装x2空托盘呼叫成功";
Log.Information("【EmptyCarryOutStk】外包装x2空托盘呼叫成功");
//_redisData.Set("YTCS_CallCtuEmptyIn_CS06_flag", true, TimeSpan.FromMinutes(20));
}
else
{
msg = $"外包装x2空托盘呼叫失败:{result.msg}";
Log.Error($"【EmptyCarryOutStk】外包装x2空托盘呼叫失败:{result.msg}");
}
return msg;
}
// [HttpGet]
// [AllowAnonymous]
// public async Task<string> FixedPointDelivery()
// {
// string state = await _redisData.TryGetValueByKeyField<string>("YTCS", "State");
// if ("OK" != state)
// {
// Log.Error($"TCS没开机");
// return "YTCS没开机";
// }
// string stateHxja = await _redisData.TryGetValueByKeyField<string>("hxjA", "State");
// string stateHxjc = await _redisData.TryGetValueByKeyField<string>("hxjC", "State");
// List<String> hxjList = new List<string>();
// if ("OK" == stateHxja)
// {
// hxjList.Add("hxjA");
// }
// if ("OK" == stateHxjc)
// {
// hxjList.Add("hxjC");
// }
//
// if (hxjList.IsEmpty())
// {
// Log.Error($"hxjA,hxjC不正常");
// return "hxjA,hxjC不正常";
// }
// string msg = "";
// List<EqpEquipment> equipments = await _db.Queryable<EqpEquipType>()
// .InnerJoin<EqpEquipment>((x, y) => x.id == y.equip_type_id)
// .Where((x, y) => x.code == "ZSJ")
// .Select((x, y) => y).ToListAsync();
//
// int? cs01Count = await _redisData.TryGetValueByKeyField<int?>("YTCS", "EmptyNo_CS01");
// int? cs03Count = await _redisData.TryGetValueByKeyField<int?>("YTCS", "EmptyNo_CS03");
//
// List<String> eqpIds = equipments.Select(x => x.id).ToList();
// List<EqpDaq> eqpDaqs = await _db.Queryable<EqpDaq>().Where(x => eqpIds.Contains(x.equip_id) && x.label_name.Contains("允许入空箱")).ToListAsync();
// //BasFactoryConfig config = await _db.Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
// foreach (var equipment in equipments)
// {
// EqpDaq eqpDaq = eqpDaqs.FirstOrDefault(x => x.equip_id==equipment.id);
// if (eqpDaq == null)
// {
// Log.Error($"{equipment.name}没配置允许入空箱");
// continue;
// }
// if (!hxjList.Contains(eqpDaq.equip_code))
// {
// Log.Error($"{eqpDaq.equip_code}状态不正常");
// continue;
// }
// if (string.IsNullOrEmpty(equipment.upmat_location_id))
// {
// Log.Error($"{equipment.name}未配置上料库位");
// continue;
// }
// if (await _db.Queryable<WmsPretaskH>().AnyAsync(x =>
// x.endlocation_id == equipment.upmat_location_id &&
// x.biz_type == WmsWareHouseConst.BIZTYPE_WMSDELIVERY_ID &&
// (x.status == WmsWareHouseConst.PRETASK_BILL_STATUS_DXF_ID
// || x.status == WmsWareHouseConst.PRETASK_BILL_STATUS_YXF_ID
// || x.status == WmsWareHouseConst.PRETASK_BILL_STATUS_START_ID
// )
// ))
// {
// Log.Error($"{equipment.name}存在未完成的任务");
// continue;
// }
// bool? value = await _redisData.TryGetValueByKeyField<bool?>(eqpDaq.equip_code, eqpDaq.label_name);
// bool valueFlag = _redisData.Get<bool>($"{eqpDaq.equip_code}_{eqpDaq.label_name}_flag");
// Log.Information($"机台号{eqpDaq.equip_code},标签名{eqpDaq.label_name}redis的值为{value.ToString()}");
//
// if (value==true && !valueFlag)
// {
// bool? cs01 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "AllowAgvEmptyOut_CS01");
// bool? cs03 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "AllowAgvEmptyOut_CS03");
// string startLocationCode = cs01==true ? "ZSSSXCTU01" : cs03==true ? "ZSSSXCTU02" : "";
// if (cs01==true && cs03==true)
// {
// string last_fixed_point_delivery = _redisData.Exists("last_fixed_point_delivery") ? _redisData.Get<string>("last_fixed_point_delivery") : "";
// if (string.IsNullOrEmpty(last_fixed_point_delivery))
// {
// startLocationCode = "ZSSSXCTU01";
// }
// else
// {
// startLocationCode = "ZSSSXCTU01ZSSSXCTU02".Replace(last_fixed_point_delivery, "");
// }
// }
// if (startLocationCode.IsEmpty())
// {
// Log.Error($"输送线无空载具");
// return "输送线无空载具";
// }
//
// BasLocation startLocation = await _db.Queryable<BasLocation>().Where(x=>x.location_code==startLocationCode).FirstAsync();
// CommonCreatePretaskInput postData = new CommonCreatePretaskInput();
// postData.startlocation_id = startLocation.id;
// postData.endlocation_id = equipment.upmat_location_id;
// postData.biz_type = WmsWareHouseConst.BIZTYPE_WMSDELIVERY_ID;
// postData.task_type = WmsWareHouseConst.WMS_PRETASK_OUTSTOCK_TYPE_ID;
// Log.Information($"【FixedPointDelivery】注塑定点配送,参数:{JsonConvert.SerializeObject(postData)}");
// Result result = await _wareHouseService.CommonCreatePretask(postData);
// // string sendResult = HttpUtils.RequestPost($"{config.value}/api/wms/ware-house/common-create-pretask", JsonConvert.SerializeObject(postData), null);
// // string sendResult = HttpUtils.RequestPost($"http://localhost:9232/api/wms/ware-house/common-create-pretask", JsonConvert.SerializeObject(postData), null);
// // AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(sendResult);
// if(result.code == HttpStatusCode.OK)
// {
// msg += $"{equipment.name}注塑定点配送成功,";
// Log.Information($"【FixedPointDelivery】{equipment.name}注塑定点配送成功");
// _redisData.Set($"{eqpDaq.equip_code}_{eqpDaq.label_name}_flag", true, TimeSpan.FromMinutes(20));
// _redisData.Set($"last_fixed_point_delivery", startLocationCode);
// }
// else
// {
// msg += $"{equipment.name}注塑定点配送失败:{result.msg},";
// Log.Error($"【FixedPointDelivery】{equipment.name}注塑定点配送失败:{result.msg}");
// }
//
// }
// }
//
// return msg;
// }
/// <summary>
/// 定点配送
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<string> FixedPointDelivery()
{
string state = await _redisData.TryGetValueByKeyField<string>("YTCS", "State");
if ("OK" != state)
{
Log.Error($"TCS没开机");
return "YTCS没开机";
}
string stateHxja = await _redisData.TryGetValueByKeyField<string>("hxjA", "State");
string stateHxjc = await _redisData.TryGetValueByKeyField<string>("hxjC", "State");
List<String> hxjList = new List<string>();
if ("OK" == stateHxja)
{
hxjList.Add("hxjA");
}
if ("OK" == stateHxjc)
{
hxjList.Add("hxjC");
}
if (hxjList.IsEmpty())
{
Log.Error($"hxjA,hxjC不正常");
return "hxjA,hxjC不正常";
}
string msg = "";
List<EqpEquipment> equipments = await _db.Queryable<EqpEquipType>()
.InnerJoin<EqpEquipment>((x, y) => x.id == y.equip_type_id)
.Where((x, y) => x.code == "ZSJ")
.Select((x, y) => y).ToListAsync();
int cs01Count = await _redisData.TryGetValueByKeyField<int>("YTCS", "EmptyNo_CS01");
int cs03Count = await _redisData.TryGetValueByKeyField<int>("YTCS", "EmptyNo_CS03");
Log.Information($"注塑定点配送cs01数量:{cs01Count},cs03数量:{cs03Count}");
List<String> eqpIds = equipments.Select(x => x.id).ToList();
List<EqpDaq> eqpDaqs = await _db.Queryable<EqpDaq>().Where(x => eqpIds.Contains(x.equip_id) && x.label_name.Contains("允许入空箱")).ToListAsync();
//BasFactoryConfig config = await _db.Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
foreach (var equipment in equipments)
{
EqpDaq eqpDaq = eqpDaqs.FirstOrDefault(x => x.equip_id==equipment.id);
if (eqpDaq == null)
{
Log.Error($"{equipment.name}没配置允许入空箱");
continue;
}
if (!hxjList.Contains(eqpDaq.equip_code))
{
Log.Error($"{eqpDaq.equip_code}状态不正常");
continue;
}
if (string.IsNullOrEmpty(equipment.upmat_location_id))
{
Log.Error($"{equipment.name}未配置上料库位");
continue;
}
if (await _db.Queryable<WmsPretaskH>().AnyAsync(x =>
x.endlocation_id == equipment.upmat_location_id &&
x.biz_type == WmsWareHouseConst.BIZTYPE_WMSDELIVERY_ID &&
(x.status == WmsWareHouseConst.PRETASK_BILL_STATUS_DXF_ID
|| x.status == WmsWareHouseConst.PRETASK_BILL_STATUS_YXF_ID
|| x.status == WmsWareHouseConst.PRETASK_BILL_STATUS_START_ID
)
))
{
Log.Error($"{equipment.name}存在未完成的任务");
continue;
}
bool? value = await _redisData.TryGetValueByKeyField<bool?>(eqpDaq.equip_code, eqpDaq.label_name);
bool valueFlag = _redisData.Get<bool>($"{eqpDaq.equip_code}_{eqpDaq.label_name}_flag");
Log.Information($"机台号{eqpDaq.equip_code},标签名{eqpDaq.label_name}redis的值为{value.ToString()}");
if (value==true && !valueFlag)
{
bool? cs01 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "AllowAgvEmptyOut_CS01");
bool? cs03 = await _redisData.TryGetValueByKeyField<bool?>("YTCS", "AllowAgvEmptyOut_CS03");
string startLocationCode = "";
if (cs01==true && cs03==true && cs01Count>0 && cs03Count>0)
{
string last_fixed_point_delivery = _redisData.Exists("last_fixed_point_delivery") ? _redisData.Get<string>("last_fixed_point_delivery") : "";
if (string.IsNullOrEmpty(last_fixed_point_delivery))
{
startLocationCode = "ZSSSXCTU01";
}
else
{
startLocationCode = "ZSSSXCTU01ZSSSXCTU02".Replace(last_fixed_point_delivery, "");
}
if (startLocationCode == "ZSSSXCTU01")
{
cs01Count--;
}
if (startLocationCode == "ZSSSXCTU02")
{
cs03Count--;
}
}
else
{
if (cs01==true && cs01Count > 0)
{
startLocationCode = "ZSSSXCTU01";
cs01Count--;
}else if (cs03==true && cs03Count > 0)
{
startLocationCode = "ZSSSXCTU02";
cs03Count--;
}
}
if (startLocationCode.IsEmpty())
{
Log.Error($"输送线无空载具");
return "输送线无空载具";
}
BasLocation startLocation = await _db.Queryable<BasLocation>().Where(x=>x.location_code==startLocationCode).FirstAsync();
CommonCreatePretaskInput postData = new CommonCreatePretaskInput();
postData.startlocation_id = startLocation.id;
postData.endlocation_id = equipment.upmat_location_id;
postData.biz_type = WmsWareHouseConst.BIZTYPE_WMSDELIVERY_ID;
postData.task_type = WmsWareHouseConst.WMS_PRETASK_OUTSTOCK_TYPE_ID;
Log.Information($"【FixedPointDelivery】注塑定点配送,参数:{JsonConvert.SerializeObject(postData)}");
Result result = await _wareHouseService.CommonCreatePretask(postData);
// string sendResult = HttpUtils.RequestPost($"{config.value}/api/wms/ware-house/common-create-pretask", JsonConvert.SerializeObject(postData), null);
// string sendResult = HttpUtils.RequestPost($"http://localhost:9232/api/wms/ware-house/common-create-pretask", JsonConvert.SerializeObject(postData), null);
// AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(sendResult);
if(result.code == HttpStatusCode.OK)
{
msg += $"{equipment.name}注塑定点配送成功,";
Log.Information($"【FixedPointDelivery】{equipment.name}注塑定点配送成功");
_redisData.Set($"{eqpDaq.equip_code}_{eqpDaq.label_name}_flag", true, TimeSpan.FromMinutes(20));
_redisData.Set($"last_fixed_point_delivery", startLocationCode);
}
else
{
msg += $"{equipment.name}注塑定点配送失败:{result.msg},";
Log.Error($"【FixedPointDelivery】{equipment.name}注塑定点配送失败:{result.msg}");
}
}
}
return msg;
}
/// <summary>
/// 自动提报
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> AutoPrdReport()
{
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
bool qu1 = await _redisData.TryGetValueByKeyField<bool>("外包装箱码垛线", "WBZX_x1_AGV_qu");
if (qu1)
{
Log.Information("血路管1线取");
HttpUtils.RequestGet($"{config.value}/api/production/time-work/x1-auto-prd-report");
}
bool qu2 = await _redisData.TryGetValueByKeyField<bool>("外包装箱码垛线", "WBZX_x2_AGV_qu");
if (qu2)
{
Log.Information("血路管2线取");
HttpUtils.RequestGet($"{config.value}/api/production/time-work/x2-auto-prd-report");
}
return "true";
}
[HttpGet]
[AllowAnonymous]
public async Task<string> X1AutoPrdReport()
{
string carryCode = await _redisData.TryGetValueByKeyField<string>("外包装箱码垛线", "WBZX_x1_take_tp");
int num = await _redisData.TryGetValueByKeyField<int>("外包装箱码垛线", "WBZX_x1_Enquantity");
if (string.IsNullOrEmpty(carryCode) || num<=0)
{
Log.Information("血路管1线无载具或数量为0");
return "无载具或数量为0";
}
PrdMoTask prdMoTask = await _db.Queryable<PrdMoTask>().Where(x => x.workline_id == WmsWareHouseConst.XUELUGUAN1XIAN && x.mo_task_status == DictConst.InProgressEnCode && x.parent_id != null).FirstAsync();
if (prdMoTask == null)
{
Log.Information("血路管1线没有进行中的任务单");
return "血路管1线没有进行中的任务单";
}
PrdReportCrInput input = new PrdReportCrInput();
input.mo_task_code = prdMoTask.mo_task_code;
input.mo_task_id = prdMoTask.id;
input.reported_qty = num;
input.station = "";
input.material_box_code = carryCode;
return await _prdMoTaskService.PrdReport(input);
}
[HttpGet]
[AllowAnonymous]
public async Task<string> X2AutoPrdReport()
{
string carryCode = await _redisData.TryGetValueByKeyField<string>("外包装箱码垛线", "WBZX_x2_take_tp");
int num = await _redisData.TryGetValueByKeyField<int>("外包装箱码垛线", "WBZX_x2_Enquantity");
if (string.IsNullOrEmpty(carryCode) || num<=0)
{
Log.Information("血路管2线无载具或数量为0");
return "无载具或数量为0";
}
PrdMoTask prdMoTask = await _db.Queryable<PrdMoTask>().Where(x => x.workline_id == WmsWareHouseConst.XUELUGUAN2XIAN && x.mo_task_status == DictConst.InProgressEnCode && x.parent_id != null).FirstAsync();
if (prdMoTask == null)
{
Log.Information("血路管2线没有进行中的任务单");
return "血路管2线没有进行中的任务单";
}
PrdReportCrInput input = new PrdReportCrInput();
input.mo_task_code = prdMoTask.mo_task_code;
input.mo_task_id = prdMoTask.id;
input.reported_qty = num;
input.station = "";
input.material_box_code = carryCode;
await _prdMoTaskService.PrdReport(input);
return await _prdMoTaskService.PrdReport(input);
}
[HttpGet]
[AllowAnonymous]
public async Task<string> SendThirdApi(string thirdNmaes)
{
string[] thirdNameArr = thirdNmaes.Split("-");
List<ThirdWebapiRecord> records = await _db.Queryable<ThirdWebapiRecord>().Where(x => thirdNameArr.Contains(x.third_name) && x.status == "0" && x.is_send == 1 && x.error_count<10).ToListAsync();
if (records.IsEmpty())
{
records = await _db.Queryable<ThirdWebapiRecord>().Where(x => thirdNameArr.Contains(x.third_name) && x.status == "0" && x.is_send == 1 && x.error_count<100).ToListAsync();
}
if (records.IsEmpty()) return "";
await _thirdApiRecordService.Send(records, "自动");
return "true";
}
/// <summary>
/// 同步基础数据
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncBaseData()
{
string result = "";
BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
try
{
string response1 = HttpUtils.RequestGet($"{config.value}/api/production/time-work/sync-unit");
AuthResponse authResponse1 = JsonConvert.DeserializeObject<AuthResponse>(response1);
result += authResponse1.data.ToString();
}
catch (Exception e)
{
Log.Error(e.Message,e);
result += e.Message;
}
// try
// {
// string response2 = HttpUtils.RequestGet($"{config.value}/api/production/time-work/sync-material",null,10*60*1000);
// AuthResponse authResponse2 = JsonConvert.DeserializeObject<AuthResponse>(response2);
// result += ","+authResponse2.data.ToString();
// }
// catch (Exception e)
// {
// Log.Error(e.Message,e);
// result += e.Message;
// }
try
{
string response3 = HttpUtils.RequestGet($"{config.value}/api/production/time-work/sync-customer");
AuthResponse authResponse3 = JsonConvert.DeserializeObject<AuthResponse>(response3);
result += ","+authResponse3.data.ToString();
}
catch (Exception e)
{
Log.Error(e.Message,e);
result += e.Message;
}
try
{
string response4 = HttpUtils.RequestGet($"{config.value}/api/production/time-work/sync-supplier");
AuthResponse authResponse4 = JsonConvert.DeserializeObject<AuthResponse>(response4);
result += ","+authResponse4.data.ToString();
}
catch (Exception e)
{
Log.Error(e.Message,e);
result += e.Message;
}
try
{
string response5 = HttpUtils.RequestGet($"{config.value}/api/production/time-work/sync-user");
AuthResponse authResponse5 = JsonConvert.DeserializeObject<AuthResponse>(response5);
result += ","+authResponse5.data.ToString();
}
catch (Exception e)
{
Log.Error(e.Message,e);
result += e.Message;
}
try
{
string response6 = HttpUtils.RequestGet($"{config.value}/api/production/time-work/sync-dept");
AuthResponse authResponse6 = JsonConvert.DeserializeObject<AuthResponse>(response6);
result += ","+authResponse6.data.ToString();
}
catch (Exception e)
{
Log.Error(e.Message,e);
result += e.Message;
}
Log.Information($"基础数据同步结果:{result}");
BasSyncRecord basSyncRecord = new BasSyncRecord()
{
msg = result,
create_time = DateTime.Now
};
await _db.Insertable(basSyncRecord).ExecuteCommandAsync();
return result;
}
/// <summary>
/// 同步物料
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncMaterial()
{
string msg = "";
try
{
int editCount = 0;
string[] tables = new[] { "base_dictionarydata", "bas_material" };
var erpdb = _db.AsTenant().GetConnection("erpdb");
List<ErpBdMaterial> list = await erpdb.Queryable<ErpBdMaterial>().ToListAsync();
List<BomList> bomList = await erpdb.Queryable<BomList>().ToListAsync();
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>()
.Where(x => tables.Contains(x.table_name)).ToListAsync();
Dictionary<string, object> unitDic = await _db.Queryable<DictionaryDataEntity>()
.Where(x => x.DictionaryTypeId == WmsWareHouseConst.UNITTYPEID)
.ToDictionaryAsync(x => x.Id, y => y.EnCode);
Dictionary<string, object> unitDic2 = await _db.Queryable<DictionaryDataEntity>()
.Where(x => x.DictionaryTypeId == WmsWareHouseConst.UNITTYPEID)
.ToDictionaryAsync(x => x.FullName, y => y.EnCode);
Dictionary<string, object> materialcategoryDic = await _db.Queryable<DictionaryDataEntity>()
.Where(x => x.DictionaryTypeId == DictConst.MaterialCatagoryID)
.ToDictionaryAsync(x => x.FullName, y => y.EnCode);
List<BasMaterial> materials = await _db.Queryable<BasMaterial>().ToListAsync();
List<BasEbomH> basEbomHs = await _db.Queryable<BasEbomH>().ToListAsync();
List<BasMaterial> insertMaterial = new List<BasMaterial>();
List<BasMaterialUnit> insertMaterialUnits = new List<BasMaterialUnit>();
List<BasEbomH> insertBasEbomHs = new List<BasEbomH>();
List<BasEbomD> insertBasEbomDs = new List<BasEbomD>();
List<ErpExtendField> insertExtendFields = new List<ErpExtendField>();
await _db.Ado.BeginTranAsync();
foreach (ErpBdMaterial erpBdMaterial in list)
{
string categoryId = "[\"CGJCJ\"]";
if (erpBdMaterial.CODE.StartsWith("0401"))
{
string str = "";
if (erpBdMaterial.MATERIALSPEC!=null && erpBdMaterial.MATERIALSPEC.Contains("*"))
{
str = erpBdMaterial.MATERIALSPEC;
}else if (erpBdMaterial.NAME!=null && erpBdMaterial.NAME.Contains("*"))
{
str = erpBdMaterial.NAME;
}
if (!string.IsNullOrEmpty(str))
{
MatchCollection mts = Regex.Matches(str, @"[0-9]|[\*]|[\.]");
string tempStr = string.Join(String.Empty, mts.Select(x => x.Value).ToList());
string[] strArr = tempStr.Split("*");
if (strArr.Length <= 2)
{
categoryId = "[\"CGJCJ\"]";
}else if (decimal.Parse(strArr[2]) > 500)
{
categoryId = "[\"CGJCJ\"]";
}
else
{
categoryId = "[\"DGJCJ\"]";
}
}
}
else
{
categoryId = !string.IsNullOrEmpty(erpBdMaterial.DEFNAME) && materialcategoryDic.ContainsKey(erpBdMaterial.DEFNAME) ? $"[\"{materialcategoryDic[erpBdMaterial.DEFNAME]}\"]" : "";
}
if (erpExtendFields.All(x => x.cmaterialoid != erpBdMaterial.ID))
{
string unitId = erpExtendFields.Find(x => x.cunitid == erpBdMaterial.PK_MEASDOC)?.table_id ?? "";
unitId = unitDic.ContainsKey(unitId) ? unitDic[unitId].ToString() : "";
string auxiliaryUnitId = erpExtendFields.Find(x => x.cunitid == erpBdMaterial.FMEASDOC)?.table_id ?? "";
auxiliaryUnitId = unitDic.ContainsKey(auxiliaryUnitId) ? unitDic[auxiliaryUnitId].ToString() : "";
string[] unitArr = erpBdMaterial.MEASRATE.Split("/");
BasMaterial basMaterial = null;
ErpExtendField tempExtendField = insertExtendFields.Find(x => x.cmaterialoid == erpBdMaterial.ID);
if (tempExtendField!=null)
{
basMaterial = insertMaterial.Find(x => x.id == tempExtendField.table_id);
}
else
{
basMaterial = new BasMaterial()
{
id = SnowflakeIdHelper.NextId(),
name = erpBdMaterial.NAME,
code = erpBdMaterial.CODE,
org_id = WmsWareHouseConst.AdministratorOrgId,
material_specification = erpBdMaterial.MATERIALSPEC,
material_standard = erpBdMaterial.MATERIALTYPE,
category_id = categoryId,
unit_id = unitId,
state = "1",
di = erpBdMaterial.UDI,
create_time = DateTime.Now
};
insertMaterial.Add(basMaterial);
ErpExtendField erpExtendField = new ErpExtendField()
{
table_name = "bas_material",
table_id = basMaterial.id,
cmaterialoid = erpBdMaterial.ID,
cmaterialvid = erpBdMaterial.VID,
};
insertExtendFields.Add(erpExtendField);
}
if (unitId != auxiliaryUnitId)
{
insertMaterialUnits.Add(new BasMaterialUnit()
{
id = SnowflakeIdHelper.NextId(),
material_id = basMaterial.id,
number_of_primary_unit = unitArr[0],
number_of_auxiliary_unit = unitArr[1],
auxiliary_unit_id = auxiliaryUnitId
});
}
}
else
{
ErpExtendField extendField = erpExtendFields.Find(x => x.cmaterialoid == erpBdMaterial.ID);
string materialId = extendField?.table_id ?? "";
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().SingleAsync(x => x.id == materialId);
// if (extendField.erp_modify_time==null || erpBdMaterial.MODIFIEDTIME != extendField.erp_modify_time)
if (erpBdMaterial.MODIFIEDTIME != extendField.erp_modify_time)
{
string unitId = erpExtendFields.Find(x => x.cunitid == erpBdMaterial.PK_MEASDOC)?.table_id ?? "";
unitId = unitDic.ContainsKey(unitId) ? unitDic[unitId].ToString() : "";
string auxiliaryUnitId = erpExtendFields.Find(x => x.cunitid == erpBdMaterial.FMEASDOC)?.table_id ?? "";
auxiliaryUnitId = unitDic.ContainsKey(auxiliaryUnitId) ? unitDic[auxiliaryUnitId].ToString() : "";
string[] unitArr = erpBdMaterial.MEASRATE.Split("/");
int updateRow = await _db.Updateable<BasMaterial>()
.SetColumns(x => x.name == erpBdMaterial.NAME)
.SetColumns(x => x.code == erpBdMaterial.CODE)
.SetColumnsIF(!string.IsNullOrEmpty(categoryId),x=>x.category_id == categoryId)
.SetColumns(x => x.material_specification == erpBdMaterial.MATERIALSPEC)
.SetColumns(x => x.material_standard == erpBdMaterial.MATERIALTYPE)
.SetColumns(x => x.unit_id == unitId)
.SetColumns(x => x.name == erpBdMaterial.NAME)
.SetColumns(x => x.di == erpBdMaterial.UDI)
.Where(x => x.id == materialId)
.ExecuteCommandAsync();
await _db.Updateable<ErpExtendField>()
.SetColumns(x => x.erp_modify_time == erpBdMaterial.MODIFIEDTIME)
.Where(x => x.table_id == extendField.table_id)
.ExecuteCommandAsync();
editCount += updateRow;
if (updateRow <= 0)
{
Log.Error($"未找到物料{erpBdMaterial.ID},跳过此条数据");
continue;
}
BasMaterialUnit basMaterialUnit = await _db.Queryable<BasMaterialUnit>()
.Where(x => x.material_id == materialId && x.auxiliary_unit_id == auxiliaryUnitId)
.FirstAsync();
if (basMaterialUnit == null)
{
if (unitId != auxiliaryUnitId)
{
insertMaterialUnits.Add(new BasMaterialUnit()
{
id = SnowflakeIdHelper.NextId(),
material_id = materialId,
number_of_primary_unit = unitArr[0],
number_of_auxiliary_unit = unitArr[1],
auxiliary_unit_id = auxiliaryUnitId
});
}
}
else
{
if (unitId != auxiliaryUnitId)
{
await _db.Updateable<BasMaterialUnit>()
.SetColumns(x => x.number_of_primary_unit == unitArr[0])
.SetColumns(x => x.number_of_auxiliary_unit == unitArr[1])
.Where(x => x.id == basMaterialUnit.id)
.ExecuteCommandAsync();
}
}
}
}
}
await _db.Insertable(insertMaterial).ExecuteCommandAsync();
await _db.Insertable(insertMaterialUnits).ExecuteCommandAsync();
await _db.Insertable(insertExtendFields).ExecuteCommandAsync();
//物料清单开始同步
materials = await _db.Queryable<BasMaterial>().ToListAsync();
var groupList = bomList.GroupBy(x => x.BOMID);
foreach (var item in groupList)
{
string key = item.Key;
List<BomList> itemList = item.ToList();
BomList firstItemInList = itemList[0];
BasMaterial material = materials.Find(x => x.code==firstItemInList.MPRODID);
if (material == null) continue;
string unitId = unitDic2.ContainsKey(firstItemInList.UNIT) ? unitDic2[firstItemInList.UNIT].ToString() : "";
if (basEbomHs.FindIndex(x => x.material_id == material.id && x.version == firstItemInList.HVERSION)==-1)
{
BasEbomH basEbomH = new BasEbomH()
{
id = SnowflakeIdHelper.NextId(),
org_id = WmsWareHouseConst.AdministratorOrgId,
material_id = material.id,
unit_id = unitId,
version = firstItemInList.HVERSION,
create_time = DateTime.Now,
};
bool flag = false;
List<BasEbomD> tempList = new List<BasEbomD>();
foreach (var children in itemList)
{
BasMaterial childrenMaterial = materials.Find(x => x.code==children.SUBPRODID);
if (childrenMaterial == null)
{
flag = true;
tempList = new List<BasEbomD>();
break;
}
BasEbomD basEbomD = new BasEbomD()
{
id = SnowflakeIdHelper.NextId(),
ebom_id = basEbomH.id,
material_id = childrenMaterial.id,
denominator = children.DISHU,
molecule = children.BATCHAMOUNT,
};
tempList.Add(basEbomD);
}
if (flag)
{
continue;
}
insertBasEbomHs.Add(basEbomH);
insertBasEbomDs.AddRange(tempList);
}
else
{
BasEbomH basEbomH = await _db.Queryable<BasEbomH>().Where(x=>x.material_id==material.id && x.version==firstItemInList.HVERSION).FirstAsync();
if (basEbomH == null) continue;
if (basEbomH.erp_modify_time != firstItemInList.MODIFIEDTIME)
{
bool flag = false;
List<BasEbomD> tempList = new List<BasEbomD>();
foreach (var children in itemList)
{
BasMaterial childrenMaterial = materials.Find(x => x.code==children.SUBPRODID);
if (childrenMaterial == null)
{
flag = true;
tempList = new List<BasEbomD>();
break;
}
BasEbomD basEbomD = new BasEbomD()
{
id = SnowflakeIdHelper.NextId(),
ebom_id = basEbomH.id,
material_id = childrenMaterial.id,
denominator = children.DISHU,
molecule = children.BATCHAMOUNT,
};
tempList.Add(basEbomD);
}
if (flag)
{
continue;
}
insertBasEbomDs.AddRange(tempList);
await _db.Updateable<BasEbomH>()
.SetColumns(x => x.unit_id == unitId)
.Where(x => x.id == basEbomH.id)
.ExecuteCommandAsync();
await _db.Deleteable<BasEbomD>().Where(x => x.ebom_id == basEbomH.id).ExecuteCommandAsync();
}
}
}
await _db.Insertable(insertBasEbomHs).ExecuteCommandAsync();
await _db.Insertable(insertBasEbomDs).ExecuteCommandAsync();
await _db.Ado.CommitTranAsync();
msg = $"新增物料{insertMaterial.Count}条,修改物料{editCount}条";
BasSyncRecord basSyncRecord = new BasSyncRecord()
{
msg = msg,
create_time = DateTime.Now
};
await _db.Insertable(basSyncRecord).ExecuteCommandAsync();
}
catch (Exception e)
{
msg = e.Message;
Log.Error(e.Message, e);
await _db.Ado.RollbackTranAsync();
throw Oops.Bah(e.Message);
}
return msg;
}
/// <summary>
/// 同步单位
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncUnit()
{
string msg = "";
var mysqlDb = _db.AsTenant().GetConnection("erpdb");
List<ErpBdMeasdoc> list = await mysqlDb.Queryable<ErpBdMeasdoc>().ToListAsync();
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>().Where(x=>x.table_name=="base_dictionarydata").ToListAsync();
List<DictionaryDataEntity> insertUnit = new List<DictionaryDataEntity>();
List<ErpExtendField> insertExtendFields = new List<ErpExtendField>();
foreach (ErpBdMeasdoc erpBdMeasdoc in list)
{
if (erpExtendFields.All(x => x.cunitid != erpBdMeasdoc.ID))
{
DictionaryDataEntity dictionaryDataEntity = new DictionaryDataEntity()
{
Id = SnowflakeIdHelper.NextId(),
FullName = erpBdMeasdoc.NAME,
EnCode = erpBdMeasdoc.CODE,
ParentId = "0",
SortCode = 0,
EnabledMark = 1,
CreatorTime = DateTime.Now,
DictionaryTypeId = WmsWareHouseConst.UNITTYPEID,
};
ErpExtendField erpExtendField = new ErpExtendField()
{
table_id = dictionaryDataEntity.Id,
table_name = "base_dictionarydata",
cunitid = erpBdMeasdoc.ID,
create_time = DateTime.Now
};
insertUnit.Add(dictionaryDataEntity);
insertExtendFields.Add(erpExtendField);
}
}
if (!insertUnit.IsEmpty() && !insertExtendFields.IsEmpty())
{
DbResult<bool> result = await _db.Ado.UseTranAsync(async () =>
{
await _db.Insertable(insertUnit).ExecuteCommandAsync();
await _db.Insertable(insertExtendFields).ExecuteCommandAsync();
});
return result.IsSuccess ? $"新增单位{insertUnit.Count}条" : result.ErrorMessage;
}
return "新增单位0条";
}
/// <summary>
/// 同步客户
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncCustomer()
{
string msg = "";
try
{
int editCount = 0;
var erpdb = _db.AsTenant().GetConnection("erpdb");
List<ErpBdCustomer> list = await erpdb.Queryable<ErpBdCustomer>().ToListAsync();
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>().Where(x=>x.table_name=="bas_customer").ToListAsync();
List<BasCustomer> insertCustomers = new List<BasCustomer>();
List<ErpExtendField> insertExtendFields = new List<ErpExtendField>();
await _db.Ado.BeginTranAsync();
foreach (ErpBdCustomer erpBdCustomer in list)
{
if (erpExtendFields.All(x => x.customer_id != erpBdCustomer.ID))
{
BasCustomer basCustomer = new BasCustomer()
{
id = SnowflakeIdHelper.NextId(),
customer_code = erpBdCustomer.CODE,
customer_name = erpBdCustomer.NAME,
create_time = DateTime.Now
};
ErpExtendField erpExtendField = new ErpExtendField()
{
table_id = basCustomer.id,
table_name = "bas_customer",
customer_id = erpBdCustomer.ID,
create_time = DateTime.Now,
erp_modify_time = erpBdCustomer.MODIFIEDTIME,
};
insertCustomers.Add(basCustomer);
insertExtendFields.Add(erpExtendField);
}
else
{
ErpExtendField erpExtendField = erpExtendFields.Find(x => x.customer_id == erpBdCustomer.ID);
if (erpBdCustomer.MODIFIEDTIME != erpExtendField.erp_modify_time)
{
int updateRow = await _db.Updateable<BasCustomer>()
.SetColumns(x => x.customer_code == erpBdCustomer.CODE)
.SetColumns(x => x.customer_name == erpBdCustomer.NAME)
.Where(x => x.id == erpExtendField.table_id)
.ExecuteCommandAsync();
await _db.Updateable<ErpExtendField>()
.SetColumns(x => x.erp_modify_time == erpBdCustomer.MODIFIEDTIME)
.Where(x => x.table_id == erpExtendField.table_id)
.ExecuteCommandAsync();
editCount += updateRow;
}
}
}
await _db.Insertable(insertCustomers).ExecuteCommandAsync();
await _db.Insertable(insertExtendFields).ExecuteCommandAsync();
await _db.Ado.CommitTranAsync();
msg = $"新增客户{insertCustomers.Count}条,修改客户{editCount}条";
}
catch (Exception e)
{
Log.Error(e.Message, e);
msg = e.Message;
await _db.Ado.RollbackTranAsync();
throw Oops.Bah(e.Message);
}
return msg;
}
/// <summary>
/// 同步供应商
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncSupplier()
{
string msg = "";
try
{
int editCount = 0;
var erpdb = _db.AsTenant().GetConnection("erpdb");
List<ErpBdSupplier> list = await erpdb.Queryable<ErpBdSupplier>().ToListAsync();
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>().Where(x=>x.table_name=="bas_supplier").ToListAsync();
List<BasSupplier> insertSuppliers = new List<BasSupplier>();
List<ErpExtendField> insertExtendFields = new List<ErpExtendField>();
await _db.Ado.BeginTranAsync();
foreach (ErpBdSupplier erpBdSupplier in list)
{
if (erpExtendFields.All(x => x.supplier_id != erpBdSupplier.ID))
{
BasSupplier basSupplier = new BasSupplier()
{
id = SnowflakeIdHelper.NextId(),
supplier_code = erpBdSupplier.CODE,
supplier_name = erpBdSupplier.NAME,
create_time = DateTime.Now
};
ErpExtendField erpExtendField = new ErpExtendField()
{
table_id = basSupplier.id,
table_name = "bas_supplier",
supplier_id = erpBdSupplier.ID,
supplier_vid = erpBdSupplier.VID,
create_time = DateTime.Now,
erp_modify_time = erpBdSupplier.MODIFIEDTIME,
};
insertSuppliers.Add(basSupplier);
insertExtendFields.Add(erpExtendField);
}
else
{
ErpExtendField erpExtendField = erpExtendFields.Find(x => x.supplier_id == erpBdSupplier.ID);
if (erpBdSupplier.MODIFIEDTIME != erpExtendField.erp_modify_time)
{
int updateRow = await _db.Updateable<BasSupplier>()
.SetColumns(x => x.supplier_code == erpBdSupplier.CODE)
.SetColumns(x => x.supplier_name == erpBdSupplier.NAME)
.Where(x => x.id == erpExtendField.table_id)
.ExecuteCommandAsync();
await _db.Updateable<ErpExtendField>()
.SetColumns(x => x.erp_modify_time == erpBdSupplier.MODIFIEDTIME)
.Where(x => x.table_id == erpExtendField.table_id)
.ExecuteCommandAsync();
editCount += updateRow;
}
}
}
await _db.Insertable(insertSuppliers).ExecuteCommandAsync();
await _db.Insertable(insertExtendFields).ExecuteCommandAsync();
await _db.Ado.CommitTranAsync();
msg = $"新增供应商{insertSuppliers.Count}条,修改供应商{editCount}条";
}
catch (Exception e)
{
Log.Error(e.Message, e);
msg = e.Message;
await _db.Ado.RollbackTranAsync();
throw Oops.Bah(e.Message);
}
return msg;
}
/// <summary>
/// 同步部门
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncDept()
{
string msg = "";
try
{
int editCount = 0;
var erpdb = _db.AsTenant().GetConnection("erpdb");
List<ErpOrgDept> list = await erpdb.Queryable<ErpOrgDept>().ToListAsync();
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>().Where(x=>x.table_name=="base_organize").ToListAsync();
List<OrganizeEntity> insertDepts = new List<OrganizeEntity>();
List<ErpExtendField> insertExtendFields = new List<ErpExtendField>();
await _db.Ado.BeginTranAsync();
foreach (ErpOrgDept erpOrgDept in list)
{
if (erpExtendFields.All(x => x.cdptid != erpOrgDept.ID))
{
string id = SnowflakeIdHelper.NextId();
OrganizeEntity organizeEntity = new OrganizeEntity()
{
Id = id,
ParentId = WmsWareHouseConst.AdministratorOrgId,
Category = "department",
EnCode = erpOrgDept.CODE,
FullName = erpOrgDept.NAME,
SortCode = 0,
EnabledMark = 1,
OrganizeIdTree = $"24755469898005,25193668006933,{id}",
CreatorTime = DateTime.Now
};
ErpExtendField erpExtendField = new ErpExtendField()
{
table_id = organizeEntity.Id,
table_name = "base_organize",
cdptid = erpOrgDept.ID,
cdptvid = erpOrgDept.VID,
create_time = DateTime.Now,
erp_modify_time = erpOrgDept.MODIFIEDTIME,
};
insertDepts.Add(organizeEntity);
insertExtendFields.Add(erpExtendField);
}
else
{
ErpExtendField erpExtendField = erpExtendFields.Find(x => x.cdptid == erpOrgDept.ID);
if (erpOrgDept.MODIFIEDTIME != erpExtendField.erp_modify_time)
{
int updateRow = await _db.Updateable<OrganizeEntity>()
.SetColumns(x => x.EnCode == erpOrgDept.CODE)
.SetColumns(x => x.FullName == erpOrgDept.NAME)
.Where(x => x.Id == erpExtendField.table_id)
.ExecuteCommandAsync();
await _db.Updateable<ErpExtendField>()
.SetColumns(x => x.erp_modify_time == erpOrgDept.MODIFIEDTIME)
.Where(x => x.table_id == erpExtendField.table_id)
.ExecuteCommandAsync();
editCount += updateRow;
}
}
}
await _db.Insertable(insertDepts).ExecuteCommandAsync();
await _db.Insertable(insertExtendFields).ExecuteCommandAsync();
await _db.Ado.CommitTranAsync();
msg = $"新增部门{insertDepts.Count}条,修改部门{editCount}条";
}
catch (Exception e)
{
Log.Error(e.Message, e);
msg = e.Message;
await _db.Ado.RollbackTranAsync();
throw Oops.Bah(e.Message);
}
return msg;
}
/// <summary>
/// 同步用户
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> SyncUser()
{
string msg = "";
try
{
var erpdb = _db.AsTenant().GetConnection("erpdb");
List<ErpBdPsndoc> users = await erpdb.Queryable<ErpBdPsndoc>().ToListAsync();
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>().Where(x=>x.table_name=="base_user").ToListAsync();
List<UserEntity> insertUsers = new List<UserEntity>();
List<UserRelationEntity> insertUserRelations = new List<UserRelationEntity>();
List<ErpExtendField> insertErpExtendFields = new List<ErpExtendField>();
await _db.Ado.BeginTranAsync();
foreach (var user in users)
{
if (erpExtendFields.All(x => x.user_id != user.ID))
{
UserEntity userEntity = new UserEntity();
userEntity.Id = SnowflakeIdHelper.NextId();
userEntity.Account = user.CODE;
userEntity.RealName = user.NAME;
userEntity.Gender = 1;
userEntity.OrganizeId = WmsWareHouseConst.AdministratorOrgId;
userEntity.RoleId = "30327535942933";
userEntity.Secretkey = Guid.NewGuid().ToString();
userEntity.Password = MD5Encryption.Encrypt(MD5Encryption.Encrypt(CommonConst.DEFAULTPASSWORD) + userEntity.Secretkey);
userEntity.EntryDate = DateTime.Now;
userEntity.EnabledMark = 1;
userEntity.CreatorTime = DateTime.Now;
insertUsers.Add(userEntity);
UserRelationEntity userRelationEntity = new UserRelationEntity();
userRelationEntity.Id = SnowflakeIdHelper.NextId();
userRelationEntity.UserId = userEntity.Id;
userRelationEntity.ObjectType = "Role";
userRelationEntity.ObjectId = "30327535942933";
userRelationEntity.CreatorTime = DateTime.Now;
insertUserRelations.Add(userRelationEntity);
UserRelationEntity userRelationEntity2 = new UserRelationEntity();
userRelationEntity2.Id = SnowflakeIdHelper.NextId();
userRelationEntity2.UserId = userEntity.Id;
userRelationEntity2.ObjectType = "Organize";
userRelationEntity2.ObjectId = WmsWareHouseConst.AdministratorOrgId;
userRelationEntity2.CreatorTime = DateTime.Now;
insertUserRelations.Add(userRelationEntity2);
ErpExtendField extendField = new ErpExtendField();
extendField.org_id = WmsWareHouseConst.AdministratorOrgId;
extendField.table_name = "base_user";
extendField.table_id = userEntity.Id;
extendField.user_id = user.ID;
insertErpExtendFields.Add(extendField);
}
}
await _db.Insertable(insertUsers).ExecuteCommandAsync();
await _db.Insertable(insertUserRelations).ExecuteCommandAsync();
await _db.Insertable(insertErpExtendFields).ExecuteCommandAsync();
await _db.Ado.CommitTranAsync();
msg = $"新增用户{insertUsers.Count}条";
}
catch (Exception e)
{
Log.Error(e.Message, e);
msg = e.Message;
await _db.Ado.RollbackTranAsync();
throw Oops.Bah(e.Message);
}
return msg;
}
/// <summary>
/// 监测工艺
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<String> MonitorPer()
{
List<PerProcessStandardsH> perProcessStandardsHs = await _db.Queryable<PrdMoTask>()
.InnerJoin<PerProcessStandardsH>((a,b)=>a.material_id==b.output_material_id && a.eqp_id==b.equip_id && a.mold_id==b.molds_id)
.Where((a,b)=>!SqlFunc.IsNullOrEmpty(a.eqp_id) && a.mo_task_status==DictConst.InProgressEnCode && b.enabled==1)
.Select((a, b) => new PerProcessStandardsH
{
id = a.id,
// process_type = b.process_type,
// code = b.code,
// file_name = b.file_name,
// enabled = b.enabled,
output_material_id = b.output_material_id,
equip_id = b.equip_id,
molds_id = b.molds_id,
process_id = b.process_id,
// input_material_id = b.input_material_id,
version = b.version,
// create_id = b.create_id,
// create_time = b.create_time,
// modify_id = b.modify_id,
// modify_time = b.modify_time,
// org_id = b.org_id,
// remark = b.remark,
// f_flowtaskid = b.f_flowtaskid,
// f_flowid = b.f_flowid,
// moulding_cycle = b.moulding_cycle,
mo_task_id = b.mo_task_id,
mo_task_code = b.mo_task_code,
})
.ToListAsync();
List<string> hids = perProcessStandardsHs.Select(x => x.id).ToList();
List<EqpDaq> eqpDaqs = await _db.Queryable<EqpDaq>()
.InnerJoin<PerProcessStandardsD>((a, b) => a.id == b.daq_id)
.Where((a, b) => hids.Contains(b.process_standards_id))
.ToListAsync();
List<PerAbnormalAlarm> insertList = new List<PerAbnormalAlarm>();
foreach (var item in perProcessStandardsHs)
{
List<PerProcessStandardsD> processStandardsDs = await _db.Queryable<PerProcessStandardsD>()
.InnerJoin<PerProcessParam>((x,y)=>x.process_param_id==y.id)
.Where(x=>x.process_standards_id==item.id && !SqlFunc.IsNullOrEmpty(x.daq_id))
.Select((x,y)=>new PerProcessStandardsD
{
id = x.id,
process_standards_id = x.process_standards_id,
process_param_type_id = x.process_param_type_id,
process_param_id = x.process_param_id,
value = x.value,
upper_value = x.upper_value,
lower_value = x.lower_value,
daq_id = x.daq_id,
name = y.name,
})
.ToListAsync();
if (processStandardsDs.IsNullOrEmpty()) continue;
foreach (var dItem in processStandardsDs)
{
EqpDaq eqpDaq = eqpDaqs.Find(x => x.id == dItem.daq_id);
if (eqpDaq == null) continue;
string key = $"{eqpDaq.equip_code}:${eqpDaq.label_name}";
if (await _redisData.ExistsAsync(key))
{
decimal realValue = _redisData.Get<decimal>(key);
if (realValue < dItem.lower_value || realValue > dItem.upper_value)
{
insertList.Add(new PerAbnormalAlarm()
{
id = SnowflakeIdHelper.NextId(),
mo_task_id = item.mo_task_id,
mo_task_code = item.mo_task_code,
type = "10",
equip_id = item.equip_id,
mold_id = item.molds_id,
product_id = item.output_material_id,
process_standards_id = item.id,
process_param_id = dItem.process_param_id,
process_alarm_type = "1",
real_value = realValue,
set_value = dItem.value,
process_standards_item_id = dItem.id,
content = dItem.name,
upper_value = dItem.upper_value,
lower_value = dItem.lower_value,
process_standards_version = item.version,
create_time = DateTime.Now,
});
}
}
}
}
if (!insertList.IsEmpty())
{
await _db.Insertable(insertList).ExecuteCommandAsync();
}
return "成功";
}
}
}