All files / src/features/Settlements/ReconciliationHub/components CostBreakdownByBrand.tsx

100% Statements 39/39
95.45% Branches 21/22
100% Functions 16/16
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343                                                                    2x 1353x   2x       330x     2x 11x 11x 11x     55x             11x                                     2x     2x                   11x   88x 440x     88x 528x 88x               440x                                                 2x     2x                           11x                     55x 55x     55x 55x 55x                                             275x                                                                                       2x                           2x 11x 11x 11x 11x 11x     11x   11x                                                             55x                                                                                                                
import { Stack, TableBody, TableRow } from "@mui/material";
import TableContainer from "@mui/material/TableContainer";
import GiveText from "@shared/Text/GiveText";
import { useAppTheme } from "@theme/v2/Provider";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { memo, useMemo } from "react";
import {
  Container,
  StyledBodyCell,
  StyledHeaderCell,
  StyledTable,
  StyledTableHead,
  StyledTableRow,
} from "../../styles";
import { ReconciliationHubView } from "../types";
import {
  computeBps,
  formatBpsAsPercent,
  formatHubAmount,
  formatHubPercent,
} from "../format";
import HubGauge from "./HubGauge";
import { CARD_BRANDS as BRANDS } from "../cardBrands";
import {
  ACTIVITY_ROWS,
  COLUMN_COUNT,
  FEE_ROWS,
} from "./CostBreakdownByBrand.constants";
import SectionHeading from "./SectionHeading";
 
interface Props {
  data?: ReconciliationHubView;
}
 
const field = (data: ReconciliationHubView | undefined, name: string): number =>
  ((data as unknown as Record<string, number>)?.[name] ?? 0) as number;
 
const sumBrandSuffixes = (
  data: ReconciliationHubView | undefined,
  prefix: string,
  suffixes: string[],
) => suffixes.reduce((acc, suffix) => acc + field(data, `${prefix}${suffix}`), 0);
 
/** Job 1 — the Chargeback Rate / Cost Rate summary gauges. */
const CostGauges = memo(({ data }: { data?: ReconciliationHubView }) => {
  const { totalChargeback, costBps, volume } = useMemo(() => {
    const vol = field(data, "volume");
    return {
      volume: vol,
      totalChargeback: BRANDS.reduce(
        (acc, brand) => acc + field(data, `${brand.key}ChargebackAmount`),
        0,
      ),
      costBps: computeBps(field(data, "processorCost"), vol),
    };
  }, [data]);
 
  return (
    <Stack direction="row" gap="16px" flexWrap="wrap">
      <HubGauge
        label="Chargeback Rate"
        color="warning"
        percent={(totalChargeback / (volume || 1)) * 100}
        centerText={formatHubPercent(totalChargeback, volume)}
        valueText={formatHubPercent(totalChargeback, volume)}
      />
      <HubGauge
        label="Cost Rate"
        color="success"
        percent={costBps / 100}
        centerText={`${costBps} BPS`}
        valueText={`${costBps} BPS (${formatBpsAsPercent(costBps)})`}
      />
    </Stack>
  );
});
CostGauges.displayName = "CostGauges";
 
/** Job 2 — the per-brand activity matrix (purchases / refunds / chargebacks). */
const ActivityRows = memo(
  ({
    data,
    isMobileView,
    bpsBg,
  }: {
    data?: ReconciliationHubView;
    isMobileView: boolean;
    bpsBg?: string;
  }) => (
    <>
      {ACTIVITY_ROWS.map((row) => {
        const total = BRANDS.reduce(
          (acc, brand) => acc + field(data, `${brand.key}${row.suffix}`),
          0,
        );
        const fmt = (n: number) =>
          row.kind === "amount" ? formatHubAmount(n) : n.toLocaleString("en-US");
        return (
          <StyledTableRow key={row.label}>
            <StyledBodyCell isFirstColumn isMobileView={isMobileView}>
              <GiveText variant="bodyS" color="secondary">
                {row.label}
              </GiveText>
            </StyledBodyCell>
            {BRANDS.map((brand) => (
              <StyledBodyCell key={brand.key} align="center" isMobileView={isMobileView}>
                <GiveText variant="bodyS" color="primary">
                  {fmt(field(data, `${brand.key}${row.suffix}`))}
                </GiveText>
              </StyledBodyCell>
            ))}
            <StyledBodyCell align="center" isMobileView={isMobileView}>
              <GiveText variant="bodyS" color="primary">
                {fmt(total)}
              </GiveText>
            </StyledBodyCell>
            {/* Activity rows have no per-row BPS, so this cell is always "-":
                keep it un-tinted (the blue highlight is only for real BPS
                values, per the mockup). */}
            <StyledBodyCell align="center" isMobileView={isMobileView}>
              <GiveText variant="bodyS" color="secondary">
                -
              </GiveText>
            </StyledBodyCell>
          </StyledTableRow>
        );
      })}
    </>
  ),
);
ActivityRows.displayName = "ActivityRows";
 
