Skip to content

Commit

Permalink
chore: add new rules to eslint cfg
Browse files Browse the repository at this point in the history
  • Loading branch information
uigywnkiub committed Dec 23, 2024
1 parent fb378df commit 3011a69
Show file tree
Hide file tree
Showing 15 changed files with 73 additions and 3 deletions.
18 changes: 18 additions & 0 deletions app/lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import type {
export const getAuthSession = async (): Promise<TSession> => {
try {
const session = await auth()

return session
} catch (err) {
throw err
Expand Down Expand Up @@ -72,13 +73,16 @@ export async function getBalance(
] as TBalanceProjection).lean<TBalance[]>({
transform: (doc: TRawTransaction) => {
delete doc?._id

return doc
},
})
const balance = transactions.reduce((acc, t) => {
const amount = parseFloat(t.amount)

return t.isIncome ? acc + amount : acc - amount
}, 0)

return balance.toString()
} catch (err) {
throw err
Expand All @@ -98,6 +102,7 @@ export async function getTransactionLimit(
{ userId },
{ transactionLimit: 1, _id: 0 },
).lean<{ transactionLimit: TTransaction['transactionLimit'] }>()

return transaction?.transactionLimit
} catch (err) {
throw err
Expand All @@ -117,6 +122,7 @@ export async function getCurrency(
{ userId },
{ currency: 1, _id: 0 },
).lean<{ currency: TTransaction['currency'] }>()

return transaction?.currency
} catch (err) {
throw err
Expand Down Expand Up @@ -267,6 +273,7 @@ export async function getCountDocuments(
}
try {
await dbConnect()

return await TransactionModel.countDocuments({ userId })
} catch (err) {
throw err
Expand All @@ -293,12 +300,14 @@ export async function getTransactions(
transform: (doc: TRawTransaction) => {
delete doc?._id
delete doc?.__v

return doc
},
}),
getCountDocuments(userId),
])
const totalPages = Math.ceil(totalEntries / limit)

return { transactions, totalEntries, totalPages }
} catch (err) {
throw err
Expand All @@ -314,10 +323,12 @@ export async function getAllTransactions(
}
try {
await dbConnect()

return TransactionModel.find({ userId }).lean<TTransaction[]>({
transform: (doc: TRawTransaction) => {
delete doc?._id
delete doc?.__v

return doc
},
})
Expand Down Expand Up @@ -458,9 +469,11 @@ export async function findTransactionById(
transform: (doc: TRawTransaction) => {
delete doc?._id
delete doc?.__v

return doc
},
})

return transaction
} catch (err) {
throw err
Expand Down Expand Up @@ -560,6 +573,7 @@ export async function editCategoryLimit(
limitAmount: newLimitAmount,
}
}

