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

Клиенты ​

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

Состав: Avatar, AvatarGroup, AvatarLabelGroup, Badge, Button, Card, Chart, Checkbox, DropdownMenu, EmptyState, FeaturedIcon, Field, IconButton, InputGroup, Kbd, MultiSelect, PageHeader, Pagination, ProgressBar, QueryContainer, SectionHeader, Select, Sidebar, Slideout, Table.

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

import { customerStatuses, customers } from '../data/customers'
import CustomersCharts from './CustomersCharts.vue'
import CustomersFilters from './CustomersFilters.vue'
import CustomersHeader from './CustomersHeader.vue'
import CustomersPagination from './CustomersPagination.vue'
import CustomersTable from './CustomersTable.vue'
import ShellLayout from './ShellLayout.vue'

const allStatuses = Object.keys(customerStatuses)

const query = ref('')
const status = ref<(string | number)[]>(allStatuses)
const category = ref<SelectOptionValue>('all')
const sort = ref<TableSort>('ascending')
const page = ref(1)
const rows = ref(10)

const matches = computed(() => {
  const text = query.value.trim().toLowerCase()

  return customers.filter(
    ({ name, site, status: state, category: kind }) =>
      [name, site].some((value) => value.toLowerCase().includes(text)) &&
      status.value.includes(state) &&
      (category.value === 'all' || kind === category.value),
  )
})

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

  return [...matches.value]
    .sort((first, second) => sign * first.name.localeCompare(second.name))
    .slice(start, start + rows.value)
})

watch([query, status, category, rows], () => {
  page.value = 1
})

const clear = (): void => {
  query.value = ''
  status.value = allStatuses
  category.value = 'all'
}
</script>

<template>
  <ShellLayout current="Клиенты" rail="Панель">
    <CustomersHeader />
    <CustomersCharts />
    <div class="results">
      <CustomersFilters
        v-model:query="query"
        v-model:status="status"
        v-model:category="category"
        @clear="clear"
      />
      <CustomersTable v-model:sort="sort" :customers="shown">
        <CustomersPagination
          v-if="matches.length > 0"
          v-model:page="page"
          v-model:rows="rows"
          :total="matches.length"
        />
      </CustomersTable>
    </div>
  </ShellLayout>
</template>

<style scoped>
.results {
  display: flex;
  flex-direction: column;
  gap: var(--prosper-spacing-3xl);
}
</style>
vue
<script setup lang="ts">
import { IconButton } from '@prosper/ui'
import { Edit01, Trash01 } from '@prosper/ui/icons'

defineProps<{ name: string }>()
</script>

<template>
  <div class="actions">
    <IconButton variant="tertiary" size="xs" :aria-label="`Удалить ${name}`">
      <Trash01 />
    </IconButton>
    <IconButton variant="tertiary" size="xs" :aria-label="`Изменить ${name}`">
      <Edit01 />
    </IconButton>
  </div>
</template>

<style scoped>
.actions {
  display: flex;
  gap: var(--prosper-spacing-xxs);
}
</style>
vue
<script setup lang="ts">
import {
  Chart,
  ChartCenter,
  ChartLegend,
  type ChartSeries,
  ChartTooltip,
  ChartXAxis,
} from '@prosper/ui'

import { activeChannels, customerTotals } from '../data/customers'
import CustomersSection from './CustomersSection.vue'

const activeSeries: ChartSeries<(typeof activeChannels)[number]>[] = [
  { key: 'percent', name: 'Дневная цель' },
]

const totalSeries: ChartSeries<(typeof customerTotals)[number]>[] = [
  { key: 'current', name: '2026' },
  { key: 'previous', name: '2025', line: 'dotted' },
  { key: 'beforePrevious', name: '2024', line: 'dotted' },
]

const formatPercent = (value: number): string => `${value} %`
</script>

<template>
  <div class="charts">
    <CustomersSection id="active-title" title="Активны сейчас">
      <Chart
        class="gauge"
        :data="activeChannels"
        category-key="channel"
        :series="activeSeries"
        variant="gauge"
        size="md"
        :format-value="formatPercent"
        aria-labelledby="active-title"
      >
        <ChartCenter>316</ChartCenter>
        <ChartTooltip />
      </Chart>
    </CustomersSection>
    <CustomersSection id="total-title" title="Всего клиентов">
      <Chart
        :data="customerTotals"
        category-key="month"
        :series="totalSeries"
        aria-labelledby="total-title"
      >
        <ChartLegend />
        <ChartXAxis />
        <ChartTooltip />
      </Chart>
    </CustomersSection>
  </div>
