From dc72cf2869a6659315b59bf1307771a09d46666d Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Tue, 24 Nov 2026 12:03:32 +0300 Subject: [PATCH] =?UTF-8?q?Refinery=20wage=20claims:=20the=20claim=20scree?= =?UTF-8?q?n=20=D8=AA=D8=B3=D8=AF=D9=8A=D8=AF=20keeps=20the=20legacy=20clo?= =?UTF-8?q?se=20(trips=20COMPLETE);=20the=20grid=20action=20only=20changes?= =?UTF-8?q?=20the=20claim=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- .../V1/Refinery/WageClaimsController.cs | 5 ++++ .../WageClaims/IWageClaimRepository.cs | 3 +++ .../Refinery/WageClaims/WageClaimRules.cs | 7 ++++++ .../Refinery/WageClaims/WageClaimService.cs | 23 ++++++++++++++++-- .../WageClaims/WageClaimRepository.cs | 21 ++++++++++++++++ .../NTP.Tests/Refinery/WageClaimRulesTests.cs | 9 +++++++ .../Refinery/WageClaimServiceTests.cs | 24 +++++++++++++++++-- web/src/features/refinery/wage-claims/api.ts | 4 +++- .../features/refinery/wage-claims/pages.tsx | 8 +++---- .../features/refinery/wage-claims/strings.ts | 3 ++- 10 files changed, 97 insertions(+), 10 deletions(-) diff --git a/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs b/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs index 9a906f9..d522588 100644 --- a/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs +++ b/src/NTP.Api/Controllers/V1/Refinery/WageClaimsController.cs @@ -63,6 +63,11 @@ public sealed class WageClaimsController(IWageClaimService claims) : ControllerB [RequirePermission(PermissionKeys.RefineryWageClaimsClose)] public Task Close(long id, CancellationToken ct) => claims.CloseAsync(id, Ip, ct); + /// Grid status change NEW -> CLOSE: only the claim record, trips untouched. Same permission as the close. + [HttpPost("{id:long}/status-close")] + [RequirePermission(PermissionKeys.RefineryWageClaimsClose)] + public Task StatusClose(long id, CancellationToken ct) => claims.SetClosedAsync(id, Ip, ct); + /// Reopen (CLOSE -> NEW): new action of this system, same permission as the close. [HttpPost("{id:long}/reopen")] [RequirePermission(PermissionKeys.RefineryWageClaimsClose)] diff --git a/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs b/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs index 9d2ebce..58f0080 100644 --- a/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs +++ b/src/NTP.Application/Refinery/WageClaims/IWageClaimRepository.cs @@ -28,6 +28,9 @@ public interface IWageClaimRepository Task InsertClaimAsync(string createdBy, CancellationToken ct = default); Task AttachTripsAsync(long claimId, IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default); + Task> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default); + /// TRIP_COMPLETE for every trip of the claim: status COMPLETE plus one REFINERY_TRIPS_LOG row each. Returns the number of trips. + Task CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default); /// STATUS_CODE of a commission claim (null when it does not exist). Task CommissionClaimStatusAsync(long commissionClaimId, CancellationToken ct = default); Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default); diff --git a/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs b/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs index dbfc66e..c58b20d 100644 --- a/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs +++ b/src/NTP.Application/Refinery/WageClaims/WageClaimRules.cs @@ -58,6 +58,13 @@ public static class WageClaimRules if (from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo); } + /// factory.CLAIM_CLOSE: a claim is paid only when it has trips and every one of them is EXCHANGED. + public static bool CanCloseClaim(IEnumerable tripStatuses) + { + var distinct = tripStatuses.Distinct().ToList(); + return distinct.Count == 1 && distinct[0] == "EXCHANGED"; + } + /// factory.TRANSFER: the Jopetrol answer must contain this text (findNoCase) for the trip to move to TRIP_STATUS 7. public static bool IsStatus7Success(string? serviceAnswer) => serviceAnswer is not null && serviceAnswer.Contains("Status Updated successfully To 7", StringComparison.OrdinalIgnoreCase); diff --git a/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs b/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs index 7b32796..36507eb 100644 --- a/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs +++ b/src/NTP.Application/Refinery/WageClaims/WageClaimService.cs @@ -24,6 +24,7 @@ public interface IWageClaimService Task> LogAsync(long id, PageRequest page, CancellationToken ct); Task CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct); Task CloseAsync(long id, string? ip, CancellationToken ct); + Task SetClosedAsync(long id, string? ip, CancellationToken ct); Task ReopenAsync(long id, string? ip, CancellationToken ct); Task TransferAsync(long id, string? ip, CancellationToken ct); Task ExportAsync(long id, CancellationToken ct); @@ -82,14 +83,32 @@ public sealed class WageClaimService(IWageClaimRepository repo, IUnitOfWork unit return new ClaimResult(ClaimMessages.Success, id); } - /// factory.CLAIM_CLOSE (تسديد): NEW claim -> CLOSE (+ log). Only the claim record changes, the trips keep their status. + /// factory.CLAIM_CLOSE (تسديد, claim screen): NEW claim whose trips are all EXCHANGED -> trips COMPLETE (+ trip log), claim CLOSE (+ log). public async Task CloseAsync(long id, string? ip, CancellationToken ct) + { + var claim = await GetAsync(id, ct); + if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority); + await EnsureCommissionNewAsync(claim, ct); + if (!WageClaimRules.CanCloseClaim(await repo.ClaimTripStatusesAsync(id, ct))) + throw new BusinessException("CLOSE_CLAIM", ClaimMessages.CloseClaim); + + await unit.ExecuteInTransactionAsync(async c => + { + await repo.CompleteClaimTripsAsync(id, user.UserId, user.Id, ip, c); + await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c); + await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusClose), user.Id, ip, c); + return 0; + }, ct); + return new ClaimResult(ClaimMessages.Success, id); + } + + /// Grid status change NEW -> CLOSE: only the REFINERY_WAGE_CLAIM record (+ log); the trips keep their status. + public async Task SetClosedAsync(long id, string? ip, CancellationToken ct) { var claim = await GetAsync(id, ct); if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority); await EnsureCommissionNewAsync(claim, ct); - // only the claim record changes: the trips (permits) keep their status await unit.ExecuteInTransactionAsync(async c => { await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c); diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs index 44bad9a..4e478b5 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Refinery/WageClaims/WageClaimRepository.cs @@ -122,6 +122,27 @@ internal sealed class WageClaimRepository(IDbSession session, ILogger> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default) => + await QueryAsync("SELECT DISTINCT STATUS_CODE FROM REFINERY_TRIPS WHERE WAGE_CLAIM_ID = :ClaimId", new { ClaimId = claimId }, ct); + + public async Task CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default) + { + // logs.saveLog(session, 'REFINERYTRIP', 'TRIP_COMPLETE', ...): old/new status captions, ids from SEQ_REFINERY_TRIPS_LOG + await ExecuteAsync(""" + INSERT INTO REFINERY_TRIPS_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA) + SELECT SEQ_REFINERY_TRIPS_LOG.NEXTVAL, t.ID, 'TRIP_COMPLETE', SYSDATE, :UserId, :Ip, :OldData, :NewData + FROM REFINERY_TRIPS t WHERE t.WAGE_CLAIM_ID = :ClaimId + """, new + { + UserId = userId.ToString(System.Globalization.CultureInfo.InvariantCulture), Ip = Cut(ip, 50), ClaimId = claimId, + OldData = ClaimLogJson.Status(ClaimMessages.TripExchanged), NewData = ClaimLogJson.Status(ClaimMessages.TripComplete), + }, ct); + return await ExecuteAsync(""" + UPDATE REFINERY_TRIPS SET STATUS_CODE = 'COMPLETE', LAST_UPDATE_DATE = SYSDATE, UPDATED_BY = :UserLogin + WHERE WAGE_CLAIM_ID = :ClaimId + """, new { UserLogin = userLogin, ClaimId = claimId }, ct); + } + public async Task CommissionClaimStatusAsync(long commissionClaimId, CancellationToken ct = default) => (await QueryAsync("SELECT STATUS_CODE FROM REFINERY_COMMISSION_CLAIM WHERE ID = :Id", new { Id = commissionClaimId }, ct)).FirstOrDefault(); diff --git a/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs b/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs index 384e538..75668c3 100644 --- a/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs +++ b/tests/NTP.Tests/Refinery/WageClaimRulesTests.cs @@ -29,6 +29,15 @@ public class WageClaimRulesTests WageClaimRules.ValidateCreate(ok, from, to); } + [Fact] + public void Claim_closes_only_when_it_has_trips_and_all_are_exchanged() + { + Assert.True(WageClaimRules.CanCloseClaim(["EXCHANGED", "EXCHANGED"])); + Assert.False(WageClaimRules.CanCloseClaim([])); + Assert.False(WageClaimRules.CanCloseClaim(["EXCHANGED", "DISCHARGED"])); + Assert.False(WageClaimRules.CanCloseClaim(["READY_TO_PAY"])); + } + [Theory] [InlineData("Status Updated successfully To 7", true)] [InlineData("OK: status updated SUCCESSFULLY to 7 for 123", true)] diff --git a/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs b/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs index a394528..372e341 100644 --- a/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs +++ b/tests/NTP.Tests/Refinery/WageClaimServiceTests.cs @@ -54,6 +54,7 @@ public class WageClaimServiceTests public List ToTransfer = []; public int Candidates = 5; public long? CommissionId; + public List TripStatuses = ["EXCHANGED"]; public string? CommissionStatus = "NEW"; public readonly List Writes = []; @@ -65,6 +66,8 @@ public class WageClaimServiceTests public Task CountCandidateTripsAsync(IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default) => Task.FromResult(Candidates); public Task InsertClaimAsync(string createdBy, CancellationToken ct = default) { Writes.Add("insert:" + createdBy); return Task.FromResult(9L); } public Task AttachTripsAsync(long claimId, IReadOnlyList statuses, DateOnly from, DateOnly to, CancellationToken ct = default) { Writes.Add("attach:" + claimId + ":" + string.Join('+', statuses)); return Task.FromResult(Candidates); } + public Task> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default) => Task.FromResult>(TripStatuses); + public Task CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default) { Writes.Add("tripsComplete:" + userLogin + ":" + userId); return Task.FromResult(1); } public Task CommissionClaimStatusAsync(long commissionClaimId, CancellationToken ct = default) => Task.FromResult(CommissionStatus); public Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default) { Writes.Add("status:" + status); return Task.CompletedTask; } public Task> TripsToTransferAsync(long claimId, CancellationToken ct = default) => Task.FromResult>(ToTransfer); @@ -98,10 +101,10 @@ public class WageClaimServiceTests } [Fact] - public async Task Close_changes_only_the_claim_and_logs_it() + public async Task Grid_status_close_changes_only_the_claim_and_logs_it() { var repo = new FakeRepo(); - await Service(repo).CloseAsync(5, null, default); + await Service(repo).SetClosedAsync(5, null, default); Assert.Equal(["status:CLOSE", "log:CLAIM_CLOSE:{\"STATUS_CODE\":\"جديد\"}:{\"STATUS_CODE\":\"تم التسديد\"}"], repo.Writes); } @@ -179,6 +182,23 @@ public class WageClaimServiceTests Assert.Empty(close.Writes); } + [Fact] + public async Task Claim_screen_close_completes_the_trips_and_the_claim() + { + var repo = new FakeRepo(); + await Service(repo).CloseAsync(5, null, default); + Assert.Equal(["tripsComplete:TESTER:77", "status:CLOSE", "log:CLAIM_CLOSE:{\"STATUS_CODE\":\"جديد\"}:{\"STATUS_CODE\":\"تم التسديد\"}"], repo.Writes); + } + + [Fact] + public async Task Claim_screen_close_is_refused_while_a_trip_is_not_exchanged() + { + var repo = new FakeRepo { TripStatuses = ["EXCHANGED", "DISCHARGED"] }; + var ex = await Assert.ThrowsAsync(() => Service(repo).CloseAsync(5, null, default)); + Assert.Contains("جاهز للدفع او تم التفريغ", ex.Message); + Assert.Empty(repo.Writes); + } + [Fact] public async Task Close_and_transfer_need_a_new_claim() { diff --git a/web/src/features/refinery/wage-claims/api.ts b/web/src/features/refinery/wage-claims/api.ts index fc1c820..743747f 100644 --- a/web/src/features/refinery/wage-claims/api.ts +++ b/web/src/features/refinery/wage-claims/api.ts @@ -45,7 +45,7 @@ export function useCreateWageClaim() { } /** After close / transfer the claim, its trips and its log change. */ -function useClaimAction(action: 'close' | 'transfer' | 'reopen') { +function useClaimAction(action: 'close' | 'transfer' | 'reopen' | 'status-close') { const qc = useQueryClient(); return useWrite((id: number) => api.post(`${BASE}/${id}/${action}`), { invalidate: [gridKey(GRID_WAGE_CLAIMS)], @@ -57,5 +57,7 @@ function useClaimAction(action: 'close' | 'transfer' | 'reopen') { }); } export const useCloseWageClaim = () => useClaimAction('close'); +/** Grid action: only the claim status changes, the trips are not touched. */ +export const useSetClosedWageClaim = () => useClaimAction('status-close'); export const useReopenWageClaim = () => useClaimAction('reopen'); export const useTransferWageClaim =() => useClaimAction('transfer'); diff --git a/web/src/features/refinery/wage-claims/pages.tsx b/web/src/features/refinery/wage-claims/pages.tsx index ffaf887..811dc1e 100644 --- a/web/src/features/refinery/wage-claims/pages.tsx +++ b/web/src/features/refinery/wage-claims/pages.tsx @@ -19,7 +19,7 @@ import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { downloadFile } from '../../grains-orders/api'; import { - BASE, useCandidateTrips, useClaimTrips, useCloseWageClaim, useCreateWageClaim, useReopenWageClaim, useTransferWageClaim, useWageClaim, + BASE, useCandidateTrips, useClaimTrips, useCloseWageClaim, useCreateWageClaim, useReopenWageClaim, useSetClosedWageClaim, useTransferWageClaim, useWageClaim, } from './api'; import { Block, ClaimLogSection, TripsTable } from './components'; import { claimableTripStatuses, claimStatuses, tripStatusLabelKey, wageClaimGrid } from './meta'; @@ -33,14 +33,14 @@ export function WageClaimsPage() { const { can } = useAuth(); const navigate = useNavigate(); const confirm = useConfirm(); - const close = useCloseWageClaim(); + const setClosed = useSetClosedWageClaim(); const reopen = useReopenWageClaim(); const canChange = can('refinery.wageClaims.close'); const meta = useMemo(() => wageClaimGrid((r) => navigate(`${ROOT}/${r.id}`), { canChange, - onClose: async (r) => { if (await confirm({ message: t('wc.closeConfirm') })) close.mutate(r.id); }, + onClose: async (r) => { if (await confirm({ message: t('wc.statusCloseConfirm') })) setClosed.mutate(r.id); }, onReopen: async (r) => { if (await confirm({ message: t('wc.reopenConfirm') })) reopen.mutate(r.id); }, - }), [navigate, canChange, confirm, close, reopen, t]); + }), [navigate, canChange, confirm, setClosed, reopen, t]); return ( <>