feat(parties): Förslag från bokföringen, confirmed straight into Leverantörer and Kunder (#2206)
* feat(parties): Kontakter register, suggestion queue, dossier and merge Phase 1's two surfaces on top of the parties substrate: - /parties page: one list with the five-way switch (Alla, Kunder, Leverantörer, Förslag, Bara i bokföringen), search, a 12-month/all period picker, and at most one attention line. Confirmed rows show roles as muted text, rhythm, underlag, dominant account and money. Observed rows are computed and never stored; a generic band keeps unattributed spend visible. - Suggestion queue: a reason per row, hard-key rows pre-ticked, bulk confirm behind one dialog, dismiss on hover, undo on the toast. - Dossier slide-over: Pengar, Bokföring, Vad Accounted vet (facts and identities with source and count), Underlag och verifikat, Historik. - Merge dialog with a visible, swappable survivor and undo. - API: GET /api/parties, GET /api/parties/[id], POST suggest, decide, decide/undo, merge, merge/undo (withRouteContext, Zod, 15 tests). - Migration 20260903090000: decide_parties snapshots the reason it clears; undo_party_decisions reverses confirm/dismiss within 30 days; decision kind 'undo'. - The pipeline runs after SIE import and provider migration (non-blocking) so a migrant's register is full on arrival. - Nav entry under Register; sv/en strings. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): pass explicit interpolation values to next-intl next build's type check rejects a typed interface where the translator wants an index-signature record. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): retry label on the load-failed state Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): hard keys for companies without org number, readable names, look-alikes at read time - get_ledger_key_evidence dropped every document for a company whose own org number is NULL (the self check compared against NULL). Replaced in 20260903100000 with a coalesced comparison; pg test covers it. - Display names come from the printed name on documents, otherwise from the voucher text with the AP/AR prefix and supplier number removed. - Look-alike parties (same core, or one core extending the other by whole words: Fortnox / Fortnox Finans) are detected when the register is read, never stored, and feed the Dubblett? chip and the merge dialog. - Queue shows Intäkt beside Kostnad; dossier hides zero money rows and formats bankgiro/plusgiro; merge dialog cancels with Avbryt; no synchronous setState inside effects. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): link every new supplier and customer to a party on write The backfill covered the rows that existed on 2026-09-02; 108 rows created since had no party and never reached the register. A BEFORE INSERT/UPDATE trigger on customers and suppliers now calls ensure_party on every write path at once: find-or-create by org number inside the company, never by name; a private customer gets a kind=person party without any number; a nameless row stays unlinked; a foreign party id is refused with the same error as the composite foreign key; a link to a merged party follows the chain to the survivor; the clear that ON DELETE SET NULL performs is kept. ensure_party lets the trigger act for the row's owner (pg_trigger_depth() > 0); the RPC path is unchanged. The migration also links the rows created since the backfill. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): dossier hides dismissed parties and follows merges to the survivor The register hid archived parties while the dossier still served them by id, and a merged party's dossier pointed at a dead row. Superagent P2 on #2206; three unit tests. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move the role-link migration past main's 20260903110000 Two files with one version would collide in schema_migrations. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(parties): confirm suggestions into Leverantörer and Kunder, no third noun Founder decision after the walkthrough: users know two words. The page becomes the queue 'Förslag från bokföringen' with 'Bara i bokföringen' beside it; the Kontakter nav entry and the Alla/Kunder/Leverantörer views go. Each suggestion shows what it becomes (Blir), read from the ledger side and changeable per row; confirming calls promote_parties, which creates the supplier and/or customer row from the party's facts, never a duplicate, and is undoable for 30 days through undo_party_promotions (the created rows are archived, the party returns to the queue). Leverantörer and Kunder carry the one attention line that leads here. The dossier offers Lägg upp som leverantör / som kund. Migration 20260903130000, 5 pg tests, route and unit tests updated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(parties): write bankgiro and plusgiro the way the supplier form does Identities are stored as digits; suppliers carry 5317-0900. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(parties): move the four queue migrations past main's 20260903170000 Main merged 20260903120000_skattekonto_transactions_realtime_publication with the same version as the role-link trigger; the preview database refused the duplicate key. All four now sit after main's newest so the set applies in one ordered run on prod. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
e2d38b0ab3
commit
b996da60ee
@@ -20,6 +20,7 @@ import { ReportExportMenu } from '@/components/reports/ReportExportMenu'
|
||||
import { cn } from '@/lib/utils'
|
||||
import Link from 'next/link'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { SuggestionsAttn } from '@/components/parties/SuggestionsAttn'
|
||||
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
|
||||
import { customerListIdentifier } from '@/lib/customers/mask-personal-number'
|
||||
|
||||
@@ -287,6 +288,7 @@ function CustomersPageInner() {
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
<SuggestionsAttn side="customer" />
|
||||
|
||||
{/* Toolbar: search (concept) */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
'use client'
|
||||
|
||||
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Lock } from 'lucide-react'
|
||||
import { ContextPicker, type ContextPickerItem } from '@/components/common/ContextPicker'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { HelpPopover } from '@/components/ui/help-popover'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { SegmentedControl } from '@/components/ui/segmented-control'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { ToastAction } from '@/components/ui/toast'
|
||||
import { ToolbarSearch } from '@/components/ui/toolbar-search'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { MergeDialog, type MergeCandidate } from '@/components/parties/MergeDialog'
|
||||
import { ObservedTable } from '@/components/parties/ObservedTable'
|
||||
import { PartyDossier } from '@/components/parties/PartyDossier'
|
||||
import { SuggestionQueue } from '@/components/parties/SuggestionQueue'
|
||||
import { hasHardKey } from '@/components/parties/format'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { PartyRole, Register, RegisterPeriod, RegisterRow, RegisterView } from '@/lib/parties/register'
|
||||
|
||||
const VIEWS: RegisterView[] = ['suggested', 'observed']
|
||||
|
||||
async function post<T>(url: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
if (!res.ok) throw new Error(String(res.status))
|
||||
const json = (await res.json()) as { data: T }
|
||||
return json.data
|
||||
}
|
||||
|
||||
function roleSummary(t: (k: string, v?: Record<string, string | number>) => string, items: Array<{ roles: PartyRole[] }>): string {
|
||||
const suppliers = items.filter((i) => i.roles.includes('supplier')).length
|
||||
const customers = items.filter((i) => i.roles.includes('customer')).length
|
||||
const parts: string[] = []
|
||||
if (suppliers) parts.push(t('summary_suppliers', { count: suppliers }))
|
||||
if (customers) parts.push(t('summary_customers', { count: customers }))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Förslag från bokföringen: the queue in front of Leverantörer and Kunder.
|
||||
* Nothing here is a register of its own; confirming creates the supplier or
|
||||
* customer row, and "Bara i bokföringen" shows what the vouchers name that
|
||||
* nothing owns yet.
|
||||
*/
|
||||
function SuggestionsPage() {
|
||||
const t = useTranslations('parties')
|
||||
const tCommon = useTranslations('common')
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const initialView: RegisterView = searchParams.get('view') === 'observed' ? 'observed' : 'suggested'
|
||||
const [view, setView] = useState<RegisterView>(initialView)
|
||||
const [query, setQuery] = useState('')
|
||||
const [debounced, setDebounced] = useState('')
|
||||
const [period, setPeriod] = useState<RegisterPeriod>('12m')
|
||||
const [register, setRegister] = useState<Register | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [roleOverrides, setRoleOverrides] = useState<Record<string, PartyRole[]>>({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [dossierId, setDossierId] = useState<string | null>(null)
|
||||
const [dossierReload, setDossierReload] = useState(0)
|
||||
const [merge, setMerge] = useState<{ subject: MergeCandidate; suggested: MergeCandidate[] } | null>(null)
|
||||
const preselected = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => setDebounced(query.trim()), 250)
|
||||
return () => clearTimeout(id)
|
||||
}, [query])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
const params = new URLSearchParams({ view, period })
|
||||
if (debounced) params.set('q', debounced)
|
||||
fetch(`/api/parties?${params.toString()}`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error(String(res.status))
|
||||
const json = (await res.json()) as { data: Register }
|
||||
if (cancelled) return
|
||||
setRegister(json.data)
|
||||
setFailed(false)
|
||||
// Only rows with a hard key arrive pre-ticked, once per queue load.
|
||||
if (view === 'suggested' && preselected.current !== `${reloadKey}:${debounced}`) {
|
||||
preselected.current = `${reloadKey}:${debounced}`
|
||||
setSelected(new Set(json.data.rows.filter(hasHardKey).map((r) => r.id)))
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setFailed(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [view, debounced, period, reloadKey])
|
||||
|
||||
const reload = useCallback(() => {
|
||||
setReloadKey((k) => k + 1)
|
||||
setDossierReload((k) => k + 1)
|
||||
}, [])
|
||||
|
||||
const counts = register?.counts
|
||||
const viewOptions = useMemo(
|
||||
() =>
|
||||
VIEWS.map((v) => ({
|
||||
value: v,
|
||||
label: t(`view_${v}`),
|
||||
count: counts ? counts[v] : undefined,
|
||||
})),
|
||||
[counts, t],
|
||||
)
|
||||
const periodItems: ContextPickerItem[] = useMemo(
|
||||
() => [
|
||||
{ id: '12m', label: t('period_12m') },
|
||||
{ id: 'all', label: t('period_all') },
|
||||
],
|
||||
[t],
|
||||
)
|
||||
|
||||
const fail = useCallback(() => toast({ title: t('action_failed'), variant: 'destructive' }), [toast, t])
|
||||
const rolesFor = useCallback((row: RegisterRow): PartyRole[] => roleOverrides[row.id] ?? row.defaultRoles, [roleOverrides])
|
||||
|
||||
async function refreshSuggestions() {
|
||||
if (refreshing) return
|
||||
setRefreshing(true)
|
||||
try {
|
||||
const summary = await post<{ created: number; attached: number }>('/api/parties/suggest')
|
||||
toast({ title: t('refreshed_title'), description: t('refreshed_description', { created: summary.created, attached: summary.attached }) })
|
||||
reload()
|
||||
} catch {
|
||||
fail()
|
||||
} finally {
|
||||
setRefreshing(false)
|
||||
}
|
||||
}
|
||||
|
||||
function undoToast(title: string, undoUrl: string, ids: string[], undoneTitle: string) {
|
||||
toast({
|
||||
title,
|
||||
action: (
|
||||
<ToastAction
|
||||
altText={t('undo')}
|
||||
onClick={() => {
|
||||
post(undoUrl, { partyIds: ids })
|
||||
.then(() => {
|
||||
toast({ title: undoneTitle })
|
||||
reload()
|
||||
})
|
||||
.catch(fail)
|
||||
}}
|
||||
>
|
||||
{t('undo')}
|
||||
</ToastAction>
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
async function promote(items: Array<{ partyId: string; roles: PartyRole[] }>) {
|
||||
if (items.length === 0) return
|
||||
setBusy(true)
|
||||
try {
|
||||
const r = await post<{ parties: number; suppliers: number; customers: number }>('/api/parties/promote', { items })
|
||||
undoToast(t('promoted_title', { count: r.parties, detail: roleSummary(t, items) }), '/api/parties/promote/undo', items.map((i) => i.partyId), t('undone_title'))
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
for (const i of items) next.delete(i.partyId)
|
||||
return next
|
||||
})
|
||||
reload()
|
||||
} catch {
|
||||
fail()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function dismiss(ids: string[]) {
|
||||
if (ids.length === 0) return
|
||||
setBusy(true)
|
||||
try {
|
||||
const { count } = await post<{ count: number }>('/api/parties/decide', { partyIds: ids, kind: 'dismiss' })
|
||||
undoToast(t('dismissed_title', { count }), '/api/parties/decide/undo', ids, t('undone_title'))
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
for (const id of ids) next.delete(id)
|
||||
return next
|
||||
})
|
||||
reload()
|
||||
} catch {
|
||||
fail()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function runMerge(survivorId: string, mergedIds: string[]) {
|
||||
setBusy(true)
|
||||
try {
|
||||
const { decisionId } = await post<{ decisionId: string }>('/api/parties/merge', { survivorId, mergedIds })
|
||||
toast({
|
||||
title: t('merged_title'),
|
||||
action: (
|
||||
<ToastAction
|
||||
altText={t('undo')}
|
||||
onClick={() => {
|
||||
post('/api/parties/merge/undo', { decisionId })
|
||||
.then(() => {
|
||||
toast({ title: t('merge_undone_title') })
|
||||
reload()
|
||||
})
|
||||
.catch(fail)
|
||||
}}
|
||||
>
|
||||
{t('undo')}
|
||||
</ToastAction>
|
||||
),
|
||||
})
|
||||
setMerge(null)
|
||||
if (dossierId && mergedIds.includes(dossierId)) setDossierId(survivorId)
|
||||
reload()
|
||||
} catch {
|
||||
fail()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const rows = register?.rows ?? []
|
||||
const searching = debounced.length > 0
|
||||
const selectedItems = rows.filter((r) => selected.has(r.id)).map((r) => ({ partyId: r.id, roles: rolesFor(r) }))
|
||||
|
||||
let attn: React.ReactNode = null
|
||||
if (counts && counts.suggested === 0 && counts.observed > 0 && canWrite && view === 'suggested') {
|
||||
attn = <AttnLine action={{ label: t('refresh'), onClick: () => void refreshSuggestions() }}>{t('attn_observed', { count: counts.observed })}</AttnLine>
|
||||
}
|
||||
|
||||
function empty() {
|
||||
if (searching) return <EmptyState title={t('empty_search_title')} description={t('empty_search_description')} />
|
||||
if (view === 'observed') return <EmptyState title={t('empty_observed_title')} description={t('empty_observed_description')} />
|
||||
return (
|
||||
<EmptyState
|
||||
title={t('empty_suggested_title')}
|
||||
description={t('empty_suggested_description')}
|
||||
actionLabel={canWrite ? t('refresh') : undefined}
|
||||
onAction={canWrite ? () => void refreshSuggestions() : undefined}
|
||||
secondaryActionLabel={t('go_suppliers')}
|
||||
secondaryActionHref="/suppliers"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function content() {
|
||||
if (failed) return <EmptyState title={t('load_failed')} description={t('action_failed')} actionLabel={tCommon('retry')} onAction={reload} />
|
||||
if (loading && !register)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
)
|
||||
if (!register) return null
|
||||
if (view === 'observed') {
|
||||
if (register.observed.length === 0 && register.generic.count === 0) return empty()
|
||||
return <ObservedTable rows={register.observed} generic={register.generic} />
|
||||
}
|
||||
if (rows.length === 0) return empty()
|
||||
return (
|
||||
<SuggestionQueue
|
||||
rows={rows}
|
||||
selected={selected}
|
||||
roles={rolesFor}
|
||||
canWrite={canWrite}
|
||||
busy={busy}
|
||||
onToggle={(id) =>
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
onSelectAll={() => setSelected(new Set(rows.map((r) => r.id)))}
|
||||
onClear={() => setSelected(new Set())}
|
||||
onRoles={(id, roles) => setRoleOverrides((prev) => ({ ...prev, [id]: roles }))}
|
||||
onConfirmSelected={() => setConfirmOpen(true)}
|
||||
onDismiss={(row) => void dismiss([row.id])}
|
||||
onOpen={setDossierId}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
description={counts ? t('summary', { suggested: counts.suggested, observed: counts.observed }) : undefined}
|
||||
help={
|
||||
<HelpPopover>
|
||||
<p>{t('help')}</p>
|
||||
</HelpPopover>
|
||||
}
|
||||
action={
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void refreshSuggestions()}
|
||||
disabled={!canWrite || refreshing}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" aria-hidden="true" /> : null}
|
||||
{refreshing ? t('refreshing') : t('refresh')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{attn}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<SegmentedControl<RegisterView>
|
||||
value={view}
|
||||
onChange={(v) => {
|
||||
setView(v)
|
||||
router.replace(v === 'observed' ? '/parties?view=observed' : '/parties', { scroll: false })
|
||||
}}
|
||||
options={viewOptions}
|
||||
/>
|
||||
<ToolbarSearch value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('search_placeholder')} aria-label={t('search_placeholder')} />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<ContextPicker
|
||||
items={periodItems}
|
||||
value={period}
|
||||
onChange={(id) => setPeriod(id as RegisterPeriod)}
|
||||
triggerLabel={periodItems.find((i) => i.id === period)?.label ?? t('period_12m')}
|
||||
ariaLabel={t('period_label')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{content()}
|
||||
|
||||
{register && view === 'suggested' && rows.length > 0 ? (
|
||||
<p className="px-1 text-xs text-muted-foreground tabular-nums">{t('count_summary', { count: rows.length })}</p>
|
||||
) : null}
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
title={t('promote_dialog_title', { count: selectedItems.length })}
|
||||
description={t('promote_dialog_body', { detail: roleSummary(t, selectedItems) })}
|
||||
confirmLabel={t('promote_n', { count: selectedItems.length })}
|
||||
onConfirm={async () => {
|
||||
setConfirmOpen(false)
|
||||
await promote(selectedItems)
|
||||
}}
|
||||
/>
|
||||
|
||||
<PartyDossier
|
||||
partyId={dossierId}
|
||||
period={period}
|
||||
canWrite={canWrite}
|
||||
busy={busy}
|
||||
reloadKey={dossierReload}
|
||||
onClose={() => setDossierId(null)}
|
||||
onPromote={(id, roles) => void promote([{ partyId: id, roles }])}
|
||||
onDismiss={(id) => {
|
||||
void dismiss([id])
|
||||
setDossierId(null)
|
||||
}}
|
||||
onMerge={(subject, suggested) => setMerge({ subject, suggested })}
|
||||
/>
|
||||
|
||||
{merge ? (
|
||||
<MergeDialog
|
||||
open
|
||||
onOpenChange={(open) => (!open ? setMerge(null) : undefined)}
|
||||
subject={merge.subject}
|
||||
suggested={merge.suggested}
|
||||
busy={busy}
|
||||
onMerge={runMerge}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function PartiesPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<SuggestionsPage />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import Link from 'next/link'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { SuggestionsAttn } from '@/components/parties/SuggestionsAttn'
|
||||
import type { Supplier, SupplierType, CreateSupplierInput } from '@/types'
|
||||
|
||||
const SupplierForm = dynamic(
|
||||
@@ -170,6 +171,7 @@ export default function SuppliersPage() {
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
<SuggestionsAttn side="supplier" />
|
||||
|
||||
{/* Toolbar: search (concept) */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { getDossier } from '@/lib/parties/register'
|
||||
|
||||
/** GET /api/parties/[id]: the dossier for one party (facts, identities, decisions, vouchers). */
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'parties.get',
|
||||
async (_request, { supabase, companyId, log, requestId }, { params }) => {
|
||||
const { id } = await params
|
||||
if (!/^[0-9a-f-]{36}$/i.test(id)) return errorResponseFromCode('NOT_FOUND', log, { requestId })
|
||||
const dossier = await getDossier(supabase, companyId, id)
|
||||
if (!dossier) return errorResponseFromCode('NOT_FOUND', log, { requestId })
|
||||
return NextResponse.json({ data: dossier })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* /api/parties: the Kontakter register and its write actions. The read model
|
||||
* and the pipeline are unit-tested in lib/parties; here the routes are
|
||||
* checked for auth, validation and the shape they hand the page.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
const getRegister = vi.fn()
|
||||
const getDossier = vi.fn()
|
||||
vi.mock('@/lib/parties/register', () => ({
|
||||
getRegister: (...args: unknown[]) => getRegister(...args),
|
||||
getDossier: (...args: unknown[]) => getDossier(...args),
|
||||
}))
|
||||
const suggestPartiesForCompany = vi.fn()
|
||||
vi.mock('@/lib/parties/suggest', () => ({
|
||||
suggestPartiesForCompany: (...args: unknown[]) => suggestPartiesForCompany(...args),
|
||||
}))
|
||||
|
||||
import { GET as listGet } from '../route'
|
||||
import { GET as dossierGet } from '../[id]/route'
|
||||
import { POST as suggestPost } from '../suggest/route'
|
||||
import { POST as decidePost } from '../decide/route'
|
||||
import { POST as undoDecidePost } from '../decide/undo/route'
|
||||
import { POST as mergePost } from '../merge/route'
|
||||
import { POST as undoMergePost } from '../merge/undo/route'
|
||||
import { POST as promotePost } from '../promote/route'
|
||||
import { POST as undoPromotePost } from '../promote/undo/route'
|
||||
|
||||
const user = { id: 'user-1', email: 'test@test.se' }
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
const PARTY = '11111111-1111-4111-8111-111111111111'
|
||||
const OTHER = '22222222-2222-4222-8222-222222222222'
|
||||
const DECISION = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
function json(url: string, body: unknown) {
|
||||
return createMockRequest(url, { method: 'POST', body })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user } })
|
||||
})
|
||||
|
||||
describe('GET /api/parties', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const { status } = await parseJsonResponse(await listGet(createMockRequest('/api/parties'), noParams))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an unknown view with 400', async () => {
|
||||
const { status } = await parseJsonResponse(await listGet(createMockRequest('/api/parties?view=nope'), noParams))
|
||||
expect(status).toBe(400)
|
||||
expect(getRegister).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes view, query and period to the read model for the active company', async () => {
|
||||
const register = { counts: { suggested: 1, suggestedSuppliers: 1, suggestedCustomers: 0, observed: 0, confirmed: 3 }, rows: [], observed: [], generic: { count: 0, expenseSek: 0, examples: [] }, period: 'all' }
|
||||
getRegister.mockResolvedValue(register)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof register }>(
|
||||
await listGet(createMockRequest('/api/parties?view=observed&q=beijer&period=all'), noParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual(register)
|
||||
expect(getRegister).toHaveBeenCalledWith(mockSupabase, 'company-1', { view: 'observed', q: 'beijer', period: 'all' })
|
||||
})
|
||||
|
||||
it('no longer accepts the register views that moved to Leverantörer and Kunder', async () => {
|
||||
const { status } = await parseJsonResponse(await listGet(createMockRequest('/api/parties?view=suppliers'), noParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/parties/[id]', () => {
|
||||
it('returns 404 for a party that is not in the company', async () => {
|
||||
getDossier.mockResolvedValue(null)
|
||||
const { status } = await parseJsonResponse(
|
||||
await dossierGet(createMockRequest(`/api/parties/${PARTY}`), { params: Promise.resolve({ id: PARTY }) }),
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 404 for a malformed id without touching the database', async () => {
|
||||
const { status } = await parseJsonResponse(
|
||||
await dossierGet(createMockRequest('/api/parties/not-a-uuid'), { params: Promise.resolve({ id: 'not-a-uuid' }) }),
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
expect(getDossier).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the dossier', async () => {
|
||||
const dossier = { party: { id: PARTY, displayName: 'Loopia AB' }, facts: [], identities: [], decisions: [], vouchers: [], similar: [] }
|
||||
getDossier.mockResolvedValue(dossier)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof dossier }>(
|
||||
await dossierGet(createMockRequest(`/api/parties/${PARTY}`), { params: Promise.resolve({ id: PARTY }) }),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.party.displayName).toBe('Loopia AB')
|
||||
expect(getDossier).toHaveBeenCalledWith(mockSupabase, 'company-1', PARTY)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/suggest', () => {
|
||||
it('runs the pipeline for the caller and company', async () => {
|
||||
const summary = { observed: 10, suggested: 4, skipped: 6, created: 3, attached: 1, identities: 2, facts: 5 }
|
||||
suggestPartiesForCompany.mockResolvedValue(summary)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof summary }>(await suggestPost(createMockRequest('/api/parties/suggest', { method: 'POST' }), noParams))
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual(summary)
|
||||
expect(suggestPartiesForCompany).toHaveBeenCalledWith(mockSupabase, 'company-1', 'user-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/decide', () => {
|
||||
it('rejects an empty id list and an unknown kind', async () => {
|
||||
const a = await parseJsonResponse(await decidePost(json('/api/parties/decide', { partyIds: [], kind: 'confirm' }), noParams))
|
||||
expect(a.status).toBe(400)
|
||||
const b = await parseJsonResponse(await decidePost(json('/api/parties/decide', { partyIds: [PARTY], kind: 'merge' }), noParams))
|
||||
expect(b.status).toBe(400)
|
||||
})
|
||||
|
||||
it('calls decide_parties with the caller identity and returns the count', async () => {
|
||||
enqueue({ data: 2 })
|
||||
const { status, body } = await parseJsonResponse<{ data: { count: number; kind: string } }>(
|
||||
await decidePost(json('/api/parties/decide', { partyIds: [PARTY, OTHER], kind: 'confirm', note: 'from queue' }), noParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ count: 2, kind: 'confirm' })
|
||||
expect(mockSupabase.rpc).toHaveBeenCalledWith('decide_parties', {
|
||||
p_company_id: 'company-1',
|
||||
p_user_id: 'user-1',
|
||||
p_party_ids: [PARTY, OTHER],
|
||||
p_kind: 'confirm',
|
||||
p_note: 'from queue',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/decide/undo', () => {
|
||||
it('reverses the latest decisions for the given parties', async () => {
|
||||
enqueue({ data: 1 })
|
||||
const { status, body } = await parseJsonResponse<{ data: { count: number } }>(
|
||||
await undoDecidePost(json('/api/parties/decide/undo', { partyIds: [PARTY] }), noParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ count: 1 })
|
||||
expect(mockSupabase.rpc).toHaveBeenCalledWith('undo_party_decisions', { p_company_id: 'company-1', p_user_id: 'user-1', p_party_ids: [PARTY] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/merge', () => {
|
||||
it('rejects a survivor listed among the merged ids', async () => {
|
||||
const { status } = await parseJsonResponse(await mergePost(json('/api/parties/merge', { survivorId: PARTY, mergedIds: [PARTY] }), noParams))
|
||||
expect(status).toBe(400)
|
||||
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps a foreign or merged party to 404', async () => {
|
||||
enqueue({ data: null, error: { code: '23503', message: 'survivor is not a live party of this company' } })
|
||||
const { status } = await parseJsonResponse(await mergePost(json('/api/parties/merge', { survivorId: PARTY, mergedIds: [OTHER] }), noParams))
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns the decision id for undo', async () => {
|
||||
enqueue({ data: DECISION })
|
||||
const { status, body } = await parseJsonResponse<{ data: { decisionId: string; survivorId: string; mergedIds: string[] } }>(
|
||||
await mergePost(json('/api/parties/merge', { survivorId: PARTY, mergedIds: [OTHER], note: 'same supplier' }), noParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ decisionId: DECISION, survivorId: PARTY, mergedIds: [OTHER] })
|
||||
expect(mockSupabase.rpc).toHaveBeenCalledWith('merge_parties', {
|
||||
p_company_id: 'company-1',
|
||||
p_user_id: 'user-1',
|
||||
p_survivor: PARTY,
|
||||
p_merged: [OTHER],
|
||||
p_note: 'same supplier',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/merge/undo', () => {
|
||||
it('validates the decision id', async () => {
|
||||
const { status } = await parseJsonResponse(await undoMergePost(json('/api/parties/merge/undo', { decisionId: 'x' }), noParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('restores the merged parties', async () => {
|
||||
enqueue({ data: 2 })
|
||||
const { status, body } = await parseJsonResponse<{ data: { restored: number } }>(
|
||||
await undoMergePost(json('/api/parties/merge/undo', { decisionId: DECISION }), noParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ restored: 2 })
|
||||
expect(mockSupabase.rpc).toHaveBeenCalledWith('undo_party_merge', { p_company_id: 'company-1', p_user_id: 'user-1', p_decision_id: DECISION })
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/promote', () => {
|
||||
it('rejects an item without roles', async () => {
|
||||
const { status } = await parseJsonResponse(await promotePost(json('/api/parties/promote', { items: [{ partyId: PARTY, roles: [] }] }), noParams))
|
||||
expect(status).toBe(400)
|
||||
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps a foreign or archived party to 404', async () => {
|
||||
enqueue({ data: null, error: { code: '23503', message: 'not a live party' } })
|
||||
const { status } = await parseJsonResponse(await promotePost(json('/api/parties/promote', { items: [{ partyId: PARTY, roles: ['supplier'] }] }), noParams))
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('calls promote_parties with snake_case items and returns the counts', async () => {
|
||||
enqueue({ data: { parties: 2, suppliers: 1, customers: 1 } })
|
||||
const { status, body } = await parseJsonResponse<{ data: { parties: number; suppliers: number; customers: number } }>(
|
||||
await promotePost(
|
||||
json('/api/parties/promote', {
|
||||
items: [
|
||||
{ partyId: PARTY, roles: ['supplier'] },
|
||||
{ partyId: OTHER, roles: ['customer'] },
|
||||
],
|
||||
}),
|
||||
noParams,
|
||||
),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ parties: 2, suppliers: 1, customers: 1 })
|
||||
expect(mockSupabase.rpc).toHaveBeenCalledWith('promote_parties', {
|
||||
p_company_id: 'company-1',
|
||||
p_user_id: 'user-1',
|
||||
p_items: [
|
||||
{ party_id: PARTY, roles: ['supplier'] },
|
||||
{ party_id: OTHER, roles: ['customer'] },
|
||||
],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/parties/promote/undo', () => {
|
||||
it('reverses promotions for the given parties', async () => {
|
||||
enqueue({ data: 2 })
|
||||
const { status, body } = await parseJsonResponse<{ data: { count: number } }>(
|
||||
await undoPromotePost(json('/api/parties/promote/undo', { partyIds: [PARTY, OTHER] }), noParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ count: 2 })
|
||||
expect(mockSupabase.rpc).toHaveBeenCalledWith('undo_party_promotions', { p_company_id: 'company-1', p_user_id: 'user-1', p_party_ids: [PARTY, OTHER] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PartyDecideSchema } from '@/lib/api/schemas'
|
||||
|
||||
/** POST /api/parties/decide: bulk confirm or dismiss suggested parties. */
|
||||
export const POST = withRouteContext(
|
||||
'parties.decide',
|
||||
async (request, { supabase, companyId, user, log }) => {
|
||||
const validation = await validateBody(request, PartyDecideSchema, { log, operation: 'parties.decide' })
|
||||
if (!validation.success) return validation.response
|
||||
const { partyIds, kind, note } = validation.data
|
||||
const { data, error } = await supabase.rpc('decide_parties', {
|
||||
p_company_id: companyId,
|
||||
p_user_id: user.id,
|
||||
p_party_ids: partyIds,
|
||||
p_kind: kind,
|
||||
p_note: note ?? null,
|
||||
})
|
||||
if (error) throw new Error(`decide_parties failed: ${error.message}`)
|
||||
return NextResponse.json({ data: { count: Number(data) || 0, kind } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PartyUndoDecisionsSchema } from '@/lib/api/schemas'
|
||||
|
||||
/** POST /api/parties/decide/undo: reverse the latest confirm or dismiss per party (30 days). */
|
||||
export const POST = withRouteContext(
|
||||
'parties.decide.undo',
|
||||
async (request, { supabase, companyId, user, log }) => {
|
||||
const validation = await validateBody(request, PartyUndoDecisionsSchema, { log, operation: 'parties.decide.undo' })
|
||||
if (!validation.success) return validation.response
|
||||
const { data, error } = await supabase.rpc('undo_party_decisions', {
|
||||
p_company_id: companyId,
|
||||
p_user_id: user.id,
|
||||
p_party_ids: validation.data.partyIds,
|
||||
})
|
||||
if (error) throw new Error(`undo_party_decisions failed: ${error.message}`)
|
||||
return NextResponse.json({ data: { count: Number(data) || 0 } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PartyMergeSchema } from '@/lib/api/schemas'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
/** POST /api/parties/merge: soft-merge parties into a survivor; returns the decision id for undo. */
|
||||
export const POST = withRouteContext(
|
||||
'parties.merge',
|
||||
async (request, { supabase, companyId, user, log, requestId }) => {
|
||||
const validation = await validateBody(request, PartyMergeSchema, { log, operation: 'parties.merge' })
|
||||
if (!validation.success) return validation.response
|
||||
const { survivorId, mergedIds, note } = validation.data
|
||||
if (mergedIds.includes(survivorId)) {
|
||||
return errorResponseFromCode('VALIDATION_ERROR', log, { requestId, details: { field: 'mergedIds', reason: 'survivor_in_merged' } })
|
||||
}
|
||||
const { data, error } = await supabase.rpc('merge_parties', {
|
||||
p_company_id: companyId,
|
||||
p_user_id: user.id,
|
||||
p_survivor: survivorId,
|
||||
p_merged: mergedIds,
|
||||
p_note: note ?? null,
|
||||
})
|
||||
if (error) {
|
||||
if (error.code === '23503') return errorResponseFromCode('NOT_FOUND', log, { requestId })
|
||||
throw new Error(`merge_parties failed: ${error.message}`)
|
||||
}
|
||||
return NextResponse.json({ data: { decisionId: data as string, survivorId, mergedIds } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PartyUndoMergeSchema } from '@/lib/api/schemas'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
/** POST /api/parties/merge/undo: restore the parties one merge decision folded, within 30 days. */
|
||||
export const POST = withRouteContext(
|
||||
'parties.merge.undo',
|
||||
async (request, { supabase, companyId, user, log, requestId }) => {
|
||||
const validation = await validateBody(request, PartyUndoMergeSchema, { log, operation: 'parties.merge.undo' })
|
||||
if (!validation.success) return validation.response
|
||||
const { data, error } = await supabase.rpc('undo_party_merge', {
|
||||
p_company_id: companyId,
|
||||
p_user_id: user.id,
|
||||
p_decision_id: validation.data.decisionId,
|
||||
})
|
||||
if (error) {
|
||||
if (error.code === '23503') return errorResponseFromCode('NOT_FOUND', log, { requestId })
|
||||
throw new Error(`undo_party_merge failed: ${error.message}`)
|
||||
}
|
||||
return NextResponse.json({ data: { restored: Number(data) || 0 } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PartyPromoteSchema } from '@/lib/api/schemas'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
|
||||
/**
|
||||
* POST /api/parties/promote: confirm suggestions into roles. Each item
|
||||
* becomes a supplier and/or customer row filled from the party's facts;
|
||||
* undo through /api/parties/promote/undo for 30 days.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'parties.promote',
|
||||
async (request, { supabase, companyId, user, log, requestId }) => {
|
||||
const validation = await validateBody(request, PartyPromoteSchema, { log, operation: 'parties.promote' })
|
||||
if (!validation.success) return validation.response
|
||||
const { data, error } = await supabase.rpc('promote_parties', {
|
||||
p_company_id: companyId,
|
||||
p_user_id: user.id,
|
||||
p_items: validation.data.items.map((i) => ({ party_id: i.partyId, roles: i.roles })),
|
||||
})
|
||||
if (error) {
|
||||
if (error.code === '23503') return errorResponseFromCode('NOT_FOUND', log, { requestId })
|
||||
throw new Error(`promote_parties failed: ${error.message}`)
|
||||
}
|
||||
const r = (data ?? {}) as Partial<Record<'parties' | 'suppliers' | 'customers', number>>
|
||||
return NextResponse.json({ data: { parties: r.parties ?? 0, suppliers: r.suppliers ?? 0, customers: r.customers ?? 0 } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PartyUndoDecisionsSchema } from '@/lib/api/schemas'
|
||||
|
||||
/** POST /api/parties/promote/undo: reverse the latest promotion per party (30 days). */
|
||||
export const POST = withRouteContext(
|
||||
'parties.promote.undo',
|
||||
async (request, { supabase, companyId, user, log }) => {
|
||||
const validation = await validateBody(request, PartyUndoDecisionsSchema, { log, operation: 'parties.promote.undo' })
|
||||
if (!validation.success) return validation.response
|
||||
const { data, error } = await supabase.rpc('undo_party_promotions', {
|
||||
p_company_id: companyId,
|
||||
p_user_id: user.id,
|
||||
p_party_ids: validation.data.partyIds,
|
||||
})
|
||||
if (error) throw new Error(`undo_party_promotions failed: ${error.message}`)
|
||||
return NextResponse.json({ data: { count: Number(data) || 0 } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateQuery } from '@/lib/api/validate'
|
||||
import { PartiesRegisterQuerySchema } from '@/lib/api/schemas'
|
||||
import { getRegister } from '@/lib/parties/register'
|
||||
|
||||
/**
|
||||
* GET /api/parties: the Kontakter register for the active company. One
|
||||
* response carries the counts for every view plus the rows of the requested
|
||||
* view, so the segmented switch never waits on a second request.
|
||||
*/
|
||||
export const GET = withRouteContext('parties.list', async (request, { supabase, companyId, log }) => {
|
||||
const validated = validateQuery(request, PartiesRegisterQuerySchema, { log, operation: 'parties.list' })
|
||||
if (!validated.success) return validated.response
|
||||
const { view, q, period } = validated.data
|
||||
const register = await getRegister(supabase, companyId, { view, q, period })
|
||||
return NextResponse.json({ data: register })
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { suggestPartiesForCompany } from '@/lib/parties/suggest'
|
||||
|
||||
/**
|
||||
* POST /api/parties/suggest: run the suggestion pipeline for the active
|
||||
* company. Idempotent: re-running attaches new evidence and creates nothing
|
||||
* a person already decided on.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'parties.suggest',
|
||||
async (_request, { supabase, companyId, user, log }) => {
|
||||
const summary = await suggestPartiesForCompany(supabase, companyId, user.id)
|
||||
log.info('party suggestions refreshed', summary)
|
||||
return NextResponse.json({ data: summary })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Reference in New Issue
Block a user