Skip to main content
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.

formatDate

Formats a timestamp or date string according to a specified format and timezone.
value
string | number
required
The date value to format (timestamp or date string)
format
string
default:"DD - MM - YYYY"
The output format using Day.js format tokens
userTimezone
string
IANA timezone name (e.g., "America/New_York", "Europe/London"). If omitted, uses local timezone.
return
string
Formatted date string, or empty string if invalid
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.
str
string
required
String to convert
return
string
kebab-case string
import { toKebabCase } from "@/utils";

toKebabCase("assetManagement"); // "asset-management"
toKebabCase("OilSampleAnalysis"); // "oil-sample-analysis"

camelToSpaced

Converts camelCase to lowercase with spaces.
str
string
required
String to convert
return
string
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).
str
string
required
String to convert
return
string
Sentence-cased string
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.
items
string[]
required
Array of string values
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.
obj
Record<string, unknown>
Object with query parameters
return
string
URL-encoded query string (without leading ?)
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"])
return
unknown
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

Formatting Helpers

Functions for formatting data for display.

formatCurrency

Formats a number as currency with locale-specific formatting.
value
number
required
Amount to format
currency
string
default:"NGN"
Currency code (ISO 4217)
fractionalDigit
number
default:"2"
Maximum number of decimal places
locale
string
default:"en-NG"
Locale for number formatting
return
string
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)

formatFileSize

Formats a file size in bytes to a human-readable string.
sizeInBytes
number
required
File size in bytes
return
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
string | null
required
Number to mask (can include non-digit characters)
return
string
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
return
string
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"

formatRoleNames

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
return
string
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
string
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)
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.
status
string
Status value
return
string
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
number
required
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
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
return
Blob
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.
file
Blob | File
required
File to download
fileName
string
default:"csv-file"
Download file name
import { downloadFile } from "@/utils";

const blob = new Blob(["Hello, World!"], { type: "text/plain" });
downloadFile(blob, "hello.txt");

Pagination

Functions for generating pagination UI.

generateDottedPages

Generates a page number array with ellipsis for pagination controls.
page
number
default:"1"
Current page number
totalPages
number
required
Total number of pages
radius
number
default:"2"
Number of pages to show on each side of current page
dotRepresentation
string
default:"..."
String to represent ellipsis
return
Array<string | number>
Array of page numbers and ellipsis markers
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.
roles
Role | Role[]
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.
menuItems
MenuItem[]
required
Application menu structure (from @/utils/shared)
userPermissions
PermissionType[]
required
User’s permission array
return
string | null
First matching route path, or null if no match
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.
roles
IAdmin['roles']
Admin roles array
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" },
// ]

Data Transformation

transformStaffCsvData

Transforms CSV import data into the format expected by the user creation API.
data
StaffCsvDataItem[]
required
Array of CSV row objects
return
Array<UserCreatePayload>
Transformed user data
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.

Build docs developers (and LLMs) love