Перейти к содержимому

История сделок ​

Узкая полоса меню со второй колонкой и таблица сделок с фильтрами, выбором строк, сортировкой и пагинацией.

Состав: Avatar, AvatarLabelGroup, Badge, Button, ButtonGroup, Calendar, Card, Checkbox, DateRangePicker, DropdownMenu, EmptyState, Field, Filters, IconButton, InputGroup, Kbd, PageHeader, Pagination, QueryContainer, Select, Sidebar, Slideout, Table.

vue
<script setup lang="ts">
import type { DateRange, SelectOptionValue, TableSort } from '@prosper/ui'
import { computed, ref, watch } from 'vue'

import {
  trades,
  tradesPerPage,
  type Trade,
  type TradeSide,
} from '../data/trade-history'
import ShellLayout from './ShellLayout.vue'
import TradeHistoryFilters from './TradeHistoryFilters.vue'
import TradeHistoryHeader from './TradeHistoryHeader.vue'
import TradeHistoryPanel from './TradeHistoryPanel.vue'
import TradeHistoryTable from './TradeHistoryTable.vue'

const side = ref<TradeSide | 'all'>('all')
const query = ref('')
const period = ref<DateRange | null>(null)
const status = ref<SelectOptionValue>('all')
const sort = ref<TableSort>('descending')
const page = ref(1)

const matchesQuery = ({ ticker, company }: Trade): boolean => {
  const text = query.value.trim().toLocaleLowerCase('ru')

  return `${ticker} ${company}`.toLocaleLowerCase('ru').includes(text)
}

const inPeriod = ({ deliveryIso }: Trade): boolean =>
  period.value === null ||
  (deliveryIso >= period.value.start && deliveryIso <= period.value.end)

const matches = computed(() =>
  trades.filter(
    (trade) =>
      (side.value === 'all' || trade.side === side.value) &&
      (status.value === 'all' || trade.status === status.value) &&
      matchesQuery(trade) &&
      inPeriod(trade),
  ),
)

const shown = computed(() => {
  const sign = sort.value === 'ascending' ? -1 : 1
  const start = (page.value - 1) * tradesPerPage

  return [...matches.value]
    .sort((first, second) => sign * (first.day - second.day))
    .slice(start, start + tradesPerPage)
})

watch([side, query, period, status], () => {
  page.value = 1
})
</script>

<template>
  <ShellLayout current="Сделки" rail="Панель">
    <template #panel><TradeHistoryPanel /></template>
    <TradeHistoryHeader v-model:side="side" />
    <div class="results">
      <TradeHistoryFilters
        v-model:query="query"
        v-model:period="period"
        v-model:status="status"
      />
      <TradeHistoryTable
        v-model:sort="sort"
        v-model:page="page"
        :trades="shown"
        :total="matches.length"
      />
    </div>
  </ShellLayout>
</template>

<style scoped>
.results {
  display: flex;
  flex-direction: column;
  gap: var(--prosper-spacing-3xl);
}
</style>
vue
<script setup lang="ts">
import {
  CalendarGrid,
  CalendarHeader,
  CalendarMonth,
  CalendarNext,
  CalendarPrev,
  CalendarTitle,
  DateRangePickerApply,
  DateRangePickerCalendar,
  DateRangePickerCancel,
  DateRangePickerEndInput,
  DateRangePickerFooter,
  DateRangePickerInputs,
  DateRangePickerMain,
  DateRangePickerStartInput,
} from '@prosper/ui'
</script>

<template>
  <DateRangePickerMain>
    <DateRangePickerCalendar v-slot="{ months }">
      <CalendarMonth
        v-for="(month, index) in months"
        :key="month.id"
        :month="month"
      >
        <CalendarHeader>
          <CalendarPrev v-if="index === 0" />
          <CalendarTitle />
          <CalendarNext v-if="index === months.length - 1" />
        </CalendarHeader>
        <CalendarGrid />
      </CalendarMonth>
    </DateRangePickerCalendar>
    <DateRangePickerFooter>
      <DateRangePickerInputs>
        <DateRangePickerStartInput />
        <DateRangePickerEndInput />
      </DateRangePickerInputs>
      <DateRangePickerCancel>Отмена</DateRangePickerCancel>
      <DateRangePickerApply>Применить</DateRangePickerApply>
    </DateRangePickerFooter>
  </DateRangePickerMain>
</template>
vue
<script setup lang="ts">
import {
  type DateRange,
  DateRangePicker,
  DateRangePickerContent,
  DateRangePickerPreset,
  DateRangePickerPresets,
  DateRangePickerTrigger,
  defaultDateRangePresets,
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  Kbd,
  type SelectOptionValue,
} from '@prosper/ui'
import { SearchLg } from '@prosper/ui/icons'

