feat(repository): CncRepository完整实现 - 20接口+16实现,编译通过

- Interface: 20个仓储接口(ISysConfig/IWorkshop/IBrand/IBrandFieldMapping/ICollectAddress/IMachine/IWorker/IWorkerMachine/IDailyProduction/IProductionSegment/IMachineDailyStatus/IWorkerDailySummary/IProductionAdjustment/IAlert/IScreenConfig/IScreenFilter/ICollectRaw/ISystemLog/ICollectorHeartbeat/IDashboard)
- Impl: 16个仓储实现(BusinessRepository子类+LogRepository子类)
- 包含: 基础CRUD/分页查询/多表JOIN/统计聚合/仪表盘查询
- 修复: AlertRepository继承修正(BusinessRepository)/dynamic替换为强类型
main
haoliang 1 week ago
parent 5ec37e6724
commit fc7d350c3d

@ -1,15 +1,16 @@
using System.Collections.Generic;
namespace CncModels.Dto.Alert
{
/// <summary>
/// 告警统计
/// 告警统计结果(未处理告警分类型统计)
/// </summary>
public class AlertStatisticsResponse
{
public int Unresolved { get; set; }
public int CollectFail { get; set; }
public int DeviceOffline { get; set; }
public int ProductionAnomaly { get; set; }
public int UnknownDevice { get; set; }
public int ServiceError { get; set; }
/// <summary>未处理告警总数</summary>
public int UnresolvedCount { get; set; }
/// <summary>按告警类型统计的未处理数量</summary>
public Dictionary<string, int> UnresolvedByType { get; set; } = new Dictionary<string, int>();
}
}

@ -0,0 +1,15 @@
using System;
namespace CncModels.Dto.Dashboard
{
/// <summary>
/// 最新告警条目
/// </summary>
public class AlertListItem
{
public long Id { get; set; }
public string Message { get; set; }
public string Severity { get; set; }
public DateTime CreatedAt { get; set; }
}
}

@ -1,3 +1,5 @@
using System;
namespace CncModels.Dto.Dashboard
{
/// <summary>
@ -5,11 +7,7 @@ namespace CncModels.Dto.Dashboard
/// </summary>
public class MachineRankResponse
{
public int Rank { get; set; }
public int MachineId { get; set; }
public string MachineName { get; set; }
public string Program { get; set; }
public int Quantity { get; set; }
public int Status { get; set; }
}
}

@ -1,3 +1,5 @@
using System;
namespace CncModels.Dto.Dashboard
{
/// <summary>
@ -5,10 +7,7 @@ namespace CncModels.Dto.Dashboard
/// </summary>
public class WorkerRankResponse
{
public int Rank { get; set; }
public int WorkerId { get; set; }
public string WorkerName { get; set; }
public int MachineCount { get; set; }
public int TotalQuantity { get; set; }
public int Quantity { get; set; }
}
}

@ -3,20 +3,13 @@ using System;
namespace CncModels.Dto.Dashboard
{
/// <summary>
/// 各车间产量详情
/// 车间生产量统计
/// </summary>
public class WorkshopProductionResponse
{
/// <summary>车间名称</summary>
public string WorkshopName { get; set; }
/// <summary>产量</summary>
public int Quantity { get; set; }
/// <summary>机床数量</summary>
public int MachineCount { get; set; }
/// <summary>日均产量</summary>
public decimal AvgQuantity { get; set; }
}
}

@ -1,19 +1,22 @@
using System;
namespace CncModels.Dto.Production
{
/// <summary>
/// 日产量列表项
/// cnc_daily_production 日汇总表列表项
/// </summary>
public class DailyProductionListItem
{
public int Id { get; set; }
public string Date { get; set; }
public int MachineId { get; set; }
public string MachineName { get; set; }
public DateTime ProductionDate { get; set; }
public string ProgramName { get; set; }
public int Quantity { get; set; }
public string RunTime { get; set; }
public string CuttingTime { get; set; }
public string DataStatus { get; set; }
public int IsAdjusted { get; set; }
public int? AdjustedQuantity { get; set; }
public decimal TotalQuantity { get; set; }
public int SegmentCount { get; set; }
public decimal? TotalRunTime { get; set; }
public decimal? TotalCuttingTime { get; set; }
public decimal? TotalCycleTime { get; set; }
public int? WorkerId { get; set; }
}
}

@ -22,6 +22,9 @@ namespace CncModels.Entity
/// <summary>总产量</summary>
public decimal TotalQuantity { get; set; }
/// <summary>工人ID用于产量按工人汇总的场景</summary>
public int? WorkerId { get; set; }
/// <summary>段数</summary>
public int SegmentCount { get; set; }

@ -0,0 +1,111 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
using System.Data;
using CncModels.Dto;
namespace CncRepository.Impl
{
/// <summary>
/// 车间仓储实现
/// </summary>
public class WorkshopRepository : BusinessRepository, IWorkshopRepository
{
public WorkshopRepository(string connectionString) : base(connectionString) { }
public Workshop GetById(int id)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, SortOrder as SortOrder, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_workshop WHERE Id = @Id";
return conn.QuerySingleOrDefault<Workshop>(sql, new { Id = id });
}
}
public List<Workshop> GetAll()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, SortOrder as SortOrder, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_workshop ORDER BY SortOrder ASC";
return conn.Query<Workshop>(sql).ToList();
}
}
public PagedResult<Workshop> GetList(string keyword)
{
using (var conn = CreateConnection())
{
var where = string.Empty;
var param = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(keyword))
{
where = " WHERE Name LIKE @Keyword";
param.Add("Keyword", $"%{keyword}%");
}
var limit = 20;
var sql = $@"SELECT Id as Id, Name as Name, SortOrder as SortOrder, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt
FROM cnc_workshop {where} ORDER BY SortOrder ASC LIMIT {limit} OFFSET 0";
var totalSql = $@"SELECT COUNT(*) FROM cnc_workshop {where}";
var items = conn.Query<Workshop>(sql, param).ToList();
var total = conn.ExecuteScalar<int>(totalSql, param);
return new PagedResult<Workshop>
{
Items = items,
Total = total,
Page = 1,
PageSize = limit
};
}
}
public int Create(Workshop entity)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_workshop (Name, SortOrder, IsEnabled, CreatedAt, UpdatedAt)
VALUES (@Name, @SortOrder, @IsEnabled, @CreatedAt, @UpdatedAt);
SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, entity);
}
}
public bool Update(Workshop entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_workshop SET Name = @Name, SortOrder = @SortOrder, IsEnabled = @IsEnabled, UpdatedAt = @UpdatedAt WHERE Id = @Id";
return conn.Execute(sql, entity) > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_workshop WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public bool ToggleEnabled(int id)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_workshop SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public int GetMachineCount(int workshopId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT COUNT(*) FROM cnc_machine WHERE WorkshopId = @WorkshopId";
return conn.ExecuteScalar<int>(sql, new { WorkshopId = workshopId });
}
}
}
}

@ -10,6 +10,10 @@ namespace CncRepository.Base
/// </summary>
public class BusinessRepository : BaseRepository
{
/// <summary>
/// 初始化业务库仓储
/// </summary>
/// <param name="connectionString">cnc_business 数据库连接字符串</param>
public BusinessRepository(string connectionString) : base(connectionString) { }
}
@ -19,6 +23,10 @@ namespace CncRepository.Base
/// </summary>
public class LogRepository : BaseRepository
{
/// <summary>
/// 初始化日志库仓储
/// </summary>
/// <param name="connectionString">cnc_log 数据库连接字符串</param>
public LogRepository(string connectionString) : base(connectionString) { }
}
}

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Alert;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class AlertRepository : BusinessRepository, IAlertRepository
{
public AlertRepository(string connectionString) : base(connectionString) { }
public Alert GetById(long id)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_alert WHERE Id = @Id";
return conn.QuerySingleOrDefault<Alert>(sql, new { Id = id });
}
}
public PagedResult<AlertListItem> GetList(AlertQuery query)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT a.Id, a.CreatedAt, a.AlertType, a.Title, m.Name AS MachineName, a.Detail, a.IsResolved, a.ResolvedAt
FROM cnc_alert a LEFT JOIN cnc_machine m ON a.MachineId = m.Id
WHERE 1=1";
string countSql = @"SELECT COUNT(*) FROM cnc_alert a LEFT JOIN cnc_machine m ON a.MachineId = m.Id WHERE 1=1";
var p = new DynamicParameters();
if (!string.IsNullOrEmpty(query.AlertType)) { sql += " AND a.AlertType = @AlertType"; countSql += " AND a.AlertType = @AlertType"; p.Add("AlertType", query.AlertType); }
if (query.IsResolved.HasValue) { sql += " AND a.IsResolved = @IsResolved"; countSql += " AND a.IsResolved = @IsResolved"; p.Add("IsResolved", query.IsResolved.Value); }
if (query.MachineId.HasValue) { sql += " AND a.MachineId = @MachineId"; countSql += " AND a.MachineId = @MachineId"; p.Add("MachineId", query.MachineId.Value); }
if (query.StartDate.HasValue) { sql += " AND a.CreatedAt >= @Start"; countSql += " AND a.CreatedAt >= @Start"; p.Add("Start", query.StartDate.Value); }
if (query.EndDate.HasValue) { sql += " AND a.CreatedAt <= @End"; countSql += " AND a.CreatedAt <= @End"; p.Add("End", query.EndDate.Value); }
int offset = (query.Page - 1) * query.PageSize;
sql += " ORDER BY a.CreatedAt DESC LIMIT @Limit OFFSET @Offset";
p.Add("Limit", query.PageSize);
p.Add("Offset", offset);
var items = conn.Query<AlertListItem>(sql, p).AsList();
int total = conn.ExecuteScalar<int>(countSql, p);
return new PagedResult<AlertListItem> { Items = items, Total = total, Page = query.Page, PageSize = query.PageSize };
}
}
public long Create(Alert entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_alert (AlertType, MachineId, CollectAddressId, Title, Detail, IsResolved, ResolvedAt, CreatedAt)
VALUES (@AlertType, @MachineId, @CollectAddressId, @Title, @Detail, @IsResolved, @ResolvedAt, @CreatedAt); SELECT LAST_INSERT_ID();";
return conn.ExecuteScalar<long>(sql, entity);
}
}
public bool Resolve(long id)
{
using (var conn = CreateConnection())
{
string sql = "UPDATE cnc_alert SET IsResolved = 1, ResolvedAt = NOW() WHERE Id = @Id";
int affected = conn.Execute(sql, new { Id = id });
return affected > 0;
}
}
public int BatchResolve(List<long> ids)
{
using (var conn = CreateConnection())
{
string sql = "UPDATE cnc_alert SET IsResolved = 1, ResolvedAt = NOW() WHERE Id IN @Ids";
return conn.Execute(sql, new { Ids = ids });
}
}
public AlertStatisticsResponse GetStatistics()
{
using (var conn = CreateConnection())
{
string sql = @"SELECT alert_type AS AlertType, COUNT(*) AS Count
FROM cnc_alert WHERE is_resolved = 0 GROUP BY alert_type";
var rows = conn.Query<AlertTypeCount>(sql).AsList();
var dict = rows.ToDictionary(r => r.AlertType, r => r.Count);
return new AlertStatisticsResponse
{
UnresolvedCount = dict.Values.Sum(),
UnresolvedByType = dict
};
}
}
/// <summary>
/// 告警类型计数内部类用于Dapper映射
/// </summary>
private class AlertTypeCount
{
public string AlertType { get; set; }
public int Count { get; set; }
}
}
}

