feat: adição de novos ícones SVG e configuração do ambiente

- Adicionados ícones SVG para ChatGPT, Claude, Gemini e OpenRouter
- Implementados ícones para modos claro e escuro do ChatGPT
- Criado script de inicialização para PostgreSQL com extensão pgcrypto
- Adicionado script de configuração de ambiente que faz backup do .env
- Configurado tsconfig.json para TypeScript com opções de compilação
This commit is contained in:
Felipe Coutinho
2025-11-15 15:49:36 -03:00
commit ea0b8618e0
441 changed files with 53569 additions and 0 deletions

168
lib/utils/calculator.ts Normal file
View File

@@ -0,0 +1,168 @@
export type Operator = "add" | "subtract" | "multiply" | "divide";
export const OPERATOR_SYMBOLS: Record<Operator, string> = {
add: "+",
subtract: "-",
multiply: "×",
divide: "÷",
};
export function formatNumber(value: number): string {
if (!Number.isFinite(value)) {
return "Erro";
}
const rounded = Number(Math.round(value * 1e10) / 1e10);
return rounded.toString();
}
export function formatLocaleValue(rawValue: string): string {
if (rawValue === "Erro") {
return rawValue;
}
const isNegative = rawValue.startsWith("-");
const unsignedValue = isNegative ? rawValue.slice(1) : rawValue;
if (unsignedValue === "") {
return isNegative ? "-0" : "0";
}
const hasDecimalSeparator = unsignedValue.includes(".");
const [integerPartRaw, decimalPartRaw] = unsignedValue.split(".");
const integerPart = integerPartRaw || "0";
const decimalPart = hasDecimalSeparator ? (decimalPartRaw ?? "") : undefined;
const numericInteger = Number(integerPart);
const formattedInteger = Number.isFinite(numericInteger)
? numericInteger.toLocaleString("pt-BR")
: integerPart;
if (decimalPart === undefined) {
return `${isNegative ? "-" : ""}${formattedInteger}`;
}
return `${isNegative ? "-" : ""}${formattedInteger},${decimalPart}`;
}
export function performOperation(
a: number,
b: number,
operator: Operator,
): number {
switch (operator) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
return b === 0 ? Infinity : a / b;
default:
return b;
}
}
// Trata colagem de valores com formatação brasileira (ponto para milhar, vírgula para decimal)
// e variações simples em formato internacional.
export function normalizeClipboardNumber(rawValue: string): string | null {
const trimmed = rawValue.trim();
if (!trimmed) {
return null;
}
const match = trimmed.match(/-?[\d.,\s]+/);
if (!match) {
return null;
}
let extracted = match[0].replace(/\s+/g, "");
if (!extracted) {
return null;
}
const isNegative = extracted.startsWith("-");
if (isNegative) {
extracted = extracted.slice(1);
}
extracted = extracted.replace(/[^\d.,]/g, "");
if (!extracted) {
return null;
}
const countOccurrences = (char: string) =>
(extracted.match(new RegExp(`\\${char}`, "g")) ?? []).length;
const hasComma = extracted.includes(",");
const hasDot = extracted.includes(".");
let decimalSeparator: "," | "." | null = null;
if (hasComma && hasDot) {
decimalSeparator =
extracted.lastIndexOf(",") > extracted.lastIndexOf(".") ? "," : ".";
} else if (hasComma) {
const commaCount = countOccurrences(",");
if (commaCount > 1) {
decimalSeparator = null;
} else {
const digitsAfterComma =
extracted.length - extracted.lastIndexOf(",") - 1;
decimalSeparator =
digitsAfterComma > 0 && digitsAfterComma <= 2 ? "," : null;
}
} else if (hasDot) {
const dotCount = countOccurrences(".");
if (dotCount > 1) {
decimalSeparator = null;
} else {
const digitsAfterDot = extracted.length - extracted.lastIndexOf(".") - 1;
const decimalCandidate = extracted.slice(extracted.lastIndexOf(".") + 1);
const allZeros = /^0+$/.test(decimalCandidate);
const shouldTreatAsDecimal =
digitsAfterDot > 0 &&
digitsAfterDot <= 3 &&
!(digitsAfterDot === 3 && allZeros);
decimalSeparator = shouldTreatAsDecimal ? "." : null;
}
}
let integerPart = extracted;
let decimalPart = "";
if (decimalSeparator) {
const decimalIndex = extracted.lastIndexOf(decimalSeparator);
integerPart = extracted.slice(0, decimalIndex);
decimalPart = extracted.slice(decimalIndex + 1);
}
integerPart = integerPart.replace(/[^\d]/g, "");
decimalPart = decimalPart.replace(/[^\d]/g, "");
if (!integerPart) {
integerPart = "0";
}
let normalized = integerPart;
if (decimalPart) {
normalized = `${integerPart}.${decimalPart}`;
}
if (isNegative && Number(normalized) !== 0) {
normalized = `-${normalized}`;
}
if (!/^(-?\d+(\.\d+)?)$/.test(normalized)) {
return null;
}
const numericValue = Number(normalized);
if (!Number.isFinite(numericValue)) {
return null;
}
return normalized;
}

