mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-04-17 18:24:10 +00:00
Phase 1: TypeScript foundation in scripts-v2/
Create the complete TypeScript foundation for the Vue 3 migration in a parallel scripts-v2/ directory. 72 files, 5430 lines, zero any types, strict mode. - types/ (21 files): Domain interfaces for all 17 entities derived from actual Laravel models and API resources. Enums for all statuses. Generic API response wrappers. - api/ (29 files): Typed axios client with interceptors, endpoint constants from routes/api.php, 25 typed service classes covering every API endpoint. - composables/ (14 files): Vue 3 composition functions for auth, notifications, dialogs, modals, pagination, filters, currency, dates, theme, sidebar, company context, and permissions. - utils/ (5 files): Pure typed utilities for money formatting, date formatting (date-fns), localStorage, and error handling. - config/ (3 files): Typed ability constants, app constants. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
165
resources/scripts-v2/utils/error-handling.ts
Normal file
165
resources/scripts-v2/utils/error-handling.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import type { ApiError } from '../types/api'
|
||||
|
||||
/**
|
||||
* Shape of an Axios-like error response.
|
||||
*/
|
||||
interface AxiosLikeError {
|
||||
response?: {
|
||||
status?: number
|
||||
statusText?: string
|
||||
data?: {
|
||||
message?: string
|
||||
error?: string | boolean
|
||||
errors?: Record<string, string[]>
|
||||
}
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized API error result.
|
||||
*/
|
||||
export interface NormalizedApiError {
|
||||
message: string
|
||||
statusCode: number | null
|
||||
validationErrors: Record<string, string[]>
|
||||
isUnauthorized: boolean
|
||||
isValidationError: boolean
|
||||
isNetworkError: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Known error message to translation key map.
|
||||
*/
|
||||
const ERROR_TRANSLATION_MAP: Record<string, string> = {
|
||||
'These credentials do not match our records.': 'errors.login_invalid_credentials',
|
||||
'invalid_key': 'errors.invalid_provider_key',
|
||||
'This feature is available on Starter plan and onwards!': 'errors.starter_plan',
|
||||
'taxes_attached': 'settings.tax_types.already_in_use',
|
||||
'expense_attached': 'settings.expense_category.already_in_use',
|
||||
'payments_attached': 'settings.payment_modes.payments_attached',
|
||||
'expenses_attached': 'settings.payment_modes.expenses_attached',
|
||||
'role_attached_to_users': 'settings.roles.already_in_use',
|
||||
'items_attached': 'settings.customization.items.already_in_use',
|
||||
'payment_attached_message': 'invoices.payment_attached_message',
|
||||
'The email has already been taken.': 'validation.email_already_taken',
|
||||
'Relation estimateItems exists.': 'items.item_attached_message',
|
||||
'Relation invoiceItems exists.': 'items.item_attached_message',
|
||||
'Relation taxes exists.': 'settings.tax_types.already_in_use',
|
||||
'Relation payments exists.': 'errors.payment_attached',
|
||||
'The estimate number has already been taken.': 'errors.estimate_number_used',
|
||||
'The payment number has already been taken.': 'errors.estimate_number_used',
|
||||
'The invoice number has already been taken.': 'errors.invoice_number_used',
|
||||
'The name has already been taken.': 'errors.name_already_taken',
|
||||
'total_invoice_amount_must_be_more_than_paid_amount': 'invoices.invalid_due_amount_message',
|
||||
'you_cannot_edit_currency': 'customers.edit_currency_not_allowed',
|
||||
'receipt_does_not_exist': 'errors.receipt_does_not_exist',
|
||||
'customer_cannot_be_changed_after_payment_is_added': 'errors.customer_cannot_be_changed_after_payment_is_added',
|
||||
'invalid_credentials': 'errors.invalid_credentials',
|
||||
'not_allowed': 'errors.not_allowed',
|
||||
'invalid_state': 'errors.invalid_state',
|
||||
'invalid_city': 'errors.invalid_city',
|
||||
'invalid_postal_code': 'errors.invalid_postal_code',
|
||||
'invalid_format': 'errors.invalid_format',
|
||||
'api_error': 'errors.api_error',
|
||||
'feature_not_enabled': 'errors.feature_not_enabled',
|
||||
'request_limit_met': 'errors.request_limit_met',
|
||||
'address_incomplete': 'errors.address_incomplete',
|
||||
'invalid_address': 'errors.invalid_address',
|
||||
'Email could not be sent to this email address.': 'errors.email_could_not_be_sent',
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an API error and return a normalized error object.
|
||||
*
|
||||
* @param err - The error from an API call (typically an Axios error)
|
||||
* @returns A normalized error with extracted message, status, and validation errors
|
||||
*/
|
||||
export function handleApiError(err: unknown): NormalizedApiError {
|
||||
const axiosError = err as AxiosLikeError
|
||||
|
||||
if (!axiosError.response) {
|
||||
return {
|
||||
message: 'Please check your internet connection or wait until servers are back online.',
|
||||
statusCode: null,
|
||||
validationErrors: {},
|
||||
isUnauthorized: false,
|
||||
isValidationError: false,
|
||||
isNetworkError: true,
|
||||
}
|
||||
}
|
||||
|
||||
const { response } = axiosError
|
||||
const statusCode = response.status ?? null
|
||||
const isUnauthorized =
|
||||
response.statusText === 'Unauthorized' ||
|
||||
response.data?.message === ' Unauthorized.' ||
|
||||
statusCode === 401
|
||||
|
||||
if (isUnauthorized) {
|
||||
const message = response.data?.message ?? 'Unauthorized'
|
||||
return {
|
||||
message,
|
||||
statusCode,
|
||||
validationErrors: {},
|
||||
isUnauthorized: true,
|
||||
isValidationError: false,
|
||||
isNetworkError: false,
|
||||
}
|
||||
}
|
||||
|
||||
const validationErrors = response.data?.errors ?? {}
|
||||
const isValidationError = Object.keys(validationErrors).length > 0
|
||||
|
||||
if (isValidationError) {
|
||||
const firstErrorKey = Object.keys(validationErrors)[0]
|
||||
const firstErrorMessage = validationErrors[firstErrorKey]?.[0] ?? 'Validation error'
|
||||
return {
|
||||
message: firstErrorMessage,
|
||||
statusCode,
|
||||
validationErrors,
|
||||
isUnauthorized: false,
|
||||
isValidationError: true,
|
||||
isNetworkError: false,
|
||||
}
|
||||
}
|
||||
|
||||
const errorField = response.data?.error
|
||||
let message: string
|
||||
|
||||
if (typeof errorField === 'string') {
|
||||
message = errorField
|
||||
} else {
|
||||
message = response.data?.message ?? 'An unexpected error occurred'
|
||||
}
|
||||
|
||||
return {
|
||||
message,
|
||||
statusCode,
|
||||
validationErrors: {},
|
||||
isUnauthorized: false,
|
||||
isValidationError: false,
|
||||
isNetworkError: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract validation errors from an API error response.
|
||||
*
|
||||
* @param err - The error from an API call
|
||||
* @returns A record mapping field names to arrays of error messages
|
||||
*/
|
||||
export function extractValidationErrors(err: unknown): Record<string, string[]> {
|
||||
const axiosError = err as AxiosLikeError
|
||||
return axiosError.response?.data?.errors ?? {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the translation key for a known error message.
|
||||
*
|
||||
* @param errorMessage - The raw error message
|
||||
* @returns The translation key if known, or null if not mapped
|
||||
*/
|
||||
export function getErrorTranslationKey(errorMessage: string): string | null {
|
||||
return ERROR_TRANSLATION_MAP[errorMessage] ?? null
|
||||
}
|
||||
105
resources/scripts-v2/utils/format-date.ts
Normal file
105
resources/scripts-v2/utils/format-date.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { format, formatDistanceToNow, parseISO, isValid } from 'date-fns'
|
||||
import type { Locale } from 'date-fns'
|
||||
|
||||
/**
|
||||
* Default date format used across the application.
|
||||
*/
|
||||
export const DEFAULT_DATE_FORMAT = 'yyyy-MM-dd'
|
||||
|
||||
/**
|
||||
* Default datetime format used across the application.
|
||||
*/
|
||||
export const DEFAULT_DATETIME_FORMAT = 'yyyy-MM-dd HH:mm:ss'
|
||||
|
||||
/**
|
||||
* Format a date value into a string using the given format pattern.
|
||||
*
|
||||
* @param date - A Date object, ISO string, or timestamp
|
||||
* @param formatStr - A date-fns format pattern (default: 'yyyy-MM-dd')
|
||||
* @param options - Optional locale for localized formatting
|
||||
* @returns Formatted date string, or empty string if invalid
|
||||
*/
|
||||
export function formatDate(
|
||||
date: Date | string | number,
|
||||
formatStr: string = DEFAULT_DATE_FORMAT,
|
||||
options?: { locale?: Locale }
|
||||
): string {
|
||||
const parsed = normalizeDate(date)
|
||||
|
||||
if (!parsed || !isValid(parsed)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return format(parsed, formatStr, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a human-readable relative time string (e.g. "3 days ago").
|
||||
*
|
||||
* @param date - A Date object, ISO string, or timestamp
|
||||
* @param options - Optional settings for suffix and locale
|
||||
* @returns Relative time string, or empty string if invalid
|
||||
*/
|
||||
export function relativeTime(
|
||||
date: Date | string | number,
|
||||
options?: { addSuffix?: boolean; locale?: Locale }
|
||||
): string {
|
||||
const parsed = normalizeDate(date)
|
||||
|
||||
if (!parsed || !isValid(parsed)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return formatDistanceToNow(parsed, {
|
||||
addSuffix: options?.addSuffix ?? true,
|
||||
locale: options?.locale,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a date string or value into a Date object.
|
||||
*
|
||||
* @param date - A Date object, ISO string, or timestamp
|
||||
* @returns A valid Date object, or null if parsing fails
|
||||
*/
|
||||
export function parseDate(date: Date | string | number): Date | null {
|
||||
const parsed = normalizeDate(date)
|
||||
|
||||
if (!parsed || !isValid(parsed)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a given date value is valid.
|
||||
*
|
||||
* @param date - A Date object, ISO string, or timestamp
|
||||
* @returns True if the date is valid
|
||||
*/
|
||||
export function isValidDate(date: Date | string | number): boolean {
|
||||
const parsed = normalizeDate(date)
|
||||
return parsed !== null && isValid(parsed)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize various date input types into a Date object.
|
||||
*/
|
||||
function normalizeDate(date: Date | string | number): Date | null {
|
||||
if (date instanceof Date) {
|
||||
return date
|
||||
}
|
||||
|
||||
if (typeof date === 'string') {
|
||||
const parsed = parseISO(date)
|
||||
return isValid(parsed) ? parsed : null
|
||||
}
|
||||
|
||||
if (typeof date === 'number') {
|
||||
const parsed = new Date(date)
|
||||
return isValid(parsed) ? parsed : null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
96
resources/scripts-v2/utils/format-money.ts
Normal file
96
resources/scripts-v2/utils/format-money.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
export interface CurrencyConfig {
|
||||
precision: number
|
||||
thousand_separator: string
|
||||
decimal_separator: string
|
||||
symbol: string
|
||||
swap_currency_symbol?: boolean
|
||||
}
|
||||
|
||||
const DEFAULT_CURRENCY: CurrencyConfig = {
|
||||
precision: 2,
|
||||
thousand_separator: ',',
|
||||
decimal_separator: '.',
|
||||
symbol: '$',
|
||||
swap_currency_symbol: false,
|
||||
}
|
||||
|
||||
/**
|
||||
* Format an amount in cents to a currency string with symbol and separators.
|
||||
*
|
||||
* @param amountInCents - The amount in cents (e.g. 10050 = $100.50)
|
||||
* @param currency - Currency configuration for formatting
|
||||
* @returns Formatted currency string (e.g. "$ 100.50")
|
||||
*/
|
||||
export function formatMoney(
|
||||
amountInCents: number,
|
||||
currency: CurrencyConfig = DEFAULT_CURRENCY
|
||||
): string {
|
||||
let amount = amountInCents / 100
|
||||
|
||||
const {
|
||||
symbol,
|
||||
swap_currency_symbol = false,
|
||||
} = currency
|
||||
|
||||
let precision = Math.abs(currency.precision)
|
||||
if (Number.isNaN(precision)) {
|
||||
precision = 2
|
||||
}
|
||||
|
||||
const negativeSign = amount < 0 ? '-' : ''
|
||||
amount = Math.abs(Number(amount) || 0)
|
||||
|
||||
const fixedAmount = amount.toFixed(precision)
|
||||
const integerPart = parseInt(fixedAmount, 10).toString()
|
||||
const remainder = integerPart.length > 3 ? integerPart.length % 3 : 0
|
||||
|
||||
const thousandText = remainder
|
||||
? integerPart.substring(0, remainder) + currency.thousand_separator
|
||||
: ''
|
||||
|
||||
const amountText = integerPart
|
||||
.substring(remainder)
|
||||
.replace(/(\d{3})(?=\d)/g, '$1' + currency.thousand_separator)
|
||||
|
||||
const precisionText = precision
|
||||
? currency.decimal_separator +
|
||||
Math.abs(amount - parseInt(fixedAmount, 10))
|
||||
.toFixed(precision)
|
||||
.slice(2)
|
||||
: ''
|
||||
|
||||
const combinedAmountText =
|
||||
negativeSign + thousandText + amountText + precisionText
|
||||
|
||||
const moneySymbol = `${symbol}`
|
||||
|
||||
return swap_currency_symbol
|
||||
? `${combinedAmountText} ${moneySymbol}`
|
||||
: `${moneySymbol} ${combinedAmountText}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a formatted currency string back to cents.
|
||||
*
|
||||
* @param formattedAmount - The formatted string (e.g. "$ 1,234.56")
|
||||
* @param currency - Currency configuration used for parsing
|
||||
* @returns Amount in cents
|
||||
*/
|
||||
export function parseMoneyCents(
|
||||
formattedAmount: string,
|
||||
currency: CurrencyConfig = DEFAULT_CURRENCY
|
||||
): number {
|
||||
const cleaned = formattedAmount
|
||||
.replace(currency.symbol, '')
|
||||
.replace(new RegExp(`\\${currency.thousand_separator}`, 'g'), '')
|
||||
.replace(currency.decimal_separator, '.')
|
||||
.trim()
|
||||
|
||||
const parsed = parseFloat(cleaned)
|
||||
|
||||
if (Number.isNaN(parsed)) {
|
||||
return 0
|
||||
}
|
||||
|
||||
return Math.round(parsed * 100)
|
||||
}
|
||||
29
resources/scripts-v2/utils/index.ts
Normal file
29
resources/scripts-v2/utils/index.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export {
|
||||
formatMoney,
|
||||
parseMoneyCents,
|
||||
} from './format-money'
|
||||
export type { CurrencyConfig } from './format-money'
|
||||
|
||||
export {
|
||||
formatDate,
|
||||
relativeTime,
|
||||
parseDate,
|
||||
isValidDate,
|
||||
DEFAULT_DATE_FORMAT,
|
||||
DEFAULT_DATETIME_FORMAT,
|
||||
} from './format-date'
|
||||
|
||||
export {
|
||||
get as lsGet,
|
||||
set as lsSet,
|
||||
remove as lsRemove,
|
||||
has as lsHas,
|
||||
clear as lsClear,
|
||||
} from './local-storage'
|
||||
|
||||
export {
|
||||
handleApiError,
|
||||
extractValidationErrors,
|
||||
getErrorTranslationKey,
|
||||
} from './error-handling'
|
||||
export type { NormalizedApiError } from './error-handling'
|
||||
66
resources/scripts-v2/utils/local-storage.ts
Normal file
66
resources/scripts-v2/utils/local-storage.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Typed wrapper around localStorage for safe get/set/remove operations.
|
||||
* Handles JSON serialization and deserialization automatically.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Retrieve a value from localStorage, parsed from JSON.
|
||||
*
|
||||
* @param key - The localStorage key
|
||||
* @returns The parsed value, or null if the key does not exist or parsing fails
|
||||
*/
|
||||
export function get<T>(key: string): T | null {
|
||||
const raw = localStorage.getItem(key)
|
||||
|
||||
if (raw === null) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as T
|
||||
} catch {
|
||||
// If parsing fails, return the raw string cast to T.
|
||||
// This handles cases where the value is a plain string not wrapped in quotes.
|
||||
return raw as unknown as T
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a value in localStorage as JSON.
|
||||
*
|
||||
* @param key - The localStorage key
|
||||
* @param value - The value to store (will be JSON-serialized)
|
||||
*/
|
||||
export function set<T>(key: string, value: T): void {
|
||||
if (typeof value === 'string') {
|
||||
localStorage.setItem(key, value)
|
||||
} else {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a key from localStorage.
|
||||
*
|
||||
* @param key - The localStorage key to remove
|
||||
*/
|
||||
export function remove(key: string): void {
|
||||
localStorage.removeItem(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a key exists in localStorage.
|
||||
*
|
||||
* @param key - The localStorage key
|
||||
* @returns True if the key exists
|
||||
*/
|
||||
export function has(key: string): boolean {
|
||||
return localStorage.getItem(key) !== null
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all entries in localStorage.
|
||||
*/
|
||||
export function clear(): void {
|
||||
localStorage.clear()
|
||||
}
|
||||
Reference in New Issue
Block a user