@ -0,0 +1,97 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
using System.Data;
namespace CncRepository.Impl
{
/// <summary>
/// 品牌字段映射实现
/// </summary>
public class BrandFieldMappingRepository : BusinessRepository, IBrandFieldMappingRepository
{
public BrandFieldMappingRepository(string connectionString) : base(connectionString) { }
public List<BrandFieldMapping> GetByBrandId(int brandId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, BrandId as BrandId, StandardField as StandardField, FieldName as FieldName, MatchBy as MatchBy, DataType as DataType, IsRequired as IsRequired, CreatedAt as CreatedAt
FROM cnc_brand_field_mapping WHERE BrandId = @BrandId ORDER BY Id";
return conn.Query<BrandFieldMapping>(sql, new { BrandId = brandId }).ToList();
}
}
public BrandFieldMapping GetById(int id)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, BrandId as BrandId, StandardField as StandardField, FieldName as FieldName, MatchBy as MatchBy, DataType as DataType, IsRequired as IsRequired, CreatedAt as CreatedAt
FROM cnc_brand_field_mapping WHERE Id = @Id";
return conn.QuerySingleOrDefault<BrandFieldMapping>(sql, new { Id = id });
}
}
public int Create(BrandFieldMapping entity)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_brand_field_mapping (BrandId, StandardField, FieldName, MatchBy, DataType, IsRequired, CreatedAt)
VALUES (@BrandId, @StandardField, @FieldName, @MatchBy, @DataType, @IsRequired, @CreatedAt);
SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, entity);
}
}
public bool Update(BrandFieldMapping entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_brand_field_mapping SET BrandId = @BrandId, StandardField = @StandardField, FieldName = @FieldName, MatchBy = @MatchBy, DataType = @DataType, IsRequired = @IsRequired, CreatedAt = @CreatedAt WHERE Id = @Id";
return conn.Execute(sql, entity) > 0;
}
}
public bool DeleteByBrandId(int brandId)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_brand_field_mapping WHERE BrandId = @BrandId";
return conn.Execute(sql, new { BrandId = brandId }) > 0;
}
}
public int BatchCreate(int brandId, List<BrandFieldMapping> mappings)
{
using (var conn = CreateConnection())
{
using (var tran = conn.BeginTransaction())
{
try
{
int count = 0;
var sql = @"INSERT INTO cnc_brand_field_mapping (BrandId, StandardField, FieldName, MatchBy, DataType, IsRequired, CreatedAt)
VALUES (@BrandId, @StandardField, @FieldName, @MatchBy, @DataType, @IsRequired, @CreatedAt);
SELECT LAST_INSERT_ID();";
foreach (var m in mappings)
{
m.BrandId = brandId;
var id = conn.QuerySingle<int>(sql, m, tran);
count++;
}
tran.Commit();
return count;
}
catch
{
tran.Rollback();
throw;
}
}
}
}
}
}

@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
/// <summary>
/// 品牌实现
/// </summary>
public class BrandRepository : BusinessRepository, IBrandRepository
{
public BrandRepository(string connectionString) : base(connectionString) { }
public Brand GetById(int id)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, BrandName as BrandName, DeviceField as DeviceField, TagsPath as TagsPath, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt
FROM cnc_brand WHERE Id = @Id";
return conn.QuerySingleOrDefault<Brand>(sql, new { Id = id });
}
}
public List<Brand> GetAll()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, BrandName as BrandName, DeviceField as DeviceField, TagsPath as TagsPath, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_brand ORDER BY Id";
return conn.Query<Brand>(sql).ToList();
}
}
public int Create(Brand entity)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_brand (BrandName, DeviceField, TagsPath, IsEnabled, CreatedAt, UpdatedAt)
VALUES (@BrandName, @DeviceField, @TagsPath, @IsEnabled, @CreatedAt, @UpdatedAt);
SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, entity);
}
}
public bool Update(Brand entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_brand SET BrandName = @BrandName, DeviceField = @DeviceField, TagsPath = @TagsPath, IsEnabled = @IsEnabled, UpdatedAt = @UpdatedAt WHERE Id = @Id";
return conn.Execute(sql, entity) > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_brand WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public bool ToggleEnabled(int id)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_brand SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public int GetFieldMappingCount(int brandId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT COUNT(*) FROM cnc_brand_field_mapping WHERE BrandId = @BrandId";
return conn.ExecuteScalar<int>(sql, new { BrandId = brandId });
}
}
public int GetCollectAddressCount(int brandId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT COUNT(*) FROM cnc_collect_address WHERE BrandId = @BrandId";
return conn.ExecuteScalar<int>(sql, new { BrandId = brandId });
}
}
}
}

