@iconicompany/idossier-panel 0.2.0 → 0.2.1

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/README.md CHANGED
@@ -30,7 +30,7 @@ import { DossierPanel } from "@iconicompany/idossier-panel";
30
30
  | `schema` | код схемы досье в реестре idossier (`application`, `customer`, …): какие разделы и типы документов |
31
31
  | `title` | подпись досье при заведении из панели |
32
32
  | `labels` | подписи интерфейса (`attach`, `create`, `slot.verified`, …); непереданные — по умолчанию |
33
- | `canCreate`, `canEdit` | показать «Завести досье» и «Прикрепить». Сервер idossier проверяет права сам, флаги только прячут кнопки |
33
+ | `canCreate`, `canEdit` | разрешить «Завести досье» и «Прикрепить». Кнопка видна, только если и флаг стоит, и права человека из `/idossier/api/me` содержат `dossier:create` / `dossier:write` |
34
34
  | `code` | код досье, если продукт хранит его сам — тогда поиск по владельцу не нужен |
35
35
  | `loginUrl` | куда вести, если нет сессии idossier (по умолчанию `/idossier/`) |
36
36
  | `onChange` | вызывается после загрузки файла с кодом досье |
@@ -51,9 +51,12 @@ interface DossierTransport {
51
51
  find?(q: { ownerType: string; ownerKey: string; type: string }): Promise<string | null>;
52
52
  create?(input: { type: string; ownerType: string; ownerKey: string; title?: string }): Promise<string>;
53
53
  upload?(target: { dossierCode: string; sectionCode: string; typeCode: string }, file: File): Promise<void>;
54
+ permissions?(): Promise<string[]>; // нет метода — кнопки решают только флаги
54
55
  }
55
56
  ```
56
57
 
58
+ Перенаправление или ответ не-JSON на адресе API — «Данные недоступны» с адресом: значит, модуль досье на этом домене не развёрнут.
59
+
57
60
  Отказ — `TransportError(status, message)`: 401 панель показывает входом, 403 — нехваткой прав, прочее — «недоступно».
58
61
 
59
62
  ## Исходы различимы
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iconicompany/idossier-panel",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Панель досье idossier на странице продукта: документы записи, статусы проверки, прикрепление файла",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -94,6 +94,25 @@ export function DossierPanel({
94
94
  const [creating, setCreating] = useState(false);
95
95
  /** Код, полученный заведением: досье может не находиться поиском (вне охвата), но оно уже есть. */
96
96
  const [createdCode, setCreatedCode] = useState<string | null>(null);
97
+ /** Права из модуля досье; `null` — ещё не известны, кнопок нет. Транспорт без прав — решают флаги. */
98
+ const [permissions, setPermissions] = useState<string[] | null>(null);
99
+ useEffect(() => {
100
+ let live = true;
101
+ const read = transportRef.current.permissions;
102
+ if (!read) {
103
+ setPermissions(["dossier:create", "dossier:write"]);
104
+ return;
105
+ }
106
+ read().then(
107
+ (list) => live && setPermissions(list),
108
+ () => live && setPermissions([])
109
+ );
110
+ return () => {
111
+ live = false;
112
+ };
113
+ }, []);
114
+ const mayCreate = canCreate && (permissions?.includes("dossier:create") ?? false);
115
+ const mayEdit = canEdit && (permissions?.includes("dossier:write") ?? false);
97
116
  const target = `${code ?? ""}|${ownerType ?? ""}|${ownerKey ?? ""}|${schema ?? ""}`;
98
117
 
99
118
  // Сменилось досье — прежнее больше не показывается: «Прикрепить» у него положил бы файл не туда.
@@ -177,7 +196,7 @@ export function DossierPanel({
177
196
  return wrap(
178
197
  <div data-testid={T.missing} className="flex items-center gap-2 text-sm">
179
198
  <Badge tone="muted">{labels.notCreated}</Badge>
180
- {canCreate && transport.create && (
199
+ {mayCreate && transport.create && (
181
200
  <button
182
201
  type="button"
183
202
  data-testid={T.create}
@@ -195,7 +214,7 @@ export function DossierPanel({
195
214
  const { dossier } = state;
196
215
  const upload = transport.upload;
197
216
  const uploader: Upload =
198
- canEdit && upload
217
+ mayEdit && upload
199
218
  ? async (slot, dossierCode, file) => {
200
219
  await upload(
201
220
  { dossierCode, sectionCode: slot.sectionCode, typeCode: slot.typeCode },
@@ -15,13 +15,23 @@ export function createHttpTransport(options: HttpTransportOptions = {}): Dossier
15
15
  const api = (options.api ?? "/idossier/api").replace(/\/+$/, "");
16
16
  const call = async <T>(path: string, init: RequestInit = {}): Promise<T> => {
17
17
  const doFetch = options.fetch ?? globalThis.fetch;
18
- const res = await doFetch(`${api}${path}`, { ...init, credentials: "include" });
18
+ // Перенаправление не догоняем: так отвечает не модуль досье, а то, что стоит на его адресе.
19
+ const res = await doFetch(`${api}${path}`, {
20
+ ...init,
21
+ credentials: "include",
22
+ redirect: "manual",
23
+ });
24
+ if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400))
25
+ throw new TransportError(502, `модуль досье не отвечает по адресу ${api}: перенаправление`);
19
26
  if (!res.ok) throw new TransportError(res.status, await reasonOf(res));
27
+ if (!(res.headers.get("content-type") ?? "").includes("json"))
28
+ throw new TransportError(502, `модуль досье не отвечает по адресу ${api}: ответ не JSON`);
20
29
  return (await res.json()) as T;
21
30
  };
22
31
  const enc = encodeURIComponent;
23
32
 
24
33
  return {
34
+ permissions: async () => (await call<{ permissions: string[] }>("/me")).permissions,
25
35
  composite: (code) => call<PanelDossier>(`/dossiers/${enc(code)}/composite`),
26
36
  async find({ ownerType, ownerKey, type }) {
27
37
  const q = new URLSearchParams({ ownerType, ownerKey, type, limit: "1" });
package/src/types.ts CHANGED
@@ -127,6 +127,8 @@ export interface DossierTransport {
127
127
  }): Promise<string>;
128
128
  /** Положить файл в слот. */
129
129
  upload?(target: SlotTarget, file: File): Promise<void>;
130
+ /** Права актора в модуле досье (`dossier:create`, `dossier:write`, …): по ним панель прячет кнопки. */
131
+ permissions?(): Promise<string[]>;
130
132
  }
131
133
 
132
134
  /**