Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/apps/sales/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,35 @@ revenue keeps report `00O1K000009GxBtUAK` and the customer matrices.

Deploy the companion Reports API changes before the UI. The same shared dashboard
also appears in the Reports portal. No browser Salesforce credentials are needed.


### PM-6783 goods-sold customer controls

Goods Sold Customer-Wise has independent inclusive **From date** / **To date**
controls and an offering-type checkbox group (multiple selections, or **ALL**).
**Apply filters** requests the selected range; **Reset filters** returns to the
shared current-fiscal-year payments response. The other charts and the revenue
customer table keep their existing scopes. The API receives UTC midnight for the
start and midnight after the selected To day as the exclusive end. Reversed
ranges are rejected locally. Filtered tables label their sum **Period total**.

**Member Payment** shows `customerPayments`; **Booking Cost** shows
`customerBookingCosts` (member payments plus challenge fees). Both measures use
the same customer grouping, date/offering selection and Monthly/Quarterly view.
Changing measures does not refetch. Missing booking-cost data is shown explicitly
instead of substituting the member-payment matrix. Failed filtered requests have
an independent retry and superseded requests are cancelled.

The companion PM-6783 Reports API change supplies `filterOptions.offeringType`
and `customerBookingCosts`. It resolves offerings by billing-account ID through
the linked Salesforce Opportunity, then applies the selection before payment
aggregation. ALL includes unknown/unmapped offerings; Unknown can also be
selected explicitly. Missing fees remain unknown, with a source notice; totals
include known amounts only. The API retains portal scope and existing payment
version/status rules.

Deploy the companion Reports API change before this UI. Existing Salesforce
credentials and read permissions must allow the billing-account/Opportunity
lookup. A source failure is shown beside this report; selected offerings are
never silently ignored. The date range is limited to 24 months, matching the API.
Repeated quarter labels include the calendar year when a range spans fiscal years.
7 changes: 5 additions & 2 deletions src/apps/sales/src/SalesCustomerTable.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* The horizontally scrolling table region must be focusable for keyboard scrolling. */
/* eslint-disable jsx-a11y/no-noninteractive-tabindex */
import { FC, useCallback, useId, useState } from 'react'
import { FC, ReactNode, useCallback, useId, useState } from 'react'