@ -0,0 +1,128 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.CollectAddress;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
/// <summary>
/// 采集地址实现
/// </summary>
public class CollectAddressRepository : BusinessRepository, ICollectAddressRepository
{
public CollectAddressRepository(string connectionString) : base(connectionString) { }
public CollectAddress GetById(int id)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, Url as Url, BrandId as BrandId, CollectInterval as CollectInterval, IsEnabled as IsEnabled, LastCollectTime as LastCollectTime, LastCollectStatus as LastCollectStatus, FailCount as FailCount, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_collect_address WHERE Id = @Id";
return conn.QuerySingleOrDefault<CollectAddress>(sql, new { Id = id });
}
}
public PagedResult<CollectAddressListItem> GetList(CollectAddressQuery query)
{
using (var conn = CreateConnection())
{
var where = " WHERE 1=1";
var parameters = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(query.Keyword))
{
where += " AND (ca.Name LIKE @Keyword OR ca.Url LIKE @Keyword)";
parameters.Add("Keyword", $"%{query.Keyword}%");
}
if (query.BrandId.HasValue)
{
where += " AND ca.BrandId = @BrandId";
parameters.Add("BrandId", query.BrandId.Value);
}
if (query.IsEnabled.HasValue)
{
where += " AND ca.IsEnabled = @IsEnabled";
parameters.Add("IsEnabled", query.IsEnabled.Value);
}
var limit = query.PageSize;
var offset = query.Offset;
var sql = @"SELECT ca.Id as Id, ca.Name as Name, ca.Url as Url, ca.BrandId as BrandId, b.BrandName as BrandName, ca.CollectInterval as CollectInterval, ca.IsEnabled as IsEnabled, ca.LastCollectTime as LastCollectTime,
(SELECT COUNT(*) FROM cnc_machine m WHERE m.CollectAddressId = ca.Id) as MachineCount
FROM cnc_collect_address ca LEFT JOIN cnc_brand b ON ca.BrandId = b.Id" + where + @" ORDER BY ca.Id DESC LIMIT @Limit OFFSET @Offset";
parameters.Add("Limit", limit);
parameters.Add("Offset", offset);
var totalSql = @"SELECT COUNT(*) FROM cnc_collect_address ca LEFT JOIN cnc_brand b ON ca.BrandId = b.Id" + where;
var total = conn.ExecuteScalar<int>(totalSql, parameters);
var items = conn.Query<CollectAddressListItem>(sql, parameters).ToList();
return new PagedResult<CollectAddressListItem>
{
Items = items,
Total = total,
Page = query.Page,
PageSize = limit
};
}
}
public int Create(CollectAddress entity)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_collect_address (Name, Url, BrandId, CollectInterval, IsEnabled, CreatedAt, UpdatedAt)
VALUES (@Name, @Url, @BrandId, @CollectInterval, @IsEnabled, @CreatedAt, @UpdatedAt);
SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, entity);
}
}
public bool Update(CollectAddress entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_collect_address SET Name = @Name, Url = @Url, BrandId = @BrandId, CollectInterval = @CollectInterval, IsEnabled = @IsEnabled, UpdatedAt = @UpdatedAt WHERE Id = @Id";
return conn.Execute(sql, entity) > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_collect_address WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public bool ToggleEnabled(int id)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_collect_address SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public List<CollectAddress> GetEnabledList()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, Url as Url, BrandId as BrandId, CollectInterval as CollectInterval, IsEnabled as IsEnabled, LastCollectTime as LastCollectTime, LastCollectStatus as LastCollectStatus, FailCount as FailCount, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_collect_address WHERE IsEnabled = 1";
return conn.Query<CollectAddress>(sql).ToList();
}
}
public int GetMachineCount(int collectAddressId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT COUNT(*) FROM cnc_machine WHERE CollectAddressId = @CollectAddressId";
return conn.ExecuteScalar<int>(sql, new { CollectAddressId = collectAddressId });
}
}
}
}

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto.Production;
using CncModels.Dto;
using CncModels.Dto.Production;
using CncRepository.Base;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
/// <summary>
/// cnc_daily_production 产量仓储实现(业务库)
/// </summary>
public class DailyProductionRepository : BusinessRepository, IDailyProductionRepository
{
public DailyProductionRepository(string connectionString) : base(connectionString) { }
public DailyProduction GetById(int id)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_daily_production WHERE Id = @Id";
return conn.QuerySingleOrDefault<DailyProduction>(sql, new { Id = id });
}
}
public PagedResult<DailyProductionListItem> GetList(ProductionQuery query)
{
using (var conn = CreateConnection())
{
string baseSql = @"SELECT dp.Id, dp.MachineId, m.Name AS MachineName, dp.ProductionDate, dp.ProgramName, dp.TotalQuantity, dp.SegmentCount, dp.TotalRunTime, dp.TotalCuttingTime, dp.TotalCycleTime, dp.WorkerId AS WorkerId
FROM cnc_daily_production dp
LEFT JOIN cnc_machine m ON dp.MachineId = m.Id
WHERE 1=1";
string countSql = @"SELECT COUNT(*) FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.MachineId = m.Id WHERE 1=1";
var parameters = new DynamicParameters();
if (query?.Date.HasValue == true)
{
baseSql += " AND dp.ProductionDate = @Date";
countSql += " AND dp.ProductionDate = @Date";
parameters.Add("Date", query.Date);
}
int offset = (query.Page - 1) * query.PageSize;
string paging = " ORDER BY dp.ProductionDate DESC LIMIT @Limit OFFSET @Offset";
parameters.Add("Limit", query.PageSize);
parameters.Add("Offset", offset);
var items = conn.Query<DailyProductionListItem>(baseSql + paging, parameters).ToList();
int total = conn.ExecuteScalar<int>(countSql, parameters);
return new PagedResult<DailyProductionListItem>
{
Items = items,
Total = total,
Page = query.Page,
PageSize = query.PageSize
};
}
}
public List<DailyProduction> GetByMachineAndDate(int machineId, DateTime date)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_daily_production WHERE MachineId = @MachineId AND ProductionDate = @Date";
return conn.Query<DailyProduction>(sql, new { MachineId = machineId, Date = date }).ToList();
}
}
public List<DailyProduction> GetByDateRange(DateTime startDate, DateTime endDate)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT dp.* FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.MachineId = m.Id WHERE dp.ProductionDate BETWEEN @Start AND @End ORDER BY dp.ProductionDate DESC";
return conn.Query<DailyProduction>(sql, new { Start = startDate, End = endDate }).ToList();
}
}
public decimal GetTotalByDateRange(DateTime startDate, DateTime endDate, int? workshopId)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT SUM(dp.TotalQuantity) FROM cnc_daily_production dp LEFT JOIN cnc_machine m ON dp.MachineId = m.Id WHERE dp.ProductionDate BETWEEN @Start AND @End";
if (workshopId.HasValue)
{
sql += " AND m.WorkshopId = @WorkshopId";
return conn.ExecuteScalar<decimal>(sql, new { Start = startDate, End = endDate, WorkshopId = workshopId.Value });
}
return conn.ExecuteScalar<decimal>(sql, new { Start = startDate, End = endDate });
}
}
public decimal GetTotalByWorkerAndDateRange(int workerId, DateTime startDate, DateTime endDate)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT SUM(TotalQuantity) FROM cnc_daily_production WHERE WorkerId = @WorkerId AND ProductionDate BETWEEN @Start AND @End";
var res = conn.ExecuteScalar<decimal?>(sql, new { WorkerId = workerId, Start = startDate, End = endDate });
return res ?? 0m;
}
}
public List<DailyProduction> GetMachineRankByDateRange(DateTime startDate, DateTime endDate, int top)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT m.Id AS Id, m.Id AS MachineId, m.Name AS MachineName, SUM(dp.TotalQuantity) AS TotalQuantity, NULL AS ProgramName, NULL AS ProductionDate, NULL AS SegmentCount, NULL AS TotalRunTime, NULL AS TotalCuttingTime, NULL AS TotalCycleTime
FROM cnc_daily_production dp
JOIN cnc_machine m ON dp.MachineId = m.Id
WHERE dp.ProductionDate BETWEEN @Start AND @End
GROUP BY m.Id, m.Name
ORDER BY SUM(dp.TotalQuantity) DESC LIMIT @Top";
return conn.Query<DailyProduction>(sql, new { Start = startDate, End = endDate, Top = top }).ToList();
}
}
public List<DailyProduction> GetWorkerRankByDateRange(DateTime startDate, DateTime endDate, int top)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT 0 AS Id, NULL AS MachineId, NULL AS MachineName, SUM(TotalQuantity) AS TotalQuantity, WorkerId AS WorkerId, NULL AS ProductionDate, NULL AS ProgramName, NULL AS SegmentCount, NULL AS TotalRunTime, NULL AS TotalCuttingTime, NULL AS TotalCycleTime
FROM cnc_daily_production
WHERE ProductionDate BETWEEN @Start AND @End AND WorkerId IS NOT NULL
GROUP BY WorkerId
ORDER BY SUM(TotalQuantity) DESC LIMIT @Top";
return conn.Query<DailyProduction>(sql, new { Start = startDate, End = endDate, Top = top }).ToList();
}
}
}
}