</template>

<style scoped>
.charts {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  gap: var(--prosper-spacing-4xl);
}

.gauge {
  margin-inline: auto;
}

@media (width >= 64rem) {
  .charts {
    grid-template-columns:
      calc(var(--prosper-space-56) + var(--prosper-space-4))
      minmax(0, 1fr);
    column-gap: var(--prosper-spacing-7xl);
  }
}
</style>
vue
<script setup lang="ts">
import { Button, IconButton } from '@prosper/ui'
import { XClose } from '@prosper/ui/icons'

defineEmits<{ clear: [] }>()
</script>

<template>
  <Button variant="secondary" size="sm" class="wide" @click="$emit('clear')">
    Сбросить
  </Button>
  <IconButton
    variant="tertiary"
    aria-label="Сбросить фильтры"
    class="narrow"
    @click="$emit('clear')"
  >
    <XClose />
  </IconButton>
</template>

<style scoped>
.wide {
  margin-inline-start: auto;
}

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

@media (width >= 40rem) {
  .narrow {
    display: none;
  }
}
</style>
vue
<script setup lang="ts">
import {
  EmptyState,
  EmptyStateDescription,
  EmptyStateMedia,
  EmptyStateTitle,
  FeaturedIcon,
  TableCell,
  TableRow,
} from '@prosper/ui'
import { SearchLg } from '@prosper/ui/icons'
</script>

<template>
  <TableRow>
    <TableCell colspan="6">
      <EmptyState size="sm">
        <EmptyStateMedia>
          <FeaturedIcon variant="modern" color="gray" size="lg">
            <SearchLg />
          </FeaturedIcon>
        </EmptyStateMedia>
        <EmptyStateTitle>Клиенты не найдены</EmptyStateTitle>
        <EmptyStateDescription>
          Измените фильтры, чтобы снова увидеть клиентов.
        </EmptyStateDescription>
      </EmptyState>
    </TableCell>
  </TableRow>
</template>
vue
<script setup lang="ts">
import {
  Field,
  FieldLabel,
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  MultiSelect,
  MultiSelectBody,
  MultiSelectContent,
  MultiSelectItem,
  MultiSelectList,
  MultiSelectTrigger,
  Select,
  SelectItem,
  type SelectOptionValue,
} from '@prosper/ui'
import { SearchLg } from '@prosper/ui/icons'

import { customerCategories, customerStatuses } from '../data/customers'
import CustomersClear from './CustomersClear.vue'

const query = defineModel<string>('query', { required: true })
const status = defineModel<(string | number)[]>('status', { required: true })
const category = defineModel<SelectOptionValue>('category', { required: true })

defineEmits<{ clear: [] }>()
</script>

<template>
  <div class="filters">
    <Field class="search">
      <FieldLabel>Поиск клиента</FieldLabel>
      <InputGroup size="sm">
        <InputGroupAddon><SearchLg /></InputGroupAddon>
        <InputGroupInput
          v-model="query"
          type="search"
          placeholder="Название или сайт"
        />
      </InputGroup>
    </Field>
    <Field class="choice">
      <FieldLabel>Статус</FieldLabel>
      <MultiSelect v-model="status" size="sm">
        <MultiSelectTrigger placeholder="Выберите статусы" />
        <MultiSelectContent>
          <MultiSelectBody>
            <MultiSelectList>
              <MultiSelectItem
                v-for="(item, value) in customerStatuses"
                :key="value"
                :value="value"
              >
                {{ item.label }}
              </MultiSelectItem>
            </MultiSelectList>
          </MultiSelectBody>
        </MultiSelectContent>
      </MultiSelect>
    </Field>
    <Field class="choice">
      <FieldLabel>Категория</FieldLabel>
      <Select v-model="category" size="sm">
        <SelectItem value="all">Все</SelectItem>
        <SelectItem
          v-for="item in customerCategories"
          :key="item"
          :value="item"
        >
          {{ item }}
        </SelectItem>
      </Select>
    </Field>
    <CustomersClear @clear="$emit('clear')" />
  </div>
</template>

<style scoped>
.filters {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: var(--prosper-spacing-lg);
}

.search {
  flex: 0 1 calc(var(--prosper-space-64) + var(--prosper-space-6));
}

