
using Dapper;
using FastEndpoints;
using Npgsql;
namespace KBX.Modules.OMS.Claims.Search;
public sealed record Request(DateOnly? From, DateOnly? To, string? Type, string? Status, string? Keyword, int Page = 1, int PageSize = 100);
public sealed record Row(Guid Id,string ClaimNo,string OrderNo,string ChannelName,string Type,string Reason,decimal RequestedQty,string Status,string? OwnerName,DateTimeOffset RequestedAt);
public sealed record Response(IReadOnlyList<Row> Items,long TotalCount);
public sealed class Endpoint(NpgsqlDataSource db) : Endpoint<Request,Response>
{
 public override void Configure(){Get("/api/oms/claims");Permissions("oms.claim.read");}
 public override async Task HandleAsync(Request req,CancellationToken ct){await using var c=await db.OpenConnectionAsync(ct); const string where=""" from oms.claim_search_projection where (@From is null or requested_at>=@From) and (@To is null or requested_at<@To+1) and (@Type is null or type=@Type) and (@Status is null or status=@Status) and (@Keyword is null or claim_no ilike '%'||@Keyword||'%' or order_no ilike '%'||@Keyword||'%') """; var items=(await c.QueryAsync<Row>(new CommandDefinition("select id,claim_no ClaimNo,order_no OrderNo,channel_name ChannelName,type,reason,requested_qty RequestedQty,status,owner_name OwnerName,requested_at RequestedAt"+where+" order by requested_at desc limit @PageSize offset @Offset",new {req.From,req.To,req.Type,req.Status,req.Keyword,req.PageSize,Offset=(req.Page-1)*req.PageSize},cancellationToken:ct))).AsList(); var total=await c.ExecuteScalarAsync<long>(new CommandDefinition("select count(*)"+where,req,cancellationToken:ct)); await SendOkAsync(new(items,total),ct); }
}
