* feat(salary): validate employee clearing/kontonummer at entry Bank details on the "Anställda" form had no structural validation, so a typo in clearing/kontonummer was saved silently and only surfaced at Bankgirot LB generation (or never, on the SEPA path). Adds a shared validator (lib/salary/payment/bank-account.ts) wired into the create dialog, edit page, CreateEmployeeSchema, and the PATCH route: 4-digit clearing or 5-digit Swedbank (8xxxx), 5-11 digit account, both-or-neither. Mirrors encodeReceiverAccount so entry-time validation matches what the payout layer can encode. Update validates only when a bank field actually changes, so legacy free-text data stays editable. Includes a conservative clearing to bank-name hint (null for unknown ranges). Per-bank mod10/mod11 checksum deferred to a soft-warning follow-up. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(chart-of-accounts): styled delete warnings and bulk select-all Replace the native window.confirm() on single-account delete with the styled DestructiveConfirmDialog, and add to the prune dialog a master 'select all unused accounts' checkbox plus an explicit confirmation step before bulk deletion. New sv/en strings for the confirm titles and actions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(salary): encrypt personnummer on v1 employee create; tolerate legacy plaintext on read The v1 REST create route stored personnummer unencrypted, which then threw ERR_CRYPTO_INVALID_AUTH_TAG on every decrypt-on-read path and 500'd the employees roster. Encrypt on write in v1 create, decrypt on read in the v1 list/detail/patch responses, and make decryptPersonnummer pass a raw 12-digit value through with a warn so a legacy plaintext row can't take the roster down. Encrypt seeded personnummer. Add a gated, idempotent backfill for existing rows. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(bookkeeping): save a manual entry as a reusable template Add a "Spara som mall" action to the manual journal-entry form next to the existing "Anvand mall" picker, so users can capture a booking pattern the moment they work it out. Opens the shared TemplateForm (create mode) pre-seeded from the current lines via deriveTemplateLinesFromBooking, and saves through the existing POST /api/settings/booking-templates. Rendered in both the mobile and desktop layouts and in create + edit modes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(pending): label all staged operation types The Granskning list rendered the raw snake_case operation_type (e.g. create_supplier_invoice_from_inbox) for any type missing from the label map, which hogs the meta row and wraps awkwardly on mobile. Add short sv/en labels for all operation types in OPERATION_RISK_TIERS, plus a humanized fallback for future ones, and simplify the label map to a plain operation_type -> i18n-key record (the icon/variant fields were dead). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(reports): let users file moms without a Skatteverket connection The momsdeklaration was never gated on the Skatteverket connection (it renders from the bookkeeping), but the not-connected "Anslut med BankID" card read as a wall. Make manual filing a first-class path: - Add a "Lämna in din momsdeklaration" card under the report with a PDF download (SKV 4700 layout, hela kronor) and a skatteverket.se link. - Add a momsdeklaration PDF route + template; buildManualFilingRows() rounds each ruta to whole kronor and recomputes ruta 49 per the SKV 4700 formula so it ties out. The PDF is a read/record copy, not a submission file (moms has no upload channel). - Offer PDF alongside Excel in the report's export menu. - Reframe the not-connected SkatteverketPanel to "Skicka direkt till Skatteverket (valfritt)". Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(salary): compact new-employee dialog and warn on bad account check digit Redesign NewEmployeeDialog into a compact layout: borderless sections split by hairline dividers (no per-section cards), a fixed header + scrolling body + solid footer (fixes content showing through the old sticky bar), and denser grids. EmployeeTaxCard gains a `flat` variant so the dialog can host it without card chrome; the edit page keeps the boxed version. Add non-blocking Swedish account check-digit validation (lib/bankgiro/account-number.ts): mod10 (reuses luhn) + mod11, with a clearing->method table from the Bankgirot "Bankernas kontonummeruppbyggnad" spec, cross-checked against jop-io/kontonummer.js and verified against a real account (Forex 9420/4172385). Surfaced as a soft warning in both employee forms; unrecognised clearings return 'unknown' so we never warn on a valid but unmapped account. Never blocks saving. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * feat(invoices): configurable send time + editing for recurring invoices Re-register the accidentally-removed recurring cron (now hourly) and add a per-schedule send hour (Europe/Stockholm, DST-aware). The cron never sends for a past date, and the enabling migration pauses every existing schedule on deploy so nothing auto-sends behind a user's back; users reactivate consciously (with a confirm) or click "Skapa faktura nu" to send this month on demand. Automatic sending now requires a customer email. Adds a full edit flow (row click opens the prefilled form, PATCH), fixing the row-click 404. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(invoices): configure självfaktura via the invoice API Add an optional is_self_billed flag (plus external_invoice_number, self_billing_agreement_ref, received_date) to the public invoice-create endpoint so callers can register a received self-billing invoice (mottagen självfaktura, ML 17 kap 15§) via the API. It was previously only reachable from the internal dashboard route, so it was missing from the API docs. Extract the booking into a shared service (lib/invoices/self-billed-sale.ts) and refactor the internal /api/invoices/self-billed route to a thin wrapper over it, so the dashboard and the API cannot drift. Books as a sale (Debit 1510 / Credit 30xx+26xx) with the counterparty's number; no own number is consumed. Fields are plain optionals (no schema refine) so UpdateInvoiceSchema.omit() keeps working; required-when-self-billed is enforced in the route. Documented in the endpoint registry. No migration (columns already exist). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(settings): allow a partial voucher-series-per-source-type map In Zod 4 an enum-keyed z.record is exhaustive (every source_type required), so saving a default_voucher_series_per_source_type map that omits a source type (e.g. the newly added result_appropriation) failed with "expected string, received undefined". Use partialRecord so the map can be sparse; the engine falls back to series 'A' for any unmapped key. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(salary): resolve employer name via getCompanyDisplayName Payslip PDFs, the payslip email, AGI, KU10, and the BG/LB + SEPA payment files now resolve the employer name through getCompanyDisplayName (company_settings.company_name, falling back to companies.name), matching how invoices already display it. Read-side coalesce, so no migration or backfill: companies.name is write-once at onboarding and not authoritative for these surfaces. The sidebar company switcher uses the same coalesce for the non-active companies in the list. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * perf(kontoplan): index-only account usage counts + lighter reference load Add a covering index on journal_entry_lines (journal_entry_id, account_number) so get_account_usage_counts becomes an index-only scan (prod worst case ~440ms). Slim /api/bookkeeping/accounts/reference to return only the company's activation rows and merge against the client-bundled BAS_REFERENCE instead of re-sending the full ~1,300-account catalog every load, and defer the BAS catalog + usage counts off the first-paint critical path in ChartOfAccountsManager. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * i18n(salary): add bank-account checksum warning string sv/en strings for the employee bank-account (clearing/kontonummer) soft checksum warning shown by the create/edit forms. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: update decision log Append the 2026-07-06/07 decision entries (salary employer-name coalesce, sidebar switcher, employees API personnummer fix, kontoplan load optimization, momsdeklaration manual filing, recurring invoices resend + reactivation + editing, "spara som mall", voucher-series partial map, and självfaktura via the invoice API). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: address compliance-review findings on recurring invoices + moms filing - recurring cron: close the double-send window with an atomic compare-and-set claim on last_run_at (release-on-failure) so two overlapping hourly runs can't both spawn from the same stale batch row - recurring edit dialog: force auto_send=false whenever the effective customer has no email, so a disabled-but-checked box can't PATCH auto_send=true after the async customer load - momsdeklaration manual-filing: truncate rutor to whole kronor (öretal faller bort per SFL 22 kap 1 §) instead of round-to-nearest, matching the SRU path Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
520 lines
18 KiB
TypeScript
520 lines
18 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useMemo } from 'react'
|
|
import { useTranslations } from 'next-intl'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { useForm, useFieldArray, Controller } from 'react-hook-form'
|
|
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { z } from 'zod'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from '@/components/ui/dialog'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Label } from '@/components/ui/label'
|
|
import { Textarea } from '@/components/ui/textarea'
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from '@/components/ui/select'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { useCompany } from '@/contexts/CompanyContext'
|
|
import { Plus, Trash2 } from 'lucide-react'
|
|
import type { Customer, Currency, RecurringInvoiceSchedule } from '@/types'
|
|
import { formatCurrency } from '@/lib/utils'
|
|
|
|
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
|
const units = ['st', 'tim', 'dag', 'månad', 'km', 'kg']
|
|
|
|
interface Props {
|
|
open: boolean
|
|
onOpenChange: (open: boolean) => void
|
|
/** Fired after a successful create or edit. Hosts close the dialog and refresh their list. */
|
|
onSaved: () => void
|
|
/** When provided, the dialog edits this schedule (PATCH) instead of creating a new one. */
|
|
schedule?: RecurringInvoiceSchedule
|
|
}
|
|
|
|
/**
|
|
* "Nytt schema" / "Redigera schema" as a modal: mirrors NewInvoiceDialog now
|
|
* that regular invoice creation opens in one. Passing `schedule` switches it to
|
|
* edit mode (prefilled form, PATCH on save).
|
|
*/
|
|
export default function NewRecurringScheduleDialog({ open, onOpenChange, onSaved, schedule }: Props) {
|
|
const t = useTranslations('invoice_recurring_new')
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent
|
|
className="sm:max-w-4xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto"
|
|
// A half-typed schedule must survive an accidental backdrop click or
|
|
// a stray Escape (the customer/currency selects portal outside the
|
|
// dialog). Closing is explicit: the header X or Avbryt. Same
|
|
// convention as NewInvoiceDialog.
|
|
onEscapeKeyDown={(e) => e.preventDefault()}
|
|
onPointerDownOutside={(e) => e.preventDefault()}
|
|
onInteractOutside={(e) => e.preventDefault()}
|
|
>
|
|
<DialogHeader>
|
|
<DialogTitle>{schedule ? t('edit_title') : t('title')}</DialogTitle>
|
|
</DialogHeader>
|
|
<NewRecurringScheduleForm
|
|
schedule={schedule}
|
|
onSaved={onSaved}
|
|
onCancel={() => onOpenChange(false)}
|
|
/>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|
|
|
|
// Inner component so form state resets whenever the dialog reopens (Radix
|
|
// unmounts DialogContent children on close). This is also what makes edit mode
|
|
// work: each open re-mounts with the current schedule's values as defaults.
|
|
function NewRecurringScheduleForm({
|
|
schedule,
|
|
onSaved,
|
|
onCancel,
|
|
}: {
|
|
schedule?: RecurringInvoiceSchedule
|
|
onSaved: () => void
|
|
onCancel: () => void
|
|
}) {
|
|
const { toast } = useToast()
|
|
const { company } = useCompany()
|
|
const supabase = createClient()
|
|
const t = useTranslations('invoice_recurring_new')
|
|
const [customers, setCustomers] = useState<Customer[]>([])
|
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
|
|
|
const schema = useMemo(() => {
|
|
const itemSchema = z.object({
|
|
description: z.string().min(1, t('validation_description_required')),
|
|
quantity: z.number().min(0.01, t('validation_quantity_min')),
|
|
unit: z.string().min(1, t('validation_unit_required')),
|
|
unit_price: z.number(),
|
|
vat_rate: z
|
|
.union([z.literal(0), z.literal(6), z.literal(12), z.literal(25)])
|
|
.nullable()
|
|
.optional(),
|
|
})
|
|
return z.object({
|
|
customer_id: z.string().uuid(t('validation_customer_required')),
|
|
name: z.string().min(1, t('validation_name_required')),
|
|
day_of_month: z.number().int().min(1).max(31),
|
|
send_hour: z.number().int().min(0).max(23),
|
|
payment_terms_days: z.number().int().min(0).max(90),
|
|
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
|
|
auto_send: z.boolean(),
|
|
your_reference: z.string().optional(),
|
|
our_reference: z.string().optional(),
|
|
notes: z.string().optional(),
|
|
items: z.array(itemSchema).min(1, t('validation_min_one_row')),
|
|
})
|
|
}, [t])
|
|
|
|
type FormData = z.infer<typeof schema>
|
|
|
|
const {
|
|
register,
|
|
control,
|
|
handleSubmit,
|
|
watch,
|
|
setValue,
|
|
formState: { errors },
|
|
} = useForm<FormData>({
|
|
resolver: zodResolver(schema),
|
|
defaultValues: schedule
|
|
? {
|
|
customer_id: schedule.customer_id,
|
|
name: schedule.name,
|
|
day_of_month: schedule.day_of_month,
|
|
send_hour: schedule.send_hour ?? 8,
|
|
payment_terms_days: schedule.payment_terms_days,
|
|
currency: schedule.currency,
|
|
auto_send: schedule.auto_send,
|
|
your_reference: schedule.your_reference ?? undefined,
|
|
our_reference: schedule.our_reference ?? undefined,
|
|
notes: schedule.notes ?? undefined,
|
|
items:
|
|
schedule.items && schedule.items.length > 0
|
|
? [...schedule.items]
|
|
.sort((a, b) => a.sort_order - b.sort_order)
|
|
.map((it) => ({
|
|
description: it.description,
|
|
quantity: it.quantity,
|
|
unit: it.unit,
|
|
unit_price: it.unit_price,
|
|
vat_rate: (it.vat_rate as 0 | 6 | 12 | 25 | null) ?? null,
|
|
}))
|
|
: [{ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: 25 }],
|
|
}
|
|
: {
|
|
customer_id: '',
|
|
name: '',
|
|
day_of_month: 15,
|
|
send_hour: 8,
|
|
payment_terms_days: 30,
|
|
currency: 'SEK',
|
|
auto_send: false,
|
|
items: [{ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: 25 }],
|
|
},
|
|
})
|
|
|
|
const { fields, append, remove } = useFieldArray({ control, name: 'items' })
|
|
|
|
useEffect(() => {
|
|
if (!company) return
|
|
supabase
|
|
.from('customers')
|
|
.select('*')
|
|
.eq('company_id', company.id)
|
|
.order('name')
|
|
.then(({ data }) => setCustomers(data ?? []))
|
|
}, [company])
|
|
|
|
async function onSubmit(data: FormData) {
|
|
setIsSubmitting(true)
|
|
try {
|
|
const res = await fetch(
|
|
schedule ? `/api/invoices/recurring/${schedule.id}` : '/api/invoices/recurring',
|
|
{
|
|
method: schedule ? 'PATCH' : 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data),
|
|
},
|
|
)
|
|
if (!res.ok) {
|
|
const body = await res.json().catch(() => ({}))
|
|
throw new Error(body.error || t('create_failed_fallback'))
|
|
}
|
|
toast({ title: schedule ? t('updated_title') : t('created_title') })
|
|
onSaved()
|
|
} catch (err) {
|
|
toast({
|
|
title: schedule ? t('update_failed_title') : t('create_failed_title'),
|
|
description: err instanceof Error ? err.message : undefined,
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsSubmitting(false)
|
|
}
|
|
}
|
|
|
|
const items = watch('items')
|
|
const watchCurrency = watch('currency')
|
|
// Automatic sending requires a customer email; without one the cron would
|
|
// just produce a monthly draft + warning. Block it at the source.
|
|
const watchCustomerId = watch('customer_id')
|
|
const selectedCustomer = customers.find((c) => c.id === watchCustomerId)
|
|
const customerMissingEmail = !!selectedCustomer && !selectedCustomer.email
|
|
|
|
// The onValueChange guard on the customer select only fires on a manual
|
|
// change. In edit mode a schedule can load with auto_send=true against a
|
|
// customer who has since lost their email (customers load async, after the
|
|
// form's defaultValues). Force auto_send off whenever the effective customer
|
|
// has no email so a disabled-but-checked box can't PATCH auto_send=true.
|
|
useEffect(() => {
|
|
if (customerMissingEmail) setValue('auto_send', false)
|
|
}, [customerMissingEmail, setValue])
|
|
const subtotalRaw = items.reduce(
|
|
(sum, it) => sum + (it.quantity || 0) * (it.unit_price || 0),
|
|
0,
|
|
)
|
|
// Round to öre using the project monetary rule, then format.
|
|
const subtotal = Math.round(subtotalRaw * 100) / 100
|
|
|
|
return (
|
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('schedule_card_title')}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div>
|
|
<Label htmlFor="name">{t('name_label')}</Label>
|
|
<Input
|
|
id="name"
|
|
placeholder={t('name_placeholder')}
|
|
{...register('name')}
|
|
/>
|
|
{errors.name && (
|
|
<p className="text-sm text-destructive mt-1">{errors.name.message}</p>
|
|
)}
|
|
</div>
|
|
|
|
<div>
|
|
<Label htmlFor="customer_id">{t('customer_label')}</Label>
|
|
<Controller
|
|
control={control}
|
|
name="customer_id"
|
|
render={({ field }) => (
|
|
<Select
|
|
value={field.value}
|
|
onValueChange={(v) => {
|
|
field.onChange(v)
|
|
// Switching to a customer without email while auto-send is
|
|
// checked would create an unsendable schedule.
|
|
const c = customers.find((x) => x.id === v)
|
|
if (!c?.email) setValue('auto_send', false)
|
|
}}
|
|
>
|
|
<SelectTrigger id="customer_id">
|
|
<SelectValue placeholder={t('customer_placeholder')} />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{customers.map((c) => (
|
|
<SelectItem key={c.id} value={c.id}>
|
|
{c.name}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
/>
|
|
{errors.customer_id && (
|
|
<p className="text-sm text-destructive mt-1">{errors.customer_id.message}</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
<div>
|
|
<Label htmlFor="day_of_month">{t('day_label')}</Label>
|
|
<Input
|
|
id="day_of_month"
|
|
type="number"
|
|
min={1}
|
|
max={31}
|
|
className="tabular-nums"
|
|
{...register('day_of_month', { valueAsNumber: true })}
|
|
/>
|
|
<p className="text-xs text-muted-foreground mt-1">
|
|
{t('day_hint')}
|
|
</p>
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="send_hour">{t('send_hour_label')}</Label>
|
|
<Controller
|
|
control={control}
|
|
name="send_hour"
|
|
render={({ field }) => (
|
|
<Select
|
|
value={String(field.value)}
|
|
onValueChange={(v) => field.onChange(Number(v))}
|
|
>
|
|
<SelectTrigger id="send_hour" className="tabular-nums">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{Array.from({ length: 24 }, (_, h) => h).map((h) => (
|
|
<SelectItem key={h} value={String(h)} className="tabular-nums">
|
|
{`${String(h).padStart(2, '0')}:00`}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
/>
|
|
<p className="text-xs text-muted-foreground mt-1">
|
|
{t('send_hour_hint')}
|
|
</p>
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="payment_terms_days">{t('payment_terms_label')}</Label>
|
|
<Input
|
|
id="payment_terms_days"
|
|
type="number"
|
|
min={0}
|
|
max={90}
|
|
className="tabular-nums"
|
|
{...register('payment_terms_days', { valueAsNumber: true })}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="currency">{t('currency_label')}</Label>
|
|
<Controller
|
|
control={control}
|
|
name="currency"
|
|
render={({ field }) => (
|
|
<Select value={field.value} onValueChange={field.onChange}>
|
|
<SelectTrigger id="currency">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{currencies.map((c) => (
|
|
<SelectItem key={c} value={c}>
|
|
{c}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="rounded-lg border border-border p-4">
|
|
<div className="flex items-start gap-3">
|
|
<Controller
|
|
control={control}
|
|
name="auto_send"
|
|
render={({ field }) => (
|
|
<input
|
|
type="checkbox"
|
|
id="auto_send"
|
|
checked={field.value}
|
|
onChange={(e) => field.onChange(e.target.checked)}
|
|
disabled={customerMissingEmail}
|
|
className="mt-1 h-4 w-4"
|
|
/>
|
|
)}
|
|
/>
|
|
<div className="flex-1">
|
|
<Label htmlFor="auto_send" className="font-medium">
|
|
{t('auto_send_label')}
|
|
</Label>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
{t('auto_send_description')}
|
|
</p>
|
|
{customerMissingEmail && (
|
|
<p className="text-sm text-warning-foreground mt-1">
|
|
{t('auto_send_missing_email')}
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('items_card_title')}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-3">
|
|
{fields.map((field, index) => (
|
|
<div
|
|
key={field.id}
|
|
className="grid grid-cols-12 gap-2 items-start"
|
|
>
|
|
<div className="col-span-12 sm:col-span-5">
|
|
<Input
|
|
placeholder={t('description_placeholder')}
|
|
{...register(`items.${index}.description`)}
|
|
/>
|
|
</div>
|
|
<div className="col-span-3 sm:col-span-2">
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
placeholder={t('quantity_placeholder')}
|
|
className="tabular-nums"
|
|
{...register(`items.${index}.quantity`, { valueAsNumber: true })}
|
|
/>
|
|
</div>
|
|
<div className="col-span-3 sm:col-span-1">
|
|
<Controller
|
|
control={control}
|
|
name={`items.${index}.unit`}
|
|
render={({ field }) => (
|
|
<Select value={field.value} onValueChange={field.onChange}>
|
|
<SelectTrigger>
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{units.map((u) => (
|
|
<SelectItem key={u} value={u}>
|
|
{u}
|
|
</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
)}
|
|
/>
|
|
</div>
|
|
<div className="col-span-4 sm:col-span-3">
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
placeholder={t('unit_price_placeholder')}
|
|
className="tabular-nums"
|
|
{...register(`items.${index}.unit_price`, { valueAsNumber: true })}
|
|
/>
|
|
</div>
|
|
<div className="col-span-2 sm:col-span-1">
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={() => fields.length > 1 && remove(index)}
|
|
aria-label={t('remove_row')}
|
|
>
|
|
<Trash2 className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
))}
|
|
<Button
|
|
type="button"
|
|
variant="secondary"
|
|
size="sm"
|
|
onClick={() =>
|
|
append({ description: '', quantity: 1, unit: 'st', unit_price: 0, vat_rate: 25 })
|
|
}
|
|
>
|
|
<Plus className="mr-2 h-4 w-4" />
|
|
{t('add_row')}
|
|
</Button>
|
|
<div className="pt-2 text-sm text-muted-foreground tabular-nums">
|
|
{t('subtotal_ex_vat', { amount: formatCurrency(subtotal, watchCurrency) })}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">{t('other_card_title')}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
<div>
|
|
<Label htmlFor="your_reference">{t('your_reference_label')}</Label>
|
|
<Input id="your_reference" {...register('your_reference')} />
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="our_reference">{t('our_reference_label')}</Label>
|
|
<Input id="our_reference" {...register('our_reference')} />
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="notes">{t('notes_label')}</Label>
|
|
<Textarea id="notes" rows={3} {...register('notes')} />
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<div className="flex justify-end gap-2">
|
|
<Button type="button" variant="secondary" onClick={onCancel}>
|
|
{t('cancel')}
|
|
</Button>
|
|
<Button type="submit" disabled={isSubmitting}>
|
|
{schedule
|
|
? isSubmitting
|
|
? t('saving')
|
|
: t('save_changes')
|
|
: isSubmitting
|
|
? t('creating')
|
|
: t('create_schedule')}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
)
|
|
}
|