import { MonthlySalesChart, SalesDashboardPeriod } from './sales-dashboard.service'
import { salesPeriodChart } from './sales-dashboard.utils'
Expand All @@ -15,6 +15,7 @@ import styles from './SalesDashboardsPage.module.scss'
*/
const SalesCustomerTable: FC<{
data: MonthlySalesChart; title: string; notices?: string[]; period?: SalesDashboardPeriod
controls?: ReactNode; totalLabel?: string; emptyMessage?: string
}> = props => {
const data = salesPeriodChart(props.data, props.period ?? 'Monthly')
const [expanded, setExpanded] = useState(false)
Expand All @@ -23,6 +24,7 @@ const SalesCustomerTable: FC<{
return (
<article className={`${styles.card} ${styles.customerTable}`}>
<h3>{props.title}</h3>
{props.controls}
{props.notices?.map(notice => <p key={notice} role='status'>{notice}</p>)}
{data.series.length ? (
<SalesDashboardTable
Expand All @@ -32,9 +34,10 @@ const SalesCustomerTable: FC<{
firstColumn='Customer'
limit={expanded ? undefined : 5}
id={tableId}
totalLabel={props.totalLabel}
showTotal
/>
) : <p>No customer data in this fiscal year.</p>}
) : <p>{props.emptyMessage ?? 'No customer data in this fiscal year.'}</p>}
{data.series.length > 5 && (
<button
type='button'
Expand Down
11 changes: 7 additions & 4 deletions src/apps/sales/src/SalesDashboardTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ import styles from './SalesDashboardsPage.module.scss'
/** A shared category-by-period matrix; sort the full dataset before limiting visible customer rows. */
const SalesDashboardTable: FC<{
chart: MonthlySalesChart; period?: SalesDashboardPeriod; caption: string; firstColumn?: string
limit?: number; id?: string; showTotal?: boolean
limit?: number; id?: string; showTotal?: boolean; totalLabel?: string
}> = props => {
const chart = props.chart
const [sort, setSort] = useState({ ascending: true, column: 'label' })
const periodLabels = chart.months.map(month => salesPeriodLabel(month.month, props.period ?? 'Monthly'))
const repeatedLabels = new Set(periodLabels).size < periodLabels.length
const columns = [
{ key: 'label', label: props.firstColumn ?? 'Field' },
{ key: 'annual', label: 'Annual' },
...chart.months.map(month => ({
key: month.month, label: salesPeriodLabel(month.month, props.period ?? 'Monthly'),
{ key: 'annual', label: props.totalLabel ?? 'Annual' },
...chart.months.map((month, index) => ({
key: month.month,
label: repeatedLabels ? `${periodLabels[index]} ${month.month.slice(0, 4)}` : periodLabels[index],
})),
]
const active = columns.some(column => column.key === sort.column) ? sort : { ascending: true, column: 'label' }
Expand Down
13 changes: 12 additions & 1 deletion src/apps/sales/src/SalesDashboardsPage.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@
margin: 16px 0;

label { display: flex; flex: 0 1 320px; flex-direction: column; gap: 6px; min-width: 0; }
select { background: #fff; border: 1px solid #aab3c5; border-radius: 6px; min-height: 40px; padding: 8px; width: 100%; }
select, input[type='date'] { background: #fff; border: 1px solid #aab3c5; border-radius: 6px; min-height: 40px; padding: 8px; width: 100%; }
}

.tableToggle {
Expand All @@ -146,3 +146,14 @@

&:focus-visible { outline: 2px solid #0f62fe; outline-offset: 4px; }
}

.offeringFilters {
display: flex;
flex-wrap: wrap;
gap: 12px 24px;
margin: 16px 0;

legend { margin-bottom: 8px; }
label { align-items: center; display: flex; gap: 8px; }
input { accent-color: #111b46; }
}
8 changes: 2 additions & 6 deletions src/apps/sales/src/SalesDashboardsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { SalesDashboardSource, useSalesDashboard } from './useSalesDashboard'
import GroupBy from './SalesDashboardGroupBy'
import SalesCustomerTable from './SalesCustomerTable'
import SalesDashboardChart from './SalesDashboardChart'
import SalesGoodsSold from './SalesGoodsSold'
import styles from './SalesDashboardsPage.module.scss'

/**
Expand Down Expand Up @@ -308,12 +309,7 @@ const SalesDashboardsPage: FC<{ portal?: SalesDashboardPortal }> = props => {
accountCategory={accountCategory || undefined}
offeringType={offeringType || undefined}
/>
<CustomerDashboard
source={payments}
field='customerPayments'
title='Goods Sold Customer-Wise'
period={period}
/>
<SalesGoodsSold source={payments} portal={portal} refreshKey={refreshKey} period={period} />
</section>
</div>
)
Expand Down
180 changes: 180 additions & 0 deletions src/apps/sales/src/SalesGoodsSold.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/* eslint-disable import/no-extraneous-dependencies, ordered-imports/ordered-imports */
import '@testing-library/jest-dom'
import { ButtonHTMLAttributes } from 'react'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'

import { fetchSalesDashboard, SalesDashboardResponse } from './sales-dashboard.service'
import SalesGoodsSold from './SalesGoodsSold'

jest.mock('./sales-dashboard.service', () => ({ fetchSalesDashboard: jest.fn() }))
jest.mock('~/libs/ui', () => ({
Button: (props: ButtonHTMLAttributes<HTMLButtonElement>) => (
<button type='button' onClick={props.onClick} disabled={props.disabled}>{props.children}</button>
),
LoadingSpinner: (props: { message: string }) => <span role='status'>{props.message}</span>,
}), { virtual: true })

const response: SalesDashboardResponse = {
charts: [],
customerPayments: {
description: '',
id: 'payments',
months: [
{ month: '2026-04-01', values: { a: 100, b: 50 } },
{ month: '2026-05-01', values: { a: 200, b: -20 } },
],
series: [{ key: 'a', label: 'Acme' }, { key: 'b', label: 'Beta' }],
stacked: true,
title: '',
unit: 'currency',
},
filterOptions: { offeringType: ['AI Training', 'Flexible Talent', 'TopGear'] },
notices: [],
}
response.customerBookingCosts = {
...response.customerPayments!,
months: [
{ month: '2026-04-01', values: { a: 125, b: 60 } },
{ month: '2026-05-01', values: { a: 250, b: -25 } },
],
}
const fetchDashboard = jest.mocked(fetchSalesDashboard)
const source = { data: response, retry: jest.fn() }
const table = (): HTMLElement => screen.getByRole('table', { name: 'Goods Sold Customer-Wise (USD)' })
const total = (): HTMLElement => within(table())
.getByRole('row', { name: /^Total / })
const apply = (): void => {
fireEvent.click(screen.getByRole('button', { name: 'Apply filters' }))
}

beforeEach(() => {
jest.clearAllMocks()
fetchDashboard.mockResolvedValue(response)
})

it('switches member/booking amounts and quarterly totals without refetching', () => {
const view = render(<SalesGoodsSold source={source} portal='sales' refreshKey={0} period='Monthly' />)
expect(total())
.toHaveTextContent('$330.00')
fireEvent.click(screen.getByRole('button', { name: 'Booking Cost' }))
expect(total())
.toHaveTextContent('$410.00')
expect(within(table())
.getByRole('row', { name: /^Acme / }))
.toHaveTextContent('$375.00')
view.rerender(<SalesGoodsSold source={source} portal='sales' refreshKey={0} period='Quarterly' />)
expect(within(total())
.getAllByText('$410.00'))
.toHaveLength(2)
fireEvent.click(screen.getByRole('button', { name: 'Member Payment' }))
expect(total())
.toHaveTextContent('$330.00')
expect(fetchDashboard).not.toHaveBeenCalled()
})

it('applies both dates and multiple offerings, then resets to the shared source', async () => {
render(<SalesGoodsSold source={source} portal='sales' refreshKey={0} period='Monthly' />)
fireEvent.change(screen.getByLabelText('From date'), { target: { value: '2026-04-15' } })
fireEvent.change(screen.getByLabelText('To date'), { target: { value: '2026-05-20' } })
fireEvent.click(screen.getByLabelText('AI Training'))
fireEvent.click(screen.getByLabelText('Flexible Talent'))
expect(fetchDashboard).not.toHaveBeenCalled()
apply()
await waitFor(() => expect(fetchDashboard)
.toHaveBeenCalledTimes(1))
expect(fetchDashboard)
.toHaveBeenLastCalledWith('payments', 'sales', 'close', expect.any(AbortSignal), undefined, {
endDate: '2026-05-20', offeringType: ['AI Training', 'Flexible Talent'], startDate: '2026-04-15',
})
expect(await screen.findByRole('columnheader', { name: 'Period total' }))
.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Reset filters' }))
expect(screen.getByRole('columnheader', { name: 'Annual' }))
.toBeInTheDocument()
expect(screen.getByLabelText('ALL'))
.toBeChecked()
expect(fetchDashboard.mock.calls[0][3].aborted)
.toBe(true)
expect(fetchDashboard)
.toHaveBeenCalledTimes(1)
})

it('rejects reversed dates without requesting or changing the displayed report', () => {
render(<SalesGoodsSold source={source} portal='reports' refreshKey={0} period='Monthly' />)
fireEvent.change(screen.getByLabelText('From date'), { target: { value: '2026-05-21' } })
fireEvent.change(screen.getByLabelText('To date'), { target: { value: '2026-05-20' } })
apply()
expect(screen.getByRole('alert'))
.toHaveTextContent('From date must be on or before To date.')
expect(fetchDashboard).not.toHaveBeenCalled()
expect(total())
.toHaveTextContent('$330.00')
})

it('cancels superseded filters and retries failed filtered requests with the same scope', async () => {
fetchDashboard.mockImplementationOnce(() => new Promise(() => { /* Superseded request. */ }))
fetchDashboard.mockRejectedValueOnce(new Error('offline'))
const view = render(<SalesGoodsSold source={source} portal='reports' refreshKey={0} period='Monthly' />)
apply()
const firstSignal = fetchDashboard.mock.calls[0][3]
fireEvent.click(screen.getByLabelText('TopGear'))
apply()
expect(firstSignal.aborted)
.toBe(true)
expect(await screen.findByRole('alert'))
.toHaveTextContent('Member payments could not be loaded')
fireEvent.click(screen.getByRole('button', { name: 'Try again' }))
await screen.findByRole('table', { name: 'Goods Sold Customer-Wise (USD)' })
expect(fetchDashboard.mock.calls[2][5]?.offeringType)
.toEqual(['TopGear'])
view.rerender(<SalesGoodsSold source={source} portal='reports' refreshKey={1} period='Monthly' />)
await waitFor(() => expect(fetchDashboard)
.toHaveBeenCalledTimes(4))
view.unmount()
expect(fetchDashboard.mock.calls[3][3].aborted)
.toBe(true)
})

it('shows an empty filtered result and does not substitute payments for missing booking costs', async () => {
fetchDashboard.mockResolvedValue({ ...response, customerPayments: { ...response.customerPayments!, series: [] } })
render(<SalesGoodsSold
source={{ ...source, data: { ...response, customerBookingCosts: undefined } }}
portal='sales'
refreshKey={0}
period='Monthly'
/>)
fireEvent.click(screen.getByRole('button', { name: 'Booking Cost' }))
expect(screen.getByText('Booking cost details are unavailable for this source.'))
.toBeInTheDocument()
expect(screen.queryByRole('table')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Member Payment' }))
apply()
expect(await screen.findByText('No customer data matches these filters.'))
.toBeInTheDocument()
})

it('rejects ranges beyond the API limit without refetching', () => {
render(<SalesGoodsSold source={source} portal='reports' refreshKey={0} period='Monthly' />)
fireEvent.change(screen.getByLabelText('From date'), { target: { value: '2025-01-01' } })
fireEvent.change(screen.getByLabelText('To date'), { target: { value: '2027-02-01' } })
apply()
expect(screen.getByRole('alert'))
.toHaveTextContent('Choose a range of no more than 24 months.')
expect(fetchDashboard)
.not.toHaveBeenCalled()
})

it('distinguishes repeated quarters when the date range spans fiscal years', () => {
const data = {
...response,
customerPayments: {
...response.customerPayments!,
months: [{ month: '2026-04-01', values: { a: 100 } }, { month: '2027-04-01', values: { a: 200 } }],
},
}
render(<SalesGoodsSold source={{ ...source, data }} portal='reports' refreshKey={0} period='Quarterly' />)
expect(screen.getByRole('columnheader', { name: 'Q1 2026' }))
.toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: 'Q1 2027' }))
.toBeInTheDocument()
})
Loading
Loading