@open-mercato/core 0.10.1-develop.7923.1.35033d071b → 0.10.1-develop.7925.1.ec40f75262
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/staff/api/timesheets/time-entries/route.js +65 -5
- package/dist/modules/staff/api/timesheets/time-entries/route.js.map +2 -2
- package/dist/modules/staff/backend/staff/time-tracking/entries/page.js +49 -25
- package/dist/modules/staff/backend/staff/time-tracking/entries/page.js.map +2 -2
- package/dist/modules/staff/lib/time-tracking-ui/TimeEntriesSummaryFooter.js +13 -6
- package/dist/modules/staff/lib/time-tracking-ui/TimeEntriesSummaryFooter.js.map +2 -2
- package/dist/modules/staff/lib/time-tracking-ui/timeEntryListData.js +23 -0
- package/dist/modules/staff/lib/time-tracking-ui/timeEntryListData.js.map +2 -2
- package/dist/modules/staff/lib/timesheets/timeEntryTotals.js +149 -0
- package/dist/modules/staff/lib/timesheets/timeEntryTotals.js.map +7 -0
- package/dist/modules/staff/widgets/injection/time-entries-summary-footer/widget.js +24 -0
- package/dist/modules/staff/widgets/injection/time-entries-summary-footer/widget.js.map +7 -0
- package/dist/modules/staff/widgets/injection-table.js +4 -0
- package/dist/modules/staff/widgets/injection-table.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/staff/AGENTS.md +1 -0
- package/src/modules/staff/api/timesheets/time-entries/route.ts +77 -4
- package/src/modules/staff/backend/staff/time-tracking/entries/page.tsx +29 -7
- package/src/modules/staff/i18n/de.json +1 -0
- package/src/modules/staff/i18n/en.json +1 -0
- package/src/modules/staff/i18n/es.json +1 -0
- package/src/modules/staff/i18n/ko.json +1 -0
- package/src/modules/staff/i18n/pl.json +1 -0
- package/src/modules/staff/lib/time-tracking-ui/TimeEntriesSummaryFooter.tsx +25 -8
- package/src/modules/staff/lib/time-tracking-ui/timeEntryListData.ts +30 -0
- package/src/modules/staff/lib/timesheets/timeEntryTotals.ts +271 -0
- package/src/modules/staff/widgets/injection/time-entries-summary-footer/widget.tsx +32 -0
- package/src/modules/staff/widgets/injection-table.ts +4 -0
|
@@ -83,7 +83,8 @@ import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
|
83
83
|
import { TimeEntryDialog } from '../../../../lib/time-tracking-ui/TimeEntryDialog'
|
|
84
84
|
import { REPORTS_PATH, reportDetailHref } from '../../../../lib/time-tracking-ui/reportLinks'
|
|
85
85
|
import { TimeEntryDurationCell } from '../../../../lib/time-tracking-ui/TimeEntryDurationCell'
|
|
86
|
-
import {
|
|
86
|
+
import type { TimeEntriesTableInjectionContext } from '../../../../widgets/injection/time-entries-summary-footer/widget'
|
|
87
|
+
import type { TimeEntryTotals } from '../../../../lib/timesheets/timeEntryTotals'
|
|
87
88
|
import {
|
|
88
89
|
collectDirectoryIds,
|
|
89
90
|
currentWeekRange,
|
|
@@ -91,6 +92,7 @@ import {
|
|
|
91
92
|
formatEntryDay,
|
|
92
93
|
isEntryLockedError,
|
|
93
94
|
readCopyDayTargetConflict,
|
|
95
|
+
readTimeEntryTotals,
|
|
94
96
|
summarizeTimeEntries,
|
|
95
97
|
toTimeEntryListRow,
|
|
96
98
|
type TimeEntryDirectory,
|
|
@@ -129,6 +131,7 @@ type EntriesResponse = {
|
|
|
129
131
|
total?: number
|
|
130
132
|
totalIsCapped?: boolean
|
|
131
133
|
totalPages?: number
|
|
134
|
+
totals?: unknown
|
|
132
135
|
}
|
|
133
136
|
|
|
134
137
|
type CopyDayResponse = {
|
|
@@ -240,6 +243,7 @@ export default function TimeTrackingEntriesPage() {
|
|
|
240
243
|
const [rows, setRows] = React.useState<TimeEntryListRow[]>([])
|
|
241
244
|
const [total, setTotal] = React.useState(0)
|
|
242
245
|
const [totalIsCapped, setTotalIsCapped] = React.useState(false)
|
|
246
|
+
const [filteredTotals, setFilteredTotals] = React.useState<TimeEntryTotals | null>(null)
|
|
243
247
|
const [totalPages, setTotalPages] = React.useState(1)
|
|
244
248
|
const [isLoading, setIsLoading] = React.useState(true)
|
|
245
249
|
const [isRefreshing, setIsRefreshing] = React.useState(false)
|
|
@@ -514,7 +518,11 @@ export default function TimeTrackingEntriesPage() {
|
|
|
514
518
|
if (hasLoadedOnceRef.current) setIsRefreshing(true)
|
|
515
519
|
else setIsLoading(true)
|
|
516
520
|
try {
|
|
517
|
-
const params = new URLSearchParams({
|
|
521
|
+
const params = new URLSearchParams({
|
|
522
|
+
page: String(page),
|
|
523
|
+
pageSize: String(PAGE_SIZE),
|
|
524
|
+
includeTotals: 'true',
|
|
525
|
+
})
|
|
518
526
|
const sort = sorting[0]
|
|
519
527
|
params.set('sortField', sort?.id ?? 'date')
|
|
520
528
|
params.set('sortDir', sort?.desc === false ? 'asc' : 'desc')
|
|
@@ -563,6 +571,7 @@ export default function TimeTrackingEntriesPage() {
|
|
|
563
571
|
)
|
|
564
572
|
setTotal(typeof listPayload.total === 'number' ? listPayload.total : items.length)
|
|
565
573
|
setTotalIsCapped(listPayload.totalIsCapped === true)
|
|
574
|
+
setFilteredTotals(readTimeEntryTotals(listPayload.totals))
|
|
566
575
|
setTotalPages(
|
|
567
576
|
typeof listPayload.totalPages === 'number'
|
|
568
577
|
? listPayload.totalPages
|
|
@@ -672,13 +681,14 @@ export default function TimeTrackingEntriesPage() {
|
|
|
672
681
|
}),
|
|
673
682
|
'success',
|
|
674
683
|
)
|
|
684
|
+
handleRefresh()
|
|
675
685
|
} catch (error) {
|
|
676
686
|
setRows(previousRows)
|
|
677
687
|
setTotal((current) => current + 1)
|
|
678
688
|
reportFailure(error, labels.errors.delete, 'staff.time_tracking.entries delete failed')
|
|
679
689
|
}
|
|
680
690
|
},
|
|
681
|
-
[labels.errors.delete, labels.noTask, mutationContext, reportFailure, rows, runMutation, t],
|
|
691
|
+
[handleRefresh, labels.errors.delete, labels.noTask, mutationContext, reportFailure, rows, runMutation, t],
|
|
682
692
|
)
|
|
683
693
|
|
|
684
694
|
const handleDuplicate = React.useCallback(
|
|
@@ -1089,12 +1099,22 @@ export default function TimeTrackingEntriesPage() {
|
|
|
1089
1099
|
])
|
|
1090
1100
|
|
|
1091
1101
|
const summary = React.useMemo(() => summarizeTimeEntries(rows), [rows])
|
|
1102
|
+
const tableId = extensionPoints.hosts.timeEntriesTable.tableId
|
|
1103
|
+
const tableInjectionContext = React.useMemo<TimeEntriesTableInjectionContext>(
|
|
1104
|
+
() => ({
|
|
1105
|
+
tableId,
|
|
1106
|
+
title: labels.title,
|
|
1107
|
+
entriesSummary: { summary, totalCount: total, canSeeMoney, totals: filteredTotals },
|
|
1108
|
+
}),
|
|
1109
|
+
[tableId, labels.title, summary, total, canSeeMoney, filteredTotals],
|
|
1110
|
+
)
|
|
1092
1111
|
|
|
1093
1112
|
return (
|
|
1094
1113
|
<Page>
|
|
1095
1114
|
<PageBody>
|
|
1096
1115
|
<DataTable<TimeEntryListRow>
|
|
1097
|
-
extensionTableId={
|
|
1116
|
+
extensionTableId={tableId}
|
|
1117
|
+
injectionContext={tableInjectionContext}
|
|
1098
1118
|
title={labels.title}
|
|
1099
1119
|
titleHeadingLevel={1}
|
|
1100
1120
|
data={rows}
|
|
@@ -1110,8 +1130,12 @@ export default function TimeTrackingEntriesPage() {
|
|
|
1110
1130
|
dropDeepLinkParams(DEEP_LINK_PARAMS.filter((id) => !values[id]))
|
|
1111
1131
|
}}
|
|
1112
1132
|
onFiltersClear={clearAllFilters}
|
|
1133
|
+
showActiveFilterChips={false}
|
|
1113
1134
|
activeFilterChips={
|
|
1114
|
-
<div
|
|
1135
|
+
<div
|
|
1136
|
+
className="flex flex-col gap-2 border-b border-border px-4 py-3"
|
|
1137
|
+
data-staff-entries-filter-chips=""
|
|
1138
|
+
>
|
|
1115
1139
|
<EntryFilterPresets
|
|
1116
1140
|
presets={presets}
|
|
1117
1141
|
activePresetId={activePresetId}
|
|
@@ -1210,8 +1234,6 @@ export default function TimeTrackingEntriesPage() {
|
|
|
1210
1234
|
}}
|
|
1211
1235
|
/>
|
|
1212
1236
|
|
|
1213
|
-
<TimeEntriesSummaryFooter summary={summary} totalCount={total} canSeeMoney={canSeeMoney} />
|
|
1214
|
-
|
|
1215
1237
|
{!canManage ? (
|
|
1216
1238
|
<p className="mt-2 text-xs text-muted-foreground">
|
|
1217
1239
|
{t('staff.time_tracking.entries.readOnlyNotice', 'You can view these entries but not change them.')}
|
|
@@ -1410,6 +1410,7 @@
|
|
|
1410
1410
|
"staff.time_tracking.entries.source.mobile": "Mobil",
|
|
1411
1411
|
"staff.time_tracking.entries.source.timer": "Timer",
|
|
1412
1412
|
"staff.time_tracking.entries.summary.count": "Gesamt ({visible} von {total} Einträgen)",
|
|
1413
|
+
"staff.time_tracking.entries.summary.filteredCount": "Gesamt aller {total} passenden Einträge",
|
|
1413
1414
|
"staff.time_tracking.entries.summary.multiCurrencyHint": "Diese Einträge werden in mehreren Währungen abgerechnet und werden daher getrennt statt summiert angezeigt.",
|
|
1414
1415
|
"staff.time_tracking.entries.table.durationAria": "Dauer des Eintrags",
|
|
1415
1416
|
"staff.time_tracking.entries.table.noTask": "Keine Aufgabe",
|
|
@@ -1410,6 +1410,7 @@
|
|
|
1410
1410
|
"staff.time_tracking.entries.source.mobile": "Mobile",
|
|
1411
1411
|
"staff.time_tracking.entries.source.timer": "Timer",
|
|
1412
1412
|
"staff.time_tracking.entries.summary.count": "Total ({visible} of {total} entries)",
|
|
1413
|
+
"staff.time_tracking.entries.summary.filteredCount": "Total of all {total} matching entries",
|
|
1413
1414
|
"staff.time_tracking.entries.summary.multiCurrencyHint": "These entries are billed in more than one currency, so they are shown separately instead of added up.",
|
|
1414
1415
|
"staff.time_tracking.entries.table.durationAria": "Entry duration",
|
|
1415
1416
|
"staff.time_tracking.entries.table.noTask": "No task",
|
|
@@ -1410,6 +1410,7 @@
|
|
|
1410
1410
|
"staff.time_tracking.entries.source.mobile": "Móvil",
|
|
1411
1411
|
"staff.time_tracking.entries.source.timer": "Cronómetro",
|
|
1412
1412
|
"staff.time_tracking.entries.summary.count": "Total ({visible} de {total} registros)",
|
|
1413
|
+
"staff.time_tracking.entries.summary.filteredCount": "Total de los {total} registros coincidentes",
|
|
1413
1414
|
"staff.time_tracking.entries.summary.multiCurrencyHint": "Estos registros se facturan en más de una moneda, por eso se muestran por separado en lugar de sumarse.",
|
|
1414
1415
|
"staff.time_tracking.entries.table.durationAria": "Duración del registro",
|
|
1415
1416
|
"staff.time_tracking.entries.table.noTask": "Sin tarea",
|
|
@@ -1410,6 +1410,7 @@
|
|
|
1410
1410
|
"staff.time_tracking.entries.source.mobile": "모바일",
|
|
1411
1411
|
"staff.time_tracking.entries.source.timer": "타이머",
|
|
1412
1412
|
"staff.time_tracking.entries.summary.count": "합계 (전체 {total}건 중 {visible}건)",
|
|
1413
|
+
"staff.time_tracking.entries.summary.filteredCount": "일치하는 항목 {total}건 전체 합계",
|
|
1413
1414
|
"staff.time_tracking.entries.summary.multiCurrencyHint": "이 기록들은 두 가지 이상의 통화로 청구되므로 합산하지 않고 따로 표시합니다.",
|
|
1414
1415
|
"staff.time_tracking.entries.table.durationAria": "기록 소요 시간",
|
|
1415
1416
|
"staff.time_tracking.entries.table.noTask": "작업 없음",
|
|
@@ -1410,6 +1410,7 @@
|
|
|
1410
1410
|
"staff.time_tracking.entries.source.mobile": "Mobilnie",
|
|
1411
1411
|
"staff.time_tracking.entries.source.timer": "Stoper",
|
|
1412
1412
|
"staff.time_tracking.entries.summary.count": "Razem ({visible} z {total} wpisów)",
|
|
1413
|
+
"staff.time_tracking.entries.summary.filteredCount": "Razem wszystkie pasujące wpisy: {total}",
|
|
1413
1414
|
"staff.time_tracking.entries.summary.multiCurrencyHint": "Te wpisy są rozliczane w więcej niż jednej walucie, więc pokazujemy je osobno zamiast sumować.",
|
|
1414
1415
|
"staff.time_tracking.entries.table.durationAria": "Czas trwania wpisu",
|
|
1415
1416
|
"staff.time_tracking.entries.table.noTask": "Bez zadania",
|
|
@@ -10,6 +10,7 @@ import { formatCurrency } from '@open-mercato/ui/utils/format'
|
|
|
10
10
|
import { useT } from '@open-mercato/shared/lib/i18n/context'
|
|
11
11
|
import { formatDuration } from '../time-tracking/duration'
|
|
12
12
|
import type { TimeEntriesSummary } from './timeEntryListData'
|
|
13
|
+
import type { TimeEntryTotals } from '../timesheets/timeEntryTotals'
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* The mockup's table footer: `Razem (5 z 23 wpisów) · 15:15 · 4 315,00 PLN`.
|
|
@@ -21,28 +22,43 @@ import type { TimeEntriesSummary } from './timeEntryListData'
|
|
|
21
22
|
* financially false, and a footer is exactly where somebody would trust it.
|
|
22
23
|
*/
|
|
23
24
|
export type TimeEntriesSummaryFooterProps = {
|
|
25
|
+
/** Sums of the rows on the current page. */
|
|
24
26
|
summary: TimeEntriesSummary
|
|
25
27
|
totalCount: number
|
|
26
28
|
canSeeMoney: boolean
|
|
29
|
+
/**
|
|
30
|
+
* Sums of the WHOLE filtered set, from the list API's `includeTotals=true`.
|
|
31
|
+
* When present the footer shows these instead of the page sums; absent or
|
|
32
|
+
* `null` keeps the page-only behaviour.
|
|
33
|
+
*/
|
|
34
|
+
totals?: TimeEntryTotals | null
|
|
27
35
|
}
|
|
28
36
|
|
|
29
|
-
function DefaultTimeEntriesSummaryFooter({ summary, totalCount, canSeeMoney }: TimeEntriesSummaryFooterProps) {
|
|
37
|
+
function DefaultTimeEntriesSummaryFooter({ summary, totalCount, canSeeMoney, totals }: TimeEntriesSummaryFooterProps) {
|
|
30
38
|
const t = useT()
|
|
31
|
-
const
|
|
39
|
+
const wholeSet = totals ?? null
|
|
40
|
+
const money = canSeeMoney ? (wholeSet ? wholeSet.money ?? [] : summary.money) : []
|
|
41
|
+
const minutes = wholeSet ? wholeSet.durationMinutes : summary.totalMinutes
|
|
32
42
|
|
|
33
43
|
return (
|
|
34
44
|
<div
|
|
35
|
-
className="
|
|
45
|
+
className="flex flex-wrap items-center justify-end gap-x-4 gap-y-1 text-sm"
|
|
36
46
|
data-testid="entries-summary-footer"
|
|
47
|
+
data-staff-entries-summary-footer=""
|
|
48
|
+
data-summary-scope={wholeSet ? 'filtered' : 'page'}
|
|
37
49
|
>
|
|
38
50
|
<span className="text-muted-foreground">
|
|
39
|
-
{
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
51
|
+
{wholeSet
|
|
52
|
+
? t('staff.time_tracking.entries.summary.filteredCount', 'Total of all {total} matching entries', {
|
|
53
|
+
total: wholeSet.entryCount,
|
|
54
|
+
})
|
|
55
|
+
: t('staff.time_tracking.entries.summary.count', 'Total ({visible} of {total} entries)', {
|
|
56
|
+
visible: summary.visibleCount,
|
|
57
|
+
total: totalCount,
|
|
58
|
+
})}
|
|
43
59
|
</span>
|
|
44
60
|
<span className="font-mono font-semibold tabular-nums text-foreground" data-testid="entries-summary-duration">
|
|
45
|
-
{formatDuration(
|
|
61
|
+
{formatDuration(minutes, 'clock')}
|
|
46
62
|
</span>
|
|
47
63
|
{money.length > 1 ? (
|
|
48
64
|
<span
|
|
@@ -76,6 +92,7 @@ const timeEntriesSummaryFooterPropsSchema: z.ZodType<TimeEntriesSummaryFooterPro
|
|
|
76
92
|
summary: opaqueProp<TimeEntriesSummary>(),
|
|
77
93
|
totalCount: z.number(),
|
|
78
94
|
canSeeMoney: z.boolean(),
|
|
95
|
+
totals: opaqueProp<TimeEntryTotals>().nullable().optional(),
|
|
79
96
|
})
|
|
80
97
|
|
|
81
98
|
registerComponent<TimeEntriesSummaryFooterProps>({
|
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
readRowString,
|
|
30
30
|
type ApiRow,
|
|
31
31
|
} from './timeEntryDialogState'
|
|
32
|
+
import type { TimeEntryTotals } from '../timesheets/timeEntryTotals'
|
|
32
33
|
|
|
33
34
|
/** The shared refusal code every write path answers when an entry is frozen in a report. */
|
|
34
35
|
export const TIME_ENTRY_LOCKED_CODE = 'time_entry_locked'
|
|
@@ -144,6 +145,35 @@ export function summarizeTimeEntries(rows: readonly TimeEntryListRow[]): TimeEnt
|
|
|
144
145
|
}
|
|
145
146
|
}
|
|
146
147
|
|
|
148
|
+
function readFiniteNumber(value: unknown): number | null {
|
|
149
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Reads the list API's optional `totals` (sent for `includeTotals=true`). Anything
|
|
154
|
+
* malformed reads as `null`, which keeps the footer on the page-only sums rather
|
|
155
|
+
* than showing a whole-set figure it cannot trust.
|
|
156
|
+
*/
|
|
157
|
+
export function readTimeEntryTotals(value: unknown): TimeEntryTotals | null {
|
|
158
|
+
if (!value || typeof value !== 'object') return null
|
|
159
|
+
const raw = value as Record<string, unknown>
|
|
160
|
+
const entryCount = readFiniteNumber(raw.entryCount)
|
|
161
|
+
const durationMinutes = readFiniteNumber(raw.durationMinutes)
|
|
162
|
+
const roundedMinutes = readFiniteNumber(raw.roundedMinutes)
|
|
163
|
+
if (entryCount === null || durationMinutes === null || roundedMinutes === null) return null
|
|
164
|
+
const totals: TimeEntryTotals = { entryCount, durationMinutes, roundedMinutes }
|
|
165
|
+
if (Array.isArray(raw.money)) {
|
|
166
|
+
totals.money = raw.money.flatMap((item) => {
|
|
167
|
+
if (!item || typeof item !== 'object') return []
|
|
168
|
+
const amount = readFiniteNumber((item as Record<string, unknown>).amount)
|
|
169
|
+
if (amount === null) return []
|
|
170
|
+
const code = (item as Record<string, unknown>).currencyCode
|
|
171
|
+
return [{ currencyCode: typeof code === 'string' && code.length > 0 ? code : null, amount }]
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
return totals
|
|
175
|
+
}
|
|
176
|
+
|
|
147
177
|
type ErrorBag = Record<string, unknown>
|
|
148
178
|
|
|
149
179
|
/**
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Totals for the WHOLE filtered set of time entries, not the page on screen.
|
|
3
|
+
*
|
|
4
|
+
* The list route answers `?includeTotals=true` with one extra aggregate query
|
|
5
|
+
* over the same scoped filters the list itself runs (`buildScopedTimeEntryListFilters`),
|
|
6
|
+
* so the footer can say "Total for these 300 entries" instead of silently summing
|
|
7
|
+
* the 50 rows of the current page.
|
|
8
|
+
*
|
|
9
|
+
* The filters are the column-keyed shape the CRUD query engine consumes. Only the
|
|
10
|
+
* operators that shape actually uses are compiled; anything else throws, and the
|
|
11
|
+
* route then omits `totals` rather than answering a different question than the
|
|
12
|
+
* list did.
|
|
13
|
+
*
|
|
14
|
+
* Money is produced by `entryAmount` — the single place an amount is produced
|
|
15
|
+
* (D-7) — and summed in cents like `sumAmounts`, so the total always equals the
|
|
16
|
+
* sum of the row `cost` values and the report totals. PostgreSQL only groups the
|
|
17
|
+
* billable, priced entries by currency, rounded minutes and both rates, and
|
|
18
|
+
* counts them; pricing each group in SQL would round exact decimals
|
|
19
|
+
* (0.75 h × 0.30 = 0.225 → 0.23) where `entryAmount` rounds a float
|
|
20
|
+
* (0.22499… → 0.22). The currency is the entry's snapshot currency or else the
|
|
21
|
+
* project's; currencies are never added together.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { sql, type Expression, type ExpressionBuilder, type Kysely, type SqlBool } from 'kysely'
|
|
25
|
+
import { entryAmount, round2 } from '../time-tracking/cost'
|
|
26
|
+
|
|
27
|
+
export type TimeEntryMoneyTotal = {
|
|
28
|
+
currencyCode: string | null
|
|
29
|
+
amount: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type TimeEntryTotals = {
|
|
33
|
+
entryCount: number
|
|
34
|
+
durationMinutes: number
|
|
35
|
+
roundedMinutes: number
|
|
36
|
+
/** Present only for a caller holding `staff.timesheets.rates.view`. */
|
|
37
|
+
money?: TimeEntryMoneyTotal[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type TotalsDb = {
|
|
41
|
+
staff_time_entries: {
|
|
42
|
+
id: string
|
|
43
|
+
tenant_id: string
|
|
44
|
+
organization_id: string
|
|
45
|
+
staff_member_id: string
|
|
46
|
+
date: string
|
|
47
|
+
duration_minutes: number
|
|
48
|
+
rounded_minutes: number | null
|
|
49
|
+
started_at: string | null
|
|
50
|
+
ended_at: string | null
|
|
51
|
+
notes: string | null
|
|
52
|
+
time_project_id: string | null
|
|
53
|
+
task_id: string | null
|
|
54
|
+
customer_id: string | null
|
|
55
|
+
is_billable: boolean
|
|
56
|
+
rate_override_amount: string | null
|
|
57
|
+
rate_currency_code: string | null
|
|
58
|
+
locked_report_id: string | null
|
|
59
|
+
deleted_at: string | null
|
|
60
|
+
}
|
|
61
|
+
staff_time_projects: {
|
|
62
|
+
id: string
|
|
63
|
+
tenant_id: string
|
|
64
|
+
organization_id: string
|
|
65
|
+
hourly_rate: string | null
|
|
66
|
+
currency_code: string | null
|
|
67
|
+
deleted_at: string | null
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const FILTERABLE_COLUMNS = new Set([
|
|
72
|
+
'id',
|
|
73
|
+
'staff_member_id',
|
|
74
|
+
'date',
|
|
75
|
+
'duration_minutes',
|
|
76
|
+
'rounded_minutes',
|
|
77
|
+
'started_at',
|
|
78
|
+
'ended_at',
|
|
79
|
+
'notes',
|
|
80
|
+
'time_project_id',
|
|
81
|
+
'task_id',
|
|
82
|
+
'customer_id',
|
|
83
|
+
'is_billable',
|
|
84
|
+
'locked_report_id',
|
|
85
|
+
])
|
|
86
|
+
|
|
87
|
+
type FilterableColumn = `e.${keyof TotalsDb['staff_time_entries']}`
|
|
88
|
+
type EntryExpressionBuilder = ExpressionBuilder<{ e: TotalsDb['staff_time_entries'] }, 'e'>
|
|
89
|
+
|
|
90
|
+
const COMPARISON_OPERATORS: Record<string, '>=' | '<=' | '>' | '<'> = {
|
|
91
|
+
$gte: '>=',
|
|
92
|
+
$lte: '<=',
|
|
93
|
+
$gt: '>',
|
|
94
|
+
$lt: '<',
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
98
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function compileColumnCondition(
|
|
102
|
+
eb: EntryExpressionBuilder,
|
|
103
|
+
column: string,
|
|
104
|
+
condition: unknown,
|
|
105
|
+
): Expression<SqlBool> {
|
|
106
|
+
if (!FILTERABLE_COLUMNS.has(column)) {
|
|
107
|
+
throw new Error(`[internal] time entry totals: unsupported filter column "${column}"`)
|
|
108
|
+
}
|
|
109
|
+
const ref = `e.${column}` as FilterableColumn
|
|
110
|
+
if (condition === null) return eb(ref, 'is', null)
|
|
111
|
+
if (!isPlainObject(condition)) return eb(ref, '=', condition as never)
|
|
112
|
+
const parts: Expression<SqlBool>[] = []
|
|
113
|
+
for (const [operator, operand] of Object.entries(condition)) {
|
|
114
|
+
if (operator === '$eq') {
|
|
115
|
+
parts.push(operand === null ? eb(ref, 'is', null) : eb(ref, '=', operand as never))
|
|
116
|
+
} else if (operator === '$ne') {
|
|
117
|
+
parts.push(operand === null ? eb(ref, 'is not', null) : eb(ref, '<>', operand as never))
|
|
118
|
+
} else if (operator === '$in') {
|
|
119
|
+
if (!Array.isArray(operand)) throw new Error('[internal] time entry totals: $in needs an array')
|
|
120
|
+
parts.push(operand.length === 0 ? sql<SqlBool>`false` : eb(ref, 'in', operand as never[]))
|
|
121
|
+
} else if (operator in COMPARISON_OPERATORS) {
|
|
122
|
+
parts.push(eb(ref, COMPARISON_OPERATORS[operator], operand as never))
|
|
123
|
+
} else if (operator === '$ilike') {
|
|
124
|
+
parts.push(eb(ref, 'ilike', operand as never))
|
|
125
|
+
} else {
|
|
126
|
+
throw new Error(`[internal] time entry totals: unsupported filter operator "${operator}"`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return parts.length === 1 ? parts[0] : eb.and(parts)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function compileTimeEntryFilters(
|
|
133
|
+
eb: EntryExpressionBuilder,
|
|
134
|
+
filters: Record<string, unknown>,
|
|
135
|
+
): Expression<SqlBool> {
|
|
136
|
+
const parts: Expression<SqlBool>[] = []
|
|
137
|
+
for (const [key, condition] of Object.entries(filters)) {
|
|
138
|
+
if (condition === undefined) continue
|
|
139
|
+
if (key === '$or' || key === '$and') {
|
|
140
|
+
if (!Array.isArray(condition) || condition.some((branch) => !isPlainObject(branch))) {
|
|
141
|
+
throw new Error(`[internal] time entry totals: ${key} needs an array of filter objects`)
|
|
142
|
+
}
|
|
143
|
+
const branches = condition.map((branch) => compileTimeEntryFilters(eb, branch as Record<string, unknown>))
|
|
144
|
+
if (key === '$or') parts.push(branches.length === 0 ? sql<SqlBool>`false` : eb.or(branches))
|
|
145
|
+
else parts.push(...branches)
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
parts.push(compileColumnCondition(eb, key, condition))
|
|
149
|
+
}
|
|
150
|
+
if (parts.length === 0) return sql<SqlBool>`true`
|
|
151
|
+
return parts.length === 1 ? parts[0] : eb.and(parts)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type TimeEntryTotalsScope = {
|
|
155
|
+
tenantId: string
|
|
156
|
+
/** Organizations the list itself is scoped to; an empty list matches nothing. */
|
|
157
|
+
organizationIds: string[]
|
|
158
|
+
canSeeRates: boolean
|
|
159
|
+
/** Mirrors the list's `withDeleted=true`: soft-deleted entries are counted too. */
|
|
160
|
+
includeDeleted?: boolean
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function toNumber(value: unknown): number {
|
|
164
|
+
const parsed = typeof value === 'number' ? value : Number(value)
|
|
165
|
+
return Number.isFinite(parsed) ? parsed : 0
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function toNullableNumber(value: unknown): number | null {
|
|
169
|
+
if (value === null || value === undefined) return null
|
|
170
|
+
const parsed = typeof value === 'number' ? value : Number(value)
|
|
171
|
+
return Number.isFinite(parsed) ? parsed : null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function baseQuery(db: Kysely<TotalsDb>, filters: Record<string, unknown>, scope: TimeEntryTotalsScope) {
|
|
175
|
+
const scoped = db
|
|
176
|
+
.selectFrom('staff_time_entries as e')
|
|
177
|
+
.where('e.tenant_id', '=', scope.tenantId)
|
|
178
|
+
.where('e.organization_id', 'in', scope.organizationIds)
|
|
179
|
+
const live = scope.includeDeleted ? scoped : scoped.where('e.deleted_at', 'is', null)
|
|
180
|
+
return live.where((eb) => compileTimeEntryFilters(eb as unknown as EntryExpressionBuilder, filters))
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function buildTimeEntryTotalsQuery(
|
|
184
|
+
db: Kysely<TotalsDb>,
|
|
185
|
+
filters: Record<string, unknown>,
|
|
186
|
+
scope: TimeEntryTotalsScope,
|
|
187
|
+
) {
|
|
188
|
+
return baseQuery(db, filters, scope).select([
|
|
189
|
+
sql<string>`count(*)`.as('entry_count'),
|
|
190
|
+
sql<string>`coalesce(sum(e.duration_minutes), 0)`.as('duration_minutes'),
|
|
191
|
+
sql<string>`coalesce(sum(e.rounded_minutes), 0)`.as('rounded_minutes'),
|
|
192
|
+
])
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function buildTimeEntryMoneyTotalsQuery(
|
|
196
|
+
db: Kysely<TotalsDb>,
|
|
197
|
+
filters: Record<string, unknown>,
|
|
198
|
+
scope: TimeEntryTotalsScope,
|
|
199
|
+
) {
|
|
200
|
+
return baseQuery(db, filters, scope)
|
|
201
|
+
.leftJoin('staff_time_projects as p', (join) =>
|
|
202
|
+
join
|
|
203
|
+
.onRef('p.id', '=', 'e.time_project_id')
|
|
204
|
+
.onRef('p.tenant_id', '=', 'e.tenant_id')
|
|
205
|
+
.onRef('p.organization_id', '=', 'e.organization_id')
|
|
206
|
+
.on('p.deleted_at', 'is', null),
|
|
207
|
+
)
|
|
208
|
+
.where('e.is_billable', '=', true)
|
|
209
|
+
.where(sql<SqlBool>`coalesce(e.rate_override_amount, p.hourly_rate) is not null`)
|
|
210
|
+
.select([
|
|
211
|
+
sql<string | null>`coalesce(nullif(trim(e.rate_currency_code), ''), p.currency_code)`.as('currency_code'),
|
|
212
|
+
sql<string>`coalesce(e.rounded_minutes, 0)`.as('rounded_minutes'),
|
|
213
|
+
sql<string | null>`e.rate_override_amount`.as('rate_override_amount'),
|
|
214
|
+
sql<string | null>`p.hourly_rate`.as('hourly_rate'),
|
|
215
|
+
sql<string>`count(*)`.as('entry_count'),
|
|
216
|
+
])
|
|
217
|
+
.groupBy([
|
|
218
|
+
sql`coalesce(nullif(trim(e.rate_currency_code), ''), p.currency_code)`,
|
|
219
|
+
sql`coalesce(e.rounded_minutes, 0)`,
|
|
220
|
+
sql`e.rate_override_amount`,
|
|
221
|
+
sql`p.hourly_rate`,
|
|
222
|
+
])
|
|
223
|
+
.orderBy(sql`coalesce(nullif(trim(e.rate_currency_code), ''), p.currency_code)`)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
type MoneyGroupRow = {
|
|
227
|
+
currency_code: string | null
|
|
228
|
+
rounded_minutes: unknown
|
|
229
|
+
rate_override_amount: unknown
|
|
230
|
+
hourly_rate: unknown
|
|
231
|
+
entry_count: unknown
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function sumTimeEntryMoneyGroups(groups: readonly MoneyGroupRow[]): TimeEntryMoneyTotal[] {
|
|
235
|
+
const centsByCurrency = new Map<string | null, number>()
|
|
236
|
+
for (const group of groups) {
|
|
237
|
+
const amount = entryAmount(
|
|
238
|
+
{
|
|
239
|
+
isBillable: true,
|
|
240
|
+
roundedMinutes: toNumber(group.rounded_minutes),
|
|
241
|
+
rateOverrideAmount: toNullableNumber(group.rate_override_amount),
|
|
242
|
+
},
|
|
243
|
+
{ hourlyRate: toNullableNumber(group.hourly_rate) },
|
|
244
|
+
)
|
|
245
|
+
if (amount === null) continue
|
|
246
|
+
const currencyCode = typeof group.currency_code === 'string' && group.currency_code.length > 0 ? group.currency_code : null
|
|
247
|
+
const cents = Math.round(round2(amount) * 100) * toNumber(group.entry_count)
|
|
248
|
+
centsByCurrency.set(currencyCode, (centsByCurrency.get(currencyCode) ?? 0) + cents)
|
|
249
|
+
}
|
|
250
|
+
return Array.from(centsByCurrency, ([currencyCode, cents]) => ({ currencyCode, amount: round2(cents / 100) }))
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export async function computeTimeEntryTotals(
|
|
254
|
+
db: Kysely<unknown>,
|
|
255
|
+
filters: Record<string, unknown>,
|
|
256
|
+
scope: TimeEntryTotalsScope,
|
|
257
|
+
): Promise<TimeEntryTotals> {
|
|
258
|
+
const typedDb = db as unknown as Kysely<TotalsDb>
|
|
259
|
+
if (scope.organizationIds.length === 0) {
|
|
260
|
+
return { entryCount: 0, durationMinutes: 0, roundedMinutes: 0, ...(scope.canSeeRates ? { money: [] } : {}) }
|
|
261
|
+
}
|
|
262
|
+
const row = await buildTimeEntryTotalsQuery(typedDb, filters, scope).executeTakeFirst()
|
|
263
|
+
const totals: TimeEntryTotals = {
|
|
264
|
+
entryCount: toNumber(row?.entry_count),
|
|
265
|
+
durationMinutes: toNumber(row?.duration_minutes),
|
|
266
|
+
roundedMinutes: toNumber(row?.rounded_minutes),
|
|
267
|
+
}
|
|
268
|
+
if (!scope.canSeeRates) return totals
|
|
269
|
+
totals.money = sumTimeEntryMoneyGroups(await buildTimeEntryMoneyTotalsQuery(typedDb, filters, scope).execute())
|
|
270
|
+
return totals
|
|
271
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import * as React from 'react'
|
|
4
|
+
import type { InjectionWidgetModule } from '@open-mercato/shared/modules/widgets/injection'
|
|
5
|
+
import {
|
|
6
|
+
TimeEntriesSummaryFooter,
|
|
7
|
+
type TimeEntriesSummaryFooterProps,
|
|
8
|
+
} from '../../../lib/time-tracking-ui/TimeEntriesSummaryFooter'
|
|
9
|
+
|
|
10
|
+
export type TimeEntriesTableInjectionContext = {
|
|
11
|
+
tableId?: string | null
|
|
12
|
+
title?: string
|
|
13
|
+
entriesSummary?: TimeEntriesSummaryFooterProps
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function TimeEntriesSummaryFooterWidget({ context }: { context: TimeEntriesTableInjectionContext }) {
|
|
17
|
+
const props = context?.entriesSummary
|
|
18
|
+
if (!props) return null
|
|
19
|
+
return <TimeEntriesSummaryFooter {...props} />
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const widget: InjectionWidgetModule<TimeEntriesTableInjectionContext> = {
|
|
23
|
+
metadata: {
|
|
24
|
+
id: 'staff.injection.time-entries-summary-footer',
|
|
25
|
+
title: 'Time entries totals',
|
|
26
|
+
description: 'Totals for the filtered time entries, rendered inside the entries table footer.',
|
|
27
|
+
features: ['staff.timesheets.view'],
|
|
28
|
+
},
|
|
29
|
+
Widget: TimeEntriesSummaryFooterWidget,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export default widget
|
|
@@ -5,6 +5,10 @@ export const injectionTable: ModuleInjectionTable = {
|
|
|
5
5
|
widgetId: 'staff.injection.timer-sidebar-indicator',
|
|
6
6
|
priority: 90,
|
|
7
7
|
},
|
|
8
|
+
'data-table:staff.time_entries.list:footer': {
|
|
9
|
+
widgetId: 'staff.injection.time-entries-summary-footer',
|
|
10
|
+
priority: 100,
|
|
11
|
+
},
|
|
8
12
|
'staff.time_tracking.settings:tabs': [
|
|
9
13
|
{
|
|
10
14
|
widgetId: 'staff.injection.time-tracking-settings-support',
|