import { tradesToday } from '../data/trade-history'
import TradeHistoryCalendar from './TradeHistoryCalendar.vue'
import TradeHistoryStatus from './TradeHistoryStatus.vue'

const query = defineModel<string>('query', { required: true })
const period = defineModel<DateRange | null>('period', { required: true })
const status = defineModel<SelectOptionValue>('status', { required: true })

const presets = defaultDateRangePresets('ru', tradesToday)
</script>

<template>
  <div class="filters">
    <InputGroup size="sm" class="search">
      <InputGroupAddon><SearchLg /></InputGroupAddon>
      <InputGroupInput
        v-model="query"
        type="search"
        aria-label="Поиск сделок"
        placeholder="Тикер или компания"
      />
      <InputGroupAddon class="hint" variant="inline" align="end">
        <Kbd aria-hidden="true">⌘K</Kbd>
      </InputGroupAddon>
    </InputGroup>
    <div class="tools">
      <DateRangePicker v-model="period" aria-label="Период поставки">
        <DateRangePickerTrigger size="sm" placeholder="Выбрать даты" />
        <DateRangePickerContent>
          <DateRangePickerPresets>
            <DateRangePickerPreset
              v-for="preset in presets"
              :key="preset.label"
              :start="preset.start"
              :end="preset.end"
            >
              {{ preset.label }}
            </DateRangePickerPreset>
          </DateRangePickerPresets>
          <TradeHistoryCalendar />
        </DateRangePickerContent>
      </DateRangePicker>
      <TradeHistoryStatus v-model:status="status" />
    </div>
  </div>
</template>

<style scoped>
.filters {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--prosper-spacing-lg);
  padding: var(--prosper-spacing-lg) var(--prosper-spacing-xl);
  border: 1px solid var(--prosper-color-border-secondary);
  border-radius: var(--prosper-radius-xl);
  background: var(--prosper-color-bg-secondary);
}

.search {
  flex: 0 1 calc(var(--prosper-space-80) - var(--prosper-space-10));
}

.tools {
  display: flex;
  gap: var(--prosper-spacing-lg);
}

@media (width < 48rem) {
  .filters {
    padding: var(--prosper-spacing-none);
    border: 0;
    background: transparent;
  }

  .search {
    flex: 1 1 0%;
  }
}

@media (width < 40rem) {
  .search :deep(.hint) {
    display: none;
  }
}
</style>
vue
<script setup lang="ts">
import {
  Button,
  ButtonGroup,
  ButtonGroupItem,
  ButtonIcon,
  PageHeader,
  PageHeaderActions,
  PageHeaderContent,
  PageHeaderDescription,
  PageHeaderHeading,
  PageHeaderTitle,
} from '@prosper/ui'
import { DownloadCloud02, Plus } from '@prosper/ui/icons'

import type { TradeSide } from '../data/trade-history'

const side = defineModel<TradeSide | 'all'>('side', { required: true })

const sides = [
  { value: 'all', label: 'Все сделки' },
  { value: 'buy', label: 'Покупка' },
  { value: 'sell', label: 'Продажа' },
] as const
</script>

<template>
  <div class="header">
    <PageHeader>
      <PageHeaderContent>
        <PageHeaderHeading>
          <PageHeaderTitle>История сделок</PageHeaderTitle>
          <PageHeaderDescription>
            Сделки и операции вашей команды.
          </PageHeaderDescription>
        </PageHeaderHeading>
        <PageHeaderActions>
          <Button variant="secondary" size="sm">
            <ButtonIcon><DownloadCloud02 /></ButtonIcon>
            Скачать CSV
          </Button>
          <Button size="sm">
            <ButtonIcon><Plus /></ButtonIcon>
            Добавить
          </Button>
        </PageHeaderActions>
      </PageHeaderContent>
    </PageHeader>
    <ButtonGroup size="sm" aria-label="Сторона сделки" class="sides">
      <ButtonGroupItem
        v-for="item in sides"
        :key="item.value"
        :current="side === item.value"
        @click="side = item.value"
      >
        {{ item.label }}
      </ButtonGroupItem>
    </ButtonGroup>
  </div>
</template>

<style scoped>
.header {
  display: flex;
  flex-direction: column;
  gap: var(--prosper-spacing-2xl);
}