@ -0,0 +1,146 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using Dapper;
using CncModels.Dto.Dashboard;
using CncModels.Dto;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl.Dashboard
{
/// <summary>
/// 仪表盘跨表统计查询实现
/// </summary>
public class DashboardRepository : BusinessRepository, IDashboardRepository
{
public DashboardRepository(string connectionString) : base(connectionString) { }
/// <summary>汇总卡片数据</summary>
public DashboardSummaryResponse GetSummary()
{
using (var conn = CreateConnection())
{
var onlineCount = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM cnc_machine WHERE is_online = 1");
var totalMachines = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM cnc_machine");
var todayProduction = conn.ExecuteScalar<int>(@"SELECT COALESCE(SUM(total_quantity),0) FROM cnc_daily_production WHERE production_date = CURDATE()");
var activeAlerts = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM cnc_alert WHERE is_resolved = 0");
// 采集成功率,简单实现:统计 cnc_collect_address 表的记录中的成功率若无数据则返回0
var totalAddresses = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM cnc_collect_address");
var failCount = conn.ExecuteScalar<int>(@"SELECT COALESCE(SUM(fail_count),0) FROM cnc_collect_address");
decimal collectSuccessRate = totalAddresses > 0 ? (decimal)(totalAddresses - failCount) / totalAddresses * 100 : 0m;
var todayCuttingTime = conn.ExecuteScalar<int>(@"SELECT COALESCE(SUM(total_cutting_time),0) FROM cnc_daily_production WHERE production_date = CURDATE()");
var runningMachines = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM cnc_machine WHERE last_device_status = 'running'");
var dataMissingMachines = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM cnc_machine_daily_status WHERE production_date = CURDATE() AND data_status = 'data_missing'");
return new DashboardSummaryResponse
{
OnlineCount = onlineCount,
TotalMachines = totalMachines,
TodayProduction = todayProduction,
ActiveAlerts = activeAlerts,
CollectSuccessRate = collectSuccessRate,
TodayCuttingTime = todayCuttingTime,
RunningMachines = runningMachines,
DataMissingMachines = dataMissingMachines
};
}
}
/// <summary>按车间时间区间统计生产量(平均单机产量)</summary>
public List<WorkshopProductionResponse> GetWorkshopProduction(DateTime startDate, DateTime endDate)
{
using (var conn = CreateConnection())
{
var sql = @"
SELECT w.Name AS WorkshopName,
COALESCE(SUM(dp.total_quantity),0) AS Quantity,
COUNT(DISTINCT m.id) AS MachineCount,
CASE
WHEN DATEDIFF(@EndDate, @StartDate) = 0 THEN COALESCE(SUM(dp.total_quantity),0) / NULLIF(COUNT(DISTINCT m.id),0)
ELSE COALESCE(SUM(dp.total_quantity),0) / (DATEDIFF(@EndDate, @StartDate) + 1) / NULLIF(COUNT(DISTINCT m.id),0)
END AS AvgQuantity
FROM cnc_workshop w
LEFT JOIN cnc_machine m ON m.workshop_id = w.id
LEFT JOIN cnc_daily_production dp ON dp.machine_id = m.id
AND dp.production_date BETWEEN @StartDate AND @EndDate
GROUP BY w.id, w.name";
return conn.Query<WorkshopProductionResponse>(sql, new { StartDate = startDate, EndDate = endDate }).ToList();
}
}
/// <summary>机床排行</summary>
public List<MachineRankResponse> GetMachineRank(DateTime startDate, DateTime endDate, int top)
{
using (var conn = CreateConnection())
{
var sql = @"
SELECT m.name AS MachineName,
COALESCE(SUM(dp.total_quantity),0) AS Quantity
FROM cnc_machine m
LEFT JOIN cnc_daily_production dp ON dp.machine_id = m.id
AND dp.production_date BETWEEN @StartDate AND @EndDate
GROUP BY m.id, m.name
ORDER BY Quantity DESC
LIMIT @Top";
return conn.Query<MachineRankResponse>(sql, new { StartDate = startDate, EndDate = endDate, Top = top }).ToList();
}
}
/// <summary>工人排行</summary>
public List<WorkerRankResponse> GetWorkerRank(DateTime startDate, DateTime endDate, int top)
{
using (var conn = CreateConnection())
{
var sql = @"
SELECT w.name AS WorkerName,
COALESCE(SUM(dp.total_quantity),0) AS Quantity
FROM cnc_worker w
LEFT JOIN cnc_daily_production dp ON dp.worker_id = w.id
AND dp.production_date BETWEEN @StartDate AND @EndDate
GROUP BY w.id, w.name
ORDER BY Quantity DESC
LIMIT @Top";
return conn.Query<WorkerRankResponse>(sql, new { StartDate = startDate, EndDate = endDate, Top = top }).ToList();
}
}
/// <summary>产量趋势(最近 days 天)</summary>
public List<dynamic> GetProductionTrend(int days)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT production_date AS Date, COALESCE(SUM(total_quantity),0) AS Quantity
FROM cnc_daily_production
WHERE production_date >= DATE_SUB(CURDATE(), INTERVAL @Days DAY)
GROUP BY production_date
ORDER BY production_date ASC";
return conn.Query(sql, new { Days = days }).ToList();
}
}
/// <summary>机床状态分布(示意性实现,需要根据实际状态表结构调整)</summary>
public List<dynamic> GetMachineStatusDistribution()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT last_device_status AS Status, COUNT(1) AS Count FROM cnc_machine GROUP BY last_device_status";
return conn.Query(sql).ToList();
}
}
/// <summary>最近告警</summary>
public List<AlertListItem> GetRecentAlerts(int count)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id, Title AS Message, Severity, CreatedAt FROM cnc_alert ORDER BY CreatedAt DESC LIMIT @Count";
// 如果 cnc_alert 不存在 Title/Severity后续可调整为 Message/Level 等字段
return conn.Query<AlertListItem>(sql, new { Count = count }).ToList();
}
}
}
}

@ -0,0 +1,144 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using Dapper;
using CncModels.Entity;
using CncModels.Dto;
using CncRepository.Base;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl.Log
{
/// <summary>
/// 日志库log_collect_raw 原始采集记录仓储实现
/// </summary>
public class CollectRawRepository : LogRepository, ICollectRawRepository
{
public CollectRawRepository(string connectionString) : base(connectionString) { }
/// <summary>通过 Id 获取原始记录</summary>
public CollectRaw GetById(long id)
{
using (var conn = CreateConnection())
{
return conn.QueryFirstOrDefault<CollectRaw>(@"
SELECT Id,
CollectAddressId AS CollectAddressId,
RequestTime AS RequestTime,
ResponseTime AS ResponseTime,
ResponseDuration AS ResponseDuration,
IsSuccess AS IsSuccess,
StatusCode AS StatusCode,
RawJson AS RawJson,
ErrorMessage AS ErrorMessage,
CreatedAt AS CreatedAt
FROM log_collect_raw
WHERE Id = @Id", new { Id = id });
}
}
/// <summary>按地址分页获取原始记录</summary>
public PagedResult<CollectRaw> GetByAddressId(int collectAddressId, int page, int pageSize)
{
using (var conn = CreateConnection())
{
int skip = Math.Max(0, (page - 1) * pageSize);
var items = conn.Query<CollectRaw>(@"
SELECT Id AS Id,
CollectAddressId AS CollectAddressId,
RequestTime AS RequestTime,
ResponseTime AS ResponseTime,
ResponseDuration AS ResponseDuration,
IsSuccess AS IsSuccess,
StatusCode AS StatusCode,
RawJson AS RawJson,
ErrorMessage AS ErrorMessage,
CreatedAt AS CreatedAt
FROM log_collect_raw
WHERE CollectAddressId = @CollectAddressId
ORDER BY CreatedAt DESC
LIMIT @PageSize OFFSET @Skip", new { CollectAddressId = collectAddressId, PageSize = pageSize, Skip = skip }).AsList();
int total = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM log_collect_raw WHERE CollectAddressId = @CollectAddressId", new { CollectAddressId = collectAddressId });
return new PagedResult<CollectRaw> { Items = items.ToList(), Total = total, Page = page, PageSize = pageSize };
}
}
/// <summary>获取某地址最新的一条原始采集记录</summary>
public CollectRaw GetLatestByAddressId(int collectAddressId)
{
using (var conn = CreateConnection())
{
return conn.QueryFirstOrDefault<CollectRaw>(@"
SELECT Id AS Id,
CollectAddressId AS CollectAddressId,
RequestTime AS RequestTime,
ResponseTime AS ResponseTime,
ResponseDuration AS ResponseDuration,
IsSuccess AS IsSuccess,
StatusCode AS StatusCode,
RawJson AS RawJson,
ErrorMessage AS ErrorMessage,
CreatedAt AS CreatedAt
FROM log_collect_raw
WHERE CollectAddressId = @CollectAddressId
ORDER BY CreatedAt DESC
LIMIT 1", new { CollectAddressId = collectAddressId });
}
}
/// <summary>写入原始采集记录</summary>
public long Create(CollectRaw entity)
{
using (var conn = CreateConnection())
{
var sql = @"
INSERT INTO log_collect_raw (
CollectAddressId,
RequestTime,
ResponseTime,
ResponseDuration,
IsSuccess,
StatusCode,
RawJson,
ErrorMessage,
CreatedAt
) VALUES (
@CollectAddressId,
@RequestTime,
@ResponseTime,
@ResponseDuration,
@IsSuccess,
@StatusCode,
@RawJson,
@ErrorMessage,
@CreatedAt
);
SELECT LAST_INSERT_ID();";
return conn.ExecuteScalar<long>(sql, new
{
CollectAddressId = entity.CollectAddressId,
RequestTime = entity.RequestTime,
ResponseTime = entity.ResponseTime,
ResponseDuration = entity.ResponseDuration,
IsSuccess = entity.IsSuccess,
StatusCode = entity.StatusCode,
RawJson = entity.RawJson,
ErrorMessage = entity.ErrorMessage,
CreatedAt = entity.CreatedAt
});
}
}
/// <summary>清理过期数据(按日期)</summary>
public int DeleteBeforeDate(DateTime date)
{
using (var conn = CreateConnection())
{
return conn.Execute(@"DELETE FROM log_collect_raw WHERE CreatedAt < @Date", new { Date = date });
}
}
}
}

@ -0,0 +1,68 @@
using System;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl.Log
{
/// <summary>
/// 日志库log_collector_heartbeat 心跳仓储实现
/// </summary>
public class CollectorHeartbeatRepository : LogRepository, ICollectorHeartbeatRepository
{
public CollectorHeartbeatRepository(string connectionString) : base(connectionString) { }
/// <summary>写入心跳</summary>
public long Create(CollectorHeartbeat entity)
{
using (var conn = CreateConnection())
{
var sql = @"
INSERT INTO log_collector_heartbeat (
ServiceId, Status, CollectAddressId, LastCollectTime, SuccessCount, FailCount, UptimeSeconds, Detail, CreatedAt
) VALUES (
@ServiceId, @Status, @CollectAddressId, @LastCollectTime, @SuccessCount, @FailCount, @UptimeSeconds, @Detail, @CreatedAt
);
SELECT LAST_INSERT_ID();";
return conn.ExecuteScalar<long>(sql, new
{
ServiceId = entity.ServiceId,
Status = entity.Status,
CollectAddressId = entity.CollectAddressId,
LastCollectTime = entity.LastCollectTime,
SuccessCount = entity.SuccessCount,
FailCount = entity.FailCount,
UptimeSeconds = entity.UptimeSeconds,
Detail = entity.Detail,
CreatedAt = entity.CreatedAt
});
}
}
/// <summary>获取最新心跳</summary>
public CollectorHeartbeat GetLatest(string serviceId)
{
using (var conn = CreateConnection())
{
return conn.QueryFirstOrDefault<CollectorHeartbeat>(@"
SELECT Id, ServiceId AS ServiceId, Status AS Status, CollectAddressId AS CollectAddressId, LastCollectTime AS LastCollectTime,
SuccessCount AS SuccessCount, FailCount AS FailCount, UptimeSeconds AS UptimeSeconds, Detail AS Detail, CreatedAt AS CreatedAt
FROM log_collector_heartbeat
WHERE ServiceId = @ServiceId
ORDER BY CreatedAt DESC
LIMIT 1", new { ServiceId = serviceId });
}
}
/// <summary>清理过去的心跳记录(按日期)</summary>
public int DeleteBeforeDate(DateTime date)
{
using (var conn = CreateConnection())
{
return conn.Execute(@"DELETE FROM log_collector_heartbeat WHERE CreatedAt < @Date", new { Date = date });
}
}
}
}

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class MachineDailyStatusRepository : BusinessRepository, IMachineDailyStatusRepository
{
public MachineDailyStatusRepository(string connectionString) : base(connectionString) { }
public MachineDailyStatus GetByMachineAndDate(int machineId, DateTime date)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_machine_daily_status WHERE MachineId = @MachineId AND ProductionDate = @Date";
return conn.QuerySingleOrDefault<MachineDailyStatus>(sql, new { MachineId = machineId, Date = date });
}
}
public int Upsert(MachineDailyStatus entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_machine_daily_status (MachineId, ProductionDate, DataStatus, CreatedAt, UpdatedAt)
VALUES (@MachineId, @ProductionDate, @DataStatus, @CreatedAt, @UpdatedAt)
ON DUPLICATE KEY UPDATE DataStatus = @DataStatus, UpdatedAt = @UpdatedAt";
return conn.Execute(sql, entity);
}
}
public List<MachineDailyStatus> GetByDate(DateTime date)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_machine_daily_status WHERE ProductionDate = @Date";
return conn.Query<MachineDailyStatus>(sql, new { Date = date }).AsList();
}
}
public int CountByDateAndStatus(DateTime date, string dataStatus)
{
using (var conn = CreateConnection())
{
string sql = "SELECT COUNT(*) FROM cnc_machine_daily_status WHERE ProductionDate = @Date AND DataStatus = @Status";
return conn.ExecuteScalar<int>(sql, new { Date = date, Status = dataStatus });
}
}
}
}