.choice {
  flex: 0 0 var(--prosper-space-40);
}

@media (width < 40rem) {
  .search {
    flex-basis: 100%;
  }

  .choice {
    flex: 1 1 0%;
  }
}
</style>
vue
<script setup lang="ts">
import {
  Button,
  ButtonIcon,
  PageHeader,
  PageHeaderActions,
  PageHeaderContent,
  PageHeaderHeading,
  PageHeaderTitle,
} from '@prosper/ui'
import { Plus, UploadCloud02 } from '@prosper/ui/icons'
</script>

<template>
  <PageHeader>
    <PageHeaderContent>
      <PageHeaderHeading>
        <PageHeaderTitle>Клиенты</PageHeaderTitle>
      </PageHeaderHeading>
      <PageHeaderActions>
        <Button variant="secondary" size="sm">
          <ButtonIcon><UploadCloud02 /></ButtonIcon>
          Импорт
        </Button>
        <Button size="sm">
          <ButtonIcon><Plus /></ButtonIcon>
          Добавить клиента
        </Button>
      </PageHeaderActions>
    </PageHeaderContent>
  </PageHeader>
</template>
vue
<script setup lang="ts">
import {
  Button,
  ButtonIcon,
  Pagination,
  PaginationNext,
  PaginationPrev,
  Select,
  SelectItem,
} from '@prosper/ui'
import { ArrowLeft, ArrowRight } from '@prosper/ui/icons'
import { computed } from 'vue'

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

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

const rowOptions = [10, 20, 50]

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

<template>
  <div class="bar">
    <Pagination
      v-model:page="page"
      aria-label="Страницы клиентов"
      :total="total"
      :items-per-page="rows"
      class="pages"
    >
      <PaginationPrev as-child class="wide">
        <Button variant="secondary" size="sm">Предыдущая</Button>
      </PaginationPrev>
      <PaginationPrev as-child class="narrow">
        <Button variant="secondary" size="sm" aria-label="Предыдущая страница">
          <ButtonIcon align="only"><ArrowLeft /></ButtonIcon>
        </Button>
      </PaginationPrev>
      <div class="middle">
        <span>Страница {{ page }} из {{ pageCount }}</span>
        <Select
          size="sm"
          aria-label="Строк на странице"
          :model-value="rows"
          class="rows"
          @update:model-value="rows = Number($event)"
        >
          <SelectItem
            v-for="option in rowOptions"
            :key="option"
            :value="option"
          >
            {{ option }} на странице
          </SelectItem>
        </Select>
      </div>
      <PaginationNext as-child class="wide">
        <Button variant="secondary" size="sm">Следующая</Button>
      </PaginationNext>
      <PaginationNext as-child class="narrow">
        <Button variant="secondary" size="sm" aria-label="Следующая страница">
          <ButtonIcon align="only"><ArrowRight /></ButtonIcon>
        </Button>
      </PaginationNext>
    </Pagination>
  </div>
</template>

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

.pages {
  justify-content: space-between;
  inline-size: 100%;
}

.middle {
  display: flex;
  align-items: center;
  gap: var(--prosper-spacing-lg);
}

@media (width < 40rem) {
  .wide,
  .rows {
    display: none;
  }
}

@media (width >= 40rem) {
  .narrow {
    display: none;
  }
}
</style>
vue
<script setup lang="ts">
import {
  Avatar,
  AvatarFallback,
  AvatarGroup,
  AvatarLabelGroup,
  AvatarLabelGroupDescription,
  AvatarLabelGroupName,
  Badge,
  BadgeDot,
  Checkbox,
  ProgressBar,
  TableCell,
  TableRow,
} from '@prosper/ui'
import { computed } from 'vue'

import { customerStatuses, type Customer } from '../data/customers'
import CustomersActions from './CustomersActions.vue'

const props = defineProps<{ customer: Customer }>()

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

const status = computed(() => customerStatuses[props.customer.status])
</script>