return limit
},
)
Expand Down Expand Up @@ -588,6 +602,7 @@ export async function getCategoryItemNameAI(

const content = await CompletionAIModel.generateContent(prompt)
const text = content.response.text().trim()

return text
} catch (err) {
throw err
Expand All @@ -608,6 +623,7 @@ export async function getAmountAI(

const content = await CompletionAIModel.generateContent(prompt)
const text = content.response.text().trim()

return text
} catch (err) {
throw err
Expand All @@ -627,6 +643,7 @@ export async function getTransactionTypeAI(

const content = await CompletionAIModel.generateContent(prompt)
const text = content.response.text().trim()

return text
} catch (err) {
throw err
Expand All @@ -646,6 +663,7 @@ export async function getExpenseTipsAI(categories: string[]): Promise<string> {

const content = await ExpenseTipsAIModel.generateContent(prompt)
const text = content.response.text().trim()

return text
} catch (err) {
throw err
Expand Down
6 changes: 6 additions & 0 deletions app/lib/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const filterTransactions = (transactions: TTransaction[]) => ({

export const getTransactionsTotals = (transactions: TTransaction[]) => {
const { income, expense } = filterTransactions(transactions)

return {
income: calculateTotalAmount(income),
expense: calculateTotalAmount(expense),
Expand All @@ -38,6 +39,7 @@ export const calculateChartData = (
t.category,
(totals.get(t.category) || 0) + parseFloat(t.amount),
)

return totals
}, new Map<string, number>())

Expand All @@ -52,6 +54,7 @@ export const calculateChartData = (
const chartData: TChartData[] = Array.from(allCategories).map((category) => {
const expense = categoryExpenseTotals.get(category) || 0
const income = categoryIncomeTotals.get(category) || 0

return {
category,
income,
Expand All @@ -73,6 +76,7 @@ export const calculateTotalsByCategory = (
: category
totals[modifiedCategory] =
(totals[modifiedCategory] || 0) + parseFloat(amount)

return totals
},
{} as Record<string, number>,
Expand Down Expand Up @@ -117,6 +121,7 @@ export const filterTransactionsByDateRange = (
): TTransaction[] => {
return transactions.filter((t) => {
const transactionDate = formatISO(t.createdAt)

return isWithinInterval(transactionDate, {
start: startDate,
end: endOfDay(endDate),
Expand All @@ -141,6 +146,7 @@ export const getMinMaxTransactionsByDate = (
) {
acc.maxTransaction = transaction
}

return acc
},
{ minTransaction: null, maxTransaction: null },
Expand Down
13 changes: 13 additions & 0 deletions app/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const getBreakpointWidth = (

export const capitalizeFirstLetter = (str: string): string => {
if (!str) return str

return str.charAt(0).toUpperCase() + str.slice(1)
}

Expand All @@ -61,13 +62,15 @@ export const getEmojiFromCategory = (
): string => {
const regex = emojiRegex()
const match = category.match(regex)

return match ? match[0] : ''
}

export const getCategoryWithoutEmoji = (
category: TTransaction['category'],
): string => {
const regex = emojiRegex()

// Replace the emoji(s) at the beginning of the category with an empty string
return category.replace(regex, '').trim()
}
Expand Down Expand Up @@ -103,13 +106,15 @@ export const formatDate = (dateStr: Date) => {
if (isToday(date)) return 'Today'
if (isYesterday(date)) return 'Yesterday'
if (dateYear !== currentYear) return format(date, 'EEEE, MMMM d, yyyy')

return format(date, 'EEEE, MMMM d')
}

export const formatTime = (dateStr: Date): string => {
const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
const date = new Date(dateStr)
const formatStr = userTimeZone.includes('America') ? 'hh:mm a' : 'HH:mm'

return formatInTimeZone(date, userTimeZone || DEFAULT_TIME_ZONE, formatStr)
}

Expand All @@ -132,6 +137,7 @@ export const getCategoryWithEmoji = (
return `${foundCategory.emoji} ${category}`
}
}

return category
}

Expand All @@ -156,11 +162,13 @@ export const getFormattedCurrency = (
if (isAmountHidden) return '*'.repeat(numericValue.toString().length)

const formattedNumber = new Intl.NumberFormat('de-DE').format(numericValue)

return formattedNumber.replace(/\./g, ' ')
}

export const getFormattedBalance = (balance: TTransaction['balance']) => {
const formattedCurrency = getFormattedCurrency(balance)

return Number(balance) < 0
? `- ${formattedCurrency.slice(1)}`
: formattedCurrency
Expand All @@ -171,6 +179,7 @@ export const formatAmount = (value: string): string => {
?.replace(/\s/g, '')
?.replace(',', '.')
?.replace(/^0+/, '')

return rawAmount
}

Expand All @@ -184,6 +193,7 @@ export const calculateEntryRange = (
const parsedTotalEntries = toNumber(totalEntries)
const startEntry = (parsedPage - 1) * parsedLimit + 1
const endEntry = Math.min(parsedPage * parsedLimit, parsedTotalEntries)

return { startEntry, endEntry }
}

Expand All @@ -197,6 +207,7 @@ export const copyToClipboard = async (

if (!content) {
toast.error(errorTitle)

return
}
try {
Expand Down Expand Up @@ -280,6 +291,7 @@ export const pluralize = (
): string => {
const pluralRules = new Intl.PluralRules(DEFAULT_LANG)
const pluralCategory = pluralRules.select(count)

return pluralCategory === 'one' || pluralCategory === 'zero' || count === 0
? singular
: plural
Expand Down Expand Up @@ -307,6 +319,7 @@ export const getCategoryItemNames = (
categories: TTransaction['categories'],
) => {
if (!categories) return []

return categories
.flatMap((subject) => subject.items.map((item) => item.name))
.filter(Boolean) // Remove empty strings
Expand Down
3 changes: 3 additions & 0 deletions app/lib/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,17 @@ const useAttemptTracker = (
// Reset attempts if attemptResetInterval or ATTEMPT_RESET_INTERVAL number value have passed.
if (currentTime - lastAttemptTime > attemptResetInterval) {
resetAttempts()

return true
}

return count < attemptLimit
}, [attemptLimit, attemptResetInterval, attemptsData, resetAttempts])

const registerAttempt = useCallback(() => {
if (!attemptsData) {
setAttemptsData({ count: 1, lastAttemptTime: Date.now() })

return
}
const { count } = attemptsData
Expand Down
3 changes: 3 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export default async function Home(props: {
acc[date] = []
}
acc[date].unshift(t)

return acc
}, {})

Expand All @@ -119,10 +120,12 @@ export default async function Home(props: {
} else {
totals.expense += parseFloat(t.amount)
}

return totals
},
{ income: 0, expense: 0 },
)

return [date, totals]
}),
)
Expand Down
2 changes: 2 additions & 0 deletions app/ui/categories/categories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ function Categories({ userId, userCategories }: TProps) {
setEditingIndex(null)
setNewTargetName('')
toast.error('No changes detected.')

return
}

Expand Down Expand Up @@ -141,6 +142,7 @@ function Categories({ userId, userCategories }: TProps) {
setEditingItemIndex(null)
setNewItemName('')
toast.error('No changes detected.')

return
}

Expand Down
2 changes: 2 additions & 0 deletions app/ui/home/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export default function Search({ hasSearchedTransactionsByQuery }: TProps) {
if (newState) {
isInitialExpanded.current = true
}

return newState
})
}
Expand All @@ -64,6 +65,7 @@ export default function Search({ hasSearchedTransactionsByQuery }: TProps) {
// Skip the first render
if (isInitialRender.current) {
isInitialRender.current = false

return
}

Expand Down
1 change: 1 addition & 0 deletions app/ui/home/transaction-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ function TransactionForm({ currency, userCategories }: TProps) {
): Promise<UseDebounceReturn | undefined> => {
if (!trimmedDescription) {
resetAIRelatedStates()

return [() => null, () => undefined]
}

Expand Down
1 change: 1 addition & 0 deletions app/ui/home/transaction-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ function TransactionList({
?.sort((t1, t2) => {
const t1Time = new Date(t1.createdAt).getTime()
const t2Time = new Date(t2.createdAt).getTime()

return t2Time - t1Time
})
.map((t) => {
Expand Down
5 changes: 5 additions & 0 deletions app/ui/limits/limits.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ function Limits({ userId, currency, transactions, userCategories }: TProps) {

const getLimitAmount = (categoryName: string) => {
const limit = userLimitsData.find((l) => l.categoryName === categoryName)

return limit ? limit.limitAmount : null
}

Expand Down Expand Up @@ -209,6 +210,7 @@ function Limits({ userId, currency, transactions, userCategories }: TProps) {
) => {
if (!categoryName) {
toast.error('Invalid category name.')

return
}
setIsLoadingDelete(true)
Expand Down Expand Up @@ -245,14 +247,17 @@ function Limits({ userId, currency, transactions, userCategories }: TProps) {
) => {
if (!categoryName) {
toast.error('Invalid category name.')

return
}
if (!limitAmount) {
toast.error('Invalid limit amount.')

return
}
if (limitAmount === tempLimitAmount) {
toast.error('Limit amount is the same.')

return
}
setIsLoadingEdit(true)
Expand Down
Loading

0 comments on commit 3011a69

Please sign in to comment.