Registry exports, ratios report as legacy Excel, RED_SEA distribution, UI fixes

- Trucks / trailers / drivers Excel export, allowed only by DB permission keys grains.registry.*.export (db/registry-export-permissions.sql)
- Bulk order ratios report: CSV removed, legacy HTML-table Excel, added to the Reports menu, cleaner layout
- Distribution: new category RED_SEA (البحر الأحمر)
- Tender order: shift optional, loading site and destination searchable
- Supply order shows company number; chassis number hidden in registry grids
- Change password: rules shown, validation messages translated and detailed
- Menu: Finance first, "الطلبيات"; toast auto-hide shortened

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-18 14:21:57 +03:00
parent e03179917f
commit 0eb83d3bb5
29 changed files with 299 additions and 71 deletions

View File

@ -0,0 +1,34 @@
-- Registry Excel export rights (NAFITHTCS schema): who sees the "تصدير Excel" button of the trucks, trailers and drivers lists.
-- The application has NO role list for this: only these rows decide (SU always may). Safe to re-run: a row is only inserted
-- when it is not there yet. Not executed by the application.
--
-- Starting values copy the legacy screens (truckGrid.cfm / driverGrid.cfm):
-- trucks, trailers : GTO, GOO, GNAC (+ CO, which has the same rights as GTO)
-- drivers : GTO, GOO (+ CO)
--
-- To take a right away, delete the row; the API applies it within about a minute (permissions are cached per role for 60 seconds)
-- and the user's browser picks it up on the next page reload or sign-in.
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
SELECT v.rolecode, v.resource_key
FROM (
SELECT 'GTO' AS rolecode, 'grains.registry.trucks.export' AS resource_key FROM dual UNION ALL
SELECT 'GOO', 'grains.registry.trucks.export' FROM dual UNION ALL
SELECT 'GNAC', 'grains.registry.trucks.export' FROM dual UNION ALL
SELECT 'CO', 'grains.registry.trucks.export' FROM dual UNION ALL
SELECT 'GTO', 'grains.registry.trailers.export' FROM dual UNION ALL
SELECT 'GOO', 'grains.registry.trailers.export' FROM dual UNION ALL
SELECT 'GNAC', 'grains.registry.trailers.export' FROM dual UNION ALL
SELECT 'CO', 'grains.registry.trailers.export' FROM dual UNION ALL
SELECT 'GTO', 'grains.registry.drivers.export' FROM dual UNION ALL
SELECT 'GOO', 'grains.registry.drivers.export' FROM dual UNION ALL
SELECT 'CO', 'grains.registry.drivers.export' FROM dual
) v
WHERE NOT EXISTS (
SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p
WHERE p.rolecode = v.rolecode AND p.resource_key = v.resource_key);
COMMIT;
-- Check (expect 11 rows):
-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE resource_key LIKE 'grains.registry.%.export' ORDER BY 2, 1;

View File

@ -50,6 +50,7 @@ Apply these scripts once per database (not run by the application), in this orde
1. `db/grains-screen-permissions.sql` - role to screen/action permissions (`GRAINS_SCREEN_PERMISSIONS`) 1. `db/grains-screen-permissions.sql` - role to screen/action permissions (`GRAINS_SCREEN_PERMISSIONS`)
2. `db/registry-create-permissions.sql` - add / edit rights of trucks, trailers and drivers (safe to re-run) 2. `db/registry-create-permissions.sql` - add / edit rights of trucks, trailers and drivers (safe to re-run)
2b. `db/registry-export-permissions.sql` - Excel export rights of the trucks, trailers and drivers lists (`grains.registry.*.export`; without rows nobody but SU sees the button) (safe to re-run)
3. `db/disabled-features.sql` - features switched OFF for everybody, SU included (safe to re-run) 3. `db/disabled-features.sql` - features switched OFF for everybody, SU included (safe to re-run)
4. `db/permits-create-permission.sql` - right to register a turn (تسجيل دور) from the permits list, granted to GOO (safe to re-run) 4. `db/permits-create-permission.sql` - right to register a turn (تسجيل دور) from the permits list, granted to GOO (safe to re-run)
5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run) 5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run)

View File

@ -234,12 +234,12 @@ public sealed class OrderReportsController(IOrderReportService reports) : Contro
public Task<TenderOrderReportDto> TenderOrders([FromQuery] DateTime orderDate, CancellationToken ct) => public Task<TenderOrderReportDto> TenderOrders([FromQuery] DateTime orderDate, CancellationToken ct) =>
reports.GetTenderOrderReportAsync(orderDate, ct); reports.GetTenderOrderReportAsync(orderDate, ct);
/// format: csv (default) or xlsx. /// Legacy Excel (HTML table) of the distribution ratios.
[HttpGet("tender-orders/export")] [HttpGet("tender-orders/export")]
[RequirePermission(PermissionKeys.OrdersReportOrders)] [RequirePermission(PermissionKeys.OrdersReportOrders)]
public async Task<IActionResult> ExportTenderOrders([FromQuery] DateTime orderDate, [FromQuery] string format = "csv", CancellationToken ct = default) public async Task<IActionResult> ExportTenderOrders([FromQuery] DateTime orderDate, CancellationToken ct = default)
{ {
var f = await reports.ExportTenderOrderReportAsync(orderDate, format, ct); var f = await reports.ExportTenderOrderReportAsync(orderDate, ct);
return File(f.Content, f.ContentType, f.FileName); return File(f.Content, f.ContentType, f.FileName);
} }

View File