60
lib/utils/currency.ts Normal file
View File

@@ -0,0 +1,60 @@
/**
* Utility functions for currency/decimal formatting and parsing
*/
/**
* Formats a decimal number for database storage (2 decimal places)
* @param value - The number to format
* @returns Formatted string with 2 decimal places, or null if input is null
*/
export function formatDecimalForDb(value: number | null): string | null {
if (value === null) {
return null;
}
return (Math.round(value * 100) / 100).toFixed(2);
}
/**
* Formats a decimal number for database storage (non-nullable version)
* @param value - The number to format
* @returns Formatted string with 2 decimal places
*/
export function formatDecimalForDbRequired(value: number): string {
return (Math.round(value * 100) / 100).toFixed(2);
}
/**
* Normalizes decimal input by replacing comma with period
* @param value - Input string
* @returns Normalized string with period as decimal separator
*/
export function normalizeDecimalInput(value: string): string {
return value.replace(/\s/g, "").replace(",", ".");
}
/**
* Formats a limit/balance input for display
* @param value - The number to format
* @returns Formatted string or empty string
*/
export function formatLimitInput(value?: number | null): string {
if (value === null || value === undefined || Number.isNaN(value)) {
return "";
}
return (Math.round(value * 100) / 100).toFixed(2);
}
/**
* Formats an initial balance input for display (defaults to "0.00")
* @param value - The number to format
* @returns Formatted string with default "0.00"
*/
export function formatInitialBalanceInput(value?: number | null): string {
if (value === null || value === undefined || Number.isNaN(value)) {
return "0.00";
}
return (Math.round(value * 100) / 100).toFixed(2);
}

235
lib/utils/date.ts Normal file
View File

