Панель со списками заявок (#1)
Co-authored-by: gorbenko.pavel <gorbenko.pavel@tansu.kz> Reviewed-on: http://git.tnsu.kz/timur.gorodetskiy/request-portal/pulls/1 Co-authored-by: gorbenko.pavel <gorbenko.pavel@tnsu.kz> Co-committed-by: gorbenko.pavel <gorbenko.pavel@tnsu.kz>
This commit was merged in pull request #1.
This commit is contained in:
@@ -1,33 +0,0 @@
|
||||
@import '../../../../styles/design-tokens';
|
||||
|
||||
// Постоянная боковая панель (всегда открыта). Раскладку колонок задаёт корень;
|
||||
// здесь — только внутреннее оформление панели.
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: $white;
|
||||
border: 1px solid $gray-200;
|
||||
border-radius: $r-lg;
|
||||
box-shadow: $sh-1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: $sp-4 $sp-5;
|
||||
border-bottom: 1px solid $gray-200;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-family: $font-serif;
|
||||
font-size: 18px;
|
||||
color: $navy-900;
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: $sp-5;
|
||||
color: $gray-500;
|
||||
font-size: $fs-sm;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import type { WebPartContext } from '@microsoft/sp-webpart-base';
|
||||
import styles from './MyRequestsPanel.module.scss';
|
||||
|
||||
export interface IMyRequestsPanelProps {
|
||||
context: WebPartContext;
|
||||
}
|
||||
|
||||
// Постоянная боковая панель «Мои заявки»: пользователь видит, что он отправлял
|
||||
// и согласовывал. Всегда открыта (без кнопки/оверлея).
|
||||
// Владелец: второй разработчик. Вся логика/данные — внутри этой папки.
|
||||
// Общий UI-кит (shared/ui), pnpjs и config можно импортировать, но НЕ менять.
|
||||
const MyRequestsPanel: React.FC<IMyRequestsPanelProps> = (/* { context } */) => {
|
||||
return (
|
||||
<aside className={styles.panel} aria-label="Мои заявки">
|
||||
<div className={styles.header}>
|
||||
<span className={styles.title}>Мои заявки</span>
|
||||
</div>
|
||||
<div className={styles.body}>
|
||||
Раздел в разработке: здесь будут заявки пользователя, статусы и согласования.
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
export default MyRequestsPanel;
|
||||
@@ -0,0 +1,244 @@
|
||||
@import '../../../../styles/design-tokens';
|
||||
|
||||
.view {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: $sp-4;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: $sp-4;
|
||||
}
|
||||
|
||||
.heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $sp-3;
|
||||
margin: 0;
|
||||
font-family: $font-serif;
|
||||
font-size: $fs-page-title;
|
||||
font-weight: 600;
|
||||
color: $navy-900;
|
||||
}
|
||||
|
||||
.count {
|
||||
padding: 2px 10px;
|
||||
border-radius: $r-full;
|
||||
background: $navy-100;
|
||||
color: $navy-700;
|
||||
font-family: $font-sans;
|
||||
font-size: $fs-label;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 280px;
|
||||
max-width: 100%;
|
||||
padding: 9px 13px;
|
||||
border: 1px solid $gray-300;
|
||||
border-radius: $r-sm;
|
||||
background: $white;
|
||||
font-family: $font-sans;
|
||||
font-size: $fs-sm;
|
||||
color: $gray-900;
|
||||
transition: .18s;
|
||||
|
||||
@include input-focus-gold;
|
||||
|
||||
&::placeholder {
|
||||
color: $gray-400;
|
||||
}
|
||||
}
|
||||
|
||||
.empty,
|
||||
.error {
|
||||
padding: $sp-6;
|
||||
background: $white;
|
||||
border: 1px solid $gray-200;
|
||||
border-radius: $r-md;
|
||||
color: $gray-500;
|
||||
font-size: $fs-sm;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: $red-500;
|
||||
border-color: $red-500;
|
||||
background: $red-50;
|
||||
}
|
||||
|
||||
.tableWrap {
|
||||
background: $white;
|
||||
border: 1px solid $gray-200;
|
||||
border-radius: $r-md;
|
||||
box-shadow: $sh-1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: $fs-sm;
|
||||
|
||||
th {
|
||||
text-align: left;
|
||||
padding: 12px 16px;
|
||||
background: $gray-50;
|
||||
border-bottom: 1px solid $gray-200;
|
||||
color: $gray-500;
|
||||
font-size: $fs-label;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .04em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 14px 16px;
|
||||
border-bottom: 1px solid $gray-100;
|
||||
color: $gray-900;
|
||||
vertical-align: middle;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Кликабельна вся строка (см. RequestsTableView — onClick на <tr>).
|
||||
.row {
|
||||
cursor: pointer;
|
||||
transition: background .16s;
|
||||
|
||||
&:hover {
|
||||
background: $gold-50;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid $gold-500;
|
||||
outline-offset: -2px;
|
||||
}
|
||||
}
|
||||
|
||||
.colId {
|
||||
width: 70px;
|
||||
color: $gray-400;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.colType {
|
||||
width: 200px;
|
||||
color: $navy-700;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.colTitle {
|
||||
min-width: 240px;
|
||||
}
|
||||
|
||||
.colDate {
|
||||
width: 110px;
|
||||
color: $gray-500;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.colAuthor {
|
||||
width: 280px;
|
||||
color: $gray-500;
|
||||
}
|
||||
|
||||
.colStatus {
|
||||
width: 190px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-block;
|
||||
padding: 3px 10px;
|
||||
border-radius: $r-md;
|
||||
font-size: $fs-caption;
|
||||
font-weight: 500;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.statusDraft {
|
||||
background: $gray-100;
|
||||
color: $gray-700;
|
||||
}
|
||||
|
||||
.statusOnApproval {
|
||||
background: $gold-100;
|
||||
color: $gold-600;
|
||||
}
|
||||
|
||||
.statusApproved {
|
||||
background: $green-50;
|
||||
color: $green-600;
|
||||
}
|
||||
|
||||
.statusRejected {
|
||||
background: $red-50;
|
||||
color: $red-500;
|
||||
}
|
||||
|
||||
.statusReturned {
|
||||
background: $blue-50;
|
||||
color: $blue-600;
|
||||
}
|
||||
|
||||
.statusDefault {
|
||||
background: $gray-100;
|
||||
color: $gray-500;
|
||||
}
|
||||
|
||||
.pager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $sp-1;
|
||||
margin-top: $sp-4;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.pagerBtn {
|
||||
min-width: 30px;
|
||||
height: 30px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid $gray-200;
|
||||
border-radius: $r-sm;
|
||||
background: $white;
|
||||
color: $gray-700;
|
||||
font-family: $font-sans;
|
||||
font-size: $fs-sm;
|
||||
cursor: pointer;
|
||||
transition: .16s;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
border-color: $gold-400;
|
||||
color: $gold-600;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: .4;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.pagerBtnActive {
|
||||
background: $navy-800;
|
||||
border-color: $navy-800;
|
||||
color: $white;
|
||||
|
||||
&:hover {
|
||||
border-color: $navy-800 !important;
|
||||
color: $white !important;
|
||||
}
|
||||
}
|
||||
|
||||
.pagerEllipsis {
|
||||
color: $gray-400;
|
||||
font-size: $fs-sm;
|
||||
padding: 0 4px;
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import * as React from 'react';
|
||||
import type { WebPartContext } from '@microsoft/sp-webpart-base';
|
||||
import { getLinkedTypes, getOwnRequests, getPendingApproval } from './myRequests.service';
|
||||
import { IMyRequest } from './models/IMyRequest';
|
||||
import { REQUEST_STATUS, IRequestType } from '../../shared/approval';
|
||||
import { onRequestsChanged } from '../../shared/requestEvents';
|
||||
import styles from './RequestsTableView.module.scss';
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export interface IRequestsTableViewProps {
|
||||
context: WebPartContext;
|
||||
/** 'approvals' — ждут решения текущего пользователя; 'own' — созданные им. */
|
||||
kind: 'approvals' | 'own';
|
||||
/** Клик по строке — открыть заявку (в выезжающей панели). */
|
||||
onOpen: (request: IMyRequest) => void;
|
||||
}
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
const dd = d.getDate() < 10 ? `0${d.getDate()}` : `${d.getDate()}`;
|
||||
const mm = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : `${d.getMonth() + 1}`;
|
||||
return `${dd}.${mm}.${d.getFullYear()}`;
|
||||
}
|
||||
|
||||
function statusClass(status: string): string {
|
||||
switch (status) {
|
||||
case REQUEST_STATUS.approved:
|
||||
return styles.statusApproved;
|
||||
case REQUEST_STATUS.rejected:
|
||||
return styles.statusRejected;
|
||||
case REQUEST_STATUS.returned:
|
||||
return styles.statusReturned;
|
||||
case REQUEST_STATUS.onApproval:
|
||||
return styles.statusOnApproval;
|
||||
case REQUEST_STATUS.draft:
|
||||
return styles.statusDraft;
|
||||
default:
|
||||
return styles.statusDefault;
|
||||
}
|
||||
}
|
||||
|
||||
// Постраничная навигация: номера страниц + вперёд/назад. При большом
|
||||
// количестве страниц показывает только соседние с текущей + первую/последнюю.
|
||||
const Pager: React.FC<{ page: number; totalPages: number; onChange: (page: number) => void }> = ({
|
||||
page,
|
||||
totalPages,
|
||||
onChange,
|
||||
}) => {
|
||||
if (totalPages <= 1) return null;
|
||||
|
||||
const numbers: number[] = [];
|
||||
const from = Math.max(1, page - 2);
|
||||
const to = Math.min(totalPages, page + 2);
|
||||
for (let i = from; i <= to; i++) numbers.push(i);
|
||||
|
||||
return (
|
||||
<div className={styles.pager}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pagerBtn}
|
||||
disabled={page <= 1}
|
||||
onClick={() => onChange(page - 1)}
|
||||
aria-label="Предыдущая страница"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
{from > 1 && (
|
||||
<>
|
||||
<button type="button" className={styles.pagerBtn} onClick={() => onChange(1)}>
|
||||
1
|
||||
</button>
|
||||
{from > 2 && <span className={styles.pagerEllipsis}>…</span>}
|
||||
</>
|
||||
)}
|
||||
{numbers.map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className={`${styles.pagerBtn} ${n === page ? styles.pagerBtnActive : ''}`}
|
||||
onClick={() => onChange(n)}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
))}
|
||||
{to < totalPages && (
|
||||
<>
|
||||
{to < totalPages - 1 && <span className={styles.pagerEllipsis}>…</span>}
|
||||
<button type="button" className={styles.pagerBtn} onClick={() => onChange(totalPages)}>
|
||||
{totalPages}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pagerBtn}
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => onChange(page + 1)}
|
||||
aria-label="Следующая страница"
|
||||
>
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Таблица заявок. Клик в ЛЮБОМ месте строки открывает заявку (кликабельна вся
|
||||
// строка, а не только название), поэтому строка — <tr> с onClick + tabIndex
|
||||
// (доступ с клавиатуры: Enter/Space).
|
||||
//
|
||||
// «approvals»: автор — не текущий пользователь, поэтому нужна колонка «Автор»;
|
||||
// статус не показываем — здесь все заявки по определению на согласовании.
|
||||
// «own»: автор всегда текущий пользователь, зато важен статус.
|
||||
const Table: React.FC<{
|
||||
rows: IMyRequest[];
|
||||
kind: 'approvals' | 'own';
|
||||
onOpen: (request: IMyRequest) => void;
|
||||
}> = ({ rows, kind, onOpen }) => (
|
||||
<div className={styles.tableWrap}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={styles.colId}>ID</th>
|
||||
<th className={styles.colType}>Тип</th>
|
||||
<th className={styles.colTitle}>Название</th>
|
||||
<th className={styles.colDate}>Дата</th>
|
||||
{kind === 'approvals' && <th className={styles.colAuthor}>Автор</th>}
|
||||
{kind === 'own' && <th className={styles.colStatus}>Статус</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr
|
||||
className={styles.row}
|
||||
key={`${r.requestTypeId}-${r.id}`}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={`Открыть заявку «${r.title || r.id}»`}
|
||||
onClick={() => onOpen(r)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
onOpen(r);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td className={styles.colId}>{r.id}</td>
|
||||
<td className={styles.colType}>{r.requestTypeName}</td>
|
||||
<td className={styles.colTitle}>{r.title || `#${r.id}`}</td>
|
||||
<td className={styles.colDate}>{formatDate(r.created)}</td>
|
||||
{kind === 'approvals' && (
|
||||
<td className={styles.colAuthor}>
|
||||
{[r.authorName, r.authorEmail].filter(Boolean).join(' · ') || '—'}
|
||||
</td>
|
||||
)}
|
||||
{kind === 'own' && (
|
||||
<td className={styles.colStatus}>
|
||||
<span className={`${styles.status} ${statusClass(r.status)}`}>{r.status || '—'}</span>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Раздел с таблицей заявок: поиск по названию + постраничный вывод.
|
||||
//
|
||||
// 'approvals' грузится целиком (алгоритм «чья сейчас очередь» требует видеть
|
||||
// весь маршрут заявки), поиск и пагинация — на клиенте.
|
||||
// 'own' идёт постранично через обычный REST (см. myRequests.service), поиск —
|
||||
// серверным OData-фильтром по Title.
|
||||
//
|
||||
// Оба варианта перечитываются по событию rp-requests-changed
|
||||
// (shared/requestEvents) — после создания заявки и после решения согласующего.
|
||||
export const RequestsTableView: React.FC<IRequestsTableViewProps> = ({ context, kind, onOpen }) => {
|
||||
const [types, setTypes] = React.useState<IRequestType[] | undefined>(undefined);
|
||||
const [rows, setRows] = React.useState<IMyRequest[] | undefined>(undefined);
|
||||
const [totalRows, setTotalRows] = React.useState<number>(0);
|
||||
const [page, setPage] = React.useState<number>(1);
|
||||
const [query, setQuery] = React.useState<string>('');
|
||||
const [error, setError] = React.useState<string>('');
|
||||
|
||||
React.useEffect(() => setPage(1), [query, kind]);
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false;
|
||||
getLinkedTypes(context)
|
||||
.then((t) => {
|
||||
if (!cancelled) setTypes(t);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError((e as Error).message);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [context]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (types === undefined) return;
|
||||
let cancelled = false;
|
||||
|
||||
const load = (): void => {
|
||||
const request =
|
||||
kind === 'own'
|
||||
? getOwnRequests(context, types, query, page).then((r) => ({ rows: r.rows, total: r.totalRows }))
|
||||
: getPendingApproval(context).then((r) => {
|
||||
console.table(r.debug);
|
||||
return { rows: r.rows, total: r.rows.length };
|
||||
});
|
||||
|
||||
request
|
||||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
setRows(result.rows);
|
||||
setTotalRows(result.total);
|
||||
setError('');
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError((e as Error).message);
|
||||
});
|
||||
};
|
||||
|
||||
load();
|
||||
const unsubscribe = onRequestsChanged(load);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [context, types, kind, query, page]);
|
||||
|
||||
// 'approvals' приходит целиком — фильтруем и нарезаем страницы на клиенте.
|
||||
const q = query.trim().toLowerCase();
|
||||
let visible = rows || [];
|
||||
let total = totalRows;
|
||||
if (kind === 'approvals' && rows) {
|
||||
const filtered = q ? rows.filter((r) => r.title.toLowerCase().indexOf(q) !== -1) : rows;
|
||||
total = filtered.length;
|
||||
visible = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
|
||||
}
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
|
||||
const heading = kind === 'approvals' ? 'Ждут вашего решения' : 'Мои заявки';
|
||||
|
||||
return (
|
||||
<section className={styles.view}>
|
||||
<div className={styles.head}>
|
||||
<h2 className={styles.heading}>
|
||||
{heading}
|
||||
{rows && <span className={styles.count}>{total}</span>}
|
||||
</h2>
|
||||
<input
|
||||
type="search"
|
||||
className={styles.search}
|
||||
placeholder="Поиск по названию…"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <div className={styles.error}>Не удалось загрузить заявки: {error}</div>}
|
||||
{!error && rows === undefined && <div className={styles.empty}>Загрузка…</div>}
|
||||
{!error && rows && total === 0 && (
|
||||
<div className={styles.empty}>
|
||||
{q
|
||||
? `По запросу «${query}» ничего не найдено.`
|
||||
: kind === 'approvals'
|
||||
? 'Нет заявок, ждущих вашего решения.'
|
||||
: 'Вы ещё не создавали заявок.'}
|
||||
</div>
|
||||
)}
|
||||
{!error && rows && total > 0 && (
|
||||
<>
|
||||
<Table rows={visible} kind={kind} onOpen={onOpen} />
|
||||
<Pager page={page} totalPages={totalPages} onChange={setPage} />
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
// Строка заявки пользователя для боковой панели «Мои заявки».
|
||||
// Собирается из списка данных SharePoint конкретного типа заявки (см. myRequests.service.ts).
|
||||
export interface IMyRequest {
|
||||
id: number;
|
||||
title: string;
|
||||
status: string;
|
||||
authorEmail: string;
|
||||
authorName: string;
|
||||
/** Дата создания (ISO-строка, колонка Created). */
|
||||
created: string;
|
||||
requestTypeId: number;
|
||||
requestTypeName: string;
|
||||
section: string;
|
||||
/** Ключ формы (rptype в URL режима согласования) — поле pageUrl из approval-route API. */
|
||||
formKey: string;
|
||||
/** 'own' — заявка, созданная текущим пользователем; 'approval' — ждёт его решения. */
|
||||
kind: 'own' | 'approval';
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Диагностика по одному типу заявки — для отладочного блока в панели «Мои заявки».
|
||||
export interface IMyRequestsTypeDebug {
|
||||
requestTypeId: number;
|
||||
requestTypeName: string;
|
||||
listId?: string;
|
||||
siteUrl?: string;
|
||||
/** Тип пропущен: у него нет listId/siteUrl в approval-route API. */
|
||||
skipped: boolean;
|
||||
/** Сколько строк текущего пользователя найдено (undefined, если не дошли до запроса). */
|
||||
rowCount?: number;
|
||||
/** Текст ошибки, если запрос к списку упал. */
|
||||
error?: string;
|
||||
|
||||
/** Заголовок списка согласования, вычисленный из имени списка данных. */
|
||||
approvalListTitle?: string;
|
||||
/** Список данных не похож на «... — данные» — список согласования не искали. */
|
||||
approvalSkippedReason?: string;
|
||||
/** Сколько строк маршрута (фаза «Согласование») прочитано из списка согласования. */
|
||||
approvalRowCount?: number;
|
||||
/** Сколько заявок сейчас ждут решения текущего пользователя. */
|
||||
approvalPendingTickets?: number;
|
||||
/** Текст ошибки, если запрос к списку согласования упал. */
|
||||
approvalError?: string;
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { spfi, SPFx } from '@pnp/sp';
|
||||
import '@pnp/sp/webs';
|
||||
import '@pnp/sp/lists';
|
||||
import '@pnp/sp/items';
|
||||
import '@pnp/sp/site-users/web';
|
||||
import { WebPartContext } from '@microsoft/sp-webpart-base';
|
||||
import { getRequestTypes, IRequestType, REQUEST_STATUS } from '../../shared/approval';
|
||||
import { IMyRequest } from './models/IMyRequest';
|
||||
import { IMyRequestsTypeDebug } from './models/IMyRequestsDebug';
|
||||
|
||||
// Список данных «... — данные» → список согласования «... — согласование»
|
||||
// (конвенция именования; см. forms/*/provisioning.json и forms/*/approval/provisioning.json).
|
||||
const DATA_LIST_SUFFIX = /\s*—\s*данные\s*$/;
|
||||
|
||||
interface IApprovalStep {
|
||||
status: string;
|
||||
order?: number;
|
||||
approverEmail: string;
|
||||
}
|
||||
|
||||
export function currentUserEmail(context: WebPartContext): string {
|
||||
return (context.pageContext.user.email || '').toLowerCase();
|
||||
}
|
||||
|
||||
// Типы заявок, у которых approval-route API уже отдал listId/siteUrl (готовы к чтению).
|
||||
export async function getLinkedTypes(context: WebPartContext): Promise<IRequestType[]> {
|
||||
const types = await getRequestTypes(context);
|
||||
return types.filter((t) => !!t.listId && !!t.siteUrl);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// «Ждёт вашего решения» — требует видеть ВЕСЬ маршрут заявки, чтобы понять,
|
||||
// чья сейчас очередь, поэтому идёт обычным REST-запросом (не через Search),
|
||||
// целиком за один раз. Пагинация по этому результату — на стороне панели
|
||||
// (клиентская нарезка по страницам), т.к. сам список обычно небольшой
|
||||
// (сколько заявок сейчас реально ждут решения ОДНОГО согласующего).
|
||||
export async function getPendingApproval(
|
||||
context: WebPartContext
|
||||
): Promise<{ rows: IMyRequest[]; debug: IMyRequestsTypeDebug[] }> {
|
||||
const types = await getLinkedTypes(context);
|
||||
const tokenEmail = currentUserEmail(context);
|
||||
|
||||
const perType = await Promise.all(
|
||||
types.map((t) => getApprovalPendingForType(context, t, tokenEmail))
|
||||
);
|
||||
|
||||
return {
|
||||
rows: perType.reduce((all, r) => all.concat(r.rows), [] as IMyRequest[]),
|
||||
debug: perType.map((r) => r.debug),
|
||||
};
|
||||
}
|
||||
|
||||
async function getApprovalPendingForType(
|
||||
context: WebPartContext,
|
||||
type: IRequestType,
|
||||
tokenEmail: string
|
||||
): Promise<{ rows: IMyRequest[]; debug: IMyRequestsTypeDebug }> {
|
||||
const debug: IMyRequestsTypeDebug = {
|
||||
requestTypeId: type.id,
|
||||
requestTypeName: type.name,
|
||||
listId: type.listId,
|
||||
siteUrl: type.siteUrl,
|
||||
skipped: false,
|
||||
};
|
||||
|
||||
try {
|
||||
const sp = spfi(type.siteUrl as string).using(SPFx(context));
|
||||
const list = sp.web.getList(type.listId as string);
|
||||
|
||||
const dataListInfo = await list.select('Title')();
|
||||
const dataTitle = (dataListInfo.Title as string) || '';
|
||||
if (!DATA_LIST_SUFFIX.test(dataTitle)) {
|
||||
debug.approvalSkippedReason = `«${dataTitle}» не оканчивается на «— данные» — список согласования не ищем`;
|
||||
return { rows: [], debug };
|
||||
}
|
||||
const approvalListTitle = `${dataTitle.replace(DATA_LIST_SUFFIX, '')} — согласование`;
|
||||
debug.approvalListTitle = approvalListTitle;
|
||||
const approvalList = sp.web.lists.getByTitle(approvalListTitle);
|
||||
|
||||
// Phase не смотрим вообще — работаем только по Status.
|
||||
const stepRows = (await approvalList.items
|
||||
.select('Id', 'StepOrder', 'Status', 'TicketId', 'Approver/EMail')
|
||||
.expand('Approver')
|
||||
.top(2000)()) as Array<Record<string, unknown>>;
|
||||
console.log(
|
||||
`[Текущие заявки] «${type.name}»: список согласования «${approvalListTitle}», элементов в списке: ${stepRows.length}, ваш email из токена: «${tokenEmail}»`
|
||||
);
|
||||
console.table(
|
||||
stepRows.map((r) => ({
|
||||
Id: r.Id,
|
||||
TicketId: r.TicketId,
|
||||
StepOrder: r.StepOrder,
|
||||
Status: r.Status,
|
||||
'Approver/EMail': (r.Approver as { EMail?: string } | undefined)?.EMail,
|
||||
}))
|
||||
);
|
||||
|
||||
debug.approvalRowCount = stepRows.length;
|
||||
|
||||
const byTicket = new Map<number, IApprovalStep[]>();
|
||||
stepRows.forEach((r) => {
|
||||
const ticketId = r.TicketId as number | undefined;
|
||||
if (!ticketId) return;
|
||||
const approver = r.Approver as { EMail?: string } | undefined;
|
||||
const steps = byTicket.get(ticketId) || [];
|
||||
steps.push({
|
||||
status: (r.Status as string) || '',
|
||||
order: typeof r.StepOrder === 'number' ? (r.StepOrder as number) : undefined,
|
||||
approverEmail: (approver?.EMail || '').toLowerCase(),
|
||||
});
|
||||
byTicket.set(ticketId, steps);
|
||||
});
|
||||
|
||||
const myTicketIds: number[] = [];
|
||||
const byTicketDebug: Array<Record<string, unknown>> = [];
|
||||
byTicket.forEach((steps, ticketId) => {
|
||||
const mine = isMyTurn(steps, tokenEmail);
|
||||
byTicketDebug.push({ TicketId: ticketId, isMyTurn: mine, steps: JSON.stringify(steps) });
|
||||
if (mine) myTicketIds.push(ticketId);
|
||||
});
|
||||
console.table(byTicketDebug);
|
||||
|
||||
debug.approvalPendingTickets = myTicketIds.length;
|
||||
if (myTicketIds.length === 0) return { rows: [], debug };
|
||||
|
||||
const ticketFilter = myTicketIds.map((id) => `Id eq ${id}`).join(' or ');
|
||||
const ticketRows = (await list.items
|
||||
.filter(ticketFilter)
|
||||
.select('Id', 'Title', 'Status', 'Created', 'Author/EMail', 'Author/Title')
|
||||
.expand('Author')
|
||||
.top(2000)()) as Array<Record<string, unknown>>;
|
||||
|
||||
const rows = ticketRows.map((r) => {
|
||||
const author = r.Author as { EMail?: string; Title?: string } | undefined;
|
||||
return toMyRequest(r, author, type, 'approval');
|
||||
});
|
||||
return { rows, debug };
|
||||
} catch (e) {
|
||||
debug.approvalError = (e as Error).message;
|
||||
console.error(
|
||||
`Мои заявки: не удалось прочитать согласование для «${type.name}»:`,
|
||||
debug.approvalError
|
||||
);
|
||||
return { rows: [], debug };
|
||||
}
|
||||
}
|
||||
|
||||
// Сейчас ли очередь пользователя с данным email среди строк маршрута одной заявки.
|
||||
// Маршрут остановлен (где-то есть Отклонено/Возвращена) — не его очередь, заявка
|
||||
// не активна. Иначе «текущие» строки — это ещё не решённые (Status = На согласовании)
|
||||
// без указанного StepOrder (параллельно, все активны сразу) плюс, если есть строки
|
||||
// с указанным StepOrder, ещё не решённая с минимальным StepOrder (последовательно).
|
||||
function isMyTurn(steps: IApprovalStep[], tokenEmail: string): boolean {
|
||||
if (!tokenEmail) return false;
|
||||
const stopped = steps.some(
|
||||
(s) => s.status === REQUEST_STATUS.rejected || s.status === REQUEST_STATUS.returned
|
||||
);
|
||||
if (stopped) return false;
|
||||
|
||||
const pending = steps.filter((s) => s.status === REQUEST_STATUS.onApproval);
|
||||
const noOrder = pending.filter((s) => s.order === undefined);
|
||||
const ordered = pending.filter((s): s is IApprovalStep & { order: number } => s.order !== undefined);
|
||||
|
||||
const current = [...noOrder];
|
||||
if (ordered.length > 0) {
|
||||
const minOrder = Math.min(...ordered.map((s) => s.order));
|
||||
current.push(...ordered.filter((s) => s.order === minOrder));
|
||||
}
|
||||
|
||||
return current.some((s) => s.approverEmail === tokenEmail);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// «Созданы вами» — обычный REST по спискам данных (НЕ Search): данные всегда
|
||||
// актуальны, только что созданная заявка видна сразу (у поискового индекса
|
||||
// была бы задержка переиндексации).
|
||||
//
|
||||
// Пагинация «сшивает» несколько списков в один нумерованный список: сначала по
|
||||
// каждому типу берём только лёгкие поля (Id + Created) всех заявок автора,
|
||||
// сортируем объединённый набор по дате создания и лишь для нужной страницы
|
||||
// дочитываем полные поля. Так на экран не тянется всё содержимое заявок,
|
||||
// но общее число страниц известно точно.
|
||||
export interface IOwnRequestsPage {
|
||||
rows: IMyRequest[];
|
||||
totalRows: number;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
// Столько «лёгких» строк (Id + Created) максимум читаем из одного списка, чтобы
|
||||
// посчитать общее число страниц. Хватает с большим запасом; если у кого-то
|
||||
// заявок окажется больше — в консоль уйдёт предупреждение.
|
||||
const INDEX_LIMIT = 5000;
|
||||
|
||||
// В OData-строке одинарная кавычка экранируется удвоением.
|
||||
function escapeOData(text: string): string {
|
||||
return text.replace(/'/g, "''");
|
||||
}
|
||||
|
||||
interface IOwnIndexEntry {
|
||||
id: number;
|
||||
created: string;
|
||||
type: IRequestType;
|
||||
}
|
||||
|
||||
export async function getOwnRequests(
|
||||
context: WebPartContext,
|
||||
types: IRequestType[],
|
||||
query: string,
|
||||
page: number
|
||||
): Promise<IOwnRequestsPage> {
|
||||
if (types.length === 0) return { rows: [], totalRows: 0 };
|
||||
|
||||
const q = query.trim();
|
||||
|
||||
// 1) Лёгкий индекс по каждому типу: только Id + Created заявок автора.
|
||||
const perType = await Promise.all(
|
||||
types.map(async (type): Promise<IOwnIndexEntry[]> => {
|
||||
try {
|
||||
const sp = spfi(type.siteUrl as string).using(SPFx(context));
|
||||
const me = await sp.web.currentUser.select('Id')();
|
||||
const filters = [`AuthorId eq ${me.Id}`];
|
||||
if (q) filters.push(`substringof('${escapeOData(q)}',Title)`);
|
||||
|
||||
const rows = (await sp.web
|
||||
.getList(type.listId as string)
|
||||
.items.filter(filters.join(' and '))
|
||||
.select('Id', 'Created')
|
||||
.orderBy('Created', false)
|
||||
.top(INDEX_LIMIT)()) as Array<Record<string, unknown>>;
|
||||
|
||||
if (rows.length === INDEX_LIMIT) {
|
||||
console.warn(
|
||||
`[Текущие заявки] «${type.name}»: индекс своих заявок обрезан на ${INDEX_LIMIT} — часть страниц не видна`
|
||||
);
|
||||
}
|
||||
return rows.map((r) => ({ id: r.Id as number, created: (r.Created as string) || '', type }));
|
||||
} catch (e) {
|
||||
console.error(`[Текущие заявки] «${type.name}»: не удалось прочитать свои заявки:`, (e as Error).message);
|
||||
return [];
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// 2) Общий список всех типов, свежие сверху.
|
||||
const index = perType
|
||||
.reduce((all, rows) => all.concat(rows), [] as IOwnIndexEntry[])
|
||||
.sort((a, b) => b.created.localeCompare(a.created));
|
||||
|
||||
const pageEntries = index.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
|
||||
if (pageEntries.length === 0) {
|
||||
return { rows: [], totalRows: index.length };
|
||||
}
|
||||
|
||||
// 3) Полные поля — только для заявок текущей страницы, по своему списку на тип.
|
||||
const idsByType = new Map<IRequestType, number[]>();
|
||||
pageEntries.forEach((e) => {
|
||||
const ids = idsByType.get(e.type) || [];
|
||||
ids.push(e.id);
|
||||
idsByType.set(e.type, ids);
|
||||
});
|
||||
|
||||
const byKey = new Map<string, IMyRequest>();
|
||||
await Promise.all(
|
||||
Array.from(idsByType.entries()).map(async ([type, ids]) => {
|
||||
const sp = spfi(type.siteUrl as string).using(SPFx(context));
|
||||
const rows = (await sp.web
|
||||
.getList(type.listId as string)
|
||||
.items.filter(ids.map((id) => `Id eq ${id}`).join(' or '))
|
||||
.select('Id', 'Title', 'Status', 'Created', 'Author/EMail', 'Author/Title')
|
||||
.expand('Author')
|
||||
.top(PAGE_SIZE)()) as Array<Record<string, unknown>>;
|
||||
rows.forEach((r) => {
|
||||
const author = r.Author as { EMail?: string; Title?: string } | undefined;
|
||||
byKey.set(`${type.id}-${r.Id as number}`, toMyRequest(r, author, type, 'own'));
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// Порядок страницы задаёт индекс (по дате), а не порядок ответов REST.
|
||||
const rows = pageEntries
|
||||
.map((e) => byKey.get(`${e.type.id}-${e.id}`))
|
||||
.filter((r): r is IMyRequest => !!r);
|
||||
|
||||
return { rows, totalRows: index.length };
|
||||
}
|
||||
|
||||
function toMyRequest(
|
||||
r: Record<string, unknown>,
|
||||
author: { EMail?: string; Title?: string } | undefined,
|
||||
type: IRequestType,
|
||||
kind: 'own' | 'approval'
|
||||
): IMyRequest {
|
||||
return {
|
||||
id: r.Id as number,
|
||||
title: (r.Title as string) || '',
|
||||
status: (r.Status as string) || '',
|
||||
authorEmail: author?.EMail || '',
|
||||
authorName: author?.Title || '',
|
||||
created: (r.Created as string) || '',
|
||||
requestTypeId: type.id,
|
||||
requestTypeName: type.name,
|
||||
section: type.section,
|
||||
formKey: type.pageUrl,
|
||||
kind,
|
||||
};
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
@import '../../../../styles/design-tokens';
|
||||
|
||||
// Центрированная колонка контента. 1080px — ширина контента из дизайн-системы
|
||||
// (как .sec в референсе): форма и плитки читаются аккуратно, не растягиваясь.
|
||||
// Колонка контента. 1080px — ширина контента из дизайн-системы (как .sec в
|
||||
// референсе): форма и плитки читаются аккуратно, не растягиваясь. Прижата
|
||||
// влево (без margin: auto), иначе на широком экране между боковым меню и
|
||||
// формой появлялась пустая полоса, а вкладки категорий сверху шли шире формы.
|
||||
.content {
|
||||
width: 100%;
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
// ── Заглушка формы (до появления реальных форм) ──
|
||||
.formPlaceholder {
|
||||
margin-top: $sp-6;
|
||||
padding: $sp-8;
|
||||
background: $white;
|
||||
border: 1px solid $gray-200;
|
||||
@@ -44,7 +44,6 @@
|
||||
}
|
||||
|
||||
.loading {
|
||||
margin-top: $sp-6;
|
||||
padding: $sp-8;
|
||||
color: $gray-500;
|
||||
font-size: $fs-sm;
|
||||
|
||||
@@ -1,41 +1,40 @@
|
||||
import * as React from 'react';
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import type { WebPartContext } from '@microsoft/sp-webpart-base';
|
||||
import styles from './SubmitFeature.module.scss';
|
||||
import { Icon } from '../../shared/ui/Icon/Icon';
|
||||
import { CategoryTabs } from '../../components/CategoryTabs/CategoryTabs';
|
||||
import { RequestGrid } from '../../components/RequestGrid/RequestGrid';
|
||||
import { CATEGORIES, DEFAULT_CATEGORY_ID } from '../../data/categories';
|
||||
import { getRequestsByCategory, REQUEST_TYPES } from '../../data/requests';
|
||||
import { getFormComponent } from '../../forms/registry';
|
||||
import { IRequestType } from '../../models/types';
|
||||
import { emitRequestsChanged } from '../../shared/requestEvents';
|
||||
|
||||
export interface ISubmitFeatureProps {
|
||||
context: WebPartContext;
|
||||
/** Активная категория. Вкладки теперь рендерятся на уровне портала (RequestPortal),
|
||||
* чтобы оставаться на экране и в режиме согласования — эта фича их только слушает. */
|
||||
activeCategoryId: string;
|
||||
/** Открыть сразу форму с предзаполнением (производная заявка), минуя плитки. */
|
||||
initialForm?: { formKey: string; sourceId: number };
|
||||
}
|
||||
|
||||
// Фича «Подать заявку»: категории → плитки → беспоук-форма.
|
||||
// Фича «Подать заявку»: плитки → беспоук-форма (категории/вкладки — в RequestPortal).
|
||||
// Владелец: автор портала. Живёт целиком в features/submit/**.
|
||||
const SubmitFeature: React.FC<ISubmitFeatureProps> = ({ context, initialForm }) => {
|
||||
const SubmitFeature: React.FC<ISubmitFeatureProps> = ({ context, activeCategoryId, initialForm }) => {
|
||||
// Если пришли по ссылке «создать на основе» — сразу открываем нужную форму.
|
||||
const initialSelected = useMemo(
|
||||
() => (initialForm ? REQUEST_TYPES.filter((r) => r.id === initialForm.formKey)[0] ?? null : null),
|
||||
[initialForm]
|
||||
);
|
||||
|
||||
const [activeCategoryId, setActiveCategoryId] = useState<string>(
|
||||
initialSelected ? initialSelected.categoryId : DEFAULT_CATEGORY_ID
|
||||
);
|
||||
const [selectedRequest, setSelectedRequest] = useState<IRequestType | null>(initialSelected);
|
||||
|
||||
const requests = getRequestsByCategory(activeCategoryId);
|
||||
// Смена категории (вкладка сверху) — возвращаемся к списку плиток.
|
||||
useEffect(() => {
|
||||
setSelectedRequest((prev) => (prev && prev.categoryId !== activeCategoryId ? null : prev));
|
||||
}, [activeCategoryId]);
|
||||
|
||||
const handleCategoryChange = (categoryId: string): void => {
|
||||
setActiveCategoryId(categoryId);
|
||||
setSelectedRequest(null); // при смене категории возвращаемся к списку плиток
|
||||
};
|
||||
const requests = getRequestsByCategory(activeCategoryId);
|
||||
|
||||
const handleBack = (): void => setSelectedRequest(null);
|
||||
|
||||
@@ -62,19 +61,19 @@ const SubmitFeature: React.FC<ISubmitFeatureProps> = ({ context, initialForm })
|
||||
// Ленивый рендер формы: её код подтягивается только сейчас, при открытии.
|
||||
return (
|
||||
<React.Suspense fallback={<div className={styles.loading}>Загрузка формы…</div>}>
|
||||
<FormComponent requestType={request} context={context} onCancel={handleBack} sourceId={sourceId} />
|
||||
<FormComponent
|
||||
requestType={request}
|
||||
context={context}
|
||||
onCancel={handleBack}
|
||||
onSaved={emitRequestsChanged}
|
||||
sourceId={sourceId}
|
||||
/>
|
||||
</React.Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.content}>
|
||||
<CategoryTabs
|
||||
categories={CATEGORIES}
|
||||
activeId={activeCategoryId}
|
||||
onChange={handleCategoryChange}
|
||||
/>
|
||||
|
||||
{selectedRequest ? (
|
||||
renderSelected(selectedRequest)
|
||||
) : (
|
||||
|
||||
Reference in New Issue
Block a user