@ -25,7 +25,8 @@ public sealed class RegistryController(
IRegistryOpsService ops, IRegistryOpsService ops,
IRegistryLookupService lookups, IRegistryLookupService lookups,
IRegistryAttachmentService attachments, IRegistryAttachmentService attachments,
IRegistryQueuePermitService queuePermits) : ControllerBase IRegistryQueuePermitService queuePermits,
IRegistryExportService exports) : ControllerBase
{ {
// ------------------------------------------------------------------------------------------ permissions + lookups // ------------------------------------------------------------------------------------------ permissions + lookups
@ -67,6 +68,33 @@ public sealed class RegistryController(
[FromQuery] string? headType, [FromQuery] long? tcscac, [FromQuery] int page = 1, [FromQuery] int pageSize = 15, CancellationToken ct = default) => [FromQuery] string? headType, [FromQuery] long? tcscac, [FromQuery] int page = 1, [FromQuery] int pageSize = 15, CancellationToken ct = default) =>
trucks.SearchAsync(new TruckListQuery(searchType, tn, chasesNumber, statusCode, headType, tcscac), new PageRequest(page, pageSize), ct); trucks.SearchAsync(new TruckListQuery(searchType, tn, chasesNumber, statusCode, headType, tcscac), new PageRequest(page, pageSize), ct);
/// <summary>Excel of the filtered truck / trailer list (legacy openTruckReportExcel; right from GRAINS_SCREEN_PERMISSIONS).</summary>
[HttpGet("trucks/export")]
[RequirePermission(PermissionKeys.RegistryTrucksExport)]
public async Task<IActionResult> ExportTrucks([FromQuery] string? searchType, [FromQuery] string? tn, [FromQuery] string? chasesNumber, [FromQuery] string? statusCode,
[FromQuery] string? headType, [FromQuery] long? tcscac, CancellationToken ct)
{
var f = await exports.ExportTrucksAsync(new TruckListQuery(searchType, tn, chasesNumber, statusCode, headType, tcscac), ct);
return File(f.Content, f.ContentType, f.FileName);
}
[HttpGet("trailers/export")]
[RequirePermission(PermissionKeys.RegistryTrailersExport)]
public async Task<IActionResult> ExportTrailers([FromQuery] string? tn, [FromQuery] string? chasesNumber, [FromQuery] string? statusCode, [FromQuery] long? tcscac, CancellationToken ct)
{
var f = await exports.ExportTrailersAsync(new TrailerListQuery(tn, chasesNumber, statusCode, tcscac), ct);
return File(f.Content, f.ContentType, f.FileName);
}
/// <summary>Excel of the filtered driver list (legacy openDriversReportExcel; right from GRAINS_SCREEN_PERMISSIONS).</summary>
[HttpGet("drivers/export")]
[RequirePermission(PermissionKeys.RegistryDriversExport)]
public async Task<IActionResult> ExportDrivers([FromQuery] string? nnpn, [FromQuery] string? name, [FromQuery] string? statusCode, CancellationToken ct)
{
var f = await exports.ExportDriversAsync(new DriverListQuery(nnpn, name, statusCode), ct);
return File(f.Content, f.ContentType, f.FileName);
}
/// <summary>getTruckInfo (+ connected trailer, destinations, attachments).</summary> /// <summary>getTruckInfo (+ connected trailer, destinations, attachments).</summary>
[HttpGet("trucks/{id:long}")] [HttpGet("trucks/{id:long}")]
[RequirePermission(PermissionKeys.RegistryTrucks)] [RequirePermission(PermissionKeys.RegistryTrucks)]

View File

@ -57,7 +57,7 @@ internal sealed class GlobalExceptionHandler(
private static (int Status, string Title, string? Detail, IDictionary<string, string[]>? Errors) Map(Exception ex) => private static (int Status, string Title, string? Detail, IDictionary<string, string[]>? Errors) Map(Exception ex) =>
ex switch ex switch
{ {
ValidationException v when v.Errors.Any() => (400, "Validation failed", null, ValidationException v when v.Errors.Any() => (400, "Validation failed", string.Join(" - ", v.Errors.Select(e => e.ErrorMessage).Distinct()),
v.Errors.GroupBy(e => e.PropertyName) v.Errors.GroupBy(e => e.PropertyName)
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray())), .ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray())),
ValidationException v => (400, "Validation failed", v.Message, null), ValidationException v => (400, "Validation failed", v.Message, null),

View File

@ -47,6 +47,11 @@ public static class PermissionKeys
public const string RegistryTrucksEdit = "grains.registry.trucks.edit"; public const string RegistryTrucksEdit = "grains.registry.trucks.edit";
public const string RegistryTrailersEdit = "grains.registry.trailers.edit"; public const string RegistryTrailersEdit = "grains.registry.trailers.edit";
// Actions: Excel export of the trucks / trailers / drivers lists. Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS (SU always).
public const string RegistryTrucksExport = "grains.registry.trucks.export";
public const string RegistryTrailersExport = "grains.registry.trailers.export";
public const string RegistryDriversExport = "grains.registry.drivers.export";
// Actions / sub-screens of the permits module that have no menu entry of their own // Actions / sub-screens of the permits module that have no menu entry of their own
public const string PermitsClose = "grains.permits.close"; // legacy arrivalTruck.cfm public const string PermitsClose = "grains.permits.close"; // legacy arrivalTruck.cfm
public const string PermitsTruckOrder = "grains.permits.truckOrder"; // legacy processOpenPermit.cfm public const string PermitsTruckOrder = "grains.permits.truckOrder"; // legacy processOpenPermit.cfm

View File

@ -15,9 +15,9 @@ public sealed class ChangePasswordRequestValidator : AbstractValidator<ChangePas
{ {
public ChangePasswordRequestValidator() public ChangePasswordRequestValidator()
{ {
RuleFor(x => x.OldPassword).NotEmpty().MaximumLength(200); RuleFor(x => x.OldPassword).NotEmpty().WithMessage("الرجاء إدخال كلمة السر الحالية").MaximumLength(200);
// login keeps accepting every existing password; only a NEW password has to be reasonably strong // login keeps accepting every existing password; only a NEW password has to be reasonably strong
RuleFor(x => x.NewPassword).NotEmpty().MaximumLength(200) RuleFor(x => x.NewPassword).NotEmpty().WithMessage("الرجاء إدخال كلمة السر الجديدة").MaximumLength(200)
.MinimumLength(8).WithMessage("كلمة السر يجب ألا تقل عن 8 خانات") .MinimumLength(8).WithMessage("كلمة السر يجب ألا تقل عن 8 خانات")
.Must(p => p is not null && p.Any(char.IsLetter) && p.Any(char.IsDigit)).WithMessage("كلمة السر يجب أن تحتوي على أحرف وأرقام") .Must(p => p is not null && p.Any(char.IsLetter) && p.Any(char.IsDigit)).WithMessage("كلمة السر يجب أن تحتوي على أحرف وأرقام")
.Must((r, p) => p != r.OldPassword).WithMessage("كلمة السر الجديدة يجب أن تختلف عن القديمة"); .Must((r, p) => p != r.OldPassword).WithMessage("كلمة السر الجديدة يجب أن تختلف عن القديمة");

View File

@ -7,7 +7,8 @@ namespace NTP.Application.Grains.Orders;
public interface IOrderReportService public interface IOrderReportService
{ {
Task<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct); Task<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct); /// <summary>The legacy tenderOrderReport_xls.cfm Excel (an HTML table opened by Excel).</summary>
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct); Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct);
/// <summary>The legacy FinancialBilling.cfm Excel (an HTML table opened by Excel), byte for byte the same layout.</summary> /// <summary>The legacy FinancialBilling.cfm Excel (an HTML table opened by Excel), byte for byte the same layout.</summary>
@ -62,30 +63,40 @@ public sealed class OrderReportService(IOrderReportRepository repository, ICurre
destRows.Sum(x => x.Individuals), destRows.Sum(x => x.Companies)); destRows.Sum(x => x.Individuals), destRows.Sum(x => x.Companies));
} }
public async Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct) /// <summary>Legacy tenderOrderReport_xls.cfm: an HTML table opened by Excel, same layout and texts.</summary>
public async Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, CancellationToken ct)
{ {
var r = await GetTenderOrderReportAsync(orderDate, ct); var r = await GetTenderOrderReportAsync(orderDate, ct);
string TypeLabel(string? t) => t switch static string E(object? v) => System.Net.WebUtility.HtmlEncode(Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty);
{ static string TypeLabel(string? t) => t switch { TenderOrderType.Individuals => "افراد", TenderOrderType.Company => "شركات", _ => string.Empty };
TenderOrderType.Individuals => L("افراد", "Individuals"),
TenderOrderType.Company => L("شركات", "Companies"),
_ => string.Empty
};
var title = new[] { L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), L("نسب التوزيع في طلبيات السائب", "Distribution ratios of bulk orders"), $"{L("تاريخ الطلبية", "Order date")}: {r.OrderDate}" }; var h = new System.Text.StringBuilder();
var t1 = new ExportTable(title, h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
[L("افراد \\ شركات", "Individuals / Companies"), L("العدد", "Count"), L("النسبة", "Ratio")], h.Append("<style>.header{font-weight:bold;font-size:28px;}");
r.ByType.Select(x => (IReadOnlyList<object?>)new object?[] { TypeLabel(x.Type), x.Quantity, x.Percent }).ToList(), h.Append(".sub_header{font-weight:bold;font-size:14px;text-align:right;width:80px;background-color:#034878;color:#FFFFFF;text-align:center;}");
[L("المجموع", "Total"), r.TypeTotal, "100%"]); h.Append(".footer{background-color:#034878;color:#FFFFFF;font-weight:bold;}</style>");
h.Append("<table border=\"2\" bordercolor=\"#034878\"><tr><td><table align=\"center\" dir=\"rtl\" border=\"1\">");
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"6\" align=\"center\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"6\" align=\"center\" class=\"header\"> نسب التوزيع في طلبيات السائب</td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\"><td class=\"sub_header\">افراد \\ شركات</td><td class=\"sub_header\">العدد</td><td class=\"sub_header\">النسبة</td></tr>");
foreach (var x in r.ByType)
h.Append($"<tr align=\"center\" dir=\"rtl\"><td>{TypeLabel(x.Type)}</td><td>{E(x.Quantity)}</td><td>{E(x.Percent)}</td></tr>");
h.Append($"<tr align=\"center\" dir=\"rtl\"><td>المجموع</td><td>{E(r.TypeTotal)}</td><td>100%</td></tr>");
h.Append("<tr><td colspan=\"6\"></td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var c in new[] { "الوجهة", "عدد الافراد", "نسبة الافراد", "عدد الشركات", "نسبة الشركات", "المجموع" })
h.Append($"<td class=\"sub_header\">{c}</td>");
h.Append("</tr>");
foreach (var x in r.ByDestination)
h.Append($"<tr align=\"center\" dir=\"rtl\"><td>{E(x.Destination)}</td><td>{E(x.Individuals)}</td><td>{E(x.IndividualsPercent)}%</td><td>{E(x.Companies)}</td><td>{E(x.CompaniesPercent)}%</td><td>{E(x.Total)}</td></tr>");
h.Append("<tr><td colspan=\"6\"></td></tr>");
if (r.ByDestination.Count == 0) h.Append("<tr><td colspan=\"6\">لايوجد معلومات</td></tr>");
h.Append($"<tr><td colspan=\"2\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm}</td><td colspan=\"2\">جميع الحقوق محفوظة لشركة نافذ للخدمات اللوجستية</td>");
h.Append($"<td colspan=\"2\" align=\"left\">طبع التقرير بواسطة : {E(user.UserId)}</td></tr>");
h.Append("</table></td></tr></table></body></html>");
var t2 = new ExportTable([], var bytes = new System.Text.UTF8Encoding(true).GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(h.ToString())).ToArray();
[L("الوجهة", "Destination"), L("عدد الافراد", "Individuals"), L("نسبة الافراد", "Individuals %"), return new ExportFile(bytes, "application/vnd.ms-excel", "ordersReport.xls");
L("عدد الشركات", "Companies"), L("نسبة الشركات", "Companies %"), L("المجموع", "Total")],
r.ByDestination.Select(x => (IReadOnlyList<object?>)new object?[]
{ x.Destination, x.Individuals, x.IndividualsPercent + "%", x.Companies, x.CompaniesPercent + "%", x.Total }).ToList(),
[L("المجموع", "Total"), r.TotalIndividuals, null, r.TotalCompanies, null, r.TotalIndividuals + r.TotalCompanies]);
return Build([t1, t2], format, $"ordersReport_{r.OrderDate}");
} }
// ------------------------------------------------------------------ financial billing // ------------------------------------------------------------------ financial billing