@ -0,0 +1,167 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Machine;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
/// <summary>
/// 机床实现
/// </summary>
public class MachineRepository : BusinessRepository, IMachineRepository
{
public MachineRepository(string connectionString) : base(connectionString) { }
public Machine GetById(int id)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, DeviceCode as DeviceCode, Name as Name, WorkshopId as WorkshopId, CollectAddressId as CollectAddressId, IpAddress as IpAddress, BrandId as BrandId, IsEnabled as IsEnabled, IsOnline as IsOnline, LastPingTime as LastPingTime, LastCollectTime as LastCollectTime, LastDeviceStatus as LastDeviceStatus, LastRunStatus as LastRunStatus, LastProgramName as LastProgramName, LastPartCount as LastPartCount, LastOperateMode as LastOperateMode, LastMachiningStatus as LastMachiningStatus, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_machine WHERE Id = @Id";
return conn.QuerySingleOrDefault<Machine>(sql, new { Id = id });
}
}
public PagedResult<MachineListItem> GetList(MachineQuery query)
{
using (var conn = CreateConnection())
{
var where = " WHERE 1=1";
var p = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(query.Keyword))
{
where += " AND (m.Name LIKE @Keyword OR m.DeviceCode LIKE @Keyword)";
p.Add("Keyword", $"%{query.Keyword}%");
}
if (query.WorkshopId.HasValue)
{
where += " AND m.WorkshopId = @WorkshopId";
p.Add("WorkshopId", query.WorkshopId.Value);
}
if (query.IsOnline.HasValue)
{
where += " AND m.IsOnline = @IsOnline";
p.Add("IsOnline", query.IsOnline.Value);
}
if (query.BrandId.HasValue)
{
where += " AND m.BrandId = @BrandId";
p.Add("BrandId", query.BrandId.Value);
}
var limit = query.PageSize;
var offset = query.Offset;
var sql = @"SELECT m.Id as Id, m.DeviceCode as DeviceCode, m.Name as Name, m.WorkshopId as WorkshopId, ws.Name as WorkshopName, m.CollectAddressId as CollectAddressId, m.BrandId as BrandId, b.BrandName as BrandName, m.IpAddress as IpAddress, m.IsEnabled as IsEnabled, m.IsOnline as IsOnline, m.LastProgramName as LastProgramName, m.LastCollectTime as LastCollectTime, w.Id as WorkerId, w.Name as WorkerName
FROM cnc_machine m
LEFT JOIN cnc_workshop ws ON m.WorkshopId = ws.Id
LEFT JOIN cnc_brand b ON m.BrandId = b.Id
LEFT JOIN cnc_worker_machine wm ON m.Id = wm.MachineId
LEFT JOIN cnc_worker w ON wm.WorkerId = w.Id" + where + @" ORDER BY m.Id DESC LIMIT @Limit OFFSET @Offset";
p.Add("Limit", limit);
p.Add("Offset", offset);
var totalSql = @"SELECT COUNT(*) FROM cnc_machine m" + where + @"";
var total = conn.ExecuteScalar<int>(totalSql, p);
var items = conn.Query<MachineListItem>(sql, p).ToList();
return new PagedResult<MachineListItem>
{
Items = items,
Total = total,
Page = query.Page,
PageSize = limit
};
}
}
public int Create(Machine entity)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_machine (DeviceCode, Name, WorkshopId, CollectAddressId, IpAddress, BrandId, IsEnabled, IsOnline, CreatedAt, UpdatedAt)
VALUES (@DeviceCode, @Name, @WorkshopId, @CollectAddressId, @IpAddress, @BrandId, @IsEnabled, @IsOnline, @CreatedAt, @UpdatedAt);
SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, entity);
}
}
public bool Update(Machine entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_machine SET DeviceCode = @DeviceCode, Name = @Name, WorkshopId = @WorkshopId, CollectAddressId = @CollectAddressId, IpAddress = @IpAddress, BrandId = @BrandId, IsEnabled = @IsEnabled, IsOnline = @IsOnline, UpdatedAt = @UpdatedAt, LastProgramName = @LastProgramName, LastCollectTime = @LastCollectTime, LastDeviceStatus = @LastDeviceStatus, LastRunStatus = @LastRunStatus, LastMachiningStatus = @LastMachiningStatus WHERE Id = @Id";
return conn.Execute(sql, entity) > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_machine WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public bool ToggleEnabled(int id)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_machine SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public Machine GetByDeviceCode(string deviceCode)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, DeviceCode as DeviceCode, Name as Name, WorkshopId as WorkshopId, CollectAddressId as CollectAddressId, IpAddress as IpAddress, BrandId as BrandId, IsEnabled as IsEnabled, IsOnline as IsOnline, LastPingTime as LastPingTime, LastCollectTime as LastCollectTime, LastDeviceStatus as LastDeviceStatus, LastRunStatus as LastRunStatus, LastProgramName as LastProgramName, LastPartCount as LastPartCount, LastOperateMode as LastOperateMode, LastMachiningStatus as LastMachiningStatus, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_machine WHERE DeviceCode = @DeviceCode";
return conn.QuerySingleOrDefault<Machine>(sql, new { DeviceCode = deviceCode });
}
}
public List<Machine> GetEnabledByAddressId(int collectAddressId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, DeviceCode as DeviceCode, Name as Name, WorkshopId as WorkshopId, CollectAddressId as CollectAddressId, IpAddress as IpAddress, BrandId as BrandId, IsEnabled as IsEnabled, IsOnline as IsOnline, LastPingTime as LastPingTime, LastCollectTime as LastCollectTime, LastDeviceStatus as LastDeviceStatus, LastRunStatus as LastRunStatus, LastProgramName as LastProgramName, LastPartCount as LastPartCount, LastOperateMode as LastOperateMode, LastMachiningStatus as LastMachiningStatus, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_machine WHERE CollectAddressId = @CollectAddressId AND IsEnabled = 1";
return conn.Query<Machine>(sql, new { CollectAddressId = collectAddressId }).ToList();
}
}
public List<Machine> GetEnabledOnline()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, DeviceCode as DeviceCode, Name as Name, WorkshopId as WorkshopId, CollectAddressId as CollectAddressId, IpAddress as IpAddress, BrandId as BrandId, IsEnabled as IsEnabled, IsOnline as IsOnline, LastPingTime as LastPingTime, LastCollectTime as LastCollectTime, LastDeviceStatus as LastDeviceStatus, LastRunStatus as LastRunStatus, LastProgramName as LastProgramName, LastPartCount as LastPartCount, LastOperateMode as LastOperateMode, LastMachiningStatus as LastMachiningStatus, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_machine WHERE IsEnabled = 1 AND IsOnline = 1";
return conn.Query<Machine>(sql).ToList();
}
}
public void UpdateOnlineStatus(int id, bool isOnline)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_machine SET IsOnline = @IsOnline, UpdatedAt = NOW() WHERE Id = @Id";
conn.Execute(sql, new { Id = id, IsOnline = isOnline ? 1 : 0 });
}
}
public void UpdateLastCollect(int id, Machine entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_machine SET LastCollectTime = @LastCollectTime, LastProgramName = @LastProgramName, LastMachiningStatus = @LastMachiningStatus, UpdatedAt = NOW() WHERE Id = @Id";
var param = new
{
Id = id,
LastCollectTime = entity.LastCollectTime,
LastProgramName = entity.LastProgramName,
LastMachiningStatus = entity.LastMachiningStatus
};
conn.Execute(sql, param);
}
}
}
}

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using Dapper;
using System.Linq;
using CncModels.Entity;
using CncModels.Dto;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class ProductionAdjustmentRepository : BusinessRepository, IProductionAdjustmentRepository
{
public ProductionAdjustmentRepository(string connectionString) : base(connectionString) { }
public int Create(ProductionAdjustment entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_production_adjustment (TargetTable, TargetId, FieldName, OldValue, NewValue, Reason, OperatorIp, CreatedAt)
VALUES (@TargetTable, @TargetId, @FieldName, @OldValue, @NewValue, @Reason, @OperatorIp, @CreatedAt);";
return conn.Execute(sql, entity);
}
}
public PagedResult<ProductionAdjustment> GetList(string targetTable, DateTime? startDate, DateTime? endDate, string keyword, int page, int pageSize)
{
using (var conn = CreateConnection())
{
string sqlBase = "SELECT * FROM cnc_production_adjustment WHERE 1=1";
if (!string.IsNullOrEmpty(targetTable)) sqlBase += " AND TargetTable = @TargetTable";
if (startDate.HasValue) sqlBase += " AND CreatedAt >= @StartDate";
if (endDate.HasValue) sqlBase += " AND CreatedAt <= @EndDate";
if (!string.IsNullOrEmpty(keyword)) sqlBase += " AND (CAST(TargetId AS CHAR) LIKE @Keyword OR FieldName LIKE @Keyword)";
int offset = (page - 1) * pageSize;
string sqlCount = "SELECT COUNT(*) FROM cnc_production_adjustment WHERE 1=1" +
(string.IsNullOrEmpty(targetTable) ? string.Empty : " AND TargetTable = @TargetTable") +
(startDate.HasValue ? " AND CreatedAt >= @StartDate" : "") +
(endDate.HasValue ? " AND CreatedAt <= @EndDate" : "") +
(!string.IsNullOrEmpty(keyword) ? " AND (CAST(TargetId AS CHAR) LIKE @Keyword OR FieldName LIKE @Keyword)" : "");
string sqlPage = sqlBase + " ORDER BY CreatedAt DESC LIMIT @Limit OFFSET @Offset";
var param = new { TargetTable = targetTable, StartDate = startDate, EndDate = endDate, Keyword = ("%" + keyword + "%"), Limit = pageSize, Offset = offset };
var items = conn.Query<ProductionAdjustment>(sqlPage, param).AsList();
int total = conn.ExecuteScalar<int>(sqlCount, param);
return new PagedResult<ProductionAdjustment> { Items = items, Total = total, Page = page, PageSize = pageSize };
}
}
}
}

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class ProductionSegmentRepository : BusinessRepository, IProductionSegmentRepository
{
public ProductionSegmentRepository(string connectionString) : base(connectionString) { }
public ProductionSegment GetById(long id)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_production_segment WHERE Id = @Id";
return conn.QuerySingleOrDefault<ProductionSegment>(sql, new { Id = id });
}
}
public ProductionSegment GetActiveSegment(int machineId)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_production_segment WHERE MachineId = @MachineId AND IsSettled = 0 AND EndTime IS NULL ORDER BY StartTime DESC LIMIT 1";
return conn.QuerySingleOrDefault<ProductionSegment>(sql, new { MachineId = machineId });
}
}
public List<ProductionSegment> GetByMachineAndDate(int machineId, DateTime date)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_production_segment WHERE MachineId = @MachineId AND DATE(StartTime) = DATE(@Date)";
return conn.Query<ProductionSegment>(sql, new { MachineId = machineId, Date = date }).AsList();
}
}
public int Create(ProductionSegment entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_production_segment (MachineId, ProgramName, ProductionDate, StartTime, StartPartCount, EndPartCount, Quantity, IsSettled, CloseReason, EndTime, CreatedAt, UpdatedAt)
VALUES (@MachineId, @ProgramName, @ProductionDate, @StartTime, @StartPartCount, @EndPartCount, @Quantity, @IsSettled, @CloseReason, @EndTime, @CreatedAt, @UpdatedAt); SELECT LAST_INSERT_ID();";
return conn.ExecuteScalar<int>(sql, entity);
}
}
public bool CloseSegment(long id, decimal? endPartCount, decimal? quantity, string closeReason, DateTime endTime)
{
using (var conn = CreateConnection())
{
string sql = @"UPDATE cnc_production_segment
SET EndPartCount = @EndPartCount, Quantity = @Quantity, CloseReason = @CloseReason, EndTime = @EndTime
WHERE Id = @Id";
int affected = conn.Execute(sql, new { Id = id, EndPartCount = endPartCount, Quantity = quantity, CloseReason = closeReason, EndTime = endTime });
return affected > 0;
}
}
public bool SettleByDate(DateTime date)
{
using (var conn = CreateConnection())
{
string sql = @"UPDATE cnc_production_segment SET IsSettled = 1, CloseReason = 'end_of_day' WHERE DATE(StartTime) = DATE(@Date) AND IsSettled = 0";
int affected = conn.Execute(sql, new { Date = date });
return affected > 0;
}
}
}
}

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class ScreenConfigRepository : BusinessRepository, IScreenConfigRepository
{
public ScreenConfigRepository(string connectionString) : base(connectionString) { }
public List<ScreenConfig> GetAll()
{
using (var conn = CreateConnection())
{
return conn.Query<ScreenConfig>("SELECT * FROM cnc_screen_config").AsList();
}
}
public List<ScreenConfig> GetEnabled()
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_screen_config WHERE IsEnabled = 1 ORDER BY SortOrder ASC";
return conn.Query<ScreenConfig>(sql).AsList();
}
}
public ScreenConfig GetById(int id)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_screen_config WHERE Id = @Id";
return conn.QuerySingleOrDefault<ScreenConfig>(sql, new { Id = id });
}
}
public int Create(ScreenConfig entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_screen_config (CardKey, CardType, Title, Metric, Dimension, SortOrder, IsEnabled, ChartConfig, CreatedAt, UpdatedAt)
VALUES (@CardKey, @CardType, @Title, @Metric, @Dimension, @SortOrder, @IsEnabled, @ChartConfig, @CreatedAt, @UpdatedAt); SELECT LAST_INSERT_ID();";
return conn.ExecuteScalar<int>(sql, entity);
}
}
public bool Update(ScreenConfig entity)
{
using (var conn = CreateConnection())
{
string sql = @"UPDATE cnc_screen_config SET CardKey = @CardKey, CardType = @CardType, Title = @Title, Metric = @Metric, Dimension = @Dimension, SortOrder = @SortOrder, IsEnabled = @IsEnabled, ChartConfig = @ChartConfig, UpdatedAt = @UpdatedAt WHERE Id = @Id";
int affected = conn.Execute(sql, entity);
return affected > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
string sql = "DELETE FROM cnc_screen_config WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public bool ToggleEnabled(int id)
{
using (var conn = CreateConnection())
{
string sql = "UPDATE cnc_screen_config SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
int affected = conn.Execute(sql, new { Id = id });
return affected > 0;
}
}
}
}

