Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to write math expression in amount field #184

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion messages/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@
"label": "Amount"
},
"isReimbursementField": {
"label": "This is a reimbursement"
"label": "Reimbursement"
},
"categoryField": {
"label": "Category"
Expand Down
13 changes: 9 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"dayjs": "^1.11.10",
"embla-carousel-react": "^8.0.0-rc21",
"lucide-react": "^0.290.0",
"math-expression-evaluator": "^2.0.5",
"nanoid": "^5.0.4",
"negotiator": "^0.6.3",
"next": "^14.2.5",
Expand Down
66 changes: 43 additions & 23 deletions src/components/expense-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
import { cn } from '@/lib/utils'
import { zodResolver } from '@hookform/resolvers/zod'
import { Save } from 'lucide-react'
import Mexp from 'math-expression-evaluator'
import { useTranslations } from 'next-intl'
import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
Expand All @@ -54,6 +55,8 @@ import { DeletePopup } from './delete-popup'
import { extractCategoryFromTitle } from './expense-form-actions'
import { Textarea } from './ui/textarea'

const mexp = new Mexp()

export type Props = {
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
expense?: NonNullable<Awaited<ReturnType<typeof getExpense>>>
Expand Down Expand Up @@ -244,6 +247,7 @@ export function ExpenseForm({
}

const [isIncome, setIsIncome] = useState(Number(form.getValues().amount) < 0)
const [evaluatedAmount, setEvaluatedAmount] = useState('0')
const [manuallyEditedParticipants, setManuallyEditedParticipants] = useState<
Set<string>
>(new Set())
Expand Down Expand Up @@ -392,15 +396,28 @@ export function ExpenseForm({
<span>{group.currency}</span>
<FormControl>
<Input
className="text-base max-w-[120px]"
className="text-base"
type="text"
inputMode="decimal"
placeholder="0.00"
onChange={(event) => {
const v = enforceCurrencyPattern(event.target.value)
const income = Number(v) < 0
setIsIncome(income)
if (income) form.setValue('isReimbursement', false)
let v = event.target.value
if (v === '') {
setEvaluatedAmount('0')
} else {
try {
const evaluatedValue = Number(mexp.eval(v))
.toFixed(2)
.replace(/\.?0+$/, '') // replace trailing zeros
setEvaluatedAmount(evaluatedValue)
const income = Number(evaluatedValue) < 0
setIsIncome(income)
if (income)
form.setValue('isReimbursement', false)
} catch {
setEvaluatedAmount('Invalid Expression')
}
}
onChange(v)
}}
onFocus={(e) => {
Expand All @@ -414,27 +431,30 @@ export function ExpenseForm({
</div>
<FormMessage />

{!isIncome && (
<FormField
control={form.control}
name="isReimbursement"
render={({ field }) => (
<FormItem className="flex flex-row gap-2 items-center space-y-0 pt-2">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div>
<div className="flex flex-row gap-2 items-center justify-between">
<div className="text-white/50 pl-5">
{' = ' + evaluatedAmount}
</div>
{!isIncome && (
<FormField
control={form.control}
name="isReimbursement"
render={({ field }) => (
<FormItem className="flex flex-row gap-2 items-center space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<FormLabel>
{t('isReimbursementField.label')}
</FormLabel>
</div>
</FormItem>
)}
/>
)}
</FormItem>
)}
/>
)}
</div>
</FormItem>
)}
/>
Expand Down
26 changes: 19 additions & 7 deletions src/lib/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { SplitMode } from '@prisma/client'
import Mexp from 'math-expression-evaluator'
import * as z from 'zod'

const mexp = new Mexp()

export const groupFormSchema = z
.object({
name: z.string().min(2, 'min2').max(50, 'max50'),
Expand Down Expand Up @@ -41,13 +44,22 @@ export const expenseFormSchema = z
[
z.number(),
z.string().transform((value, ctx) => {
const valueAsNumber = Number(value)
if (Number.isNaN(valueAsNumber))
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'invalidNumber',
})
return Math.round(valueAsNumber * 100)
let valueAsNumber = NaN
try {
valueAsNumber = Number(
mexp
.eval(value)
.toFixed(2)
.replace(/\.?0+$/, ''), // replace trailing zeros
)
} finally {
if (Number.isNaN(valueAsNumber))
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Invalid number.',
})
return Math.round(valueAsNumber * 100)
}
}),
],
{ required_error: 'amountRequired' },
Expand Down