/** Job 3 — the "Cost Breakdown" fee section with the per-row Fees BPS column. */
const FeeRows = memo(
  ({
    data,
    isMobileView,
    bpsBg,
    totalBg,
    volume,
  }: {
    data?: ReconciliationHubView;
    isMobileView: boolean;
    bpsBg?: string;
    totalBg?: string;
    volume: number;
  }) => (
    <>
      {/* Sub-section divider */}
      <StyledTableRow>
        <StyledBodyCell colSpan={COLUMN_COUNT} isFirstColumn isMobileView={isMobileView}>
          <GiveText variant="bodyS" color="primary" fontWeight="medium">
            Cost Breakdown
          </GiveText>
        </StyledBodyCell>
      </StyledTableRow>
 
      {FEE_ROWS.map((row) => {
        const total = field(data, row.totalField);
        const bps = computeBps(total, volume);
        // The summary "Total Fees Paid" row carries extra weight and a grey
        // fill in the mock; its BPS cell keeps the blue column tint below.
        const weight = row.isTotal ? "medium" : undefined;
        const rowBg = row.isTotal ? totalBg : undefined;
        return (
          <StyledTableRow key={row.label} data-testid={`hub-fee-row-${row.label}`}>
            <StyledBodyCell
              isFirstColumn
              isMobileView={isMobileView}
              sx={{ backgroundColor: rowBg }}
            >
              <Stack gap="2px">
                <GiveText
                  variant="bodyS"
                  color={row.isTotal ? "primary" : "secondary"}
                  fontWeight={weight}
                >
                  {row.label}
                </GiveText>
                {row.description && (
                  <GiveText variant="bodyXS" color="tertiary">
                    {row.description}
                  </GiveText>
                )}
              </Stack>
            </StyledBodyCell>
            {BRANDS.map((brand) => (
              <StyledBodyCell
                key={brand.key}
                align="center"
                isMobileView={isMobileView}
                sx={{ backgroundColor: rowBg }}
              >
                <GiveText variant="bodyS" color="primary" fontWeight={weight}>
                  {formatHubAmount(
                    row.brandSuffixes
                      ? sumBrandSuffixes(data, brand.key, row.brandSuffixes)
                      : 0,
                  )}
                </GiveText>
              </StyledBodyCell>
            ))}
            <StyledBodyCell
              align="center"
              isMobileView={isMobileView}
              sx={{ backgroundColor: rowBg }}
            >
              <GiveText variant="bodyS" color="primary" fontWeight={weight}>
                {formatHubAmount(total)}
              </GiveText>
            </StyledBodyCell>
            {/* Blue-tint the BPS cell only when there's an actual value; a
                "-" (zero volume) stays un-highlighted per the mockup. The
                summary row keeps the same tint as the rest of the column. */}
            <StyledBodyCell
              align="center"
              isMobileView={isMobileView}
              sx={{ backgroundColor: bps ? bpsBg : undefined }}
            >
              <GiveText variant="bodyS" color="link" fontWeight={weight}>
                <span data-testid={`hub-fee-bps-${row.label}`}>
                  {bps ? `${bps} BPS` : "-"}
                </span>
              </GiveText>
            </StyledBodyCell>
          </StyledTableRow>
        );
      })}
    </>
  ),
);
FeeRows.displayName = "FeeRows";
 
