mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-26 13:02:50 +00:00
Merge remote-tracking branch 'origin/WorkflowChange' into feature/exam-attempt-domain
# Conflicts: # apps/portal/src/app/features/exams/pages/ExamsPage/columns.tsx # apps/portal/src/app/features/exams/pages/ExamsPage/index.tsx # libs/api/src/lib/features/licensing/licensing.helpers.ts # libs/auth/src/lib/components/AuthBootstrap.tsx
This commit is contained in:
@@ -2,7 +2,10 @@ export * from './lib/base-api';
|
||||
export * from './lib/query-and-mutation';
|
||||
export * from './lib/session';
|
||||
export * from './lib/features/licensing';
|
||||
export * from './lib/features/location';
|
||||
export * from './lib/features/seafarer';
|
||||
export * from './lib/features/seafarer-registration';
|
||||
export * from './lib/features/seafarer-document';
|
||||
export * from './lib/features/vessel';
|
||||
export { baseQueryWithReauth, configureTokenRefresh } from './lib/base-api/base-query-with-reauth';
|
||||
export { openAuthedDocument } from './lib/base-api/download';
|
||||
export { openAuthedDocument, downloadAuthedFile } from './lib/base-api/download';
|
||||
|
||||
@@ -42,8 +42,13 @@ export const baseQueryWithReauth: BaseQueryFn<
|
||||
try {
|
||||
await _onTokenExpired();
|
||||
result = await baseQuery(args, api, extraOptions);
|
||||
} catch {
|
||||
_onAuthFailure?.();
|
||||
} catch (err) {
|
||||
// Only a rejected refresh token ends the session. A network blip or a
|
||||
// 5xx leaves the original 401 for the screen to report, rather than
|
||||
// throwing the user out of a session that is still valid.
|
||||
if ((err as { sessionExpired?: boolean })?.sessionExpired) {
|
||||
_onAuthFailure?.();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_onAuthFailure?.();
|
||||
|
||||
@@ -41,3 +41,57 @@ export async function openAuthedDocument(
|
||||
// Revoking immediately would race the new tab's load.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads an authenticated endpoint straight to a file.
|
||||
*
|
||||
* Same reason as `openAuthedDocument` for bypassing RTK Query — `fetchBaseQuery`
|
||||
* would parse a CSV body as JSON — but a spreadsheet is something you save, not
|
||||
* something the browser can display, so this always takes the anchor path.
|
||||
*
|
||||
* The server names the file via `Content-Disposition`, and the API's CORS
|
||||
* config exposes that header along with `X-Total-Rows` and `X-Truncated`; those
|
||||
* two are returned so a caller can say when an export was cut short instead of
|
||||
* handing over a silently partial file.
|
||||
*/
|
||||
export async function downloadAuthedFile(
|
||||
path: string,
|
||||
fallbackName: string,
|
||||
): Promise<{ rowCount: number | null; truncated: boolean }> {
|
||||
const token = resolveTokenFromStorage();
|
||||
const response = await fetch(`${BASE_API_URL}${path}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
if (!response.ok) {
|
||||
let message = `${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
message = body?.message ?? message;
|
||||
} catch {
|
||||
/* non-JSON error body — the status is all we have */
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = filenameFrom(response.headers) ?? fallbackName;
|
||||
anchor.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
|
||||
const rows = response.headers.get('X-Total-Rows');
|
||||
return {
|
||||
rowCount: rows === null ? null : Number(rows),
|
||||
truncated: response.headers.get('X-Truncated') === 'true',
|
||||
};
|
||||
}
|
||||
|
||||
/** `attachment; filename="vessel-register-2026-08-18.csv"` → the file name. */
|
||||
function filenameFrom(headers: Headers): string | null {
|
||||
const disposition = headers.get('Content-Disposition');
|
||||
if (!disposition) return null;
|
||||
const match = /filename="?([^";]+)"?/.exec(disposition);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const tagTypes = ["ProfessionApi"];
|
||||
export const tagTypes = ["ProfessionApi", "NumberFormatApi"];
|
||||
|
||||
@@ -398,8 +398,11 @@ export const licensingApi = baseApi
|
||||
* claim or a decision refreshes the badges along with the list and the
|
||||
* numbers can never drift from what the grid is showing.
|
||||
*/
|
||||
getQueueCounts: builder.query<QueueCounts, void>({
|
||||
query: () => ({ url: '/license-application-review/counts' }),
|
||||
getQueueCounts: builder.query<QueueCounts, string | void>({
|
||||
query: (licenseTypeKey) => ({
|
||||
url: '/license-application-review/counts',
|
||||
params: licenseTypeKey ? { licenseTypeKey } : undefined,
|
||||
}),
|
||||
providesTags: () => [listTag('ApplicationQueue')],
|
||||
}),
|
||||
|
||||
@@ -721,6 +724,28 @@ export const licensingApi = baseApi
|
||||
error ? [] : [itemTag('LicenseApplication', id), listTag('ApplicationQueue')],
|
||||
}),
|
||||
|
||||
scheduleIssuance: builder.mutation<
|
||||
LicenseApplication,
|
||||
{ id: string; scheduledDate: string }
|
||||
>({
|
||||
query: ({ id, scheduledDate }) => ({
|
||||
url: `/license-application-review/${id}/schedule-issuance`,
|
||||
method: 'POST',
|
||||
body: { scheduledDate },
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) =>
|
||||
error ? [] : [itemTag('LicenseApplication', id), listTag('ApplicationQueue')],
|
||||
}),
|
||||
|
||||
issueCertificate: builder.mutation<LicenseApplication, string>({
|
||||
query: (id) => ({
|
||||
url: `/license-application-review/${id}/issue-certificate`,
|
||||
method: 'POST',
|
||||
}),
|
||||
invalidatesTags: (_r, error, id) =>
|
||||
error ? [] : [itemTag('LicenseApplication', id), listTag('ApplicationQueue')],
|
||||
}),
|
||||
|
||||
// --------------------------------------------------------- inspection
|
||||
scheduleInspection: builder.mutation<
|
||||
Inspection,
|
||||
@@ -841,6 +866,8 @@ export const {
|
||||
useScheduleExamMutation,
|
||||
useRequestExamPaymentMutation,
|
||||
useConfirmPaymentMutation,
|
||||
useScheduleIssuanceMutation,
|
||||
useIssueCertificateMutation,
|
||||
useScheduleInspectionMutation,
|
||||
useGetInspectionsQuery,
|
||||
useRecordInspectionResultMutation,
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { resolveTokenFromStorage } from "../../session";
|
||||
import { resolveTokenFromStorage } from '../../session';
|
||||
import type {
|
||||
Bilingual,
|
||||
FamilyKind,
|
||||
FormFieldConfig,
|
||||
FormSectionConfig,
|
||||
LicenseApplication,
|
||||
LicenseStatus,
|
||||
ValidationIssue,
|
||||
} from "./licensing.types";
|
||||
} from './licensing.types';
|
||||
|
||||
const BASE_API_URL =
|
||||
(import.meta as { env?: Record<string, string> }).env?.[
|
||||
"VITE_BASE_API_URL"
|
||||
] ?? "http://localhost:3001/api";
|
||||
(import.meta as { env?: Record<string, string> }).env?.['VITE_BASE_API_URL'] ??
|
||||
'http://localhost:3000/api';
|
||||
|
||||
/**
|
||||
* Uploads a document straight to the API.
|
||||
@@ -21,12 +22,13 @@ const BASE_API_URL =
|
||||
*/
|
||||
export async function uploadDocument(params: {
|
||||
ownerType:
|
||||
| "APPLICATION"
|
||||
| "APPLICATION_STAFF"
|
||||
| "INSPECTION"
|
||||
| "LICENSE"
|
||||
| "SEA_SERVICE_RECORD"
|
||||
| "MEDICAL_CERTIFICATE";
|
||||
| 'APPLICATION'
|
||||
| 'APPLICATION_STAFF'
|
||||
| 'INSPECTION'
|
||||
| 'LICENSE'
|
||||
| 'SEA_SERVICE_RECORD'
|
||||
| 'MEDICAL_CERTIFICATE'
|
||||
| 'SEAFARER_REGISTRATION';
|
||||
ownerId: string;
|
||||
documentKey: string;
|
||||
file: File;
|
||||
@@ -35,17 +37,17 @@ export async function uploadDocument(params: {
|
||||
validTo?: string;
|
||||
}): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
const form = new FormData();
|
||||
form.append("ownerType", params.ownerType);
|
||||
form.append("ownerId", params.ownerId);
|
||||
form.append("documentKey", params.documentKey);
|
||||
if (params.title) form.append("title", params.title);
|
||||
if (params.validFrom) form.append("validFrom", params.validFrom);
|
||||
if (params.validTo) form.append("validTo", params.validTo);
|
||||
form.append("files", params.file, params.file.name);
|
||||
form.append('ownerType', params.ownerType);
|
||||
form.append('ownerId', params.ownerId);
|
||||
form.append('documentKey', params.documentKey);
|
||||
if (params.title) form.append('title', params.title);
|
||||
if (params.validFrom) form.append('validFrom', params.validFrom);
|
||||
if (params.validTo) form.append('validTo', params.validTo);
|
||||
form.append('files', params.file, params.file.name);
|
||||
|
||||
const token = resolveTokenFromStorage();
|
||||
const res = await fetch(`${BASE_API_URL}/attachments`, {
|
||||
method: "POST",
|
||||
method: 'POST',
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
body: form,
|
||||
});
|
||||
@@ -56,40 +58,55 @@ export async function uploadDocument(params: {
|
||||
|
||||
/** Human label for a status, in the vocabulary the user stories use. */
|
||||
export const STATUS_LABELS: Record<LicenseStatus, string> = {
|
||||
DRAFT: "Draft",
|
||||
SUBMITTED: "Submitted",
|
||||
UNDER_REVIEW: "Under Review",
|
||||
UNDER_EVALUATION: "Under Evaluation",
|
||||
RESUBMIT_REQUIRED: "Resubmit Required",
|
||||
INSPECTION_PENDING: "Inspection Pending",
|
||||
INSPECTION_COMPLETED: "Inspection Completed",
|
||||
APPROVED: "Approved",
|
||||
REJECTED: "Rejected",
|
||||
ON_HOLD: "On Hold",
|
||||
PAYMENT_PENDING: "Payment Pending",
|
||||
PAID: "Paid",
|
||||
PAYMENT_CONFIRMED: "Preparing Certificate",
|
||||
CERTIFICATE_ISSUED: "Certificate Issued",
|
||||
COMPLETED: "Completed",
|
||||
DRAFT: 'Draft',
|
||||
SUBMITTED: 'Submitted',
|
||||
UNDER_REVIEW: 'Under Review',
|
||||
UNDER_EVALUATION: 'Under Evaluation',
|
||||
RESUBMIT_REQUIRED: 'Resubmit Required',
|
||||
INSPECTION_PENDING: 'Inspection Pending',
|
||||
INSPECTION_COMPLETED: 'Inspection Completed',
|
||||
APPROVED: 'Approved',
|
||||
REJECTED: 'Rejected',
|
||||
ON_HOLD: 'On Hold',
|
||||
PAYMENT_PENDING: 'Payment Pending',
|
||||
PAID: 'Paid',
|
||||
PAYMENT_CONFIRMED: 'Preparing Certificate',
|
||||
SCHEDULED: 'Pickup Scheduled',
|
||||
CERTIFICATE_ISSUED: 'Certificate Issued',
|
||||
COMPLETED: 'Completed',
|
||||
ELIGIBILITY_APPROVED: 'Eligible to Sit',
|
||||
EXAM_PAYMENT_PENDING: 'Exam Fee Due',
|
||||
EXAM_PAID: 'Awaiting Exam Date',
|
||||
EXAM_SCHEDULED: 'Exam Scheduled',
|
||||
EXAM_PASSED: 'Exam Passed',
|
||||
EXAM_FAILED: 'Exam Not Passed',
|
||||
};
|
||||
|
||||
/** Mantine colour per status — green progresses, orange needs the applicant. */
|
||||
export const STATUS_COLORS: Record<LicenseStatus, string> = {
|
||||
DRAFT: "gray",
|
||||
SUBMITTED: "blue",
|
||||
UNDER_REVIEW: "indigo",
|
||||
UNDER_EVALUATION: "indigo",
|
||||
RESUBMIT_REQUIRED: "orange",
|
||||
INSPECTION_PENDING: "cyan",
|
||||
INSPECTION_COMPLETED: "cyan",
|
||||
APPROVED: "teal",
|
||||
REJECTED: "red",
|
||||
ON_HOLD: "gray",
|
||||
PAYMENT_PENDING: "yellow",
|
||||
PAID: "lime",
|
||||
PAYMENT_CONFIRMED: "teal",
|
||||
CERTIFICATE_ISSUED: "green",
|
||||
COMPLETED: "green",
|
||||
DRAFT: 'gray',
|
||||
SUBMITTED: 'blue',
|
||||
UNDER_REVIEW: 'indigo',
|
||||
UNDER_EVALUATION: 'indigo',
|
||||
RESUBMIT_REQUIRED: 'orange',
|
||||
INSPECTION_PENDING: 'cyan',
|
||||
INSPECTION_COMPLETED: 'cyan',
|
||||
APPROVED: 'teal',
|
||||
REJECTED: 'red',
|
||||
ON_HOLD: 'gray',
|
||||
PAYMENT_PENDING: 'yellow',
|
||||
PAID: 'lime',
|
||||
PAYMENT_CONFIRMED: 'teal',
|
||||
SCHEDULED: 'cyan',
|
||||
CERTIFICATE_ISSUED: 'green',
|
||||
COMPLETED: 'green',
|
||||
ELIGIBILITY_APPROVED: 'teal',
|
||||
EXAM_PAYMENT_PENDING: 'yellow',
|
||||
EXAM_PAID: 'lime',
|
||||
EXAM_SCHEDULED: 'cyan',
|
||||
EXAM_PASSED: 'teal',
|
||||
// Orange, not red: a failure is recoverable here — the candidate resits.
|
||||
EXAM_FAILED: 'orange',
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -112,6 +129,7 @@ export const STATUS_PROGRESS: Record<LicenseStatus, number> = {
|
||||
PAYMENT_PENDING: 80,
|
||||
PAID: 88,
|
||||
PAYMENT_CONFIRMED: 94,
|
||||
SCHEDULED: 97,
|
||||
CERTIFICATE_ISSUED: 100,
|
||||
COMPLETED: 100,
|
||||
REJECTED: 100,
|
||||
@@ -128,59 +146,180 @@ export const STATUS_PROGRESS: Record<LicenseStatus, number> = {
|
||||
|
||||
/** Statuses where nothing moves until the applicant does something. */
|
||||
export const APPLICANT_ACTION_STATUSES: LicenseStatus[] = [
|
||||
"DRAFT",
|
||||
"RESUBMIT_REQUIRED",
|
||||
"PAYMENT_PENDING",
|
||||
'DRAFT',
|
||||
'RESUBMIT_REQUIRED',
|
||||
'PAYMENT_PENDING',
|
||||
// Both wait on the candidate: one to pay for a sitting, one to decide to
|
||||
// sit again after a failure.
|
||||
'EXAM_PAYMENT_PENDING',
|
||||
'EXAM_FAILED',
|
||||
];
|
||||
|
||||
/** Statuses that are finished, whichever way they went. */
|
||||
export const TERMINAL_STATUSES: LicenseStatus[] = [
|
||||
"CERTIFICATE_ISSUED",
|
||||
"COMPLETED",
|
||||
"REJECTED",
|
||||
'CERTIFICATE_ISSUED',
|
||||
'COMPLETED',
|
||||
'REJECTED',
|
||||
];
|
||||
|
||||
/** Licence types with no `companyName` — these are filed by a person, not a
|
||||
* business, so display falls back to the applicant name captured in the form. */
|
||||
export const APPLICANT_NAME_TYPE_KEYS = [
|
||||
"SEAFARER_REGISTRATION",
|
||||
"CERTIFICATE_OF_COMPETENCY",
|
||||
"CERTIFICATE_OF_PROFICIENCY",
|
||||
"VESSEL_REGISTRATION",
|
||||
"VESSEL_OWNERSHIP_TRANSFER",
|
||||
"ENDORSEMENT_COC",
|
||||
"ENDORSEMENT_GOC",
|
||||
'SEAFARER_REGISTRATION',
|
||||
'CERTIFICATE_OF_COMPETENCY',
|
||||
'CERTIFICATE_OF_PROFICIENCY',
|
||||
'VESSEL_REGISTRATION',
|
||||
'VESSEL_OWNERSHIP_TRANSFER',
|
||||
'ENDORSEMENT_COC',
|
||||
'ENDORSEMENT_GOC',
|
||||
];
|
||||
|
||||
/** Company name, or applicant name for licence types that have no company. */
|
||||
export function applicantOrCompanyName(
|
||||
app: LicenseApplication,
|
||||
): string | undefined {
|
||||
if (
|
||||
!app.licenseType?.key ||
|
||||
!APPLICANT_NAME_TYPE_KEYS.includes(app.licenseType.key)
|
||||
) {
|
||||
const FAMILY_KIND_BY_KEY: Partial<Record<string, FamilyKind>> = {
|
||||
SEAFARER_REGISTRATION: 'DOCUMENT',
|
||||
SEAMAN_BOOK: 'DOCUMENT',
|
||||
VESSEL_REGISTRATION: 'DOCUMENT',
|
||||
BTC_BASIC_TRAINING: 'CERTIFICATE',
|
||||
CERTIFICATE_OF_COMPETENCY: 'CERTIFICATE',
|
||||
CERTIFICATE_OF_PROFICIENCY: 'CERTIFICATE',
|
||||
ENDORSEMENT_COC: 'CERTIFICATE',
|
||||
ENDORSEMENT_GOC: 'CERTIFICATE',
|
||||
FREIGHT_FORWARDER: 'LOGISTICS_LICENSE',
|
||||
SHIPPING_AGENT: 'LOGISTICS_LICENSE',
|
||||
COMBINED_SA_FF: 'LOGISTICS_LICENSE',
|
||||
MULTIMODAL_TRANSPORT_OPERATOR: 'LOGISTICS_LICENSE',
|
||||
JOINT_INVESTOR: 'LOGISTICS_LICENSE',
|
||||
};
|
||||
|
||||
/**
|
||||
* `FamilyKind` for a type key, for data that predates `familyKind` being a
|
||||
* real column on the server (cached responses from before the rollout, or
|
||||
* anything that only ever had a bare key to go on). Every fresh response now
|
||||
* carries `familyKind` directly from the server's own `family_kind` column —
|
||||
* prefer that over calling this. Kept only as a fallback, and only for keys
|
||||
* this map happens to know about; falls back further to `LOGISTICS_LICENSE`
|
||||
* for anything else, reproducing today's "Licence ___" wording — the safe
|
||||
* default for an unrecognised key.
|
||||
*/
|
||||
export function resolveFamilyKind(licenseTypeKey: string | undefined | null): FamilyKind {
|
||||
return (licenseTypeKey && FAMILY_KIND_BY_KEY[licenseTypeKey]) || 'LOGISTICS_LICENSE';
|
||||
}
|
||||
|
||||
export interface FamilyLabels {
|
||||
/** e.g. "Certificate", "Document", "Licence". */
|
||||
typeLabel: string;
|
||||
/** e.g. "Certificate Number", "Document Number", "Licence Number". */
|
||||
numberLabel: string;
|
||||
/** e.g. "Certificate Holder", "Document Holder", "Licence Holder". */
|
||||
holderLabel: string;
|
||||
/** e.g. "Certificate Review", "Document Review", "Licence Review". */
|
||||
reviewLabel: string;
|
||||
}
|
||||
|
||||
const FAMILY_LABELS: Record<FamilyKind, FamilyLabels> = {
|
||||
CERTIFICATE: {
|
||||
typeLabel: 'Certificate',
|
||||
numberLabel: 'Certificate Number',
|
||||
holderLabel: 'Certificate Holder',
|
||||
reviewLabel: 'Certificate Review',
|
||||
},
|
||||
DOCUMENT: {
|
||||
typeLabel: 'Document',
|
||||
numberLabel: 'Document Number',
|
||||
holderLabel: 'Document Holder',
|
||||
reviewLabel: 'Document Review',
|
||||
},
|
||||
LOGISTICS_LICENSE: {
|
||||
typeLabel: 'Licence',
|
||||
numberLabel: 'Licence Number',
|
||||
holderLabel: 'Licence Holder',
|
||||
reviewLabel: 'Licence Review',
|
||||
},
|
||||
};
|
||||
|
||||
export function familyLabels(familyKind: FamilyKind): FamilyLabels {
|
||||
return FAMILY_LABELS[familyKind];
|
||||
}
|
||||
|
||||
/**
|
||||
* Company name, or applicant name for applications with no company.
|
||||
*
|
||||
* Branches on `familyKind` — the real data-model column — rather than a
|
||||
* hand-maintained key list. A certificate or document is filed by a person,
|
||||
* never a business, so it never has a `companyName` to show; a logistics
|
||||
* licence always does. This is what used to be `APPLICANT_NAME_TYPE_KEYS`, a
|
||||
* frontend array that had to be remembered and kept in sync by hand every
|
||||
* time a new certificate/document type was added — it silently missed
|
||||
* `SEAMAN_BOOK`/`BTC_BASIC_TRAINING`, which is why those rows rendered "—"
|
||||
* instead of the applicant's name in the backoffice queue. `familyKind` is
|
||||
* correct for every current and future type without a matching array update.
|
||||
*/
|
||||
export function applicantOrCompanyName(app: LicenseApplication): string | undefined {
|
||||
if (app.familyKind === 'LOGISTICS_LICENSE') {
|
||||
return app.companyName ?? undefined;
|
||||
}
|
||||
const applicantName = (
|
||||
app.formData?.account as Record<string, unknown> | undefined
|
||||
)?.applicantName;
|
||||
return typeof applicantName === "string" && applicantName
|
||||
? applicantName
|
||||
: undefined;
|
||||
const applicantName = (app.formData?.account as Record<string, unknown> | undefined)
|
||||
?.applicantName;
|
||||
return typeof applicantName === 'string' && applicantName ? applicantName : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* One form answer as a person should read it back.
|
||||
*
|
||||
* The stored value is not it: a SELECT holds the option's `value`, so an
|
||||
* unformatted view shows reviewers and applicants `AB_POSITIVE` and `DECK` —
|
||||
* the codes the database wants, not the words that were chosen. Shared by the
|
||||
* applicant's summary and the officer's review so the two never describe the
|
||||
* same application differently.
|
||||
*
|
||||
* `showDate` is passed in rather than imported: date display is a hook
|
||||
* (`useDateDisplayer`, Ethiopian-calendar aware) and this is a plain function.
|
||||
*/
|
||||
export function displayFieldValue(
|
||||
field: Pick<FormFieldConfig, 'type' | 'options'>,
|
||||
raw: unknown,
|
||||
opts: {
|
||||
language?: string;
|
||||
showDate?: (value: string) => string;
|
||||
currency?: string;
|
||||
} = {},
|
||||
): string {
|
||||
if (raw === null || raw === undefined || raw === '') return '';
|
||||
const { language = 'en', showDate, currency } = opts;
|
||||
|
||||
switch (field.type) {
|
||||
case 'BOOLEAN':
|
||||
return raw ? 'Yes' : 'No';
|
||||
case 'DATE':
|
||||
return showDate?.(String(raw)) || String(raw);
|
||||
case 'SELECT': {
|
||||
const option = field.options?.find((o) => o.value === raw);
|
||||
// Falls back to the stored value rather than blanking: an option removed
|
||||
// from the config since this was filed still has to show what was chosen.
|
||||
return option ? localized(option.label, language) : String(raw);
|
||||
}
|
||||
case 'MONEY': {
|
||||
const amount = Number(raw);
|
||||
return Number.isFinite(amount)
|
||||
? `${amount.toLocaleString()} ${currency ?? ''}`.trim()
|
||||
: String(raw);
|
||||
}
|
||||
default:
|
||||
return String(raw);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a bilingual value for the active language, falling back to English. */
|
||||
export function localized(
|
||||
value: Bilingual | undefined,
|
||||
language = "en",
|
||||
): string {
|
||||
if (!value) return "";
|
||||
export function localized(value: Bilingual | undefined, language = 'en'): string {
|
||||
if (!value) return '';
|
||||
// `||` not `??`: an empty Amharic string is "not translated", not a value —
|
||||
// editors save `am: ''` freely (ExamPage, CertificationPage, LocationForm).
|
||||
return (
|
||||
(language === "am" ? value.am : value.en) || value.en || value.am || ""
|
||||
);
|
||||
//
|
||||
// Keyed by the active language rather than an en/am ternary, so a locale the
|
||||
// backend stores but the UI does not yet offer a switcher for (`om`, `so` on
|
||||
// location names) still resolves once it does. English then Amharic remain
|
||||
// the fallbacks, in that order.
|
||||
const active = value[language as keyof Bilingual];
|
||||
return active || value.en || value.am || '';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -190,7 +329,7 @@ export function localized(
|
||||
export function extractValidationIssues(error: unknown): ValidationIssue[] {
|
||||
const data = (error as { data?: Record<string, unknown> })?.data;
|
||||
if (!data) return [];
|
||||
const issues = data["issues"];
|
||||
const issues = data['issues'];
|
||||
return Array.isArray(issues) ? (issues as ValidationIssue[]) : [];
|
||||
}
|
||||
|
||||
@@ -202,54 +341,47 @@ export function extractValidationIssues(error: unknown): ValidationIssue[] {
|
||||
*/
|
||||
const ERROR_MESSAGES: Record<string, string> = {
|
||||
capital_verification_required:
|
||||
"Record the verified capital before approving — it must be checked against the bank letter.",
|
||||
'Record the verified capital before approving — it must be checked against the bank letter.',
|
||||
capital_below_threshold:
|
||||
"The verified capital is below the minimum required for this licence type.",
|
||||
'The verified capital is below the minimum required for this licence type.',
|
||||
inspection_required_before_approval:
|
||||
"A physical inspection must be recorded before this application can be approved.",
|
||||
application_already_claimed:
|
||||
"Another officer has already claimed this application.",
|
||||
'A physical inspection must be recorded before this application can be approved.',
|
||||
application_already_claimed: 'Another officer has already claimed this application.',
|
||||
assigned_to_another_officer:
|
||||
"This application is assigned to another officer, so only they can act on it.",
|
||||
not_application_owner: "This application belongs to another applicant.",
|
||||
application_incomplete: "The application is missing required information.",
|
||||
unresolved_remarks: "Every requested correction must be addressed first.",
|
||||
adjustment_items_required:
|
||||
"Flag at least one item before requesting an adjustment.",
|
||||
remark_text_required:
|
||||
"Each flagged item needs a remark explaining what to fix.",
|
||||
rejection_reason_required: "A rejection reason is required.",
|
||||
'This application is assigned to another officer, so only they can act on it.',
|
||||
not_application_owner: 'This application belongs to another applicant.',
|
||||
application_incomplete: 'The application is missing required information.',
|
||||
unresolved_remarks: 'Every requested correction must be addressed first.',
|
||||
adjustment_items_required: 'Flag at least one item before requesting an adjustment.',
|
||||
remark_text_required: 'Each flagged item needs a remark explaining what to fix.',
|
||||
rejection_reason_required: 'A rejection reason is required.',
|
||||
section_not_flagged_for_adjustment:
|
||||
"Only the sections the officer flagged can be changed in this round.",
|
||||
application_not_editable: "This application can no longer be edited.",
|
||||
invalid_transition: "That action is not available at this stage.",
|
||||
'Only the sections the officer flagged can be changed in this round.',
|
||||
application_not_editable: 'This application can no longer be edited.',
|
||||
invalid_transition: 'That action is not available at this stage.',
|
||||
inspection_not_required_use_final_approve:
|
||||
"This licence type needs no inspection — approve it directly.",
|
||||
'This licence type needs no inspection — approve it directly.',
|
||||
application_not_awaiting_inspection:
|
||||
"This application is not waiting for an inspection.",
|
||||
inspection_already_completed: "This inspection has already been recorded.",
|
||||
license_type_inactive:
|
||||
"This licence type is not currently accepting applications.",
|
||||
'This application is not waiting for an inspection.',
|
||||
inspection_already_completed: 'This inspection has already been recorded.',
|
||||
license_type_inactive: 'This licence type is not currently accepting applications.',
|
||||
};
|
||||
|
||||
export function extractErrorMessage(
|
||||
error: unknown,
|
||||
fallback = "Something went wrong",
|
||||
): string {
|
||||
export function extractErrorMessage(error: unknown, fallback = 'Something went wrong'): string {
|
||||
const data = (error as { data?: Record<string, unknown> })?.data;
|
||||
const raw = data?.["message"];
|
||||
const raw = data?.['message'];
|
||||
|
||||
// The filter passes structured errors through as `{ message: { message } }`.
|
||||
const key =
|
||||
typeof raw === "string"
|
||||
typeof raw === 'string'
|
||||
? raw
|
||||
: typeof (raw as { message?: unknown })?.message === "string"
|
||||
? (raw as { message: string }).message
|
||||
: typeof (raw as { message?: unknown })?.message === 'string'
|
||||
? ((raw as { message: string }).message)
|
||||
: undefined;
|
||||
|
||||
if (key && ERROR_MESSAGES[key]) return ERROR_MESSAGES[key];
|
||||
if (typeof raw === "string") return raw;
|
||||
if (Array.isArray(raw)) return raw.join(", ");
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (Array.isArray(raw)) return raw.join(', ');
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@@ -257,7 +389,7 @@ export function extractErrorMessage(
|
||||
export interface WizardStep {
|
||||
key: string;
|
||||
label: string;
|
||||
kind: "sections" | "staff" | "documents" | "review";
|
||||
kind: 'sections' | 'staff' | 'documents' | 'review';
|
||||
sections: FormSectionConfig[];
|
||||
}
|
||||
|
||||
@@ -268,6 +400,16 @@ export interface WizardStep {
|
||||
* the stepper short. Anything ungrouped keeps a step of its own, so a licence
|
||||
* type that has not been grouped still behaves exactly as before.
|
||||
*/
|
||||
/** "identitySummary" -> "Identity Summary". Last resort for an untitled group. */
|
||||
function humanise(key: string): string {
|
||||
return key
|
||||
.replace(/[_-]+/g, ' ')
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.replace(/^./, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
export function buildWizardSteps(
|
||||
sections: FormSectionConfig[],
|
||||
formData: Record<string, Record<string, unknown>>,
|
||||
@@ -296,7 +438,7 @@ export function buildWizardSteps(
|
||||
steps.push({
|
||||
key: `section:${section.key}`,
|
||||
label: localized(section.title, options?.language),
|
||||
kind: "sections",
|
||||
kind: 'sections',
|
||||
sections: [section],
|
||||
});
|
||||
continue;
|
||||
@@ -308,8 +450,12 @@ export function buildWizardSteps(
|
||||
}
|
||||
const step: WizardStep = {
|
||||
key: `group:${group}`,
|
||||
label: group,
|
||||
kind: "sections",
|
||||
// A group is a config key, not a caption — showing it raw put
|
||||
// "identitySummary" and "applicant" in front of applicants. The first
|
||||
// section's own title is the readable name for the step it opens; the
|
||||
// humanised key is the fallback when a section carries no title.
|
||||
label: localized(section.title, options?.language) || humanise(group),
|
||||
kind: 'sections',
|
||||
sections: [section],
|
||||
};
|
||||
byGroup.set(group, step);
|
||||
@@ -325,7 +471,7 @@ export function buildWizardSteps(
|
||||
// beside the summary rather than earning a step of their own. It is what
|
||||
// keeps a one-checkbox declaration from costing a whole page.
|
||||
const isReviewGroup = (step: WizardStep) =>
|
||||
step.sections.some((s) => s.group?.trim().toLowerCase() === "review");
|
||||
step.sections.some((s) => s.group?.trim().toLowerCase() === 'review');
|
||||
const reviewSections = steps.filter(isReviewGroup).flatMap((s) => s.sections);
|
||||
const formSteps = steps.filter((step) => !isReviewGroup(step));
|
||||
|
||||
@@ -333,21 +479,9 @@ export function buildWizardSteps(
|
||||
...formSteps,
|
||||
...(options?.hasStaff === false
|
||||
? []
|
||||
: [
|
||||
{
|
||||
key: "staff",
|
||||
label: "Staff",
|
||||
kind: "staff",
|
||||
sections: [],
|
||||
} as WizardStep,
|
||||
]),
|
||||
{ key: "documents", label: "Documents", kind: "documents", sections: [] },
|
||||
{
|
||||
key: "review",
|
||||
label: "Review",
|
||||
kind: "review",
|
||||
sections: reviewSections,
|
||||
},
|
||||
: [{ key: 'staff', label: 'Staff', kind: 'staff', sections: [] } as WizardStep]),
|
||||
{ key: 'documents', label: 'Documents', kind: 'documents', sections: [] },
|
||||
{ key: 'review', label: 'Review', kind: 'review', sections: reviewSections },
|
||||
];
|
||||
}
|
||||
|
||||
@@ -362,7 +496,7 @@ export type FieldErrors = Record<string, string>;
|
||||
export function validateSections(
|
||||
sections: FormSectionConfig[],
|
||||
formData: Record<string, Record<string, unknown>>,
|
||||
language = "en",
|
||||
language = 'en',
|
||||
): FieldErrors {
|
||||
const errors: FieldErrors = {};
|
||||
|
||||
@@ -379,13 +513,13 @@ export function validateSections(
|
||||
const empty =
|
||||
value === undefined ||
|
||||
value === null ||
|
||||
(typeof value === "string" && value.trim() === "") ||
|
||||
(typeof value === "boolean" && value === false) ||
|
||||
(typeof value === 'string' && value.trim() === '') ||
|
||||
(typeof value === 'boolean' && value === false) ||
|
||||
(Array.isArray(value) && value.length === 0);
|
||||
|
||||
if (field.required && empty) {
|
||||
errors[`${section.key}.${field.key}`] =
|
||||
field.type === "BOOLEAN"
|
||||
field.type === 'BOOLEAN'
|
||||
? `${localized(field.label, language)} must be accepted`
|
||||
: `${localized(field.label, language)} is required`;
|
||||
continue;
|
||||
@@ -410,33 +544,23 @@ export function validateSections(
|
||||
/** Evaluates a config condition against the current form answers. */
|
||||
export function conditionHolds(
|
||||
condition:
|
||||
| {
|
||||
field: string;
|
||||
equals?: unknown;
|
||||
notEquals?: unknown;
|
||||
in?: (string | number)[];
|
||||
isSet?: boolean;
|
||||
}
|
||||
| { field: string; equals?: unknown; notEquals?: unknown; in?: (string | number)[]; isSet?: boolean }
|
||||
| undefined
|
||||
| null,
|
||||
formData: Record<string, Record<string, unknown>>,
|
||||
): boolean {
|
||||
if (!condition?.field) return true;
|
||||
const value = condition.field
|
||||
.split(".")
|
||||
.split('.')
|
||||
.reduce<unknown>(
|
||||
(acc, key) =>
|
||||
acc && typeof acc === "object"
|
||||
? (acc as Record<string, unknown>)[key]
|
||||
: undefined,
|
||||
acc && typeof acc === 'object' ? (acc as Record<string, unknown>)[key] : undefined,
|
||||
formData as unknown,
|
||||
);
|
||||
const isEmpty = value === undefined || value === null || value === "";
|
||||
if (condition.isSet !== undefined)
|
||||
return condition.isSet ? !isEmpty : isEmpty;
|
||||
const isEmpty = value === undefined || value === null || value === '';
|
||||
if (condition.isSet !== undefined) return condition.isSet ? !isEmpty : isEmpty;
|
||||
if (condition.equals !== undefined) return value === condition.equals;
|
||||
if (condition.notEquals !== undefined) return value !== condition.notEquals;
|
||||
if (condition.in !== undefined)
|
||||
return condition.in.includes(value as string | number);
|
||||
if (condition.in !== undefined) return condition.in.includes(value as string | number);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,20 @@
|
||||
|
||||
// Reused rather than redeclared: the department vocabulary belongs to the
|
||||
// seafarer domain, and two copies would drift.
|
||||
import type { SeafarerDepartment } from '../seafarer/seafarer.types';
|
||||
import type { SeafarerDepartment } from "../seafarer/seafarer.types";
|
||||
|
||||
export type Bilingual = { en?: string; am?: string };
|
||||
/**
|
||||
* A backend `LocaleValidationDto`. Named for the two locales the UI offers, but
|
||||
* carries every locale the column stores — location names are seeded with `om`
|
||||
* (Finfinnee) and `so` too, and a type that declared only en/am made those
|
||||
* unreachable through the typed client.
|
||||
*/
|
||||
export type Bilingual = {
|
||||
en?: string;
|
||||
am?: string;
|
||||
om?: string;
|
||||
so?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The application status vocabulary. Single source of truth for both apps —
|
||||
@@ -24,6 +35,10 @@ export type LicenseStatus =
|
||||
| "PAYMENT_PENDING"
|
||||
| "PAID"
|
||||
| "PAYMENT_CONFIRMED"
|
||||
// Payment confirmed and pickup date set — for a document printed once and
|
||||
// handed over in person (seaman book, BTC). Most license types skip this
|
||||
// and go straight from PAYMENT_CONFIRMED to CERTIFICATE_ISSUED.
|
||||
| "SCHEDULED"
|
||||
| "CERTIFICATE_ISSUED"
|
||||
| "COMPLETED"
|
||||
// Examined certificates (CoC, some CoP): approval establishes eligibility,
|
||||
@@ -87,12 +102,25 @@ export interface FormSectionConfig {
|
||||
|
||||
/** Grouping the portal organises the licence catalogue by. */
|
||||
export type LicenseCategory =
|
||||
| 'CARGO_FREIGHT'
|
||||
| 'SHIPPING_AGENCY'
|
||||
| 'INVESTMENT'
|
||||
| 'MARITIME_PERSONNEL'
|
||||
| 'VESSEL_SERVICES'
|
||||
| 'WAIVER_SERVICES';
|
||||
| "CARGO_FREIGHT"
|
||||
| "SHIPPING_AGENCY"
|
||||
| "INVESTMENT"
|
||||
| "MARITIME_PERSONNEL"
|
||||
| "VESSEL_SERVICES"
|
||||
| "WAIVER_SERVICES";
|
||||
|
||||
/**
|
||||
* Which business concept a licence type actually is — the real data-model
|
||||
* classification (emaapi's `license_types.family_kind` column), not a label
|
||||
* computed from `key`. A permission granted to a logistics operator, a
|
||||
* seafarer's proof of competence, and a seafarer/vessel's identity or
|
||||
* statutory record are three different things to the people using this
|
||||
* system, even though they run through the identical application pipeline —
|
||||
* see BR-MTO-020. Drives terminology, navigation, and which columns a grid
|
||||
* shows (Company/TIN only make sense for LOGISTICS_LICENSE rows) — never a
|
||||
* workflow or eligibility branch.
|
||||
*/
|
||||
export type FamilyKind = "LOGISTICS_LICENSE" | "CERTIFICATE" | "DOCUMENT";
|
||||
|
||||
export interface LicenseCategoryDefinition {
|
||||
key: LicenseCategory;
|
||||
@@ -120,6 +148,8 @@ export interface LicenseType {
|
||||
name: Bilingual;
|
||||
description?: Bilingual;
|
||||
category: LicenseCategory;
|
||||
/** The real data-model classification — see `FamilyKind`. */
|
||||
familyKind: FamilyKind;
|
||||
certificatePrefix: string;
|
||||
feeNewApplication: string | number | null;
|
||||
feeRenewal: string | number | null;
|
||||
@@ -134,6 +164,8 @@ export interface LicenseType {
|
||||
inspectionRequired: boolean;
|
||||
issuesCertificate: boolean;
|
||||
renewalEnabled: boolean;
|
||||
/** Payment confirmation waits for a scheduled pickup date before issuance. */
|
||||
requiresIssuanceScheduling: boolean;
|
||||
/**
|
||||
* False for person-centric registrations (seafarer): they are open to any
|
||||
* authenticated applicant, live outside the operator catalogue, and have
|
||||
@@ -141,6 +173,11 @@ export interface LicenseType {
|
||||
*/
|
||||
requiresOperatorMode: boolean;
|
||||
formSchema: { sections: FormSectionConfig[] };
|
||||
/**
|
||||
* Which course an application of this type runs. REGISTRATION skips the
|
||||
* evaluation and inspection stages, so those statuses are unreachable for it.
|
||||
*/
|
||||
workflowProfile?: WorkflowProfile;
|
||||
isActive: boolean;
|
||||
/** Display order set by EMA; lower comes first. */
|
||||
sortOrder: number;
|
||||
@@ -170,11 +207,7 @@ export interface LicenseType {
|
||||
|
||||
/** What kind of document a certificate type produces. */
|
||||
export type CertificateCategory =
|
||||
| "COC"
|
||||
| "COP"
|
||||
| "ENDORSEMENT"
|
||||
| "GOC"
|
||||
| "NATIONAL";
|
||||
"COC" | "COP" | "ENDORSEMENT" | "GOC" | "NATIONAL";
|
||||
|
||||
/**
|
||||
* STCW responsibility level. Cadet is absent by design — under STCW a cadet is
|
||||
@@ -244,7 +277,10 @@ export interface LicenseApplication {
|
||||
applicationNumber: string;
|
||||
licenseTypeId: string;
|
||||
licenseType?: LicenseType;
|
||||
/** Denormalized from `licenseType.familyKind` at submission time. */
|
||||
familyKind: FamilyKind;
|
||||
applicantUserId: string;
|
||||
parentApplicationId?: string | null;
|
||||
kind: ApplicationKind;
|
||||
status: LicenseStatus;
|
||||
assignedOfficerId: string | null;
|
||||
@@ -263,6 +299,9 @@ export interface LicenseApplication {
|
||||
feeAmount: string | null;
|
||||
feeCurrency: string;
|
||||
issuedLicenseId: string | null;
|
||||
/** Set once an officer schedules pickup for a document requiring in-person handover. */
|
||||
scheduledIssuanceDate: string | null;
|
||||
scheduledBy: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
@@ -324,8 +363,38 @@ export interface ApplicationRemark {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who filed the application, from their profile.
|
||||
*
|
||||
* Served alongside the form because a person-centric service (seafarer
|
||||
* registration, a certificate) has no `companyName` to identify itself by — a
|
||||
* reviewer opening one otherwise sees only an application number and has to
|
||||
* infer the human from the answers.
|
||||
*/
|
||||
export interface ApplicationApplicant {
|
||||
profileId: string;
|
||||
firstName: string | null;
|
||||
middleName: string | null;
|
||||
lastName: string | null;
|
||||
gender: string | null;
|
||||
dob: string | null;
|
||||
pob: string | null;
|
||||
maritalStatus: string | null;
|
||||
seafarerNumber: string | null;
|
||||
seafarerStatus: string | null;
|
||||
seafarerDepartment: string | null;
|
||||
nationality: string | null;
|
||||
idType: string | null;
|
||||
idNumber: string | null;
|
||||
primaryPhoneNumber: string | null;
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
export interface ApplicationDetail {
|
||||
application: LicenseApplication;
|
||||
relatedApplications?: LicenseApplication[];
|
||||
/** Null when the applicant has no profile row (never expected in practice). */
|
||||
applicant: ApplicationApplicant | null;
|
||||
staff: ApplicationStaff[];
|
||||
attachments: Attachment[];
|
||||
history: StatusHistoryEntry[];
|
||||
@@ -382,6 +451,9 @@ export type QueueSortField =
|
||||
| "dueAt"
|
||||
| "claimedAt";
|
||||
|
||||
/** Review → evaluation → (inspection) → approval, or the short registration course. */
|
||||
export type WorkflowProfile = "STANDARD" | "REGISTRATION";
|
||||
|
||||
/** Row counts behind the queue's saved-view tabs. */
|
||||
export interface QueueCounts {
|
||||
unassigned: number;
|
||||
@@ -440,11 +512,7 @@ export interface TemplatePageOptions {
|
||||
|
||||
/** Corner the institute logo is anchored to. */
|
||||
export type TemplateLogoCorner =
|
||||
| 'TOP_LEFT'
|
||||
| 'TOP_CENTER'
|
||||
| 'TOP_RIGHT'
|
||||
| 'BOTTOM_LEFT'
|
||||
| 'BOTTOM_RIGHT';
|
||||
"TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT" | "BOTTOM_LEFT" | "BOTTOM_RIGHT";
|
||||
|
||||
/** Where the institute logo sits on the certificate. */
|
||||
export interface TemplateLogoPlacement {
|
||||
@@ -471,8 +539,8 @@ export interface TemplateFieldPlacement {
|
||||
yPct: number;
|
||||
widthPct: number;
|
||||
fontSize?: number;
|
||||
fontWeight?: 'normal' | 'bold';
|
||||
align?: 'left' | 'center' | 'right';
|
||||
fontWeight?: "normal" | "bold";
|
||||
align?: "left" | "center" | "right";
|
||||
color?: string;
|
||||
}
|
||||
|
||||
@@ -545,7 +613,8 @@ export interface InitiatePaymentResult {
|
||||
|
||||
export interface ApplicationPayment {
|
||||
id: string;
|
||||
applicationId: string;
|
||||
applicationId: string | null;
|
||||
documentId?: string | null;
|
||||
paymentIntentId: string;
|
||||
amount: string;
|
||||
currency: string;
|
||||
@@ -568,6 +637,8 @@ export interface IssuedLicense {
|
||||
certificateNumber: string;
|
||||
licenseTypeId: string;
|
||||
licenseType?: LicenseType;
|
||||
/** Denormalized from `licenseType.familyKind` at issuance time. */
|
||||
familyKind: FamilyKind;
|
||||
applicationId: string;
|
||||
companyName: string | null;
|
||||
tinNumber: string | null;
|
||||
|
||||
1
libs/api/src/lib/features/location/index.ts
Normal file
1
libs/api/src/lib/features/location/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './location.types';
|
||||
47
libs/api/src/lib/features/location/location.types.ts
Normal file
47
libs/api/src/lib/features/location/location.types.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/** Shared location contract — mirrors the `iam.locations` tree in emaapi. */
|
||||
|
||||
import type { Bilingual } from '../licensing/licensing.types';
|
||||
|
||||
/**
|
||||
* One node of the location tree.
|
||||
*
|
||||
* Both apps read the same `/locations` route, so the model lives here rather
|
||||
* than in each app's own feature folder — the two hand-maintained copies had
|
||||
* already drifted (the portal's lacked `locationType`, `children` and the
|
||||
* timestamps, and its query accepted no `parentId` filter even though the
|
||||
* backend supports one).
|
||||
*
|
||||
* `names` is `Bilingual`, the backend's `LocaleValidationDto`: seeded location
|
||||
* names carry `om` and `so` alongside `en`/`am`, which the previous
|
||||
* `{ en, am }` pair made unreachable.
|
||||
*/
|
||||
export interface Location {
|
||||
id: string;
|
||||
code: string;
|
||||
names: Bilingual;
|
||||
locationTypeId: string;
|
||||
parentId: string | null;
|
||||
locationType?: LocationType;
|
||||
children?: Location[];
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A level in the tree. `level` orders them (City 1 → Sub-city 2 → Woreda 3 →
|
||||
* Kebele 4); `code` is what both sides key behaviour off, so it is the field to
|
||||
* match on rather than the display name.
|
||||
*/
|
||||
export interface LocationType {
|
||||
id: string;
|
||||
code: string;
|
||||
names: Bilingual;
|
||||
level: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface ListResponse<T> {
|
||||
count: number;
|
||||
items: T[];
|
||||
}
|
||||
3
libs/api/src/lib/features/seafarer-document/index.ts
Normal file
3
libs/api/src/lib/features/seafarer-document/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './seafarer-document.types';
|
||||
export * from './seafarer-document.constants';
|
||||
export * from './seafarer-document-api';
|
||||
@@ -0,0 +1,131 @@
|
||||
import { baseApi } from '../../base-api';
|
||||
import type { ApplicationPayment, InitiatePaymentResult } from '../licensing/licensing.types';
|
||||
import type {
|
||||
SeafarerDocument,
|
||||
SeafarerDocumentDetail,
|
||||
SeafarerDocumentKind,
|
||||
SeafarerDocumentRow,
|
||||
SeafarerDocumentStatus,
|
||||
} from './seafarer-document.types';
|
||||
|
||||
const TAG = 'SeafarerDocument' as const;
|
||||
const LIST = { type: TAG, id: 'LIST' } as const;
|
||||
const item = (id: string) => ({ type: TAG, id }) as const;
|
||||
|
||||
export interface SeafarerDocumentListFilter {
|
||||
kind?: SeafarerDocumentKind;
|
||||
status?: SeafarerDocumentStatus;
|
||||
search?: string;
|
||||
take?: number;
|
||||
skip?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seaman Book and BTC — own endpoints, not licence applications. Fees settle
|
||||
* through the same payment gateway, under `/seafarer-documents/:id/payments`.
|
||||
*/
|
||||
export const seafarerDocumentApi = baseApi
|
||||
.enhanceEndpoints({ addTagTypes: [TAG] })
|
||||
.injectEndpoints({
|
||||
endpoints: (builder) => ({
|
||||
// ------------------------------------------------------------ applicant
|
||||
getMySeafarerDocuments: builder.query<
|
||||
{ seamanBook: SeafarerDocument | null; btc: SeafarerDocument | null },
|
||||
void
|
||||
>({
|
||||
query: () => ({ url: '/seafarer-documents/mine' }),
|
||||
providesTags: () => [LIST],
|
||||
}),
|
||||
|
||||
getMySeafarerDocumentDownload: builder.query<{ url: string }, string>({
|
||||
query: (id) => ({ url: `/seafarer-documents/${id}/download` }),
|
||||
}),
|
||||
|
||||
initiateDocumentPayment: builder.mutation<
|
||||
InitiatePaymentResult,
|
||||
{ id: string; provider?: string; platform?: 'web' | 'mobile'; payerAccount?: string }
|
||||
>({
|
||||
query: ({ id, ...body }) => ({
|
||||
url: `/seafarer-documents/${id}/payments/initiate`,
|
||||
method: 'POST',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
getDocumentPayment: builder.query<ApplicationPayment, string>({
|
||||
query: (id) => ({ url: `/seafarer-documents/${id}/payments` }),
|
||||
providesTags: (_r, _e, id) => [item(id)],
|
||||
}),
|
||||
|
||||
bypassDocumentPayment: builder.mutation<{ status: SeafarerDocumentStatus }, string>({
|
||||
query: (id) => ({ url: `/seafarer-documents/${id}/payments/bypass`, method: 'POST' }),
|
||||
invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
// --------------------------------------------------------------- review
|
||||
listSeafarerDocuments: builder.query<
|
||||
{ total: number; items: SeafarerDocumentRow[] },
|
||||
SeafarerDocumentListFilter
|
||||
>({
|
||||
query: (params) => ({ url: '/seafarer-document-review', params }),
|
||||
providesTags: () => [LIST],
|
||||
}),
|
||||
|
||||
getSeafarerDocumentReview: builder.query<SeafarerDocumentDetail, string>({
|
||||
query: (id) => ({ url: `/seafarer-document-review/${id}` }),
|
||||
providesTags: (_r, _e, id) => [item(id)],
|
||||
}),
|
||||
|
||||
getSeafarerDocumentReviewDownload: builder.query<{ url: string }, string>({
|
||||
query: (id) => ({ url: `/seafarer-document-review/${id}/download` }),
|
||||
}),
|
||||
|
||||
confirmSeafarerDocumentPayment: builder.mutation<SeafarerDocument, string>({
|
||||
query: (id) => ({ url: `/seafarer-document-review/${id}/confirm-payment`, method: 'POST' }),
|
||||
invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
scheduleSeafarerDocument: builder.mutation<
|
||||
SeafarerDocument,
|
||||
{ id: string; scheduledDate: string }
|
||||
>({
|
||||
query: ({ id, ...body }) => ({
|
||||
url: `/seafarer-document-review/${id}/schedule-issuance`,
|
||||
method: 'POST',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
issueSeafarerDocument: builder.mutation<SeafarerDocument, string>({
|
||||
query: (id) => ({ url: `/seafarer-document-review/${id}/issue`, method: 'POST' }),
|
||||
invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
rejectSeafarerDocument: builder.mutation<SeafarerDocument, { id: string; reason: string }>({
|
||||
query: ({ id, ...body }) => ({
|
||||
url: `/seafarer-document-review/${id}/reject`,
|
||||
method: 'POST',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
}),
|
||||
overrideExisting: false,
|
||||
});
|
||||
|
||||
export const {
|
||||
useGetMySeafarerDocumentsQuery,
|
||||
useLazyGetMySeafarerDocumentDownloadQuery,
|
||||
useInitiateDocumentPaymentMutation,
|
||||
useGetDocumentPaymentQuery,
|
||||
useBypassDocumentPaymentMutation,
|
||||
useListSeafarerDocumentsQuery,
|
||||
useGetSeafarerDocumentReviewQuery,
|
||||
useLazyGetSeafarerDocumentReviewDownloadQuery,
|
||||
useConfirmSeafarerDocumentPaymentMutation,
|
||||
useScheduleSeafarerDocumentMutation,
|
||||
useIssueSeafarerDocumentMutation,
|
||||
useRejectSeafarerDocumentMutation,
|
||||
} = seafarerDocumentApi;
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { SeafarerDocumentKind, SeafarerDocumentStatus } from './seafarer-document.types';
|
||||
|
||||
export const SEAFARER_DOCUMENT_KIND_LABELS: Record<SeafarerDocumentKind, string> = {
|
||||
SEAMAN_BOOK: 'Seaman Book',
|
||||
BTC_BASIC_TRAINING: 'Basic Training Certificate',
|
||||
};
|
||||
|
||||
export const SEAFARER_DOCUMENT_STATUS_LABELS: Record<SeafarerDocumentStatus, string> = {
|
||||
AWAITING_REGISTRATION: 'Awaiting Registration',
|
||||
PAYMENT_PENDING: 'Payment Pending',
|
||||
PAID: 'Paid',
|
||||
PAYMENT_CONFIRMED: 'Payment Confirmed',
|
||||
SCHEDULED: 'Pickup Scheduled',
|
||||
ISSUED: 'Issued',
|
||||
REJECTED: 'Rejected',
|
||||
CANCELLED: 'Cancelled',
|
||||
};
|
||||
|
||||
export const SEAFARER_DOCUMENT_STATUS_COLORS: Record<SeafarerDocumentStatus, string> = {
|
||||
AWAITING_REGISTRATION: 'gray',
|
||||
PAYMENT_PENDING: 'orange',
|
||||
PAID: 'blue',
|
||||
PAYMENT_CONFIRMED: 'blue',
|
||||
SCHEDULED: 'grape',
|
||||
ISSUED: 'teal',
|
||||
REJECTED: 'red',
|
||||
CANCELLED: 'gray',
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { ApplicationPayment } from '../licensing/licensing.types';
|
||||
|
||||
export type SeafarerDocumentKind = 'SEAMAN_BOOK' | 'BTC_BASIC_TRAINING';
|
||||
|
||||
export type SeafarerDocumentStatus =
|
||||
| 'AWAITING_REGISTRATION'
|
||||
| 'PAYMENT_PENDING'
|
||||
| 'PAID'
|
||||
| 'PAYMENT_CONFIRMED'
|
||||
| 'SCHEDULED'
|
||||
| 'ISSUED'
|
||||
| 'REJECTED'
|
||||
| 'CANCELLED';
|
||||
|
||||
/** A Seaman Book or BTC request — opened by a seafarer registration. */
|
||||
export interface SeafarerDocument {
|
||||
id: string;
|
||||
kind: SeafarerDocumentKind;
|
||||
requestNumber: string;
|
||||
applicantUserId: string;
|
||||
profileId: string | null;
|
||||
seafarerRegistrationId: string | null;
|
||||
status: SeafarerDocumentStatus;
|
||||
feeAmount: number | null;
|
||||
feeCurrency: string;
|
||||
submittedAt: string | null;
|
||||
paidAt: string | null;
|
||||
paymentReference: string | null;
|
||||
scheduledIssuanceDate: string | null;
|
||||
documentNumber: string | null;
|
||||
issueDate: string | null;
|
||||
expiryDate: string | null;
|
||||
documentFileKey: string | null;
|
||||
issuedAt: string | null;
|
||||
rejectionReason: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface SeafarerDocumentApplicant {
|
||||
name: string;
|
||||
seafarerNumber: string | null;
|
||||
registrationNumber: string | null;
|
||||
registrationId: string | null;
|
||||
}
|
||||
|
||||
export type SeafarerDocumentRow = SeafarerDocument & {
|
||||
applicant: SeafarerDocumentApplicant | null;
|
||||
};
|
||||
|
||||
export interface SeafarerDocumentDetail {
|
||||
document: SeafarerDocument;
|
||||
applicant: SeafarerDocumentApplicant | null;
|
||||
payment: ApplicationPayment | null;
|
||||
}
|
||||
3
libs/api/src/lib/features/seafarer-registration/index.ts
Normal file
3
libs/api/src/lib/features/seafarer-registration/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './seafarer-registration.types';
|
||||
export * from './seafarer-registration.constants';
|
||||
export * from './seafarer-registration-api';
|
||||
@@ -0,0 +1,118 @@
|
||||
import { baseApi } from '../../base-api';
|
||||
import type { Attachment } from '../licensing/licensing.types';
|
||||
import type {
|
||||
SaveSeafarerRegistration,
|
||||
SeafarerRegistration,
|
||||
SeafarerRegistrationStatus,
|
||||
} from './seafarer-registration.types';
|
||||
|
||||
const TAG = 'SeafarerRegistration' as const;
|
||||
const LIST = { type: TAG, id: 'LIST' } as const;
|
||||
const item = (id: string) => ({ type: TAG, id }) as const;
|
||||
|
||||
export interface SeafarerRegistrationListFilter {
|
||||
status?: SeafarerRegistrationStatus;
|
||||
search?: string;
|
||||
take?: number;
|
||||
skip?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seafarer registration — its own endpoints, not a licence application.
|
||||
* Uploads still go through `/attachments` with ownerType SEAFARER_REGISTRATION.
|
||||
*/
|
||||
export const seafarerRegistrationApi = baseApi
|
||||
.enhanceEndpoints({ addTagTypes: [TAG] })
|
||||
.injectEndpoints({
|
||||
endpoints: (builder) => ({
|
||||
// ------------------------------------------------------------ applicant
|
||||
getMySeafarerRegistration: builder.query<{ registration: SeafarerRegistration | null }, void>({
|
||||
query: () => ({ url: '/seafarer-registrations/mine' }),
|
||||
providesTags: (r) => [LIST, ...(r?.registration ? [item(r.registration.id)] : [])],
|
||||
}),
|
||||
|
||||
startSeafarerRegistration: builder.mutation<SeafarerRegistration, void>({
|
||||
query: () => ({ url: '/seafarer-registrations', method: 'POST' }),
|
||||
invalidatesTags: (_r, error) => (error ? [] : [LIST]),
|
||||
}),
|
||||
|
||||
saveSeafarerRegistration: builder.mutation<
|
||||
SeafarerRegistration,
|
||||
{ id: string; body: SaveSeafarerRegistration }
|
||||
>({
|
||||
query: ({ id, body }) => ({ url: `/seafarer-registrations/${id}`, method: 'PUT', body }),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
submitSeafarerRegistration: builder.mutation<SeafarerRegistration, string>({
|
||||
query: (id) => ({ url: `/seafarer-registrations/${id}/submit`, method: 'POST' }),
|
||||
invalidatesTags: (_r, error, id) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
// --------------------------------------------------------------- review
|
||||
listSeafarerRegistrations: builder.query<
|
||||
{ total: number; items: SeafarerRegistration[] },
|
||||
SeafarerRegistrationListFilter
|
||||
>({
|
||||
query: (params) => ({ url: '/seafarer-registration-review', params }),
|
||||
providesTags: () => [LIST],
|
||||
}),
|
||||
|
||||
getSeafarerRegistrationReview: builder.query<
|
||||
{ registration: SeafarerRegistration; attachments: Attachment[] },
|
||||
string
|
||||
>({
|
||||
query: (id) => ({ url: `/seafarer-registration-review/${id}` }),
|
||||
providesTags: (_r, _e, id) => [item(id)],
|
||||
}),
|
||||
|
||||
approveSeafarerRegistration: builder.mutation<
|
||||
SeafarerRegistration,
|
||||
{ id: string; remark?: string }
|
||||
>({
|
||||
query: ({ id, ...body }) => ({
|
||||
url: `/seafarer-registration-review/${id}/approve`,
|
||||
method: 'POST',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
rejectSeafarerRegistration: builder.mutation<
|
||||
SeafarerRegistration,
|
||||
{ id: string; reason: string }
|
||||
>({
|
||||
query: ({ id, ...body }) => ({
|
||||
url: `/seafarer-registration-review/${id}/reject`,
|
||||
method: 'POST',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
|
||||
requestSeafarerRegistrationChanges: builder.mutation<
|
||||
SeafarerRegistration,
|
||||
{ id: string; remark: string }
|
||||
>({
|
||||
query: ({ id, ...body }) => ({
|
||||
url: `/seafarer-registration-review/${id}/request-changes`,
|
||||
method: 'POST',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_r, error, { id }) => (error ? [] : [LIST, item(id)]),
|
||||
}),
|
||||
}),
|
||||
overrideExisting: false,
|
||||
});
|
||||
|
||||
export const {
|
||||
useGetMySeafarerRegistrationQuery,
|
||||
useStartSeafarerRegistrationMutation,
|
||||
useSaveSeafarerRegistrationMutation,
|
||||
useSubmitSeafarerRegistrationMutation,
|
||||
useListSeafarerRegistrationsQuery,
|
||||
useGetSeafarerRegistrationReviewQuery,
|
||||
useApproveSeafarerRegistrationMutation,
|
||||
useRejectSeafarerRegistrationMutation,
|
||||
useRequestSeafarerRegistrationChangesMutation,
|
||||
} = seafarerRegistrationApi;
|
||||
@@ -0,0 +1,209 @@
|
||||
import type {
|
||||
SeafarerRegistrationAnswers,
|
||||
SeafarerRegistrationStatus,
|
||||
} from './seafarer-registration.types';
|
||||
|
||||
/**
|
||||
* Option lists and labels shared by the portal wizard and the backoffice
|
||||
* review screen. Values are the server's enum members.
|
||||
*/
|
||||
export const GENDER_OPTIONS = [
|
||||
{ value: 'MALE', label: 'Male' },
|
||||
{ value: 'FEMALE', label: 'Female' },
|
||||
];
|
||||
|
||||
export const MARITAL_STATUS_OPTIONS = [
|
||||
{ value: 'SINGLE', label: 'Single' },
|
||||
{ value: 'MARRIED', label: 'Married' },
|
||||
{ value: 'DIVORCED', label: 'Divorced' },
|
||||
{ value: 'WIDOWED', label: 'Widowed' },
|
||||
];
|
||||
|
||||
export const DEPARTMENT_OPTIONS = [
|
||||
{ value: 'DECK', label: 'Deck' },
|
||||
{ value: 'ENGINE', label: 'Engine' },
|
||||
{ value: 'CATERING', label: 'Catering' },
|
||||
];
|
||||
|
||||
export const HAIR_COLOR_OPTIONS = [
|
||||
{ value: 'BLACK', label: 'Black' },
|
||||
{ value: 'BROWN', label: 'Brown' },
|
||||
{ value: 'BLONDE', label: 'Blonde' },
|
||||
{ value: 'RED', label: 'Red' },
|
||||
{ value: 'GREY', label: 'Grey' },
|
||||
{ value: 'WHITE', label: 'White' },
|
||||
{ value: 'BALD', label: 'Bald' },
|
||||
{ value: 'OTHER', label: 'Other' },
|
||||
];
|
||||
|
||||
export const EYE_COLOR_OPTIONS = [
|
||||
{ value: 'BROWN', label: 'Brown' },
|
||||
{ value: 'BLACK', label: 'Black' },
|
||||
{ value: 'BLUE', label: 'Blue' },
|
||||
{ value: 'GREEN', label: 'Green' },
|
||||
{ value: 'HAZEL', label: 'Hazel' },
|
||||
{ value: 'GREY', label: 'Grey' },
|
||||
{ value: 'OTHER', label: 'Other' },
|
||||
];
|
||||
|
||||
export const BLOOD_TYPE_OPTIONS = [
|
||||
{ value: 'A_POSITIVE', label: 'A+' },
|
||||
{ value: 'A_NEGATIVE', label: 'A−' },
|
||||
{ value: 'B_POSITIVE', label: 'B+' },
|
||||
{ value: 'B_NEGATIVE', label: 'B−' },
|
||||
{ value: 'AB_POSITIVE', label: 'AB+' },
|
||||
{ value: 'AB_NEGATIVE', label: 'AB−' },
|
||||
{ value: 'O_POSITIVE', label: 'O+' },
|
||||
{ value: 'O_NEGATIVE', label: 'O−' },
|
||||
{ value: 'UNKNOWN', label: 'Unknown' },
|
||||
];
|
||||
|
||||
/** Same plausibility bounds the API enforces (PHYSICAL_BOUNDS). */
|
||||
export const PHYSICAL_BOUNDS = {
|
||||
heightCm: { min: 100, max: 250 },
|
||||
weightKg: { min: 30, max: 250 },
|
||||
} as const;
|
||||
|
||||
/** Upload slots, keyed as the API's submission check expects them. */
|
||||
export const SEAFARER_REGISTRATION_DOCUMENTS: {
|
||||
key: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
/** `'passport'`: required only once a passport number is declared. */
|
||||
required: boolean | 'passport';
|
||||
accept?: string;
|
||||
}[] = [
|
||||
{
|
||||
key: 'photo',
|
||||
name: 'Passport-size Photograph',
|
||||
description: 'Recent colour photograph with a plain background.',
|
||||
required: true,
|
||||
accept: 'image/jpeg,image/png',
|
||||
},
|
||||
{ key: 'nationalId', name: 'National ID (Fayda) or Kebele ID', required: true },
|
||||
{ key: 'passport', name: 'Passport Copy', required: 'passport' },
|
||||
{ key: 'graduation', name: 'Educational Certificate', required: false },
|
||||
{
|
||||
key: 'medical_certificate',
|
||||
name: 'Medical Certificate',
|
||||
description:
|
||||
'Your STCW medical fitness certificate. Must match the certificate details entered above.',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
key: 'basic_training_evidence',
|
||||
name: 'Basic Training Evidence',
|
||||
description:
|
||||
'One file containing evidence of all five basic training competencies: Personal Survival Techniques (PST), Fire Prevention and Fire Fighting (FPFF), Elementary First Aid (EFA), Personal Safety and Social Responsibility (PSSR), and Security Awareness.',
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const SEAFARER_REGISTRATION_STATUS_LABELS: Record<SeafarerRegistrationStatus, string> = {
|
||||
DRAFT: 'Draft',
|
||||
SUBMITTED: 'Submitted',
|
||||
RESUBMIT_REQUIRED: 'Corrections Requested',
|
||||
APPROVED: 'Approved',
|
||||
REJECTED: 'Rejected',
|
||||
};
|
||||
|
||||
export const SEAFARER_REGISTRATION_STATUS_COLORS: Record<SeafarerRegistrationStatus, string> = {
|
||||
DRAFT: 'gray',
|
||||
SUBMITTED: 'blue',
|
||||
RESUBMIT_REQUIRED: 'orange',
|
||||
APPROVED: 'teal',
|
||||
REJECTED: 'red',
|
||||
};
|
||||
|
||||
/** Human label for each answer — the review table and the summary both use it. */
|
||||
export const SEAFARER_REGISTRATION_FIELD_LABELS: Record<keyof SeafarerRegistrationAnswers, string> = {
|
||||
firstName: 'First Name',
|
||||
middleName: 'Middle Name',
|
||||
lastName: 'Last Name',
|
||||
gender: 'Gender',
|
||||
dateOfBirth: 'Date of Birth',
|
||||
maritalStatus: 'Marital Status',
|
||||
nationality: 'Nationality',
|
||||
nationalIdNumber: 'National ID (Fayda) Number',
|
||||
placeOfBirth: 'Place of Birth',
|
||||
passportNumber: 'Passport Number',
|
||||
passportExpiry: 'Passport Expiry Date',
|
||||
department: 'Department',
|
||||
locationId: 'Location',
|
||||
permanentAddress: 'Permanent Address',
|
||||
currentAddress: 'Current Address',
|
||||
emergencyContactName: 'Full Name',
|
||||
emergencyContactRelationship: 'Relationship',
|
||||
emergencyContactPhone: 'Phone Number',
|
||||
hairColor: 'Hair Colour',
|
||||
eyeColor: 'Eye Colour',
|
||||
heightCm: 'Height (cm)',
|
||||
weightKg: 'Weight (kg)',
|
||||
bloodType: 'Blood Type',
|
||||
medicalCertificateNumber: 'Certificate Number',
|
||||
medicalIssuerName: 'Issuing Clinic or Practitioner',
|
||||
medicalIssueDate: 'Issue Date',
|
||||
declarationAccepted: 'Declaration',
|
||||
};
|
||||
|
||||
/**
|
||||
* The answers grouped the way the wizard asks them — the summary on the
|
||||
* portal and the review screen in the backoffice render the same sections.
|
||||
*/
|
||||
export const SEAFARER_REGISTRATION_SECTIONS: {
|
||||
key: string;
|
||||
title: string;
|
||||
fields: (keyof SeafarerRegistrationAnswers)[];
|
||||
}[] = [
|
||||
{
|
||||
key: 'identityDetails',
|
||||
title: 'Identity Details',
|
||||
fields: ['firstName', 'middleName', 'lastName', 'gender', 'dateOfBirth', 'maritalStatus', 'nationality', 'nationalIdNumber'],
|
||||
},
|
||||
{
|
||||
key: 'identity',
|
||||
title: 'Identity',
|
||||
fields: ['placeOfBirth', 'passportNumber', 'passportExpiry', 'department'],
|
||||
},
|
||||
{
|
||||
key: 'address',
|
||||
title: 'Address',
|
||||
fields: ['locationId', 'permanentAddress', 'currentAddress'],
|
||||
},
|
||||
{
|
||||
key: 'physicalCharacteristics',
|
||||
title: 'Physical Characteristics',
|
||||
fields: ['hairColor', 'eyeColor', 'heightCm', 'weightKg', 'bloodType'],
|
||||
},
|
||||
{
|
||||
key: 'medicalCertificate',
|
||||
title: 'Medical Certificate',
|
||||
fields: ['medicalCertificateNumber', 'medicalIssuerName', 'medicalIssueDate'],
|
||||
},
|
||||
{
|
||||
key: 'emergencyContact',
|
||||
title: 'Emergency Contact',
|
||||
fields: ['emergencyContactName', 'emergencyContactRelationship', 'emergencyContactPhone'],
|
||||
},
|
||||
];
|
||||
|
||||
const OPTION_LABELS: Partial<Record<keyof SeafarerRegistrationAnswers, { value: string; label: string }[]>> = {
|
||||
gender: GENDER_OPTIONS,
|
||||
maritalStatus: MARITAL_STATUS_OPTIONS,
|
||||
department: DEPARTMENT_OPTIONS,
|
||||
hairColor: HAIR_COLOR_OPTIONS,
|
||||
eyeColor: EYE_COLOR_OPTIONS,
|
||||
bloodType: BLOOD_TYPE_OPTIONS,
|
||||
};
|
||||
|
||||
/** Display value for one answer: option label for enums, "—" when blank. */
|
||||
export function displaySeafarerAnswer(
|
||||
field: keyof SeafarerRegistrationAnswers,
|
||||
value: unknown,
|
||||
): string {
|
||||
if (value === null || value === undefined || value === '') return '—';
|
||||
if (typeof value === 'boolean') return value ? 'Yes' : 'No';
|
||||
const options = OPTION_LABELS[field];
|
||||
if (options) return options.find((o) => o.value === value)?.label ?? String(value);
|
||||
return String(value);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { SeafarerDepartment } from '../seafarer/seafarer.types';
|
||||
|
||||
export type SeafarerRegistrationStatus =
|
||||
| 'DRAFT'
|
||||
| 'SUBMITTED'
|
||||
| 'RESUBMIT_REQUIRED'
|
||||
| 'APPROVED'
|
||||
| 'REJECTED';
|
||||
|
||||
export type Gender = 'MALE' | 'FEMALE';
|
||||
export type MaritalStatus = 'SINGLE' | 'MARRIED' | 'DIVORCED' | 'WIDOWED';
|
||||
export type HairColor = 'BLACK' | 'BROWN' | 'BLONDE' | 'RED' | 'GREY' | 'WHITE' | 'BALD' | 'OTHER';
|
||||
export type EyeColor = 'BROWN' | 'BLACK' | 'BLUE' | 'GREEN' | 'HAZEL' | 'GREY' | 'OTHER';
|
||||
export type BloodType =
|
||||
| 'A_POSITIVE' | 'A_NEGATIVE' | 'B_POSITIVE' | 'B_NEGATIVE'
|
||||
| 'AB_POSITIVE' | 'AB_NEGATIVE' | 'O_POSITIVE' | 'O_NEGATIVE' | 'UNKNOWN';
|
||||
|
||||
/** Every answer the registration collects — one typed row, no form schema. */
|
||||
export interface SeafarerRegistrationAnswers {
|
||||
firstName: string | null;
|
||||
middleName: string | null;
|
||||
lastName: string | null;
|
||||
gender: Gender | null;
|
||||
dateOfBirth: string | null;
|
||||
maritalStatus: MaritalStatus | null;
|
||||
/** Full demonym as the profile stores it ("Ethiopian"). */
|
||||
nationality: string | null;
|
||||
nationalIdNumber: string | null;
|
||||
placeOfBirth: string | null;
|
||||
passportNumber: string | null;
|
||||
passportExpiry: string | null;
|
||||
department: SeafarerDepartment | null;
|
||||
locationId: string | null;
|
||||
permanentAddress: string | null;
|
||||
currentAddress: string | null;
|
||||
emergencyContactName: string | null;
|
||||
emergencyContactRelationship: string | null;
|
||||
emergencyContactPhone: string | null;
|
||||
hairColor: HairColor | null;
|
||||
eyeColor: EyeColor | null;
|
||||
heightCm: number | null;
|
||||
weightKg: number | null;
|
||||
bloodType: BloodType | null;
|
||||
medicalCertificateNumber: string | null;
|
||||
medicalIssuerName: string | null;
|
||||
medicalIssueDate: string | null;
|
||||
declarationAccepted: boolean;
|
||||
}
|
||||
|
||||
export interface SeafarerRegistration extends SeafarerRegistrationAnswers {
|
||||
id: string;
|
||||
registrationNumber: string;
|
||||
applicantUserId: string;
|
||||
profileId: string | null;
|
||||
status: SeafarerRegistrationStatus;
|
||||
submittedAt: string | null;
|
||||
decidedAt: string | null;
|
||||
decidedById: string | null;
|
||||
/** What the officer asked to be fixed, or noted at approval. */
|
||||
reviewRemark: string | null;
|
||||
rejectionReason: string | null;
|
||||
/** Stamped at approval. */
|
||||
seafarerNumber: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** `null` clears a field; an absent key leaves it alone. */
|
||||
export type SaveSeafarerRegistration = Partial<SeafarerRegistrationAnswers>;
|
||||
|
||||
export interface SeafarerRegistrationIssue {
|
||||
kind: 'field' | 'document';
|
||||
target: string;
|
||||
message: string;
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from './seafarer.types';
|
||||
export * from './seafarer-api';
|
||||
export * from './seafarer.helpers';
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
CreateMedicalCertificate,
|
||||
CreateSeaServiceRecord,
|
||||
MedicalCertificate,
|
||||
RecordQueueFilter,
|
||||
SeaServiceRecord,
|
||||
SeaTimeSummary,
|
||||
SeafarerStatus,
|
||||
@@ -14,8 +15,8 @@ const listTag = (type: (typeof TAGS)[number]) => ({ type, id: 'LIST' }) as const
|
||||
|
||||
/**
|
||||
* The seafarer's evidence shelf: sea-service records and medical
|
||||
* certificates (modules 05/06). Registration itself rides the licensing
|
||||
* endpoints — a SEAFARER_REGISTRATION application through `licensingApi`.
|
||||
* certificates (modules 05/06). Registration itself lives in
|
||||
* `seafarer-registration-api.ts`.
|
||||
*/
|
||||
export const seafarerApi = baseApi
|
||||
.enhanceEndpoints({ addTagTypes: TAGS })
|
||||
@@ -104,13 +105,25 @@ export const seafarerApi = baseApi
|
||||
}),
|
||||
|
||||
// -------------------------------------------------------- verification
|
||||
getPendingSeaService: builder.query<SeaServiceRecord[], void>({
|
||||
query: () => ({ url: '/sea-service-records/pending' }),
|
||||
getPendingSeaService: builder.query<
|
||||
SeaServiceRecord[],
|
||||
RecordQueueFilter | void
|
||||
>({
|
||||
query: (status) => ({
|
||||
url: '/sea-service-records/pending',
|
||||
params: { status: status || 'SUBMITTED' },
|
||||
}),
|
||||
providesTags: () => [listTag('SeaServiceRecord')],
|
||||
}),
|
||||
|
||||
getPendingMedical: builder.query<MedicalCertificate[], void>({
|
||||
query: () => ({ url: '/medical-certificates/pending' }),
|
||||
getPendingMedical: builder.query<
|
||||
MedicalCertificate[],
|
||||
RecordQueueFilter | void
|
||||
>({
|
||||
query: (status) => ({
|
||||
url: '/medical-certificates/pending',
|
||||
params: { status: status || 'SUBMITTED' },
|
||||
}),
|
||||
providesTags: () => [listTag('MedicalCertificate')],
|
||||
}),
|
||||
|
||||
|
||||
23
libs/api/src/lib/features/seafarer/seafarer.helpers.ts
Normal file
23
libs/api/src/lib/features/seafarer/seafarer.helpers.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Days served on one engagement, counted inclusively — embarkation and
|
||||
* discharge days both count. The same arithmetic the API uses for approved
|
||||
* sea time (`SeafarerRecordService.approvedSeaTime`), so the figure a seafarer
|
||||
* sees while typing is the figure the eligibility gate will credit.
|
||||
*
|
||||
* `null` until both dates are set or while they are out of order.
|
||||
*/
|
||||
export function seaServiceDays(
|
||||
engagementDate: string | null | undefined,
|
||||
dischargeDate: string | null | undefined,
|
||||
): number | null {
|
||||
if (!engagementDate || !dischargeDate) return null;
|
||||
const from = Date.UTC(...dateParts(engagementDate));
|
||||
const to = Date.UTC(...dateParts(dischargeDate));
|
||||
if (Number.isNaN(from) || Number.isNaN(to) || to < from) return null;
|
||||
return Math.round((to - from) / 86_400_000) + 1;
|
||||
}
|
||||
|
||||
function dateParts(value: string): [number, number, number] {
|
||||
const [y, m, d] = value.slice(0, 10).split('-').map(Number);
|
||||
return [y, (m || 1) - 1, d || 1];
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
export type SeafarerRecordStatus = 'SUBMITTED' | 'VERIFIED' | 'REJECTED';
|
||||
|
||||
/** Verification-queue filter: a record status, or ALL for no filter. */
|
||||
export type RecordQueueFilter = SeafarerRecordStatus | 'ALL';
|
||||
export type MedicalFitness = 'FIT' | 'FIT_WITH_RESTRICTIONS' | 'UNFIT';
|
||||
export type SeafarerDepartment = 'DECK' | 'ENGINE' | 'CATERING';
|
||||
export type SeafarerStatus = 'ACTIVE' | 'INACTIVE' | 'PENDING' | 'SUSPENDED';
|
||||
|
||||
@@ -3,6 +3,8 @@ import type {
|
||||
CreateVesselIncident,
|
||||
Vessel,
|
||||
VesselIncident,
|
||||
VesselReport,
|
||||
VesselReportQuery,
|
||||
VesselStatus,
|
||||
} from './vessel.types';
|
||||
|
||||
@@ -35,6 +37,22 @@ export const vesselApi = baseApi
|
||||
providesTags: () => [listTag('Vessel')],
|
||||
}),
|
||||
|
||||
/**
|
||||
* The whole backoffice dashboard in one call — KPIs, time series,
|
||||
* breakdowns and worklists. Backoffice only (`can:View:vessel-registry`).
|
||||
*
|
||||
* Array filters are passed as arrays, not joined strings: the API accepts
|
||||
* both the repeated and the comma-separated form, and `params` serialises
|
||||
* the repeated one.
|
||||
*/
|
||||
getVesselReport: builder.query<VesselReport, VesselReportQuery | void>({
|
||||
query: (params) => ({
|
||||
url: '/vessels/report',
|
||||
params: params ?? undefined,
|
||||
}),
|
||||
providesTags: () => [listTag('Vessel')],
|
||||
}),
|
||||
|
||||
getVessel: builder.query<Vessel, string>({
|
||||
query: (id) => ({ url: `/vessels/${id}` }),
|
||||
providesTags: (_r, _e, id) => [{ type: 'Vessel', id }],
|
||||
@@ -77,6 +95,7 @@ export const vesselApi = baseApi
|
||||
export const {
|
||||
useGetMyVesselsQuery,
|
||||
useGetVesselsQuery,
|
||||
useGetVesselReportQuery,
|
||||
useGetVesselQuery,
|
||||
useUpdateVesselStatusMutation,
|
||||
useGetVesselIncidentsQuery,
|
||||
|
||||
@@ -49,3 +49,247 @@ export interface CreateVesselIncident {
|
||||
description: string;
|
||||
severity?: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vessel registration report (GET /vessels/report)
|
||||
//
|
||||
// One call fills the whole backoffice dashboard. Unlike `Vessel` above, every
|
||||
// numeric field here is already a real number — the API casts the Postgres
|
||||
// `numeric` strings before it answers.
|
||||
|
||||
export type ReportGranularity = 'DAY' | 'WEEK' | 'MONTH';
|
||||
|
||||
/**
|
||||
* One slice of a breakdown chart.
|
||||
*
|
||||
* `percentage` is of the whole, not of the slices that survived the `topN`
|
||||
* cut, so a set of slices always totals 100.
|
||||
*/
|
||||
export interface BreakdownItem {
|
||||
key: string;
|
||||
label: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface VesselReportQuery {
|
||||
/** Bounds the time series and the "in period" figures only. */
|
||||
from?: string;
|
||||
to?: string;
|
||||
granularity?: ReportGranularity;
|
||||
category?: VesselCategory[];
|
||||
status?: VesselStatus[];
|
||||
flagState?: string[];
|
||||
portOfRegistry?: string[];
|
||||
vesselType?: string[];
|
||||
search?: string;
|
||||
expiringWithinDays?: number;
|
||||
/** Slices kept per high-cardinality chart; the tail collapses into "Other". */
|
||||
topN?: number;
|
||||
tableLimit?: number;
|
||||
}
|
||||
|
||||
export interface RegisterKpis {
|
||||
total: number;
|
||||
registered: number;
|
||||
suspended: number;
|
||||
deregistered: number;
|
||||
registeredInPeriod: number;
|
||||
registeredInPreviousPeriod: number;
|
||||
/** Null when there is no previous period to compare against. */
|
||||
changePct: number | null;
|
||||
}
|
||||
|
||||
export interface FleetKpis {
|
||||
totalGrossTonnage: number;
|
||||
avgGrossTonnage: number | null;
|
||||
/** How many hulls the tonnage average actually covers. */
|
||||
grossTonnageKnownFor: number;
|
||||
totalPassengerCapacity: number;
|
||||
avgLengthMeters: number | null;
|
||||
avgAgeYears: number | null;
|
||||
ageKnownFor: number;
|
||||
seaGoing: number;
|
||||
inlandWaterway: number;
|
||||
}
|
||||
|
||||
export interface PipelineKpis {
|
||||
total: number;
|
||||
draft: number;
|
||||
inProgress: number;
|
||||
approved: number;
|
||||
rejected: number;
|
||||
issued: number;
|
||||
submittedInPeriod: number;
|
||||
decidedInPeriod: number;
|
||||
newCount: number;
|
||||
renewalCount: number;
|
||||
/** Approved over settled. Null while nothing has been decided. */
|
||||
approvalRatePct: number | null;
|
||||
avgProcessingDays: number | null;
|
||||
medianProcessingDays: number | null;
|
||||
avgAdjustmentRounds: number | null;
|
||||
}
|
||||
|
||||
export interface CertificateKpis {
|
||||
total: number;
|
||||
active: number;
|
||||
expired: number;
|
||||
suspended: number;
|
||||
/** Cumulative: a certificate due in 11 days is inside all three. */
|
||||
expiringIn30: number;
|
||||
expiringIn60: number;
|
||||
expiringIn90: number;
|
||||
missingCertificate: number;
|
||||
}
|
||||
|
||||
export interface IncidentKpis {
|
||||
total: number;
|
||||
inPeriod: number;
|
||||
reportedByOfficer: number;
|
||||
reportedByOwner: number;
|
||||
vesselsWithIncidents: number;
|
||||
}
|
||||
|
||||
export interface RevenueKpis {
|
||||
currency: string;
|
||||
/** True when more than one currency was summed — warn rather than total. */
|
||||
mixedCurrency: boolean;
|
||||
paid: number;
|
||||
pending: number;
|
||||
paidCount: number;
|
||||
pendingCount: number;
|
||||
failedCount: number;
|
||||
}
|
||||
|
||||
/** Bucketed series. `bucket` is an ISO date; the window is zero-filled. */
|
||||
export interface RegistrationBucket {
|
||||
bucket: string;
|
||||
count: number;
|
||||
grossTonnage: number;
|
||||
}
|
||||
|
||||
export interface ApplicationBucket {
|
||||
bucket: string;
|
||||
submitted: number;
|
||||
approved: number;
|
||||
rejected: number;
|
||||
issued: number;
|
||||
}
|
||||
|
||||
export interface IncidentBucket {
|
||||
bucket: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface RevenueBucket {
|
||||
bucket: string;
|
||||
amount: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface ExpiringCertificateRow {
|
||||
vesselId: string;
|
||||
registrationNumber: string;
|
||||
name: string;
|
||||
ownerName: string | null;
|
||||
ownerUserId: string;
|
||||
certificateNumber: string | null;
|
||||
expiryDate: string;
|
||||
certificateStatus: string | null;
|
||||
/** 0 means it expires today, which still counts as live. */
|
||||
daysToExpiry: number;
|
||||
}
|
||||
|
||||
export interface RecentRegistrationRow {
|
||||
vesselId: string;
|
||||
registrationNumber: string;
|
||||
name: string;
|
||||
category: VesselCategory;
|
||||
vesselType: string | null;
|
||||
flagState: string | null;
|
||||
grossTonnage: number | null;
|
||||
ownerName: string | null;
|
||||
status: VesselStatus;
|
||||
registeredAt: string;
|
||||
}
|
||||
|
||||
export interface RecentIncidentRow {
|
||||
id: string;
|
||||
vesselId: string;
|
||||
registrationNumber: string;
|
||||
vesselName: string;
|
||||
occurredAt: string;
|
||||
severity: string | null;
|
||||
location: string | null;
|
||||
description: string;
|
||||
reportedByOfficer: boolean;
|
||||
}
|
||||
|
||||
export interface PendingApplicationRow {
|
||||
applicationNumber: string;
|
||||
status: string;
|
||||
kind: 'NEW' | 'RENEWAL';
|
||||
assignedOfficerId: string | null;
|
||||
submittedAt: string | null;
|
||||
adjustmentRound: number;
|
||||
daysOpen: number;
|
||||
}
|
||||
|
||||
export interface VesselReport {
|
||||
generatedAt: string;
|
||||
/** True when the register passed the API's scan cap — figures are partial. */
|
||||
truncated: boolean;
|
||||
filters: {
|
||||
from: string;
|
||||
to: string;
|
||||
granularity: ReportGranularity;
|
||||
expiringWithinDays: number;
|
||||
topN: number;
|
||||
tableLimit: number;
|
||||
category: VesselCategory[] | null;
|
||||
status: VesselStatus[] | null;
|
||||
flagState: string[] | null;
|
||||
portOfRegistry: string[] | null;
|
||||
vesselType: string[] | null;
|
||||
search: string | null;
|
||||
};
|
||||
kpis: {
|
||||
register: RegisterKpis;
|
||||
fleet: FleetKpis;
|
||||
pipeline: PipelineKpis;
|
||||
certificates: CertificateKpis;
|
||||
incidents: IncidentKpis;
|
||||
revenue: RevenueKpis;
|
||||
};
|
||||
timeSeries: {
|
||||
registrations: RegistrationBucket[];
|
||||
applications: ApplicationBucket[];
|
||||
incidents: IncidentBucket[];
|
||||
revenue: RevenueBucket[];
|
||||
};
|
||||
breakdowns: {
|
||||
byStatus: BreakdownItem[];
|
||||
byCategory: BreakdownItem[];
|
||||
byFlagState: BreakdownItem[];
|
||||
byPortOfRegistry: BreakdownItem[];
|
||||
byVesselType: BreakdownItem[];
|
||||
byHullMaterial: BreakdownItem[];
|
||||
byEngineType: BreakdownItem[];
|
||||
byTonnageBand: BreakdownItem[];
|
||||
byLengthBand: BreakdownItem[];
|
||||
byAgeBand: BreakdownItem[];
|
||||
byBuildDecade: BreakdownItem[];
|
||||
byApplicationStatus: BreakdownItem[];
|
||||
byApplicationKind: BreakdownItem[];
|
||||
/** `key` is an IAM user uuid, or the literal "UNASSIGNED". */
|
||||
byOfficer: BreakdownItem[];
|
||||
byIncidentSeverity: BreakdownItem[];
|
||||
};
|
||||
tables: {
|
||||
expiringCertificates: ExpiringCertificateRow[];
|
||||
recentRegistrations: RecentRegistrationRow[];
|
||||
recentIncidents: RecentIncidentRow[];
|
||||
pendingApplications: PendingApplicationRow[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ const queryApi = baseApi.injectEndpoints({
|
||||
overrideExisting: false,
|
||||
});
|
||||
|
||||
export const { useApiQueryQuery, useApiMutationMutation } = queryApi;
|
||||
export const { useApiQueryQuery, useLazyApiQueryQuery, useApiMutationMutation } = queryApi;
|
||||
|
||||
export function useApiQuery<TData = unknown>(
|
||||
args: ApiQueryArgs,
|
||||
@@ -37,6 +37,17 @@ export function useApiQuery<TData = unknown>(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same endpoint as `useApiQuery`, fetched on demand instead of on render — for
|
||||
* the case where the arguments are only known at click time.
|
||||
*/
|
||||
export function useApiLazyQuery<TData = unknown>(): [
|
||||
(args: ApiQueryArgs) => { unwrap: () => Promise<TData> },
|
||||
] {
|
||||
const [trigger] = useLazyApiQueryQuery();
|
||||
return [trigger as unknown as (args: ApiQueryArgs) => { unwrap: () => Promise<TData> }];
|
||||
}
|
||||
|
||||
type UseApiMutationResult<TData> = {
|
||||
data: TData | undefined;
|
||||
isLoading: boolean;
|
||||
|
||||
@@ -3,6 +3,7 @@ export type { AuthConfigValue } from "./lib/AuthConfig";
|
||||
export { AuthShell, BrandMark } from "./lib/components/AuthShell";
|
||||
export { ProtectedRoute } from "./lib/components/ProtectedRoute";
|
||||
export { AuthBootstrap } from "./lib/components/AuthBootstrap";
|
||||
export { useIdleTimer } from "./lib/hooks/useIdleTimer";
|
||||
export { LoginPage } from "./lib/pages/LoginPage";
|
||||
export { SignupPage } from "./lib/pages/SignupPage";
|
||||
export { ForgotPasswordPage } from "./lib/pages/ForgotPasswordPage";
|
||||
@@ -25,6 +26,12 @@ export {
|
||||
resetSignup,
|
||||
} from "./lib/store/signup.slice";
|
||||
export { usePermissions } from "./lib/hooks/usePermissions";
|
||||
export { useAuthToken } from "./lib/hooks/useAuthToken";
|
||||
export { useTwoFactor } from "./lib/hooks/useTwoFactor";
|
||||
export { useSessions } from "./lib/hooks/useSessions";
|
||||
export type { MySession } from "./lib/hooks/useSessions";
|
||||
export { ActiveSessions } from "./lib/components/ActiveSessions";
|
||||
export { currentSessionId } from "./lib/utils/jwt";
|
||||
export type { PermissionSet } from "./lib/hooks/usePermissions";
|
||||
export { RequirePermission } from "./lib/components/RequirePermission";
|
||||
export {
|
||||
@@ -36,6 +43,7 @@ export {
|
||||
useGetMyProfileQuery,
|
||||
useUpdateMyProfileMutation,
|
||||
useUpdateMyAddressMutation,
|
||||
useUpdateMyAccountTypeMutation,
|
||||
PROFILE_FIELDS,
|
||||
PROFILE_FIELD_SECTION,
|
||||
} from "./lib/hooks/useCurrentProfile";
|
||||
|
||||
124
libs/auth/src/lib/components/ActiveSessions/columns.tsx
Normal file
124
libs/auth/src/lib/components/ActiveSessions/columns.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import { ActionIcon, Badge, Checkbox, Group, Text, Tooltip } from '@mantine/core';
|
||||
import { IconLogout } from '@tabler/icons-react';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { AdvancedColumn } from '@ema-platform/ui';
|
||||
import type { MySession } from '../../hooks/useSessions';
|
||||
|
||||
interface Opts {
|
||||
t: TFunction;
|
||||
sessions: MySession[];
|
||||
selected: string[];
|
||||
setSelected: Dispatch<SetStateAction<string[]>>;
|
||||
/** Undefined when the token carries no session claim — then no row is "this device". */
|
||||
currentId?: string;
|
||||
showDate: (value: string) => string;
|
||||
onRevoke: (session: MySession) => void;
|
||||
}
|
||||
|
||||
export function sessionColumns({
|
||||
t,
|
||||
sessions,
|
||||
selected,
|
||||
setSelected,
|
||||
currentId,
|
||||
showDate,
|
||||
onRevoke,
|
||||
}: Opts): AdvancedColumn<MySession>[] {
|
||||
// The current session is never selectable, so "all" means "all the others".
|
||||
const selectable = sessions.filter((s) => s.id !== currentId);
|
||||
const allSelected = selectable.length > 0 && selectable.every((s) => selected.includes(s.id));
|
||||
|
||||
return [
|
||||
{
|
||||
header: (
|
||||
<Checkbox
|
||||
aria-label={t('profile.sessions.selectAll')}
|
||||
checked={allSelected}
|
||||
indeterminate={selected.length > 0 && !allSelected}
|
||||
disabled={selectable.length === 0}
|
||||
onChange={() => setSelected(allSelected ? [] : selectable.map((s) => s.id))}
|
||||
/>
|
||||
),
|
||||
label: t('profile.sessions.select'),
|
||||
size: 40,
|
||||
cell: ({ row }) => {
|
||||
const isCurrent = row.original.id === currentId;
|
||||
return (
|
||||
<Checkbox
|
||||
aria-label={t('profile.sessions.selectRow', { device: row.original.device })}
|
||||
checked={selected.includes(row.original.id)}
|
||||
disabled={isCurrent}
|
||||
onChange={(e) => {
|
||||
const checked = e.currentTarget.checked;
|
||||
setSelected((prev) =>
|
||||
checked
|
||||
? [...prev, row.original.id]
|
||||
: prev.filter((id) => id !== row.original.id),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.device'),
|
||||
cell: ({ row }) => (
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text size="sm" fw={500}>
|
||||
{row.original.device || '—'}
|
||||
</Text>
|
||||
{row.original.id === currentId && (
|
||||
<Badge variant="light" color="emaTeal" size="sm">
|
||||
{t('profile.sessions.thisDevice')}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.signedIn'),
|
||||
cell: ({ row }) => <Text size="sm">{showDate(row.original.createdAt)}</Text>,
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.expires'),
|
||||
cell: ({ row }) => <Text size="sm">{showDate(row.original.expiryTime)}</Text>,
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.status'),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="light" size="sm" color={row.original.status === 'ACTIVE' ? 'green' : 'gray'}>
|
||||
{row.original.status}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: t('profile.sessions.columns.actions'),
|
||||
size: 70,
|
||||
align: 'center',
|
||||
cell: ({ row }) => {
|
||||
const isCurrent = row.original.id === currentId;
|
||||
return (
|
||||
<Tooltip
|
||||
label={
|
||||
isCurrent ? t('profile.sessions.cannotRevokeCurrent') : t('profile.sessions.revoke')
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="red"
|
||||
size="sm"
|
||||
disabled={isCurrent}
|
||||
aria-label={t('profile.sessions.revoke')}
|
||||
onClick={() => onRevoke(row.original)}
|
||||
>
|
||||
<IconLogout size={14} />
|
||||
</ActionIcon>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
153
libs/auth/src/lib/components/ActiveSessions/index.tsx
Normal file
153
libs/auth/src/lib/components/ActiveSessions/index.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Button, Group, Paper, Stack, Text, Title } from '@mantine/core';
|
||||
import { IconLogout } from '@tabler/icons-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AdvancedTable, ConfirmModal, notify, useErrorHandler, useServerTable } from '@ema-platform/ui';
|
||||
import { useDateDisplayer } from '@ema-platform/shared';
|
||||
import { useSessions, type MySession } from '../../hooks/useSessions';
|
||||
import { useAuthToken } from '../../hooks/useAuthToken';
|
||||
import { currentSessionId } from '../../utils/jwt';
|
||||
import { sessionColumns } from './columns';
|
||||
|
||||
/** What the one confirm dialog is currently asking about. */
|
||||
type Pending =
|
||||
| { kind: 'one'; ids: string[]; device: string }
|
||||
| { kind: 'selected'; ids: string[] }
|
||||
| { kind: 'others' };
|
||||
|
||||
/**
|
||||
* Where the signed-in user is logged in, and how to end those sessions.
|
||||
*
|
||||
* Renders as its own card so it can sit OUTSIDE the change-password <form> on
|
||||
* the Security tab — a bare <button> inside that form would submit it.
|
||||
*/
|
||||
export function ActiveSessions() {
|
||||
const { t } = useTranslation();
|
||||
const { handleError } = useErrorHandler();
|
||||
const showDate = useDateDisplayer();
|
||||
const token = useAuthToken();
|
||||
const currentId = useMemo(() => currentSessionId(token), [token]);
|
||||
|
||||
const { pageIndex, setPageIndex, pageSize, setPageSize, skip, take } = useServerTable({
|
||||
pageSize: 5,
|
||||
});
|
||||
const { sessions, total, isFetching, refetch, revoke, isRevoking, allSessionIds } = useSessions({
|
||||
skip,
|
||||
take,
|
||||
});
|
||||
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [pending, setPending] = useState<Pending | null>(null);
|
||||
|
||||
const columns = useMemo(
|
||||
() =>
|
||||
sessionColumns({
|
||||
t,
|
||||
sessions,
|
||||
selected,
|
||||
setSelected,
|
||||
currentId,
|
||||
showDate,
|
||||
onRevoke: (s: MySession) => setPending({ kind: 'one', ids: [s.id], device: s.device }),
|
||||
}),
|
||||
[t, sessions, selected, currentId, showDate],
|
||||
);
|
||||
|
||||
const confirmMessage = () => {
|
||||
if (!pending) return '';
|
||||
const base =
|
||||
pending.kind === 'one'
|
||||
? t('profile.sessions.confirm.one', { device: pending.device })
|
||||
: pending.kind === 'selected'
|
||||
? t('profile.sessions.confirm.selected', { count: pending.ids.length })
|
||||
: t('profile.sessions.confirm.others');
|
||||
// Without a session claim on the token there is no way to spare this
|
||||
// device, so say so rather than implying the current login survives.
|
||||
return currentId ? base : `${base} ${t('profile.sessions.confirm.unknownDevice')}`;
|
||||
};
|
||||
|
||||
const onConfirm = async () => {
|
||||
if (!pending) return;
|
||||
try {
|
||||
const ids =
|
||||
pending.kind === 'others'
|
||||
? (await allSessionIds()).filter((id) => id !== currentId)
|
||||
: pending.ids;
|
||||
await revoke(ids);
|
||||
notify.success(t('profile.sessions.revoked', { count: ids.length }));
|
||||
setSelected([]);
|
||||
setPending(null);
|
||||
} catch (e) {
|
||||
handleError(e);
|
||||
}
|
||||
};
|
||||
|
||||
// "Sign out everywhere else" is only meaningful once a second session exists.
|
||||
const hasOthers = total > (currentId ? 1 : 0);
|
||||
|
||||
return (
|
||||
<Paper p="xl" shadow="sm" radius="lg" withBorder>
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
||||
<div>
|
||||
<Title order={5}>{t('profile.sessions.title')}</Title>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('profile.sessions.hint')}
|
||||
</Text>
|
||||
</div>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{selected.length > 0 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
color="red"
|
||||
size="sm"
|
||||
onClick={() => setPending({ kind: 'selected', ids: selected })}
|
||||
>
|
||||
{t('profile.sessions.revokeSelected', { count: selected.length })}
|
||||
</Button>
|
||||
)}
|
||||
{hasOthers && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
color="red"
|
||||
size="sm"
|
||||
leftSection={<IconLogout size={16} />}
|
||||
onClick={() => setPending({ kind: 'others' })}
|
||||
>
|
||||
{t('profile.sessions.signOutOthers')}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<AdvancedTable<MySession>
|
||||
tableName="active-sessions"
|
||||
columns={columns}
|
||||
data={sessions}
|
||||
itemCount={total}
|
||||
pageIndex={pageIndex}
|
||||
onPageChange={setPageIndex}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={setPageSize}
|
||||
pageSizeOptions={[5, 10, 20]}
|
||||
refresh={refetch}
|
||||
isLoading={isFetching}
|
||||
emptyText={t('profile.sessions.empty')}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<ConfirmModal
|
||||
opened={pending !== null}
|
||||
onClose={() => setPending(null)}
|
||||
onConfirm={onConfirm}
|
||||
loading={isRevoking}
|
||||
title={t('profile.sessions.confirm.title')}
|
||||
message={confirmMessage()}
|
||||
confirmLabel={t('profile.sessions.revoke')}
|
||||
cancelLabel={t('common.cancel', 'Cancel')}
|
||||
/>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { authStorage } from "../utils/auth-storage";
|
||||
import { hydrateAuth, logout, setUser } from "../store/auth.slice";
|
||||
import type { AuthUser } from "../types/auth.types";
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { PageLoader } from '@ema-platform/ui';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import { hydrateAuth, logout, setToken, setUser } from '../store/auth.slice';
|
||||
import { refreshAccessToken } from '../utils/refresh-token';
|
||||
import type { AuthUser } from '../types/auth.types';
|
||||
|
||||
const BASE_API_URL =
|
||||
(import.meta as { env?: Record<string, string> }).env?.[
|
||||
"VITE_BASE_API_URL"
|
||||
] ?? "http://localhost:3001/api";
|
||||
(import.meta as { env?: Record<string, string> }).env?.['VITE_BASE_API_URL'] ??
|
||||
'http://localhost:3000/api';
|
||||
|
||||
/**
|
||||
* Restores the signed-in session before the router renders.
|
||||
@@ -38,10 +39,31 @@ export function AuthBootstrap({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BASE_API_URL}/auth/me`, {
|
||||
let response = await fetch(`${BASE_API_URL}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
// An expired access token is the normal state after a day away — spend
|
||||
// the refresh token before deciding the session is over. Without this
|
||||
// a lapsed token logs the user out on load even though the credential
|
||||
// to renew it is sitting right next to it in storage.
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
try {
|
||||
const fresh = await refreshAccessToken();
|
||||
dispatch(setToken(fresh));
|
||||
response = await fetch(`${BASE_API_URL}/auth/me`, {
|
||||
headers: { Authorization: `Bearer ${fresh}` },
|
||||
});
|
||||
} catch (err) {
|
||||
// Only the server rejecting the refresh token ends the session —
|
||||
// same rule as the API layer's 401 handler. A 502 or a network
|
||||
// blip during refresh keeps the stored session; the screens
|
||||
// surface their own errors.
|
||||
if (!(err as { sessionExpired?: boolean })?.sessionExpired) return;
|
||||
// Rejected — fall through to the logout below.
|
||||
}
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
const user = (await response.json()) as AuthUser;
|
||||
// Keep the persisted session as the source of truth when it is
|
||||
@@ -71,7 +93,7 @@ export function AuthBootstrap({ children }: { children: ReactNode }) {
|
||||
|
||||
// Rendering the router before the session resolves would let the guards
|
||||
// redirect based on a state that is about to change.
|
||||
if (!ready) return null;
|
||||
if (!ready) return <PageLoader label="Authenticating Maritime Session…" height="100vh" />;
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
@@ -7,15 +7,14 @@ import {
|
||||
Stack,
|
||||
Text,
|
||||
Title,
|
||||
UnstyledButton,
|
||||
rem,
|
||||
useComputedColorScheme,
|
||||
useMantineColorScheme,
|
||||
useMantineTheme,
|
||||
type BoxProps,
|
||||
} from '@mantine/core';
|
||||
import { IconCheck, IconMoon, IconSun } from '@tabler/icons-react';
|
||||
import { IconCheck } from '@tabler/icons-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ColorSchemeToggle, LanguageSwitcher } from '@ema-platform/ui';
|
||||
import { useAuthConfig } from '../AuthConfig';
|
||||
|
||||
export function BrandMark({ size = 44, ...boxProps }: BoxProps & { size?: number }) {
|
||||
@@ -33,35 +32,6 @@ export function BrandMark({ size = 44, ...boxProps }: BoxProps & { size?: number
|
||||
);
|
||||
}
|
||||
|
||||
function ThemeToggle() {
|
||||
const { t } = useTranslation();
|
||||
const { setColorScheme } = useMantineColorScheme();
|
||||
const computed = useComputedColorScheme('light');
|
||||
const isDark = computed === 'dark';
|
||||
|
||||
return (
|
||||
<UnstyledButton
|
||||
onClick={() => setColorScheme(isDark ? 'light' : 'dark')}
|
||||
aria-label={t('authShell.toggleTheme', 'Toggle theme')}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: rem(36),
|
||||
height: rem(36),
|
||||
borderRadius: rem(10),
|
||||
border: '1px solid var(--mantine-color-default-border)',
|
||||
background: 'var(--mantine-color-body)',
|
||||
color: 'var(--mantine-color-dimmed)',
|
||||
cursor: 'pointer',
|
||||
transition: 'all 150ms ease',
|
||||
}}
|
||||
>
|
||||
{isDark ? <IconSun size={18} /> : <IconMoon size={18} />}
|
||||
</UnstyledButton>
|
||||
);
|
||||
}
|
||||
|
||||
interface AuthShellProps {
|
||||
children: ReactNode;
|
||||
brandTitle?: string;
|
||||
@@ -98,8 +68,9 @@ export function AuthShell({ children, brandTitle, brandSubtitle }: AuthShellProp
|
||||
}}
|
||||
p="md"
|
||||
>
|
||||
{/* Theme toggle — top-right corner */}
|
||||
<Box
|
||||
{/* Language switcher & Theme toggle — top-right corner */}
|
||||
<Group
|
||||
gap="xs"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: rem(16),
|
||||
@@ -107,8 +78,9 @@ export function AuthShell({ children, brandTitle, brandSubtitle }: AuthShellProp
|
||||
zIndex: 10,
|
||||
}}
|
||||
>
|
||||
<ThemeToggle />
|
||||
</Box>
|
||||
<LanguageSwitcher supportedLanguages={['en', 'am']} />
|
||||
<ColorSchemeToggle />
|
||||
</Group>
|
||||
|
||||
<Flex
|
||||
mih="100vh"
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import Cookies from 'js-cookie';
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||
import type { ReactNode } from 'react';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import { useAuthToken } from '../hooks/useAuthToken';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children?: ReactNode;
|
||||
loginPath?: string;
|
||||
}
|
||||
|
||||
export function ProtectedRoute({ children, loginPath = '/login' }: ProtectedRouteProps) {
|
||||
export function ProtectedRoute({ children, loginPath = '/' }: ProtectedRouteProps) {
|
||||
const location = useLocation();
|
||||
// `authStorage` is already scoped to this app; the bare key is only the
|
||||
// legacy pre-prefix session. Never read a sibling app's token — that is how
|
||||
// a backoffice tab ends up authenticated as a portal applicant.
|
||||
const token = authStorage.getToken() ?? Cookies.get('auth-token');
|
||||
const token = useAuthToken();
|
||||
|
||||
if (!token) {
|
||||
return <Navigate to={loginPath} state={{ from: location }} replace />;
|
||||
|
||||
22
libs/auth/src/lib/hooks/two-factor-request.spec.ts
Normal file
22
libs/auth/src/lib/hooks/two-factor-request.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { twoFactorRequest } from "./two-factor-request";
|
||||
|
||||
describe("twoFactorRequest", () => {
|
||||
it("creates when the user has no account configuration yet", () => {
|
||||
expect(twoFactorRequest(undefined, true)).toEqual({
|
||||
url: "/account-configurations/set-my-config",
|
||||
method: "POST",
|
||||
body: { isMFARequired: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("updates an existing record instead of creating a second one", () => {
|
||||
const config = { id: "c9fc67c6", isMFARequired: true };
|
||||
|
||||
expect(twoFactorRequest(config, false)).toEqual({
|
||||
url: "/account-configurations/my-config/c9fc67c6",
|
||||
method: "PUT",
|
||||
body: { isMFARequired: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
26
libs/auth/src/lib/hooks/two-factor-request.ts
Normal file
26
libs/auth/src/lib/hooks/two-factor-request.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
type AccountConfig = { id: string; isMFARequired: boolean };
|
||||
|
||||
/**
|
||||
* Picks the request that persists the two-step verification setting.
|
||||
*
|
||||
* `set-my-config` only ever creates, and `iam.account_configurations` is unique
|
||||
* per user — so an existing record has to be updated through PUT. Getting this
|
||||
* backwards works exactly once and then fails on the unique constraint, which
|
||||
* is why the choice lives here, apart from the hook, with a test on it.
|
||||
*/
|
||||
export function twoFactorRequest(
|
||||
config: AccountConfig | undefined,
|
||||
isMFARequired: boolean,
|
||||
) {
|
||||
return config
|
||||
? {
|
||||
url: `/account-configurations/my-config/${config.id}`,
|
||||
method: "PUT" as const,
|
||||
body: { isMFARequired },
|
||||
}
|
||||
: {
|
||||
url: "/account-configurations/set-my-config",
|
||||
method: "POST" as const,
|
||||
body: { isMFARequired },
|
||||
};
|
||||
}
|
||||
15
libs/auth/src/lib/hooks/useAuthToken.ts
Normal file
15
libs/auth/src/lib/hooks/useAuthToken.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { useSelector } from 'react-redux';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import type { AuthState } from '../types/auth.types';
|
||||
|
||||
/**
|
||||
* The current auth token, preferring Redux so components re-render on login
|
||||
* and logout. Falls back to storage for the one case Redux misses: both
|
||||
* `hydrateAuth` and the stores' `preloadedState` only populate `auth.token`
|
||||
* when a token *and* a cached user are present, so a session with a token but
|
||||
* no cached user would otherwise read as signed out.
|
||||
*/
|
||||
export function useAuthToken(): string | undefined {
|
||||
const token = useSelector((state: { auth: AuthState }) => state.auth.token);
|
||||
return token ?? authStorage.getToken();
|
||||
}
|
||||
@@ -119,6 +119,22 @@ const profileApi = baseApi
|
||||
query: ({ id, body }) => ({ url: `/profiles/${id}`, method: 'PUT', body }),
|
||||
invalidatesTags: ['CurrentProfile'],
|
||||
}),
|
||||
/**
|
||||
* The portal role — seafarer, vessel owner or logistics operator.
|
||||
*
|
||||
* Sidebar and route permissions are computed from this server-side
|
||||
* (`profiles.type`), not from the declared modes of operation, so the
|
||||
* Operations tab writes it here too. Invalidates the profile so the
|
||||
* shell repermissions itself without a reload.
|
||||
*/
|
||||
updateMyAccountType: builder.mutation<unknown, { type: string }>({
|
||||
query: (body) => ({
|
||||
url: '/profiles/me/account-type',
|
||||
method: 'PUT',
|
||||
body,
|
||||
}),
|
||||
invalidatesTags: (_result, error) => (error ? [] : ['CurrentProfile']),
|
||||
}),
|
||||
updateMyAddress: builder.mutation<
|
||||
unknown,
|
||||
{ id: string; body: Record<string, unknown> }
|
||||
@@ -134,6 +150,7 @@ export const {
|
||||
useGetMyProfileQuery,
|
||||
useUpdateMyProfileMutation,
|
||||
useUpdateMyAddressMutation,
|
||||
useUpdateMyAccountTypeMutation,
|
||||
} = profileApi;
|
||||
export const currentProfileApi = profileApi;
|
||||
|
||||
|
||||
76
libs/auth/src/lib/hooks/useIdleTimer.ts
Normal file
76
libs/auth/src/lib/hooks/useIdleTimer.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
const ACTIVITY_EVENTS = [
|
||||
'mousedown',
|
||||
'mousemove',
|
||||
'keydown',
|
||||
'scroll',
|
||||
'touchstart',
|
||||
'click',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Fires `onIdle` once no activity event has fired for `timeoutMs` — the
|
||||
* "left the desk" auto-logout for a govt app handling sensitive records.
|
||||
*
|
||||
* `onIdle` is read through a ref rather than a `useEffect` dependency: the
|
||||
* caller typically passes a fresh closure every render (it captures
|
||||
* `dispatch`, `navigate`, current user), and depending on it directly would
|
||||
* tear down and re-add six window listeners — and rearm the timer to a full
|
||||
* 15 minutes — on every unrelated re-render, not just real activity.
|
||||
*/
|
||||
export function useIdleTimer(timeoutMs: number, onIdle: () => void) {
|
||||
const onIdleRef = useRef(onIdle);
|
||||
onIdleRef.current = onIdle;
|
||||
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
let lastReset = 0;
|
||||
|
||||
// localStorage is origin-scoped, so every tab of this app shares it and
|
||||
// the sibling app (other port/domain) does not.
|
||||
const ACTIVITY_KEY = 'ema-last-activity';
|
||||
|
||||
function fire() {
|
||||
// This tab sat idle, but a sibling tab may have been busy the whole
|
||||
// time — logging out here would clear the shared cookies and kill that
|
||||
// tab mid-work. Trust the newest activity stamp any tab wrote.
|
||||
let last = 0;
|
||||
try {
|
||||
last = Number(localStorage.getItem(ACTIVITY_KEY)) || 0;
|
||||
} catch {
|
||||
/* storage blocked — fall back to this tab's own timer */
|
||||
}
|
||||
const remaining = last + timeoutMs - Date.now();
|
||||
if (remaining > 1000) {
|
||||
timer = setTimeout(fire, remaining);
|
||||
} else {
|
||||
onIdleRef.current();
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
// mousemove fires dozens of times a second; only rearm once a second
|
||||
// so it isn't clearing/setting a timeout on every pixel of movement.
|
||||
const now = Date.now();
|
||||
if (now - lastReset < 1000) return;
|
||||
lastReset = now;
|
||||
try {
|
||||
localStorage.setItem(ACTIVITY_KEY, String(now));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(fire, timeoutMs);
|
||||
}
|
||||
|
||||
reset();
|
||||
ACTIVITY_EVENTS.forEach((event) => window.addEventListener(event, reset));
|
||||
return () => {
|
||||
ACTIVITY_EVENTS.forEach((event) =>
|
||||
window.removeEventListener(event, reset),
|
||||
);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [timeoutMs]);
|
||||
}
|
||||
65
libs/auth/src/lib/hooks/useSessions.ts
Normal file
65
libs/auth/src/lib/hooks/useSessions.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { useApiLazyQuery, useApiMutation, useApiQuery } from '@ema-platform/api';
|
||||
|
||||
export interface MySession {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
email: string;
|
||||
/** IP address the session was created from — IAM sends no user agent. */
|
||||
device: string;
|
||||
expiryTime: string;
|
||||
refreshCount: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** `/sessions/my-sessions` answers with a tuple, not the usual `{items, count}`. */
|
||||
type SessionsResponse = [MySession[], number];
|
||||
|
||||
const SESSIONS_URL = '/sessions/my-sessions';
|
||||
const ORDER_BY = 'CreatedAt:DESC';
|
||||
|
||||
function unwrapList(data: unknown): SessionsResponse {
|
||||
if (!Array.isArray(data)) return [[], 0];
|
||||
const [items, total] = data as Partial<SessionsResponse>;
|
||||
return [items ?? [], total ?? 0];
|
||||
}
|
||||
|
||||
/**
|
||||
* The signed-in user's login sessions, and the two ways to end them.
|
||||
*
|
||||
* Uses the generic query/mutation endpoints rather than its own slice, so
|
||||
* freshness comes from `refetch()` rather than cache tags — the same shape as
|
||||
* `useTwoFactor`.
|
||||
*/
|
||||
export function useSessions({ skip, take }: { skip: number; take: number }) {
|
||||
const { data, isFetching, refetch } = useApiQuery<SessionsResponse>({
|
||||
url: SESSIONS_URL,
|
||||
params: { skip, take, orderBy: ORDER_BY },
|
||||
});
|
||||
const [fetchAll] = useApiLazyQuery<SessionsResponse>();
|
||||
const [send, { isLoading: isRevoking }] = useApiMutation();
|
||||
|
||||
const [sessions, total] = unwrapList(data);
|
||||
|
||||
/** Every session id the user has, not just the ones on the current page. */
|
||||
const allSessionIds = async (): Promise<string[]> => {
|
||||
// `total` is one page stale at worst; ask for a page big enough to cover it
|
||||
// growing between render and click.
|
||||
const result = await fetchAll({
|
||||
url: SESSIONS_URL,
|
||||
params: { skip: 0, take: Math.max(total, sessions.length) + 20, orderBy: ORDER_BY },
|
||||
}).unwrap();
|
||||
return unwrapList(result)[0].map((s) => s.id);
|
||||
};
|
||||
|
||||
const revoke = async (ids: string[]) => {
|
||||
if (ids.length === 0) return;
|
||||
await send(
|
||||
ids.length === 1
|
||||
? { url: `/sessions/revoke/${ids[0]}`, method: 'DELETE' }
|
||||
: { url: '/sessions/bulk-revoke', method: 'POST', body: { sessionIds: ids } },
|
||||
).unwrap();
|
||||
await refetch();
|
||||
};
|
||||
|
||||
return { sessions, total, isFetching, refetch, revoke, isRevoking, allSessionIds };
|
||||
}
|
||||
21
libs/auth/src/lib/hooks/useTwoFactor.ts
Normal file
21
libs/auth/src/lib/hooks/useTwoFactor.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { useApiMutation, useApiQuery } from "@ema-platform/api";
|
||||
import { twoFactorRequest } from "./two-factor-request";
|
||||
|
||||
type AccountConfig = { id: string; isMFARequired: boolean };
|
||||
|
||||
/** Reads and writes the signed-in user's IAM two-step verification setting. */
|
||||
export function useTwoFactor() {
|
||||
const { data, refetch, isLoading } = useApiQuery<{ items: AccountConfig[] }>({
|
||||
url: "/account-configurations/my-config",
|
||||
});
|
||||
const [save, { isLoading: isSaving }] = useApiMutation();
|
||||
|
||||
const config = data?.items?.[0];
|
||||
|
||||
const setEnabled = async (isMFARequired: boolean) => {
|
||||
await save(twoFactorRequest(config, isMFARequired)).unwrap();
|
||||
await refetch();
|
||||
};
|
||||
|
||||
return { enabled: !!config?.isMFARequired, isLoading, isSaving, setEnabled };
|
||||
}
|
||||
@@ -11,8 +11,10 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
UnstyledButton,
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
IconArrowLeft,
|
||||
IconArrowRight,
|
||||
IconDeviceMobile,
|
||||
IconLock,
|
||||
@@ -50,6 +52,14 @@ export function LoginPage() {
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
const [profileTrigger] = useApiMutation<{ profile: CurrentProfile | null }>();
|
||||
|
||||
const handleBack = () => {
|
||||
if (window.history.length > 1) {
|
||||
navigate(-1);
|
||||
} else {
|
||||
navigate("/");
|
||||
}
|
||||
};
|
||||
|
||||
// Built inside the component (not module scope) so validation messages
|
||||
// pick up the active language — same pattern as ProfilePage's forms.
|
||||
const schema = z.object({
|
||||
@@ -101,6 +111,17 @@ export function LoginPage() {
|
||||
method: "POST",
|
||||
body: values,
|
||||
}).unwrap();
|
||||
|
||||
// Two-step verification on: the server withheld the tokens and mailed a
|
||||
// one-time code instead. Storing this response would write an undefined
|
||||
// token and 401 the very next request.
|
||||
if (data.mfaRequired) {
|
||||
navigate("/otp-verify", {
|
||||
state: { mode: "mfa", email: values.email },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(loginSuccess(data));
|
||||
|
||||
const me = await meTrigger({
|
||||
@@ -149,6 +170,32 @@ export function LoginPage() {
|
||||
return (
|
||||
<AuthShell>
|
||||
<Stack gap="lg">
|
||||
<UnstyledButton
|
||||
onClick={handleBack}
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: 6,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
color: "var(--mantine-color-dimmed)",
|
||||
cursor: "pointer",
|
||||
width: "fit-content",
|
||||
transition: "all 150ms ease",
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.color = "var(--mantine-primary-color-filled)";
|
||||
e.currentTarget.style.transform = "translateX(-3px)";
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.color = "var(--mantine-color-dimmed)";
|
||||
e.currentTarget.style.transform = "translateX(0)";
|
||||
}}
|
||||
>
|
||||
<IconArrowLeft size={18} />
|
||||
{t("common.back", "Back")}
|
||||
</UnstyledButton>
|
||||
|
||||
<div>
|
||||
<Title order={2} fz={30}>
|
||||
{t("login.welcome", { appName, defaultValue: "Welcome to {{appName}}" })}
|
||||
|
||||
@@ -17,10 +17,13 @@ import { Controller, useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { useDispatch } from 'react-redux';
|
||||
import { useApiMutation } from '@ema-platform/api';
|
||||
import { notify, useErrorHandler } from '@ema-platform/ui';
|
||||
import { AuthShell } from '../components/AuthShell';
|
||||
import { useAuthConfig } from '../AuthConfig';
|
||||
import { loginSuccess, setUser } from '../store/auth.slice';
|
||||
import type { AuthUser, LoginPayload } from '../types/auth.types';
|
||||
|
||||
const CODE_LENGTH = 6;
|
||||
const RESEND_SECONDS = 30;
|
||||
@@ -37,14 +40,18 @@ export function OTPVerificationPage() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { loginRedirectPath } = useAuthConfig();
|
||||
const dispatch = useDispatch();
|
||||
const state = location.state as
|
||||
| { email?: string; phoneNumber?: string }
|
||||
| { email?: string; phoneNumber?: string; mode?: 'mfa' }
|
||||
| null;
|
||||
const email = state?.email ?? '';
|
||||
const phoneNumber = state?.phoneNumber ?? '';
|
||||
/** Second factor at sign-in, as opposed to the phone-number verification. */
|
||||
const isMfa = state?.mode === 'mfa';
|
||||
|
||||
const [verifyTrigger, { isLoading: loading }] = useApiMutation();
|
||||
const [verifyTrigger, { isLoading: loading }] = useApiMutation<LoginPayload>();
|
||||
const [resendTrigger, { isLoading: resending }] = useApiMutation();
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
const [secondsLeft, setSecondsLeft] = useState(RESEND_SECONDS);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const { handleError } = useErrorHandler();
|
||||
@@ -66,6 +73,21 @@ export function OTPVerificationPage() {
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
try {
|
||||
if (isMfa) {
|
||||
const data = await verifyTrigger({
|
||||
url: '/auth/mfa-verify',
|
||||
method: 'POST',
|
||||
body: { email, otp: values.verificationCode },
|
||||
}).unwrap();
|
||||
|
||||
dispatch(loginSuccess(data));
|
||||
const me = await meTrigger({ url: '/auth/me', method: 'GET' }).unwrap();
|
||||
dispatch(setUser(me));
|
||||
|
||||
navigate(loginRedirectPath);
|
||||
return;
|
||||
}
|
||||
|
||||
await verifyTrigger({
|
||||
url: '/auth/verify-phone-number',
|
||||
method: 'PATCH',
|
||||
@@ -164,44 +186,51 @@ export function OTPVerificationPage() {
|
||||
</Stack>
|
||||
</form>
|
||||
|
||||
<Divider
|
||||
label="Having trouble?"
|
||||
labelPosition="center"
|
||||
variant="dashed"
|
||||
/>
|
||||
{/* Sign-in has not happened yet under MFA, so there is nothing to skip
|
||||
to — and the resend endpoint below only regenerates phone-verification
|
||||
codes. A fresh MFA code means logging in again. */}
|
||||
{!isMfa && (
|
||||
<>
|
||||
<Divider
|
||||
label="Having trouble?"
|
||||
labelPosition="center"
|
||||
variant="dashed"
|
||||
/>
|
||||
|
||||
<Button
|
||||
variant="light"
|
||||
fullWidth
|
||||
size="md"
|
||||
onClick={() => navigate(loginRedirectPath)}
|
||||
>
|
||||
Skip verification for now
|
||||
</Button>
|
||||
<Button
|
||||
variant="light"
|
||||
fullWidth
|
||||
size="md"
|
||||
onClick={() => navigate(loginRedirectPath)}
|
||||
>
|
||||
Skip verification for now
|
||||
</Button>
|
||||
|
||||
<Center>
|
||||
<Group justify="center" gap={6}>
|
||||
<Text size="sm" c="dimmed">
|
||||
Didn't receive a code?
|
||||
</Text>
|
||||
{secondsLeft > 0 ? (
|
||||
<Text size="sm" c="dimmed" fw={600}>
|
||||
Resend in {secondsLeft}s
|
||||
</Text>
|
||||
) : (
|
||||
<Anchor
|
||||
size="sm"
|
||||
fw={600}
|
||||
onClick={handleResendOtp}
|
||||
style={
|
||||
resending ? { pointerEvents: 'none', opacity: 0.6 } : undefined
|
||||
}
|
||||
>
|
||||
Resend code
|
||||
</Anchor>
|
||||
)}
|
||||
</Group>
|
||||
</Center>
|
||||
<Center>
|
||||
<Group justify="center" gap={6}>
|
||||
<Text size="sm" c="dimmed">
|
||||
Didn't receive a code?
|
||||
</Text>
|
||||
{secondsLeft > 0 ? (
|
||||
<Text size="sm" c="dimmed" fw={600}>
|
||||
Resend in {secondsLeft}s
|
||||
</Text>
|
||||
) : (
|
||||
<Anchor
|
||||
size="sm"
|
||||
fw={600}
|
||||
onClick={handleResendOtp}
|
||||
style={
|
||||
resending ? { pointerEvents: 'none', opacity: 0.6 } : undefined
|
||||
}
|
||||
>
|
||||
Resend code
|
||||
</Anchor>
|
||||
)}
|
||||
</Group>
|
||||
</Center>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</AuthShell>
|
||||
);
|
||||
|
||||
@@ -11,8 +11,10 @@ import {
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
UnstyledButton,
|
||||
} from '@mantine/core';
|
||||
import {
|
||||
IconArrowLeft,
|
||||
IconArrowRight,
|
||||
IconAt,
|
||||
IconDeviceMobile,
|
||||
@@ -61,6 +63,14 @@ export function SignupPage() {
|
||||
}>();
|
||||
const [meTrigger] = useApiMutation<AuthUser>();
|
||||
|
||||
const handleBack = () => {
|
||||
if (window.history.length > 1) {
|
||||
navigate(-1);
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
// Order matches passwordRules' default list: length, lowercase, uppercase,
|
||||
// number, special character. Shared between the zod schema (field error)
|
||||
// and the live checklist below, so both agree on the wording.
|
||||
@@ -80,7 +90,12 @@ export function SignupPage() {
|
||||
username: z.string().min(3, { message: t('signup.usernameMinLength', 'Username must be at least 3 characters') }),
|
||||
phoneNumber: z.string().min(1, { message: t('signup.phoneRequired', 'Phone number is required') }),
|
||||
userType: z.literal('individual'),
|
||||
nameEn: z.string().min(1, { message: t('signup.nameEnRequired', 'Name (English) is required') }),
|
||||
nameEn: z
|
||||
.string()
|
||||
.min(1, { message: t('signup.nameEnRequired', 'Name (English) is required') })
|
||||
.refine((v) => v.trim().split(/\s+/).length >= 3, {
|
||||
message: t('signup.nameEnFullNameRequired', 'Please enter your full name (first, middle, and last)'),
|
||||
}),
|
||||
nameAm: z.string().optional(),
|
||||
password: passwordSchema(8, passwordRuleLabels),
|
||||
confirmPassword: z.string().min(1, { message: t('signup.confirmPasswordRequired', 'Confirm your password') }),
|
||||
@@ -155,6 +170,32 @@ export function SignupPage() {
|
||||
})}
|
||||
>
|
||||
<Stack gap="lg">
|
||||
<UnstyledButton
|
||||
onClick={handleBack}
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
color: 'var(--mantine-color-dimmed)',
|
||||
cursor: 'pointer',
|
||||
width: 'fit-content',
|
||||
transition: 'all 150ms ease',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.color = 'var(--mantine-primary-color-filled)';
|
||||
e.currentTarget.style.transform = 'translateX(-3px)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.color = 'var(--mantine-color-dimmed)';
|
||||
e.currentTarget.style.transform = 'translateX(0)';
|
||||
}}
|
||||
>
|
||||
<IconArrowLeft size={18} />
|
||||
{t('common.back', 'Back')}
|
||||
</UnstyledButton>
|
||||
|
||||
<div>
|
||||
<Title order={2} fz={30}>
|
||||
{t('signup.title', 'Create account')}
|
||||
@@ -174,7 +215,7 @@ export function SignupPage() {
|
||||
<Stack gap="md">
|
||||
<SimpleGrid cols={{ base: 1, xs: 2 }} spacing="md">
|
||||
<TextInput
|
||||
label={t('signup.nameEnLabel', 'Name (English)')}
|
||||
label={t('signup.nameEnLabel', 'Full name (English)')}
|
||||
placeholder={t('signup.nameEnPlaceholder', 'Abebe Bekele')}
|
||||
leftSection={<IconUser size={18} />}
|
||||
error={errors.nameEn?.message}
|
||||
|
||||
@@ -31,6 +31,8 @@ export const LICENSE_PERMISSIONS = {
|
||||
VIEW_INSPECTIONS: "can:View:inspections",
|
||||
CONFIRM_PAYMENT: "can:confirm:license-payment",
|
||||
VIEW_PAYMENTS: "can:View:license-payments",
|
||||
SCHEDULE_ISSUANCE: "can:schedule:license-issuance",
|
||||
ISSUE_CERTIFICATE: "can:issue:license-certificate",
|
||||
CREATE_LICENSE_TYPE: "can:create:license-type",
|
||||
VIEW_LICENSE_TYPES: "can:View:license-types",
|
||||
UPDATE_LICENSE_TYPE: "can:update:license-type",
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
LoginPayload,
|
||||
} from "../types/auth.types";
|
||||
import { authStorage } from "../utils/auth-storage";
|
||||
import { setSignedOut } from "../utils/refresh-token";
|
||||
|
||||
const initialState: AuthState = {
|
||||
user: null,
|
||||
@@ -19,6 +20,7 @@ const authSlice = createSlice({
|
||||
initialState,
|
||||
reducers: {
|
||||
loginSuccess(state, action: PayloadAction<LoginPayload>) {
|
||||
setSignedOut(false);
|
||||
state.token = action.payload.token;
|
||||
state.isAuthenticated = true;
|
||||
authStorage.setToken(action.payload.token);
|
||||
@@ -37,6 +39,8 @@ const authSlice = createSlice({
|
||||
authStorage.removeProfile();
|
||||
},
|
||||
logout(state) {
|
||||
// Before clearing storage, so an in-flight refresh can't repopulate it.
|
||||
setSignedOut(true);
|
||||
state.user = null;
|
||||
state.token = null;
|
||||
state.isAuthenticated = false;
|
||||
|
||||
18
libs/auth/src/lib/utils/jwt.ts
Normal file
18
libs/auth/src/lib/utils/jwt.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Session id from the access token, when it carries one.
|
||||
*
|
||||
* `/sessions/my-sessions` returns no "this is you" flag, so the only way to
|
||||
* stop the user revoking the session they are sitting in is to read the id off
|
||||
* the token. Undefined is a normal answer — an opaque token just means no
|
||||
* "This device" badge and a confirm dialog that warns instead.
|
||||
*/
|
||||
export function currentSessionId(token?: string): string | undefined {
|
||||
const payload = token?.split('.')[1];
|
||||
if (!payload) return undefined;
|
||||
try {
|
||||
const claims = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
|
||||
return claims.sessionId ?? claims.sid ?? claims.jti;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -10,24 +10,92 @@ interface RefreshResponse {
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
export async function refreshAccessToken(): Promise<string> {
|
||||
/**
|
||||
* Marks the one failure that actually ends a session: the server rejecting the
|
||||
* refresh token. Read structurally by the API layer's 401 handler — a shared
|
||||
* error class would mean `libs/api` importing `libs/auth`, which already
|
||||
* imports `libs/api`.
|
||||
*/
|
||||
const sessionExpired = (message: string) =>
|
||||
Object.assign(new Error(message), { sessionExpired: true });
|
||||
|
||||
let inFlight: Promise<string> | null = null;
|
||||
|
||||
let signedOut = false;
|
||||
|
||||
/**
|
||||
* Set on logout, cleared on login. A refresh that was already in flight when
|
||||
* the user (or the idle timer) signed out must not write its response back
|
||||
* into storage — that would silently re-authenticate an unattended desk.
|
||||
*/
|
||||
export function setSignedOut(v: boolean) {
|
||||
signedOut = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Concurrent 401s must share one refresh. A page fires several requests at
|
||||
* once; without this each one POSTs the same refresh token, the server rotates
|
||||
* on the first and rejects the rest, and the losers tear down the session the
|
||||
* winner just renewed.
|
||||
*/
|
||||
export function refreshAccessToken(): Promise<string> {
|
||||
inFlight ??= acquireAndRefresh().finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-tab guard on top of the in-tab one: cookies are shared per origin, so
|
||||
* two tabs expiring together would both POST the same rotating refresh token
|
||||
* and the loser would tear down the session the winner just renewed. A Web
|
||||
* Lock makes the second tab wait; if the first tab already refreshed while it
|
||||
* waited, the fresh token is sitting in storage and no request is needed.
|
||||
*/
|
||||
async function acquireAndRefresh(): Promise<string> {
|
||||
if (typeof navigator === "undefined" || !navigator.locks) {
|
||||
// Old Safari / test env — in-tab de-dup still applies.
|
||||
return runRefresh();
|
||||
}
|
||||
const tokenBefore = authStorage.getToken();
|
||||
return navigator.locks.request("ema-token-refresh", async () => {
|
||||
const current = authStorage.getToken();
|
||||
if (current && current !== tokenBefore) return current;
|
||||
return runRefresh();
|
||||
});
|
||||
}
|
||||
|
||||
async function runRefresh(): Promise<string> {
|
||||
if (signedOut) throw new Error("Signed out");
|
||||
const refreshToken = authStorage.getRefreshToken();
|
||||
if (!refreshToken) throw new Error("No refresh token available");
|
||||
if (!refreshToken) throw sessionExpired("No refresh token available");
|
||||
|
||||
// The IAM service exposes this as `refresh-token`; posting to `/auth/refresh`
|
||||
// 404s, which the catch below turns into a silent logout.
|
||||
// 404s, which the caller would turn into a silent logout.
|
||||
const response = await fetch(`${BASE_API_URL}/auth/refresh-token`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
|
||||
if (
|
||||
response.status === 400 ||
|
||||
response.status === 401 ||
|
||||
response.status === 403
|
||||
) {
|
||||
throw sessionExpired("Refresh token rejected");
|
||||
}
|
||||
|
||||
// Anything else is the API having a bad minute — a 502, a proxy timeout. The
|
||||
// session is still valid, so leave it alone and let the screen report it.
|
||||
if (!response.ok) {
|
||||
authStorage.clear();
|
||||
throw new Error("Token refresh failed");
|
||||
throw new Error(`Token refresh failed (${response.status})`);
|
||||
}
|
||||
|
||||
const data: RefreshResponse = await response.json();
|
||||
// Deliberately NOT sessionExpired: the user already signed out, so there is
|
||||
// no session left to end — just refuse to resurrect it.
|
||||
if (signedOut) throw new Error("Signed out during refresh");
|
||||
authStorage.setToken(data.token);
|
||||
if (data.refreshToken) authStorage.setRefreshToken(data.refreshToken);
|
||||
return data.token;
|
||||
|
||||
11
libs/auth/vite.config.mts
Normal file
11
libs/auth/vite.config.mts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
watch: false,
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['src/**/*.spec.ts'],
|
||||
reporters: ['default'],
|
||||
},
|
||||
});
|
||||
@@ -1,12 +1,16 @@
|
||||
export * from "./lib/input/BilingualInput";
|
||||
export * from "./lib/input/AmharicDatePicker";
|
||||
export * from "./lib/feedback/ConfirmModal";
|
||||
export * from "./lib/feedback/PdfPreviewModal";
|
||||
export * from "./lib/feedback/ModalFooter";
|
||||
export * from "./lib/feedback/ApiErrorAlert";
|
||||
export * from "./lib/feedback/notify";
|
||||
export * from "./lib/feedback/FeatureUnavailable";
|
||||
export * from "./lib/feedback/EmptyState";
|
||||
export * from "./lib/feedback/ErrorState";
|
||||
export * from "./lib/feedback/PageLoader";
|
||||
export * from "./lib/components/MaritimeLoader";
|
||||
export * from "./lib/theme/maritime-loader-theme";
|
||||
export * from "./lib/layout/AppHeader";
|
||||
export * from "./lib/layout/AppSidebar";
|
||||
export * from "./lib/layout/AppTopNav";
|
||||
@@ -23,3 +27,4 @@ export * from "./lib/feedback/use-error-handler";
|
||||
export * from "./lib/data/useServerTable";
|
||||
export * from "./lib/landing/LandingPage";
|
||||
export * from "./lib/landing/landing-copy";
|
||||
export * from "./lib/utils/person-name";
|
||||
|
||||
@@ -1,246 +1,141 @@
|
||||
import type { CSSProperties, ComponentPropsWithoutRef } from "react";
|
||||
import type { CSSProperties, ComponentPropsWithoutRef, Ref } from "react";
|
||||
|
||||
export interface MaritimeLoaderProps extends Omit<
|
||||
ComponentPropsWithoutRef<"span">,
|
||||
"children" | "color"
|
||||
> {
|
||||
/** Standalone size. Mantine's Loader size is used automatically when omitted. */
|
||||
/** Size in pixels or CSS string. Defaults to 80. */
|
||||
size?: number | string;
|
||||
/** Standalone CSS color. Mantine's Loader color is used automatically when omitted. */
|
||||
/** Primary accent color. Defaults to EMA Ocean Blue (#0284C7). */
|
||||
color?: string;
|
||||
/** Accessible status text. */
|
||||
/** Visual variant: 'full' (emblem + orbital radar) or 'compact' (sleek inline spinner). */
|
||||
variant?: "full" | "compact";
|
||||
/** Accessible label. */
|
||||
label?: string;
|
||||
ref?: Ref<HTMLSpanElement>;
|
||||
}
|
||||
|
||||
const styles = `
|
||||
.ema-loader {
|
||||
.ema-pro-loader {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: calc(var(--ema-size, var(--loader-size, 80px)) * 1.88);
|
||||
color: var(--ema-color, var(--loader-color, #075985));
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.ema-loader__svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--ema-size, var(--loader-size, 80px));
|
||||
height: var(--ema-size, var(--loader-size, 80px));
|
||||
vertical-align: middle;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ema-pro-loader--full {
|
||||
width: calc(var(--ema-size, var(--loader-size, 80px)) * 1.15);
|
||||
height: calc(var(--ema-size, var(--loader-size, 80px)) * 1.15);
|
||||
}
|
||||
|
||||
.ema-pro-loader__stage {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* --- Glowing Ambient Backdrop --- */
|
||||
.ema-pro-loader__glow {
|
||||
position: absolute;
|
||||
inset: 10%;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, rgba(2, 132, 199, 0.28) 0%, rgba(14, 165, 233, 0.08) 55%, transparent 75%);
|
||||
filter: blur(8px);
|
||||
animation: ema-glow-pulse 3s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
/* --- SVG Overlay & Ring Animations --- */
|
||||
.ema-pro-loader__svg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
filter: drop-shadow(
|
||||
0 calc(var(--ema-size, var(--loader-size, 80px)) * 0.035)
|
||||
calc(var(--ema-size, var(--loader-size, 80px)) * 0.04)
|
||||
rgb(7 39 58 / 18%)
|
||||
);
|
||||
}
|
||||
|
||||
.ema-loader__ship {
|
||||
transform-box: fill-box;
|
||||
transform-origin: 50% 82%;
|
||||
animation: ema-ship-float 2.55s cubic-bezier(0.45, 0, 0.55, 1) infinite;
|
||||
}
|
||||
|
||||
.ema-loader__shadow {
|
||||
fill: currentColor;
|
||||
opacity: 0.12;
|
||||
.ema-pro-loader__ring-outer {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
animation: ema-shadow-breathe 2.55s cubic-bezier(0.45, 0, 0.55, 1) infinite;
|
||||
animation: ema-spin-cw 16s linear infinite;
|
||||
}
|
||||
|
||||
.ema-loader__deck {
|
||||
fill: currentColor;
|
||||
opacity: 0.82;
|
||||
}
|
||||
|
||||
.ema-loader__superstructure > path:first-child,
|
||||
.ema-loader__bridge-top {
|
||||
fill: #f8fbfc;
|
||||
stroke: currentColor;
|
||||
stroke-width: 2.4;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.ema-loader__bridge-top { stroke-width: 2; }
|
||||
|
||||
.ema-loader__window {
|
||||
fill: #bfe9ff;
|
||||
stroke: currentColor;
|
||||
stroke-width: 0.7;
|
||||
}
|
||||
|
||||
.ema-loader__cabin-line {
|
||||
fill: currentColor;
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
.ema-loader__funnel > path:first-child {
|
||||
fill: #eef3f5;
|
||||
stroke: currentColor;
|
||||
stroke-width: 2;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.ema-loader__green { fill: #078930; }
|
||||
.ema-loader__yellow { fill: #fcd116; }
|
||||
.ema-loader__red { fill: #da121a; }
|
||||
|
||||
.ema-loader__mast {
|
||||
fill: currentColor;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.8;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.ema-loader__flag-pole {
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.7;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
|
||||
.ema-loader__flag {
|
||||
.ema-pro-loader__ring-inner {
|
||||
transform-box: fill-box;
|
||||
transform-origin: left center;
|
||||
animation: ema-flag-wave 0.95s ease-in-out infinite alternate;
|
||||
transform-origin: center;
|
||||
animation: ema-spin-ccw 10s cubic-bezier(0.4, 0, 0.2, 1) infinite;
|
||||
}
|
||||
|
||||
.ema-loader__hull {
|
||||
fill: #f8fbfc;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.4;
|
||||
stroke-linejoin: round;
|
||||
.ema-pro-loader__sonar-wave {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
animation: ema-sonar-expand 2.6s cubic-bezier(0.1, 0.8, 0.3, 1) infinite;
|
||||
}
|
||||
|
||||
.ema-loader__lower-hull {
|
||||
fill: currentColor;
|
||||
opacity: 0.92;
|
||||
.ema-pro-loader__core-logo {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 54%;
|
||||
height: 54%;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 4px 10px rgba(11, 25, 44, 0.25));
|
||||
animation: ema-logo-float 3.5s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
.ema-loader__waterline {
|
||||
fill: none;
|
||||
stroke: rgb(255 255 255 / 52%);
|
||||
stroke-width: 2.4;
|
||||
stroke-linecap: round;
|
||||
.ema-pro-loader__center-sync {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
animation: ema-spin-cw 3s linear infinite;
|
||||
}
|
||||
|
||||
.ema-loader__bow-highlight {
|
||||
fill: none;
|
||||
stroke: rgb(255 255 255 / 46%);
|
||||
stroke-width: 2.3;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
/* --- Keyframe Animations --- */
|
||||
@keyframes ema-spin-cw {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.ema-loader__portholes {
|
||||
fill: #d7f2ff;
|
||||
stroke: currentColor;
|
||||
stroke-width: 0.8;
|
||||
@keyframes ema-spin-ccw {
|
||||
from { transform: rotate(360deg); }
|
||||
to { transform: rotate(0deg); }
|
||||
}
|
||||
|
||||
.ema-loader__cargo path {
|
||||
fill: none;
|
||||
stroke: rgb(255 255 255 / 22%);
|
||||
stroke-width: 1;
|
||||
@keyframes ema-glow-pulse {
|
||||
0% { transform: scale(0.92); opacity: 0.5; }
|
||||
100% { transform: scale(1.12); opacity: 0.9; }
|
||||
}
|
||||
|
||||
.ema-loader__container-dark rect { fill: #3f4a52; }
|
||||
.ema-loader__container-muted rect { fill: #7d8991; }
|
||||
.ema-loader__container-steel rect { fill: #59656d; }
|
||||
.ema-loader__container-light rect { fill: #aab2b8; }
|
||||
.ema-loader__container-medium rect { fill: #6c7880; }
|
||||
|
||||
.ema-loader__water-back,
|
||||
.ema-loader__water-front,
|
||||
.ema-loader__foam {
|
||||
fill: none;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
@keyframes ema-sonar-expand {
|
||||
0% { transform: scale(0.65); opacity: 0.9; stroke-width: 3; }
|
||||
60% { opacity: 0.35; }
|
||||
100% { transform: scale(1.4); opacity: 0; stroke-width: 0.5; }
|
||||
}
|
||||
|
||||
.ema-loader__water-back {
|
||||
stroke: currentColor;
|
||||
stroke-width: 5;
|
||||
opacity: 0.28;
|
||||
stroke-dasharray: 58 12;
|
||||
animation: ema-water-back 2.8s linear infinite;
|
||||
}
|
||||
|
||||
.ema-loader__water-front {
|
||||
stroke: currentColor;
|
||||
stroke-width: 6;
|
||||
opacity: 0.55;
|
||||
stroke-dasharray: 70 10;
|
||||
animation: ema-water-front 1.9s linear infinite;
|
||||
}
|
||||
|
||||
.ema-loader__foam {
|
||||
stroke: rgb(255 255 255 / 78%);
|
||||
stroke-width: 3;
|
||||
stroke-dasharray: 11 7;
|
||||
animation: ema-foam-drift 1.65s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes ema-ship-float {
|
||||
0%, 100% { transform: translateY(1.5px) rotate(-0.65deg); }
|
||||
50% { transform: translateY(-3px) rotate(0.65deg); }
|
||||
}
|
||||
|
||||
@keyframes ema-shadow-breathe {
|
||||
0%, 100% { transform: scaleX(1.02); opacity: 0.14; }
|
||||
50% { transform: scaleX(0.9); opacity: 0.08; }
|
||||
}
|
||||
|
||||
@keyframes ema-flag-wave {
|
||||
from { transform: skewY(-3deg) scaleX(0.94); }
|
||||
to { transform: skewY(3deg) scaleX(1.04); }
|
||||
}
|
||||
|
||||
@keyframes ema-water-back {
|
||||
to { stroke-dashoffset: -140; }
|
||||
}
|
||||
|
||||
@keyframes ema-water-front {
|
||||
to { stroke-dashoffset: 160; }
|
||||
}
|
||||
|
||||
@keyframes ema-foam-drift {
|
||||
to { stroke-dashoffset: -36; }
|
||||
@keyframes ema-logo-float {
|
||||
0% { transform: translateY(1px) scale(0.98); }
|
||||
100% { transform: translateY(-2px) scale(1.02); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ema-loader__ship,
|
||||
.ema-loader__shadow,
|
||||
.ema-loader__flag,
|
||||
.ema-loader__water-back,
|
||||
.ema-loader__water-front,
|
||||
.ema-loader__foam {
|
||||
animation: none;
|
||||
.ema-pro-loader__ring-outer,
|
||||
.ema-pro-loader__ring-inner,
|
||||
.ema-pro-loader__sonar-wave,
|
||||
.ema-pro-loader__core-logo,
|
||||
.ema-pro-loader__glow,
|
||||
.ema-pro-loader__center-sync {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.ema-loader__green,
|
||||
.ema-loader__yellow,
|
||||
.ema-loader__red,
|
||||
.ema-loader__container-dark rect,
|
||||
.ema-loader__container-muted rect,
|
||||
.ema-loader__container-steel rect,
|
||||
.ema-loader__container-light rect,
|
||||
.ema-loader__container-medium rect {
|
||||
fill: currentColor;
|
||||
}
|
||||
}
|
||||
|
||||
.ema-loader__label {
|
||||
display: block;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
line-height: 1.2;
|
||||
margin-top: 4px;
|
||||
color: currentColor;
|
||||
}
|
||||
`;
|
||||
[data-mantine-color-scheme='dark'] .ema-pro-loader__glow {
|
||||
background: radial-gradient(circle, rgba(56, 189, 248, 0.35) 0%, rgba(2, 132, 199, 0.12) 60%, transparent 80%);
|
||||
}
|
||||
`;
|
||||
|
||||
function toCssSize(value: number | string | undefined) {
|
||||
return typeof value === "number" ? `${value}px` : value;
|
||||
@@ -249,9 +144,11 @@ function toCssSize(value: number | string | undefined) {
|
||||
export function MaritimeLoader({
|
||||
size,
|
||||
color,
|
||||
label = "Loading maritime services",
|
||||
variant = "full",
|
||||
label = "Ethiopian Maritime Authority Loading",
|
||||
className,
|
||||
style,
|
||||
ref,
|
||||
...props
|
||||
}: MaritimeLoaderProps) {
|
||||
const cssVariables = {
|
||||
@@ -263,174 +160,152 @@ export function MaritimeLoader({
|
||||
return (
|
||||
<span
|
||||
{...props}
|
||||
className={["ema-loader", className].filter(Boolean).join(" ")}
|
||||
ref={ref}
|
||||
className={[
|
||||
"ema-pro-loader",
|
||||
variant === "full" ? "ema-pro-loader--full" : "ema-pro-loader--compact",
|
||||
className,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
style={cssVariables}
|
||||
role="status"
|
||||
aria-label={label}
|
||||
>
|
||||
<style>{styles}</style>
|
||||
<style href="ema-maritime-loader-v3" precedence="low">
|
||||
{styles}
|
||||
</style>
|
||||
|
||||
<svg
|
||||
className="ema-loader__svg"
|
||||
viewBox="0 0 260 138"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<g className="ema-loader__shadow">
|
||||
<ellipse cx="132" cy="113" rx="78" ry="7" />
|
||||
</g>
|
||||
<div className="ema-pro-loader__stage">
|
||||
{/* Soft Ambient Radial Light Aura */}
|
||||
<div className="ema-pro-loader__glow" />
|
||||
|
||||
<g className="ema-loader__ship">
|
||||
<g className="ema-loader__cargo">
|
||||
<g className="ema-loader__container-dark">
|
||||
<rect x="60" y="54" width="27" height="17" rx="1.5" />
|
||||
<path d="M66 56v13M73 56v13M80 56v13" />
|
||||
</g>
|
||||
<g className="ema-loader__container-steel">
|
||||
<rect x="89" y="54" width="27" height="17" rx="1.5" />
|
||||
<path d="M95 56v13M102 56v13M109 56v13" />
|
||||
</g>
|
||||
<g className="ema-loader__container-light">
|
||||
<rect x="118" y="54" width="27" height="17" rx="1.5" />
|
||||
<path d="M124 56v13M131 56v13M138 56v13" />
|
||||
</g>
|
||||
<g className="ema-loader__container-medium">
|
||||
<rect x="147" y="54" width="27" height="17" rx="1.5" />
|
||||
<path d="M153 56v13M160 56v13M167 56v13" />
|
||||
</g>
|
||||
<g className="ema-loader__container-dark">
|
||||
<rect x="76" y="35" width="27" height="17" rx="1.5" />
|
||||
<path d="M82 37v13M89 37v13M96 37v13" />
|
||||
</g>
|
||||
<g className="ema-loader__container-muted">
|
||||
<rect x="105" y="35" width="27" height="17" rx="1.5" />
|
||||
<path d="M111 37v13M118 37v13M125 37v13" />
|
||||
</g>
|
||||
<g className="ema-loader__container-dark">
|
||||
<rect x="134" y="35" width="27" height="17" rx="1.5" />
|
||||
<path d="M140 37v13M147 37v13M154 37v13" />
|
||||
</g>
|
||||
</g>
|
||||
{/* Precision Orbital Rings & Sonar Radar SVG */}
|
||||
<svg
|
||||
className="ema-pro-loader__svg"
|
||||
viewBox="0 0 120 120"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<defs>
|
||||
{/* Ethiopian Maritime Brand Gradients */}
|
||||
<linearGradient id="ema-ring-grad-1" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stopColor="#0284C7" />
|
||||
<stop offset="50%" stopColor="#38BDF8" />
|
||||
<stop offset="100%" stopColor="#078930" />
|
||||
</linearGradient>
|
||||
|
||||
<path className="ema-loader__deck" d="M42 72H214l-4 6H48z" />
|
||||
<linearGradient id="ema-ring-grad-2" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stopColor="#F59E0B" />
|
||||
<stop offset="50%" stopColor="#D4AF37" />
|
||||
<stop offset="100%" stopColor="#FCD116" />
|
||||
</linearGradient>
|
||||
|
||||
<g className="ema-loader__superstructure">
|
||||
<path d="M174 41h27l10 31h-42z" />
|
||||
<path className="ema-loader__bridge-top" d="M178 32h20l5 9h-27z" />
|
||||
<rect
|
||||
className="ema-loader__window"
|
||||
x="179"
|
||||
y="45"
|
||||
width="7"
|
||||
height="7"
|
||||
rx="1"
|
||||
/>
|
||||
<rect
|
||||
className="ema-loader__window"
|
||||
x="188"
|
||||
y="45"
|
||||
width="7"
|
||||
height="7"
|
||||
rx="1"
|
||||
/>
|
||||
<rect
|
||||
className="ema-loader__window"
|
||||
x="197"
|
||||
y="45"
|
||||
width="7"
|
||||
height="7"
|
||||
rx="1"
|
||||
/>
|
||||
<rect
|
||||
className="ema-loader__cabin-line"
|
||||
x="180"
|
||||
y="58"
|
||||
width="20"
|
||||
height="2.5"
|
||||
rx="1.25"
|
||||
/>
|
||||
</g>
|
||||
<linearGradient id="ema-sonar-grad" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||
<stop offset="0%" stopColor="#38BDF8" stopOpacity="0.8" />
|
||||
<stop offset="100%" stopColor="#0284C7" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<g className="ema-loader__funnel">
|
||||
<path d="M166 25h10l3 17h-15z" />
|
||||
<path
|
||||
className="ema-loader__green"
|
||||
d="M166.9 29h9.9l.6 3.5h-11.1z"
|
||||
/>
|
||||
<path
|
||||
className="ema-loader__yellow"
|
||||
d="M166.2 32.5h11.2l.6 3.5h-12.4z"
|
||||
/>
|
||||
<path
|
||||
className="ema-loader__red"
|
||||
d="M165.6 36h12.4l.6 3.5h-13.6z"
|
||||
/>
|
||||
</g>
|
||||
|
||||
<g className="ema-loader__mast">
|
||||
<path d="M194 31V12M188 20h12M194 13l11 8M194 13l-9 8" />
|
||||
<circle cx="194" cy="11" r="2" />
|
||||
</g>
|
||||
|
||||
<g>
|
||||
<path className="ema-loader__flag-pole" d="M184 20V8" />
|
||||
<g className="ema-loader__flag">
|
||||
<path
|
||||
className="ema-loader__green"
|
||||
d="M184 8c7-3 11 3 18 0v4c-7 3-11-3-18 0z"
|
||||
/>
|
||||
<path
|
||||
className="ema-loader__yellow"
|
||||
d="M184 12c7-3 11 3 18 0v4c-7 3-11-3-18 0z"
|
||||
/>
|
||||
<path
|
||||
className="ema-loader__red"
|
||||
d="M184 16c7-3 11 3 18 0v4c-7 3-11-3-18 0z"
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<path
|
||||
className="ema-loader__hull"
|
||||
d="M28 76h205l-15 18c-8 10-20 15-33 15H66c-13 0-24-5-31-15L23 80c-2-2 0-4 5-4z"
|
||||
{/* Sonar Pulsing Wave */}
|
||||
<circle
|
||||
className="ema-pro-loader__sonar-wave"
|
||||
cx="60"
|
||||
cy="60"
|
||||
r="42"
|
||||
fill="none"
|
||||
stroke="url(#ema-ring-grad-1)"
|
||||
/>
|
||||
<path
|
||||
className="ema-loader__lower-hull"
|
||||
d="M34 88h190l-6 6c-8 10-20 15-33 15H66c-13 0-24-5-31-15z"
|
||||
/>
|
||||
<path className="ema-loader__waterline" d="M36 87h188" />
|
||||
<path className="ema-loader__bow-highlight" d="M206 81l15 1-8 9" />
|
||||
|
||||
<g className="ema-loader__portholes">
|
||||
<circle cx="66" cy="91" r="2.2" />
|
||||
<circle cx="78" cy="91" r="2.2" />
|
||||
<circle cx="90" cy="91" r="2.2" />
|
||||
{/* Outer Precision Nautical Tick Ring */}
|
||||
<g className="ema-pro-loader__ring-outer">
|
||||
<circle
|
||||
cx="60"
|
||||
cy="60"
|
||||
r="54"
|
||||
fill="none"
|
||||
stroke="url(#ema-ring-grad-1)"
|
||||
strokeWidth="1.8"
|
||||
strokeDasharray="8 6 2 6"
|
||||
opacity="0.85"
|
||||
/>
|
||||
<circle
|
||||
cx="60"
|
||||
cy="60"
|
||||
r="48"
|
||||
fill="none"
|
||||
stroke="url(#ema-ring-grad-2)"
|
||||
strokeWidth="1"
|
||||
strokeDasharray="40 18"
|
||||
opacity="0.9"
|
||||
/>
|
||||
{/* 4 Cardinal Anchor Points */}
|
||||
<circle cx="60" cy="6" r="2.5" fill="#FCD116" />
|
||||
<circle cx="114" cy="60" r="2.5" fill="#0284C7" />
|
||||
<circle cx="60" cy="114" r="2.5" fill="#078930" />
|
||||
<circle cx="6" cy="60" r="2.5" fill="#DA121A" />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<g className="ema-loader__water-back">
|
||||
<path d="M3 112c17-8 30-8 47 0s30 8 47 0 30-8 47 0 30 8 47 0 30-8 47 0 30 8 47 0" />
|
||||
</g>
|
||||
<g className="ema-loader__water-front">
|
||||
<path d="M-8 121c19-9 34-9 53 0s34 9 53 0 34-9 53 0 34 9 53 0 34-9 53 0 34 9 53 0" />
|
||||
</g>
|
||||
<g className="ema-loader__foam">
|
||||
<path d="M29 106c13 4 25 5 38 3" />
|
||||
<path d="M200 108c14 1 24-1 35-5" />
|
||||
</g>
|
||||
</svg>
|
||||
{label && <span className="ema-loader__label">{label}</span>}
|
||||
{/* Inner Counter-Rotating Golden Ring */}
|
||||
<g className="ema-pro-loader__ring-inner">
|
||||
<circle
|
||||
cx="60"
|
||||
cy="60"
|
||||
r="39"
|
||||
fill="none"
|
||||
stroke="url(#ema-ring-grad-2)"
|
||||
strokeWidth="2"
|
||||
strokeDasharray="28 14"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<circle
|
||||
cx="60"
|
||||
cy="60"
|
||||
r="34"
|
||||
fill="none"
|
||||
stroke="#38BDF8"
|
||||
strokeWidth="1"
|
||||
strokeDasharray="4 8"
|
||||
opacity="0.6"
|
||||
/>
|
||||
</g>
|
||||
|
||||
{/* Vector EMA Emblem Backup for Instant Render */}
|
||||
{variant === "compact" && (
|
||||
<g transform="translate(36, 36) scale(0.4)">
|
||||
<path
|
||||
d="M 60 10 L 110 100 L 85 100 L 60 48 L 35 100 L 10 100 Z"
|
||||
fill="url(#ema-ring-grad-1)"
|
||||
/>
|
||||
<circle
|
||||
className="ema-pro-loader__center-sync"
|
||||
cx="60"
|
||||
cy="64"
|
||||
r="12"
|
||||
fill="none"
|
||||
stroke="#FCD116"
|
||||
strokeWidth="3.5"
|
||||
strokeDasharray="14 8"
|
||||
/>
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
|
||||
{/* Official EMA Crest Logo Image */}
|
||||
<img
|
||||
src="/ema-logo.png"
|
||||
alt="Ethiopian Maritime Authority"
|
||||
className="ema-pro-loader__core-logo"
|
||||
onError={(e) => {
|
||||
// Fallback if image path is not resolving in dev iframe
|
||||
(e.target as HTMLElement).style.display = "none";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default MaritimeLoader;
|
||||
|
||||
// how to use this component.
|
||||
// <Center style={{ width: "90vw", height: "90vh" }}>
|
||||
// <MaritimeLoader
|
||||
// size={120}
|
||||
// color="#075985"
|
||||
// label="Loading Maritime Services..."
|
||||
// />
|
||||
// </Center>
|
||||
|
||||
|
||||
129
libs/ui/src/lib/feedback/PageLoader.tsx
Normal file
129
libs/ui/src/lib/feedback/PageLoader.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import { Center, Box, Stack, Text, useComputedColorScheme } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { MaritimeLoader } from '../components/MaritimeLoader';
|
||||
|
||||
interface PageLoaderProps {
|
||||
/** Visible + accessible label. Defaults to the shared i18n "loading" string. */
|
||||
label?: string;
|
||||
/** Subtitle or secondary detail string. */
|
||||
subtitle?: string;
|
||||
/** Container height. Defaults to a full-page fill. */
|
||||
height?: number | string;
|
||||
/** Show framed executive card backdrop (default: true). */
|
||||
framed?: boolean;
|
||||
}
|
||||
|
||||
/** The full-page/section loading state every screen should use. */
|
||||
export function PageLoader({
|
||||
label,
|
||||
subtitle,
|
||||
height = '60vh',
|
||||
framed = true,
|
||||
}: PageLoaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const computedColorScheme = useComputedColorScheme('light', { getInitialValueInEffect: true });
|
||||
const isDark = computedColorScheme === 'dark';
|
||||
|
||||
const resolvedLabel = label ?? t('loading', 'Loading Maritime Services…');
|
||||
|
||||
return (
|
||||
<Center h={height} w="100%" p="md">
|
||||
<Box
|
||||
style={{
|
||||
position: 'relative',
|
||||
padding: framed ? '2rem 3rem' : '1rem',
|
||||
borderRadius: framed ? '1.25rem' : '0',
|
||||
background: framed
|
||||
? isDark
|
||||
? 'rgba(15, 23, 42, 0.75)'
|
||||
: 'rgba(255, 255, 255, 0.85)'
|
||||
: 'transparent',
|
||||
backdropFilter: framed ? 'blur(12px)' : 'none',
|
||||
boxShadow: framed
|
||||
? isDark
|
||||
? '0 20px 40px rgba(0, 0, 0, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.08)'
|
||||
: '0 20px 40px rgba(11, 25, 44, 0.08), 0 0 0 1px rgba(15, 44, 89, 0.08)'
|
||||
: 'none',
|
||||
transition: 'all 0.3s ease',
|
||||
maxWidth: '440px',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<Stack align="center" gap="md">
|
||||
{/* Main Maritime Animated Loader */}
|
||||
<MaritimeLoader size={110} variant="full" label={resolvedLabel} />
|
||||
|
||||
{/* Ethiopian Maritime Authority Branding Header */}
|
||||
<Box style={{ textAlign: 'center' }}>
|
||||
<Text
|
||||
fw={700}
|
||||
size="xs"
|
||||
style={{
|
||||
letterSpacing: '0.16em',
|
||||
textTransform: 'uppercase',
|
||||
background: 'linear-gradient(135deg, #0284C7 0%, #D4AF37 50%, #078930 100%)',
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
marginBottom: '2px',
|
||||
}}
|
||||
>
|
||||
ETHIOPIAN MARITIME AUTHORITY
|
||||
</Text>
|
||||
<Text
|
||||
fw={500}
|
||||
size="xs"
|
||||
c="dimmed"
|
||||
style={{ letterSpacing: '0.05em', marginBottom: '8px' }}
|
||||
>
|
||||
የኢትዮጵያ ማሪታይም ባለስልጣን
|
||||
</Text>
|
||||
<Text
|
||||
fw={600}
|
||||
size="md"
|
||||
c={isDark ? 'gray.1' : 'navy.9'}
|
||||
style={{ lineHeight: 1.3 }}
|
||||
>
|
||||
{resolvedLabel}
|
||||
</Text>
|
||||
{subtitle && (
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{subtitle}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Animated Gold Shimmer Bar */}
|
||||
<Box
|
||||
style={{
|
||||
width: '120px',
|
||||
height: '3px',
|
||||
borderRadius: '2px',
|
||||
background: isDark ? 'rgba(255,255,255,0.1)' : 'rgba(15,44,89,0.1)',
|
||||
overflow: 'hidden',
|
||||
position: 'relative',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: '40%',
|
||||
background: 'linear-gradient(90deg, #078930, #FCD116, #2563EB)',
|
||||
borderRadius: '2px',
|
||||
animation: 'ema-shimmer 1.8s infinite ease-in-out',
|
||||
}}
|
||||
/>
|
||||
<style>{`
|
||||
@keyframes ema-shimmer {
|
||||
0% { left: -40%; }
|
||||
100% { left: 100%; }
|
||||
}
|
||||
`}</style>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Box>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
|
||||
40
libs/ui/src/lib/feedback/PdfPreviewModal.tsx
Normal file
40
libs/ui/src/lib/feedback/PdfPreviewModal.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Modal } from '@mantine/core';
|
||||
|
||||
interface PdfPreviewModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
url: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one place a PDF gets opened anywhere in the app. Never `window.open` /
|
||||
* `target="_blank"` a PDF directly — route it through this modal instead, so
|
||||
* the reviewer never loses their place to a new tab.
|
||||
*/
|
||||
export function PdfPreviewModal({
|
||||
opened,
|
||||
onClose,
|
||||
url,
|
||||
title = 'Document',
|
||||
}: PdfPreviewModalProps) {
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={title}
|
||||
size="80%"
|
||||
centered
|
||||
trapFocus
|
||||
returnFocus
|
||||
>
|
||||
{url && (
|
||||
<iframe
|
||||
src={url}
|
||||
title={title}
|
||||
style={{ width: '100%', height: '85vh', border: 'none' }}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -28,6 +28,7 @@ export const landingEn = {
|
||||
},
|
||||
|
||||
hero: {
|
||||
livePill: 'Official Digital Portal — FDRE',
|
||||
eyebrow: 'Federal Democratic Republic of Ethiopia',
|
||||
title: 'Ethiopian Maritime Authority',
|
||||
subtitle: 'Digital Maritime Services for Seafarers, Vessel Owners and Logistics Operators',
|
||||
@@ -41,6 +42,7 @@ export const landingEn = {
|
||||
},
|
||||
|
||||
about: {
|
||||
eyebrow: 'Institutional Framework',
|
||||
title: 'About EMA',
|
||||
visionLabel: 'Vision',
|
||||
vision:
|
||||
@@ -52,6 +54,32 @@ export const landingEn = {
|
||||
|
||||
cta: {
|
||||
getStarted: 'Get Started',
|
||||
verifyCertificate: 'Verify Certificate',
|
||||
exploreServices: 'Explore Services',
|
||||
},
|
||||
|
||||
stats: {
|
||||
seafarers: 'Registered Seafarers',
|
||||
seafarersVal: '10,000+',
|
||||
vessels: 'Registered Vessels',
|
||||
vesselsVal: '1,200+',
|
||||
efficiency: 'Digital Processing',
|
||||
efficiencyVal: '100%',
|
||||
availability: 'Portal Service Uptime',
|
||||
availabilityVal: '24/7',
|
||||
},
|
||||
|
||||
verification: {
|
||||
title: 'Public Verification & Tracking',
|
||||
subtitle: 'Verify the authenticity of any EMA-issued certificate, licence, or track an active application.',
|
||||
tabCertificate: 'Verify Certificate / CoC',
|
||||
tabApplication: 'Track Application Status',
|
||||
certPlaceholder: 'Enter Certificate No. (e.g. COC-2026-8891)',
|
||||
appPlaceholder: 'Enter Application Ref (e.g. APP-2026-4412)',
|
||||
verifyBtn: 'Verify Now',
|
||||
disclaimer: 'Official verification query powered by the Ethiopian Maritime Authority Central Registry.',
|
||||
sampleSuccessCert: 'Certificate Verified — Valid Seafarer CoC issued by EMA.',
|
||||
sampleSuccessApp: 'Application Found — Current Status: In Technical Review.',
|
||||
},
|
||||
|
||||
quickAccess: {
|
||||
@@ -68,93 +96,146 @@ export const landingEn = {
|
||||
},
|
||||
|
||||
services: {
|
||||
title: 'Maritime Services',
|
||||
subtitle: 'Every licence, certificate and registration EMA issues, in one digital system.',
|
||||
title: 'Comprehensive Maritime & Logistics Services',
|
||||
subtitle: 'Every statutory licence, seafarer certificate, vessel registration, and logistics permit issued by EMA in one unified platform.',
|
||||
items: {
|
||||
seafarerRegistration: {
|
||||
title: 'Seafarer Registration & Certification',
|
||||
title: 'Seafarer Certification & Seaman’s Book',
|
||||
description:
|
||||
"Register as a seafarer, apply for a Certificate of Competency or Proficiency, and manage your seaman's book online.",
|
||||
"Apply for Continuous Discharge Certificates (CDC/Seaman's Book), STCW Certificates of Competency (CoC), Proficiency (CoP), and foreign CoC endorsements.",
|
||||
},
|
||||
vesselRegistration: {
|
||||
title: 'Vessel Registration',
|
||||
title: 'Vessel Registration & Flag State Registry',
|
||||
description:
|
||||
'Register inland or sea-going vessels and manage ownership transfers with full document tracking.',
|
||||
'Inland waterway and sea-going ship registration, ownership transfers, tonnage measurement, safety survey inspection, and marine radio licensing.',
|
||||
},
|
||||
licensing: {
|
||||
title: 'Operator Licensing',
|
||||
title: 'Commercial Logistics & Operator Licensing',
|
||||
description:
|
||||
'Apply for freight forwarder, shipping agent, combined and multimodal transport operator licences.',
|
||||
'Licensing for Multimodal Transport Operators (MTO), Freight Forwarders, Shipping Agencies, Customs Clearance Brokers, and Terminal Operators.',
|
||||
},
|
||||
examinations: {
|
||||
title: 'Examinations',
|
||||
description: 'Sit competency examinations and track your results as part of certification.',
|
||||
title: 'Maritime Competency Examinations',
|
||||
description: 'Schedule computer-based competency exams, track examination results, and link qualified scores directly to certificate issuance.',
|
||||
},
|
||||
medical: {
|
||||
title: 'Maritime Medical Examination Verification',
|
||||
description: 'Approved Maritime Medical Practitioner portal for medical fitness certificates, sea-service health clearances, and STCW compliance.',
|
||||
},
|
||||
waivers: {
|
||||
title: 'Waivers',
|
||||
description: 'Apply for a maritime waiver where standard requirements do not apply.',
|
||||
title: 'Cargo Waiver & Cargo Tracking Notes (CTN)',
|
||||
description: 'Apply for cargo allocation clearances, maritime waivers, and cargo tracking notes across international trade corridors.',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
mandate: {
|
||||
title: 'Institutional Mandate & Regulatory Oversight',
|
||||
subtitle: 'Under the Ministry of Transport & Logistics (FDRE), EMA drives maritime safety, logistics efficiency, and international compliance.',
|
||||
items: {
|
||||
safety: {
|
||||
title: 'Maritime Safety & Security',
|
||||
description: 'Enforcing SOLAS, MARPOL, and ISPS standards for vessel safety, marine environment protection, and shipboard security.',
|
||||
},
|
||||
logistics: {
|
||||
title: 'Multimodal Logistics Development',
|
||||
description: 'Regulating Ethiopia’s dry ports, sea-land transit corridors, freight forwarding standards, and multimodal trade infrastructure.',
|
||||
},
|
||||
stcw: {
|
||||
title: 'STCW Training & Certification Standards',
|
||||
description: 'Accrediting maritime education institutions, administering national qualification frameworks, and issuing international seafarer credentials.',
|
||||
},
|
||||
flagState: {
|
||||
title: 'Flag State & Port State Inspection',
|
||||
description: 'Conducting flag state registration, seaworthiness inspections, vessel safety surveys, and port state control oversight.',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
roles: {
|
||||
title: 'Built for Every User',
|
||||
subtitle: 'One portal, tailored to what you do.',
|
||||
title: 'Built for Every User & Maritime Entity',
|
||||
subtitle: 'One digital portal tailored to your operational role in Ethiopia’s maritime sector.',
|
||||
seafarers: {
|
||||
title: 'Seafarers',
|
||||
description: 'Register, certify, and manage your sea service records.',
|
||||
title: 'Seafarers & Maritime Officers',
|
||||
description: 'Register, apply for CDC/CoC certificates, schedule STCW exams, and track sea service records.',
|
||||
},
|
||||
vesselOwners: {
|
||||
title: 'Vessel Owners',
|
||||
description: 'Register vessels and manage ownership and licensing.',
|
||||
title: 'Vessel Owners & Operators',
|
||||
description: 'Register commercial & inland vessels, request tonnage surveys, and manage fleet licenses.',
|
||||
},
|
||||
agents: {
|
||||
title: 'Agents & Logistics Operators',
|
||||
description: 'Apply for and renew operator licences for freight and shipping.',
|
||||
title: 'Logistics Operators & Shipping Agencies',
|
||||
description: 'Apply for MTO, freight forwarding, customs clearance, and shipping agent licenses.',
|
||||
},
|
||||
reviewers: {
|
||||
title: 'EMA Reviewers',
|
||||
description: 'Review, verify and approve applications from the backoffice.',
|
||||
title: 'EMA Inspectors & Regulatory Reviewers',
|
||||
description: 'Review applications, conduct technical audits, issue digital approvals, and verify credentials.',
|
||||
},
|
||||
},
|
||||
|
||||
howItWorks: {
|
||||
title: 'How It Works',
|
||||
subtitle: 'From application to approval, in five steps.',
|
||||
subtitle: 'From digital registration to official certificate issuance in five streamlined steps.',
|
||||
steps: {
|
||||
selectRole: 'Select role',
|
||||
createAccount: 'Create account',
|
||||
submitApplication: 'Submit application',
|
||||
trackStatus: 'Track status',
|
||||
receiveApproval: 'Receive approval',
|
||||
createAccount: {
|
||||
title: 'Create Account & Role',
|
||||
description: 'Register with phone/email, verify via OTP, and select your operational role (Seafarer, Owner, Agent).',
|
||||
},
|
||||
submitApplication: {
|
||||
title: 'Submit Digital Application',
|
||||
description: 'Select your service (Seaman’s Book, CoC, Vessel Registration, MTO License) and upload required documents.',
|
||||
},
|
||||
fulfillRequirements: {
|
||||
title: 'Medical & Examinations',
|
||||
description: 'Complete approved maritime medical fitness checks and sit computer-based competency exams if required.',
|
||||
},
|
||||
payFees: {
|
||||
title: 'Pay Statutory Fees',
|
||||
description: 'Pay official processing fees securely via integrated e-payment channels (Telebirr, CBE Birr, e-Banking).',
|
||||
},
|
||||
receiveCertificate: {
|
||||
title: 'Receive Digital Certificate',
|
||||
description: 'Track real-time progress as EMA reviews your file, then download your QR-verifiable digital certificate or licence.',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
system: {
|
||||
title: 'A Modern Digital System',
|
||||
subtitle: 'Built to make maritime services faster, safer and accessible from anywhere.',
|
||||
title: 'Advanced Digital Platform Capabilities',
|
||||
subtitle: 'State-of-the-art infrastructure ensuring speed, security, transparency, and international compliance.',
|
||||
items: {
|
||||
secure: {
|
||||
title: 'Secure & Verified',
|
||||
description: 'Every application and certificate is digitally recorded and verifiable.',
|
||||
title: 'Digital Document Vault & QR Verification',
|
||||
description: 'All issued certificates carry encrypted QR codes and digital signatures for instant global verification by port authorities.',
|
||||
},
|
||||
bilingual: {
|
||||
title: 'Bilingual by Design',
|
||||
description: 'Use the system fully in English or Amharic — switch anytime.',
|
||||
title: 'Full Amharic & English Dual Compliance',
|
||||
description: 'Native Ethiopic (አማርኛ) and English localization providing seamless access for national seafarers and global shipping lines.',
|
||||
},
|
||||
tracking: {
|
||||
title: 'Real-Time Tracking',
|
||||
description: 'Follow your application from submission to approval, step by step.',
|
||||
title: 'End-to-End Real-Time Audit Trail',
|
||||
description: 'Track your application transparently through document verification, technical audit, fee payment, and executive sign-off.',
|
||||
},
|
||||
singleAccount: {
|
||||
title: 'One Account, Every Service',
|
||||
description: 'Register once and access all EMA licensing and certification services.',
|
||||
title: 'Single Sign-On (SSO) Portal',
|
||||
description: 'Access seafarer records, vessel registries, and commercial licenses under a unified secure digital identity.',
|
||||
},
|
||||
payments: {
|
||||
title: 'Integrated Statutory e-Payment Gateway',
|
||||
description: 'Pay statutory licensing and certification fees via Telebirr, CBE Birr, and electronic banking with automated digital receipts.',
|
||||
},
|
||||
framework: {
|
||||
title: 'STCW & Multimodal Regulatory Framework',
|
||||
description: 'Architected strictly according to IMO STCW 1978/2010 Manila Amendments, SOLAS, MARPOL, and national Proclamations.',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
faq: {
|
||||
eyebrow: 'Got Questions?',
|
||||
title: 'Frequently Asked Questions',
|
||||
supportPrompt: 'Can’t find the answer you’re looking for? Reach out directly to our support team.',
|
||||
contactSupport: 'Contact Support Team',
|
||||
items: {
|
||||
whatIsPortal: {
|
||||
question: 'What is the EMA portal?',
|
||||
@@ -180,16 +261,39 @@ export const landingEn = {
|
||||
},
|
||||
|
||||
contact: {
|
||||
title: 'Contact EMA',
|
||||
subtitle: 'Reach the Ethiopian Maritime Authority head office.',
|
||||
addressLabel: 'Address',
|
||||
eyebrow: 'Get In Touch',
|
||||
title: 'Contact EMA Headquarters',
|
||||
subtitle: 'Reach the Ethiopian Maritime Authority head office in Addis Ababa or send a direct inquiry.',
|
||||
addressLabel: 'Head Office Address',
|
||||
address: 'Meskel Square, behind Hyatt Regency Hotel, Sunshine Building No. 4, Addis Ababa, Ethiopia',
|
||||
phoneLabel: 'Phone',
|
||||
websiteLabel: 'Website',
|
||||
phoneLabel: 'Telephone Line',
|
||||
websiteLabel: 'Official Portal',
|
||||
inquiryTitle: 'Send a Direct Inquiry',
|
||||
inquirySubtitle: 'Have a specific question regarding seafarer certification, vessel registration or licensing?',
|
||||
nameLabel: 'Full Name',
|
||||
namePlaceholder: 'e.g. Abebe Bikila',
|
||||
emailLabel: 'Email Address',
|
||||
emailPlaceholder: 'e.g. abebe@example.com',
|
||||
topicLabel: 'Inquiry Topic',
|
||||
topicPlaceholder: 'Select topic (Seafarer, Vessel, Licensing...)',
|
||||
messageLabel: 'Your Message',
|
||||
messagePlaceholder: 'Describe your query or assistance needed...',
|
||||
sendBtn: 'Send Inquiry',
|
||||
successMsg: 'Thank you! Your message has been successfully routed to EMA Customer Support.',
|
||||
getDirections: 'Get Directions',
|
||||
callOffice: 'Call HQ Office',
|
||||
},
|
||||
|
||||
footer: {
|
||||
rights: 'All rights reserved.',
|
||||
tagline: 'Empowering Ethiopia’s Maritime & Logistics Infrastructure.',
|
||||
quickLinks: 'Quick Links',
|
||||
servicesHeading: 'Core Services',
|
||||
contactHeading: 'Contact & Support',
|
||||
hoursLabel: 'Working Hours',
|
||||
hoursValue: 'Mon – Fri: 8:30 AM – 5:30 PM (EAT)',
|
||||
emergencyLabel: 'Emergency Maritime Line',
|
||||
emergencyValue: '+251 11 551 0000',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -215,6 +319,7 @@ export const landingAm: LandingCopy = {
|
||||
},
|
||||
|
||||
hero: {
|
||||
livePill: 'ይፋዊ ዲጂታል ፖርታል — ኢፌዴሪ',
|
||||
eyebrow: 'የኢትዮጵያ ፌዴራላዊ ዲሞክራሲያዊ ሪፐብሊክ',
|
||||
title: 'የኢትዮጵያ ማሪታይም ባለስልጣን',
|
||||
subtitle: 'ለመርከበኞች፣ ለመርከብ ባለቤቶች እና ለሎጂስቲክስ ኦፕሬተሮች የተዘጋጁ ዲጂታል የባህር አገልግሎቶች',
|
||||
@@ -228,6 +333,7 @@ export const landingAm: LandingCopy = {
|
||||
},
|
||||
|
||||
about: {
|
||||
eyebrow: 'የተቋማዊ ማዕቀፍ',
|
||||
title: 'ስለ ባለስልጣኑ',
|
||||
visionLabel: 'ራዕይ',
|
||||
vision:
|
||||
@@ -239,6 +345,32 @@ export const landingAm: LandingCopy = {
|
||||
|
||||
cta: {
|
||||
getStarted: 'ይጀምሩ',
|
||||
verifyCertificate: 'ምስክር ወረቀት ያረጋግጡ',
|
||||
exploreServices: 'አገልግሎቶችን ይመልከቱ',
|
||||
},
|
||||
|
||||
stats: {
|
||||
seafarers: 'የተመዘገቡ መርከበኞች',
|
||||
seafarersVal: '10,000+',
|
||||
vessels: 'የተመዘገቡ መርከቦች',
|
||||
vesselsVal: '1,200+',
|
||||
efficiency: 'ዲጂታል አሰራር',
|
||||
efficiencyVal: '100%',
|
||||
availability: 'የፖርታል አገልግሎት ዝግጁነት',
|
||||
availabilityVal: '24/7',
|
||||
},
|
||||
|
||||
verification: {
|
||||
title: 'የህዝብ ማረጋገጫና ክትትል',
|
||||
subtitle: 'በኢትዮጵያ ማሪታይም ባለስልጣን የተሰጠ ማንኛውንም ምስክር ወረቀት፣ ፈቃድ ወይም የማመልከቻ ሁኔታ ያረጋግጡ።',
|
||||
tabCertificate: 'የምስክር ወረቀት / CoC ማረጋገጫ',
|
||||
tabApplication: 'የማመልከቻ ሁኔታ',
|
||||
certPlaceholder: 'የምስክር ወረቀት ቁጥር ያስገቡ (ምሳሌ፡ COC-2026-8891)',
|
||||
appPlaceholder: 'የማመልከቻ መለያ ያስገቡ (ምሳሌ፡ APP-2026-4412)',
|
||||
verifyBtn: 'አሁን ያረጋግጡ',
|
||||
disclaimer: 'በኢትዮጵያ ማሪታይም ባለስልጣን ማዕከላዊ መዝገብ የተደገፈ ይፋዊ የማረጋገጫ ስርዓት።',
|
||||
sampleSuccessCert: 'ምስክር ወረቀቱ ተረጋገጠ — በEMA የተሰጠ ህጋዊ የመርከበኛ CoC።',
|
||||
sampleSuccessApp: 'ማመልከቻው ተገኝቷል — ሁኔታ፡ በቴክኒክ ግምገማ ላይ።',
|
||||
},
|
||||
|
||||
quickAccess: {
|
||||
@@ -255,91 +387,146 @@ export const landingAm: LandingCopy = {
|
||||
},
|
||||
|
||||
services: {
|
||||
title: 'የባህር አገልግሎቶች',
|
||||
subtitle: 'ባለስልጣኑ የሚሰጣቸው ሁሉም ፈቃድ፣ ምስክር ወረቀትና ምዝገባ በአንድ ዲጂታል ስርዓት ውስጥ።',
|
||||
title: 'አጠቃላይ የባህር እና የሎጂስቲክስ አገልግሎቶች',
|
||||
subtitle: 'በኢትዮጵያ ማሪታይም ባለስልጣን የሚሰጡ ሁሉም ህጋዊ ፈቃዶች፣ የመርከበኛ ምስክር ወረቀቶች፣ የመርከብ ምዝገባዎች እና የሎጂስቲክስ ፈቃዶች በአንድ ዲጂታል ፖርታል::',
|
||||
items: {
|
||||
seafarerRegistration: {
|
||||
title: 'የመርከበኞች ምዝገባና ማረጋገጫ',
|
||||
title: 'የመርከበኞች ማረጋገጫ እና የመርከበኛ ደብተር',
|
||||
description:
|
||||
'እንደ መርከበኛ ይመዝገቡ፣ ለብቃት ወይም ችሎታ ማረጋገጫ ምስክር ወረቀት ያመልክቱ፣ እንዲሁም የመርከበኛ መዝገብ መጽሐፍዎን በመስመር ላይ ያስተዳድሩ።',
|
||||
'የመርከበኛ መታወቂያ ደብተር (CDC/Seaman’s Book)፣ የSTCW የብቃት ምስክር ወረቀቶች (CoC/CoP) እና የውጭ CoC ማረጋገጫዎችን ያመልክቱ።',
|
||||
},
|
||||
vesselRegistration: {
|
||||
title: 'የመርከብ ምዝገባ',
|
||||
description: 'የውስጥ ውሃ ወይም የባህር ማዶ መርከቦችን ይመዝገቡ፣ የባለቤትነት ዝውውርንም ሙሉ በሙሉ በሰነድ ክትትል ያስተዳድሩ።',
|
||||
title: 'የመርከብ ምዝገባ እና የባንዲራ መዝገብ',
|
||||
description:
|
||||
'የውስጥ ውሃ እና የባህር ማዶ መርከቦች ምዝገባ፣ የባለቤትነት ዝውውር፣ የቶን ልኬት፣ የደህንነት ፍተሻ እና የመርከብ ሬዲዮ ፈቃድ።',
|
||||
},
|
||||
licensing: {
|
||||
title: 'የኦፕሬተር ፈቃድ',
|
||||
description: 'ለጭነት አስተላላፊ፣ ለመርከብ ወኪል፣ ለተቀናጀ እና ለብዙ-ዘዴ ትራንስፖርት ኦፕሬተር ፈቃድ ያመልክቱ።',
|
||||
title: 'የንግድ ሎጂስቲክስ እና የኦፕሬተር ፈቃድ',
|
||||
description:
|
||||
'ለብዙ-ዘዴ ትራንስፖርት ኦፕሬተሮች (MTO)፣ ጭነት አስተላላፊዎች፣ የመርከብ ወኪሎች፣ የጉምሩክ አስተላላፊዎች እና ተርሚናል ኦፕሬተሮች ፈቃድ።',
|
||||
},
|
||||
examinations: {
|
||||
title: 'ፈተናዎች',
|
||||
description: 'የብቃት ፈተናዎችን ይውሰዱ እንዲሁም ውጤቶችዎን እንደ ማረጋገጫ ሂደት አካል ይከታተሉ።',
|
||||
title: 'የባህር ላይ የብቃት ፈተናዎች',
|
||||
description: 'በኮምፒውተር የተደገፉ የብቃት ፈተናዎችን መርሃ ግብር ይያዙ፣ ውጤቶችን ይከታተሉ፣ እንዲሁም ውጤቶችን ከምስክር ወረቀት ጋር ያያይዙ።',
|
||||
},
|
||||
medical: {
|
||||
title: 'የባህር ህክምና ፍተሻ ማረጋገጫ',
|
||||
description: 'በተፈቀደላቸው የባህር ህክምና ባለሙያዎች የተሰጡ የጤና ብቃት ማረጋገጫዎች እና የSTCW ህክምና ማረጋገጫዎች ፖርታል።',
|
||||
},
|
||||
waivers: {
|
||||
title: 'ነፃ ፈቃዶች',
|
||||
description: 'መደበኛ መስፈርቶች በማይሟሉበት ጊዜ ለባህር ትራንስፖርት ነፃ ፈቃድ ያመልክቱ።',
|
||||
title: 'የጭነት ነፃ ፈቃድ እና የጭነት ክትትል (CTN)',
|
||||
description: 'በአለም አቀፍ የንግድ መስመሮች ላይ የጭነት ድልድል ነፃ ፈቃድ እና የጭነት ክትትል ሰነዶችን (CTN) ያመልክቱ።',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
mandate: {
|
||||
title: 'የተቋሙ ሃላፊነት እና ህጋዊ ቁጥጥር',
|
||||
subtitle: 'በኢፌዴሪ በትራንስፖርት እና ሎጂስቲክስ ሚኒስቴር ስር የኢትዮጵያን የባህር ደህንነት፣ የሎጂስቲክስ ቅልጥፍና እና አለም አቀፍ ተገዥነት ማረጋገጥ።',
|
||||
items: {
|
||||
safety: {
|
||||
title: 'የባህር ደህንነት እና ጸጥታ',
|
||||
description: 'የSOLAS፣ MARPOL እና ISPS አለም አቀፍ መስፈርቶችን በመተግበር የመርከቦችን እና የባህር አካባቢን ደህንነት መጠበቅ።',
|
||||
},
|
||||
logistics: {
|
||||
title: 'የብዙ-ዘዴ ሎጂስቲክስ ልማት',
|
||||
description: 'የኢትዮጵያን ደረቅ ወደቦች፣ የባህር-የብስ ትራንዚት መስመሮች፣ የጭነት ማስተላለፍ መስፈርቶች እና የሎጂስቲክስ መሠረተ ልማቶችን መቆጣጠር።',
|
||||
},
|
||||
stcw: {
|
||||
title: 'የSTCW ስልጠና እና የብቃት መስፈርቶች',
|
||||
description: 'የባህር ስልጠና ተቋማትን እውቅና መስጠት፣ ብሔራዊ የብቃት ማዕቀፎችን ማስተዳደር እና አለም አቀፍ የመርከበኞች ማረጋገጫ መስጠት።',
|
||||
},
|
||||
flagState: {
|
||||
title: 'የባንዲራ እና የወደብ ግዛት ፍተሻ',
|
||||
description: 'የመርከብ ምዝገባ፣ የባህር ብቃት ፍተሻ፣ የደህንነት ሰነዶች ማረጋገጥ እና የወደብ ግዛት ቁጥጥር ስራዎችን ማከናወን።',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
roles: {
|
||||
title: 'ለሁሉም ተጠቃሚ የተዘጋጀ',
|
||||
subtitle: 'አንድ ፖርታል፣ ለሚናዎ የተዘጋጀ።',
|
||||
subtitle: 'በኢትዮጵያ የባህር ዘርፍ ውስጥ ለሚሰሩት ሚና ተስማሚ የሆነ ዲጂታል ፖርታል።',
|
||||
seafarers: {
|
||||
title: 'መርከበኞች',
|
||||
description: 'ይመዝገቡ፣ ይረጋገጡ እንዲሁም የባህር አገልግሎት መዝገብዎን ያስተዳድሩ።',
|
||||
title: 'መርከበኞች እና የባህር መኮንኖች',
|
||||
description: 'ይመዝገቡ፣ ለCDC/CoC ምስክር ወረቀቶች ያመልክቱ፣ የSTCW ፈተናዎችን ይያዙ፣ እንዲሁም የባህር አገልግሎት መዝገብዎን ያስተዳድሩ።',
|
||||
},
|
||||
vesselOwners: {
|
||||
title: 'የመርከብ ባለቤቶች',
|
||||
description: 'መርከብ ይመዝገቡ እንዲሁም ባለቤትነትና ፈቃድ ያስተዳድሩ።',
|
||||
title: 'የመርከብ ባለቤቶች እና ኦፕሬተሮች',
|
||||
description: 'የንግድ እና የውስጥ ውሃ መርከቦችን ይመዝገቡ፣ የቶን ልኬት ጥያቄ ያቅርቡ፣ እንዲሁም የመርከብ ፈቃዶችን ያስተዳድሩ።',
|
||||
},
|
||||
agents: {
|
||||
title: 'ወኪሎችና ሎጂስቲክስ ኦፕሬተሮች',
|
||||
description: 'ለጭነትና ለመላኪያ ፈቃድ ያመልክቱ እንዲሁም ያድሱ።',
|
||||
title: 'የሎጂስቲክስ ኦፕሬተሮች እና የመርከብ ወኪሎች',
|
||||
description: 'ለMTO፣ የጭነት ማስተላለፍ፣ የጉምሩክ አስተላላፊነት እና የመርከብ ወኪል ፈቃዶች ያመልክቱ።',
|
||||
},
|
||||
reviewers: {
|
||||
title: 'የባለስልጣኑ ገምጋሚዎች',
|
||||
description: 'ማመልከቻዎችን ይገመግሙ፣ ያረጋግጡ እንዲሁም ይፍቀዱ።',
|
||||
title: 'የባለስልጣኑ ተቆጣጣሪዎች እና ገምጋሚዎች',
|
||||
description: 'ማመልከቻዎችን ይገመግሙ፣ ቴክኒካዊ ኦዲት ያድርጉ፣ ዲጂታል ማጽደቂያዎችን ይስጡ፣ እንዲሁም ሰነዶችን ያረጋግጡ።',
|
||||
},
|
||||
},
|
||||
|
||||
howItWorks: {
|
||||
title: 'እንዴት እንደሚሰራ',
|
||||
subtitle: 'ከማመልከቻ እስከ ፈቃድ፣ በአምስት ደረጃዎች።',
|
||||
title: 'አገልግሎቱ እንዴት እንደሚሰጥ',
|
||||
subtitle: 'ከዲጂታል ምዝገባ እስከ ይፋዊ ምስክር ወረቀት አሰጣጥ፣ በአምስት ግልጽ ደረጃዎች።',
|
||||
steps: {
|
||||
selectRole: 'ሚና ይምረጡ',
|
||||
createAccount: 'መለያ ይፍጠሩ',
|
||||
submitApplication: 'ማመልከቻ ያስገቡ',
|
||||
trackStatus: 'ሁኔታ ይከታተሉ',
|
||||
receiveApproval: 'ፍቃድ ይቀበሉ',
|
||||
createAccount: {
|
||||
title: 'መለያ እና ሚና ይምረጡ',
|
||||
description: 'በስልክ/ኢሜይል ይመዝገቡ፣ በኦቲፒ ያረጋግጡ፣ እና ሚናዎን (መርከበኛ፣ የመርከብ ባለቤት፣ ወኪል) ይምረጡ።',
|
||||
},
|
||||
submitApplication: {
|
||||
title: 'ማመልከቻ ያስገቡ',
|
||||
description: 'የሚፈልጉትን አገልግሎት (የመርከበኛ ደብተር፣ CoC፣ የመርከብ ምዝገባ፣ MTO ፈቃድ) መርጠው ሰነዶችን ያያይዙ።',
|
||||
},
|
||||
fulfillRequirements: {
|
||||
title: 'ህክምና እና ፈተና',
|
||||
description: 'የተፈቀደላቸውን የባህር ህክምና ፍተሻዎች ያጠናቅቁ እና የሚያስፈልግ ከሆነ የብቃት ፈተና ይውሰዱ።',
|
||||
},
|
||||
payFees: {
|
||||
title: 'ህጋዊ ክፍያ ይክፈሉ',
|
||||
description: 'የአገልግሎት ክፍያዎችን በቴሌብር፣ በCBE Birr ወይም በባንክ በዲጂታል መንገድ ደህንነቱ በተጠበቀ ሁኔታ ይክፈሉ።',
|
||||
},
|
||||
receiveCertificate: {
|
||||
title: 'ዲጂታል ምስክር ወረቀት ይቀበሉ',
|
||||
description: 'የማመልከቻዎን ሁኔታ ይከታተሉ፣ ሲጸድቅም በQR ኮድ የተረጋገጠውን ዲጂታል ሰነድዎን ያውርዱ።',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
system: {
|
||||
title: 'ዘመናዊ ዲጂታል ስርዓት',
|
||||
subtitle: 'የባህር አገልግሎቶችን ፈጣን፣ ደህንነቱ የተጠበቀና ከየትኛውም ቦታ ተደራሽ ለማድረግ የተዘጋጀ።',
|
||||
title: 'የላቀ የዲጂታል ፖርታል አቅሞች',
|
||||
subtitle: 'ፈጣንነትን፣ ደህንነትን፣ ግልጽነትን እና አለም አቀፍ ተገዥነትን የሚያረጋግጥ ዘመናዊ መሠረተ ልማት።',
|
||||
items: {
|
||||
secure: {
|
||||
title: 'ደህንነቱ የተጠበቀ እና የተረጋገጠ',
|
||||
description: 'እያንዳንዱ ማመልከቻና ምስክር ወረቀት በዲጂታል መልኩ ተመዝግቦ ሊረጋገጥ የሚችል ነው።',
|
||||
title: 'የዲጂታል ሰነድ ማከማቻ እና የQR ማረጋገጫ',
|
||||
description: 'ሁሉም የተሰጡ ምስክር ወረቀቶች በምስጠራ የተጠበቀ QR ኮድ እና ዲጂታል ፊርማ ያላቸው በመሆናቸው በየትኛውም የወደብ ባለስልጣናት ወዲያውኑ ይረጋገጣሉ።',
|
||||
},
|
||||
bilingual: {
|
||||
title: 'በሁለት ቋንቋ የተዘጋጀ',
|
||||
description: 'ስርዓቱን ሙሉ በሙሉ በአማርኛ ወይም በእንግሊዝኛ ይጠቀሙ — በማንኛውም ጊዜ ይቀይሩ።',
|
||||
title: 'ሙሉ የአማርኛ እና የእንግሊዝኛ ድጋፍ',
|
||||
description: 'ለሀገር ውስጥ መርከበኞች እና ለአለም አቀፍ የመርከብ ኩባንያዎች ምቹ የሆነ ሙሉ በሙሉ በአማርኛ እና በእንግሊዝኛ የተዘጋጀ ስርዓት።',
|
||||
},
|
||||
tracking: {
|
||||
title: 'የቀጥታ ሁኔታ ክትትል',
|
||||
description: 'ማመልከቻዎን ከማስገባት እስከ ማጽደቅ ደረጃ በደረጃ ይከታተሉ።',
|
||||
title: 'የቀጥታ ሁኔታ እና ኦዲት ክትትል',
|
||||
description: 'ማመልከቻዎን ከሰነድ ማረጋገጫ፣ ከቴክኒክ ኦዲት፣ ከክፍያ እስከ መሪዎች ማጽደቅ ድረስ በግልጽ ይከታተሉ።',
|
||||
},
|
||||
singleAccount: {
|
||||
title: 'አንድ መለያ፣ ሁሉም አገልግሎት',
|
||||
description: 'አንድ ጊዜ ይመዝገቡና ሁሉንም የEMA ፈቃድና የምስክር ወረቀት አገልግሎቶች ይድረሱ።',
|
||||
title: 'አንድ መለያ (SSO) አገልግሎት',
|
||||
description: 'የመርከበኛ መዝገቦችን፣ የመርከብ መዝገቦችን እና የንግድ ፈቃዶችን በአንድ ደህንነቱ በተጠበቀ ዲጂታል መለያ ስር ያግኙ።',
|
||||
},
|
||||
payments: {
|
||||
title: 'የተቀናጀ የዲጂታል ክፍያ ስርዓት',
|
||||
description: 'የመንግስት የፈቃድ እና የምስክር ወረቀት ክፍያዎችን በቴሌብር፣ በCBE Birr እና በባንክ በዲጂታል ደረሰኝ ይክፈሉ።',
|
||||
},
|
||||
framework: {
|
||||
title: 'የSTCW እና የባህር ህግ ማዕቀፍ ተገዥነት',
|
||||
description: 'በአለም አቀፍ የIMO STCW 1978/2010 Manila ስምምነቶች፣ SOLAS፣ MARPOL እና በሀገራዊ አዋጆች መሰረት የተገነባ።',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
faq: {
|
||||
eyebrow: 'ጥያቄዎች አሉዎት?',
|
||||
title: 'ተደጋጋሚ ጥያቄዎች',
|
||||
supportPrompt: 'የሚፈልጉትን መልስ አላገኙም? ቀጥታ የደንበኞች ድጋፍ ቡድናችንን ያግኙ።',
|
||||
contactSupport: 'ድጋፍ ቡድንን ያግኙ',
|
||||
items: {
|
||||
whatIsPortal: {
|
||||
question: 'EMA ፖርታል ምንድን ነው?',
|
||||
@@ -363,15 +550,38 @@ export const landingAm: LandingCopy = {
|
||||
},
|
||||
|
||||
contact: {
|
||||
title: 'ባለስልጣኑን ያግኙ',
|
||||
subtitle: 'የኢትዮጵያ ማሪታይም ባለስልጣን ዋና መሥሪያ ቤትን ያግኙ።',
|
||||
addressLabel: 'አድራሻ',
|
||||
eyebrow: 'እኛን ያግኙ',
|
||||
title: 'የኢትዮጵያ ማሪታይም ባለስልጣን ዋና መሥሪያ ቤት',
|
||||
subtitle: 'በአዲስ አበባ የሚገኘውን የኢትዮጵያ ማሪታይም ባለስልጣን ዋና መሥሪያ ቤት ያግኙ ወይም ቀጥታ ጥያቄ ይላኩ።',
|
||||
addressLabel: 'የዋና መሥሪያ ቤት አድራሻ',
|
||||
address: 'መስቀል አደባባይ፣ ከHyatt Regency ሆቴል ጀርባ፣ Sunshine ህንፃ ቁጥር 4፣ አዲስ አበባ፣ ኢትዮጵያ',
|
||||
phoneLabel: 'ስልክ',
|
||||
websiteLabel: 'ድረ ገጽ',
|
||||
phoneLabel: 'የስልክ መስመር',
|
||||
websiteLabel: 'ይፋዊ ድረ ገጽ',
|
||||
inquiryTitle: 'ቀጥታ ጥያቄ ይላኩ',
|
||||
inquirySubtitle: 'ስለ መርከበኛ ማረጋገጫ፣ የመርከብ ምዝገባ ወይም ፈቃዶች ጥያቄዎች አሉዎት?',
|
||||
nameLabel: 'ሙሉ ስም',
|
||||
namePlaceholder: 'ምሳሌ፡ አበበ ቢቂላ',
|
||||
emailLabel: 'ኢሜይል አድራሻ',
|
||||
emailPlaceholder: 'ምሳሌ፡ abebe@example.com',
|
||||
topicLabel: 'የጥያቄው ርዕስ',
|
||||
topicPlaceholder: 'ርዕስ ይምረጡ (መርከበኛ፣ መርከብ፣ ፈቃድ...)',
|
||||
messageLabel: 'መልዕክትዎ',
|
||||
messagePlaceholder: 'ጥያቄዎን ወይም የሚያስፈልግዎትን ድጋፍ ያብራሩ...',
|
||||
sendBtn: 'መልዕክት ላክ',
|
||||
successMsg: 'እናመሰግናለን! መልዕክትዎ ለEMA ደንበኞች ድጋፍ ተልኳል።',
|
||||
getDirections: 'አቅጣጫዎችን ያግኙ',
|
||||
callOffice: 'ወደ መሥሪያ ቤት ይደውሉ',
|
||||
},
|
||||
|
||||
footer: {
|
||||
rights: 'ሁሉም መብቶች የተጠበቁ ናቸው።',
|
||||
tagline: 'የኢትዮጵያን የባህር እና የሎጂስቲክስ መሠረተ ልማት ማሳደግ።',
|
||||
quickLinks: 'ፈጣን ማያያዣዎች',
|
||||
servicesHeading: 'ዋና አገልግሎቶች',
|
||||
contactHeading: 'ግንኙነትና ድጋፍ',
|
||||
hoursLabel: 'የስራ ሰዓት',
|
||||
hoursValue: 'ሰኞ – አርብ፡ ከጠዋቱ 2:30 – ከሰዓት 11:30 (የምስራቅ አፍሪካ ሰዓት)',
|
||||
emergencyLabel: 'የአደጋ ጊዜ የባህር መስመር',
|
||||
emergencyValue: '+251 11 551 0000',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -3,17 +3,15 @@
|
||||
.ema-hover-lift, portal's --ema-surface-*) is available here, so this file
|
||||
is self-contained. */
|
||||
|
||||
/* `scroll-behavior` only affects the element that actually scrolls — for a
|
||||
full page that's `html`, not this div, so it has to live here. Scoped with
|
||||
:has() so it only applies while the landing page is mounted. */
|
||||
html,
|
||||
body,
|
||||
html:has(.ema-landing) {
|
||||
scroll-behavior: smooth;
|
||||
scroll-behavior: smooth !important;
|
||||
}
|
||||
|
||||
.ema-landing section[id] {
|
||||
/* Offsets anchor jumps by the sticky header height so the heading isn't
|
||||
hidden underneath it. Keep in sync with the header's fixed height. */
|
||||
scroll-margin-top: 72px;
|
||||
.ema-landing section[id],
|
||||
.ema-landing div[id] {
|
||||
scroll-margin-top: 80px;
|
||||
}
|
||||
|
||||
.ema-landing .ema-landing-fade {
|
||||
@@ -33,12 +31,168 @@ html:has(.ema-landing) {
|
||||
|
||||
.ema-landing .ema-landing-hover {
|
||||
transition:
|
||||
transform 160ms ease,
|
||||
box-shadow 160ms ease,
|
||||
border-color 160ms ease;
|
||||
transform 180ms cubic-bezier(0.2, 0, 0, 1),
|
||||
box-shadow 180ms cubic-bezier(0.2, 0, 0, 1),
|
||||
border-color 180ms ease;
|
||||
}
|
||||
.ema-landing .ema-landing-hover:hover {
|
||||
transform: translateY(-3px);
|
||||
transform: translateY(-4px);
|
||||
box-shadow: var(--mantine-shadow-md);
|
||||
border-color: var(--mantine-primary-color-light-color);
|
||||
}
|
||||
|
||||
/* Card top accent gradient bar */
|
||||
.ema-landing .ema-landing-card-accent {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.ema-landing .ema-landing-card-accent::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, #3160b7 0%, #1fc29d 100%);
|
||||
opacity: 0.85;
|
||||
transition: opacity 180ms ease;
|
||||
}
|
||||
.ema-landing .ema-landing-card-accent:hover::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Stats counter card background glassmorphism */
|
||||
.ema-landing .ema-stats-banner {
|
||||
background: linear-gradient(135deg, rgba(49, 96, 183, 0.04) 0%, rgba(31, 194, 157, 0.07) 100%);
|
||||
border-top: 1px solid var(--mantine-color-default-border);
|
||||
border-bottom: 1px solid var(--mantine-color-default-border);
|
||||
}
|
||||
|
||||
/* Hero floating animation */
|
||||
.ema-hero-pulse {
|
||||
animation: ema-hero-float 8s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes ema-hero-float {
|
||||
0% {
|
||||
transform: translateY(0px) scale(1);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(-12px) scale(1.03);
|
||||
}
|
||||
}
|
||||
|
||||
/* Verification tab search box focus ring */
|
||||
.ema-verification-box {
|
||||
box-shadow: 0 12px 32px rgba(15, 23, 42, 0.08);
|
||||
transition: box-shadow 200ms ease;
|
||||
}
|
||||
.ema-verification-box:focus-within {
|
||||
box-shadow: 0 16px 40px rgba(49, 96, 183, 0.14);
|
||||
}
|
||||
|
||||
/* Gradient text helper */
|
||||
.ema-landing .ema-text-gradient {
|
||||
background: linear-gradient(135deg, #2453a2 0%, #0aab89 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
/* Hero live status indicator pulse dot */
|
||||
.ema-landing .ema-live-dot {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background-color: #22c55e;
|
||||
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.7);
|
||||
animation: ema-dot-pulse 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes ema-dot-pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.7);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px rgba(34, 197, 94, 0);
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Vision & Mission card left accent borders */
|
||||
.ema-landing .ema-vision-card {
|
||||
border-left: 4px solid #3160b7 !important;
|
||||
}
|
||||
.ema-landing .ema-mission-card {
|
||||
border-left: 4px solid #1fc29d !important;
|
||||
}
|
||||
|
||||
/* Card hover arrow animation */
|
||||
.ema-landing .ema-landing-hover .ema-card-arrow {
|
||||
transition: transform 180ms ease, color 180ms ease;
|
||||
}
|
||||
.ema-landing .ema-landing-hover:hover .ema-card-arrow {
|
||||
transform: translateX(4px);
|
||||
color: var(--mantine-primary-color-filled);
|
||||
}
|
||||
|
||||
/* Footer top gradient accent bar */
|
||||
.ema-landing footer {
|
||||
position: relative;
|
||||
}
|
||||
.ema-landing footer::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, #3160b7 0%, #1fc29d 50%, #3160b7 100%);
|
||||
}
|
||||
|
||||
/* FAQ custom item styling */
|
||||
.ema-landing .ema-faq-accordion .mantine-Accordion-item {
|
||||
border: 1px solid var(--mantine-color-default-border);
|
||||
border-radius: var(--mantine-radius-lg);
|
||||
margin-bottom: 14px;
|
||||
background-color: var(--mantine-color-body);
|
||||
transition: box-shadow 180ms ease, border-color 180ms ease;
|
||||
}
|
||||
.ema-landing .ema-faq-accordion .mantine-Accordion-item[data-active] {
|
||||
border-color: var(--mantine-primary-color-light-color);
|
||||
box-shadow: 0 8px 24px rgba(49, 96, 183, 0.08);
|
||||
}
|
||||
.ema-landing .ema-faq-accordion .mantine-Accordion-control {
|
||||
font-weight: 600;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
/* Contact HQ Card and Inquiry Form Styling */
|
||||
.ema-landing .ema-contact-hq-card {
|
||||
border-left: 4px solid var(--mantine-primary-color-filled);
|
||||
}
|
||||
.ema-landing .ema-inquiry-box {
|
||||
box-shadow: 0 12px 36px rgba(15, 23, 42, 0.06);
|
||||
border: 1px solid var(--mantine-color-default-border);
|
||||
}
|
||||
|
||||
/* Mobile drawer link item */
|
||||
.ema-drawer-nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
border-radius: var(--mantine-radius-md);
|
||||
font-weight: 500;
|
||||
color: var(--mantine-color-text);
|
||||
text-decoration: none;
|
||||
transition: background-color 140ms ease;
|
||||
}
|
||||
.ema-drawer-nav-link:hover,
|
||||
.ema-drawer-nav-link[aria-current='true'] {
|
||||
background-color: var(--mantine-color-default-hover);
|
||||
color: var(--mantine-primary-color-filled);
|
||||
}
|
||||
|
||||
/* Amharic runs 20-40% longer than English and falls back to a different font
|
||||
@@ -52,7 +206,9 @@ html:has(.ema-landing) {
|
||||
scroll-behavior: auto;
|
||||
}
|
||||
.ema-landing .ema-landing-fade,
|
||||
.ema-landing .ema-landing-hover {
|
||||
.ema-landing .ema-landing-hover,
|
||||
.ema-hero-pulse,
|
||||
.ema-landing .ema-live-dot {
|
||||
animation: none;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
AppShell,
|
||||
Badge,
|
||||
Collapse,
|
||||
Group,
|
||||
NavLink,
|
||||
Popover,
|
||||
@@ -11,10 +12,10 @@ import {
|
||||
Tooltip,
|
||||
UnstyledButton,
|
||||
rem,
|
||||
useMantineColorScheme,
|
||||
useComputedColorScheme,
|
||||
} from '@mantine/core';
|
||||
import { useMediaQuery } from '@mantine/hooks';
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
} from '@tabler/icons-react';
|
||||
@@ -110,13 +111,18 @@ function SidebarItem({ item, collapsed, activePath, onNavigate, opened, onToggle
|
||||
);
|
||||
|
||||
// Parent headers always carry a chevron so the expand/collapse state is
|
||||
// never ambiguous, even when a badge is also present.
|
||||
// never ambiguous, even when a badge is also present. One icon rotated
|
||||
// (rather than swapping icons) so the toggle animates instead of jumping.
|
||||
const chevron = hasChildren ? (
|
||||
opened ? (
|
||||
<IconChevronDown size={14} stroke={1.8} color="var(--mantine-color-gray-5)" />
|
||||
) : (
|
||||
<IconChevronRight size={14} stroke={1.8} color="var(--mantine-color-gray-5)" />
|
||||
)
|
||||
<IconChevronRight
|
||||
size={14}
|
||||
stroke={1.8}
|
||||
color="var(--mantine-color-gray-5)"
|
||||
style={{
|
||||
transform: opened ? 'rotate(90deg)' : 'rotate(0deg)',
|
||||
transition: 'transform 200ms ease',
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
const soonBadge = (
|
||||
@@ -270,7 +276,7 @@ interface AppSidebarProps {
|
||||
|
||||
export function AppSidebar({
|
||||
navItems,
|
||||
collapsed,
|
||||
collapsed: collapsedProp,
|
||||
activePath,
|
||||
onToggleCollapse,
|
||||
onNavigate,
|
||||
@@ -279,7 +285,13 @@ export function AppSidebar({
|
||||
brandLogo,
|
||||
}: AppSidebarProps) {
|
||||
const { t } = useTranslation();
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const colorScheme = useComputedColorScheme('light', { getInitialValueInEffect: true });
|
||||
// The icon-rail toggle is a desktop-only affordance (its button is
|
||||
// `visibleFrom="sm"`) — on mobile the sidebar renders in a full-width
|
||||
// drawer, so a `collapsed` state carried over from a prior desktop session
|
||||
// would otherwise show icon-only with no way back. Mobile always expands.
|
||||
const isMobile = useMediaQuery('(max-width: 48em)');
|
||||
const collapsed = collapsedProp && !isMobile;
|
||||
const hoverBg = colorScheme === 'dark'
|
||||
? 'var(--mantine-color-dark-6)'
|
||||
: 'var(--mantine-color-gray-0)';
|
||||
@@ -405,11 +417,15 @@ export function AppSidebar({
|
||||
>
|
||||
{t(section.label)}
|
||||
</Text>
|
||||
{sectionOpened ? (
|
||||
<IconChevronDown size={14} stroke={1.8} color="var(--mantine-color-gray-5)" />
|
||||
) : (
|
||||
<IconChevronRight size={14} stroke={1.8} color="var(--mantine-color-gray-5)" />
|
||||
)}
|
||||
<IconChevronRight
|
||||
size={14}
|
||||
stroke={1.8}
|
||||
color="var(--mantine-color-gray-5)"
|
||||
style={{
|
||||
transform: sectionOpened ? 'rotate(90deg)' : 'rotate(0deg)',
|
||||
transition: 'transform 200ms ease',
|
||||
}}
|
||||
/>
|
||||
</UnstyledButton>
|
||||
)}
|
||||
{section.label && collapsed && sectionIndex > 0 && (
|
||||
@@ -421,18 +437,21 @@ export function AppSidebar({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{(!section.label || sectionOpened || collapsed) &&
|
||||
section.items.map((item) => (
|
||||
<SidebarItem
|
||||
key={item.label}
|
||||
item={item}
|
||||
collapsed={collapsed}
|
||||
activePath={activePath}
|
||||
onNavigate={onNavigate}
|
||||
opened={openMap[item.label] ?? isBranchActive(item, activePath)}
|
||||
onToggle={(next) => setItemOpened(item.label, next)}
|
||||
/>
|
||||
))}
|
||||
<Collapse in={!section.label || sectionOpened || collapsed}>
|
||||
<Stack gap={2}>
|
||||
{section.items.map((item) => (
|
||||
<SidebarItem
|
||||
key={item.label}
|
||||
item={item}
|
||||
collapsed={collapsed}
|
||||
activePath={activePath}
|
||||
onNavigate={onNavigate}
|
||||
opened={openMap[item.label] ?? isBranchActive(item, activePath)}
|
||||
onToggle={(next) => setItemOpened(item.label, next)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</Collapse>
|
||||
</Stack>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,45 +1,118 @@
|
||||
import { UnstyledButton, useMantineColorScheme, useComputedColorScheme, rem } from '@mantine/core';
|
||||
import { IconSun, IconMoon } from '@tabler/icons-react';
|
||||
import {
|
||||
Menu,
|
||||
UnstyledButton,
|
||||
Text,
|
||||
Group,
|
||||
rem,
|
||||
useMantineColorScheme,
|
||||
useComputedColorScheme,
|
||||
} from '@mantine/core';
|
||||
import {
|
||||
IconSun,
|
||||
IconMoon,
|
||||
IconDeviceDesktop,
|
||||
IconCheck,
|
||||
} from '@tabler/icons-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export function ColorSchemeToggle() {
|
||||
const { t } = useTranslation();
|
||||
const { setColorScheme } = useMantineColorScheme();
|
||||
const { colorScheme, setColorScheme } = useMantineColorScheme();
|
||||
const computed = useComputedColorScheme('light', { getInitialValueInEffect: true });
|
||||
const isDark = computed === 'dark';
|
||||
|
||||
const themes = [
|
||||
{
|
||||
value: 'light' as const,
|
||||
label: t('profile.appearance.light', 'Light'),
|
||||
icon: IconSun,
|
||||
color: '#e67e22',
|
||||
},
|
||||
{
|
||||
value: 'dark' as const,
|
||||
label: t('profile.appearance.dark', 'Dark'),
|
||||
icon: IconMoon,
|
||||
color: '#9b59b6',
|
||||
},
|
||||
{
|
||||
value: 'auto' as const,
|
||||
label: t('profile.appearance.system', 'System'),
|
||||
icon: IconDeviceDesktop,
|
||||
color: '#3498db',
|
||||
},
|
||||
];
|
||||
|
||||
const CurrentIcon = colorScheme === 'auto' ? IconDeviceDesktop : isDark ? IconMoon : IconSun;
|
||||
|
||||
return (
|
||||
<UnstyledButton
|
||||
aria-label={t('common.toggleTheme')}
|
||||
onClick={() => setColorScheme(isDark ? 'light' : 'dark')}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: rem(38),
|
||||
height: rem(38),
|
||||
borderRadius: rem(12),
|
||||
background: 'var(--mantine-color-body)',
|
||||
color: 'var(--mantine-color-gray-6)',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.06)',
|
||||
transition: 'all 150ms ease',
|
||||
cursor: 'pointer',
|
||||
border: 'none',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.background = 'var(--mantine-primary-color-light)';
|
||||
e.currentTarget.style.color = 'var(--mantine-primary-color-6)';
|
||||
e.currentTarget.style.boxShadow =
|
||||
'0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px var(--mantine-primary-color-2)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'var(--mantine-color-body)';
|
||||
e.currentTarget.style.color = 'var(--mantine-color-gray-6)';
|
||||
e.currentTarget.style.boxShadow =
|
||||
'0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.06)';
|
||||
}}
|
||||
>
|
||||
{isDark ? <IconSun size={19} /> : <IconMoon size={19} />}
|
||||
</UnstyledButton>
|
||||
<Menu shadow="lg" width={170} position="bottom-end" withinPortal transitionProps={{ transition: 'pop-top-right', duration: 150 }}>
|
||||
<Menu.Target>
|
||||
<UnstyledButton
|
||||
aria-label={t('common.toggleTheme', 'Toggle light / dark mode')}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: rem(38),
|
||||
height: rem(38),
|
||||
borderRadius: rem(12),
|
||||
background: 'var(--mantine-color-body)',
|
||||
color: isDark ? 'var(--mantine-color-yellow-4)' : 'var(--mantine-color-blue-6)',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 0 0 1px rgba(0,0,0,0.08)',
|
||||
transition: 'all 200ms ease',
|
||||
cursor: 'pointer',
|
||||
border: 'none',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.transform = 'translateY(-1px)';
|
||||
e.currentTarget.style.boxShadow =
|
||||
'0 4px 12px rgba(0,0,0,0.1), 0 0 0 1px var(--mantine-primary-color-3)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.transform = 'translateY(0)';
|
||||
e.currentTarget.style.boxShadow =
|
||||
'0 1px 3px rgba(0,0,0,0.06), 0 0 0 1px rgba(0,0,0,0.08)';
|
||||
}}
|
||||
>
|
||||
<CurrentIcon size={19} stroke={1.8} />
|
||||
</UnstyledButton>
|
||||
</Menu.Target>
|
||||
|
||||
<Menu.Dropdown
|
||||
style={{
|
||||
borderRadius: rem(14),
|
||||
padding: rem(6),
|
||||
boxShadow: '0 10px 30px rgba(0,0,0,0.15)',
|
||||
backdropFilter: 'blur(8px)',
|
||||
}}
|
||||
>
|
||||
<Menu.Label style={{ fontWeight: 600, fontSize: rem(11), letterSpacing: '0.5px', textTransform: 'uppercase' }}>
|
||||
{t('profile.appearance.title', 'Appearance')}
|
||||
</Menu.Label>
|
||||
{themes.map((theme) => {
|
||||
const Icon = theme.icon;
|
||||
const isSelected = colorScheme === theme.value;
|
||||
return (
|
||||
<Menu.Item
|
||||
key={theme.value}
|
||||
onClick={() => setColorScheme(theme.value)}
|
||||
leftSection={<Icon size={16} stroke={1.8} style={{ color: isSelected ? 'var(--mantine-primary-color-filled)' : 'currentColor' }} />}
|
||||
rightSection={
|
||||
isSelected ? <IconCheck size={16} stroke={2.4} style={{ color: 'var(--mantine-primary-color-filled)' }} /> : undefined
|
||||
}
|
||||
style={{
|
||||
borderRadius: rem(8),
|
||||
fontWeight: isSelected ? 600 : 400,
|
||||
backgroundColor: isSelected ? 'var(--mantine-primary-color-light)' : undefined,
|
||||
color: isSelected ? 'var(--mantine-primary-color-filled)' : undefined,
|
||||
}}
|
||||
>
|
||||
<Text size="sm">{theme.label}</Text>
|
||||
</Menu.Item>
|
||||
);
|
||||
})}
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,83 +1,179 @@
|
||||
import { Menu, UnstyledButton, Text, rem } from '@mantine/core';
|
||||
import { IconWorld, IconCheck, IconChevronDown } from '@tabler/icons-react';
|
||||
import type { ComponentType, SVGProps } from 'react';
|
||||
import { Menu, UnstyledButton, Text, Group, rem } from '@mantine/core';
|
||||
import { IconCheck, IconChevronDown, IconWorld } from '@tabler/icons-react';
|
||||
import { GB, ET } from 'country-flag-icons/react/3x2';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface LanguageSwitcherProps {
|
||||
supportedLanguages: readonly string[];
|
||||
/** `icon` renders a compact globe button; `button` shows the language label. */
|
||||
/** `icon` renders a compact flag button; `button` shows the language label. */
|
||||
variant?: 'icon' | 'button';
|
||||
}
|
||||
|
||||
export function LanguageSwitcher({ supportedLanguages, variant = 'icon' }: LanguageSwitcherProps) {
|
||||
type FlagComponentType = ComponentType<SVGProps<SVGSVGElement>>;
|
||||
|
||||
const LANGUAGE_CONFIG: Record<
|
||||
string,
|
||||
{ Flag: FlagComponentType; nativeName: string; shortCode: string }
|
||||
> = {
|
||||
en: { Flag: GB, nativeName: 'English', shortCode: 'EN' },
|
||||
am: { Flag: ET, nativeName: 'አማርኛ', shortCode: 'AM' },
|
||||
};
|
||||
|
||||
export function LanguageSwitcher({
|
||||
supportedLanguages,
|
||||
variant = 'icon',
|
||||
}: LanguageSwitcherProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const current = i18n.language;
|
||||
const current = i18n.language || 'en';
|
||||
|
||||
const change = (lng: string) => {
|
||||
if (lng !== current) i18n.changeLanguage(lng);
|
||||
};
|
||||
|
||||
const currentConfig = LANGUAGE_CONFIG[current] || {
|
||||
Flag: null,
|
||||
nativeName: current.toUpperCase(),
|
||||
shortCode: current.toUpperCase(),
|
||||
};
|
||||
|
||||
const CurrentFlag = currentConfig.Flag;
|
||||
|
||||
return (
|
||||
<Menu shadow="md" width={160} position="bottom-end" withinPortal>
|
||||
<Menu
|
||||
shadow="lg"
|
||||
width={190}
|
||||
position="bottom-end"
|
||||
withinPortal
|
||||
transitionProps={{ transition: 'pop-top-right', duration: 150 }}
|
||||
>
|
||||
<Menu.Target>
|
||||
<UnstyledButton
|
||||
aria-label={t('language.label')}
|
||||
aria-label={t('language.label', 'Language')}
|
||||
style={{
|
||||
display: 'flex',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: rem(4),
|
||||
gap: rem(6),
|
||||
width: variant === 'icon' ? rem(38) : 'auto',
|
||||
height: rem(38),
|
||||
padding: variant === 'icon' ? 0 : '0 12px',
|
||||
borderRadius: rem(12),
|
||||
background: 'var(--mantine-color-body)',
|
||||
color: 'var(--mantine-color-gray-6)',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.06)',
|
||||
transition: 'all 150ms ease',
|
||||
color: 'var(--mantine-color-gray-7)',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 0 0 1px rgba(0,0,0,0.08)',
|
||||
transition: 'all 200ms ease',
|
||||
cursor: 'pointer',
|
||||
border: 'none',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.background = 'var(--mantine-primary-color-light)';
|
||||
e.currentTarget.style.color = 'var(--mantine-primary-color-6)';
|
||||
e.currentTarget.style.transform = 'translateY(-1px)';
|
||||
e.currentTarget.style.boxShadow =
|
||||
'0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px var(--mantine-primary-color-2)';
|
||||
'0 4px 12px rgba(0,0,0,0.1), 0 0 0 1px var(--mantine-primary-color-3)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'var(--mantine-color-body)';
|
||||
e.currentTarget.style.color = 'var(--mantine-color-gray-6)';
|
||||
e.currentTarget.style.transform = 'translateY(0)';
|
||||
e.currentTarget.style.boxShadow =
|
||||
'0 1px 3px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.06)';
|
||||
'0 1px 3px rgba(0,0,0,0.06), 0 0 0 1px rgba(0,0,0,0.08)';
|
||||
}}
|
||||
>
|
||||
<IconWorld size={19} />
|
||||
{CurrentFlag ? (
|
||||
<CurrentFlag
|
||||
style={{
|
||||
width: rem(20),
|
||||
height: rem(14),
|
||||
borderRadius: rem(2),
|
||||
display: 'block',
|
||||
boxShadow: '0 1px 2px rgba(0,0,0,0.2)',
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<IconWorld size={19} />
|
||||
)}
|
||||
|
||||
{variant !== 'icon' && (
|
||||
<>
|
||||
<Text size="sm" fw={500}>
|
||||
{t(`language.${current}`)}
|
||||
<Group gap={6} wrap="nowrap">
|
||||
<Text size="sm" fw={600}>
|
||||
{t(`language.${current}`, currentConfig.nativeName)}
|
||||
</Text>
|
||||
<IconChevronDown size={14} />
|
||||
</>
|
||||
<IconChevronDown size={14} stroke={2} style={{ opacity: 0.7 }} />
|
||||
</Group>
|
||||
)}
|
||||
</UnstyledButton>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown
|
||||
style={{ borderRadius: rem(12), padding: rem(6) }}
|
||||
style={{
|
||||
borderRadius: rem(14),
|
||||
padding: rem(6),
|
||||
boxShadow: '0 10px 30px rgba(0,0,0,0.15)',
|
||||
backdropFilter: 'blur(8px)',
|
||||
}}
|
||||
>
|
||||
<Menu.Label>{t('language.label')}</Menu.Label>
|
||||
{supportedLanguages.map((lng) => (
|
||||
<Menu.Item
|
||||
key={lng}
|
||||
onClick={() => change(lng)}
|
||||
rightSection={
|
||||
current === lng ? <IconCheck size={16} /> : undefined
|
||||
}
|
||||
style={{ borderRadius: rem(8) }}
|
||||
>
|
||||
{t(`language.${lng}`)}
|
||||
</Menu.Item>
|
||||
))}
|
||||
<Menu.Label
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
fontSize: rem(11),
|
||||
letterSpacing: '0.5px',
|
||||
textTransform: 'uppercase',
|
||||
}}
|
||||
>
|
||||
{t('language.label', 'Language')}
|
||||
</Menu.Label>
|
||||
{supportedLanguages.map((lng) => {
|
||||
const config = LANGUAGE_CONFIG[lng] || {
|
||||
Flag: null,
|
||||
nativeName: lng.toUpperCase(),
|
||||
shortCode: lng.toUpperCase(),
|
||||
};
|
||||
const Flag = config.Flag;
|
||||
const isSelected = current === lng;
|
||||
|
||||
return (
|
||||
<Menu.Item
|
||||
key={lng}
|
||||
onClick={() => change(lng)}
|
||||
leftSection={
|
||||
Flag ? (
|
||||
<Flag
|
||||
style={{
|
||||
width: rem(20),
|
||||
height: rem(14),
|
||||
borderRadius: rem(2),
|
||||
display: 'block',
|
||||
boxShadow: '0 1px 2px rgba(0,0,0,0.15)',
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<IconWorld size={16} />
|
||||
)
|
||||
}
|
||||
rightSection={
|
||||
isSelected ? (
|
||||
<IconCheck
|
||||
size={16}
|
||||
stroke={2.4}
|
||||
style={{ color: 'var(--mantine-primary-color-filled)' }}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
style={{
|
||||
borderRadius: rem(8),
|
||||
fontWeight: isSelected ? 600 : 400,
|
||||
backgroundColor: isSelected
|
||||
? 'var(--mantine-primary-color-light)'
|
||||
: undefined,
|
||||
color: isSelected ? 'var(--mantine-primary-color-filled)' : undefined,
|
||||
}}
|
||||
>
|
||||
<Group justify="space-between" wrap="nowrap" style={{ width: '100%' }}>
|
||||
<Text size="sm">{t(`language.${lng}`, config.nativeName)}</Text>
|
||||
</Group>
|
||||
</Menu.Item>
|
||||
);
|
||||
})}
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
47
libs/ui/src/lib/theme/maritime-loader-theme.ts
Normal file
47
libs/ui/src/lib/theme/maritime-loader-theme.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
ActionIcon,
|
||||
Button,
|
||||
createTheme,
|
||||
Input,
|
||||
Loader,
|
||||
Select,
|
||||
TextInput,
|
||||
type MantineLoaderComponent,
|
||||
} from '@mantine/core';
|
||||
import { MaritimeLoader } from '../components/MaritimeLoader';
|
||||
|
||||
/**
|
||||
* Registers the branded Ethiopian Maritime Authority loader as the default Mantine `Loader` type,
|
||||
* sets prominent 80px size for page/section loaders, and opts inline control loaders
|
||||
* (buttons, inputs, select fields) back out to the compact oval spinner.
|
||||
*/
|
||||
export const maritimeLoaderTheme = createTheme({
|
||||
components: {
|
||||
Loader: Loader.extend({
|
||||
defaultProps: {
|
||||
loaders: {
|
||||
...Loader.defaultLoaders,
|
||||
maritime: MaritimeLoader as unknown as MantineLoaderComponent,
|
||||
},
|
||||
type: 'maritime',
|
||||
size: 80,
|
||||
},
|
||||
}),
|
||||
Button: Button.extend({
|
||||
defaultProps: { loaderProps: { type: 'oval' } },
|
||||
}),
|
||||
ActionIcon: ActionIcon.extend({
|
||||
defaultProps: { loaderProps: { type: 'oval' } },
|
||||
}),
|
||||
Input: Input.extend({
|
||||
defaultProps: { loaderProps: { type: 'oval' } },
|
||||
}),
|
||||
TextInput: TextInput.extend({
|
||||
defaultProps: { loaderProps: { type: 'oval' } },
|
||||
}),
|
||||
Select: Select.extend({
|
||||
defaultProps: { loaderProps: { type: 'oval' } },
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
19
libs/ui/src/lib/utils/person-name.ts
Normal file
19
libs/ui/src/lib/utils/person-name.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Splits and joins a person's name between the account's single `name.en`
|
||||
* string and the profile's separate `firstName`/`middleName`/`lastName`
|
||||
* fields.
|
||||
*
|
||||
* The account has no first/middle/last columns of its own (that model lives
|
||||
* only on the profile), so this is the one place that heuristic lives —
|
||||
* reused everywhere a name crosses that boundary: the signup form joins into
|
||||
* it, the Identity Details wizard step and the Profile page's Personal tab
|
||||
* both split out of it.
|
||||
*/
|
||||
export function splitPersonName(fullName: string) {
|
||||
const [firstName = '', middleName = '', ...rest] = fullName.trim().split(/\s+/);
|
||||
return { firstName, middleName, lastName: rest.join(' ') };
|
||||
}
|
||||
|
||||
export function joinPersonName(parts: { firstName: string; middleName?: string; lastName: string }) {
|
||||
return [parts.firstName, parts.middleName, parts.lastName].filter(Boolean).join(' ');
|
||||
}
|
||||
Reference in New Issue
Block a user