<template>
  <TableRow :selected="selected">
    <TableCell>
      <template #leading>
        <Checkbox
          v-model:checked="selected"
          :aria-label="`Выбрать ${customer.name}`"
        />
      </template>
      <div class="person">
        <AvatarLabelGroup size="md">
          <Avatar>
            <AvatarFallback>{{ customer.initials }}</AvatarFallback>
          </Avatar>
          <AvatarLabelGroupName>{{ customer.name }}</AvatarLabelGroupName>
          <AvatarLabelGroupDescription>
            {{ customer.site }}
          </AvatarLabelGroupDescription>
        </AvatarLabelGroup>
      </div>
    </TableCell>
    <TableCell>
      <Badge size="sm" variant="badge" :color="status.color">
        <BadgeDot />
        {{ status.label }}
      </Badge>
    </TableCell>
    <TableCell class="detail">
      <div class="about">
        <span>{{ customer.activity }}</span>
        <span class="summary">{{ customer.summary }}</span>
      </div>
    </TableCell>
    <TableCell class="detail">
      <AvatarGroup size="xs" :aria-label="`Сотрудники: ${customer.name}`">
        <Avatar v-for="person in customer.team" :key="person.name">
          <AvatarFallback :label="person.name" />
        </Avatar>
        <Avatar>
          <AvatarFallback :label="`Ещё ${customer.more} сотрудников`"
            >+{{ customer.more }}</AvatarFallback
          >
        </Avatar>
      </AvatarGroup>
    </TableCell>
    <TableCell class="detail">
      <div class="licence">
        <ProgressBar
          :value="customer.licences"
          :aria-label="`Лицензии: ${customer.name}`"
        />
      </div>
    </TableCell>
    <TableCell class="detail">
      <CustomersActions :name="customer.name" />
    </TableCell>
  </TableRow>
</template>

<style scoped>
.person {
  min-inline-size: calc(var(--prosper-space-32) + var(--prosper-space-4));
}

.about {
  display: flex;
  flex-direction: column;
}

.summary {
  color: var(--prosper-color-text-tertiary);
}

.licence {
  min-inline-size: var(--prosper-space-32);
}

@media (width < 40rem) {
  .detail {
    display: none;
  }
}
</style>
vue
<script setup lang="ts">
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  IconButton,
  SectionHeader,
  SectionHeaderActions,
  SectionHeaderContent,
  SectionHeaderDivider,
  SectionHeaderHeading,
  SectionHeaderTitle,
} from '@prosper/ui'
import { DotsVertical } from '@prosper/ui/icons'

defineProps<{ id: string; title: string }>()
</script>

<template>
  <section class="block" :aria-labelledby="id">
    <SectionHeader>
      <SectionHeaderContent>
        <SectionHeaderHeading>
          <SectionHeaderTitle :id="id">{{ title }}</SectionHeaderTitle>
        </SectionHeaderHeading>
        <SectionHeaderActions>
          <DropdownMenu>
            <DropdownMenuTrigger as-child>
              <IconButton
                variant="tertiary"
                size="md"
                :aria-label="`Действия: ${title}`"
              >
                <DotsVertical />
              </IconButton>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              <DropdownMenuItem>Скачать отчёт</DropdownMenuItem>
              <DropdownMenuItem>Настроить период</DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </SectionHeaderActions>
      </SectionHeaderContent>
      <SectionHeaderDivider />
    </SectionHeader>
    <slot />
  </section>
</template>

<style scoped>
.block {
  display: flex;
  flex-direction: column;
  gap: var(--prosper-spacing-3xl);
}
</style>
vue
<script setup lang="ts">
import {
  Card,
  Checkbox,
  Table,
  TableBody,
  TableHead,
  TableHeader,
  TableRow,
  type TableSort,
} from '@prosper/ui'
import { computed, ref } from 'vue'

import type { Customer } from '../data/customers'
import CustomersEmpty from './CustomersEmpty.vue'
import CustomersRow from './CustomersRow.vue'

const props = defineProps<{ customers: readonly Customer[] }>()

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

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

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

const some = computed(() =>
  props.customers.some(({ name }) => selected.value.includes(name)),
)

const setAll = (checked: boolean): void => {
  const shown = props.customers.map(({ name }) => name)
  const others = selected.value.filter((name) => !shown.includes(name))

  selected.value = checked ? [...others, ...shown] : others
}

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

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

<template>
  <Card class="table-card">
    <Table aria-label="Клиенты">
      <TableHeader>
        <TableRow>
          <TableHead :sort="sort" @update:sort="flip">
            <template #leading>
              <Checkbox
                aria-label="Выбрать всех клиентов на странице"
                :checked="all"
                :indeterminate="some && !all"
                @update:checked="setAll"
              />
            </template>
            Компания
          </TableHead>
          <TableHead>Статус</TableHead>
          <TableHead class="detail">О компании</TableHead>
          <TableHead class="detail">Сотрудники</TableHead>
          <TableHead class="detail">Лицензии</TableHead>
          <TableHead class="detail">Действия</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        <CustomersRow
          v-for="customer in customers"
          :key="customer.name"
          :customer="customer"
          :selected="selected.includes(customer.name)"
          @update:selected="setOne(customer.name, $event)"
        />
        <CustomersEmpty v-if="customers.length === 0" />
      </TableBody>
    </Table>
    <slot />
  </Card>
