using Dapper;using FastEndpoints;using Npgsql;using Shared.Problems;
namespace Modules.OMS.Orders.Get;
public sealed record OrderLine(Guid Id,string ClientId,Guid ItemId,string ItemCode,string ItemName,decimal OrderQty,decimal UnitPrice,decimal Amount,string Remark);
public sealed record Response(Guid OrderId,string OrderNo,long Version,string Status,DateOnly OrderDate,Guid CustomerId,Guid WarehouseId,string ReceiverName,string Phone,string? PostalCode,string Address1,string? Address2,IReadOnlyList<OrderLine> Lines);
public sealed class Endpoint(NpgsqlDataSource dataSource):EndpointWithoutRequest<Response>{public override void Configure(){Get("/api/oms/orders/{id}");Permissions("oms.order.read");}public override async Task HandleAsync(CancellationToken ct){var id=Route<Guid>("id");await using var c=await dataSource.OpenConnectionAsync(ct);var h=await c.QuerySingleOrDefaultAsync(new CommandDefinition("select id as OrderId,order_no as OrderNo,version,status,order_date as OrderDate,customer_id as CustomerId,warehouse_id as WarehouseId,receiver_name as ReceiverName,phone,postal_code as PostalCode,address1,address2 from oms.orders where id=@Id",new{Id=id},cancellationToken:ct));if(h is null){await Send.ResponseAsync(KbxNotFoundProblem.Create("ORDER_NOT_FOUND","주문을 찾을 수 없습니다."),404,cancellation:ct);return;}var lines=(await c.QueryAsync<OrderLine>(new CommandDefinition(@"select l.id,l.id::text as ClientId,l.item_id as ItemId,i.code as ItemCode,i.name as ItemName,l.quantity as OrderQty,l.unit_price as UnitPrice,l.amount,coalesce(l.remark,'') as Remark from oms.order_lines l join catalog.items i on i.id=l.item_id where l.order_id=@Id order by l.line_no",new{Id=id},cancellationToken:ct))).AsList();await Send.OkAsync(new((Guid)h.orderid,(string)h.orderno,(long)h.version,(string)h.status,(DateOnly)h.orderdate,(Guid)h.customerid,(Guid)h.warehouseid,(string)h.receivername,(string)h.phone,(string?)h.postalcode,(string)h.address1,(string?)h.address2,lines),ct);}}
