Fix sales breakdown GL matching — exact group ID instead of fuzzy names

Switch sales breakdown column matching from fuzzy name matching to exact
gl_group_id comparison. Add gl_account_groups_list endpoint for settings
sync so columns store real Newbook group IDs. Removes the name-based
fallback that was causing sundries VAT to bleed into sundries no-VAT.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
jtricerolph 2026-07-20 08:23:54 +00:00
parent 2b04d99fd6
commit dbef4b9f7a
6 changed files with 111 additions and 28 deletions

View file

@ -16,6 +16,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url))
const UPLOADS_DIR = join(__dirname, '..', 'uploads')
const app = Fastify({ logger: true, trustProxy: true })
const startedAt = Date.now()
await app.register(cookie)
await app.register(cors, {
@ -29,7 +30,7 @@ await app.register(staticFiles, {
decorateReply: false,
})
app.get('/health', async () => ({ status: 'healthy' }))
app.get('/health', async () => ({ status: 'healthy', version: process.env.BUILD_VERSION || String(startedAt) }))
await app.register(cashupRoutes)
await app.register(newbookRoutes)

View file

@ -175,14 +175,19 @@ export async function fetchGlAccountList() {
return response?.data ?? []
}
export async function fetchGlAccountGroupsList() {
const response = await callApi('gl_account_groups_list', {})
return response?.data ?? []
}
export async function fetchGlAccountsGrouped() {
const data = await fetchGlAccountList()
const data = await fetchGlAccountGroupsList()
const groups = {}
for (const item of data) {
if (item.gl_group_id && item.gl_group_name && !groups[item.gl_group_id]) {
let displayName = item.gl_group_name
if (displayName.includes(' - ')) displayName = displayName.split(' - ').slice(1).join(' - ').trim()
groups[item.gl_group_id] = displayName
groups[String(item.gl_group_id)] = displayName
}
}
return groups

View file

@ -131,27 +131,11 @@ export async function reportRoutes(app) {
{ category: 'bacs', banked_amount: pt.bacs, reported_amount: pt.bacs },
]
// Build a lookup from gl_group_id → name using the accounts list
// gl_group_id from Newbook is often numeric; normalise to string for comparison
const glGroupById = {}
for (const a of (glAccountList || [])) {
const gid = String(a.gl_group_id ?? '')
if (gid && !glGroupById[gid]) glGroupById[gid] = (a.gl_group_name ?? '').toLowerCase().replace(/[^a-z0-9]/g, '')
}
// Sales breakdown — match earned revenue to configured columns
// Try: (1) exact code match, (2) normalised name contains code / vice-versa
// Sales breakdown — match earned revenue to configured columns by exact gl_group_id
const salesBreakdown = enabledColumns.map(col => {
const code = col.gl_code.toLowerCase().replace(/[^a-z0-9]/g, '')
const item = earnedRevenue.find(r => {
if (r.period !== date) return false
const gid = String(r.gl_group_id ?? '')
if (gid === col.gl_code || gid.toUpperCase() === col.gl_code.toUpperCase()) return true
const gName = glGroupById[gid] ?? ''
// Only fuzzy-match when the column has a non-empty gl_code — prevents
// placeholder columns (empty code) from matching any GL group via gName.includes('')
return code.length > 0 && (gName.includes(code) || code.includes(gName))
})
const item = col.gl_code
? earnedRevenue.find(r => r.period === date && String(r.gl_group_id ?? '') === String(col.gl_code))
: undefined
const net = parseFloat(item?.earned_revenue_ex || 0)
const vat = parseFloat(item?.earned_revenue_tax || 0)
const gross = parseFloat(item?.earned_revenue || 0)

View file

@ -1,5 +1,7 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { AuthGate } from './components/AuthGate'
import { UpdateBanner } from './components/UpdateBanner'
import { useVersionCheck } from './hooks/useVersionCheck'
import { Layout } from './components/Layout'
import { DailyCashUp } from './pages/DailyCashUp'
import { History } from './pages/History'
@ -42,11 +44,15 @@ function AppRoutes({ user }: { user: User }) {
}
export default function App() {
const updateAvailable = useVersionCheck('/cashup/health')
return (
<>
<BrowserRouter basename="/cashup">
<AuthGate>
{user => <AppRoutes user={user} />}
</AuthGate>
</BrowserRouter>
<UpdateBanner visible={updateAvailable} />
</>
)
}

View file

@ -0,0 +1,44 @@
import { RefreshCw } from 'lucide-react'
export function UpdateBanner({ visible }: { visible: boolean }) {
if (!visible) return null
return (
<div style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
zIndex: 9999,
background: 'var(--sidebar)',
color: 'var(--text-light)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '12px',
padding: '10px 16px',
fontSize: '14px',
boxShadow: '0 -2px 8px rgba(0,0,0,0.3)',
}}>
<span>A new version is available.</span>
<button
onClick={() => window.location.reload()}
style={{
display: 'flex',
alignItems: 'center',
gap: '6px',
background: 'var(--accent)',
color: 'var(--sidebar)',
border: 'none',
borderRadius: '4px',
padding: '6px 14px',
fontWeight: 600,
cursor: 'pointer',
fontSize: '13px',
}}
>
<RefreshCw size={14} strokeWidth={1.75} />
Reload
</button>
</div>
)
}

View file

@ -0,0 +1,43 @@
import { useEffect, useState } from 'react'
const POLL_MS = 2 * 60 * 1000
export function useVersionCheck(healthUrl: string) {
const [updateAvailable, setUpdateAvailable] = useState(false)
useEffect(() => {
let seenVersion: string | null = null
async function check() {
try {
const res = await fetch(healthUrl, { cache: 'no-store' })
if (!res.ok) return
const data = await res.json()
const v: string | undefined = data.version
if (!v) return
if (seenVersion === null) {
seenVersion = v
} else if (v !== seenVersion) {
setUpdateAvailable(true)
}
} catch {
// network error — skip silently
}
}
check()
const interval = setInterval(check, POLL_MS)
function onVisible() {
if (document.visibilityState === 'visible') check()
}
document.addEventListener('visibilitychange', onVisible)
return () => {
clearInterval(interval)
document.removeEventListener('visibilitychange', onVisible)
}
}, [healthUrl])
return updateAvailable
}