/**
 * Cost Breakdown by Card Brand: the Chargeback / Cost Rate gauges, then an
 * activity matrix (purchases / refunds / chargebacks / pre-CB refunds) and a
 * "Cost Breakdown" fee section (Interchange, Scheme, Processor, Network, Total)
 * with a blue-highlighted per-row Fees BPS column. Reuses the settlement
 * bank-provider table styling. Per-brand processor fees aren't tracked in the
 * view, so that row shows the total only.
 *
 * Composed of three memoized sections (gauges / activity matrix / fee
 * breakdown) so a filter-driven parent re-render with unchanged `data` skips
 * the whole subtree.
 */
const CostBreakdownByBrand = ({ data }: Props) => {
  const theme = useAppTheme();
  const { isLargeView } = useCustomThemeV2();
  const isMobileView = !isLargeView;
  const volume = field(data, "volume");
  const bpsBg = theme.palette.primitive?.blue?.[10];
  // Grey fill behind the summary "Total Fees Paid" row (mock). No token sits
  // between neutral.5 (#f5f5f3) and neutral.0 (#fff), so use a lighter literal.
  const totalBg = "#fafaf9";
 
  return (
    // Design "Section Heading" spec: 46px above the label. The parent hub
    // Stack already contributes a 20px inter-section gap, so add 26px top
    // padding (20 + 26 = 46).
    <Stack gap="16px" pt="26px" data-testid="hub-cost-breakdown">
      <SectionHeading variant="h6">Cost Breakdown by Card Brand</SectionHeading>
 
      <CostGauges data={data} />
 
      <TableContainer
        component={Container}
        isMobileView={isMobileView}
        // Shared `Container` rounds at radius.small (12px); the mock uses a
        // subtler corner, so drop to extraSmall (8px) scoped to this table.
        sx={{ marginTop: 0, marginBottom: 0, maxWidth: "100%", borderRadius: "8px" }}
      >
        <StyledTable
          aria-label="cost breakdown by card brand"
          isMobileView={isMobileView}
          // Shared body cells pad 12px vertically; the mock rows are taller, so
          // bump to 16px scoped here (leaves the settlement table untouched).
          sx={{ minWidth: 880, "& tbody td": { paddingTop: "16px", paddingBottom: "16px" } }}
        >
          <StyledTableHead>
            <TableRow>
              <StyledHeaderCell isFirstColumn isMobileView={isMobileView}>
                <GiveText variant="bodyS" color="primary">
                  Cost Type
                </GiveText>
              </StyledHeaderCell>
              {BRANDS.map((brand) => (
                <StyledHeaderCell key={brand.key} isMobileView={isMobileView} align="center">
                  {brand.Icon ? (
                    <Stack
                      alignItems="center"
                      justifyContent="center"
                      // The shared brand logos ship a grey rounded border (a
                      // "card chip" reused in checkout / agreements / fees); the
                      // rebrand shows them borderless in this table. The border
                      // is a <rect> on Visa but a <path> on Mastercard/Discover/
                      // Amex, so match the stroke on any element — scoped here so
                      // the shared icon components (other consumers) are untouched.
                      sx={{ "& [stroke='#E6E6E3']": { stroke: "none" } }}
                    >
                      <brand.Icon width={34} height={22} />
                    </Stack>
                  ) : (
                    <GiveText variant="bodyS" color="primary" textAlign="center">
                      {brand.label}
                    </GiveText>
                  )}
                </StyledHeaderCell>
              ))}
              <StyledHeaderCell isMobileView={isMobileView} align="center">
                <GiveText variant="bodyS" color="primary" textAlign="center">
                  Total
                </GiveText>
              </StyledHeaderCell>
              <StyledHeaderCell
                isMobileView={isMobileView}
                align="center"
                sx={{ backgroundColor: bpsBg }}
              >
                <GiveText variant="bodyS" color="link" textAlign="center">
                  Fees BPS
                </GiveText>
              </StyledHeaderCell>
            </TableRow>
          </StyledTableHead>
 
          <TableBody>
            <ActivityRows data={data} isMobileView={isMobileView} bpsBg={bpsBg} />
            <FeeRows
              data={data}
              isMobileView={isMobileView}
              bpsBg={bpsBg}
              totalBg={totalBg}
              volume={volume}
            />
          </TableBody>
        </StyledTable>
      </TableContainer>
    </Stack>
  );
};
 
export default memo(CostBreakdownByBrand);