using SqlSugar;
namespace Admin.NET.Plugin.AiDOP.MaterialWarehouse.InventoryPosting.L0;
///
/// IQC 收货标准层只读读取(L0,态①)。**只读 `mdp_std_iqc_receipt_state`**——不直连 dopdemorq、不读旧 InvMaster/PurOrd* raw。
/// 双源边界:std 内容由入站/切源决定(本库 或 dopdemorq),读端只按 tenant+domain+fbillno 查,与 source 解耦。
///
public interface IIqcReceiptStdReader
{
/// 按 (tenant, domain, FBILLNO) 读标准层单行;不存在返回 null(Found=false)。
Task LoadRowAsync(long tenantId, string domainCode, string fbillno);
}
///
/// 生产实现:原生 SQL 读 `mdp_std_iqc_receipt_state`(运行时 DDL 表,非 SugarTable 实体,故走 Ado)。
/// ⚠️ Phase 5B 未实库验证:标准层需先由 贴源产出。
///
public sealed class SqlSugarIqcReceiptStdReader : IIqcReceiptStdReader, ITransient
{
private readonly ISqlSugarClient _db;
public SqlSugarIqcReceiptStdReader(ISqlSugarClient db) => _db = db;
public async Task LoadRowAsync(long tenantId, string domainCode, string fbillno)
{
var dt = await _db.Ado.GetDataTableAsync(
"""
SELECT tenant_id, domain, fbillno, qc_nbr, item_num, location, lot_serial, rct_nbr,
pur_ord, pur_line, potype, qty_ordered, received_cum_qty, returned_cum_qty,
sample_qty, receipt_pending_qty, receivable_detail_count, sync_time
FROM mdp_std_iqc_receipt_state
WHERE tenant_id=@t AND domain=@d AND fbillno=@fb
LIMIT 1
""",
new SugarParameter("@t", tenantId), new SugarParameter("@d", domainCode ?? ""), new SugarParameter("@fb", fbillno));
if (dt.Rows.Count == 0) return null;
var r = dt.Rows[0];
decimal Dec(string c) => r[c] == DBNull.Value ? 0m : Convert.ToDecimal(r[c]);
int Int(string c) => r[c] == DBNull.Value ? 0 : Convert.ToInt32(r[c]);
string Str(string c) => r[c] == DBNull.Value ? "" : Convert.ToString(r[c]);
return new IqcReceiptStdRow
{
TenantId = tenantId, Domain = domainCode ?? "", Fbillno = fbillno, QcNbr = Str("qc_nbr"),
ItemNum = Str("item_num"), Location = Str("location"), LotSerial = Str("lot_serial"), RctNbr = Str("rct_nbr"),
PurOrd = Str("pur_ord"), PurLine = Int("pur_line"), Potype = Str("potype"),
OrderedQty = Dec("qty_ordered"), ReceivedCumQty = Dec("received_cum_qty"), ReturnedCumQty = Dec("returned_cum_qty"),
SampleQty = Dec("sample_qty"), ReceiptPendingQty = Dec("receipt_pending_qty"), ReceivableDetailCount = Int("receivable_detail_count"),
SourceSyncedAt = r["sync_time"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(r["sync_time"]),
};
}
}