View File

@ -47,14 +47,14 @@ public sealed record TenderOrderDto(
bool? MobileShow, bool? MobileShow,
bool CanDelete); bool CanDelete);
// Shift: Mobile shift: 1 morning, 2 evening, 3 night (legacy form field SHIFT). // Shift (optional): Mobile shift: 1 morning, 2 evening, 3 night (legacy form field SHIFT).
// Type: AHALE or COMP (required unless cargo type is 41). // Type: AHALE or COMP (required unless cargo type is 41).
public sealed record CreateTenderOrderRequest( public sealed record CreateTenderOrderRequest(
long CargoType, long CargoType,
long Location, long Location,
long Destination, long Destination,
DateTime OrderDate, DateTime OrderDate,
int Shift, int? Shift,
int Quantity, int Quantity,
bool IsTipper, bool IsTipper,
string? Type); string? Type);

View File

@ -11,7 +11,7 @@ public sealed class CreateTenderOrderValidator : AbstractValidator<CreateTenderO
RuleFor(x => x.Location).GreaterThan(0).WithMessage("موقع التحميل مطلوب"); RuleFor(x => x.Location).GreaterThan(0).WithMessage("موقع التحميل مطلوب");
RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الوجهه مطلوبة"); RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الوجهه مطلوبة");
RuleFor(x => x.OrderDate).NotEmpty().WithMessage("تاريخ الطلبية مطلوب"); RuleFor(x => x.OrderDate).NotEmpty().WithMessage("تاريخ الطلبية مطلوب");
RuleFor(x => x.Shift).InclusiveBetween(1, 3).WithMessage("الفترة مطلوبة"); RuleFor(x => x.Shift).InclusiveBetween(1, 3).When(x => x.Shift.HasValue).WithMessage("الفترة غير صحيحة");
RuleFor(x => x.Quantity) RuleFor(x => x.Quantity)
.Must(TenderOrderRules.IsQuantityValid).WithMessage("عدد السيارات يجب ان يكون بين 1 - 200"); .Must(TenderOrderRules.IsQuantityValid).WithMessage("عدد السيارات يجب ان يكون بين 1 - 200");
RuleFor(x => x.Type) RuleFor(x => x.Type)

View File

@ -0,0 +1,92 @@
using System.Net;
using System.Text;
using NTP.Application.Abstractions;
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
namespace NTP.Application.Grains.Registry;
public interface IRegistryExportService
{
Task<ExportFile> ExportTrucksAsync(TruckListQuery query, CancellationToken ct);
Task<ExportFile> ExportTrailersAsync(TrailerListQuery query, CancellationToken ct);
Task<ExportFile> ExportDriversAsync(DriverListQuery query, CancellationToken ct);
}
/// <summary>
/// Excel of the filtered registry grids (legacy truckGrid.cfm openTruckReportExcel / driverGrid.cfm openDriversReportExcel: the buttons
/// were shown to GTO, GOO, GNAC / GTO, GOO). Who may export is decided only by the permission keys *.export (GRAINS_SCREEN_PERMISSIONS, see
/// the controller); there is no role list in code.
/// </summary>
public sealed class RegistryExportService(
ITruckRegistryService trucks, ITrailerRegistryService trailers, IDriverRegistryService drivers, ICurrentUser user) : IRegistryExportService
{
private const int MaxRows = 20000;
private static async Task<List<T>> AllAsync<T>(Func<PageRequest, Task<PagedResult<T>>> fetch)
{
var all = new List<T>();
for (var p = 1; all.Count < MaxRows; p++)
{
var r = await fetch(new PageRequest(p, PageRequest.MaxPageSize));
all.AddRange(r.Items);
if (r.Items.Count == 0 || all.Count >= r.TotalCount) break;
}
return all;
}
public async Task<ExportFile> ExportTrucksAsync(TruckListQuery query, CancellationToken ct)
{
var rows = await AllAsync(p => trucks.SearchAsync(query, p, ct));
var label = query.SearchType == "TRN" ? "المقطورة" : "القاطرة";
return Build("شاشة القاطرات/ المقطورات المسجلة", "TruckReport",
[label, "رقم الشاصي", "الشركة", "انتهاء الترخيص", "تاريخ الإنشاء", "أنشئ بواسطة", "الحالة"],
rows.Select(r => new object?[] { r.Tn, r.ChasesNumber, r.CompName, D(r.RegDate), D(r.CreateTimestamp, true), r.CreateUserId, r.StatusCaption }));
}
public async Task<ExportFile> ExportTrailersAsync(TrailerListQuery query, CancellationToken ct)
{
var rows = await AllAsync(p => trailers.SearchAsync(query, p, ct));
return Build("شاشة المقطورات المسجلة", "TrailerReport",
["رقم المقطورة", "رقم الشاصي", "الشركة", "المالك", "انتهاء الترخيص", "تاريخ الإنشاء", "أنشئ بواسطة", "الحالة"],
rows.Select(r => new object?[] { r.Tn, r.ChasesNumber, r.CompName, r.OwnerName, D(r.RegDate), D(r.CreateTimestamp, true), r.CreateUserId, r.StatusCaption }));
}
public async Task<ExportFile> ExportDriversAsync(DriverListQuery query, CancellationToken ct)
{
var rows = await AllAsync(p => drivers.SearchAsync(query, p, ct));
return Build("شاشة السائقين المسجلين", "DriversReport",
["الرقم الوطني", "الاسم", "رقم الرخصة", "انتهاء الرخصة", "الشركة", "تاريخ الإنشاء", "أنشئ بواسطة", "الحالة"],
rows.Select(r => new object?[] { r.Nnpn, r.Name, r.Dln, D(r.Dled), r.CompName, D(r.CreateTimestamp, true), r.CreateUserId, r.StatusCaption }));
}
private static string D(DateTime? d, bool time = false) => d is null ? string.Empty : d.Value.ToString(time ? "dd/MM/yyyy HH:mm" : "dd/MM/yyyy");
private ExportFile Build(string title, string fileName, string[] headers, IEnumerable<object?[]> rows)
{
static string E(object? v) => WebUtility.HtmlEncode(Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty);
var n = headers.Length;
var h = new StringBuilder();
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
h.Append("<style>.header{font-weight:bold;font-size:28px;}");
h.Append(".sub_header{font-weight:bold;font-size:14px;width:80px;background-color:#034878;color:#FFFFFF;text-align:center;}</style>");
h.Append("<table border=\"2\" bordercolor=\"#034878\"><tr><td><table align=\"center\" dir=\"rtl\" border=\"1\">");
h.Append($"<tr align=\"center\" dir=\"rtl\"><td colspan=\"{n}\" align=\"center\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
h.Append($"<tr align=\"center\" dir=\"rtl\"><td colspan=\"{n}\" align=\"center\" class=\"header\">{E(title)}</td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var c in headers) h.Append($"<td class=\"sub_header\">{E(c)}</td>");
h.Append("</tr>");
var count = 0;
foreach (var r in rows)
{
count++;
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var v in r) h.Append($"<td>{E(v)}</td>");
h.Append("</tr>");
}
if (count == 0) h.Append($"<tr><td colspan=\"{n}\">لايوجد معلومات</td></tr>");
h.Append($"<tr><td colspan=\"{n}\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm} - عدد النتائج : {count} - طبع التقرير بواسطة : {E(user.UserId)}</td></tr>");
h.Append("</table></td></tr></table></body></html>");
var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h.ToString())).ToArray();
return new ExportFile(bytes, "application/vnd.ms-excel", fileName + ".xls");
}
}

