Helper functions provide reusable utilities for date formatting, string manipulation, file operations, pagination, and role-based access control.
Date & Time Helpers
Functions for working with dates and timestamps.
Formats a timestamp or date string according to a specified format and timezone.
The date value to format (timestamp or date string)
format
string
default: "DD - MM - YYYY"
The output format using Day.js format tokens
IANA timezone name (e.g., "America/New_York", "Europe/London"). If omitted, uses local timezone.
Formatted date string, or empty string if invalid
Basic Usage
Custom Format
With Timezone
In Component
import { formatDate } from "@/utils" ;
const timestamp = 1709481600000 ;
const formatted = formatDate ( timestamp );
// Output: "03 - 03 - 2024"
Timezone Handling : The function parses input as UTC and converts to the specified timezone. Always store timestamps in UTC on the backend.
String Manipulation
Functions for transforming and formatting strings.
toKebabCase
Converts camelCase or PascalCase strings to kebab-case.
import { toKebabCase } from "@/utils" ;
toKebabCase ( "assetManagement" ); // "asset-management"
toKebabCase ( "OilSampleAnalysis" ); // "oil-sample-analysis"
camelToSpaced
Converts camelCase to lowercase with spaces.
Lowercase string with spaces
import { camelToSpaced } from "@/utils" ;
camelToSpaced ( "assetManagement" ); // "asset management"
camelToSpaced ( "oilSampleAnalysis" ); // "oil sample analysis"
sentenceCase
Converts a string to sentence case (capitalizes first letter of sentences).
import { sentenceCase } from "@/utils" ;
sentenceCase ( "hello world. this is a test." );
// "Hello world. This is a test."
makeDropdownOptions
Transforms an array of strings into dropdown options with sentence-cased labels.
return
Array<{ label: string; value: string }>
Array of dropdown options
import { makeDropdownOptions } from "@/utils" ;
const options = makeDropdownOptions ([ "active" , "inactive" , "pending" ]);
// [
// { label: "Active", value: "active" },
// { label: "Inactive", value: "inactive" },
// { label: "Pending", value: "pending" },
// ]
Query String Helpers
Functions for building URL query parameters.
getQueryString
Builds a URL query string from an object, excluding null, undefined, and empty string values.
Object with query parameters
URL-encoded query string (without leading ?)
Basic Usage
With Server Actions
import { getQueryString } from "@/utils" ;
const params = {
page: 1 ,
limit: 10 ,
status: "active" ,
search: "" , // Excluded
filter: null , // Excluded
};
const query = getQueryString ( params );
// "page=1&limit=10&status=active"
getTarget
Extracts a nested value from an object using a dot-notation path.
inputObj
Record<string, unknown>
required
Source object
path
string | string[]
required
Path to the target value (e.g., "user.profile.name" or ["user", "profile", "name"])
The value at the path, or undefined if not found
import { getTarget } from "@/utils" ;
const data = {
user: {
profile: {
name: "John Doe" ,
email: "[email protected] " ,
},
},
};
getTarget ( data , "user.profile.name" ); // "John Doe"
getTarget ( data , [ "user" , "profile" , "email" ]); // "[email protected] "
getTarget ( data , "user.missing.field" ); // undefined
Functions for formatting data for display.
Formats a number as currency with locale-specific formatting.
Maximum number of decimal places
Locale for number formatting
Formatted currency string
import { formatCurrency } from "@/utils" ;
formatCurrency ( 1500.5 ); // "₦1,500.50"
formatCurrency ( 1000 , "USD" , 2 , "en-US" ); // "$1,000"
formatCurrency ( 2500.0 ); // "₦2,500" (removes .00)
Formats a file size in bytes to a human-readable string.
Formatted file size (e.g., "1.5 MB", "250 KB")
import { formatFileSize } from "@/utils" ;
formatFileSize ( 500 ); // "500 B"
formatFileSize ( 2048 ); // "2.00 KB"
formatFileSize ( 1572864 ); // "1.50 MB"
maskNumber
Masks a phone number or other numeric string by showing only the first 3 and last 2 digits.
Number to mask (can include non-digit characters)
Masked number string, or empty string if input is null
import { maskNumber } from "@/utils" ;
maskNumber ( "+234 803 123 4567" ); // "234*******67"
maskNumber ( "08031234567" ); // "080*****67"
maskNumber ( null ); // ""
Error Handling : Throws an error if the number has fewer than 5 digits.
getFullName
Combines first and last name into a full name.
customer
{ first_name: string; last_name: string }
required
Object with name fields
Full name with space separator
import { getFullName } from "@/utils" ;
getFullName ({ first_name: "John" , last_name: "Doe" }); // "John Doe"
getFullName ({ first_name: "Jane" , last_name: "" }); // "Jane"
Formats an array of roles for display, showing up to 2 names and a count for additional roles.
arr
Array<{ name: string }>
required
Array of role objects
Formatted role names string
import { formatRoleNames } from "@/utils" ;
formatRoleNames ([{ name: "Admin" }]);
// "Admin"
formatRoleNames ([{ name: "Admin" }, { name: "Analyst" }]);
// "Admin, Analyst"
formatRoleNames ([
{ name: "Admin" },
{ name: "Analyst" },
{ name: "Viewer" },
{ name: "Technician" },
]);
// "Admin, Analyst +2 more"
Status Helpers
Functions for determining UI variants and text for status values.
getStatusVariant
Returns the appropriate color variant for a status or severity value.
Status or severity string
return
'success' | 'warning' | 'error'
Color variant for UI components
import { getStatusVariant } from "@/utils" ;
getStatusVariant ( "active" ); // "success"
getStatusVariant ( "completed" ); // "success"
getStatusVariant ( "low" ); // "success"
getStatusVariant ( "pending" ); // "warning"
getStatusVariant ( "medium" ); // "warning"
getStatusVariant ( "inactive" ); // "error"
getStatusVariant ( "critical" ); // "error"
getStatusVariant ( "high" ); // "error"
getStatusVariant ( "unknown" ); // "warning" (default)
Status Badge
Severity Indicator
import { getStatusVariant } from "@/utils" ;
import { Badge } from "@/components/ui/badge" ;
const StatusBadge = ({ status }) => {
const variant = getStatusVariant ( status );
return < Badge variant = { variant } > { status } </ Badge > ;
};
getStatusText
Normalizes status values to display text.
Display text for the status
import { getStatusText } from "@/utils" ;
getStatusText ( "active" ); // "Active"
getStatusText ( "inactive" ); // "Inactive"
getStatusText ( "deactivated" ); // "Deactivated"
getStatusText ( "deactivate" ); // "Deactivated"
getStatusText ( "unknown" ); // "Pending" (default)
getTrendData
Generates trend indicator data (icon and label) from a percentage change.
Percentage change (positive or negative)
return
{ icon: string; label: string; isPositive: boolean }
Trend indicator data
import { getTrendData } from "@/utils" ;
getTrendData ( 12.5 );
// {
// icon: "mdi:trending-up",
// label: "+12.5% from last period",
// isPositive: true
// }
getTrendData ( - 8.3 );
// {
// icon: "mdi:trending-down",
// label: "+8.3% from last period",
// isPositive: false
// }
File Operations
Functions for generating and downloading files.
generateAndDownloadCsv
Generates a CSV file from data and triggers a browser download.
options
generateCsvParams
required
CSV generation options Column definitions
name: Column header text
accessor: Path to the data field (dot notation)
transform: Optional function to transform the value
Array of data objects to export
Download file name (without extension)
Basic Export
Nested Data
With Transform
import { generateAndDownloadCsv } from "@/utils" ;
const assets = [
{ id: "1" , name: "Pump A" , status: "active" , commissioned: 1704067200000 },
{ id: "2" , name: "Motor B" , status: "inactive" , commissioned: 1706745600000 },
];
generateAndDownloadCsv ({
headers: [
{ name: "ID" , accessor: "id" },
{ name: "Name" , accessor: "name" },
{ name: "Status" , accessor: "status" },
{
name: "Commissioned" ,
accessor: "commissioned" ,
transform : ( val ) => new Date ( val ). toLocaleDateString (),
},
],
data: assets ,
fileName: "assets-export" ,
});
generateCsv
Generates a CSV Blob without triggering download.
options
generateCsvParams
required
Same as generateAndDownloadCsv
CSV file as a Blob object
import { generateCsv } from "@/utils" ;
const csvBlob = generateCsv ({
headers: [{ name: "Name" , accessor: "name" }],
data: [{ name: "Asset 1" }],
fileName: "export" ,
});
// Upload to server or attach to email
const formData = new FormData ();
formData . append ( "file" , csvBlob , "export.csv" );
downloadFile
Triggers a browser download for a Blob or File.
import { downloadFile } from "@/utils" ;
const blob = new Blob ([ "Hello, World!" ], { type: "text/plain" });
downloadFile ( blob , "hello.txt" );
Functions for generating pagination UI.
generateDottedPages
Generates a page number array with ellipsis for pagination controls.
Number of pages to show on each side of current page
String to represent ellipsis
Array of page numbers and ellipsis markers
Basic Usage
Custom Radius
Pagination Component
import { generateDottedPages } from "@/utils" ;
generateDottedPages ({ page: 1 , totalPages: 10 });
// [1, 2, 3, "...", 10]
generateDottedPages ({ page: 5 , totalPages: 10 });
// [1, "...", 3, 4, 5, 6, 7, "...", 10]
generateDottedPages ({ page: 10 , totalPages: 10 });
// [1, "...", 8, 9, 10]
Role & Permission Helpers
Functions for working with roles and permissions.
getAllAdminPermissions
Extracts all permissions from a role or array of roles.
Role object or array of role objects with permissions property
return
PermissionType[] | string[]
Flattened array of all permissions
import { getAllAdminPermissions } from "@/utils" ;
const role = {
id: "1" ,
name: "Analyst" ,
permissions: [ "assets:read" , "samples:read" , "samples:create" ],
};
getAllAdminPermissions ( role );
// ["assets:read", "samples:read", "samples:create"]
const roles = [
{ permissions: [ "assets:read" ] },
{ permissions: [ "samples:read" , "alarms:read" ] },
];
getAllAdminPermissions ( roles );
// ["assets:read", "samples:read", "alarms:read"]
getFirstRouteFromUser
Finds the first accessible route for a user based on their permissions.
Application menu structure (from @/utils/shared)
First matching route path, or null if no match
Redirect After Login
Dashboard Redirect
import { getFirstRouteFromUser } from "@/utils" ;
import menuItems from "@/utils/shared" ;
import { redirect } from "next/navigation" ;
const userPermissions = [ "samples:read" , "alarms:read" ];
const firstRoute = getFirstRouteFromUser ( menuItems , userPermissions );
if ( firstRoute ) {
redirect ( firstRoute ); // Redirects to "/samples"
}
getAdminRoles
Transforms admin roles into dropdown options.
return
Array<{ label: string; value: string }>
Dropdown options array
import { getAdminRoles } from "@/utils" ;
const admin = {
roles: [
{ id: "1" , name: "Admin" },
{ id: "2" , name: "Analyst" },
],
};
getAdminRoles ( admin . roles );
// [
// { label: "Admin", value: "1" },
// { label: "Analyst", value: "2" },
// ]
Transforms CSV import data into the format expected by the user creation API.
data
StaffCsvDataItem[]
required
Array of CSV row objects
import { transformStaffCsvData } from "@/utils" ;
const csvData = [
{
staffName: "John Doe" ,
emailAddress: "[email protected] " ,
phoneNumber: "08031234567" ,
assignedRole: "Analyst" ,
},
{
staffName: "Jane Smith" ,
emailAddress: "[email protected] " ,
phoneNumber: 8031234568 ,
assignedRole: "Viewer" ,
},
];
const transformed = transformStaffCsvData ( csvData );
// [
// {
// first_name: "John",
// last_name: "Doe",
// email: "[email protected] ",
// phone_number: "08031234567",
// role_names: ["Analyst"],
// },
// {
// first_name: "Jane",
// last_name: "Smith",
// email: "[email protected] ",
// phone_number: "8031234568",
// role_names: ["Viewer"],
// },
// ]
Best Practices
Date Formatting : Always use formatDate() instead of manual date formatting to ensure consistent timezone handling and format across the application.
CSV Exports : Use generateAndDownloadCsv() for user-triggered exports. Use generateCsv() if you need to upload the file to a server or process it further.
Status Variants : Use getStatusVariant() to maintain consistent color coding for statuses and severities across the UI.