@ -0,0 +1,51 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class ScreenFilterRepository : BusinessRepository, IScreenFilterRepository
{
public ScreenFilterRepository(string connectionString) : base(connectionString) { }
public List<ScreenFilter> GetByScreenKey(string screenKey)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_screen_filter WHERE ScreenKey = @ScreenKey ORDER BY SortOrder ASC";
return conn.Query<ScreenFilter>(sql, new { ScreenKey = screenKey }).AsList();
}
}
public int Create(ScreenFilter entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_screen_filter (ScreenKey, FilterType, FilterValue, IsDefault, SortOrder) VALUES (@ScreenKey, @FilterType, @FilterValue, @IsDefault, @SortOrder); SELECT LAST_INSERT_ID();";
return conn.ExecuteScalar<int>(sql, entity);
}
}
public bool Update(ScreenFilter entity)
{
using (var conn = CreateConnection())
{
string sql = @"UPDATE cnc_screen_filter SET ScreenKey = @ScreenKey, FilterType = @FilterType, FilterValue = @FilterValue, IsDefault = @IsDefault, SortOrder = @SortOrder WHERE Id = @Id";
int affected = conn.Execute(sql, entity);
return affected > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
string sql = "DELETE FROM cnc_screen_filter WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
}
}

@ -0,0 +1,50 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
using System.Data;
namespace CncRepository.Impl
{
/// <summary>
/// 系统配置实现
/// </summary>
public class SysConfigRepository : BusinessRepository, ISysConfigRepository
{
public SysConfigRepository(string connectionString) : base(connectionString) { }
/// <inheritdoc/>
public SysConfig GetByKey(string configKey)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, ConfigKey as ConfigKey, ConfigValue as ConfigValue, ValueType as ValueType, Description as Description, UpdatedAt as UpdatedAt
FROM cnc_sys_config WHERE ConfigKey = @ConfigKey LIMIT 1";
return conn.QuerySingleOrDefault<SysConfig>(sql, new { ConfigKey = configKey });
}
}
/// <inheritdoc/>
public List<SysConfig> GetAll()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, ConfigKey as ConfigKey, ConfigValue as ConfigValue, ValueType as ValueType, Description as Description, UpdatedAt as UpdatedAt FROM cnc_sys_config ORDER BY Id";
return conn.Query<SysConfig>(sql).ToList();
}
}
/// <inheritdoc/>
public bool UpdateValue(int id, string configValue)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_sys_config SET ConfigValue = @ConfigValue, UpdatedAt = NOW() WHERE Id = @Id";
var affected = conn.Execute(sql, new { Id = id, ConfigValue = configValue });
return affected > 0;
}
}
}
}

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Log;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class SystemLogRepository : LogRepository, ISystemLogRepository
{
public SystemLogRepository(string connectionString) : base(connectionString) { }
public PagedResult<SystemLogListItem> GetList(SystemLogQuery query)
{
using (var conn = CreateConnection())
{
string sql = @"SELECT Id, CreatedAt, LogLevel, Source, Message, StackTrace, ExtraData
FROM log_system
WHERE 1=1";
string countSql = @"SELECT COUNT(*) FROM log_system WHERE 1=1";
if (!string.IsNullOrEmpty(query.LogLevel)) { sql += " AND LogLevel = @LogLevel"; countSql += " AND LogLevel = @LogLevel"; }
if (!string.IsNullOrEmpty(query.Source)) { sql += " AND Source = @Source"; countSql += " AND Source = @Source"; }
if (!string.IsNullOrEmpty(query.StartDate)) { sql += " AND CreatedAt >= @Start"; countSql += " AND CreatedAt >= @Start"; }
if (!string.IsNullOrEmpty(query.EndDate)) { sql += " AND CreatedAt <= @End"; countSql += " AND CreatedAt <= @End"; }
if (!string.IsNullOrEmpty(query.Keyword)) { sql += " AND Message LIKE @Keyword"; countSql += " AND Message LIKE @Keyword"; }
var p = new { LogLevel = query.LogLevel, Source = query.Source, Start = query.StartDate, End = query.EndDate, Keyword = ("%" + query.Keyword + "%") };
int offset = (query.Page - 1) * query.PageSize;
sql += " ORDER BY CreatedAt DESC LIMIT @Limit OFFSET @Offset";
var list = conn.Query<SystemLogListItem>(sql, p).AsList();
int total = conn.ExecuteScalar<int>(countSql, p);
return new PagedResult<SystemLogListItem> { Items = list, Total = total, Page = query.Page, PageSize = query.PageSize };
}
}
public int Create(SystemLog entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO log_system (LogLevel, Source, Message, StackTrace, ExtraData, CreatedAt)
VALUES (@LogLevel, @Source, @Message, @StackTrace, @ExtraData, @CreatedAt);";
return conn.Execute(sql, entity);
}
}
}
}

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
public class WorkerDailySummaryRepository : BusinessRepository, IWorkerDailySummaryRepository
{
public WorkerDailySummaryRepository(string connectionString) : base(connectionString) { }
public WorkerDailySummary GetByWorkerAndDate(int workerId, DateTime date)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_worker_daily_summary WHERE WorkerId = @WorkerId AND ProductionDate = @Date";
return conn.QuerySingleOrDefault<WorkerDailySummary>(sql, new { WorkerId = workerId, Date = date });
}
}
public List<WorkerDailySummary> GetByDateRange(DateTime startDate, DateTime endDate)
{
using (var conn = CreateConnection())
{
string sql = "SELECT * FROM cnc_worker_daily_summary WHERE ProductionDate BETWEEN @Start AND @End";
return conn.Query<WorkerDailySummary>(sql, new { Start = startDate, End = endDate }).AsList();
}
}
public int Upsert(WorkerDailySummary entity)
{
using (var conn = CreateConnection())
{
string sql = @"INSERT INTO cnc_worker_daily_summary (WorkerId, ProductionDate, TotalQuantity, MachineCount, ProgramCount, IsAdjusted, AdjustedQuantity, CreatedAt, UpdatedAt)
VALUES (@WorkerId, @ProductionDate, @TotalQuantity, @MachineCount, @ProgramCount, @IsAdjusted, @AdjustedQuantity, @CreatedAt, @UpdatedAt)
ON DUPLICATE KEY UPDATE TotalQuantity = @TotalQuantity, MachineCount = @MachineCount, ProgramCount = @ProgramCount, UpdatedAt = @UpdatedAt";
return conn.Execute(sql, entity);
}
}
}
}

