Files
accounted/app/api/webshop-orders/route.ts
T
MattssonandClaude Fable 5 1f9578ca76 feat(woo): mark an order as already booked outside the integration (#1895)
* feat(woo): mark an order as already booked outside the integration

Orders booked by hand before the store was connected sat under Att
bokfora forever: the only exits were the book and create-invoice routes.

- Migration: manually_booked_at/_by + optional
  manually_booked_journal_entry_id on webshop_orders (informational link,
  no financial freeze; the mark produced no accounting objects).
- POST/DELETE /api/webshop-orders/[id]/mark-booked: mark with optional
  posted-verifikat reference (validated per company), conditional claim
  against concurrent booking/invoicing; unmark is a plain revert.
- book and create-invoice routes refuse marked rows (409
  WEBSHOP_ORDER_MANUALLY_BOOKED) and exclude them in their atomic claims.
- List route: booked/unbooked filters treat a manual mark as a closed
  exit, so marked rows leave the Att bokfora tab and join Bokforda.
- Orders page: row overflow menu with Markera som bokford / Angra
  markering, MarkOrderBookedDialog with a searchable candidate list of
  posted entries near the order date, muted status text linking to the
  referenced verifikat.

Fixes #1879

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(woo): close skeptic findings on the manual-booked mark

- mark-booked applies the same open-twin gate as book/create-invoice:
  an OPEN legacy feed transaction blocks the mark (409
  WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN); ignored or booked feed rows
  unlock it, so no open path to a duplicate remains.
- ingest treats manually marked rows as frozen for drift purposes:
  remote financial deltas set remote_changed_after_freeze (same badge as
  booked rows) instead of silently refreshing the row under the user's
  assertion.
- re-marking with a journal_entry_id updates the informational link
  instead of silently dropping it.
- dialog: candidate amount computed from the returned lines (the list
  API does not return total_amount), newest-first ordering, cap hint.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(migrations): bump webshop manual-booking migration past freshly merged 20260825120000

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(woo): resolve PR review findings in one pass

- freeze v3 migration: financial fields are frozen at the DB level while
  a row is manually marked as booked (review finding: the mark's freeze
  lived only in ingest.ts, so any other write path could silently mutate
  a marked row); unmark stays the escape hatch. pg test added.
- pass the active locale to getErrorMessage in the orders page and
  MarkOrderBookedDialog (CodeRabbit: English users got Swedish errors).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 14:23:56 +02:00

80 lines
3.1 KiB
TypeScript

import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateQuery } from '@/lib/api/validate'
import { WebshopOrdersListQuerySchema } from '@/lib/api/schemas'
import { errorResponse } from '@/lib/errors/get-structured-error'
ensureInitialized()
const DEFAULT_LIMIT = 50
/**
* List webshop order rows for the Orders page, with a store facet for the
* per-shop filter. Refund rows are returned inline (they are independent
* bookable rows) and grouped client-side under their parent.
*/
export const GET = withRouteContext(
'webshop_order.list',
async (request, { supabase, companyId, log, requestId }) => {
const validation = validateQuery(request, WebshopOrdersListQuerySchema)
if (!validation.success) return validation.response
const { platform, store_scope, status, row_type, paid, booked } = validation.data
const limit = validation.data.limit ?? DEFAULT_LIMIT
const offset = validation.data.offset ?? 0
let query = supabase
.from('webshop_orders')
.select('*', { count: 'exact' })
.eq('company_id', companyId)
.order('order_date', { ascending: false })
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1)
if (platform) query = query.eq('platform', platform)
if (store_scope) query = query.eq('store_scope', store_scope)
if (status) query = query.eq('status', status)
if (row_type) query = query.eq('row_type', row_type)
if (paid) query = query.eq('is_paid', paid === 'paid')
// "Booked" counts every closed exit: booked via the integration OR
// marked as manually booked outside it; "unbooked" is the open set the
// Att bokfora tab shows, so a manual mark removes the row from it.
if (booked === 'booked') {
query = query.or('journal_entry_id.not.is.null,manually_booked_at.not.is.null')
}
if (booked === 'unbooked') {
query = query.is('journal_entry_id', null).is('manually_booked_at', null)
}
const { data, error, count } = await query
if (error) {
log.error('failed to list webshop orders', error)
return errorResponse(error, log, { requestId })
}
// Store facet for the filter dropdown: cheap distinct over the company's
// stores (small cardinality; the select is capped defensively).
const { data: facetRows, error: facetError } = await supabase
.from('webshop_orders')
.select('platform, store_scope, store_label')
.eq('company_id', companyId)
.eq('row_type', 'order')
.order('store_scope')
.limit(5000)
if (facetError) {
log.error('failed to build store facet', facetError)
return errorResponse(facetError, log, { requestId })
}
const seen = new Set<string>()
const stores: Array<{ platform: string; store_scope: string; store_label: string | null }> = []
for (const row of facetRows ?? []) {
const key = `${row.platform}:${row.store_scope}`
if (seen.has(key)) continue
seen.add(key)
stores.push(row)
}
return NextResponse.json({ data: data ?? [], count, stores })
},
)