154 lines
9.1 KiB
C#
154 lines
9.1 KiB
C#
using FluentValidation;
|
|
using NTP.Application.Abstractions;
|
|
using NTP.Application.Common;
|
|
using NTP.Application.Grains.Orders;
|
|
using NTP.Application.Grains.Reports;
|
|
|
|
namespace NTP.Application.Refinery.Variables;
|
|
|
|
/// <summary>
|
|
/// Port of refinery_variablesfactory.cfc / refinery_variablesfactoryweb.cfc (screen REFINERY_VARIABLES, تسعير عطاء النفط الخام).
|
|
/// Access is decided only by the permission keys on the controller (SU / REFINERY_MGR); the legacy REFINERY_MGR / REFINERY_AC role branches are not ported.
|
|
/// There is no log: the legacy log call is commented out and no REFINERY_VARIABLES_LOG table exists.
|
|
/// </summary>
|
|
public sealed class VariablesService(
|
|
IVariablesRepository repository,
|
|
ITonPriceRecalculationService recalculation,
|
|
IUnitOfWork unitOfWork,
|
|
ICurrentUser user,
|
|
IReportExcelService excel,
|
|
IValidator<SaveVariablesRequest> saveValidator,
|
|
IValidator<TonPriceCorrectionRequest> correctionValidator) : IVariablesService
|
|
{
|
|
private const string ExcelType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
|
|
public Task<PagedResult<VariablesSetRow>> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct) =>
|
|
repository.SearchAsync(query, page, ct);
|
|
|
|
public async Task<VariablesSetDetail> GetAsync(long groupId, CancellationToken ct)
|
|
{
|
|
var row = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId);
|
|
var canUpdate = row.StartDate is not null && row.EndDate is not null
|
|
&& !await repository.HasTripsAsync(row.StartDate.Value, row.EndDate.Value, ct);
|
|
return new VariablesSetDetail
|
|
{
|
|
GroupId = row.GroupId, StartDate = row.StartDate, EndDate = row.EndDate, DieselLiterPrice = row.DieselLiterPrice,
|
|
TonWage = row.TonWage, TonPrice = row.TonPrice, DriverTip = row.DriverTip, PermitDispatch = row.PermitDispatch,
|
|
WaybillFee = row.WaybillFee, Commission = row.Commission, TolerancePercentage = row.TolerancePercentage,
|
|
FirstAdvancePayment = row.FirstAdvancePayment, TonPriceCorrection = row.TonPriceCorrection,
|
|
TonPriceCorrectionSet = row.TonPriceCorrectionSet,
|
|
CanUpdate = canUpdate,
|
|
CanSetTonPriceCorrection = !row.TonPriceCorrectionSet,
|
|
};
|
|
}
|
|
|
|
public async Task<VariablesResult> CreateAsync(SaveVariablesRequest request, CancellationToken ct)
|
|
{
|
|
await saveValidator.ValidateAndThrowAsync(request, ct);
|
|
var error = VariablesRules.FirstError(await repository.GetPeriodsAsync(null, ct), request);
|
|
if (error is { } e) throw new BusinessException(e.Code, e.Message);
|
|
|
|
var groupId = await unitOfWork.ExecuteInTransactionAsync(async token =>
|
|
{
|
|
var id = await repository.NextGroupIdAsync(token);
|
|
await repository.InsertSetAsync(id, request.StartDate, request.EndDate, VariablesRules.ToValues(request), user.UserId, token);
|
|
return id;
|
|
}, ct);
|
|
return new VariablesResult(VariablesMessages.Done, groupId);
|
|
}
|
|
|
|
public async Task<VariablesResult> UpdateAsync(long groupId, SaveVariablesRequest request, CancellationToken ct)
|
|
{
|
|
await saveValidator.ValidateAndThrowAsync(request, ct);
|
|
var current = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId);
|
|
var error = VariablesRules.FirstError(await repository.GetPeriodsAsync(groupId, ct), request);
|
|
if (error is { } e) throw new BusinessException(e.Code, e.Message);
|
|
|
|
// refinery_variablesfactory.cfc:162-170: the stored period must not hold a trip (checked on the dates before the change)
|
|
if (current.StartDate is not null && current.EndDate is not null
|
|
&& await repository.HasTripsAsync(current.StartDate.Value, current.EndDate.Value, ct))
|
|
throw new BusinessException(VariablesErrors.TripsExist, VariablesMessages.TripsExist);
|
|
|
|
await unitOfWork.ExecuteInTransactionAsync(async token =>
|
|
{
|
|
await repository.UpdateSetAsync(groupId, request.StartDate, request.EndDate, VariablesRules.ToValues(request), user.UserId, token);
|
|
return true;
|
|
}, ct);
|
|
return new VariablesResult(VariablesMessages.Done, groupId);
|
|
}
|
|
|
|
/// <summary>UPDATE_TON_PRICE_CORRECTION: sets the actual ton price once; the balances of the trucks are recalculated when it differs from TON_PRICE.</summary>
|
|
public async Task<VariablesResult> SetTonPriceCorrectionAsync(long groupId, TonPriceCorrectionRequest request, CancellationToken ct)
|
|
{
|
|
await correctionValidator.ValidateAndThrowAsync(request, ct);
|
|
var current = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId);
|
|
if (current.TonPriceCorrectionSet)
|
|
throw new BusinessException(VariablesErrors.CannotResetTonPrice, VariablesMessages.CannotResetTonPrice);
|
|
if (current.StartDate is null || current.EndDate is null)
|
|
throw new BusinessException(VariablesErrors.NotFound, VariablesMessages.NotFound);
|
|
|
|
await unitOfWork.ExecuteInTransactionAsync(async token =>
|
|
{
|
|
await repository.SetTonPriceCorrectionAsync(groupId, VariablesRules.FormatValue(request.TonPriceCorrection),
|
|
current.StartDate.Value, current.EndDate.Value, user.UserId, token);
|
|
// legacy: a failed recalculation resets both rows to 0 (DELETE_ON_PRICE_CORRECTION) and returns the error; here the transaction is rolled back
|
|
if (VariablesRules.TonPriceChanges(current.TonPrice, request.TonPriceCorrection))
|
|
await recalculation.RecalculateAsync(groupId, current.StartDate.Value, current.EndDate.Value, token);
|
|
return true;
|
|
}, ct);
|
|
return new VariablesResult(VariablesMessages.Done, groupId);
|
|
}
|
|
|
|
// ------------------------------------------------------------------ reports (Excel)
|
|
|
|
public async Task<ExportFile> ExportAsync(VariablesQuery query, CancellationToken ct)
|
|
{
|
|
var rows = new List<VariablesSetRow>();
|
|
for (var p = 1; rows.Count < 20000; p++)
|
|
{
|
|
var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct);
|
|
rows.AddRange(r.Items);
|
|
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
|
|
}
|
|
var cols = new List<ReportColumn>
|
|
{
|
|
new("startDate", "بداية فترة التسعير", "Start", "date"), new("endDate", "نهاية فترة التسعير", "End", "date"),
|
|
new("dieselLiterPrice", "سعر لتر الديزل", "Diesel liter price"), new("tonWage", "اجور الطن", "Ton wage"),
|
|
new("tonPrice", "سعر الطن", "Ton price"), new("driverTip", "اكرامية السائق", "Driver tip"),
|
|
new("permitDispatch", "سعر تسريب الصهريج", "Permit dispatch"), new("waybillFee", "اصدار وثيقة", "Waybill fee"),
|
|
new("commission", "عمولة الصرف التنافسي", "Commission"), new("tolerancePercentage", "نسبة السماح", "Tolerance"),
|
|
new("firstAdvancePayment", "قيمة شحن الديزل للتحميل", "First advance payment"),
|
|
};
|
|
var data = rows.Select(r => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
|
|
{
|
|
["startDate"] = r.StartDate, ["endDate"] = r.EndDate, ["dieselLiterPrice"] = r.DieselLiterPrice, ["tonWage"] = r.TonWage,
|
|
["tonPrice"] = r.TonPrice, ["driverTip"] = r.DriverTip, ["permitDispatch"] = r.PermitDispatch, ["waybillFee"] = r.WaybillFee,
|
|
["commission"] = r.Commission, ["tolerancePercentage"] = r.TolerancePercentage, ["firstAdvancePayment"] = r.FirstAdvancePayment,
|
|
}).ToList();
|
|
return Build("REFINERY_VARIABLES", "تسعير عطاء النفط الخام", "Crude oil tender pricing", cols, data);
|
|
}
|
|
|
|
/// <summary>refineryRemainingBalanceReport: REFINERY_REMAINING_BALANCE ordered by balance, biggest first.</summary>
|
|
public async Task<ExportFile> ExportRemainingBalanceAsync(CancellationToken ct)
|
|
{
|
|
var rows = await repository.GetRemainingBalancesAsync(ct);
|
|
var cols = new List<ReportColumn>
|
|
{
|
|
new("counter", "متسلسل", "#"), new("tn", "رقم الشاحنة", "Truck"), new("remainingBalance", "قيمة الذمم السابقة", "Previous balance"),
|
|
};
|
|
var n = 0;
|
|
var data = rows.Select(r => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
|
|
{
|
|
["counter"] = ++n, ["tn"] = r.Tn, ["remainingBalance"] = r.RemainingBalance,
|
|
}).ToList();
|
|
return Build("REMAINING_BALANCE", "قيمة الذمم السابقة", "Previous balance", cols, data);
|
|
}
|
|
|
|
private ExportFile Build(string key, string titleAr, string titleEn, IReadOnlyList<ReportColumn> cols, IReadOnlyList<IReadOnlyDictionary<string, object?>> rows)
|
|
{
|
|
var table = new ReportTable { Key = key, TitleAr = titleAr, TitleEn = titleEn, Columns = cols, Rows = rows };
|
|
var bytes = excel.Build(table, user.UserId, DateTime.Now, true);
|
|
return new ExportFile(bytes, ExcelType, key + ".xlsx");
|
|
}
|
|
}
|