Refactor inventory forms to include unit and location options; update quantity input handling
This commit is contained in:
@@ -38,10 +38,12 @@ export default function InventoryConsumeForm({ id, unit }: Props) {
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
|
||||
const form = e.currentTarget;
|
||||
const formData = new FormData(form);
|
||||
|
||||
const raw = formData.get('amountUsed') as string;
|
||||
const { quantity, unit: parsedUnit } = parseQuantityInput(raw, unit);
|
||||
formData.set('amountUsed', String(quantity));
|
||||
formData.set('unit', parsedUnit);
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await consumeInventoryItem(formData);
|
||||
@@ -67,9 +69,7 @@ export default function InventoryConsumeForm({ id, unit }: Props) {
|
||||
<br />
|
||||
<input
|
||||
name="amountUsed"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
type="text"
|
||||
required
|
||||
style={{ width: '100%', padding: '0.5rem' }}
|
||||
/>
|
||||
@@ -109,4 +109,15 @@ export default function InventoryConsumeForm({ id, unit }: Props) {
|
||||
{error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function parseQuantityInput(input: string, defaultUnit: string) {
|
||||
const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
|
||||
if (!match) return { quantity: NaN, unit: defaultUnit };
|
||||
let [, num, unit] = match;
|
||||
num = num.replace(',', '.');
|
||||
unit = unit || defaultUnit;
|
||||
if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
|
||||
if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
|
||||
return { quantity: parseFloat(num), unit };
|
||||
}
|
||||
Reference in New Issue
Block a user