View File

@ -52,7 +52,7 @@ public static class GrainsOrderConstants
/// <summary>New GRAINSTENDERORDER row.</summary> /// <summary>New GRAINSTENDERORDER row.</summary>
public sealed record NewTenderOrder( public sealed record NewTenderOrder(
long CargoType, long Location, long Destination, DateTime OrderDate, int MobileShift, long CargoType, long Location, long Destination, DateTime OrderDate, int? MobileShift,
int Quantity, string? Type, string Ct, string CreatedBy); int Quantity, string? Type, string Ct, string CreatedBy);
/// <summary>New GRAINS_BILLING row (columns exactly as written by legacy addBillingInfo).</summary> /// <summary>New GRAINS_BILLING row (columns exactly as written by legacy addBillingInfo).</summary>

View File

@ -146,7 +146,7 @@ public sealed record DistributionCategory(string Request, string DistributionCod
public bool IsGallabCompany => Request == "BULK_GALLAB_COMP"; public bool IsGallabCompany => Request == "BULK_GALLAB_COMP";
public static readonly string[] Allowed = public static readonly string[] Allowed =
["PCKD", "BULK_AHALE", "BULK_COMP", "BULK_GALLAB_COMP", "BULK_GALLAB_AHALE"]; ["PCKD", "BULK_AHALE", "BULK_COMP", "BULK_GALLAB_COMP", "BULK_GALLAB_AHALE", "RED_SEA"];
public static DistributionCategory? Parse(string? request) public static DistributionCategory? Parse(string? request)
{ {
@ -156,6 +156,8 @@ public sealed record DistributionCategory(string Request, string DistributionCod
"BULK_AHALE" => new(r, "BULK", "AHALE", "BULK"), "BULK_AHALE" => new(r, "BULK", "AHALE", "BULK"),
"BULK_COMP" => new(r, "BULK", "COMP", "BULK"), "BULK_COMP" => new(r, "BULK", "COMP", "BULK"),
"PCKD" => new(r, "PCKD", "", "PCKD"), "PCKD" => new(r, "PCKD", "", "PCKD"),
// البحر الأحمر: its own cargo class / queue code RED_SEA, not split into individuals and companies (new, no legacy counterpart)
"RED_SEA" => new(r, "RED_SEA", "", "RED_SEA"),
"BULK_GALLAB_COMP" => new(r, "BULK_GALLAB", "COMP", "BULK"), "BULK_GALLAB_COMP" => new(r, "BULK_GALLAB", "COMP", "BULK"),
"BULK_GALLAB_AHALE" => new(r, "BULK_GALLAB", "AHALE", "BULK"), "BULK_GALLAB_AHALE" => new(r, "BULK_GALLAB", "AHALE", "BULK"),
_ => null _ => null
@ -180,6 +182,7 @@ public sealed record DistributionCategory(string Request, string DistributionCod
"BULK_COMP" => "لا توجد طلبات سائب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية", "BULK_COMP" => "لا توجد طلبات سائب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"BULK_GALLAB_COMP" => "لا توجد طلبات قلاب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية", "BULK_GALLAB_COMP" => "لا توجد طلبات قلاب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"BULK_GALLAB_AHALE" => "لا توجد طلبات قلاب أفراد مسجلة على النظام ، او قد تم توزيع كامل الطلبية", "BULK_GALLAB_AHALE" => "لا توجد طلبات قلاب أفراد مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"RED_SEA" => "لا توجد طلبات البحر الأحمر مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
_ => string.Empty _ => string.Empty
}; };
} }

View File

@ -26,7 +26,7 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
{ {
var sql = packed var sql = packed
? "SELECT NVL(SUM(total_owners), 0) AS TotalOwners, NVL(SUM(total_comps), 0) AS TotalComps, NVL(SUM(allquantity), 0) AS AllQuantity FROM GN_TOTAL_ORDER_BY_CATEGORY t WHERE t.ct = 'PCKD'" ? "SELECT NVL(SUM(total_owners), 0) AS TotalOwners, NVL(SUM(total_comps), 0) AS TotalComps, NVL(SUM(allquantity), 0) AS AllQuantity FROM GN_TOTAL_ORDER_BY_CATEGORY t WHERE t.ct = 'PCKD'"
: "SELECT NVL(SUM(total_owners), 0) AS TotalOwners, NVL(SUM(total_comps), 0) AS TotalComps, NVL(SUM(allquantity), 0) AS AllQuantity FROM GN_TOTAL_ORDER_BY_CATEGORY t WHERE t.ct = :Code AND t.type = :Type"; : "SELECT NVL(SUM(total_owners), 0) AS TotalOwners, NVL(SUM(total_comps), 0) AS TotalComps, NVL(SUM(allquantity), 0) AS AllQuantity FROM GN_TOTAL_ORDER_BY_CATEGORY t WHERE t.ct = :Code" + (string.IsNullOrEmpty(queueType) ? string.Empty : " AND t.type = :Type");
return (await QueryFirstAsync<OrderTotalsRow>(sql, new { Code = distributionCode, Type = queueType }, ct)) ?? new OrderTotalsRow(); return (await QueryFirstAsync<OrderTotalsRow>(sql, new { Code = distributionCode, Type = queueType }, ct)) ?? new OrderTotalsRow();
} }
@ -34,7 +34,7 @@ internal sealed class DistributionRepository(IDbSession session, ILogger<Distrib
{ {
var sql = packed var sql = packed
? "SELECT NVL(SUM(used_owners), 0) AS UsedOwners, NVL(SUM(used_comps), 0) AS UsedComps FROM GN_USED_ORDER_BY_CATEGORY t WHERE t.ct = 'PCKD'" ? "SELECT NVL(SUM(used_owners), 0) AS UsedOwners, NVL(SUM(used_comps), 0) AS UsedComps FROM GN_USED_ORDER_BY_CATEGORY t WHERE t.ct = 'PCKD'"
: "SELECT NVL(SUM(used_owners), 0) AS UsedOwners, NVL(SUM(used_comps), 0) AS UsedComps FROM GN_USED_ORDER_BY_CATEGORY t WHERE t.ct = :Code AND t.type = :Type"; : "SELECT NVL(SUM(used_owners), 0) AS UsedOwners, NVL(SUM(used_comps), 0) AS UsedComps FROM GN_USED_ORDER_BY_CATEGORY t WHERE t.ct = :Code" + (string.IsNullOrEmpty(queueType) ? string.Empty : " AND t.type = :Type");
return await QueryFirstAsync<OrderUsedRow>(sql, new { Code = distributionCode, Type = queueType }, ct); return await QueryFirstAsync<OrderUsedRow>(sql, new { Code = distributionCode, Type = queueType }, ct);
} }

View File

@ -164,12 +164,17 @@ export function useSaveCompanyDestinations(scac: number | null) {
} }
// ---------------------------------------------------------------- CSV / Excel download (bearer token, so not a plain link) // ---------------------------------------------------------------- CSV / Excel download (bearer token, so not a plain link)
export async function downloadExport(path: string, params: Record<string, string | number | undefined>, fallbackName: string): Promise<void> { export function downloadExport(path: string, params: Record<string, string | number | undefined>, fallbackName: string): Promise<void> {
return downloadFile(`${BASE}${path}`, params, fallbackName);
}
/** Authenticated file download of any API path below the versioned base (the bearer token rules out a plain link). */
export async function downloadFile(apiPath: string, params: Record<string, string | number | undefined>, fallbackName: string): Promise<void> {
if (MOCK) return; if (MOCK) return;
const qs = new URLSearchParams(); const qs = new URLSearchParams();
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') qs.append(k, String(v)); for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') qs.append(k, String(v));
const token = getToken(); const token = getToken();
const res = await fetch(`${API_BASE}${BASE}${path}?${qs}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); const res = await fetch(`${API_BASE}${apiPath}?${qs}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
if (!res.ok) { if (!res.ok) {
let problem: { detail?: string; title?: string } | undefined; let problem: { detail?: string; title?: string } | undefined;
try { problem = await res.json(); } catch { /* not JSON */ } try { problem = await res.json(); } catch { /* not JSON */ }

View File

@ -99,10 +99,10 @@ export const tenderOrderForm = (): FormMeta => ({
columns: 2, columns: 2,
fields: [ fields: [
{ name: 'cargoType', type: 'select', label: { en: 'Cargo type', ar: 'نمط الحمولة' }, required: true, options: cargoTypeOptions }, { name: 'cargoType', type: 'select', label: { en: 'Cargo type', ar: 'نمط الحمولة' }, required: true, options: cargoTypeOptions },
{ name: 'location', type: 'select', label: { en: 'Loading site', ar: 'موقع التحميل' }, required: true, options: loadingLocationOptions }, { name: 'location', type: 'autocomplete', label: { en: 'Loading site', ar: 'موقع التحميل' }, required: true, options: loadingLocationOptions },
{ name: 'destination', type: 'select', label: { en: 'Destination', ar: 'الوجهه' }, required: true, options: destinationOptions }, { name: 'destination', type: 'autocomplete', label: { en: 'Destination', ar: 'الوجهه' }, required: true, options: destinationOptions },
{ name: 'orderDate', type: 'select', label: { en: 'Order date', ar: 'تاريخ الطلبية' }, required: true, options: orderDateOptions() }, { name: 'orderDate', type: 'select', label: { en: 'Order date', ar: 'تاريخ الطلبية' }, required: true, options: orderDateOptions() },
{ name: 'shift', type: 'select', label: { en: 'Shift', ar: 'الفترة' }, required: true, options: shiftOptions }, { name: 'shift', type: 'select', label: { en: 'Shift', ar: 'الفترة' }, options: shiftOptions },
{ name: 'quantity', type: 'number', label: { en: 'Number of trucks', ar: 'عدد السيارات' }, required: true, min: 1, max: 200 }, { name: 'quantity', type: 'number', label: { en: 'Number of trucks', ar: 'عدد السيارات' }, required: true, min: 1, max: 200 },
{ {
// packed cargo and the tipper destinations lock this box (legacy checkIfGallab); the backend derives CT anyway // packed cargo and the tipper destinations lock this box (legacy checkIfGallab); the backend derives CT anyway

View File

@ -124,7 +124,7 @@ export function TenderOrderCreatePage() {
new Promise<void>((resolve) => { new Promise<void>((resolve) => {
setServerErrors({}); setServerErrors({});
create.mutate( create.mutate(
{ ...payload, quantity: Number(payload.quantity), shift: Number(payload.shift), isTipper: payload.isTipper === true }, { ...payload, quantity: Number(payload.quantity), shift: payload.shift ? Number(payload.shift) : null, isTipper: payload.isTipper === true },
{ {
onSuccess: () => { resolve(); navigate('/grains/orders'); }, onSuccess: () => { resolve(); navigate('/grains/orders'); },
onError: (e) => { setServerErrors({ ...e.fieldErrors }); resolve(); }, onError: (e) => { setServerErrors({ ...e.fieldErrors }); resolve(); },
@ -593,8 +593,8 @@ export function TenderOrderReportPage() {
if (!canManage) return <Alert severity="warning">{t('ord.forbidden')}</Alert>; if (!canManage) return <Alert severity="warning">{t('ord.forbidden')}</Alert>;
const exportAs = (format: 'csv' | 'xlsx') => const exportExcel = () =>
downloadExport('/reports/tender-orders/export', { orderDate: date, format }, `ordersReport_${date}.${format}`) downloadExport('/reports/tender-orders/export', { orderDate: date }, 'ordersReport.xls')
.catch((e) => toast.error(errText(e, t('ord.export.failed')))); .catch((e) => toast.error(errText(e, t('ord.export.failed'))));
return ( return (
@ -602,18 +602,15 @@ export function TenderOrderReportPage() {
<PageHeader <PageHeader
title={t('ord.orders.reportTitle')} title={t('ord.orders.reportTitle')}
subtitle={t('ord.orders.reportSubtitle')} subtitle={t('ord.orders.reportSubtitle')}
actions={
<>
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={!date} onClick={() => void exportAs('csv')}>{t('ord.export.csv')}</Button>
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={!date} onClick={() => void exportAs('xlsx')}>{t('ord.export.xlsx')}</Button>
</>
}
/> />
<Stack spacing={2}> <Stack spacing={2.5} sx={{ maxWidth: 1000 }}>
<Paper variant="outlined" sx={{ p: 2, display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
<DateField <DateField
size="small" label={tr({ en: 'Order date', ar: 'تاريخ الطلبية' })} size="small" label={tr({ en: 'Order date', ar: 'تاريخ الطلبية' })}
value={date} onChange={setDate} sx={{ maxWidth: 260 }} value={date} onChange={setDate} sx={{ width: 220 }}
/> />
<Button variant="contained" startIcon={<DownloadIcon />} disabled={!date} onClick={() => void exportExcel()} sx={{ marginInlineStart: 'auto' }}>{t('ord.export.xlsx')}</Button>
</Paper>
{!date && <Alert severity="info">{t('ord.orders.reportPickDate')}</Alert>} {!date && <Alert severity="info">{t('ord.orders.reportPickDate')}</Alert>}
{q.isPending && date && <LoadingBanner variant="first" />} {q.isPending && date && <LoadingBanner variant="first" />}
{q.isError && <Alert severity="error">{errText(q.error, t('error.generic'))}</Alert>} {q.isError && <Alert severity="error">{errText(q.error, t('error.generic'))}</Alert>}

View File

@ -4,7 +4,7 @@ import { defineStrings } from '@/i18n/useUi';
export default defineStrings({ export default defineStrings({
// ---- menu // ---- menu
'ord.menu.finance': { en: 'Finance', ar: 'المالية' }, 'ord.menu.finance': { en: 'Finance', ar: 'المالية' },
'ord.menu.group': { en: 'Orders and billing', ar: 'الطلبيات والمطالبات' }, 'ord.menu.group': { en: 'Orders', ar: 'الطلبيات' },
'ord.menu.orders': { en: 'Tender orders', ar: 'الطلبيات' }, 'ord.menu.orders': { en: 'Tender orders', ar: 'الطلبيات' },
'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' }, 'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' },
'ord.menu.billing': { en: 'Billing claims', ar: 'المطالبات المالية' }, 'ord.menu.billing': { en: 'Billing claims', ar: 'المطالبات المالية' },

View File

@ -737,10 +737,10 @@ export function SupplyOrderPage() {
<PageHeader title={t('pm.supply.title')} subtitle={t('pm.supply.subtitle')} /> <PageHeader title={t('pm.supply.title')} subtitle={t('pm.supply.subtitle')} />
<Paper variant="outlined" sx={{ p: 2 }}> <Paper variant="outlined" sx={{ p: 2 }}>
<Table size="small"> <Table size="small">
<TableHead><TableRow><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="center">{t('pm.dist.silos')}</TableCell> <TableHead><TableRow><TableCell align="center">{t('pm.dist.companyNo')}</TableCell><TableCell>{t('pm.dist.company')}</TableCell><TableCell align="center">{t('pm.dist.silos')}</TableCell>
<TableCell align="center">{t('pm.dist.direct')}</TableCell><TableCell align="center">{t('pm.dist.packed')}</TableCell></TableRow></TableHead> <TableCell align="center">{t('pm.dist.direct')}</TableCell><TableCell align="center">{t('pm.dist.packed')}</TableCell></TableRow></TableHead>
<TableBody>{(pivot.data ?? []).map((r) => ( <TableBody>{(pivot.data ?? []).map((r) => (
<TableRow key={r.companyCode ?? 0}><TableCell>{r.company}</TableCell><TableCell align="center" dir="ltr">{r.silos}</TableCell> <TableRow key={r.companyCode ?? 0}><TableCell align="center" dir="ltr">{r.companyCode}</TableCell><TableCell>{r.company}</TableCell><TableCell align="center" dir="ltr">{r.silos}</TableCell>
<TableCell align="center" dir="ltr">{r.direct}</TableCell><TableCell align="center" dir="ltr">{r.packed}</TableCell></TableRow> <TableCell align="center" dir="ltr">{r.direct}</TableCell><TableCell align="center" dir="ltr">{r.packed}</TableCell></TableRow>
))}</TableBody> ))}</TableBody>
</Table> </Table>
@ -795,6 +795,7 @@ function DistributeTab() {
{ v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات', q: 'هل أنت متأكد من توزيع طلبية سائب شركات لهذا اليوم؟' }, { v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات', q: 'هل أنت متأكد من توزيع طلبية سائب شركات لهذا اليوم؟' },
{ v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد', q: 'هل أنت متأكد من توزيع طلبية قلاب أفراد لهذا اليوم؟' }, { v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد', q: 'هل أنت متأكد من توزيع طلبية قلاب أفراد لهذا اليوم؟' },
{ v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات', q: 'هل أنت متأكد من توزيع طلبية قلاب شركات لهذا اليوم؟' }, { v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات', q: 'هل أنت متأكد من توزيع طلبية قلاب شركات لهذا اليوم؟' },
{ v: 'RED_SEA', en: 'Red Sea', ar: 'البحر الأحمر', q: 'هل أنت متأكد من توزيع طلبية البحر الأحمر لهذا اليوم؟' },
]; ];
const [cat, setCat] = useState(''); // nothing preselected: a distribution run cannot be undone const [cat, setCat] = useState(''); // nothing preselected: a distribution run cannot be undone
const summary = useDistributionSummary(); const summary = useDistributionSummary();

View File

@ -161,6 +161,7 @@ export default defineStrings({
'pm.wb.tabClose': { en: 'Close a permit', ar: 'اغلاق إرسالية' }, 'pm.wb.tabClose': { en: 'Close a permit', ar: 'اغلاق إرسالية' },
'pm.menu.close': { en: 'Close a permit', ar: 'اغلاق إرسالية' }, 'pm.menu.close': { en: 'Close a permit', ar: 'اغلاق إرسالية' },
'pm.menu.inquiry': { en: 'Truck inquiry', ar: 'استعلام عن سيارة' }, 'pm.menu.inquiry': { en: 'Truck inquiry', ar: 'استعلام عن سيارة' },
'pm.dist.companyNo': { en: 'Company no.', ar: 'رقم الشركة' },
'pm.menu.supply': { en: 'Supply order', ar: 'طلبية التموين' }, 'pm.menu.supply': { en: 'Supply order', ar: 'طلبية التموين' },
'pm.close.title': { en: 'Close a permit', ar: 'اغلاق إرسالية' }, 'pm.close.title': { en: 'Close a permit', ar: 'اغلاق إرسالية' },
'pm.close.subtitle': { en: 'Close a permit manually by its number', ar: 'اغلاق الإرسالية يدويا برقمها' }, 'pm.close.subtitle': { en: 'Close a permit manually by its number', ar: 'اغلاق الإرسالية يدويا برقمها' },

View File

@ -20,7 +20,6 @@ export function trailerGrid(h: { isCompanyUser: boolean; onOpen: (r: TrailerRow)
], ],
columns: [ columns: [
{ key: 'tn', header: lbl('Number', 'الرقم'), ltr: true }, { key: 'tn', header: lbl('Number', 'الرقم'), ltr: true },
{ key: 'chasesNumber', header: lbl('Chassis number', 'رقم الشصي'), ltr: true, hideBelow: 'sm' },
{ key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' }, { key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' },
{ key: 'ownerName', header: lbl('Owner', 'المالك'), hideBelow: 'lg' }, { key: 'ownerName', header: lbl('Owner', 'المالك'), hideBelow: 'lg' },
{ key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'lg' }, { key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'lg' },

View File

@ -28,7 +28,6 @@ export function truckGrid(h: { isCompanyUser: boolean; onOpen: (r: TruckRow) =>
], ],
columns: [ columns: [
{ key: 'tn', header: lbl('Number', 'الرقم'), ltr: true }, { key: 'tn', header: lbl('Number', 'الرقم'), ltr: true },
{ key: 'chasesNumber', header: lbl('Chassis number', 'رقم الشصي'), ltr: true, hideBelow: 'sm' },
{ key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' }, { key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' },
{ key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'lg' }, { key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'lg' },
{ key: 'createTimestamp', header: lbl('Created on', 'تاريخ الإنشاء'), format: 'datetime', ltr: true, hideBelow: 'lg' }, { key: 'createTimestamp', header: lbl('Created on', 'تاريخ الإنشاء'), format: 'datetime', ltr: true, hideBelow: 'lg' },
@ -41,7 +40,6 @@ export function truckGrid(h: { isCompanyUser: boolean; onOpen: (r: TruckRow) =>
/** Small read-only grid of the trailers connected to a truck (legacy getTrailerGrid of the truck page). */ /** Small read-only grid of the trailers connected to a truck (legacy getTrailerGrid of the truck page). */
export const connectedTrailerColumns = (): GridMeta<TrailerRow>['columns'] => [ export const connectedTrailerColumns = (): GridMeta<TrailerRow>['columns'] => [
{ key: 'tn', header: lbl('Trailer', 'المقطورة'), ltr: true }, { key: 'tn', header: lbl('Trailer', 'المقطورة'), ltr: true },
{ key: 'chasesNumber', header: lbl('Chassis number', 'رقم الشصي'), ltr: true, hideBelow: 'sm' },
{ key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'md' }, { key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'md' },
{ key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: registryStatuses }, { key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: registryStatuses },
]; ];

View File

@ -5,6 +5,7 @@ import {
TableHead, TableRow, TextField, Typography, TableHead, TableRow, TextField, Typography,
} from '@mui/material'; } from '@mui/material';
import AddIcon from '@mui/icons-material/Add'; import AddIcon from '@mui/icons-material/Add';
import DownloadIcon from '@mui/icons-material/Download';
import BlockIcon from '@mui/icons-material/Block'; import BlockIcon from '@mui/icons-material/Block';
import CheckCircleIcon from '@mui/icons-material/CheckCircle'; import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import type { ApiError } from '@/api/client'; import type { ApiError } from '@/api/client';
@ -16,7 +17,9 @@ import { StatusChip } from '@/components/StatusChip';
import { formatDate, formatNumber } from '@/components/meta/format'; import { formatDate, formatNumber } from '@/components/meta/format';
import { useFeatureUi } from '@/i18n/useUi'; import { useFeatureUi } from '@/i18n/useUi';
import { useConfirm } from '@/providers/ConfirmProvider'; import { useConfirm } from '@/providers/ConfirmProvider';
import { useAuth } from '@/providers/AuthProvider';
import { useToast } from '@/providers/ToastProvider'; import { useToast } from '@/providers/ToastProvider';
import { downloadFile } from '../grains-orders/api';
import { import {
useAddBlacklist, useCancelBlacklist, useCreateDriver, useCreateTrailer, useCreateTruck, useDestinationOptions, useDriver, useAddBlacklist, useCancelBlacklist, useCreateDriver, useCreateTrailer, useCreateTruck, useDestinationOptions, useDriver,
useDriverAction, useLocationTruckCounts, usePermissions, useSaveWeighbridge, useTrailer, useTrailerAction, useTruck, useDriverAction, useLocationTruckCounts, usePermissions, useSaveWeighbridge, useTrailer, useTrailerAction, useTruck,
@ -97,6 +100,25 @@ function splitDestinations(ids: number[] | null | undefined, o: RegistryDestinat
} }
// ================================================================= trucks // ================================================================= trucks
/** Excel of the list with the filters currently applied (legacy report icon); shown only with the permission grains.registry.<kind>.export from the database. */
function ExportButton({ kind }: { kind: 'trucks' | 'trailers' | 'drivers' }) {
const { t } = useFeatureUi(strings);
const { can } = useAuth();
const toast = useToast();
const [sp] = useSearchParams();
const [busy, setBusy] = useState(false);
if (!can(`grains.registry.${kind}.export`)) return null;
const run = async () => {
setBusy(true);
const params: Record<string, string> = {};
sp.forEach((v, k) => { if (k !== 'page' && k !== 'pageSize' && k !== 'f') params[k] = v; });
try { await downloadFile(`/grains/registry/${kind}/export`, params, kind + '.xls'); }
catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); }
finally { setBusy(false); }
};
return <Button variant="outlined" startIcon={<DownloadIcon />} disabled={busy} onClick={() => void run()}>{t('reg.export')}</Button>;
}
export function TrucksPage() { export function TrucksPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const navigate = useNavigate(); const navigate = useNavigate();
@ -115,9 +137,14 @@ export function TrucksPage() {
<PageHeader <PageHeader
title={t('reg.trucks.title')} title={t('reg.trucks.title')}
subtitle={t('reg.trucks.subtitle')} subtitle={t('reg.trucks.subtitle')}
actions={perms?.canAddTruck && ( actions={(
<>
<ExportButton kind="trucks" />
{perms?.canAddTruck && (
<Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/trucks/new`)}>{t('reg.trucks.new')}</Button> <Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/trucks/new`)}>{t('reg.trucks.new')}</Button>
)} )}
</>
)}
/> />
<DataGrid meta={meta} /> <DataGrid meta={meta} />
</> </>
@ -277,9 +304,14 @@ export function TrailersPage() {
<PageHeader <PageHeader
title={t('reg.trailers.title')} title={t('reg.trailers.title')}
subtitle={t('reg.trailers.subtitle')} subtitle={t('reg.trailers.subtitle')}
actions={perms?.canAddTrailer && ( actions={(
<>
<ExportButton kind="trailers" />
{perms?.canAddTrailer && (
<Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/trailers/new`)}>{t('reg.trailers.new')}</Button> <Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/trailers/new`)}>{t('reg.trailers.new')}</Button>
)} )}
</>
)}
/> />
<DataGrid meta={meta} /> <DataGrid meta={meta} />
</> </>
@ -407,9 +439,14 @@ export function DriversPage() {
<PageHeader <PageHeader
title={t('reg.drivers.title')} title={t('reg.drivers.title')}
subtitle={t('reg.drivers.subtitle')} subtitle={t('reg.drivers.subtitle')}
actions={perms?.canAddDriver && ( actions={(
<>
<ExportButton kind="drivers" />
{perms?.canAddDriver && (
<Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/drivers/new`)}>{t('reg.drivers.new')}</Button> <Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/drivers/new`)}>{t('reg.drivers.new')}</Button>
)} )}
</>
)}
/> />
<DataGrid meta={meta} /> <DataGrid meta={meta} />
</> </>

View File

@ -50,6 +50,7 @@ export default defineStrings({
// ---- trucks // ---- trucks
'reg.trucks.title': { en: 'Trucks', ar: 'القاطرات' }, 'reg.trucks.title': { en: 'Trucks', ar: 'القاطرات' },
'reg.trucks.subtitle': { en: 'Registered tractor units per company', ar: 'القاطرات المسجلة حسب الشركة' }, 'reg.trucks.subtitle': { en: 'Registered tractor units per company', ar: 'القاطرات المسجلة حسب الشركة' },
'reg.export': { en: 'Export Excel', ar: 'تصدير Excel' },
'reg.trucks.new': { en: 'New truck', ar: 'قاطرة جديدة' }, 'reg.trucks.new': { en: 'New truck', ar: 'قاطرة جديدة' },
'reg.trucks.createTitle': { en: 'Register a truck', ar: 'تسجيل قاطرة' }, 'reg.trucks.createTitle': { en: 'Register a truck', ar: 'تسجيل قاطرة' },
'reg.trucks.detailTitle': { en: 'Truck {tn}', ar: 'القاطرة {tn}' }, 'reg.trucks.detailTitle': { en: 'Truck {tn}', ar: 'القاطرة {tn}' },

View File

@ -13,6 +13,7 @@ import {
} from './pages'; } from './pages';
import { tableReports } from './meta'; import { tableReports } from './meta';
import strings from './strings'; import strings from './strings';
import orderStrings from '../grains-orders/strings';
const B = '/grains/reports'; const B = '/grains/reports';
@ -48,6 +49,7 @@ export const menu: MenuItem[] = [
{ key: 'grains.reports.details', title: strings['rpt.menu.details'], icon: TableChartIcon, path: `${B}/trips/details` }, { key: 'grains.reports.details', title: strings['rpt.menu.details'], icon: TableChartIcon, path: `${B}/trips/details` },
table('weighbridge-events', ScaleIcon), table('waybridge-summary', ScaleIcon), table('waybridge-details', ScaleIcon), table('weighbridge-events', ScaleIcon), table('waybridge-summary', ScaleIcon), table('waybridge-details', ScaleIcon),
table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'),
{ key: 'grains.orders.reportOrders', title: orderStrings['ord.orders.reportTitle'], icon: PieChartIcon, path: '/grains/orders/reports/tender-orders' },
table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'), table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'),
table('companies-turn'), table('owners-turn'), table('companies-turn'), table('owners-turn'),
table('drivers'), table('trucks'), table('drivers'), table('trucks'),

View File

@ -51,6 +51,10 @@ export const ui = {
'user.currentPassword': { en: 'Current password', ar: 'كلمة المرور الحالية' }, 'user.currentPassword': { en: 'Current password', ar: 'كلمة المرور الحالية' },
'user.newPassword': { en: 'New password', ar: 'كلمة المرور الجديدة' }, 'user.newPassword': { en: 'New password', ar: 'كلمة المرور الجديدة' },
'user.confirmPassword': { en: 'Confirm new password', ar: 'تأكيد كلمة المرور الجديدة' }, 'user.confirmPassword': { en: 'Confirm new password', ar: 'تأكيد كلمة المرور الجديدة' },
'user.passwordRules': { en: 'At least 8 characters, letters and digits, different from the current password', ar: 'ثماني خانات على الأقل، أحرف وأرقام، وتختلف عن كلمة المرور الحالية' },
'user.passwordTooShort': { en: 'The password must be at least 8 characters', ar: 'كلمة السر يجب ألا تقل عن 8 خانات' },
'user.passwordWeak': { en: 'The password must contain letters and digits', ar: 'كلمة السر يجب أن تحتوي على أحرف وأرقام' },
'user.passwordSame': { en: 'The new password must differ from the current one', ar: 'كلمة السر الجديدة يجب أن تختلف عن القديمة' },
'user.passwordMismatch': { en: 'The passwords do not match', ar: 'كلمتا المرور غير متطابقتين' }, 'user.passwordMismatch': { en: 'The passwords do not match', ar: 'كلمتا المرور غير متطابقتين' },
'user.passwordChanged': { en: 'Password changed', ar: 'تم تغيير كلمة المرور' }, 'user.passwordChanged': { en: 'Password changed', ar: 'تم تغيير كلمة المرور' },
'user.sessionExpired': { en: 'Your session has expired. Please sign in again.', ar: 'انتهت جلستك. الرجاء تسجيل الدخول مرة أخرى.' }, 'user.sessionExpired': { en: 'Your session has expired. Please sign in again.', ar: 'انتهت جلستك. الرجاء تسجيل الدخول مرة أخرى.' },

View File

@ -59,8 +59,9 @@ export function ToastProvider({ children }: { children: ReactNode }) {
<Snackbar <Snackbar
key={current.id} key={current.id}
open open
// errors stay longer on screen // errors stay a little longer; the timer keeps running when the window loses focus (MUI pauses it by default)
autoHideDuration={current.severity === 'error' ? 12000 : current.severity === 'warning' ? 8000 : 4500} autoHideDuration={current.severity === 'error' ? 6000 : current.severity === 'warning' ? 5000 : 3000}
disableWindowBlurListener
onClose={(_, reason) => reason !== 'clickaway' && close(current.id)} onClose={(_, reason) => reason !== 'clickaway' && close(current.id)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
sx={{ zIndex: (th) => th.zIndex.snackbar + 10 }} sx={{ zIndex: (th) => th.zIndex.snackbar + 10 }}

View File

@ -16,4 +16,9 @@ const modules = import.meta.glob<FeatureModule>('./features/*/routes.tsx', { eag
const sorted = Object.entries(modules).sort(([a], [b]) => a.localeCompare(b)); const sorted = Object.entries(modules).sort(([a], [b]) => a.localeCompare(b));
export const featureRoutes: RouteObject[] = sorted.flatMap(([, m]) => m.routes ?? []); export const featureRoutes: RouteObject[] = sorted.flatMap(([, m]) => m.routes ?? []);
export const featureMenu: MenuItem[] = sorted.flatMap(([, m]) => m.menu ?? []); /** Top-level menu groups shown before everything else, in this order (the rest keep the folder order). */
const MENU_FIRST = ['grains.finance'];
const menuRank = (item: MenuItem) => { const i = MENU_FIRST.indexOf(item.key); return i < 0 ? MENU_FIRST.length : i; };
// Array.sort is stable, so groups with the same rank keep their feature order
export const featureMenu: MenuItem[] = sorted.flatMap(([, m]) => m.menu ?? []).sort((a, b) => menuRank(a) - menuRank(b));

View File

@ -22,11 +22,14 @@ export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose
const out: Record<string, string> = {}; const out: Record<string, string> = {};
if (!cur) out.cur = t('common.required'); if (!cur) out.cur = t('common.required');
if (!next) out.next = t('common.required'); if (!next) out.next = t('common.required');
if (next && next.length < 8) out.next = t('user.passwordTooShort');
else if (next && !(/\p{L}/u.test(next) && /\d/.test(next))) out.next = t('user.passwordWeak');
else if (next && next === cur) out.next = t('user.passwordSame');
if (next && again !== next) out.again = t('user.passwordMismatch'); if (next && again !== next) out.again = t('user.passwordMismatch');
setErr(out); setErr(out);
if (Object.keys(out).length) return; if (Object.keys(out).length) return;
save.mutate({ c: cur, n: next }, { save.mutate({ c: cur, n: next }, {
onError: (x) => x instanceof ApiError && setErr({ cur: x.fieldErrors.currentPassword ?? '', next: x.fieldErrors.newPassword ?? '' }), onError: (x) => x instanceof ApiError && setErr({ cur: x.fieldErrors.oldPassword ?? x.fieldErrors.currentPassword ?? '', next: x.fieldErrors.newPassword ?? '' }),
}); });
} }
@ -39,7 +42,7 @@ export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose
<TextField type="password" autoComplete="current-password" required label={t('user.currentPassword')} value={cur} <TextField type="password" autoComplete="current-password" required label={t('user.currentPassword')} value={cur}
onChange={(e) => setCur(e.target.value)} error={!!err.cur} helperText={err.cur} slotProps={{ htmlInput: { dir: 'ltr' } }} /> onChange={(e) => setCur(e.target.value)} error={!!err.cur} helperText={err.cur} slotProps={{ htmlInput: { dir: 'ltr' } }} />
<TextField type="password" autoComplete="new-password" required label={t('user.newPassword')} value={next} <TextField type="password" autoComplete="new-password" required label={t('user.newPassword')} value={next}
onChange={(e) => setNext(e.target.value)} error={!!err.next} helperText={err.next} slotProps={{ htmlInput: { dir: 'ltr' } }} /> onChange={(e) => setNext(e.target.value)} error={!!err.next} helperText={err.next ?? t('user.passwordRules')} slotProps={{ htmlInput: { dir: 'ltr' } }} />
<TextField type="password" autoComplete="new-password" required label={t('user.confirmPassword')} value={again} <TextField type="password" autoComplete="new-password" required label={t('user.confirmPassword')} value={again}
onChange={(e) => setAgain(e.target.value)} error={!!err.again} helperText={err.again} slotProps={{ htmlInput: { dir: 'ltr' } }} /> onChange={(e) => setAgain(e.target.value)} error={!!err.again} helperText={err.again} slotProps={{ htmlInput: { dir: 'ltr' } }} />
</Stack> </Stack>