@@ -0,0 +1,235 @@
/**
* Date utilities - Functions for date manipulation and formatting
*
* This module consolidates date-related utilities from:
* - /lib/utils/date.ts (basic date manipulation)
* - /lib/date/index.ts (formatting and display)
*
* Note: Period-related functions (YYYY-MM) are in /lib/utils/period
*/
// ============================================================================
// CONSTANTS
// ============================================================================
const WEEKDAY_NAMES = [
"Domingo",
"Segunda",
"Terça",
"Quarta",
"Quinta",
"Sexta",
"Sábado",
] as const;
const MONTH_NAMES = [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro",
] as const;
// ============================================================================
// DATE CREATION & MANIPULATION
// ============================================================================
/**
* Gets today's date in UTC
* @returns Date object set to today at midnight UTC
*/
export function getTodayUTC(): Date {
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
return new Date(Date.UTC(year, month, day));
}
/**
* Gets today's date in local timezone
* @returns Date object set to today at midnight local time
*/
export function getTodayLocal(): Date {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
const day = now.getDate();
return new Date(year, month, day);
}
/**
* Gets today's period in YYYY-MM format (UTC)
* @returns Period string
*/
export function getTodayPeriodUTC(): string {
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
return `${year}-${String(month + 1).padStart(2, "0")}`;
}
/**
* Formats date as YYYY-MM-DD string
* @param date - Date to format
* @returns Formatted date string
*/
export function formatDateForDb(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
/**
* Gets today's date as YYYY-MM-DD string
* @returns Formatted date string
*/
export function getTodayDateString(): string {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
/**
* Gets today's date as Date object
* @returns Date object for today
*/
export function getTodayDate(): Date {
return new Date(getTodayDateString());
}
/**
* Gets today's info (date and period)
* @returns Object with date and period
*/
export function getTodayInfo(): { date: Date; period: string } {
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
return {
date: new Date(Date.UTC(year, month, day)),
period: `${year}-${String(month + 1).padStart(2, "0")}`,
};
}
/**
* Adds months to a date
* @param value - Date to add months to
* @param offset - Number of months to add (can be negative)
* @returns New date with months added
*/
export function addMonthsToDate(value: Date, offset: number): Date {
const result = new Date(value);
const originalDay = result.getDate();
result.setDate(1);
result.setMonth(result.getMonth() + offset);
const lastDay = new Date(
result.getFullYear(),
result.getMonth() + 1,
0
).getDate();
result.setDate(Math.min(originalDay, lastDay));
return result;
}
// ============================================================================
// DATE FORMATTING
// ============================================================================
/**
* Formats a date string (YYYY-MM-DD) to short display format
* @example
* formatDate("2024-11-14") // "qui 14 nov"
*/
export function formatDate(value: string): string {
const [year, month, day] = value.split("-");
const parsed = new Date(
Number.parseInt(year ?? "0", 10),
Number.parseInt(month ?? "1", 10) - 1,
Number.parseInt(day ?? "1", 10)
);
return new Intl.DateTimeFormat("pt-BR", {
weekday: "short",
day: "2-digit",
month: "short",
})
.format(parsed)
.replace(".", "")
.replace(" de", "");
}
/**
* Formats a date to friendly long format
* @example
* friendlyDate(new Date()) // "Segunda, 14 de novembro de 2025"
*/
export function friendlyDate(date: Date): string {
const weekday = WEEKDAY_NAMES[date.getDay()];
const day = date.getDate();
const month = MONTH_NAMES[date.getMonth()];
const year = date.getFullYear();
return `${weekday}, ${day} de ${month} de ${year}`;
}
// ============================================================================
// TIME-BASED UTILITIES
// ============================================================================
/**
* Gets appropriate greeting based on time of day
* @param date - Date to get greeting for (defaults to now)
* @returns "Bom dia", "Boa tarde", or "Boa noite"
*/
export function getGreeting(date: Date = new Date()): string {
const hour = date.getHours();
if (hour >= 5 && hour < 12) return "Bom dia";
if (hour >= 12 && hour < 18) return "Boa tarde";
return "Boa noite";
}
// ============================================================================
// DATE INFORMATION
// ============================================================================
/**
* Gets information about a date
* @param date - Date to analyze (defaults to now)
* @returns Object with date information
*/
export function getDateInfo(date: Date = new Date()) {
return {
date,
year: date.getFullYear(),
month: date.getMonth() + 1,
monthName: MONTH_NAMES[date.getMonth()],
day: date.getDate(),
weekday: WEEKDAY_NAMES[date.getDay()],
friendlyDisplay: friendlyDate(date),
greeting: getGreeting(date),
};
}
// Re-export MONTH_NAMES for convenience
export { MONTH_NAMES };

61
lib/utils/icons.tsx Normal file
View File

@@ -0,0 +1,61 @@
import * as RemixIcons from "@remixicon/react";
import type { ComponentType, ReactNode } from "react";
const ICON_CLASS = "h-4 w-4";
const normalizeKey = (value: string) =>
value
.normalize("NFD")
.replace(/\p{Diacritic}/gu, "")
.toLowerCase()
.replace(/[^a-z0-9]/g, "");
export const getIconComponent = (
iconName: string
): ComponentType<{ className?: string }> | null => {
// Busca o ícone no objeto de ícones do Remix Icon
const icon = (RemixIcons as Record<string, unknown>)[iconName];
if (icon && typeof icon === "function") {
return icon as ComponentType<{ className?: string }>;
}
return null;
};
export const getConditionIcon = (condition: string): ReactNode => {
const key = normalizeKey(condition);
const registry: Record<string, ReactNode> = {
parcelado: <RemixIcons.RiLoader2Fill className={ICON_CLASS} aria-hidden />,
recorrente: <RemixIcons.RiRefreshLine className={ICON_CLASS} aria-hidden />,
avista: <RemixIcons.RiCheckLine className={ICON_CLASS} aria-hidden />,
vista: <RemixIcons.RiCheckLine className={ICON_CLASS} aria-hidden />,
};
return registry[key] ?? null;
};
export const getPaymentMethodIcon = (paymentMethod: string): ReactNode => {
const key = normalizeKey(paymentMethod);
const registry: Record<string, ReactNode> = {
dinheiro: (
<RemixIcons.RiMoneyDollarCircleLine className={ICON_CLASS} aria-hidden />
),
pix: <RemixIcons.RiPixLine className={ICON_CLASS} aria-hidden />,
boleto: <RemixIcons.RiBarcodeLine className={ICON_CLASS} aria-hidden />,
credito: (
<RemixIcons.RiMoneyDollarCircleLine className={ICON_CLASS} aria-hidden />
),
cartaodecredito: (
<RemixIcons.RiBankCardLine className={ICON_CLASS} aria-hidden />
),
cartaodedebito: (
<RemixIcons.RiBankCardLine className={ICON_CLASS} aria-hidden />
),
debito: <RemixIcons.RiBankCardLine className={ICON_CLASS} aria-hidden />,
};
return registry[key] ?? null;
};

51
lib/utils/math.ts Normal file
View File

@@ -0,0 +1,51 @@
/**
* Utility functions for mathematical calculations
*/
/**
* Calculates percentage change between two values
* @param current - Current value
* @param previous - Previous value
* @returns Percentage change or null if previous is 0 and current is also 0
*/
export function calculatePercentageChange(
current: number,
previous: number
): number | null {
const EPSILON = 0.01; // Considera valores menores que 1 centavo como zero
if (Math.abs(previous) < EPSILON) {
if (Math.abs(current) < EPSILON) return null;
return current > 0 ? 100 : -100;
}
const change = ((current - previous) / Math.abs(previous)) * 100;
// Protege contra valores absurdos (retorna null se > 1 milhão %)
return Number.isFinite(change) && Math.abs(change) < 1000000 ? change : null;
}
/**
* Calculates percentage of part relative to total
* @param part - Part value
* @param total - Total value
* @returns Percentage (0-100)
*/
export function calculatePercentage(part: number, total: number): number {
if (total === 0) {
return 0;
}
return (part / total) * 100;
}
/**
* Rounds number to specified decimal places
* @param value - Value to round
* @param decimals - Number of decimal places (default 2)
* @returns Rounded number
*/
export function roundToDecimals(value: number, decimals: number = 2): number {
const multiplier = 10 ** decimals;
return Math.round(value * multiplier) / multiplier;
}

74
lib/utils/number.ts Normal file
View File

@@ -0,0 +1,74 @@
/**
* Utility functions for safe number conversions
*/
/**
* Safely converts unknown value to number
* @param value - Value to convert
* @param defaultValue - Default value if conversion fails
* @returns Converted number or default value
*/
export function safeToNumber(
value: unknown,
defaultValue: number = 0
): number {
if (typeof value === "number") {
return value;
}
if (typeof value === "string") {
const parsed = Number(value);
return Number.isNaN(parsed) ? defaultValue : parsed;
}
if (value === null || value === undefined) {
return defaultValue;
}
const parsed = Number(value);
return Number.isNaN(parsed) ? defaultValue : parsed;
}
/**
* Safely parses integer from unknown value
* @param value - Value to parse
* @param defaultValue - Default value if parsing fails
* @returns Parsed integer or default value
*/
export function safeParseInt(
value: unknown,
defaultValue: number = 0
): number {
if (typeof value === "number") {
return Math.trunc(value);
}
if (typeof value === "string") {
const parsed = Number.parseInt(value, 10);
return Number.isNaN(parsed) ? defaultValue : parsed;
}
return defaultValue;
}
/**
* Safely parses float from unknown value
* @param value - Value to parse
* @param defaultValue - Default value if parsing fails
* @returns Parsed float or default value
*/
export function safeParseFloat(
value: unknown,
defaultValue: number = 0
): number {
if (typeof value === "number") {
return value;
}
if (typeof value === "string") {
const parsed = Number.parseFloat(value);
return Number.isNaN(parsed) ? defaultValue : parsed;
}
return defaultValue;
}

381
lib/utils/period/index.ts Normal file
View File

@@ -0,0 +1,381 @@
/**
* Period utilities - Consolidated module for period (YYYY-MM) manipulation
*
* This module consolidates period-related functionality from:
* - /lib/month-period.ts (URL param handling)
* - /lib/period/index.ts (YYYY-MM operations)
* - /hooks/use-dates.ts (month navigation)
* - /lib/lancamentos/period-helpers.ts (formatting)
*
* Moved from /lib/period to /lib/utils/period for better organization
*/
// ============================================================================
// CONSTANTS
// ============================================================================
export const MONTH_NAMES = [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro",
] as const;
export type MonthName = (typeof MONTH_NAMES)[number];
// ============================================================================
// CORE PARSING & FORMATTING (YYYY-MM format)
// ============================================================================
/**
* Parses period string into year and month
* @param period - Period string in YYYY-MM format
* @returns Object with year and month numbers
* @throws Error if period format is invalid
*/
export function parsePeriod(period: string): { year: number; month: number } {
const [yearStr, monthStr] = period.split("-");
const year = Number.parseInt(yearStr ?? "", 10);
const month = Number.parseInt(monthStr ?? "", 10);
if (Number.isNaN(year) || Number.isNaN(month) || month < 1 || month > 12) {
throw new Error(`Período inválido: ${period}`);
}
return { year, month };
}
/**
* Formats year and month into period string
* @param year - Year number
* @param month - Month number (1-12)
* @returns Period string in YYYY-MM format
*/
export function formatPeriod(year: number, month: number): string {
return `${year}-${String(month).padStart(2, "0")}`;
}
/**
* Validates if period string is valid
* @param period - Period string to validate
* @returns True if valid, false otherwise
*/
export function isPeriodValid(period: string): boolean {
try {
parsePeriod(period);
return true;
} catch {
return false;
}
}
// ============================================================================
// PERIOD NAVIGATION
// ============================================================================
/**
* Returns the current period in YYYY-MM format
* @example
* getCurrentPeriod() // "2025-11"
*/
export function getCurrentPeriod(): string {
const now = new Date();
return formatPeriod(now.getFullYear(), now.getMonth() + 1);
}
/**
* Gets the previous period
* @param period - Current period in YYYY-MM format
* @returns Previous period string
*/
export function getPreviousPeriod(period: string): string {
const { year, month } = parsePeriod(period);
if (month === 1) {
return formatPeriod(year - 1, 12);
}
return formatPeriod(year, month - 1);
}
/**
* Gets the next period
* @param period - Current period in YYYY-MM format
* @returns Next period string
*/
export function getNextPeriod(period: string): string {
const { year, month } = parsePeriod(period);
if (month === 12) {
return formatPeriod(year + 1, 1);
}
return formatPeriod(year, month + 1);
}
/**
* Adds months to a period
* @param period - Period string in YYYY-MM format
* @param offset - Number of months to add (can be negative)
* @returns New period string
*/
export function addMonthsToPeriod(period: string, offset: number): string {
const { year: baseYear, month: baseMonth } = parsePeriod(period);
const date = new Date(baseYear, baseMonth - 1, 1);
date.setMonth(date.getMonth() + offset);
const nextYear = date.getFullYear();
const nextMonth = date.getMonth() + 1;
return formatPeriod(nextYear, nextMonth);
}
/**
* Gets the last N periods including the current one
* @param current - Current period in YYYY-MM format
* @param length - Number of periods to return
* @returns Array of period strings
*/
export function getLastPeriods(current: string, length: number): string[] {
const periods: string[] = [];
for (let offset = length - 1; offset >= 0; offset -= 1) {
periods.push(addMonthsToPeriod(current, -offset));
}
return periods;
}
// ============================================================================
// PERIOD COMPARISON & RANGES
// ============================================================================
/**
* Compares two periods
* @param a - First period
* @param b - Second period
* @returns -1 if a < b, 0 if equal, 1 if a > b
*/
export function comparePeriods(a: string, b: string): number {
if (a === b) return 0;
return a < b ? -1 : 1;
}
/**
* Builds a range of periods between start and end (inclusive)
* @param start - Start period
* @param end - End period
* @returns Array of period strings
*/
export function buildPeriodRange(start: string, end: string): string[] {
const [startKey, endKey] =
comparePeriods(start, end) <= 0 ? [start, end] : [end, start];
const startParts = parsePeriod(startKey);
const endParts = parsePeriod(endKey);
const items: string[] = [];
let currentYear = startParts.year;
let currentMonth = startParts.month;
while (
currentYear < endParts.year ||
(currentYear === endParts.year && currentMonth <= endParts.month)
) {
items.push(formatPeriod(currentYear, currentMonth));
if (currentYear === endParts.year && currentMonth === endParts.month) {
break;
}
currentMonth += 1;
if (currentMonth > 12) {
currentMonth = 1;
currentYear += 1;
}
}
return items;
}
// ============================================================================
// URL PARAM HANDLING (mes-ano format for Portuguese URLs)
// ============================================================================
const MONTH_MAP = new Map(MONTH_NAMES.map((name, index) => [name, index]));
const normalize = (value: string | null | undefined) =>
(value ?? "").trim().toLowerCase();
export type ParsedPeriod = {
period: string;
monthName: string;
year: number;
};
/**
* Parses URL param in "mes-ano" format (e.g., "novembro-2025")
* @param periodParam - URL parameter string
* @param referenceDate - Fallback date if param is invalid
* @returns Parsed period object
*/
export function parsePeriodParam(
periodParam: string | null | undefined,
referenceDate = new Date()
): ParsedPeriod {
const fallbackMonthIndex = referenceDate.getMonth();
const fallbackYear = referenceDate.getFullYear();
const fallbackPeriod = formatPeriod(fallbackYear, fallbackMonthIndex + 1);
if (!periodParam) {
const monthName = MONTH_NAMES[fallbackMonthIndex];
return { period: fallbackPeriod, monthName, year: fallbackYear };
}
const [rawMonth, rawYear] = periodParam.split("-");
const normalizedMonth = normalize(rawMonth);
const monthIndex = MONTH_MAP.get(normalizedMonth);
const parsedYear = Number.parseInt(rawYear ?? "", 10);
if (monthIndex === undefined || Number.isNaN(parsedYear)) {
const monthName = MONTH_NAMES[fallbackMonthIndex];
return { period: fallbackPeriod, monthName, year: fallbackYear };
}
const monthName = MONTH_NAMES[monthIndex];
return {
period: formatPeriod(parsedYear, monthIndex + 1),
monthName,
year: parsedYear,
};
}
/**
* Formats month name and year to URL param format
* @param monthName - Month name in Portuguese
* @param year - Year number
* @returns URL param string in "mes-ano" format
*/
export function formatPeriodParam(monthName: string, year: number): string {
return `${normalize(monthName)}-${year}`;
}
/**
* Converts period from YYYY-MM format to URL param format
* @example
* formatPeriodForUrl("2025-11") // "novembro-2025"
* formatPeriodForUrl("2025-01") // "janeiro-2025"
*/
export function formatPeriodForUrl(period: string): string {
const [yearStr, monthStr] = period.split("-");
const year = Number.parseInt(yearStr ?? "", 10);
const monthIndex = Number.parseInt(monthStr ?? "", 10) - 1;
if (
Number.isNaN(year) ||
Number.isNaN(monthIndex) ||
monthIndex < 0 ||
monthIndex > 11
) {
return period;
}
const monthName = MONTH_NAMES[monthIndex] ?? "";
return formatPeriodParam(monthName, year);
}
// ============================================================================
// DISPLAY FORMATTING
// ============================================================================
function capitalize(value: string): string {
return value.length > 0
? value[0]?.toUpperCase().concat(value.slice(1))
: value;
}
/**
* Formats period for display in Portuguese
* @example
* displayPeriod("2025-11") // "Novembro de 2025"
*/
export function displayPeriod(period: string): string {
const { year, month } = parsePeriod(period);
const monthName = MONTH_NAMES[month - 1] ?? "";
return `${capitalize(monthName)} de ${year}`;
}
/**
* Alias for displayPeriod - formats period for display
* @example
* formatMonthLabel("2024-01") // "Janeiro de 2024"
*/
export function formatMonthLabel(period: string): string {
return displayPeriod(period);
}
// ============================================================================
// DATE DERIVATION
// ============================================================================
/**
* Derives a period (YYYY-MM) from a date string or current date
* @example
* derivePeriodFromDate("2024-01-15") // "2024-01"
* derivePeriodFromDate() // current period
*/
export function derivePeriodFromDate(value?: string | null): string {
const date = value ? new Date(value) : new Date();
if (Number.isNaN(date.getTime())) {
return getCurrentPeriod();
}
return formatPeriod(date.getFullYear(), date.getMonth() + 1);
}
// ============================================================================
// SELECT OPTIONS GENERATION
// ============================================================================
export type SelectOption = {
value: string;
label: string;
};
/**
* Creates month options for a select dropdown, centered around current month
* @param currentValue - Current period value to ensure it's included in options
* @param offsetRange - Number of months before/after current month (default: 3)
* @returns Array of select options with formatted labels
*/
export function createMonthOptions(
currentValue?: string,
offsetRange: number = 3
): SelectOption[] {
const now = new Date();
const options: SelectOption[] = [];
for (let offset = -offsetRange; offset <= offsetRange; offset += 1) {
const date = new Date(now.getFullYear(), now.getMonth() + offset, 1);
const value = formatPeriod(date.getFullYear(), date.getMonth() + 1);
options.push({ value, label: displayPeriod(value) });
}
// Include current value if not already in options
if (currentValue && !options.some((option) => option.value === currentValue)) {
options.push({
value: currentValue,
label: displayPeriod(currentValue),
});
}
return options.sort((a, b) => a.value.localeCompare(b.value));
}

43
lib/utils/string.ts Normal file
View File

@@ -0,0 +1,43 @@
/**
* Utility functions for string normalization and manipulation
*/
/**
* Normalizes optional string - trims and returns null if empty
* @param value - String to normalize
* @returns Trimmed string or null if empty
*/
export function normalizeOptionalString(
value: string | null | undefined
): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
/**
* Normalizes file path by extracting filename
* @param path - File path to normalize
* @returns Filename without path
*/
export function normalizeFilePath(path: string | null | undefined): string {
return path?.split("/").filter(Boolean).pop() ?? "";
}
/**
* Normalizes whitespace in string (replaces multiple spaces with single space)
* @param value - String to normalize
* @returns String with normalized whitespace
*/
export function normalizeWhitespace(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
/**
* Normalizes icon input - trims and returns null if empty
* @param icon - Icon string to normalize
* @returns Trimmed icon string or null
*/
export function normalizeIconInput(icon?: string | null): string | null {
const trimmed = icon?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}

17
lib/utils/ui.ts Normal file
View File

@@ -0,0 +1,17 @@
/**
* UI utilities - Functions for UI manipulation and styling
*
* This module contains UI-related utilities, primarily for className manipulation.
*/
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merges Tailwind CSS classes with proper override handling
* @param inputs - Class values to merge
* @returns Merged className string
*/
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}