@ -0,0 +1,62 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
/// <summary>
/// 工人-机床绑定实现
/// </summary>
public class WorkerMachineRepository : BusinessRepository, IWorkerMachineRepository
{
public WorkerMachineRepository(string connectionString) : base(connectionString) { }
public WorkerMachine GetByMachineId(int machineId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, WorkerId as WorkerId, MachineId as MachineId, CreatedAt as CreatedAt FROM cnc_worker_machine WHERE MachineId = @MachineId";
return conn.QuerySingleOrDefault<WorkerMachine>(sql, new { MachineId = machineId });
}
}
public List<WorkerMachine> GetByWorkerId(int workerId)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, WorkerId as WorkerId, MachineId as MachineId, CreatedAt as CreatedAt FROM cnc_worker_machine WHERE WorkerId = @WorkerId";
return conn.Query<WorkerMachine>(sql, new { WorkerId = workerId }).ToList();
}
}
public int Create(int workerId, int machineId)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_worker_machine (WorkerId, MachineId, CreatedAt) VALUES (@WorkerId, @MachineId, NOW()); SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, new { WorkerId = workerId, MachineId = machineId });
}
}
public bool DeleteByMachineId(int machineId)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_worker_machine WHERE MachineId = @MachineId";
return conn.Execute(sql, new { MachineId = machineId }) > 0;
}
}
public bool DeleteByWorkerId(int workerId)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_worker_machine WHERE WorkerId = @WorkerId";
return conn.Execute(sql, new { WorkerId = workerId }) > 0;
}
}
}
}

@ -0,0 +1,119 @@
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Dto;
using CncModels.Entity;
using CncModels.Dto.Worker;
using CncRepository.Base;
using CncRepository.Interface;
namespace CncRepository.Impl
{
/// <summary>
/// 工人实现
/// </summary>
public class WorkerRepository : BusinessRepository, IWorkerRepository
{
public WorkerRepository(string connectionString) : base(connectionString) { }
public Worker GetById(int id)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, Code as Code, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_worker WHERE Id = @Id";
return conn.QuerySingleOrDefault<Worker>(sql, new { Id = id });
}
}
public PagedResult<WorkerListItem> GetList(WorkerQuery query)
{
using (var conn = CreateConnection())
{
var where = " WHERE 1=1";
var p = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(query.Keyword))
{
where += " AND (w.Name LIKE @Keyword OR w.Code LIKE @Keyword)";
p.Add("Keyword", $"%{query.Keyword}%");
}
if (query.IsEnabled.HasValue)
{
where += " AND w.IsEnabled = @IsEnabled";
p.Add("IsEnabled", query.IsEnabled.Value);
}
var limit = query.PageSize;
var offset = query.Offset;
var sql = @"SELECT w.Id as Id, w.Code as Code, w.Name as Name, w.IsEnabled as IsEnabled,
(SELECT COUNT(*) FROM cnc_worker_machine wm WHERE wm.WorkerId = w.Id) as MachineCount,
(SELECT GROUP_CONCAT(m.Name SEPARATOR ', ') FROM cnc_worker_machine wm JOIN cnc_machine m ON wm.MachineId = m.Id WHERE wm.WorkerId = w.Id) as MachineNames
FROM cnc_worker w" + where + @" ORDER BY w.Id DESC LIMIT @Limit OFFSET @Offset";
p.Add("Limit", limit);
p.Add("Offset", offset);
var totalSql = @"SELECT COUNT(*) FROM cnc_worker w" + where;
var total = conn.ExecuteScalar<int>(totalSql, p);
var items = conn.Query<WorkerListItem>(sql, p).ToList();
return new PagedResult<WorkerListItem>
{
Items = items,
Total = total,
Page = query.Page,
PageSize = limit
};
}
}
public int Create(Worker entity)
{
using (var conn = CreateConnection())
{
var sql = @"INSERT INTO cnc_worker (Name, Code, IsEnabled, CreatedAt, UpdatedAt) VALUES (@Name, @Code, @IsEnabled, @CreatedAt, @UpdatedAt); SELECT LAST_INSERT_ID();";
return conn.QuerySingle<int>(sql, entity);
}
}
public bool Update(Worker entity)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_worker SET Name = @Name, Code = @Code, IsEnabled = @IsEnabled, UpdatedAt = @UpdatedAt WHERE Id = @Id";
return conn.Execute(sql, entity) > 0;
}
}
public bool Delete(int id)
{
using (var conn = CreateConnection())
{
var sql = @"DELETE FROM cnc_worker WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public bool ToggleEnabled(int id)
{
using (var conn = CreateConnection())
{
var sql = @"UPDATE cnc_worker SET IsEnabled = CASE WHEN IsEnabled = 1 THEN 0 ELSE 1 END, UpdatedAt = NOW() WHERE Id = @Id";
return conn.Execute(sql, new { Id = id }) > 0;
}
}
public Worker GetByCode(string code)
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, Code as Code, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_worker WHERE Code = @Code";
return conn.QuerySingleOrDefault<Worker>(sql, new { Code = code });
}
}
public List<Worker> GetAll()
{
using (var conn = CreateConnection())
{
var sql = @"SELECT Id as Id, Name as Name, Code as Code, IsEnabled as IsEnabled, CreatedAt as CreatedAt, UpdatedAt as UpdatedAt FROM cnc_worker ORDER BY Id";
return conn.Query<Worker>(sql).ToList();
}
}
}
}

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Alert;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_alert 告警表 仓储接口
/// </summary>
public interface IAlertRepository
{
Alert GetById(long id);
PagedResult<AlertListItem> GetList(AlertQuery query);
long Create(Alert entity);
bool Resolve(long id);
int BatchResolve(List<long> ids);
AlertStatisticsResponse GetStatistics();
}
}