.sides {
  align-self: flex-start;
}
</style>
vue
<script setup lang="ts">
import {
  Button,
  ButtonIcon,
  Pagination,
  PaginationList,
  PaginationNext,
  PaginationPrev,
} from '@prosper/ui'
import { ArrowLeft, ArrowRight } from '@prosper/ui/icons'
import { computed } from 'vue'

import { tradesPerPage } from '../data/trade-history'

const props = defineProps<{ total: number }>()

const page = defineModel<number>('page', { required: true })

const pageCount = computed(() => Math.ceil(props.total / tradesPerPage))
</script>

<template>
  <Pagination
    v-model:page="page"
    aria-label="Страницы сделок"
    :total="total"
    :items-per-page="tradesPerPage"
    class="pagination"
  >
    <PaginationPrev as-child class="wide">
      <Button variant="secondary" size="sm">
        <ButtonIcon><ArrowLeft /></ButtonIcon>
        Назад
      </Button>
    </PaginationPrev>
    <PaginationPrev as-child class="narrow">
      <Button variant="secondary" size="sm" aria-label="Предыдущая страница">
        <ButtonIcon align="only"><ArrowLeft /></ButtonIcon>
      </Button>
    </PaginationPrev>
    <PaginationList class="wide" />
    <span class="narrow">Страница {{ page }} из {{ pageCount }}</span>
    <PaginationNext as-child class="wide">
      <Button variant="secondary" size="sm">
        Вперёд
        <ButtonIcon align="end"><ArrowRight /></ButtonIcon>
      </Button>
    </PaginationNext>
    <PaginationNext as-child class="narrow">
      <Button variant="secondary" size="sm" aria-label="Следующая страница">
        <ButtonIcon align="only"><ArrowRight /></ButtonIcon>
      </Button>
    </PaginationNext>
  </Pagination>
</template>

<style scoped>
.pagination {
  justify-content: space-between;
  border-block-start: 1px solid var(--prosper-color-border-secondary);
  padding: var(--prosper-spacing-lg) var(--prosper-spacing-3xl)
    var(--prosper-spacing-xl);
}

@media (width < 48rem) {
  .wide {
    display: none;
  }
}

@media (width >= 48rem) {
  .narrow {
    display: none;
  }
}
</style>
vue
<script setup lang="ts">
import {
  Badge,
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarItem,
  SidebarSection,
  SidebarTitle,
} from '@prosper/ui'
import {
  BarChartSquare02,
  Bell01,
  ClockRewind,
  PieChart03,
  Star01,
  Users01,
} from '@prosper/ui/icons'

import ShellAccount from './ShellAccount.vue'

const sections = [
  { label: 'Обзор', icon: BarChartSquare02 },
  { label: 'Уведомления', icon: Bell01, count: 10 },
  { label: 'Аналитика', icon: PieChart03 },
  { label: 'Сохранённые отчёты', icon: Star01 },
  { label: 'История сделок', icon: ClockRewind, current: true },
  { label: 'Отчёты пользователей', icon: Users01 },
]
</script>

<template>
  <Sidebar variant="secondary" aria-labelledby="trade-panel-title">
    <SidebarHeader>
      <SidebarTitle id="trade-panel-title">Панель</SidebarTitle>
    </SidebarHeader>
    <SidebarContent>
      <SidebarSection>
        <SidebarItem
          v-for="section in sections"
          :key="section.label"
          href="#"
          :current="section.current"
        >
          <template #leading><component :is="section.icon" /></template>
          {{ section.label }}
          <template v-if="section.count" #trailing>
            <Badge size="sm">{{ section.count }}</Badge>
          </template>
        </SidebarItem>
      </SidebarSection>
    </SidebarContent>
    <SidebarFooter><ShellAccount rail /></SidebarFooter>
  </Sidebar>
</template>
vue
<script setup lang="ts">
import {
  Avatar,
  AvatarFallback,
  AvatarLabelGroup,
  AvatarLabelGroupDescription,
  AvatarLabelGroupName,
  Badge,
  BadgeDot,
  Button,
  Checkbox,
  TableCell,
  TableRow,
} from '@prosper/ui'

import { tradeSides, tradeStatuses, type Trade } from '../data/trade-history'

defineProps<{ trade: Trade }>()

const selected = defineModel<boolean>('selected', { required: true })
</script>

