@niwa-labs/requests 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +41 -4
- package/src/access-ask.ts +97 -0
- package/src/actions.ts +216 -0
- package/src/cockpit/actions.ts +68 -0
- package/src/cockpit/answer-form.tsx +103 -0
- package/src/cockpit/answers.ts +71 -0
- package/src/cockpit/history.tsx +149 -0
- package/src/cockpit/index.tsx +28 -0
- package/src/cockpit/page.tsx +115 -0
- package/src/entity.ts +58 -0
- package/src/index.ts +619 -0
- package/src/question.ts +50 -0
- package/src/records-entry.ts +47 -0
- package/src/records.ts +111 -0
- package/src/resolver.ts +74 -0
- package/src/state.ts +398 -0
- package/test/ask.test.ts +265 -0
- package/test/cockpit-actions.test.ts +36 -0
- package/test/cockpit-answers.test.ts +77 -0
- package/test/deadline.test.ts +40 -0
- package/test/ending.test.ts +223 -0
- package/test/entity.test.ts +18 -0
- package/test/ledger.test.ts +64 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { PageLink, useCall, useViewer, type PageProps } from "@niwa-labs/cockpit-sdk";
|
|
2
|
+
import { Badge, CopyValue, DataValue, PageSection, SchemaView } from "@niwa-labs/ui-kit";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
import { Address, Answer, Question } from "./actions.ts";
|
|
7
|
+
import { AnswerForm } from "./answer-form.tsx";
|
|
8
|
+
import { addressText } from "./answers.ts";
|
|
9
|
+
|
|
10
|
+
const closedStates = ["answered", "cancelled", "expired"] as const;
|
|
11
|
+
const states = z.enum(["open", ...closedStates]);
|
|
12
|
+
type State = z.infer<typeof states>;
|
|
13
|
+
|
|
14
|
+
const LABELS: Record<State, string> = {
|
|
15
|
+
open: "Ждёт ответа",
|
|
16
|
+
answered: "Есть ответ",
|
|
17
|
+
cancelled: "Отменён",
|
|
18
|
+
expired: "Срок истёк",
|
|
19
|
+
};
|
|
20
|
+
const glance = z.object({
|
|
21
|
+
id: z.string(),
|
|
22
|
+
description: z.string(),
|
|
23
|
+
status: states,
|
|
24
|
+
from: Address.optional(),
|
|
25
|
+
to: Address,
|
|
26
|
+
deadline: z.number().optional(),
|
|
27
|
+
});
|
|
28
|
+
const list = {
|
|
29
|
+
name: "request.list",
|
|
30
|
+
input: z.object({ status: states.optional() }),
|
|
31
|
+
output: z.object({ items: z.array(glance) }),
|
|
32
|
+
};
|
|
33
|
+
const get = {
|
|
34
|
+
name: "request.get",
|
|
35
|
+
input: z.object({ id: z.string() }),
|
|
36
|
+
output: glance.extend({
|
|
37
|
+
input: Question,
|
|
38
|
+
question: z.string(),
|
|
39
|
+
answerPolicy: z.literal("owner-only").optional(),
|
|
40
|
+
answer: Answer.optional(),
|
|
41
|
+
by: Address.optional(),
|
|
42
|
+
}),
|
|
43
|
+
};
|
|
44
|
+
const refreshOn = { types: ["request.*"] };
|
|
45
|
+
|
|
46
|
+
function RequestStatus({ status }: { status: State }) {
|
|
47
|
+
return <Badge variant={status === "answered" ? "default" : "secondary"}>{LABELS[status]}</Badge>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function RequestHistory() {
|
|
51
|
+
const viewer = useViewer();
|
|
52
|
+
const [status, setStatus] = useState<"" | (typeof closedStates)[number]>("");
|
|
53
|
+
const result = useCall(list, status ? { status } : {}, { enabled: viewer.can(list), refreshOn });
|
|
54
|
+
if (!viewer.can(list)) return null;
|
|
55
|
+
const entries = result.data?.items.filter((request) => request.status !== "open").toReversed();
|
|
56
|
+
return (
|
|
57
|
+
<PageSection title="История запросов" actions={
|
|
58
|
+
<label className="flex flex-wrap items-center gap-2 text-sm">
|
|
59
|
+
Статус
|
|
60
|
+
<select
|
|
61
|
+
aria-label="Статус запросов"
|
|
62
|
+
className="rounded-md border bg-background px-2 py-1"
|
|
63
|
+
value={status}
|
|
64
|
+
onChange={(event) => setStatus(event.target.value as typeof status)}
|
|
65
|
+
>
|
|
66
|
+
<option value="">Все</option>
|
|
67
|
+
{closedStates.map((state) => <option value={state} key={state}>{LABELS[state]}</option>)}
|
|
68
|
+
</select>
|
|
69
|
+
</label>
|
|
70
|
+
}>
|
|
71
|
+
{result.isError ? (
|
|
72
|
+
<p role="alert">Не удалось загрузить историю запросов.</p>
|
|
73
|
+
) : entries === undefined ? (
|
|
74
|
+
<p role="status">Загружаю историю…</p>
|
|
75
|
+
) : entries.length === 0 ? (
|
|
76
|
+
<p>{status ? "Запросов с таким статусом нет." : "Закрытых запросов пока нет."}</p>
|
|
77
|
+
) : (
|
|
78
|
+
<ul className="divide-y">
|
|
79
|
+
{entries.map((request) => (
|
|
80
|
+
<li key={request.id} className="min-w-0 flex flex-col gap-1 py-2">
|
|
81
|
+
<PageLink to={"/requests/" + encodeURIComponent(request.id)} className="text-base font-semibold wrap-anywhere hover:underline">
|
|
82
|
+
{request.description}
|
|
83
|
+
</PageLink>
|
|
84
|
+
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground wrap-anywhere">
|
|
85
|
+
<RequestStatus status={request.status} />
|
|
86
|
+
<span>Адресат · {addressText(request.to)}</span>
|
|
87
|
+
</div>
|
|
88
|
+
</li>
|
|
89
|
+
))}
|
|
90
|
+
</ul>
|
|
91
|
+
)}
|
|
92
|
+
</PageSection>
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function AnswerValue({ input, answer }: { input: z.infer<typeof Question>; answer: z.infer<typeof Answer> }) {
|
|
97
|
+
if ("text" in answer) return <p className="whitespace-pre-wrap wrap-anywhere">{answer.text}</p>;
|
|
98
|
+
if ("form" in answer) return <DataValue value={answer.form} />;
|
|
99
|
+
const options = "options" in input ? input.options : [];
|
|
100
|
+
if (answer.ids.length === 0) return <p>Ни один вариант не выбран.</p>;
|
|
101
|
+
return (
|
|
102
|
+
<ul className="list-disc flex flex-col gap-1 px-4">
|
|
103
|
+
{answer.ids.map((id) => <li className="wrap-anywhere" key={id}>{options.find((option) => option.id === id)?.label ?? id}</li>)}
|
|
104
|
+
</ul>
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function RequestDetail({ params }: PageProps<"/requests/$id">) {
|
|
109
|
+
const got = useCall(get, { id: params.id }, { refreshOn });
|
|
110
|
+
if (got.isPending) return <p role="status">Загружаю запрос…</p>;
|
|
111
|
+
if (got.isError) return <p role="alert">Не удалось загрузить запрос.</p>;
|
|
112
|
+
const request = got.data;
|
|
113
|
+
return (
|
|
114
|
+
<article className="desk-page">
|
|
115
|
+
<header className="min-w-0 flex flex-col gap-2">
|
|
116
|
+
<div className="flex flex-wrap items-center gap-2">
|
|
117
|
+
<RequestStatus status={request.status} />
|
|
118
|
+
<CopyValue value={request.id} name="Скопировать номер запроса" />
|
|
119
|
+
</div>
|
|
120
|
+
<h2 className="text-2xl font-semibold wrap-anywhere">{request.input.title}</h2>
|
|
121
|
+
</header>
|
|
122
|
+
{request.input.detail && <p className="whitespace-pre-wrap wrap-anywhere">{request.input.detail}</p>}
|
|
123
|
+
<dl className="nw-fields">
|
|
124
|
+
{request.from && <div><dt>Отправитель</dt><dd>{addressText(request.from)}</dd></div>}
|
|
125
|
+
<div><dt>Адресат</dt><dd>{addressText(request.to)}</dd></div>
|
|
126
|
+
{request.deadline !== undefined && (
|
|
127
|
+
<div><dt>Срок ответа</dt><dd><DataValue value={request.deadline} field="at" /></dd></div>
|
|
128
|
+
)}
|
|
129
|
+
</dl>
|
|
130
|
+
{request.input.kind === "form" && (
|
|
131
|
+
<PageSection title="Поля формы"><SchemaView schema={request.input.schema} /></PageSection>
|
|
132
|
+
)}
|
|
133
|
+
{request.input.kind === "permission" && (
|
|
134
|
+
<PageSection title="Условия разрешения"><DataValue value={request.input.subject} /></PageSection>
|
|
135
|
+
)}
|
|
136
|
+
{request.answer !== undefined && (
|
|
137
|
+
<PageSection title="Ответ">
|
|
138
|
+
{request.by && <p className="mb-2 text-sm text-muted-foreground wrap-anywhere">Ответил · {addressText(request.by)}</p>}
|
|
139
|
+
<AnswerValue input={request.input} answer={request.answer} />
|
|
140
|
+
</PageSection>
|
|
141
|
+
)}
|
|
142
|
+
{request.status === "open" && (
|
|
143
|
+
<PageSection title="Ответ">
|
|
144
|
+
<AnswerForm request={request} onSent={() => void got.refetch()} />
|
|
145
|
+
</PageSection>
|
|
146
|
+
)}
|
|
147
|
+
</article>
|
|
148
|
+
);
|
|
149
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** The cockpit module of the requests plugin: the questions that wait, with the forms that answer them. */
|
|
2
|
+
|
|
3
|
+
import { definePlugin } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
|
|
5
|
+
import { RequestDetail } from "./history.tsx";
|
|
6
|
+
import { RequestsPage, RequestsTile } from "./page.tsx";
|
|
7
|
+
|
|
8
|
+
export default definePlugin({
|
|
9
|
+
id: "requests",
|
|
10
|
+
setup(ctx) {
|
|
11
|
+
ctx.pages.add({
|
|
12
|
+
path: "/requests",
|
|
13
|
+
title: "Запросы",
|
|
14
|
+
commandHeading: true,
|
|
15
|
+
nav: { order: 30 },
|
|
16
|
+
commands: [{ action: "request.ask", label: "Задать вопрос", preset: { to: { kind: "owner" } } }],
|
|
17
|
+
component: () => <RequestsPage />,
|
|
18
|
+
});
|
|
19
|
+
ctx.pages.add({ path: "/requests/$id", panel: true, title: "Запрос", component: RequestDetail });
|
|
20
|
+
if (ctx.viewer.can("request.open"))
|
|
21
|
+
ctx.slots.register("home.tile", { key: "questions", order: 10, component: RequestsTile });
|
|
22
|
+
ctx.entities.register("request", {
|
|
23
|
+
label: "Запрос",
|
|
24
|
+
prefix: "req",
|
|
25
|
+
href: (id) => "/requests/" + encodeURIComponent(id),
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** Open requests and paused work waiting for a decision. */
|
|
2
|
+
|
|
3
|
+
import { EntityLink, useAction, useCall, useViewer } from "@niwa-labs/cockpit-sdk";
|
|
4
|
+
import { Badge, Button, DataValue, fieldLabel, PageSection } from "@niwa-labs/ui-kit";
|
|
5
|
+
import { useQueryClient } from "@tanstack/react-query";
|
|
6
|
+
|
|
7
|
+
import { AnswerForm } from "./answer-form.tsx";
|
|
8
|
+
import { openAction, resolveAction, type OpenPaused, type OpenRequest, type Question } from "./actions.ts";
|
|
9
|
+
import { addressText, subjectLines } from "./answers.ts";
|
|
10
|
+
import { RequestHistory } from "./history.tsx";
|
|
11
|
+
|
|
12
|
+
const QUESTION_LABELS: Record<Question["kind"], string> = {
|
|
13
|
+
choice: "Выбор варианта",
|
|
14
|
+
multi: "Выбор нескольких вариантов",
|
|
15
|
+
confirm: "Подтверждение",
|
|
16
|
+
text: "Вопрос",
|
|
17
|
+
form: "Форма",
|
|
18
|
+
permission: "Разрешение",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const CHOICES: Record<string, string> = {
|
|
22
|
+
retry: "Повторить", cancel: "Отменить", skip: "Пропустить",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function RequestCard({ request, onSent }: { request: OpenRequest; onSent: () => void }) {
|
|
26
|
+
return (
|
|
27
|
+
<article data-slot="request" data-kind={request.input.kind} className="min-w-0 flex flex-col gap-3 py-2">
|
|
28
|
+
<header className="min-w-0">
|
|
29
|
+
<div className="flex flex-wrap items-center gap-2">
|
|
30
|
+
<Badge variant="secondary">{QUESTION_LABELS[request.input.kind]}</Badge>
|
|
31
|
+
<EntityLink entity={{ kind: "request", id: request.id }} label="Карточка запроса" />
|
|
32
|
+
</div>
|
|
33
|
+
<h3 className="mt-2 text-base font-semibold wrap-anywhere">{request.input.title}</h3>
|
|
34
|
+
<ul className="mt-1 flex min-w-0 flex-wrap gap-2 text-sm text-muted-foreground">
|
|
35
|
+
{request.from && <li className="min-w-0 wrap-anywhere">Отправитель · {addressText(request.from)}</li>}
|
|
36
|
+
<li className="min-w-0 wrap-anywhere">Адресат · {addressText(request.to)}</li>
|
|
37
|
+
{request.deadline !== undefined && <li>Ответ до <DataValue field="at" value={request.deadline} /></li>}
|
|
38
|
+
</ul>
|
|
39
|
+
</header>
|
|
40
|
+
{request.input.detail && <p className="whitespace-pre-wrap wrap-anywhere">{request.input.detail}</p>}
|
|
41
|
+
{request.input.kind === "permission" && (
|
|
42
|
+
<dl data-slot="subject" className="nw-fields">
|
|
43
|
+
{subjectLines(request.input.subject).map(({ label, value }) => (
|
|
44
|
+
<div key={label}><dt>{fieldLabel(label)}</dt><dd><DataValue field={label} value={value} /></dd></div>
|
|
45
|
+
))}
|
|
46
|
+
</dl>
|
|
47
|
+
)}
|
|
48
|
+
<AnswerForm request={request} onSent={onSent} />
|
|
49
|
+
</article>
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function PausedCard({ paused, onSent }: { paused: OpenPaused; onSent: () => void }) {
|
|
54
|
+
const resolve = useAction(resolveAction);
|
|
55
|
+
const viewer = useViewer();
|
|
56
|
+
return (
|
|
57
|
+
<article data-slot="paused" className="min-w-0 flex flex-col gap-3 py-2">
|
|
58
|
+
<h3 className="text-base font-semibold">Действие приостановлено</h3>
|
|
59
|
+
{paused.reason && <p className="text-sm wrap-anywhere">{paused.reason}</p>}
|
|
60
|
+
{viewer.can(resolveAction) && (
|
|
61
|
+
<div className="flex flex-wrap gap-2">
|
|
62
|
+
{paused.choices.map((choice) => (
|
|
63
|
+
<Button
|
|
64
|
+
key={choice}
|
|
65
|
+
size="sm"
|
|
66
|
+
variant={choice === "cancel" ? "outline" : "default"}
|
|
67
|
+
disabled={resolve.isPending}
|
|
68
|
+
onClick={() => resolve.mutate({ invocation: paused.invocation, choice }, { onSettled: onSent })}
|
|
69
|
+
>
|
|
70
|
+
{CHOICES[choice] ?? choice}
|
|
71
|
+
</Button>
|
|
72
|
+
))}
|
|
73
|
+
</div>
|
|
74
|
+
)}
|
|
75
|
+
{resolve.isError && <p role="alert" className="text-sm text-destructive">Не удалось применить решение.</p>}
|
|
76
|
+
</article>
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function RequestsTile() { return <RequestsPage home />; }
|
|
81
|
+
|
|
82
|
+
export function RequestsPage({ home = false }: { home?: boolean } = {}) {
|
|
83
|
+
const queryClient = useQueryClient();
|
|
84
|
+
const open = useCall(openAction, {}, { refreshOn: { types: ["request.*", "niwa.invocation.state"] } });
|
|
85
|
+
const reread = (): void => void queryClient.invalidateQueries({ queryKey: ["niwa", "call"] });
|
|
86
|
+
const questions = open.data?.requests.filter((entry): entry is OpenRequest =>
|
|
87
|
+
"input" in entry && (!home || entry.to.kind === "owner"),
|
|
88
|
+
) ?? [];
|
|
89
|
+
const paused = open.data?.requests.filter((entry): entry is OpenPaused => "invocation" in entry) ?? [];
|
|
90
|
+
if (home && open.data && questions.length + paused.length === 0) return null;
|
|
91
|
+
return (
|
|
92
|
+
<>
|
|
93
|
+
<PageSection title="Ждут ответа">
|
|
94
|
+
{open.isPending ? <p role="status">Загружаю запросы…</p> : open.isError ? (
|
|
95
|
+
<p role="alert">Не удалось загрузить запросы.</p>
|
|
96
|
+
) : questions.length === 0 && (!home || paused.length === 0) ? (
|
|
97
|
+
<p>Запросов без ответа нет.</p>
|
|
98
|
+
) : (
|
|
99
|
+
<div data-slot="requests" className="divide-y">
|
|
100
|
+
{questions.map((request) => <RequestCard key={request.id} request={request} onSent={reread} />)}
|
|
101
|
+
{home && paused.map((entry) => <PausedCard key={entry.invocation} paused={entry} onSent={reread} />)}
|
|
102
|
+
</div>
|
|
103
|
+
)}
|
|
104
|
+
</PageSection>
|
|
105
|
+
{!home && paused.length > 0 && (
|
|
106
|
+
<PageSection title="Ждут решения">
|
|
107
|
+
<div className="divide-y">
|
|
108
|
+
{paused.map((entry) => <PausedCard key={entry.invocation} paused={entry} onSent={reread} />)}
|
|
109
|
+
</div>
|
|
110
|
+
</PageSection>
|
|
111
|
+
)}
|
|
112
|
+
{!home && <RequestHistory />}
|
|
113
|
+
</>
|
|
114
|
+
);
|
|
115
|
+
}
|
package/src/entity.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `request.list` and `request.get` answer, built from the state of a request.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { DESCRIPTION_MAX, DESCRIPTION_MIN, EntityDescription } from "@niwa-labs/core";
|
|
6
|
+
|
|
7
|
+
import type { z } from "zod";
|
|
8
|
+
|
|
9
|
+
import type { RequestEntity, requestList } from "./actions.ts";
|
|
10
|
+
import type { Created, RequestState } from "./state.ts";
|
|
11
|
+
|
|
12
|
+
/** A request's title cut to what a list shows: one line, at most `DESCRIPTION_MAX` characters, an ellipsis where it was cut. */
|
|
13
|
+
function cutTo(text: string, max: number): string {
|
|
14
|
+
if (text.length <= max) return text;
|
|
15
|
+
let kept = "";
|
|
16
|
+
for (const character of text) {
|
|
17
|
+
if (kept.length + character.length > max - 1) break;
|
|
18
|
+
kept += character;
|
|
19
|
+
}
|
|
20
|
+
return `${kept.trimEnd()}…`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The description of a request: the title the asker gave its question, on one line. A title too
|
|
25
|
+
* short to read is put after the name of the question; when that is too short as well, the id of
|
|
26
|
+
* the request is what is shown, so that a request already written never fails to be read.
|
|
27
|
+
*/
|
|
28
|
+
export function descriptionOf(created: Pick<Created, "id" | "question" | "input">): EntityDescription {
|
|
29
|
+
const title = created.input.title.replace(/\s+/g, " ").trim();
|
|
30
|
+
const named = `${created.question} ${title}`.trim();
|
|
31
|
+
const shown = title.length >= DESCRIPTION_MIN ? title : named.length >= DESCRIPTION_MIN ? named : created.id;
|
|
32
|
+
return EntityDescription.parse(cutTo(shown, DESCRIPTION_MAX));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What `request.list` shows of a request at a glance. */
|
|
36
|
+
export function itemOf(state: RequestState): z.infer<typeof requestList.output>["items"][number] {
|
|
37
|
+
const { created } = state;
|
|
38
|
+
return {
|
|
39
|
+
id: created.id,
|
|
40
|
+
description: descriptionOf(created),
|
|
41
|
+
status: state.status,
|
|
42
|
+
question: created.question,
|
|
43
|
+
to: created.to,
|
|
44
|
+
...(created.answerPolicy === undefined ? {} : { answerPolicy: created.answerPolicy }),
|
|
45
|
+
...(created.from === undefined ? {} : { from: created.from }),
|
|
46
|
+
...(created.deadline === undefined ? {} : { deadline: created.deadline }),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The whole request: what was asked, to whom, and how it stands. */
|
|
51
|
+
export function entityOf(state: RequestState): z.infer<typeof RequestEntity> {
|
|
52
|
+
return {
|
|
53
|
+
...itemOf(state),
|
|
54
|
+
input: state.created.input,
|
|
55
|
+
...(state.status === "answered" ? { answer: state.answer } : {}),
|
|
56
|
+
...(state.status === "answered" || state.status === "cancelled" ? (state.by === undefined ? {} : { by: state.by }) : {}),
|
|
57
|
+
};
|
|
58
|
+
}
|