PEP-161: «Написать аналитику» on the project cards of «Проекты»
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
1074d276b6
commit
fc48b53945
@ -1,6 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { Plus } from "lucide-react";
|
||||
import { listOtherProjects, listUserProjects } from "@peppa/core";
|
||||
import { analystLinks, listOtherProjects, listUserProjects } from "@peppa/core";
|
||||
import { ProjectList } from "@/components/cards";
|
||||
import { Flash, PageHeader, Section } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -14,7 +14,7 @@ export default async function Projects({ searchParams }: { searchParams: Promise
|
||||
const w = await words();
|
||||
const { error } = await searchParams;
|
||||
const t = await getT();
|
||||
const [projects, others] = await Promise.all([listUserProjects(db, user.id), listOtherProjects(db, user.id)]);
|
||||
const [projects, others, analyst] = await Promise.all([listUserProjects(db, user.id), listOtherProjects(db, user.id), analystLinks(db, user)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<Flash error={error} />
|
||||
@ -31,7 +31,7 @@ export default async function Projects({ searchParams }: { searchParams: Promise
|
||||
>
|
||||
{w.engineer ? t("Свои и общие проекты: доска стори, код, PR, релизы, ошибки из прода, участники.") : t("Ваши проекты и те, куда вас пригласили. Откройте проект, чтобы поставить задачу или посмотреть результат.")}
|
||||
</PageHeader>
|
||||
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} />
|
||||
<ProjectList projects={projects} userId={user.id} engineer={w.engineer} analyst={analyst} />
|
||||
{others.length > 0 && (
|
||||
<Section title={t("Проекты других")} count={others.length}>
|
||||
<p className="m-0 text-sm text-muted-foreground">{t("Видны вам как суперадмину. Вопросы агентов и уведомления этих проектов к вам не приходят.")}</p>
|
||||
|
||||
@ -3,6 +3,8 @@ import Link from "next/link";
|
||||
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
|
||||
import { questionDetails, questionIsFreeText, questionState, questionText, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { MessagesSquare } from "lucide-react";
|
||||
import type { AnalystLink } from "@peppa/core";
|
||||
import { SubscriptionName } from "@/components/SubscriptionName";
|
||||
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -256,7 +258,7 @@ export async function AgentAtWork({ s, back, engineer = false }: { s: SessionVie
|
||||
}
|
||||
|
||||
/** `engineer` (PEP-123): the address of the code is shown in «Инженер» only. */
|
||||
export async function ProjectList({ projects, userId, engineer = false }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number; engineer?: boolean }) {
|
||||
export async function ProjectList({ projects, userId, engineer = false, analyst }: { projects: Array<Project & { ownerLogin?: string | null }>; userId: number; engineer?: boolean; /** PEP-161: projectId → the chat with the analyst; no entry — no link. */ analyst?: Map<number, AnalystLink> }) {
|
||||
const t = await getT();
|
||||
if (!projects.length)
|
||||
return (
|
||||
@ -266,22 +268,32 @@ export async function ProjectList({ projects, userId, engineer = false }: { proj
|
||||
);
|
||||
return (
|
||||
<ul className="m-0 grid list-none gap-2 p-0 sm:grid-cols-2">
|
||||
{projects.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link href={`/p/${p.key}`} className="flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 text-foreground transition-colors hover:border-primary/50 hover:no-underline">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span>
|
||||
<span className="min-w-0 truncate font-medium">{p.name}</span>
|
||||
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}</span>}
|
||||
</span>
|
||||
{engineer && (
|
||||
<span className="truncate font-mono text-xs text-muted-foreground">
|
||||
{p.giteaOwner}/{p.giteaRepo}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
{projects.map((p) => {
|
||||
const chat = analyst?.get(p.id);
|
||||
return (
|
||||
<li key={p.id}>
|
||||
{/* The project link is stretched over the whole card; the analyst link lies on top of it — no nested links. */}
|
||||
<div className="relative flex h-full flex-col gap-1 rounded-lg border bg-card px-4 py-3 transition-colors hover:border-primary/50">
|
||||
<Link href={`/p/${p.key}`} className="flex items-center gap-2 text-foreground after:absolute after:inset-0 after:rounded-lg hover:no-underline">
|
||||
<span className="rounded bg-muted px-1.5 font-mono text-xs text-primary">{p.key}</span>
|
||||
<span className="min-w-0 truncate font-medium">{p.name}</span>
|
||||
{p.ownerId !== userId && <span className="ml-auto rounded-full border px-2 text-[11px] text-muted-foreground">{p.ownerLogin !== undefined ? (p.ownerLogin ?? t("без владельца")) : t("общий")}</span>}
|
||||
</Link>
|
||||
{engineer && (
|
||||
<span className="truncate font-mono text-xs text-muted-foreground">
|
||||
{p.giteaOwner}/{p.giteaRepo}
|
||||
</span>
|
||||
)}
|
||||
{chat && (
|
||||
<Link href={chat.href} className="relative z-10 mt-1 inline-flex items-center gap-1.5 self-start py-1 text-sm font-medium text-primary">
|
||||
<MessagesSquare className="size-4" /> {t("Написать аналитику")}
|
||||
{chat.unread > 0 && <span className="rounded-full bg-info px-2 text-xs font-semibold text-background" title={t("новые сообщения")}>{t("{n} нов.", { n: chat.unread })}</span>}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
19
openspec/changes/pep-161-analyst-in-projects/design.md
Normal file
19
openspec/changes/pep-161-analyst-in-projects/design.md
Normal file
@ -0,0 +1,19 @@
|
||||
## Context
|
||||
|
||||
`ProjectList` (components/cards.tsx) рисует карточку проекта одной ссылкой на `/p/<KEY>`; его используют «Проекты» и Главная. Чат с аналитиком — `/chats/<KEY>` (PEP-106/110), обзор с непрочитанным — `chatOverview` (core/chats.ts), он отдаёт только проекты из `userProjectIds` (свои и общие).
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
- Цель: с экрана «Проекты» попасть в чат с аналитиком любого своего проекта одним нажатием и видеть, где есть новые сообщения.
|
||||
- Не цель: менять Главную, сам чат, «Чаты»; встраивать поле ввода в карточку.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Ссылка в карточке, а не отдельный блок.** `ProjectList` получает необязательный проп `analyst: Map<id проекта, {href, unread}>`; ссылка рисуется только у проектов из этой карты. Страница «Проекты» передаёт карту из `analystLinks` для своих проектов и ничего — для «Проектов других»; Главная проп не передаёт и остаётся как была.
|
||||
- **Вложенных ссылок нет.** Карточка становится `div`; ссылка на проект растянута на всю карточку (`after:absolute after:inset-0`), «Написать аналитику» лежит поверх (`relative z-10`).
|
||||
- **Данные — `analystLinks` (core/chats.ts).** Маленькая функция поверх `listChats` и `discussionUnread`: id проекта → адрес чата и непрочитанное, только свои и общие проекты; так правило «у чужого ссылки нет» проверяется тестом ядра.
|
||||
- **Слова** — «Написать аналитику» (как в «Чатах», перевод есть), счётчик — «{n} нов.» с подсказкой «новые сообщения» (обе строки уже переведены).
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- `analystLinks` делает по запросу на проект — у пользователя их единицы, страница не живая; приемлемо.
|
||||
22
openspec/changes/pep-161-analyst-in-projects/proposal.md
Normal file
22
openspec/changes/pep-161-analyst-in-projects/proposal.md
Normal file
@ -0,0 +1,22 @@
|
||||
## Why
|
||||
|
||||
Чат с аналитиком — главный способ поставить задачу и узнать, что с проектом, но в разделе «Проекты» его нет: чтобы написать аналитику, нужно сначала открыть проект или уйти в «Чаты». Владелец попросил вывести аналитика в раздел «Проекты» (PEP-161).
|
||||
|
||||
## What Changes
|
||||
|
||||
- В разделе «Проекты» у каждой карточки своего проекта (владелец или участник) появляется ссылка «Написать аналитику» — открывает чат с аналитиком этого проекта.
|
||||
- Рядом со ссылкой — число непрочитанных сообщений в этом чате, если они есть.
|
||||
- У карточек «Проекты других» (видны суперадмину) ссылки нет: писать в чужой чат он не может.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `project-chats`: новое требование — чат с аналитиком доступен из раздела «Проекты».
|
||||
|
||||
## Impact
|
||||
|
||||
- `apps/web/components/cards.tsx` (`ProjectList`), `apps/web/app/(app)/projects/page.tsx`.
|
||||
- Переводы en/kk — строка «Написать аналитику» уже есть; новые — подписи счётчика.
|
||||
- Тест `discussion.test.ts`.
|
||||
@ -0,0 +1,22 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Чат с аналитиком из раздела «Проекты»
|
||||
В разделе «Проекты» у каждой карточки проекта, где пользователь владелец или участник, система SHALL показывать ссылку «Написать аналитику», которая открывает чат с аналитиком этого проекта, и число непрочитанных сообщений этого чата, если они есть. У проектов, которые суперадмин видит как чужие, ссылки SHALL NOT быть.
|
||||
|
||||
#### Scenario: Ссылка на аналитика у своего проекта
|
||||
- **GIVEN** пользователь «anna» — владелец проекта «SHOP»
|
||||
- **WHEN** она открывает раздел «Проекты»
|
||||
- **THEN** на карточке «SHOP» есть ссылка «Написать аналитику»
|
||||
- **AND** ссылка ведёт в чат с аналитиком проекта «SHOP»
|
||||
|
||||
#### Scenario: Непрочитанный ответ аналитика виден на карточке
|
||||
- **GIVEN** пользователь «anna» — владелец проекта «SHOP»
|
||||
- **AND** аналитик ответил в чате проекта, и «anna» ответ ещё не открывала
|
||||
- **WHEN** она открывает раздел «Проекты»
|
||||
- **THEN** рядом со ссылкой «Написать аналитику» на карточке «SHOP» стоит «1 нов.»
|
||||
|
||||
#### Scenario: У чужого проекта ссылки нет
|
||||
- **GIVEN** суперадмин «boss» не владелец и не участник проекта «SHOP»
|
||||
- **WHEN** он открывает раздел «Проекты»
|
||||
- **THEN** карточка «SHOP» есть в блоке «Проекты других»
|
||||
- **AND** ссылки «Написать аналитику» на ней нет
|
||||
7
openspec/changes/pep-161-analyst-in-projects/tasks.md
Normal file
7
openspec/changes/pep-161-analyst-in-projects/tasks.md
Normal file
@ -0,0 +1,7 @@
|
||||
## 1. Веб
|
||||
- [ ] 1.1 `ProjectList`: карточка без вложенных ссылок, ссылка «Написать аналитику» и счётчик непрочитанного по пропу `analyst`
|
||||
- [ ] 1.2 Страница «Проекты» передаёт карту из `analystLinks` своим проектам
|
||||
|
||||
## 2. Проверка
|
||||
- [ ] 2.1 Тест по сценариям спеки (`discussion.test.ts`)
|
||||
- [ ] 2.2 Экран «Проекты» открыт в браузере (оба вида, телефон), тексты сверены со словарём
|
||||
@ -292,6 +292,23 @@ export async function chatOverview(db: Db, user: Pick<User, "id">): Promise<Proj
|
||||
return out.sort((a, b) => b.open - a.open || b.unread - a.unread || (b.last?.at.getTime() ?? 0) - (a.last?.at.getTime() ?? 0));
|
||||
}
|
||||
|
||||
/** Where to write to the analyst of a project, and how much there is unread (PEP-161). */
|
||||
export interface AnalystLink {
|
||||
href: string;
|
||||
unread: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* «Написать аналитику» on the project cards of «Проекты» (PEP-161): projectId → link, only for
|
||||
* the projects the user owns or is a member of — a superadmin gets none for other people's.
|
||||
*/
|
||||
export async function analystLinks(db: Db, user: Pick<User, "id">): Promise<Map<number, AnalystLink>> {
|
||||
const unread = await discussionUnread(db, user.id);
|
||||
const out = new Map<number, AnalystLink>();
|
||||
for (const c of await listChats(db, user)) if (c.kind === "project" && c.projectId != null) out.set(c.projectId, { href: `/chats/${c.slug}`, unread: unread.get(c.id) ?? 0 });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The master feed: the user's own master messages and the important messages of the chats
|
||||
* of their projects (muted projects left out). `threadKey` narrows it to one project thread.
|
||||
|
||||
@ -99,4 +99,24 @@ describe("PEP-106: project discussion", () => {
|
||||
const rest = await core.chatMessagesView(db, chat.id, {});
|
||||
assert.ok(rest.every((m) => m.kind === "user" && m.threadKey === null && !m.text.startsWith("/")), "events, threads and commands are pruned");
|
||||
});
|
||||
|
||||
// PEP-161, spec project-chats: «Чат с аналитиком из раздела „Проекты“».
|
||||
test("PEP-161: Ссылка на аналитика у своего проекта · Непрочитанный ответ аналитика виден на карточке", async () => {
|
||||
await core.markDiscussionRead(db, owner.id, chat.id);
|
||||
const before = (await core.analystLinks(db, owner)).get(project.id);
|
||||
assert.deepEqual(before, { href: "/chats/MTLK", unread: 0 });
|
||||
await core.addChatMessage(db, { chatId: chat.id, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text: "Готово: каталог открыт." });
|
||||
assert.deepEqual((await core.analystLinks(db, owner)).get(project.id), { href: "/chats/MTLK", unread: 1 });
|
||||
assert.equal((await core.analystLinks(db, member)).get(project.id)?.href, "/chats/MTLK", "a member writes to the analyst too");
|
||||
});
|
||||
|
||||
test("PEP-161: У чужого проекта ссылки нет", async () => {
|
||||
await core.setPlatformAdmins(db, [stranger.login]);
|
||||
try {
|
||||
assert.ok((await core.listOtherProjects(db, stranger.id)).some((p) => p.key === "MTLK"), "the superadmin sees the project among other people's");
|
||||
assert.equal((await core.analystLinks(db, stranger)).size, 0);
|
||||
} finally {
|
||||
await core.setPlatformAdmins(db, null);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user