<template>
  <TableRow :selected="selected">
    <TableCell>
      <template #leading>
        <Checkbox
          v-model:checked="selected"
          :aria-label="`Выбрать: ${trade.ticker}, ${trade.id}`"
        />
      </template>
      <div class="trade">
        <strong>{{ trade.ticker }} {{ tradeSides[trade.side] }}</strong>
        <span>{{ trade.company }}</span>
      </div>
    </TableCell>
    <TableCell
      ><span class="nowrap">{{ trade.amount }}</span></TableCell
    >
    <TableCell
      ><span class="nowrap">{{ trade.delivery }}</span></TableCell
    >
    <TableCell>
      <Badge
        size="sm"
        variant="modern"
        :color="tradeStatuses[trade.status].color"
      >
        <BadgeDot />
        {{ tradeStatuses[trade.status].label }}
      </Badge>
    </TableCell>
    <TableCell>
      <div class="trader">
        <AvatarLabelGroup size="md">
          <Avatar>
            <AvatarFallback>{{ trade.trader.initials }}</AvatarFallback>
          </Avatar>
          <AvatarLabelGroupName>{{ trade.trader.name }}</AvatarLabelGroupName>
          <AvatarLabelGroupDescription>
            {{ trade.trader.email }}
          </AvatarLabelGroupDescription>
        </AvatarLabelGroup>
      </div>
    </TableCell>
    <TableCell>
      <Button
        variant="link-color"
        size="sm"
        :aria-label="`Изменить: ${trade.ticker}, ${trade.id}`"
      >
        Изменить
      </Button>
    </TableCell>
  </TableRow>
</template>

<style scoped>
.trade {
  display: flex;
  flex-direction: column;
  min-inline-size: var(--prosper-space-40);
}

.trade strong {
  white-space: nowrap;
  color: var(--prosper-color-text-primary);
  font-weight: var(--prosper-font-weight-medium);
}

.nowrap {
  white-space: nowrap;
}

.trader {
  min-inline-size: calc(var(--prosper-space-48) + var(--prosper-spacing-xl));
}
</style>
vue
<script setup lang="ts">
import {
  Field,
  FieldLabel,
  Filters,
  FiltersBody,
  FiltersContent,
  FiltersCount,
  FiltersTrigger,
  Select,
  SelectItem,
  type SelectOptionValue,
} from '@prosper/ui'

import { tradeStatuses } from '../data/trade-history'

const status = defineModel<SelectOptionValue>('status', { required: true })
</script>

<template>
  <Filters>
    <FiltersTrigger>
      Фильтры
      <FiltersCount v-if="status !== 'all'">1</FiltersCount>
    </FiltersTrigger>
    <FiltersContent align="end">
      <FiltersBody>
        <Field>
          <FieldLabel>Статус</FieldLabel>
          <Select v-model="status">
            <SelectItem value="all">Все статусы</SelectItem>
            <SelectItem
              v-for="(item, value) in tradeStatuses"
              :key="value"
              :value="value"
            >
              {{ item.label }}
            </SelectItem>
          </Select>
        </Field>
      </FiltersBody>
    </FiltersContent>
  </Filters>
</template>
vue
<script setup lang="ts">
import {
  Card,
  Checkbox,
  EmptyState,
  EmptyStateDescription,
  EmptyStateTitle,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  type TableSort,
} from '@prosper/ui'
import { computed, ref } from 'vue'

import type { Trade } from '../data/trade-history'
import TradeHistoryPagination from './TradeHistoryPagination.vue'
import TradeHistoryRow from './TradeHistoryRow.vue'

const props = defineProps<{ trades: readonly Trade[]; total: number }>()

const page = defineModel<number>('page', { required: true })

const sort = defineModel<TableSort>('sort', { required: true })

const selected = ref<string[]>([])

const all = computed(
  () =>
    props.trades.length > 0 &&
    props.trades.every(({ id }) => selected.value.includes(id)),
)

const some = computed(() =>
  props.trades.some(({ id }) => selected.value.includes(id)),
)

const setAll = (checked: boolean): void => {
  const shown = props.trades.map(({ id }) => id)
  const others = selected.value.filter((id) => !shown.includes(id))
  selected.value = checked ? [...others, ...shown] : others
}

const setOne = (id: string, checked: boolean): void => {
  selected.value = checked
    ? [...selected.value, id]
    : selected.value.filter((value) => value !== id)
}

const flip = (next: TableSort): void => {
  sort.value = next === 'descending' ? 'descending' : 'ascending'
}
</script>