@ -0,0 +1,18 @@
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// 品牌字段映射仓储接口
/// </summary>
public interface IBrandFieldMappingRepository
{
List<BrandFieldMapping> GetByBrandId(int brandId);
BrandFieldMapping GetById(int id);
int Create(BrandFieldMapping entity);
bool Update(BrandFieldMapping entity);
bool DeleteByBrandId(int brandId);
int BatchCreate(int brandId, List<BrandFieldMapping> mappings);
}
}

@ -0,0 +1,20 @@
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// 品牌仓储接口
/// </summary>
public interface IBrandRepository
{
Brand GetById(int id);
List<Brand> GetAll();
int Create(Brand entity);
bool Update(Brand entity);
bool Delete(int id);
bool ToggleEnabled(int id);
int GetFieldMappingCount(int brandId);
int GetCollectAddressCount(int brandId);
}
}

@ -0,0 +1,22 @@
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto.CollectAddress;
using CncModels.Dto;
namespace CncRepository.Interface
{
/// <summary>
/// 采集地址仓储接口
/// </summary>
public interface ICollectAddressRepository
{
CollectAddress GetById(int id);
PagedResult<CollectAddressListItem> GetList(CollectAddressQuery query);
int Create(CollectAddress entity);
bool Update(CollectAddress entity);
bool Delete(int id);
bool ToggleEnabled(int id);
List<CollectAddress> GetEnabledList();
int GetMachineCount(int collectAddressId);
}
}

@ -0,0 +1,22 @@
using System;
using CncModels.Entity;
using CncModels.Dto;
namespace CncRepository.Interface
{
/// <summary>
/// 日志库:原始采集记录仓储接口
/// </summary>
public interface ICollectRawRepository
{
CollectRaw GetById(long id);
PagedResult<CollectRaw> GetByAddressId(int collectAddressId, int page, int pageSize);
CollectRaw GetLatestByAddressId(int collectAddressId);
long Create(CollectRaw entity);
int DeleteBeforeDate(DateTime date);
}
}

@ -0,0 +1,17 @@
using System;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// 日志库:心跳仓储接口
/// </summary>
public interface ICollectorHeartbeatRepository
{
long Create(CollectorHeartbeat entity);
CollectorHeartbeat GetLatest(string serviceId);
int DeleteBeforeDate(DateTime date);
}
}

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using CncModels.Dto;
using CncModels.Dto.Production;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_daily_production 产量仓储接口(业务库)
/// </summary>
public interface IDailyProductionRepository
{
DailyProduction GetById(int id);
PagedResult<DailyProductionListItem> GetList(ProductionQuery query);
List<DailyProduction> GetByMachineAndDate(int machineId, DateTime date);
List<DailyProduction> GetByDateRange(DateTime startDate, DateTime endDate);
decimal GetTotalByDateRange(DateTime startDate, DateTime endDate, int? workshopId);
decimal GetTotalByWorkerAndDateRange(int workerId, DateTime startDate, DateTime endDate);
List<DailyProduction> GetMachineRankByDateRange(DateTime startDate, DateTime endDate, int top);
List<DailyProduction> GetWorkerRankByDateRange(DateTime startDate, DateTime endDate, int top);
}
}

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using CncModels.Dto.Dashboard;
namespace CncRepository.Interface
{
/// <summary>
/// 仪表盘统计查询仓储接口(跨表聚合)
/// </summary>
public interface IDashboardRepository
{
DashboardSummaryResponse GetSummary();
List<WorkshopProductionResponse> GetWorkshopProduction(DateTime startDate, DateTime endDate);
List<MachineRankResponse> GetMachineRank(DateTime startDate, DateTime endDate, int top);
List<WorkerRankResponse> GetWorkerRank(DateTime startDate, DateTime endDate, int top);
List<dynamic> GetProductionTrend(int days);
List<dynamic> GetMachineStatusDistribution();
List<AlertListItem> GetRecentAlerts(int count);
}
}

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_machine_daily_status 机床日状态表 仓储接口
/// </summary>
public interface IMachineDailyStatusRepository
{
MachineDailyStatus GetByMachineAndDate(int machineId, DateTime date);
int Upsert(MachineDailyStatus entity);
List<MachineDailyStatus> GetByDate(DateTime date);
int CountByDateAndStatus(DateTime date, string dataStatus);
}
}

@ -0,0 +1,25 @@
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Machine;
namespace CncRepository.Interface
{
/// <summary>
/// 机床仓储接口
/// </summary>
public interface IMachineRepository
{
Machine GetById(int id);
PagedResult<MachineListItem> GetList(MachineQuery query);
int Create(Machine entity);
bool Update(Machine entity);
bool Delete(int id);
bool ToggleEnabled(int id);
Machine GetByDeviceCode(string deviceCode);
List<Machine> GetEnabledByAddressId(int collectAddressId);
List<Machine> GetEnabledOnline();
void UpdateOnlineStatus(int id, bool isOnline);
void UpdateLastCollect(int id, Machine entity);
}
}

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_production_adjustment 产量修正审计表 仓储接口
/// </summary>
public interface IProductionAdjustmentRepository
{
int Create(ProductionAdjustment entity);
PagedResult<ProductionAdjustment> GetList(string targetTable, DateTime? startDate, DateTime? endDate, string keyword, int page, int pageSize);
}
}

@ -0,0 +1,19 @@
using System.Collections.Generic;
using System;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_production_segment 产量分段记录表 仓储接口
/// </summary>
public interface IProductionSegmentRepository
{
ProductionSegment GetById(long id);
ProductionSegment GetActiveSegment(int machineId);
List<ProductionSegment> GetByMachineAndDate(int machineId, DateTime date);
int Create(ProductionSegment entity);
bool CloseSegment(long id, decimal? endPartCount, decimal? quantity, string closeReason, DateTime endTime);
bool SettleByDate(DateTime date);
}
}

@ -0,0 +1,19 @@
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_screen_config 大屏卡片配置表 仓储接口
/// </summary>
public interface IScreenConfigRepository
{
List<ScreenConfig> GetAll();
List<ScreenConfig> GetEnabled();
ScreenConfig GetById(int id);
int Create(ScreenConfig entity);
bool Update(ScreenConfig entity);
bool Delete(int id);
bool ToggleEnabled(int id);
}
}

@ -0,0 +1,16 @@
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_screen_filter 大屏筛选配置表 仓储接口
/// </summary>
public interface IScreenFilterRepository
{
List<ScreenFilter> GetByScreenKey(string screenKey);
int Create(ScreenFilter entity);
bool Update(ScreenFilter entity);
bool Delete(int id);
}
}

@ -0,0 +1,22 @@
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// 系统配置仓储接口
/// </summary>
public interface ISysConfigRepository
{
/// <summary>按配置Key获取配置</summary>
SysConfig GetByKey(string configKey);
/// <summary>获取全部配置</summary>
List<SysConfig> GetAll();
/// <summary>更新配置值</summary>
/// <param name="id">配置项ID</param>
/// <param name="configValue">新值</param>
bool UpdateValue(int id, string configValue);
}
}

@ -0,0 +1,16 @@
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Log;
namespace CncRepository.Interface
{
/// <summary>
/// log_system 系统日志 仓储接口
/// </summary>
public interface ISystemLogRepository
{
PagedResult<SystemLogListItem> GetList(SystemLogQuery query);
int Create(SystemLog entity);
}
}

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// cnc_worker_daily_summary 工人日汇总表 仓储接口
/// </summary>
public interface IWorkerDailySummaryRepository
{
WorkerDailySummary GetByWorkerAndDate(int workerId, DateTime date);
List<WorkerDailySummary> GetByDateRange(DateTime startDate, DateTime endDate);
int Upsert(WorkerDailySummary entity);
}
}

@ -0,0 +1,17 @@
using System.Collections.Generic;
using CncModels.Entity;
namespace CncRepository.Interface
{
/// <summary>
/// 工人-机床绑定仓储接口
/// </summary>
public interface IWorkerMachineRepository
{
WorkerMachine GetByMachineId(int machineId);
List<WorkerMachine> GetByWorkerId(int workerId);
int Create(int workerId, int machineId);
bool DeleteByMachineId(int machineId);
bool DeleteByWorkerId(int workerId);
}
}

@ -0,0 +1,22 @@
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Worker;
namespace CncRepository.Interface
{
/// <summary>
/// 工人仓储接口
/// </summary>
public interface IWorkerRepository
{
Worker GetById(int id);
PagedResult<WorkerListItem> GetList(WorkerQuery query);
int Create(Worker entity);
bool Update(Worker entity);
bool Delete(int id);
bool ToggleEnabled(int id);
Worker GetByCode(string code);
List<Worker> GetAll();
}
}

@ -0,0 +1,21 @@
using System.Collections.Generic;
using CncModels.Entity;
using CncModels.Dto;
namespace CncRepository.Interface
{
/// <summary>
/// 车间仓储接口
/// </summary>
public interface IWorkshopRepository
{
Workshop GetById(int id);
List<Workshop> GetAll();
PagedResult<Workshop> GetList(string keyword);
int Create(Workshop entity);
bool Update(Workshop entity);
bool Delete(int id);
bool ToggleEnabled(int id);
int GetMachineCount(int workshopId);
}
}
Loading…
Cancel
Save