</template>

<style scoped>
@container prosper (width < 40rem) {
  @media (width < 64rem) {
    .table-card {
      margin-inline: calc(var(--prosper-spacing-xl) * -1);
    }
  }
}

@media (width < 40rem) {
  .detail {
    display: none;
  }
}
</style>
ts
const names =
  'Ardelo|Brimvia|Corsaro|Dastrel|Esvanto|Fulmera|Gorvelo|Hadrina|Ilvesta|Jurnelo|Kasvira|Lorvani|Metrova|Nastrel|Oredon|Pavlira|Quarvon|Rovesta|Sarvelo|Tenvira|Urvanta|Varelko|Wenvira|Xarveno|Yelvora|Zanvira|Aldorva|Bestrel|Cavanta|Dorvina|Elmaro|Fenvora|Gastrel|Havelin|Ivorsta|Jevanta|Kelmora|Lusvero|Morvina|Nelvaro'.split(
    '|',
  )

export const customerStatuses = {
  customer: { label: 'Клиент', color: 'success' },
  churned: { label: 'Ушёл', color: 'gray' },
} as const

export const customerCategories = [
  'Ритейл',
  'Общепит',
  'Логистика',
  'Услуги',
] as const

const profiles = {
  Ритейл: {
    activity: 'Розничная торговля',
    summary: 'Продажи и остатки в магазинах',
  },
  Общепит: {
    activity: 'Кафе и рестораны',
    summary: 'Заказы и столы в одном окне',
  },
  Логистика: {
    activity: 'Доставка грузов',
    summary: 'Маршруты и учёт перевозок',
  },
  Услуги: {
    activity: 'Бытовые услуги',
    summary: 'Записи клиентов и оплаты',
  },
}

const people = [
  { name: 'Айдар Нурланов' },
  { name: 'Дана Ермекова' },
  { name: 'Мурат Сарсенов' },
  { name: 'Ольга Крылова' },
  { name: 'Елена Сагитова' },
  { name: 'Болат Тулегенов' },
  { name: 'Гульнара Мусина' },
  { name: 'Игорь Ланцов' },
  { name: 'Ксения Петрова' },
  { name: 'Рустам Соловьев' },
]

const statusOf = (index: number): keyof typeof customerStatuses =>
  index % 5 === 4 ? 'churned' : 'customer'

export const customers = names.map((name, index) => {
  const category = customerCategories[index % customerCategories.length]

  return {
    name,
    site: `${name.toLowerCase()}.kz`,
    initials: name.slice(0, 2).toUpperCase(),
    status: statusOf(index),
    category,
    ...profiles[category],
    team: people.slice(index % 5, (index % 5) + 5),
    more: 5 + (index % 4),
    licences: 20 + ((index * 37) % 75),
  }
})

export type Customer = (typeof customers)[number]

export const activeChannels = [
  { channel: 'Веб', percent: 82 },
  { channel: 'Мобильное приложение', percent: 63 },
  { channel: 'API', percent: 41 },
]

export const customerTotals = [
  { month: 'Янв', current: 156, previous: 118, beforePrevious: 92 },
  { month: 'Фев', current: 157, previous: 110, beforePrevious: 84 },
  { month: 'Мар', current: 163, previous: 115, beforePrevious: 90 },
  { month: 'Апр', current: 171, previous: 124, beforePrevious: 97 },
  { month: 'Май', current: 168, previous: 120, beforePrevious: 101 },
  { month: 'Июн', current: 173, previous: 131, beforePrevious: 98 },
  { month: 'Июл', current: 181, previous: 126, beforePrevious: 106 },
  { month: 'Авг', current: 178, previous: 133, beforePrevious: 113 },
  { month: 'Сен', current: 190, previous: 140, beforePrevious: 109 },
  { month: 'Окт', current: 193, previous: 137, beforePrevious: 117 },
  { month: 'Ноя', current: 205, previous: 146, beforePrevious: 124 },
  { month: 'Дек', current: 203, previous: 152, beforePrevious: 131 },
]