<template>
  <Card class="table-card">
    <Table aria-label="Сделки">
      <TableHeader>
        <TableRow>
          <TableHead>
            <template #leading>
              <Checkbox
                aria-label="Выбрать сделки на странице"
                :checked="all"
                :indeterminate="some && !all"
                @update:checked="setAll"
              />
            </template>
            Сделка
          </TableHead>
          <TableHead>Сумма</TableHead>
          <TableHead :sort="sort" @update:sort="flip">Дата поставки</TableHead>
          <TableHead>Статус</TableHead>
          <TableHead>Исполнитель</TableHead>
          <TableHead>Действия</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        <TradeHistoryRow
          v-for="trade in trades"
          :key="trade.id"
          :trade="trade"
          :selected="selected.includes(trade.id)"
          @update:selected="setOne(trade.id, $event)"
        />
        <TableRow v-if="trades.length === 0">
          <TableCell colspan="6">
            <EmptyState size="sm">
              <EmptyStateTitle>Сделки не найдены</EmptyStateTitle>
              <EmptyStateDescription>
                Измените запрос или фильтры.
              </EmptyStateDescription>
            </EmptyState>
          </TableCell>
        </TableRow>
      </TableBody>
    </Table>
    <TradeHistoryPagination
      v-if="total > 0"
      v-model:page="page"
      :total="total"
    />
  </Card>
</template>

<style scoped>
@container prosper (width < 40rem) {
  @media (width < 64rem) {
    .table-card {
      margin-inline: calc(var(--prosper-spacing-xl) * -1);
    }
  }
}
</style>
ts
import type { BadgeColor } from '@prosper/ui'

export type TradeSide = 'buy' | 'sell'

export type TradeStatus = 'processing' | 'success' | 'declined'

export interface Trader {
  name: string
  initials: string
  email: string
}

export interface Trade {
  id: string
  ticker: string
  company: string
  side: TradeSide
  amount: string
  delivery: string
  deliveryIso: string
  day: number
  status: TradeStatus
  trader: Trader
}

export const tradeSides: Record<TradeSide, string> = {
  buy: 'Покупка',
  sell: 'Продажа',
}

export const tradeStatuses: Record<
  TradeStatus,
  { label: string; color: BadgeColor }
> = {
  processing: { label: 'В обработке', color: 'gray' },
  success: { label: 'Исполнена', color: 'success' },
  declined: { label: 'Отклонена', color: 'error' },
}

export const tradesPerPage = 7

const companies = [
  ['ALFA', 'Альфа Ресурс'],
  ['BRTX', 'Бортекс Логистик'],
  ['DLTA', 'Дельта Сети'],
  ['GRNX', 'Гринэкс Энергия'],
  ['KMTK', 'Камтек Металл'],
  ['NRVS', 'Нервус Медтех'],
  ['SNRG', 'Синергия Фуд'],
] as const

const traders: readonly Trader[] = [
  { name: 'Алия Ахметова', initials: 'АА', email: 'aliya@example.com' },
  { name: 'Дамир Сейтказин', initials: 'ДС', email: 'damir@example.com' },
  { name: 'Ольга Руденко', initials: 'ОР', email: 'olga@example.com' },
  { name: 'Тимур Жумабаев', initials: 'ТЖ', email: 'timur@example.com' },
  { name: 'Мадина Касымова', initials: 'МК', email: 'madina@example.com' },
]

const months = [
  'янв.',
  'февр.',
  'мар.',
  'апр.',
  'мая',
  'июн.',
  'июл.',
  'авг.',
  'сент.',
  'окт.',
  'нояб.',
  'дек.',
]

export const tradesToday = '2027-01-13'

const firstDay = Date.parse(tradesToday)

const dayLength = 86_400_000

const deliveryOf = (day: number): string => {
  const date = new Date(firstDay - day * dayLength)

  return `${date.getUTCDate()} ${months[date.getUTCMonth()]} ${date.getUTCFullYear()}`
}

const isoOf = (day: number): string =>
  new Date(firstDay - day * dayLength).toISOString().slice(0, 10)

const statusOf = (index: number): TradeStatus =>
  index % 9 === 0 ? 'processing' : index % 9 === 3 ? 'declined' : 'success'

const amountFormat = new Intl.NumberFormat('ru-RU', {
  style: 'currency',
  currency: 'RUB',
})

const amountOf = (index: number): string =>
  amountFormat.format(
    10_000 + ((index * 7_919) % 31_000) + ((index * 37) % 100) / 100,
  )

export const trades: readonly Trade[] = Array.from(
  { length: 70 },
  (_, index) => {
    const [ticker, company] = companies[index % companies.length]
    const day = Math.floor(index / 4)

    return {
      id: `T-${2400 - index}`,
      ticker,
      company,
      side: index % 3 === 1 ? 'sell' : 'buy',
      amount: amountOf(index),
      delivery: deliveryOf(day),
      deliveryIso: isoOf(day),
      day,
      status: statusOf(index),
      trader: traders[index % traders.length],
    }
  },
)