fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
countByCompany,
|
||||
deadlineUrgency,
|
||||
pickNextDeadlines,
|
||||
sortClientRows,
|
||||
filterClientRows,
|
||||
type ClientOverviewRow,
|
||||
} from '../aggregate'
|
||||
|
||||
function isoDaysFromNow(days: number): string {
|
||||
const d = new Date()
|
||||
d.setHours(0, 0, 0, 0)
|
||||
d.setDate(d.getDate() + days)
|
||||
// Local date parts, not toISOString(): UTC conversion would shift the day
|
||||
// in timezones ahead of UTC and skew the day math under test.
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${day}`
|
||||
}
|
||||
|
||||
function makeRow(overrides: Partial<ClientOverviewRow> = {}): ClientOverviewRow {
|
||||
return {
|
||||
companyId: 'c-1',
|
||||
name: 'Alpha AB',
|
||||
orgNumber: null,
|
||||
unbookedCount: 0,
|
||||
inboxCount: 0,
|
||||
nextDeadline: null,
|
||||
lastBookedDate: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('countByCompany', () => {
|
||||
it('counts rows per company id', () => {
|
||||
const counts = countByCompany([
|
||||
{ company_id: 'a' },
|
||||
{ company_id: 'b' },
|
||||
{ company_id: 'a' },
|
||||
{ company_id: 'a' },
|
||||
])
|
||||
expect(counts.get('a')).toBe(3)
|
||||
expect(counts.get('b')).toBe(1)
|
||||
expect(counts.get('c')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns an empty map for no rows', () => {
|
||||
expect(countByCompany([]).size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deadlineUrgency', () => {
|
||||
it('flags overdue on status overdue', () => {
|
||||
expect(
|
||||
deadlineUrgency({ due_date: isoDaysFromNow(30), status: 'overdue' }),
|
||||
).toBe('overdue')
|
||||
})
|
||||
|
||||
it('flags overdue on a passed due date even before the cron sweeps', () => {
|
||||
expect(
|
||||
deadlineUrgency({ due_date: isoDaysFromNow(-1), status: 'upcoming' }),
|
||||
).toBe('overdue')
|
||||
})
|
||||
|
||||
it('flags action_needed inside the 14-day window (status engine semantics)', () => {
|
||||
expect(
|
||||
deadlineUrgency({ due_date: isoDaysFromNow(14), status: 'upcoming' }),
|
||||
).toBe('action_needed')
|
||||
expect(
|
||||
deadlineUrgency({ due_date: isoDaysFromNow(1), status: 'in_progress' }),
|
||||
).toBe('action_needed')
|
||||
})
|
||||
|
||||
it('keeps far-future deadlines as upcoming', () => {
|
||||
expect(
|
||||
deadlineUrgency({ due_date: isoDaysFromNow(15), status: 'upcoming' }),
|
||||
).toBe('upcoming')
|
||||
})
|
||||
})
|
||||
|
||||
describe('pickNextDeadlines', () => {
|
||||
it('picks the earliest due date per company from unsorted input', () => {
|
||||
const next = pickNextDeadlines([
|
||||
{
|
||||
company_id: 'a',
|
||||
title: 'Later',
|
||||
due_date: isoDaysFromNow(40),
|
||||
tax_deadline_type: null,
|
||||
status: 'upcoming',
|
||||
},
|
||||
{
|
||||
company_id: 'a',
|
||||
title: 'Sooner',
|
||||
due_date: isoDaysFromNow(2),
|
||||
tax_deadline_type: 'vat_declaration',
|
||||
status: 'action_needed',
|
||||
},
|
||||
{
|
||||
company_id: 'b',
|
||||
title: 'Only',
|
||||
due_date: isoDaysFromNow(60),
|
||||
tax_deadline_type: null,
|
||||
status: 'upcoming',
|
||||
},
|
||||
])
|
||||
|
||||
expect(next.get('a')).toEqual({
|
||||
title: 'Sooner',
|
||||
dueDate: isoDaysFromNow(2),
|
||||
taxDeadlineType: 'vat_declaration',
|
||||
urgency: 'action_needed',
|
||||
})
|
||||
expect(next.get('b')?.urgency).toBe('upcoming')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sortClientRows', () => {
|
||||
it('puts overdue-deadline companies first, then sorts by unbooked count', () => {
|
||||
const rows = [
|
||||
makeRow({ companyId: 'calm', name: 'Calm AB', unbookedCount: 50 }),
|
||||
makeRow({
|
||||
companyId: 'late',
|
||||
name: 'Late AB',
|
||||
unbookedCount: 0,
|
||||
nextDeadline: {
|
||||
title: 'Moms',
|
||||
dueDate: isoDaysFromNow(-5),
|
||||
taxDeadlineType: 'vat_declaration',
|
||||
urgency: 'overdue',
|
||||
},
|
||||
}),
|
||||
makeRow({ companyId: 'busy', name: 'Busy AB', unbookedCount: 120 }),
|
||||
]
|
||||
|
||||
expect(sortClientRows(rows).map((r) => r.companyId)).toEqual([
|
||||
'late',
|
||||
'busy',
|
||||
'calm',
|
||||
])
|
||||
})
|
||||
|
||||
it('orders overdue companies by earliest due date', () => {
|
||||
const rows = [
|
||||
makeRow({
|
||||
companyId: 'less-late',
|
||||
name: 'A',
|
||||
nextDeadline: {
|
||||
title: 'Moms',
|
||||
dueDate: isoDaysFromNow(-2),
|
||||
taxDeadlineType: null,
|
||||
urgency: 'overdue',
|
||||
},
|
||||
}),
|
||||
makeRow({
|
||||
companyId: 'most-late',
|
||||
name: 'B',
|
||||
nextDeadline: {
|
||||
title: 'AGI',
|
||||
dueDate: isoDaysFromNow(-30),
|
||||
taxDeadlineType: null,
|
||||
urgency: 'overdue',
|
||||
},
|
||||
}),
|
||||
]
|
||||
|
||||
expect(sortClientRows(rows).map((r) => r.companyId)).toEqual([
|
||||
'most-late',
|
||||
'less-late',
|
||||
])
|
||||
})
|
||||
|
||||
it('tie-breaks by name so the list is stable', () => {
|
||||
const rows = [
|
||||
makeRow({ companyId: 'b', name: 'Beta AB', unbookedCount: 3 }),
|
||||
makeRow({ companyId: 'a', name: 'Alfa AB', unbookedCount: 3 }),
|
||||
]
|
||||
expect(sortClientRows(rows).map((r) => r.companyId)).toEqual(['a', 'b'])
|
||||
})
|
||||
|
||||
it('does not mutate the input array', () => {
|
||||
const rows = [
|
||||
makeRow({ companyId: 'x', unbookedCount: 1 }),
|
||||
makeRow({ companyId: 'y', unbookedCount: 9 }),
|
||||
]
|
||||
const before = rows.map((r) => r.companyId)
|
||||
sortClientRows(rows)
|
||||
expect(rows.map((r) => r.companyId)).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('filterClientRows', () => {
|
||||
const rows = [
|
||||
makeRow({ companyId: 'a', name: 'Alfa Bygg AB', orgNumber: '556012-5790' }),
|
||||
makeRow({ companyId: 'b', name: 'Beta Konsult AB', orgNumber: '5591234567' }),
|
||||
]
|
||||
|
||||
it('returns everything for an empty query', () => {
|
||||
expect(filterClientRows(rows, ' ')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('matches case-insensitively on name', () => {
|
||||
expect(filterClientRows(rows, 'alfa').map((r) => r.companyId)).toEqual(['a'])
|
||||
})
|
||||
|
||||
it('matches org numbers ignoring separators', () => {
|
||||
expect(filterClientRows(rows, '5560125790').map((r) => r.companyId)).toEqual(['a'])
|
||||
expect(filterClientRows(rows, '559123').map((r) => r.companyId)).toEqual(['b'])
|
||||
})
|
||||
|
||||
it('returns nothing on a miss', () => {
|
||||
expect(filterClientRows(rows, 'gamma')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Pure aggregation helpers for the byrå cockpit client list (WL-14).
|
||||
*
|
||||
* The fetch layer (lib/clients/fetch-client-overview.ts) runs a handful of
|
||||
* grouped queries across all client companies; everything that can be
|
||||
* computed without I/O lives here so it is unit-testable: per-company
|
||||
* counting, next-deadline selection with the 14-day ACTION_NEEDED semantics
|
||||
* from lib/deadlines/status-engine.ts, and the urgency sort (overdue
|
||||
* deadlines first, then largest unbooked pile).
|
||||
*/
|
||||
|
||||
import {
|
||||
ACTION_NEEDED_THRESHOLD_DAYS,
|
||||
daysUntilDeadline,
|
||||
} from '@/lib/deadlines/status-engine'
|
||||
|
||||
export type DeadlineUrgency = 'overdue' | 'action_needed' | 'upcoming'
|
||||
|
||||
export interface ClientDeadline {
|
||||
title: string
|
||||
dueDate: string
|
||||
taxDeadlineType: string | null
|
||||
urgency: DeadlineUrgency
|
||||
}
|
||||
|
||||
export interface ClientOverviewRow {
|
||||
companyId: string
|
||||
name: string
|
||||
orgNumber: string | null
|
||||
/** Canonical "att bokföra" count (lib/worklist book_transaction predicate). */
|
||||
unbookedCount: number
|
||||
/** Unconsumed inbox documents (lib/worklist inbox_document predicate). */
|
||||
inboxCount: number
|
||||
nextDeadline: ClientDeadline | null
|
||||
/** Latest posted verifikat date; null = nothing booked yet. */
|
||||
lastBookedDate: string | null
|
||||
}
|
||||
|
||||
/** Count rows per company_id from a flat grouped-query result. */
|
||||
export function countByCompany(rows: Array<{ company_id: string }>): Map<string, number> {
|
||||
const counts = new Map<string, number>()
|
||||
for (const row of rows) {
|
||||
counts.set(row.company_id, (counts.get(row.company_id) ?? 0) + 1)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
export interface DeadlineRowInput {
|
||||
company_id: string
|
||||
title: string
|
||||
due_date: string
|
||||
tax_deadline_type: string | null
|
||||
status: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Deadline urgency per the status engine: `overdue` status (or a passed due
|
||||
* date the cron has not swept yet) flags overdue; within the 14-day
|
||||
* ACTION_NEEDED window flags action_needed; everything else is upcoming.
|
||||
* Computing from the due date as well as the stored status keeps the cockpit
|
||||
* honest between cron runs.
|
||||
*/
|
||||
export function deadlineUrgency(row: Pick<DeadlineRowInput, 'due_date' | 'status'>): DeadlineUrgency {
|
||||
const days = daysUntilDeadline(row.due_date)
|
||||
if (row.status === 'overdue' || days < 0) return 'overdue'
|
||||
if (row.status === 'action_needed' || days <= ACTION_NEEDED_THRESHOLD_DAYS) {
|
||||
return 'action_needed'
|
||||
}
|
||||
return 'upcoming'
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick each company's next deadline (earliest due date) from a flat list of
|
||||
* open deadlines. Input does not need to be pre-sorted.
|
||||
*/
|
||||
export function pickNextDeadlines(rows: DeadlineRowInput[]): Map<string, ClientDeadline> {
|
||||
const next = new Map<string, { dueDate: string; row: DeadlineRowInput }>()
|
||||
for (const row of rows) {
|
||||
const current = next.get(row.company_id)
|
||||
if (!current || row.due_date < current.dueDate) {
|
||||
next.set(row.company_id, { dueDate: row.due_date, row })
|
||||
}
|
||||
}
|
||||
const result = new Map<string, ClientDeadline>()
|
||||
for (const [companyId, { row }] of next) {
|
||||
result.set(companyId, {
|
||||
title: row.title,
|
||||
dueDate: row.due_date,
|
||||
taxDeadlineType: row.tax_deadline_type,
|
||||
urgency: deadlineUrgency(row),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Urgency sort per the WL-14 resolution: companies with an OVERDUE deadline
|
||||
* first (earliest due date wins within the band), then everyone else by
|
||||
* unbooked count descending. Name is the stable tie-break so the list does
|
||||
* not jitter between renders.
|
||||
*/
|
||||
export function sortClientRows(rows: ClientOverviewRow[]): ClientOverviewRow[] {
|
||||
const byName = (a: ClientOverviewRow, b: ClientOverviewRow) =>
|
||||
a.name.localeCompare(b.name, 'sv')
|
||||
|
||||
return [...rows].sort((a, b) => {
|
||||
const aOverdue = a.nextDeadline?.urgency === 'overdue'
|
||||
const bOverdue = b.nextDeadline?.urgency === 'overdue'
|
||||
if (aOverdue !== bOverdue) return aOverdue ? -1 : 1
|
||||
if (aOverdue && bOverdue) {
|
||||
const byDue = a.nextDeadline!.dueDate.localeCompare(b.nextDeadline!.dueDate)
|
||||
if (byDue !== 0) return byDue
|
||||
}
|
||||
if (a.unbookedCount !== b.unbookedCount) return b.unbookedCount - a.unbookedCount
|
||||
return byName(a, b)
|
||||
})
|
||||
}
|
||||
|
||||
/** Case-insensitive free-text filter on name and org number. */
|
||||
export function filterClientRows(rows: ClientOverviewRow[], query: string): ClientOverviewRow[] {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return rows
|
||||
const qDigits = q.replace(/[^0-9]/g, '')
|
||||
return rows.filter((row) => {
|
||||
if (row.name.toLowerCase().includes(q)) return true
|
||||
const org = row.orgNumber ?? ''
|
||||
if (org.toLowerCase().includes(q)) return true
|
||||
// "5560-1257" should match "5560125790": compare digits to digits.
|
||||
return qDigits.length > 0 && org.replace(/[^0-9]/g, '').includes(qDigits)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* Byrå cockpit aggregation (WL-14): one overview row per client company.
|
||||
*
|
||||
* Read-first by design (WL-09): every query here is a cross-membership READ,
|
||||
* which RLS already allows via user_company_ids(); nothing writes. Queries
|
||||
* are GROUPED across all client company ids (a handful of queries total,
|
||||
* never N-per-company):
|
||||
*
|
||||
* 1. byrå team membership (teams.kind = 'byra')
|
||||
* 2. client companies (companies.team_id = byrå team)
|
||||
* 3. display names/org numbers (company_settings)
|
||||
* 4. unbooked transactions (canonical lib/worklist book_transaction predicate)
|
||||
* 5. unconsumed inbox documents (lib/worklist inbox_document predicate,
|
||||
* including the document_attachments backstop)
|
||||
* 6. open deadlines (status-engine semantics)
|
||||
* 7. latest posted verifikat per company (embedded order+limit, one query)
|
||||
*
|
||||
* fetchAllRows guards every query that can exceed PostgREST's 1000-row cap.
|
||||
*/
|
||||
|
||||
import { chunk as chunked } from '@/lib/utils'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import {
|
||||
countByCompany,
|
||||
pickNextDeadlines,
|
||||
sortClientRows,
|
||||
type ClientOverviewRow,
|
||||
type DeadlineRowInput,
|
||||
} from '@/lib/clients/aggregate'
|
||||
|
||||
export interface ClientOverview {
|
||||
team: { id: string; name: string }
|
||||
/** The caller's role in the byrå team: gates the create action (WL-15). */
|
||||
role: 'owner' | 'admin' | 'member'
|
||||
clients: ClientOverviewRow[]
|
||||
}
|
||||
|
||||
/** Max ids per PostgREST .in() filter (mirrors lib/worklist IN_CLAUSE_CHUNK). */
|
||||
const IN_CLAUSE_CHUNK = 150
|
||||
|
||||
interface ByraMembershipRow {
|
||||
team_id: string
|
||||
role: string
|
||||
teams: { id: string; name: string; kind: string } | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller's byrå team membership, or null for non-byrå users. When a user
|
||||
* somehow belongs to several byrå teams the earliest-created team wins
|
||||
* (deterministic, mirrors ensure_user_team's tie-break).
|
||||
*/
|
||||
export async function getByraMembership(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
): Promise<{ teamId: string; teamName: string; role: ClientOverview['role'] } | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('team_members')
|
||||
.select('team_id, role, teams:team_id!inner(id, name, kind, created_at)')
|
||||
.eq('user_id', userId)
|
||||
.eq('teams.kind', 'byra')
|
||||
.order('created_at', { ascending: true })
|
||||
|
||||
if (error || !data || data.length === 0) return null
|
||||
|
||||
const row = data[0] as unknown as ByraMembershipRow
|
||||
const role = row.role === 'owner' || row.role === 'admin' ? row.role : 'member'
|
||||
return {
|
||||
teamId: row.team_id,
|
||||
teamName: row.teams?.name ?? '',
|
||||
role,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate the client overview for the caller's byrå team. Returns null when
|
||||
* the user is not a byrå team member (the route maps that to 403, the page to
|
||||
* a redirect).
|
||||
*/
|
||||
export async function fetchClientOverview(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
): Promise<ClientOverview | null> {
|
||||
const membership = await getByraMembership(supabase, userId)
|
||||
if (!membership) return null
|
||||
|
||||
// 2. Client companies: everything hanging on the byrå team, archived
|
||||
// excluded. RLS additionally scopes this to companies the caller can read
|
||||
// (team sync makes every byrå member a member of every client company).
|
||||
const companies = await fetchAllRows<{
|
||||
id: string
|
||||
name: string
|
||||
org_number: string | null
|
||||
}>(({ from, to }) =>
|
||||
supabase
|
||||
.from('companies')
|
||||
.select('id, name, org_number')
|
||||
.eq('team_id', membership.teamId)
|
||||
.is('archived_at', null)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
)
|
||||
|
||||
if (companies.length === 0) {
|
||||
return {
|
||||
team: { id: membership.teamId, name: membership.teamName },
|
||||
role: membership.role,
|
||||
clients: [],
|
||||
}
|
||||
}
|
||||
|
||||
const companyIds = companies.map((c) => c.id)
|
||||
const idChunks = chunked(companyIds, IN_CLAUSE_CHUNK)
|
||||
|
||||
// 3. Current display names + settings org numbers (companies.name can be
|
||||
// stale; the dashboard layout uses the same source).
|
||||
const settingsRows: Array<{
|
||||
company_id: string
|
||||
company_name: string | null
|
||||
org_number: string | null
|
||||
}> = []
|
||||
for (const chunk of idChunks) {
|
||||
const { data, error } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_id, company_name, org_number')
|
||||
.in('company_id', chunk)
|
||||
if (error) throw new Error(error.message)
|
||||
settingsRows.push(...(data ?? []))
|
||||
}
|
||||
const settingsByCompany = new Map(settingsRows.map((s) => [s.company_id, s]))
|
||||
|
||||
// 4. Unbooked transactions: the canonical predicate (is_business IS NULL
|
||||
// AND is_ignored = false; see lib/worklist/types.ts book_transaction).
|
||||
const unbookedRows: Array<{ company_id: string }> = []
|
||||
for (const chunk of idChunks) {
|
||||
const rows = await fetchAllRows<{ id: string; company_id: string }>(({ from, to }) =>
|
||||
supabase
|
||||
.from('transactions')
|
||||
.select('id, company_id')
|
||||
.in('company_id', chunk)
|
||||
.is('is_business', null)
|
||||
.eq('is_ignored', false)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
)
|
||||
unbookedRows.push(...rows)
|
||||
}
|
||||
const unbookedByCompany = countByCompany(unbookedRows)
|
||||
|
||||
// 5. Unconsumed inbox documents (lib/worklist inbox_document): items with a
|
||||
// file that became nothing yet, whose document is still unlinked.
|
||||
const inboxRows: Array<{ company_id: string; document_id: string | null }> = []
|
||||
for (const chunk of idChunks) {
|
||||
const rows = await fetchAllRows<{
|
||||
id: string
|
||||
company_id: string
|
||||
document_id: string | null
|
||||
}>(({ from, to }) =>
|
||||
supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, company_id, document_id')
|
||||
.in('company_id', chunk)
|
||||
.not('document_id', 'is', null)
|
||||
.is('created_supplier_invoice_id', null)
|
||||
.is('created_journal_entry_id', null)
|
||||
.is('matched_transaction_id', null)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
)
|
||||
inboxRows.push(...rows)
|
||||
}
|
||||
|
||||
const docIds = [
|
||||
...new Set(inboxRows.map((r) => r.document_id).filter((id): id is string => !!id)),
|
||||
]
|
||||
const unlinkedDocRows: Array<{ company_id: string }> = []
|
||||
for (const chunk of chunked(docIds, IN_CLAUSE_CHUNK)) {
|
||||
const { data, error } = await supabase
|
||||
.from('document_attachments')
|
||||
.select('id, company_id')
|
||||
.in('id', chunk)
|
||||
.is('journal_entry_id', null)
|
||||
.eq('is_current_version', true)
|
||||
if (error) throw new Error(error.message)
|
||||
unlinkedDocRows.push(...(data ?? []))
|
||||
}
|
||||
const inboxByCompany = countByCompany(unlinkedDocRows)
|
||||
|
||||
// 6. Open deadlines across all clients, then the earliest per company with
|
||||
// the 14-day ACTION_NEEDED semantics (lib/deadlines/status-engine.ts).
|
||||
const deadlineRows: DeadlineRowInput[] = []
|
||||
for (const chunk of idChunks) {
|
||||
const rows = await fetchAllRows<DeadlineRowInput & { id: string }>(({ from, to }) =>
|
||||
supabase
|
||||
.from('deadlines')
|
||||
.select('id, company_id, title, due_date, tax_deadline_type, status')
|
||||
.in('company_id', chunk)
|
||||
.eq('is_completed', false)
|
||||
.is('dismissed_at', null)
|
||||
.in('status', ['upcoming', 'action_needed', 'in_progress', 'overdue'])
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
)
|
||||
deadlineRows.push(...rows)
|
||||
}
|
||||
const nextDeadlineByCompany = pickNextDeadlines(deadlineRows)
|
||||
|
||||
// 7. Latest posted verifikat date per company: ONE query using PostgREST's
|
||||
// per-parent embedded order + limit (lateral join under the hood), instead
|
||||
// of N latest-entry queries.
|
||||
const lastBookedByCompany = new Map<string, string>()
|
||||
for (const chunk of idChunks) {
|
||||
const { data, error } = await supabase
|
||||
.from('companies')
|
||||
.select('id, journal_entries(entry_date)')
|
||||
.in('id', chunk)
|
||||
.eq('journal_entries.status', 'posted')
|
||||
.order('entry_date', { referencedTable: 'journal_entries', ascending: false })
|
||||
.limit(1, { referencedTable: 'journal_entries' })
|
||||
if (error) throw new Error(error.message)
|
||||
for (const row of (data ?? []) as Array<{
|
||||
id: string
|
||||
journal_entries: Array<{ entry_date: string }> | null
|
||||
}>) {
|
||||
const entryDate = row.journal_entries?.[0]?.entry_date
|
||||
if (entryDate) lastBookedByCompany.set(row.id, entryDate)
|
||||
}
|
||||
}
|
||||
|
||||
const clients: ClientOverviewRow[] = companies.map((company) => {
|
||||
const settings = settingsByCompany.get(company.id)
|
||||
return {
|
||||
companyId: company.id,
|
||||
name: settings?.company_name || company.name,
|
||||
orgNumber: company.org_number ?? settings?.org_number ?? null,
|
||||
unbookedCount: unbookedByCompany.get(company.id) ?? 0,
|
||||
inboxCount: inboxByCompany.get(company.id) ?? 0,
|
||||
nextDeadline: nextDeadlineByCompany.get(company.id) ?? null,
|
||||
lastBookedDate: lastBookedByCompany.get(company.id) ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
team: { id: membership.teamId, name: membership.teamName },
|
||||
role: membership.role,
|
||||
clients: sortClientRows(clients),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user